diff --git a/README.md b/README.md index 5c069d2..345ff2d 100644 --- a/README.md +++ b/README.md @@ -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: @@ -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 diff --git a/diagrid-spring-ai/diagrid-spring-ai-starter/src/main/java/io/diagrid/springai/durable/boot/DiagridSpringAiAutoConfiguration.java b/diagrid-spring-ai/diagrid-spring-ai-starter/src/main/java/io/diagrid/springai/durable/boot/DiagridSpringAiAutoConfiguration.java index ef9b401..183f610 100644 --- a/diagrid-spring-ai/diagrid-spring-ai-starter/src/main/java/io/diagrid/springai/durable/boot/DiagridSpringAiAutoConfiguration.java +++ b/diagrid-spring-ai/diagrid-spring-ai-starter/src/main/java/io/diagrid/springai/durable/boot/DiagridSpringAiAutoConfiguration.java @@ -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; @@ -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. @@ -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) { @@ -107,14 +121,22 @@ public SmartInitializingSingleton daprToolDiscoveryInitializer( @ConditionalOnProperty(prefix = "diagrid.spring-ai.analytics", name = "enabled", havingValue = "true", matchIfMissing = true) public SmartInitializingSingleton daprUsageAnalyticsInitializer() { - return () -> { - Map 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 fallback) { + Map 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 diff --git a/diagrid-spring-ai/diagrid-spring-ai-starter/src/main/java/io/diagrid/springai/durable/boot/SpringEnvironmentLookup.java b/diagrid-spring-ai/diagrid-spring-ai-starter/src/main/java/io/diagrid/springai/durable/boot/SpringEnvironmentLookup.java new file mode 100644 index 0000000..33a3ed1 --- /dev/null +++ b/diagrid-spring-ai/diagrid-spring-ai-starter/src/main/java/io/diagrid/springai/durable/boot/SpringEnvironmentLookup.java @@ -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}. + * + *

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. + * + *

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> 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 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 resolver(Environment environment, Function fallback) { + return name -> resolve(environment, name, fallback); + } + + /** The Spring property names tried for {@code name}, in order, before {@code System.getenv}. */ + static List candidateNames(String name) { + List 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 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; + } + } +} diff --git a/diagrid-spring-ai/diagrid-spring-ai-starter/src/main/java/io/diagrid/springai/durable/boot/UsageAnalytics.java b/diagrid-spring-ai/diagrid-spring-ai-starter/src/main/java/io/diagrid/springai/durable/boot/UsageAnalytics.java index d701626..061949e 100644 --- a/diagrid-spring-ai/diagrid-spring-ai-starter/src/main/java/io/diagrid/springai/durable/boot/UsageAnalytics.java +++ b/diagrid-spring-ai/diagrid-spring-ai-starter/src/main/java/io/diagrid/springai/durable/boot/UsageAnalytics.java @@ -9,6 +9,7 @@ import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.time.Duration; +import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; @@ -19,6 +20,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; +import java.util.function.BooleanSupplier; import java.util.function.Function; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -41,6 +43,9 @@ * the executor's thread is free again; the calling thread never waits on it either way. Blocked * egress and air-gapped clusters are normal conditions, not faults. * + *

Events go to a list of destinations, each with its own gate and URL format, and each package is + * reported at most once per destination per process. + * *

Two switches turn it off: the Spring property {@code diagrid.spring-ai.analytics.enabled=false}, * which removes the reporting bean, and any of {@code DO_NOT_TRACK}, {@code SCARF_NO_ANALYTICS} or * {@code DIAGRID_NO_ANALYTICS} set to {@code 1}, {@code true}, {@code yes} or {@code on} @@ -58,6 +63,23 @@ final class UsageAnalytics { */ static final String DEFAULT_ENDPOINT = "https://diagrid.gateway.scarf.sh/java-ai"; + /** + * Reo's unauthenticated telemetry endpoint on Diagrid's tenant. No API key and no auth header: + * nothing secret goes into a published artifact. Reo attributes the event to a company from the + * request IP. + */ + static final String REO_ENDPOINT = "https://telemetry.diagrid.io/data"; + + /** The Reo activity type this artifact reports, as registered on the tenant. */ + private static final String REO_ACTIVITY_TYPE = "maven_runtime"; + + /** + * Collected dimension name to the key registered in Reo, in the order they are sent. Anything not + * listed, including {@code target} and {@code ci}, is not sent to Reo: the Reo gate makes both + * constant on every event. + */ + private static final Map REO_KEYS = reoKeys(); + private static final Duration TIMEOUT = Duration.ofSeconds(1); /** The cross-ecosystem convention, Scarf's own variable, and a Diagrid-specific opt-out. */ @@ -78,12 +100,19 @@ final class UsageAnalytics { private static final String DAPR_API_TOKEN_ENV_VAR = "DAPR_API_TOKEN"; + /** Set inside every Kubernetes pod. Reo is never contacted from a cluster. */ + private static final String KUBERNETES_ENV_VAR = "KUBERNETES_SERVICE_HOST"; + private static final String CATALYST_HOST_SUFFIX = "diagrid.io"; private static final int DIMENSION_MAX_LEN = 64; - /** Packages already reported in this process. Shared across every instance. */ - private static final Set REPORTED_PACKAGES = ConcurrentHashMap.newKeySet(); + /** + * Destination and package pairs already reported in this process, as {@code destination:package}. + * Shared across every instance. Keyed per destination so a closed gate on one destination never + * consumes another destination's single send. + */ + private static final Set REPORTED = ConcurrentHashMap.newKeySet(); private static final ExecutorService EXECUTOR = newDaemonExecutor(); @@ -91,11 +120,13 @@ final class UsageAnalytics { HttpClient.newBuilder().connectTimeout(TIMEOUT).executor(EXECUTOR).build(); private static final UsageAnalytics DEFAULT_INSTANCE = - new UsageAnalytics(DEFAULT_ENDPOINT, System::getenv, UsageAnalytics::sendHttp); + new UsageAnalytics(DEFAULT_ENDPOINT, REO_ENDPOINT, System::getenv, UsageAnalytics::sendHttp); private final String endpoint; + private final String reoEndpoint; private final Function env; private final Sender sender; + private final List destinations; /** * @param endpoint the event-collection URL; empty disables reporting @@ -105,8 +136,41 @@ final class UsageAnalytics { */ UsageAnalytics(String endpoint, Function env, Sender sender) { this.endpoint = endpoint; + this.reoEndpoint = ""; this.env = env; this.sender = sender; + this.destinations = List.of(new Destination("scarf", endpoint, () -> !isReportingDisabled(), this::buildUrl)); + } + + /** + * A reporter that sends to Scarf and to Reo, each behind its own gate. + * + * @param endpoint the Scarf event-collection URL; empty disables Scarf + * @param reoEndpoint the Reo telemetry URL; empty disables Reo + */ + UsageAnalytics(String endpoint, String reoEndpoint, Function env, Sender sender) { + this.endpoint = endpoint; + this.reoEndpoint = reoEndpoint; + this.env = env; + this.sender = sender; + this.destinations = + List.of( + new Destination("scarf", endpoint, () -> !isReportingDisabled(), this::buildUrl), + new Destination("reo", reoEndpoint, this::reoAllowed, this::buildReoUrl)); + } + + private UsageAnalytics(Function env, Sender sender, List destinations) { + this.endpoint = ""; + this.reoEndpoint = ""; + this.env = env; + this.sender = sender; + this.destinations = List.copyOf(destinations); + } + + /** A reporter with an explicit destination list. Visible for tests only. */ + static UsageAnalytics withDestinations( + Function env, Sender sender, List destinations) { + return new UsageAnalytics(env, sender, destinations); } /** @@ -124,9 +188,26 @@ static void report(String packageName, String version, Map dimen DEFAULT_INSTANCE.reportEvent(packageName, version, dimensions); } + /** + * As {@link #report(String, String, Map)}, but every environment lookup (opt-out, CI, Kubernetes and + * the Dapr target) goes through {@code env}, for example a lookup backed by Spring's Environment. + * The per-process dedupe is shared with the default reporter. + */ + static void report( + String packageName, String version, Map dimensions, Function env) { + report(packageName, version, dimensions, env, UsageAnalytics::sendHttp); + } + + /** As {@link #report(String, String, Map, Function)}, with an explicit sender. Visible for tests. */ + static void report( + String packageName, String version, Map dimensions, Function env, + Sender sender) { + new UsageAnalytics(DEFAULT_ENDPOINT, REO_ENDPOINT, env, sender).reportEvent(packageName, version, dimensions); + } + /** Clears the per-process guard. Visible for tests only. */ static void resetForTesting() { - REPORTED_PACKAGES.clear(); + REPORTED.clear(); } /** @@ -161,22 +242,29 @@ static String resolveVersion(Class anchor, String artifactId) { /** Instance form of {@link #report}, used directly by tests against a configured instance. */ void reportEvent(String packageName, String version, Map dimensions) { + for (Destination destination : destinations) { + reportTo(destination, packageName, version, dimensions); + } + } + + /** Sends one destination's event. Never throws, so one destination cannot affect another. */ + private void reportTo(Destination destination, String packageName, String version, Map dimensions) { try { - if (endpoint == null || endpoint.isEmpty()) { + if (destination.endpoint() == null || destination.endpoint().isEmpty()) { return; } - if (!REPORTED_PACKAGES.add(packageName)) { + if (!REPORTED.add(destination.name() + ":" + packageName)) { return; } - if (isReportingDisabled()) { - LOG.debug("Usage reporting for {} is disabled by the environment", packageName); + if (!destination.gate().getAsBoolean()) { + LOG.debug("Usage reporting for {} to {} is disabled", packageName, destination.name()); return; } - String url = buildUrl(packageName, version, dimensions); + String url = destination.urlBuilder().build(packageName, version, dimensions); String userAgent = packageName + "/" + version; sender.send(url, userAgent); } catch (RuntimeException e) { - LOG.debug("Usage event for {} not sent: {}", packageName, e.toString()); + LOG.debug("Usage event for {} to {} not sent: {}", packageName, destination.name(), e.toString()); } } @@ -190,6 +278,47 @@ boolean isReportingDisabled() { return false; } + /** + * The Reo gate. Stricter than Scarf's, which is the opt-out check alone. True only when no opt-out + * variable is set, the process is not in a Kubernetes cluster, it is not pointed at Catalyst, and it + * is not running in CI. Anything that cannot be determined, including an exception or a Dapr + * endpoint that does not parse, means no event. The Spring property needs no check here: when it is + * false the reporting bean does not exist. + */ + boolean reoAllowed() { + try { + if (isReportingDisabled()) { + return false; + } + String kubernetes = env.apply(KUBERNETES_ENV_VAR); + if (kubernetes != null && !kubernetes.trim().isEmpty()) { + return false; + } + if (hasUnparsableDaprEndpoint() || !"dapr".equals(detectTarget())) { + return false; + } + return !isRunningInCi(); + } catch (RuntimeException e) { + return false; + } + } + + /** True when a Dapr endpoint variable is set but its host can't be read. The Reo gate fails closed. */ + private boolean hasUnparsableDaprEndpoint() { + for (String name : DAPR_ENDPOINT_ENV_VARS) { + String raw = env.apply(name); + if (raw == null || raw.trim().isEmpty()) { + continue; + } + String trimmed = raw.trim(); + String candidate = trimmed.contains("://") ? trimmed : "https://" + trimmed; + if (hostOf(candidate) == null) { + return true; + } + } + return false; + } + /** True when a well-known CI variable is set. Reported as the {@code ci} dimension. */ boolean isRunningInCi() { for (String name : CI_TRUTHY_ENV_VARS) { @@ -237,8 +366,30 @@ String detectTarget() { return token != null && !token.trim().isEmpty() ? "catalyst" : "dapr"; } - /** Builds the event URL. Exposed package-private for tests. */ + /** Builds the Scarf event URL. Exposed package-private for tests. */ String buildUrl(String packageName, String version, Map dimensions) { + return endpoint + "?" + encode(collect(packageName, version, dimensions)); + } + + /** + * Builds the Reo event URL: {@code activity_type=maven_runtime} followed by the collected dimensions + * under the names registered in Reo. Exposed package-private for tests. + */ + String buildReoUrl(String packageName, String version, Map dimensions) { + Map collected = collect(packageName, version, dimensions); + Map params = new LinkedHashMap<>(); + params.put("activity_type", REO_ACTIVITY_TYPE); + for (Map.Entry key : REO_KEYS.entrySet()) { + String value = clean(collected.get(key.getKey())); + if (value != null) { + params.put(key.getValue(), value); + } + } + return reoEndpoint + "?" + encode(params); + } + + /** The default dimensions plus the caller's, cleaned. Shared by every destination's URL builder. */ + private Map collect(String packageName, String version, Map dimensions) { Map params = new LinkedHashMap<>(); params.put("package", packageName); params.put("version", version); @@ -257,6 +408,10 @@ String buildUrl(String packageName, String version, Map dimensio } } } + return params; + } + + private static String encode(Map params) { StringBuilder query = new StringBuilder(); for (Map.Entry entry : params.entrySet()) { if (query.length() > 0) { @@ -266,7 +421,20 @@ String buildUrl(String packageName, String version, Map dimensio query.append('='); query.append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8)); } - return endpoint + "?" + query; + return query.toString(); + } + + private static Map reoKeys() { + Map keys = new LinkedHashMap<>(); + keys.put("package", "product"); + keys.put("version", "version"); + keys.put("java_version", "jvm"); + keys.put("os", "platform"); + keys.put("arch", "arch"); + keys.put("kind", "kind"); + keys.put("framework", "framework"); + keys.put("framework_version", "framework_version"); + return Collections.unmodifiableMap(keys); } private static String hostOf(String candidate) { @@ -344,4 +512,16 @@ private static ExecutorService newDaemonExecutor() { interface Sender { void send(String url, String userAgent); } + + /** Builds one destination's event URL. */ + @FunctionalInterface + interface UrlBuilder { + String build(String packageName, String version, Map dimensions); + } + + /** + * One place usage events go: its name (the dedupe key), its endpoint (empty disables it), the gate + * that must be open for it to send, and how its URL is built. + */ + record Destination(String name, String endpoint, BooleanSupplier gate, UrlBuilder urlBuilder) { } } diff --git a/diagrid-spring-ai/diagrid-spring-ai-starter/src/test/java/io/diagrid/springai/durable/boot/SpringEnvironmentLookupTest.java b/diagrid-spring-ai/diagrid-spring-ai-starter/src/test/java/io/diagrid/springai/durable/boot/SpringEnvironmentLookupTest.java new file mode 100644 index 0000000..4862791 --- /dev/null +++ b/diagrid-spring-ai/diagrid-spring-ai-starter/src/test/java/io/diagrid/springai/durable/boot/SpringEnvironmentLookupTest.java @@ -0,0 +1,145 @@ +package io.diagrid.springai.durable.boot; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.api.Test; +import org.springframework.context.EnvironmentAware; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.MutablePropertySources; +import org.springframework.core.env.StandardEnvironment; + +/** + * A Spring application can point at Catalyst through application.yml, a profile or the Dapr Spring + * Boot starter's {@code dapr.client.*} properties with no Dapr environment variable set at all. The + * Reo gate must see that configuration, or the artifact reports from the population it must not. + */ +class SpringEnvironmentLookupTest { + + private static final String ENDPOINT = "https://example.invalid/java-ai"; + + @ParameterizedTest + @CsvSource({ + "dapr.client.grpc-endpoint,https://grpc.abc.diagrid.io:443", + "dapr.client.grpcEndpoint,https://grpc.abc.diagrid.io:443", + "dapr.client.http-endpoint,https://http.abc.diagrid.io", + "dapr.client.httpEndpoint,https://http.abc.diagrid.io", + "dapr.grpc.endpoint,https://grpc.abc.diagrid.io:443", + "dapr.http.endpoint,https://http.abc.diagrid.io", + "DAPR_GRPC_ENDPOINT,https://grpc.abc.diagrid.io:443" + }) + void reoGateIsClosedWhenCatalystIsConfiguredInSpringOnly(String property, String value) { + UsageAnalytics analytics = analyticsFor(springEnvironment(Map.of(property, value))); + assertEquals("catalyst", analytics.detectTarget()); + assertFalse(analytics.reoAllowed()); + } + + @ParameterizedTest + @CsvSource({"dapr.client.api-token", "dapr.client.apiToken", "dapr.api.token"}) + void reoGateIsClosedWhenTheApiTokenComesFromSpringConfiguration(String property) { + UsageAnalytics analytics = analyticsFor(springEnvironment(Map.of(property, "secret"))); + assertEquals("catalyst", analytics.detectTarget()); + assertFalse(analytics.reoAllowed()); + } + + @Test + void aPlainLocalSidecarInSpringConfigurationLeavesTheGateOpen() { + UsageAnalytics analytics = + analyticsFor(springEnvironment(Map.of("dapr.client.grpc-endpoint", "http://localhost:50001"))); + assertEquals("dapr", analytics.detectTarget()); + assertTrue(analytics.reoAllowed()); + } + + @Test + void withNothingConfiguredTheGateIsOpen() { + // The counterpart that makes the closed-gate tests meaningful: the same hermetic lookup, no Catalyst. + assertTrue(analyticsFor(springEnvironment(Map.of())).reoAllowed()); + } + + @Test + void anOptOutCanComeFromSpringConfigurationToo() { + UsageAnalytics analytics = analyticsFor(springEnvironment(Map.of("DO_NOT_TRACK", "1"))); + assertTrue(analytics.isReportingDisabled()); + } + + @Test + void theResolverFallsBackToGetenvWhenSpringHasNothing() { + StandardEnvironment empty = new StandardEnvironment(); + MutablePropertySources sources = empty.getPropertySources(); + for (String name : sources.stream().map(source -> source.getName()).toList()) { + sources.remove(name); + } + assertNotNull(SpringEnvironmentLookup.resolver(empty).apply("PATH")); + } + + @Test + void aNullEnvironmentFallsBackToGetenv() { + assertNotNull(SpringEnvironmentLookup.resolver(null).apply("PATH")); + } + + @Test + void anUnsetNameResolvesToNull() { + Function resolver = SpringEnvironmentLookup.resolver(springEnvironment(Map.of())); + assertNull(resolver.apply("DIAGRID_TEST_SURELY_UNSET_" + System.nanoTime())); + } + + @Test + void aThrowingEnvironmentFallsBackToGetenvInsteadOfThrowing() { + StandardEnvironment broken = + new StandardEnvironment() { + @Override + public String getProperty(String key) { + throw new IllegalStateException("boom"); + } + }; + assertNotNull(SpringEnvironmentLookup.resolver(broken).apply("PATH")); + } + + @Test + void theAutoConfigurationReceivesTheSpringEnvironment() { + // The initializer can only pass the resolver on if Spring hands the configuration its Environment. + assertTrue( + EnvironmentAware.class.isAssignableFrom(DiagridSpringAiAutoConfiguration.class), + "DiagridSpringAiAutoConfiguration must implement EnvironmentAware"); + } + + @Test + void theLookupOrderIsSpringFirstThenGetenv() { + List names = SpringEnvironmentLookup.candidateNames("DAPR_GRPC_ENDPOINT"); + assertEquals("DAPR_GRPC_ENDPOINT", names.get(0)); + assertTrue(names.contains("dapr.grpc.endpoint")); + assertTrue(names.contains("dapr.client.grpc-endpoint")); + assertTrue(names.contains("dapr.client.grpcEndpoint")); + } + + // ---------------------------------------------------------------- test doubles + + /** + * A reporter whose lookup sees only {@code environment}. The fallback returns nothing, because the + * build runs test JVMs with DIAGRID_NO_ANALYTICS=1 and CI may set CI=true: falling back to the real + * environment would close the gate for reasons that have nothing to do with Spring. + */ + private static UsageAnalytics analyticsFor(StandardEnvironment environment) { + return new UsageAnalytics( + ENDPOINT, SpringEnvironmentLookup.resolver(environment, name -> null), (url, userAgent) -> { }); + } + + /** A real Spring Environment holding only the given properties, as application.yml would supply them. */ + private static StandardEnvironment springEnvironment(Map properties) { + StandardEnvironment environment = new StandardEnvironment(); + MutablePropertySources sources = environment.getPropertySources(); + for (String name : sources.stream().map(source -> source.getName()).toList()) { + sources.remove(name); + } + sources.addFirst(new MapPropertySource("application", properties)); + return environment; + } +} diff --git a/diagrid-spring-ai/diagrid-spring-ai-starter/src/test/java/io/diagrid/springai/durable/boot/UsageAnalyticsDestinationsTest.java b/diagrid-spring-ai/diagrid-spring-ai-starter/src/test/java/io/diagrid/springai/durable/boot/UsageAnalyticsDestinationsTest.java new file mode 100644 index 0000000..f25a420 --- /dev/null +++ b/diagrid-spring-ai/diagrid-spring-ai-starter/src/test/java/io/diagrid/springai/durable/boot/UsageAnalyticsDestinationsTest.java @@ -0,0 +1,203 @@ +package io.diagrid.springai.durable.boot; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * The destination list behind {@link UsageAnalytics}: Scarf's exact output, and how several + * destinations are gated, deduplicated and isolated from each other. + */ +class UsageAnalyticsDestinationsTest { + + private static final String ENDPOINT = "https://example.invalid/java-ai"; + + @BeforeEach + void resetGuard() { + UsageAnalytics.resetForTesting(); + } + + // ---------------------------------------------------------------- Scarf golden + + @Test + void scarfUrlAndUserAgentHaveTheDocumentedShape() { + String osName = System.getProperty("os.name"); + String osArch = System.getProperty("os.arch"); + String javaVersion = System.getProperty("java.version"); + try { + System.setProperty("os.name", "Linux"); + System.setProperty("os.arch", "amd64"); + System.setProperty("java.version", "21.0.1"); + Recorder recorder = new Recorder(); + UsageAnalytics analytics = new UsageAnalytics(ENDPOINT, name -> null, recorder); + Map dimensions = new LinkedHashMap<>(); + dimensions.put("kind", "agent"); + dimensions.put("framework", "SpringAI"); + dimensions.put("framework_version", "1.0.0"); + + analytics.reportEvent("diagrid-spring-ai-starter", "0.1.0", dimensions); + + assertEquals( + List.of( + "https://example.invalid/java-ai?package=diagrid-spring-ai-starter&version=0.1.0" + + "&os=linux&arch=amd64&java_version=21.0.1&target=dapr&ci=false" + + "&kind=agent&framework=SpringAI&framework_version=1.0.0"), + recorder.urls); + assertEquals(List.of("diagrid-spring-ai-starter/0.1.0"), recorder.userAgents); + } finally { + restore("os.name", osName); + restore("os.arch", osArch); + restore("java.version", javaVersion); + } + } + + // ---------------------------------------------------------------- destination list + + @Test + void reportSendsToEachAllowedDestination() { + Recorder recorder = new Recorder(); + UsageAnalytics analytics = + UsageAnalytics.withDestinations( + name -> null, recorder, List.of(destination("a", true), destination("b", true))); + + analytics.reportEvent("pkg-each", "1.0.0", Map.of()); + + assertEquals(List.of("https://a.invalid/?package=pkg-each", "https://b.invalid/?package=pkg-each"), recorder.urls); + } + + @Test + void reportSkipsADestinationWhoseGateIsClosed() { + Recorder recorder = new Recorder(); + UsageAnalytics analytics = + UsageAnalytics.withDestinations( + name -> null, recorder, List.of(destination("a", false), destination("b", true))); + + analytics.reportEvent("pkg-gate", "1.0.0", Map.of()); + + assertEquals(List.of("https://b.invalid/?package=pkg-gate"), recorder.urls); + } + + @Test + void reportDedupesPerDestinationPerPackage() { + Recorder recorder = new Recorder(); + UsageAnalytics analytics = + UsageAnalytics.withDestinations( + name -> null, recorder, List.of(destination("a", true), destination("b", true))); + + analytics.reportEvent("pkg-dedupe", "1.0.0", Map.of()); + analytics.reportEvent("pkg-dedupe", "1.0.0", Map.of()); + analytics.reportEvent("pkg-other", "1.0.0", Map.of()); + + assertEquals(4, recorder.urls.size(), "one send per destination per package: " + recorder.urls); + } + + @Test + void aClosedGateOnOneDestinationDoesNotConsumeAnotherDestinationsSend() { + Recorder recorder = new Recorder(); + // "a" is closed and reports first; it must not mark the package as reported for "b". + UsageAnalytics analytics = + UsageAnalytics.withDestinations( + name -> null, recorder, List.of(destination("a", false), destination("b", true))); + + analytics.reportEvent("pkg-isolated", "1.0.0", Map.of()); + + assertEquals(List.of("https://b.invalid/?package=pkg-isolated"), recorder.urls); + } + + @Test + void aDestinationThatThrowsDoesNotStopTheOthers() { + Recorder recorder = new Recorder(); + UsageAnalytics.Destination throwingUrl = + new UsageAnalytics.Destination( + "url-throws", + "https://x.invalid/", + () -> true, + (packageName, version, dimensions) -> { + throw new IllegalStateException("boom"); + }); + UsageAnalytics.Destination throwingGate = + new UsageAnalytics.Destination( + "gate-throws", + "https://y.invalid/", + () -> { + throw new IllegalStateException("boom"); + }, + (packageName, version, dimensions) -> "https://y.invalid/"); + UsageAnalytics analytics = + UsageAnalytics.withDestinations( + name -> null, recorder, List.of(throwingUrl, throwingGate, destination("b", true))); + + analytics.reportEvent("pkg-throws", "1.0.0", Map.of()); + + assertEquals(List.of("https://b.invalid/?package=pkg-throws"), recorder.urls); + } + + @Test + void anEmptyEndpointIsANoOpForThatDestinationOnly() { + Recorder recorder = new Recorder(); + UsageAnalytics.Destination empty = + new UsageAnalytics.Destination( + "empty", "", () -> true, (packageName, version, dimensions) -> "https://never.invalid/"); + UsageAnalytics analytics = + UsageAnalytics.withDestinations(name -> null, recorder, List.of(empty, destination("b", true))); + + analytics.reportEvent("pkg-empty", "1.0.0", Map.of()); + + assertEquals(List.of("https://b.invalid/?package=pkg-empty"), recorder.urls); + } + + @Test + void aSenderThatThrowsForOneDestinationStillReachesTheNext() { + List delivered = new CopyOnWriteArrayList<>(); + UsageAnalytics.Sender flaky = + (url, userAgent) -> { + if (url.startsWith("https://a.invalid/")) { + throw new IllegalStateException("unreachable"); + } + delivered.add(url); + }; + UsageAnalytics analytics = + UsageAnalytics.withDestinations(name -> null, flaky, List.of(destination("a", true), destination("b", true))); + + analytics.reportEvent("pkg-flaky", "1.0.0", Map.of()); + + assertTrue(delivered.contains("https://b.invalid/?package=pkg-flaky"), "b was not reached: " + delivered); + } + + // ---------------------------------------------------------------- test doubles + + private static UsageAnalytics.Destination destination(String name, boolean open) { + return new UsageAnalytics.Destination( + name, + "https://" + name + ".invalid/", + () -> open, + (packageName, version, dimensions) -> "https://" + name + ".invalid/?package=" + packageName); + } + + private static void restore(String key, String value) { + if (value == null) { + System.clearProperty(key); + } else { + System.setProperty(key, value); + } + } + + /** Records every call synchronously; reportEvent hands the request to the sender on the caller's thread. */ + private static final class Recorder implements UsageAnalytics.Sender { + + private final List urls = new CopyOnWriteArrayList<>(); + private final List userAgents = new CopyOnWriteArrayList<>(); + + @Override + public void send(String url, String userAgent) { + urls.add(url); + userAgents.add(userAgent); + } + } +} diff --git a/diagrid-spring-ai/diagrid-spring-ai-starter/src/test/java/io/diagrid/springai/durable/boot/UsageAnalyticsReoTest.java b/diagrid-spring-ai/diagrid-spring-ai-starter/src/test/java/io/diagrid/springai/durable/boot/UsageAnalyticsReoTest.java new file mode 100644 index 0000000..155121a --- /dev/null +++ b/diagrid-spring-ai/diagrid-spring-ai-starter/src/test/java/io/diagrid/springai/durable/boot/UsageAnalyticsReoTest.java @@ -0,0 +1,337 @@ +package io.diagrid.springai.durable.boot; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.function.Function; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * The Reo destination: its gate, which is stricter than Scarf's. Every env here is an explicit map, + * so a test never reads the real environment and none passes vacuously because CI is set. + */ +class UsageAnalyticsReoTest { + + private static final String ENDPOINT = "https://example.invalid/java-ai"; + + @BeforeEach + void resetGuard() { + UsageAnalytics.resetForTesting(); + } + + // ---------------------------------------------------------------- gate + + @Test + void reoGateIsOpenOnACleanDeveloperMachine() { + assertTrue(analytics(cleanEnv()).reoAllowed()); + } + + @ParameterizedTest + @ValueSource(strings = {"DO_NOT_TRACK", "SCARF_NO_ANALYTICS", "DIAGRID_NO_ANALYTICS"}) + void reoGateIsClosedOnOptOut(String variable) { + assertFalse(analytics(envWith(variable, "1")).reoAllowed()); + } + + @Test + void reoGateIsClosedInKubernetes() { + assertFalse(analytics(envWith("KUBERNETES_SERVICE_HOST", "10.0.0.1")).reoAllowed()); + } + + @ParameterizedTest + @CsvSource({ + "DAPR_API_TOKEN,t", + "DAPR_GRPC_ENDPOINT,https://grpc.abc.diagrid.io:443", + "DAPR_HTTP_ENDPOINT,https://http.abc.diagrid.io" + }) + void reoGateIsClosedWhenPointedAtCatalyst(String name, String value) { + assertFalse(analytics(envWith(name, value)).reoAllowed()); + } + + @Test + void reoGateTreatsAPlainDaprSidecarAsNotCatalyst() { + assertTrue(analytics(envWith("DAPR_GRPC_ENDPOINT", "http://localhost:50001")).reoAllowed()); + } + + @ParameterizedTest + @ValueSource( + strings = {"CI", "GITHUB_ACTIONS", "GITLAB_CI", "CIRCLECI", "TRAVIS", "TF_BUILD", "BUILDKITE", "JENKINS_URL"}) + void reoGateIsClosedInCi(String variable) { + assertFalse(analytics(envWith(variable, "true")).reoAllowed()); + } + + @Test + void reoGateFailsClosedOnMalformedEndpoint() { + // User-supplied, parsed as a URI, inside a SmartInitializingSingleton. + assertFalse(analytics(envWith("DAPR_GRPC_ENDPOINT", "http://[:::::")).reoAllowed()); + } + + @Test + void reoGateFailsClosedWhenTheEnvironmentLookupThrows() { + Function broken = + name -> { + throw new IllegalStateException("boom"); + }; + assertFalse(analytics(broken).reoAllowed()); + } + + @Test + void reoGateIsNotVacuousUnderCi() { + // Guards the Review Focus trap: the suite itself runs with CI=true in GitHub Actions. + assertFalse(analytics(envWith("CI", "true")).reoAllowed()); + assertTrue(analytics(cleanEnv()).reoAllowed()); + } + + @Test + void aMalformedEndpointStillReportsDaprToScarf() { + // The Reo gate fails closed on it, but Scarf's target dimension must not change. + assertTrue( + "dapr".equals(analytics(envWith("DAPR_GRPC_ENDPOINT", "http://[:::::")).detectTarget()), + "Scarf's target dimension changed for a malformed endpoint"); + } + + // ---------------------------------------------------------------- the Reo URL + + @Test + void reoUrlMapsCollectedNamesToRegisteredKeys() { + Map query = query(reoUrl(springAiDimensions())); + assertEquals("maven_runtime", query.get("activity_type")); + assertEquals("diagrid-spring-ai-starter", query.get("product")); + assertEquals("0.5.0", query.get("version")); + assertEquals(System.getProperty("java.version"), query.get("jvm")); + assertTrue(query.containsKey("platform"), "platform missing: " + query); + assertEquals(System.getProperty("os.arch"), query.get("arch")); + assertEquals("agent", query.get("kind")); + assertEquals("SpringAI", query.get("framework")); + assertEquals("1.0.3", query.get("framework_version")); + } + + @Test + void reoUrlStartsAtTheReoEndpoint() { + assertTrue(reoUrl(springAiDimensions()).startsWith("https://reo.example.invalid/data?")); + } + + @Test + void reoUrlOmitsTargetAndCi() { + Map query = query(reoUrl(springAiDimensions())); + assertFalse(query.containsKey("target"), "target sent to Reo: " + query); + assertFalse(query.containsKey("ci"), "ci sent to Reo: " + query); + } + + @Test + void reoUrlOmitsTheUnmappedSourceNames() { + Map dimensions = springAiDimensions(); + dimensions.put("something_else", "x"); + Map query = query(reoUrl(dimensions)); + for (String name : List.of("package", "java_version", "os", "something_else")) { + assertFalse(query.containsKey(name), name + " sent to Reo: " + query); + } + } + + @Test + void reoUrlDropsBlankValues() { + Map dimensions = springAiDimensions(); + dimensions.put("framework_version", " "); + assertFalse(query(reoUrl(dimensions)).containsKey("framework_version")); + } + + @Test + void reoUrlEscapesHostileValues() { + Map dimensions = springAiDimensions(); + dimensions.put("framework", "a&b=c"); + Map query = query(reoUrl(dimensions)); + assertEquals("a&b=c", query.get("framework")); + assertFalse(query.containsKey("b"), "a value split into a second parameter: " + query); + } + + @Test + void reoValuesAreTrimmedAndCappedAt64Characters() { + Map dimensions = springAiDimensions(); + dimensions.put("framework", " " + "x".repeat(100) + " "); + assertEquals("x".repeat(64), query(reoUrl(dimensions)).get("framework")); + } + + // ---------------------------------------------------------------- sending + + @Test + void anOpenGateSendsOneScarfAndOneReoEvent() { + List urls = new CopyOnWriteArrayList<>(); + UsageAnalytics analytics = + new UsageAnalytics(ENDPOINT, "https://reo.example.invalid/data", cleanEnv(), (url, ua) -> urls.add(url)); + + analytics.reportEvent("diagrid-spring-ai-starter", "0.5.0", springAiDimensions()); + analytics.reportEvent("diagrid-spring-ai-starter", "0.5.0", springAiDimensions()); + + assertEquals(2, urls.size(), "one event per destination: " + urls); + assertTrue(urls.get(0).startsWith(ENDPOINT + "?package="), "Scarf first: " + urls); + assertTrue(urls.get(1).startsWith("https://reo.example.invalid/data?activity_type=maven_runtime")); + } + + @Test + void inCiScarfStillSendsAndReoDoesNot() { + List urls = new CopyOnWriteArrayList<>(); + UsageAnalytics analytics = + new UsageAnalytics( + ENDPOINT, "https://reo.example.invalid/data", envWith("CI", "true"), (url, ua) -> urls.add(url)); + + analytics.reportEvent("diagrid-spring-ai-starter", "0.5.0", springAiDimensions()); + + assertEquals(1, urls.size(), urls.toString()); + assertTrue(urls.get(0).startsWith(ENDPOINT + "?")); + } + + @Test + void scarfUrlIsUnchangedByTheReoDestination() { + String scarfOnly = new UsageAnalytics(ENDPOINT, cleanEnv(), (url, ua) -> { }) + .buildUrl("diagrid-spring-ai-starter", "0.5.0", springAiDimensions()); + String withReo = new UsageAnalytics(ENDPOINT, "https://reo.example.invalid/data", cleanEnv(), (url, ua) -> { }) + .buildUrl("diagrid-spring-ai-starter", "0.5.0", springAiDimensions()); + assertEquals(scarfOnly, withReo); + } + + @Test + void theDefaultReporterSendsToTheProductionReoEndpoint() { + assertEquals("https://telemetry.diagrid.io/data", UsageAnalytics.REO_ENDPOINT); + } + + @Test + void reoRequestIsAGetWithQueryParametersAndNoAuthorizationHeader() throws Exception { + try (RecordingServer server = new RecordingServer(true)) { + UsageAnalytics.sendHttp(server.url() + "/data?activity_type=maven_runtime&product=p", "p/1"); + List request = server.awaitRequest(); + assertEquals("GET /data?activity_type=maven_runtime&product=p HTTP/1.1", request.get(0)); + for (String header : request) { + assertFalse(header.toLowerCase(java.util.Locale.ROOT).startsWith("authorization:"), "auth header: " + request); + } + } + } + + @Test + void reportingReturnsAtFullSpeedWhenTheEndpointHangs() throws Exception { + // The initializer runs on the application's startup path, so a server that never answers must + // not hold it up. + try (RecordingServer server = new RecordingServer(false)) { + UsageAnalytics analytics = + new UsageAnalytics("", server.url() + "/data", cleanEnv(), UsageAnalytics::sendHttp); + long start = System.nanoTime(); + analytics.reportEvent("pkg-hang", "1.0.0", springAiDimensions()); + long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); + assertTrue(elapsedMillis < 200, "reportEvent blocked for " + elapsedMillis + " ms"); + } + } + + // ---------------------------------------------------------------- test doubles + + private static String reoUrl(Map dimensions) { + return new UsageAnalytics(ENDPOINT, "https://reo.example.invalid/data", cleanEnv(), (url, ua) -> { }) + .buildReoUrl("diagrid-spring-ai-starter", "0.5.0", dimensions); + } + + private static Map springAiDimensions() { + Map dimensions = new LinkedHashMap<>(); + dimensions.put("kind", "agent"); + dimensions.put("framework", "SpringAI"); + dimensions.put("framework_version", "1.0.3"); + return dimensions; + } + + private static Map query(String url) { + Map result = new LinkedHashMap<>(); + String raw = URI.create(url).getRawQuery(); + for (String pair : raw.split("&")) { + int equals = pair.indexOf('='); + result.put( + java.net.URLDecoder.decode(pair.substring(0, equals), StandardCharsets.UTF_8), + java.net.URLDecoder.decode(pair.substring(equals + 1), StandardCharsets.UTF_8)); + } + return result; + } + + /** A local HTTP server: records the request line and headers, then answers 200 or never answers. */ + private static final class RecordingServer implements AutoCloseable { + + private final ServerSocket socket; + private final List lines = new ArrayList<>(); + private final CountDownLatch received = new CountDownLatch(1); + private final Thread thread; + + RecordingServer(boolean answer) throws IOException { + socket = new ServerSocket(0); + thread = + new Thread( + () -> { + try (Socket client = socket.accept()) { + BufferedReader in = + new BufferedReader(new InputStreamReader(client.getInputStream(), StandardCharsets.US_ASCII)); + String line; + while ((line = in.readLine()) != null && !line.isEmpty()) { + synchronized (lines) { + lines.add(line); + } + } + received.countDown(); + if (answer) { + client.getOutputStream().write( + "HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + .getBytes(StandardCharsets.US_ASCII)); + } else { + Thread.sleep(5_000); + } + } catch (IOException | InterruptedException e) { + // closing the server ends the thread + } + }); + thread.setDaemon(true); + thread.start(); + } + + String url() { + return "http://127.0.0.1:" + socket.getLocalPort(); + } + + List awaitRequest() throws InterruptedException { + assertTrue(received.await(5, TimeUnit.SECONDS), "no request arrived"); + synchronized (lines) { + return List.copyOf(lines); + } + } + + @Override + public void close() throws IOException { + socket.close(); + thread.interrupt(); + } + } + + private static UsageAnalytics analytics(Function env) { + return new UsageAnalytics(ENDPOINT, env, (url, userAgent) -> { }); + } + + /** No CI, opt-out, Kubernetes or Dapr variable is set: a developer's own machine. */ + private static Function cleanEnv() { + return name -> null; + } + + private static Function envWith(String name, String value) { + Map env = Map.of(name, value); + return env::get; + } +} diff --git a/diagrid-spring-ai/diagrid-spring-ai-starter/src/test/java/io/diagrid/springai/durable/boot/UsageAnalyticsWiringTest.java b/diagrid-spring-ai/diagrid-spring-ai-starter/src/test/java/io/diagrid/springai/durable/boot/UsageAnalyticsWiringTest.java new file mode 100644 index 0000000..6db73e9 --- /dev/null +++ b/diagrid-spring-ai/diagrid-spring-ai-starter/src/test/java/io/diagrid/springai/durable/boot/UsageAnalyticsWiringTest.java @@ -0,0 +1,60 @@ +package io.diagrid.springai.durable.boot; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.MutablePropertySources; +import org.springframework.core.env.StandardEnvironment; + +/** + * The auto-configuration must hand the reporter a lookup backed by Spring's Environment. Without it, + * a Catalyst endpoint set only in application.yml would not close the Reo gate. + */ +class UsageAnalyticsWiringTest { + + @BeforeEach + void resetGuard() { + UsageAnalytics.resetForTesting(); + } + + @Test + void aCatalystEndpointInSpringConfigurationKeepsTheInitializerAwayFromReo() { + List urls = runInitializer(Map.of("dapr.client.grpc-endpoint", "https://grpc.abc.diagrid.io:443")); + + assertFalse(urls.stream().anyMatch(url -> url.startsWith(UsageAnalytics.REO_ENDPOINT)), "Reo was called: " + urls); + assertTrue(urls.stream().anyMatch(url -> url.startsWith(UsageAnalytics.DEFAULT_ENDPOINT)), "Scarf missing: " + urls); + } + + @Test + void withNothingConfiguredTheInitializerReportsToReo() { + // The counterpart: the same wiring with no Catalyst configuration does reach Reo. + List urls = runInitializer(Map.of()); + + assertTrue(urls.stream().anyMatch(url -> url.startsWith(UsageAnalytics.REO_ENDPOINT)), "Reo missing: " + urls); + } + + /** + * Runs the initializer's work against a Spring Environment holding only {@code properties}. The + * fallback lookup returns nothing, because the build runs test JVMs with DIAGRID_NO_ANALYTICS=1. + */ + private static List runInitializer(Map properties) { + StandardEnvironment environment = new StandardEnvironment(); + MutablePropertySources sources = environment.getPropertySources(); + for (String name : sources.stream().map(source -> source.getName()).toList()) { + sources.remove(name); + } + sources.addFirst(new MapPropertySource("application", properties)); + + DiagridSpringAiAutoConfiguration configuration = new DiagridSpringAiAutoConfiguration(); + configuration.setEnvironment(environment); + List urls = new CopyOnWriteArrayList<>(); + configuration.reportUsage((url, userAgent) -> urls.add(url), name -> null); + return urls; + } +}