Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 40 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -729,28 +729,51 @@ accessor and one propagated outbound call, and nothing else — is

## Usage analytics

The starter reports one anonymous usage event when the durable `ChatClient` auto-configuration
activates, once per package per process. Maven Central publishes aggregate download counts only,
so this is how Diagrid sees which package versions run on which platforms. Because it is one event
per process, a Kubernetes deployment produces one event per replica per restart: the numbers count
process starts, not deployments or users.
The starter reports anonymous usage events to two services, [Scarf](https://scarf.sh) and
[Reo](https://www.reo.dev). Maven Central publishes aggregate download counts only, so these events
show which package versions run on which platforms. Both services derive coarse company and
location information from the request IP. How they handle that data is described in
[Scarf's privacy policy](https://about.scarf.sh/privacy-policy) and
[Reo's privacy policy](https://www.reo.dev/privacy-policy).

The starter sends one event to each service when the durable `ChatClient` auto-configuration
activates, once per package per process. Because it is one event per process, a Kubernetes
deployment produces one event per replica per restart: the numbers count process starts, not
deployments or users.

**What is sent:** the package name and version, the operating system, architecture and JVM
version, the agent framework and the installed version of its library (`framework`,
`framework_version`), `kind=agent`, whether the process points at Catalyst or at a plain Dapr
sidecar (`target`), and whether it runs under a CI variable (`ci`). Nothing else: no application
data, configuration, app IDs, prompts, or hostnames. The receiving service is
[Scarf](https://scarf.sh). It derives coarse company and location information from the request IP.
How Scarf handles that data is described in
[Scarf's privacy policy](https://about.scarf.sh/privacy-policy).

**It never gets in the way:** the request is dispatched asynchronously on a background daemon
version, the agent framework and the installed version of its library, and `kind=agent`. Nothing
else: no application data, configuration, app IDs, prompts, hostnames or file paths.

| | Scarf | Reo |
|---|---|---|
| Fields | `package`, `version`, `os`, `arch`, `java_version`, `target`, `ci`, `kind`, `framework`, `framework_version` | `activity_type=maven_runtime`, `product`, `version`, `jvm`, `platform`, `arch`, `kind`, `framework`, `framework_version` |
| `target` and `ci` | sent | not sent |

`target` says whether the process points at Catalyst or at a plain Dapr sidecar. `ci` says whether
a CI variable is set.

**When Reo is skipped:** Reo is not contacted from Kubernetes, from CI, or when the application
points at Catalyst. Scarf is still contacted in those cases, so the two services report different
totals. Reo is skipped when any of these is true:

- you opt out (see below)
- `KUBERNETES_SERVICE_HOST` is set
- the Dapr gRPC or HTTP endpoint is a host under `diagrid.io`, or a Dapr API token is set. The
starter reads these from the `DAPR_GRPC_ENDPOINT`, `DAPR_HTTP_ENDPOINT` and `DAPR_API_TOKEN`
environment variables and from Spring configuration, including the Dapr Spring Boot starter's
`dapr.client.grpc-endpoint`, `dapr.client.http-endpoint` and `dapr.client.api-token` properties
- a Dapr endpoint is set but can't be parsed
- a CI variable is set, such as `CI`, `GITHUB_ACTIONS` or `GITLAB_CI`

**It never gets in the way:** each request is dispatched asynchronously on a background daemon
thread with a one second timeout, every failure is swallowed, and the calling thread never waits.
Blocked egress and air-gapped clusters behave normally. Nothing is written to your application's
output; a `DEBUG` line on the `io.diagrid.springai.durable.boot.UsageAnalytics` logger records
whether the event was sent, skipped, or failed, for operators who want to confirm an opt-out.
whether each event was sent, skipped, or failed, for operators who want to confirm an opt-out.

To opt out, set the Spring property, which removes the reporting bean and works per profile:
To opt out of both services, set the Spring property, which removes the reporting bean and works
per profile:

```yaml
diagrid:
Expand All @@ -771,7 +794,7 @@ export DIAGRID_NO_ANALYTICS=1
```

Either switch alone is enough. A value of `0`, `false`, or an empty string does not opt out. The
endpoint is fixed at build time and is not configurable.
endpoints are fixed at build time and are not configurable.

## Requirements

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import io.micrometer.observation.ObservationRegistry;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.ChatClientCustomizer;
import org.springframework.ai.chat.model.ChatModel;
Expand All @@ -27,7 +28,9 @@
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.context.ApplicationContext;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

/**
* Auto-configuration that makes Spring AI {@code ChatClient} calls durable via Dapr Workflows.
Expand All @@ -47,13 +50,24 @@
@ConditionalOnProperty(prefix = "diagrid.spring-ai", name = "enabled", havingValue = "true",
matchIfMissing = true)
@EnableConfigurationProperties(DiagridSpringAiProperties.class)
public class DiagridSpringAiAutoConfiguration {
public class DiagridSpringAiAutoConfiguration implements EnvironmentAware {

// The artifactId that hosts the usage-analytics hook below, and the anonymous "package" and
// "version" dimensions reported with every event. See UsageAnalytics and the README's
// "Usage analytics" section.
private static final String USAGE_ANALYTICS_PACKAGE = "diagrid-spring-ai-starter";

/**
* Spring's Environment, so usage reporting can see Dapr configuration that comes from
* application.yml or a profile rather than environment variables. Null until Spring sets it.
*/
private Environment environment;

@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}

@Bean
@ConditionalOnMissingBean
public DaprWorkflowClient daprWorkflowClient(ObjectProvider<ObservationRegistry> observationRegistry) {
Expand Down Expand Up @@ -107,14 +121,22 @@ public SmartInitializingSingleton daprToolDiscoveryInitializer(
@ConditionalOnProperty(prefix = "diagrid.spring-ai.analytics", name = "enabled", havingValue = "true",
matchIfMissing = true)
public SmartInitializingSingleton daprUsageAnalyticsInitializer() {
return () -> {
Map<String, String> dimensions = new LinkedHashMap<>();
dimensions.put("kind", "agent");
dimensions.put("framework", "SpringAI");
dimensions.put("framework_version", springAiVersion());
String version = UsageAnalytics.resolveVersion(DiagridSpringAiAutoConfiguration.class, USAGE_ANALYTICS_PACKAGE);
UsageAnalytics.report(USAGE_ANALYTICS_PACKAGE, version, dimensions);
};
return () -> reportUsage(UsageAnalytics::sendHttp, System::getenv);
}

/**
* The initializer's work: one usage event per destination, with every environment lookup going
* through Spring's Environment first and {@code fallback} last. Package-private so a test can pass
* a recording sender and a fallback that ignores the real environment.
*/
void reportUsage(UsageAnalytics.Sender sender, Function<String, String> fallback) {
Map<String, String> dimensions = new LinkedHashMap<>();
dimensions.put("kind", "agent");
dimensions.put("framework", "SpringAI");
dimensions.put("framework_version", springAiVersion());
String version = UsageAnalytics.resolveVersion(DiagridSpringAiAutoConfiguration.class, USAGE_ANALYTICS_PACKAGE);
UsageAnalytics.report(
USAGE_ANALYTICS_PACKAGE, version, dimensions, SpringEnvironmentLookup.resolver(environment, fallback), sender);
}

// The installed version of the Spring AI chat-client library, or null when the package metadata
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package io.diagrid.springai.durable.boot;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.function.Function;
import org.springframework.core.env.Environment;

/**
* Builds the {@link UsageAnalytics} environment lookup from Spring's {@link Environment}.
*
* <p>The Dapr SDK in other languages is configured through environment variables, and {@link
* UsageAnalytics#detectTarget()} reads those. A Spring application can instead point at Catalyst
* through {@code application.yml}, a profile, or the Dapr Spring Boot starter's {@code dapr.client.*}
* properties, with no Dapr environment variable set. This lookup lets the Reo gate see that.
*
* <p>For each name it tries, in order: the name itself (Spring resolves environment-variable-style
* names against the system environment as well as properties and YAML), the name lower-cased with
* underscores turned into dots, the matching Dapr Spring Boot starter properties, and finally {@link
* System#getenv(String)}, so behaviour outside a Spring context is unchanged. It never throws.
*/
final class SpringEnvironmentLookup {

/**
* The Dapr Spring Boot starter's own properties ({@code DaprClientProperties}, prefix {@code
* dapr.client}, read off {@code dapr-spring-boot-properties} 1.19.1) for each Dapr SDK variable, in
* both kebab and camel case.
*/
private static final Map<String, List<String>> DAPR_SPRING_PROPERTIES =
Map.of(
"DAPR_GRPC_ENDPOINT", List.of("dapr.client.grpc-endpoint", "dapr.client.grpcEndpoint"),
"DAPR_HTTP_ENDPOINT", List.of("dapr.client.http-endpoint", "dapr.client.httpEndpoint"),
"DAPR_API_TOKEN", List.of("dapr.client.api-token", "dapr.client.apiToken"));

private SpringEnvironmentLookup() {
}

/** A lookup backed by {@code environment}; a {@code null} environment falls back to getenv alone. */
static Function<String, String> resolver(Environment environment) {
return resolver(environment, System::getenv);
}

/**
* As {@link #resolver(Environment)}, with an explicit last-resort lookup in place of {@code
* System.getenv}. Visible for tests: the build runs every test JVM with {@code
* DIAGRID_NO_ANALYTICS=1}, so a test that fell back to the real environment would always see an
* opt-out.
*/
static Function<String, String> resolver(Environment environment, Function<String, String> fallback) {
return name -> resolve(environment, name, fallback);
}

/** The Spring property names tried for {@code name}, in order, before {@code System.getenv}. */
static List<String> candidateNames(String name) {
List<String> names = new ArrayList<>();
names.add(name);
names.add(name.toLowerCase(Locale.ROOT).replace('_', '.'));
names.addAll(DAPR_SPRING_PROPERTIES.getOrDefault(name, List.of()));
return names;
}

private static String resolve(Environment environment, String name, Function<String, String> fallback) {
if (environment != null) {
for (String candidate : candidateNames(name)) {
String value = propertyOrNull(environment, candidate);
if (value != null && !value.isBlank()) {
return value;
}
}
}
return fallback.apply(name);
}

private static String propertyOrNull(Environment environment, String key) {
try {
return environment.getProperty(key);
} catch (RuntimeException e) {
return null;
}
}
}
Loading