From d5049aeae84ac10c86563e14c28acc5e9aeeaabd Mon Sep 17 00:00:00 2001 From: joker23 <2494686+joker23@users.noreply.github.com> Date: Fri, 30 Oct 2026 16:53:04 -0400 Subject: [PATCH 1/5] feat: add support for `usePost` option for FDv2 (#411) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary - Adds a `usePost` option (default `false`) to `HttpConfigurationBuilder`. When the FDv2 data system is configured, polling and streaming requests use POST with the evaluation context JSON in the request body instead of GET with the base64url context in the URL path. This keeps the context out of URL-based request logs and CDN logs. - The FDv1 fallback synchronizer sends REPORT when `usePost` is enabled, because the FDv1 endpoints do not support POST. - `useReport` no longer affects FDv2 requests. The SDK logs one warning when it is set together with the data system. Legacy (non-data-system) FDv1 behavior is unchanged. - Contract tests: the test service declares the `client-use-post` capability, maps the harness's `clientSide.usePost` parameter, and the v3 harness is bumped to v3.2.0-alpha.10 (the release that added the POST test variants). The bump also pulls in stricter events-redaction tests that expose a pre-existing bug in `launchdarkly-java-sdk-internal` (attribute names containing `/` are not escaped as attribute references in `redactedAttributes`). The three affected test groups are suppressed in `testharness-suppressions-fdv2.txt` and tracked by SDK-3338; the suppressions should be removed when that fix ships. Implements CSFDV2 Requirement 2.1.3 (usePost option) and 2.1.4 (useReport ignored with a warning under the FDv2 configuration). Verified locally: full unit suite (752 tests) green; contract tests green on an emulator (v2 suite, and v3 at v3.2.0-alpha.10 with the suppressions above - all POST variants pass). --- > [!NOTE] > **Overview** > Adds a **`usePost`** HTTP option (default off) so that when the FDv2 data system is enabled, polling and streaming send the evaluation context in a **POST** body instead of a **GET** URL with a base64 context segment—keeping context out of URL/CDN logs. FDv2 paths that previously used **REPORT** under `useReport` now use **POST**; **ETag**/`If-None-Match` caching stays on **GET** only. > > With the data system, **`useReport` no longer changes FDv2 traffic**; the builder logs a **one-time warning** that requests stay GET unless `usePost` is on. **FDv1 fallback** still has no POST endpoint, so enabling `usePost` maps to **REPORT** with a body there. > > Contract testing advertises **`client-use-post`**, wires harness `clientSide.usePost`, and bumps the v3 harness to **v3.2.0-alpha.10**. Three new v3 event-redaction cases are **suppressed** pending an internal SDK fix (SDK-3338). > > Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 913ef161d68491acf89127afb4746004a59b4fec. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot). --- Makefile | 4 +- .../launchdarkly/sdktest/Representations.java | 1 + .../launchdarkly/sdktest/SdkClientEntity.java | 4 +- .../com/launchdarkly/sdktest/TestService.java | 3 +- .../sdk/android/ComponentsImpl.java | 3 +- .../sdk/android/DataSystemComponents.java | 11 +- .../sdk/android/DefaultFDv2Requestor.java | 33 ++-- .../sdk/android/FDv2DataSourceBuilder.java | 11 ++ .../android/FDv2StreamingSynchronizer.java | 16 +- .../sdk/android/StandardEndpoints.java | 2 +- .../HttpConfigurationBuilder.java | 24 +++ .../android/subsystems/HttpConfiguration.java | 32 +++- .../sdk/android/DataSystemComponentsTest.java | 181 ++++++++++++++++++ .../sdk/android/DefaultFDv2RequestorTest.java | 36 ++-- .../android/FDv2DataSourceBuilderTest.java | 35 +++- .../FDv2StreamingSynchronizerTest.java | 16 +- .../android/HttpConfigurationBuilderTest.java | 16 ++ testharness-suppressions-fdv2.txt | 5 +- 18 files changed, 369 insertions(+), 64 deletions(-) create mode 100644 launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DataSystemComponentsTest.java diff --git a/Makefile b/Makefile index ed9965b7b..05f23b0a6 100644 --- a/Makefile +++ b/Makefile @@ -21,8 +21,8 @@ run-contract-tests: | VERSION=v2 PARAMS="-url http://localhost:8001 -host 10.0.2.2 -debug -skip-from $(SUPPRESSION_FILE) $(TEST_HARNESS_PARAMS_V2)" sh @echo "Running SDK contract test v3..." @curl $${GITHUB_TOKEN:+ -H "Authorization: Token $${GITHUB_TOKEN}"} \ - -s https://raw.githubusercontent.com/launchdarkly/sdk-test-harness/v3.1.0-alpha.6/downloader/run.sh \ - | VERSION=v3.1.0-alpha.6 PARAMS="-url http://localhost:8001 -host 10.0.2.2 -debug -stop-service-at-end -skip-from $(SUPPRESSION_FILE_FDV2) $(TEST_HARNESS_PARAMS_V3)" sh + -s https://raw.githubusercontent.com/launchdarkly/sdk-test-harness/v3.2.0-alpha.10/downloader/run.sh \ + | VERSION=v3.2.0-alpha.10 PARAMS="-url http://localhost:8001 -host 10.0.2.2 -debug -stop-service-at-end -skip-from $(SUPPRESSION_FILE_FDV2) $(TEST_HARNESS_PARAMS_V3)" sh contract-tests: build-contract-tests start-emulator start-contract-test-service run-contract-tests diff --git a/contract-tests/src/main/java/com/launchdarkly/sdktest/Representations.java b/contract-tests/src/main/java/com/launchdarkly/sdktest/Representations.java index 4b7aa650a..5c94b5806 100644 --- a/contract-tests/src/main/java/com/launchdarkly/sdktest/Representations.java +++ b/contract-tests/src/main/java/com/launchdarkly/sdktest/Representations.java @@ -78,6 +78,7 @@ public static class SdkConfigClientSideParams { LDContext initialContext; boolean evaluationReasons; boolean useReport; + boolean usePost; boolean includeEnvironmentAttributes; } diff --git a/contract-tests/src/main/java/com/launchdarkly/sdktest/SdkClientEntity.java b/contract-tests/src/main/java/com/launchdarkly/sdktest/SdkClientEntity.java index f96277041..2056d47e2 100644 --- a/contract-tests/src/main/java/com/launchdarkly/sdktest/SdkClientEntity.java +++ b/contract-tests/src/main/java/com/launchdarkly/sdktest/SdkClientEntity.java @@ -329,7 +329,9 @@ private LDConfig buildSdkConfig(SdkConfigParams params, LDLogAdapter logAdapter, builder.evaluationReasons(params.clientSide.evaluationReasons); builder.http( - Components.httpConfiguration().useReport(params.clientSide.useReport) + Components.httpConfiguration() + .useReport(params.clientSide.useReport) + .usePost(params.clientSide.usePost) ); if (params.tags != null) { diff --git a/contract-tests/src/main/java/com/launchdarkly/sdktest/TestService.java b/contract-tests/src/main/java/com/launchdarkly/sdktest/TestService.java index 50acf5e51..246388bc7 100644 --- a/contract-tests/src/main/java/com/launchdarkly/sdktest/TestService.java +++ b/contract-tests/src/main/java/com/launchdarkly/sdktest/TestService.java @@ -45,7 +45,8 @@ public class TestService extends NanoHTTPD { "client-per-context-summaries", "client-event-source-http-errors", "retry-conformance-fdv1-streaming", - "retry-conformance-fdv1-polling" + "retry-conformance-fdv1-polling", + "client-use-post" }; private static final String MIME_JSON = "application/json"; static final Gson gson = new GsonBuilder() diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/ComponentsImpl.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/ComponentsImpl.java index 34b47a2fe..b3413f857 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/ComponentsImpl.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/ComponentsImpl.java @@ -233,7 +233,8 @@ public HttpConfiguration build(ClientContext clientContext) { connectTimeoutMillis, headers, headerTransform, - useReport + useReport, + usePost ); } diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DataSystemComponents.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DataSystemComponents.java index 4d9dfea8f..7e6c5ec1d 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DataSystemComponents.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DataSystemComponents.java @@ -141,7 +141,7 @@ public Synchronizer build(DataSourceBuildInputs inputs) { StandardEndpoints.FDV2_STREAMING_REQUEST_BASE_PATH, requestor, initialReconnectDelayMillis, - inputs.isEvaluationReasons(), inputs.getHttp().isUseReport(), + inputs.isEvaluationReasons(), inputs.getHttp().shouldUsePost(), httpProps, inputs.getSharedExecutor(), inputs.getBaseLogger(), null); } @@ -159,10 +159,13 @@ public FDv1PollingSynchronizerBuilderImpl pollIntervalMillis(int pollIntervalMil @Override public Synchronizer build(DataSourceBuildInputs inputs) { + // The FDv1 endpoints have no POST variant. When usePost is enabled, the fetcher + // sends the context in the request body with REPORT so it stays out of the + // request URI. useReport has no effect inside the data system. FeatureFetcher fetcher = new HttpFeatureFlagFetcher( inputs.getServiceEndpoints().getPollingBaseUri(), inputs.isEvaluationReasons(), - inputs.getHttp().isUseReport(), + inputs.getHttp().shouldUsePost(), LDUtil.makeHttpProperties(inputs.getHttp()), inputs.getCacheDir(), inputs.getBaseLogger() @@ -361,8 +364,8 @@ private static FDv2Requestor makePollingRequestor(DataSourceBuildInputs inputs, return new DefaultFDv2Requestor( inputs.getEvaluationContext(), pollingBase, StandardEndpoints.FDV2_POLLING_REQUEST_GET_BASE_PATH, - StandardEndpoints.FDV2_POLLING_REQUEST_REPORT_BASE_PATH, - httpProps, inputs.getHttp().isUseReport(), + StandardEndpoints.FDV2_POLLING_REQUEST_POST_BASE_PATH, + httpProps, inputs.getHttp().shouldUsePost(), inputs.isEvaluationReasons(), null, inputs.getBaseLogger()); } } diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DefaultFDv2Requestor.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DefaultFDv2Requestor.java index 2ffa79e8c..31c254ddf 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DefaultFDv2Requestor.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DefaultFDv2Requestor.java @@ -31,16 +31,15 @@ /** * Default OkHttp-based implementation of {@link FDv2Requestor}. *

- * Builds GET or REPORT requests to the FDv2 polling endpoint. If the current selector is + * Builds GET or POST requests to the FDv2 polling endpoint. If the current selector is * non-empty, its state is sent as the {@code basis} query parameter. ETag tracking is used * to detect 304 Not Modified responses; when the server returns 304 the application layer * treats it as {@code ChangeSetType.None} (no flags changed), so no OkHttp disk cache is - * needed or used. + * needed or used. ETag tracking runs only for GET requests. *

* The OkHttpClient is closed by {@link #close()}. */ final class DefaultFDv2Requestor implements FDv2Requestor { - private static final String METHOD_REPORT = "REPORT"; private static final String BASIS_PARAM = "basis"; private static final String FILTER_PARAM = "filter"; private static final String WITH_REASONS_PARAM = "withReasons"; @@ -50,10 +49,10 @@ final class DefaultFDv2Requestor implements FDv2Requestor { private final OkHttpClient httpClient; private final URI pollingUri; private final okhttp3.Headers headers; - private final boolean useReport; + private final boolean usePost; private final boolean evaluationReasons; @Nullable - private final RequestBody reportBody; + private final RequestBody postBody; @Nullable private final String payloadFilter; private final LDLogger logger; @@ -68,9 +67,9 @@ final class DefaultFDv2Requestor implements FDv2Requestor { * @param evaluationContext the context to evaluate flags for * @param baseUri polling base URI from service endpoints * @param getRequestPath path for GET requests (context appended as a path segment) - * @param reportRequestPath path for REPORT requests (context sent in the request body) + * @param postRequestPath path for POST requests (context sent in the request body) * @param httpProperties SDK HTTP configuration (timeouts, proxy, TLS, user-agent, etc.) - * @param useReport if true, send context in the request body via REPORT; otherwise + * @param usePost if true, send context in the request body via POST; otherwise * append the base64-encoded context to the GET path * @param evaluationReasons if true, append {@code withReasons=true} to the query string * @param payloadFilter optional payload filter key; sent as {@code filter} query param @@ -80,13 +79,13 @@ final class DefaultFDv2Requestor implements FDv2Requestor { @NonNull LDContext evaluationContext, @NonNull URI baseUri, @NonNull String getRequestPath, - @NonNull String reportRequestPath, + @NonNull String postRequestPath, @NonNull HttpProperties httpProperties, - boolean useReport, + boolean usePost, boolean evaluationReasons, @Nullable String payloadFilter, @NonNull LDLogger logger) { - this.useReport = useReport; + this.usePost = usePost; this.evaluationReasons = evaluationReasons; this.payloadFilter = payloadFilter; this.logger = logger; @@ -94,14 +93,14 @@ final class DefaultFDv2Requestor implements FDv2Requestor { // Precompute the base polling URI for the chosen request method. For GET, the // base64-encoded context is a fixed path segment (context never changes after - // construction). For REPORT, the context goes in the request body so no path + // construction). For POST, the context goes in the request body so no path // segment is needed. URI basePollingUri = HttpHelpers.concatenateUriPath(baseUri, - useReport ? reportRequestPath : getRequestPath); - this.pollingUri = useReport + usePost ? postRequestPath : getRequestPath); + this.pollingUri = usePost ? basePollingUri : HttpHelpers.concatenateUriPath(basePollingUri, LDUtil.urlSafeBase64(evaluationContext)); - this.reportBody = useReport + this.postBody = usePost ? RequestBody.create(JsonSerialization.serialize(evaluationContext), JSON) : null; @@ -139,8 +138,8 @@ public Future poll(@NonNull Selector selector) { .url(requestUri.toURL()) .headers(headers); - if (useReport) { - reqBuilder.method(METHOD_REPORT, reportBody); + if (usePost) { + reqBuilder.post(postBody); } else { synchronized (etagLock) { if (!requestUri.equals(lastRequestUri)) { @@ -207,7 +206,7 @@ private void handleResponse( return; } - if (!useReport) { + if (!usePost) { synchronized (etagLock) { cachedEtag = response.header(ETAG_HEADER); } diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/FDv2DataSourceBuilder.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/FDv2DataSourceBuilder.java index 769eaa310..2fdfc1037 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/FDv2DataSourceBuilder.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/FDv2DataSourceBuilder.java @@ -39,6 +39,10 @@ class FDv2DataSourceBuilder implements ComponentConfigurer, Closeabl private boolean includeInitializers = true; // start with initializers private ScheduledExecutorService sharedExecutor; + // The useReport warning logs once per builder; build runs again on every + // connection mode switch. + private boolean useReportWarningLogged; + FDv2DataSourceBuilder() { this(DataSystemComponents.makeDefaultModeTable(), ConnectionMode.STREAMING, ModeResolutionTable.MOBILE); } @@ -98,6 +102,13 @@ ModeDefinition getModeDefinition(@NonNull ConnectionMode mode) { @Override public DataSource build(ClientContext clientContext) { + if (clientContext.getHttp().isUseReport() && !useReportWarningLogged) { + useReportWarningLogged = true; + clientContext.getBaseLogger().warn( + "The useReport option has no effect when the data system is configured;" + + " requests use GET unless usePost is enabled."); + } + if (sharedExecutor == null) { // Pool size 4: supports the FDv2DataSource main loop (1), an active synchronizer // such as the streaming event loop (1), FDv2DataSource condition timers for diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/FDv2StreamingSynchronizer.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/FDv2StreamingSynchronizer.java index ad6daf6dd..c44e0f71d 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/FDv2StreamingSynchronizer.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/FDv2StreamingSynchronizer.java @@ -53,7 +53,7 @@ *

*/ final class FDv2StreamingSynchronizer implements Synchronizer { - private static final String METHOD_REPORT = "REPORT"; + private static final String METHOD_POST = "POST"; private static final String PING = "ping"; private static final long READ_TIMEOUT_MS = 300_000; // 5 minutes private static final long MAX_RECONNECT_TIME_MS = 300_000; // 5 minutes @@ -61,7 +61,7 @@ final class FDv2StreamingSynchronizer implements Synchronizer { private final HttpProperties httpProperties; private final URI streamBaseUri; private final String streamRequestPath; - private final boolean useReport; + private final boolean usePost; private final LDContext evaluationContext; private final SelectorSource selectorSource; @Nullable @@ -92,7 +92,7 @@ final class FDv2StreamingSynchronizer implements Synchronizer { * @param requestor optional requestor for handling ping events via poll; may be null * @param initialReconnectDelayMillis delay before reconnecting after an error, in milliseconds * @param evaluationReasons true to request evaluation reasons in the stream - * @param useReport true to use HTTP REPORT for the request body + * @param usePost true to send the context in the request body via HTTP POST * @param httpProperties HTTP configuration for the stream request * @param executor executor used to run the streaming loop on a background * thread; should use background-priority threads @@ -107,7 +107,7 @@ final class FDv2StreamingSynchronizer implements Synchronizer { @Nullable FDv2Requestor requestor, int initialReconnectDelayMillis, boolean evaluationReasons, - boolean useReport, + boolean usePost, @NonNull HttpProperties httpProperties, @NonNull Executor executor, @NonNull LDLogger logger, @@ -120,7 +120,7 @@ final class FDv2StreamingSynchronizer implements Synchronizer { this.requestor = requestor; this.initialReconnectDelayMillis = initialReconnectDelayMillis; this.evaluationReasons = evaluationReasons; - this.useReport = useReport; + this.usePost = usePost; this.httpProperties = httpProperties; this.executor = executor; this.logger = logger; @@ -188,9 +188,9 @@ private void startStream() { return reqBuilder.build(); }); - if (useReport) { + if (usePost) { connectStrategy = connectStrategy.methodAndBody( - METHOD_REPORT, + METHOD_POST, RequestBody.create(JsonSerialization.serialize(evaluationContext), JSON)); } @@ -244,7 +244,7 @@ private void startStream() { private URI getStreamUri() { URI uri = HttpHelpers.concatenateUriPath(streamBaseUri, streamRequestPath); - if (!useReport) { + if (!usePost) { uri = HttpHelpers.concatenateUriPath(uri, LDUtil.urlSafeBase64(evaluationContext)); } if (evaluationReasons) { diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/StandardEndpoints.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/StandardEndpoints.java index 06c51e32a..0c216aa34 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/StandardEndpoints.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/StandardEndpoints.java @@ -18,7 +18,7 @@ private StandardEndpoints() {} static final String DIAGNOSTIC_EVENTS_REQUEST_PATH = "/mobile/events/diagnostic"; static final String FDV2_POLLING_REQUEST_GET_BASE_PATH = "/sdk/poll/eval"; - static final String FDV2_POLLING_REQUEST_REPORT_BASE_PATH = "/sdk/poll/eval"; + static final String FDV2_POLLING_REQUEST_POST_BASE_PATH = "/sdk/poll/eval"; static final String FDV2_STREAMING_REQUEST_BASE_PATH = "/sdk/stream/eval"; /** diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/integrations/HttpConfigurationBuilder.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/integrations/HttpConfigurationBuilder.java index d59f1680d..26531d8f5 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/integrations/HttpConfigurationBuilder.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/integrations/HttpConfigurationBuilder.java @@ -46,6 +46,11 @@ public abstract class HttpConfigurationBuilder implements ComponentConfigurer + * By default, polling and streaming connections are made with the GET method, with the + * evaluation context data encoded into the request URI. When this option is enabled, the + * SDK sends the context data in the request body instead. This keeps the context out of + * URL-based request logs and CDN logs. + *

+ * This option only takes effect when the data system is configured with + * {@link com.launchdarkly.sdk.android.LDConfig.Builder#dataSystem(DataSystemBuilder)}. + * + * @param usePost true to enable the POST method + * @return the builder + */ + public HttpConfigurationBuilder usePost(boolean usePost) { + this.usePost = usePost; + return this; + } + /** * For use by wrapper libraries to set an identifying name for the wrapper being used. This will be included in a * header during requests to the LaunchDarkly servers to allow recording metrics on the usage of diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/subsystems/HttpConfiguration.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/subsystems/HttpConfiguration.java index a0257cc2c..c9e53d15b 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/subsystems/HttpConfiguration.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/subsystems/HttpConfiguration.java @@ -25,6 +25,7 @@ public final class HttpConfiguration { private final Map defaultHeaders; private final LDHeaderUpdater headerTransform; private final boolean useReport; + private final boolean usePost; /** * Creates an instance. @@ -33,18 +34,38 @@ public final class HttpConfiguration { * @param defaultHeaders see {@link #getDefaultHeaders()} * @param headerTransform see {@link #getHeaderTransform()} * @param useReport see {@link #isUseReport()} + * @param usePost see {@link #shouldUsePost()} */ public HttpConfiguration( int connectTimeoutMillis, Map defaultHeaders, LDHeaderUpdater headerTransform, - boolean useReport + boolean useReport, + boolean usePost ) { super(); this.connectTimeoutMillis = connectTimeoutMillis; this.defaultHeaders = defaultHeaders == null ? emptyMap() : new HashMap<>(defaultHeaders); this.headerTransform = headerTransform; this.useReport = useReport; + this.usePost = usePost; + } + + /** + * Creates an instance with {@code usePost} disabled. + * + * @param connectTimeoutMillis see {@link #getConnectTimeoutMillis()} + * @param defaultHeaders see {@link #getDefaultHeaders()} + * @param headerTransform see {@link #getHeaderTransform()} + * @param useReport see {@link #isUseReport()} + */ + public HttpConfiguration( + int connectTimeoutMillis, + Map defaultHeaders, + LDHeaderUpdater headerTransform, + boolean useReport + ) { + this(connectTimeoutMillis, defaultHeaders, headerTransform, useReport, false); } /** @@ -84,4 +105,13 @@ public LDHeaderUpdater getHeaderTransform() { public boolean isUseReport() { return useReport; } + + /** + * The setting for whether to use the HTTP POST method for FDv2 flag requests. + * + * @return true to use HTTP POST + */ + public boolean shouldUsePost() { + return usePost; + } } diff --git a/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DataSystemComponentsTest.java b/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DataSystemComponentsTest.java new file mode 100644 index 000000000..ed30edac1 --- /dev/null +++ b/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DataSystemComponentsTest.java @@ -0,0 +1,181 @@ +package com.launchdarkly.sdk.android; + +import com.launchdarkly.logging.LDLogger; +import com.launchdarkly.sdk.LDContext; +import com.launchdarkly.sdk.android.interfaces.ServiceEndpoints; +import com.launchdarkly.sdk.android.subsystems.FDv2SourceResult; +import com.launchdarkly.sdk.android.subsystems.HttpConfiguration; +import com.launchdarkly.sdk.android.subsystems.Synchronizer; +import com.launchdarkly.sdk.fdv2.Selector; +import com.launchdarkly.testhelpers.httptest.Handlers; +import com.launchdarkly.testhelpers.httptest.HttpServer; +import com.launchdarkly.testhelpers.httptest.RequestInfo; + +import org.junit.After; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.junit.rules.Timeout; + +import java.util.Collections; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * Tests the request wiring of the data source builder implementations in + * {@link DataSystemComponents}: which HTTP method, path, and body each FDv2 + * component and the FDv1 fallback synchronizer use for a given HTTP configuration. + */ +public class DataSystemComponentsTest { + + @Rule + public Timeout globalTimeout = Timeout.seconds(10); + + @Rule + public TemporaryFolder cacheDir = new TemporaryFolder(); + + private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(2); + + private static final LDContext CONTEXT = LDContext.create("test-context-key"); + private static final LDLogger LOGGER = LDLogger.none(); + + // A valid FDv2 polling response that produces a changeset when processed + private static final String VALID_POLL_RESPONSE_JSON = + "{\"events\":[" + + "{\"event\":\"server-intent\",\"data\":{\"payloads\":[{\"id\":\"p1\",\"target\":100,\"intentCode\":\"xfer-full\",\"reason\":\"\"}]}}," + + "{\"event\":\"payload-transferred\",\"data\":{\"state\":\"(p:p1:100)\",\"version\":100}}" + + "]}"; + + // A valid FDv1 polling response (flag key to flag object map) + private static final String VALID_FDV1_JSON = + "{\"flag1\":{\"key\":\"flag1\",\"version\":1,\"value\":true}}"; + + @After + public void tearDown() { + executor.shutdownNow(); + } + + private static HttpConfiguration httpConfig(boolean useReport, boolean usePost) { + return new HttpConfiguration(10_000, Collections.emptyMap(), null, useReport, usePost); + } + + private DataSourceBuildInputsInternal makeInputs(HttpServer server, HttpConfiguration http) { + ServiceEndpoints endpoints = new ServiceEndpoints( + server.getUri(), server.getUri(), server.getUri()); + return new DataSourceBuildInputsInternal( + CONTEXT, endpoints, http, false, + () -> Selector.EMPTY, executor, cacheDir.getRoot(), LOGGER, null); + } + + @Test + public void pollingSynchronizerSendsPostWhenUsePostEnabled() throws Exception { + try (HttpServer server = HttpServer.start(Handlers.bodyJson(VALID_POLL_RESPONSE_JSON))) { + Synchronizer sync = new DataSystemComponents.PollingSynchronizerBuilderImpl() + .build(makeInputs(server, httpConfig(false, true))); + try { + sync.next().get(5, TimeUnit.SECONDS); + + RequestInfo req = server.getRecorder().requireRequest(); + assertEquals("POST", req.getMethod()); + assertEquals("/sdk/poll/eval", req.getPath()); + assertNotNull("body should contain the serialized context", req.getBody()); + assertTrue("body should contain the context key", + req.getBody().contains("test-context-key")); + } finally { + sync.close(); + } + } + } + + @Test + public void pollingSynchronizerSendsGetWhenOnlyUseReportEnabled() throws Exception { + // useReport has no effect on FDv2 components; the request stays GET + try (HttpServer server = HttpServer.start(Handlers.bodyJson(VALID_POLL_RESPONSE_JSON))) { + Synchronizer sync = new DataSystemComponents.PollingSynchronizerBuilderImpl() + .build(makeInputs(server, httpConfig(true, false))); + try { + sync.next().get(5, TimeUnit.SECONDS); + + RequestInfo req = server.getRecorder().requireRequest(); + assertEquals("GET", req.getMethod()); + assertTrue("path should use the GET endpoint with a context segment", + req.getPath().startsWith("/sdk/poll/eval/")); + assertTrue("path should contain the base64 context", + req.getPath().contains(LDUtil.urlSafeBase64(CONTEXT))); + } finally { + sync.close(); + } + } + } + + @Test + public void streamingSynchronizerSendsPostWhenUsePostEnabled() throws Exception { + String serverIntent = "event: server-intent\ndata: {\"payloads\":[{\"id\":\"p1\",\"target\":100,\"intentCode\":\"xfer-full\",\"reason\":\"\"}]}"; + String payloadTransferred = "event: payload-transferred\ndata: {\"state\":\"(p:p1:100)\",\"version\":100}"; + + try (HttpServer server = HttpServer.start(Handlers.all( + Handlers.SSE.start(), + Handlers.SSE.event(serverIntent), + Handlers.SSE.event(payloadTransferred), + Handlers.SSE.leaveOpen()))) { + Synchronizer sync = new DataSystemComponents.StreamingSynchronizerBuilderImpl() + .build(makeInputs(server, httpConfig(false, true))); + try { + FDv2SourceResult result = sync.next().get(5, TimeUnit.SECONDS); + assertNotNull(result); + + RequestInfo req = server.getRecorder().requireRequest(); + assertEquals("POST", req.getMethod()); + assertEquals("/sdk/stream/eval", req.getPath()); + assertNotNull("body should contain the serialized context", req.getBody()); + assertTrue("body should contain the context key", + req.getBody().contains("test-context-key")); + } finally { + sync.close(); + } + } + } + + @Test + public void fdv1FallbackSynchronizerSendsReportWhenUsePostEnabled() throws Exception { + try (HttpServer server = HttpServer.start(Handlers.bodyJson(VALID_FDV1_JSON))) { + Synchronizer sync = new DataSystemComponents.FDv1PollingSynchronizerBuilderImpl() + .build(makeInputs(server, httpConfig(false, true))); + try { + sync.next().get(5, TimeUnit.SECONDS); + + RequestInfo req = server.getRecorder().requireRequest(); + assertEquals("REPORT", req.getMethod()); + assertEquals("/msdk/evalx/context", req.getPath()); + assertNotNull("body should contain the serialized context", req.getBody()); + assertTrue("body should contain the context key", + req.getBody().contains("test-context-key")); + } finally { + sync.close(); + } + } + } + + @Test + public void fdv1FallbackSynchronizerSendsGetByDefault() throws Exception { + try (HttpServer server = HttpServer.start(Handlers.bodyJson(VALID_FDV1_JSON))) { + Synchronizer sync = new DataSystemComponents.FDv1PollingSynchronizerBuilderImpl() + .build(makeInputs(server, httpConfig(false, false))); + try { + sync.next().get(5, TimeUnit.SECONDS); + + RequestInfo req = server.getRecorder().requireRequest(); + assertEquals("GET", req.getMethod()); + assertTrue("path should use the FDv1 GET endpoint with a context segment", + req.getPath().startsWith("/msdk/evalx/contexts/")); + } finally { + sync.close(); + } + } + } +} diff --git a/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DefaultFDv2RequestorTest.java b/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DefaultFDv2RequestorTest.java index a724ea87e..1d649ec17 100644 --- a/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DefaultFDv2RequestorTest.java +++ b/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DefaultFDv2RequestorTest.java @@ -37,7 +37,7 @@ public class DefaultFDv2RequestorTest { private static final LDContext CONTEXT = LDContext.create("test-context-key"); // Bogus paths used by tests — deliberately not the real production paths. private static final String GET_REQUEST_PATH = "/fake-poll-get"; - private static final String REPORT_REQUEST_PATH = "/fake-poll-report"; + private static final String POST_REQUEST_PATH = "/fake-poll-post"; private static final LDLogger LOGGER = LDLogger.none(); private static HttpProperties httpProperties() { @@ -49,14 +49,14 @@ private static HttpProperties httpProperties() { null, null); } - private static DefaultFDv2Requestor makeRequestor(HttpServer server, boolean useReport, boolean evaluationReasons, String payloadFilter) { + private static DefaultFDv2Requestor makeRequestor(HttpServer server, boolean usePost, boolean evaluationReasons, String payloadFilter) { return new DefaultFDv2Requestor( CONTEXT, server.getUri(), GET_REQUEST_PATH, - REPORT_REQUEST_PATH, + POST_REQUEST_PATH, httpProperties(), - useReport, + usePost, evaluationReasons, payloadFilter, LOGGER); @@ -358,7 +358,7 @@ public void baseUriCanHaveContextPath() throws Exception { CONTEXT, uri, GET_REQUEST_PATH, - REPORT_REQUEST_PATH, + POST_REQUEST_PATH, httpProperties(), false, false, @@ -506,16 +506,16 @@ public void evaluationReasonsAddedToRequest() throws Exception { } @Test - public void useReportMethod() throws Exception { + public void usePostMethod() throws Exception { try (HttpServer server = HttpServer.start(Handlers.bodyJson(EMPTY_EVENTS_JSON))) { try (DefaultFDv2Requestor requestor = makeRequestor(server, true, false, null)) { requestor.poll(Selector.EMPTY).get(5, TimeUnit.SECONDS); RequestInfo req = server.getRecorder().requireRequest(); - assertEquals("REPORT", req.getMethod()); - // Context should be in the request body, not the URL path - assertTrue("path should use REPORT path without context segment", - req.getPath().startsWith(REPORT_REQUEST_PATH)); + assertEquals("POST", req.getMethod()); + // Context goes in the request body, not the URL path + assertTrue("path should use POST path without context segment", + req.getPath().startsWith(POST_REQUEST_PATH)); assertFalse("path should not contain GET context segment", req.getPath().startsWith(GET_REQUEST_PATH)); assertNotNull("body should contain serialized context", req.getBody()); @@ -526,23 +526,23 @@ public void useReportMethod() throws Exception { } @Test - public void useReportMethodDoesNotUseEtag() throws Exception { - // ETag caching is disabled for REPORT requests since the context is in the body + public void usePostMethodDoesNotUseEtag() throws Exception { + // ETag caching only runs for GET requests, where the context is in the URL Handler etagResp = Handlers.all( Handlers.header("ETag", "some-etag"), Handlers.bodyJson(EMPTY_EVENTS_JSON)); try (HttpServer server = HttpServer.start(etagResp)) { try (DefaultFDv2Requestor requestor = makeRequestor(server, true, false, null)) { - // First REPORT request — server returns an ETag, but it should not be cached + // First POST request; the server returns an ETag, which is not cached requestor.poll(Selector.EMPTY).get(5, TimeUnit.SECONDS); RequestInfo req1 = server.getRecorder().requireRequest(); - assertNull("REPORT request should not send If-None-Match", req1.getHeader("If-None-Match")); + assertNull("POST request should not send If-None-Match", req1.getHeader("If-None-Match")); - // Second REPORT request — still no If-None-Match because ETag was never stored + // Second POST request; still no If-None-Match because the ETag was never stored requestor.poll(Selector.EMPTY).get(5, TimeUnit.SECONDS); RequestInfo req2 = server.getRecorder().requireRequest(); - assertNull("REPORT request should never send If-None-Match", req2.getHeader("If-None-Match")); + assertNull("POST request should never send If-None-Match", req2.getHeader("If-None-Match")); } } } @@ -551,7 +551,7 @@ public void useReportMethodDoesNotUseEtag() throws Exception { public void http400LogsProguardWarning() throws Exception { try (HttpServer server = HttpServer.start(Handlers.status(400))) { try (DefaultFDv2Requestor requestor = new DefaultFDv2Requestor( - CONTEXT, server.getUri(), GET_REQUEST_PATH, REPORT_REQUEST_PATH, + CONTEXT, server.getUri(), GET_REQUEST_PATH, POST_REQUEST_PATH, httpProperties(), false, false, null, logging.logger)) { Future future = requestor.poll(Selector.EMPTY); @@ -569,7 +569,7 @@ public void http400LogsProguardWarning() throws Exception { public void networkFailureThrowsException() throws Exception { try (DefaultFDv2Requestor requestor = new DefaultFDv2Requestor( CONTEXT, URI.create("http://localhost:1"), - GET_REQUEST_PATH, REPORT_REQUEST_PATH, + GET_REQUEST_PATH, POST_REQUEST_PATH, httpProperties(), false, false, null, LOGGER)) { requestor.poll(Selector.EMPTY).get(5, TimeUnit.SECONDS); } diff --git a/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/FDv2DataSourceBuilderTest.java b/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/FDv2DataSourceBuilderTest.java index a2044ab77..1993eddea 100644 --- a/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/FDv2DataSourceBuilderTest.java +++ b/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/FDv2DataSourceBuilderTest.java @@ -36,9 +36,12 @@ public class FDv2DataSourceBuilderTest { public LogCaptureRule logging = new LogCaptureRule(); private ClientContext makeClientContext() { + return makeClientContext(new HttpConfiguration(10_000, Collections.emptyMap(), null, false)); + } + + private ClientContext makeClientContext(HttpConfiguration http) { LDConfig config = new LDConfig.Builder(AutoEnvAttributes.Disabled).build(); MockComponents.MockDataSourceUpdateSink sink = new MockComponents.MockDataSourceUpdateSink(); - HttpConfiguration http = new HttpConfiguration(10_000, Collections.emptyMap(), null, false); ClientContext base = new ClientContext( "mobile-key", ENV_REPORTER, @@ -342,4 +345,34 @@ public void setActiveMode_notInTable_throws() { assertTrue(e.getMessage().contains("not found in mode table")); } } + + // ---- useReport warning when the data system is configured ---- + + private long useReportWarnCount() { + return logging.logCapture.getMessageStrings().stream() + .filter(m -> m.contains("WARN") && m.contains("useReport")) + .count(); + } + + @Test + public void build_withUseReport_logsWarningOnce() { + HttpConfiguration http = new HttpConfiguration( + 10_000, Collections.emptyMap(), null, true, false); + FDv2DataSourceBuilder builder = new FDv2DataSourceBuilder(); + // build runs once per connection mode switch; the warning logs only once + builder.build(makeClientContext(http)); + builder.build(makeClientContext(http)); + builder.close(); + + assertEquals(1, useReportWarnCount()); + } + + @Test + public void build_withoutUseReport_logsNoWarning() { + FDv2DataSourceBuilder builder = new FDv2DataSourceBuilder(); + builder.build(makeClientContext()); + builder.close(); + + assertEquals(0, useReportWarnCount()); + } } diff --git a/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/FDv2StreamingSynchronizerTest.java b/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/FDv2StreamingSynchronizerTest.java index 9aa3891d9..17937c138 100644 --- a/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/FDv2StreamingSynchronizerTest.java +++ b/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/FDv2StreamingSynchronizerTest.java @@ -92,10 +92,10 @@ private FDv2StreamingSynchronizer makeSynchronizer( private FDv2StreamingSynchronizer makeSynchronizer( URI streamBaseUri, - boolean evaluationReasons, boolean useReport) { + boolean evaluationReasons, boolean usePost) { return new FDv2StreamingSynchronizer( CONTEXT, EMPTY_SELECTOR_SOURCE, streamBaseUri, STREAM_PATH, - null, 100, evaluationReasons, useReport, + null, 100, evaluationReasons, usePost, httpProperties(), executor, LOGGER, null); } @@ -1038,7 +1038,7 @@ public void evaluationReasonsAddedToStreamUrl() throws Exception { Handlers.SSE.leaveOpen()))) { FDv2StreamingSynchronizer sync = makeSynchronizer(server.getUri(), - true /* evaluationReasons */, false); + true /* evaluationReasons */, false /* usePost */); sync.next().get(5, TimeUnit.SECONDS); @@ -1051,7 +1051,7 @@ public void evaluationReasonsAddedToStreamUrl() throws Exception { } @Test - public void useReportMethodForStreamRequest() throws Exception { + public void usePostMethodForStreamRequest() throws Exception { String serverIntent = makeEvent("server-intent", "{\"payloads\":[{\"id\":\"payload-1\",\"target\":100,\"intentCode\":\"xfer-full\",\"reason\":\"payload-missing\"}]}"); String payloadTransferred = makeEvent("payload-transferred", "{\"state\":\"(p:payload-1:100)\",\"version\":100}"); @@ -1062,16 +1062,16 @@ public void useReportMethodForStreamRequest() throws Exception { Handlers.SSE.leaveOpen()))) { FDv2StreamingSynchronizer sync = makeSynchronizer(server.getUri(), - false, true /* useReport */); + false, true /* usePost */); Future resultFuture = sync.next(); FDv2SourceResult result = resultFuture.get(5, TimeUnit.SECONDS); assertEquals(SourceResultType.CHANGE_SET, result.getResultType()); RequestInfo request = server.getRecorder().requireRequest(); - assertEquals("REPORT", request.getMethod()); - // With REPORT the context goes in the body, not the URL path - assertFalse("path should not contain base64 context segment when using REPORT", + assertEquals("POST", request.getMethod()); + // With POST the context goes in the body, not the URL path + assertFalse("path should not contain base64 context segment when using POST", request.getPath().contains(LDUtil.urlSafeBase64(CONTEXT))); assertNotNull("body should contain serialized context", request.getBody()); assertTrue("body should contain context key", diff --git a/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/HttpConfigurationBuilderTest.java b/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/HttpConfigurationBuilderTest.java index d9b20495f..a4c64dd4d 100644 --- a/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/HttpConfigurationBuilderTest.java +++ b/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/HttpConfigurationBuilderTest.java @@ -11,6 +11,8 @@ import static com.launchdarkly.sdk.android.integrations.HttpConfigurationBuilder.DEFAULT_CONNECT_TIMEOUT_MILLIS; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; public class HttpConfigurationBuilderTest { private static final String MOBILE_KEY = "mobile-key"; @@ -49,6 +51,20 @@ public void testConnectTimeout() { assertEquals(999, hc.getConnectTimeoutMillis()); } + @Test + public void testUsePostDefaultsToFalse() { + HttpConfiguration hc = Components.httpConfiguration().build(BASIC_CONTEXT); + assertFalse(hc.shouldUsePost()); + } + + @Test + public void testUsePost() { + HttpConfiguration hc = Components.httpConfiguration() + .usePost(true) + .build(BASIC_CONTEXT); + assertTrue(hc.shouldUsePost()); + } + @Test public void testWrapperNameOnly() { HttpConfiguration hc = Components.httpConfiguration() diff --git a/testharness-suppressions-fdv2.txt b/testharness-suppressions-fdv2.txt index 5e53af750..ceb41bc53 100644 --- a/testharness-suppressions-fdv2.txt +++ b/testharness-suppressions-fdv2.txt @@ -1 +1,4 @@ -streaming/fdv2/fallback to FDv1 handling \ No newline at end of file +streaming/fdv2/fallback to FDv1 handling +events/feature events/single-kind anonymous context redacts all attributes +events/feature events/multi-kind with anonymous context redacts attributes appropriately +events/context properties/single-kind, allAttributesPrivate, slash-prefixed attribute name From 5b238d1f24ce9cb6e92613ad77354d66d688fa3a Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 2 Nov 2026 10:00:50 -0500 Subject: [PATCH 2/5] chore(main): release 5.18.0 (#416) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit :robot: I have created a release *beep* *boop* --- ## [5.18.0](https://github.com/launchdarkly/android-client-sdk/compare/5.17.0...5.18.0) (2026-10-30) ### Features * add support for `usePost` option for FDv2 ([#411](https://github.com/launchdarkly/android-client-sdk/issues/411)) ([d5049ae](https://github.com/launchdarkly/android-client-sdk/commit/d5049aeae84ac10c86563e14c28acc5e9aeeaabd)) --- This PR was generated with [Release Please](https://github.com/googleapis/release-please). See [documentation](https://github.com/googleapis/release-please#release-please). --- > [!NOTE] > **Overview** > **Release 5.18.0** — version-only changes from Release Please: bumps the package version from **5.17.0** to **5.18.0** in `.release-please-manifest.json` and `gradle.properties`, and adds a matching **CHANGELOG** section dated 2026-10-30. > > The new changelog entry records the headline feature shipped in this release: **FDv2 `usePost` support** ([#411]), allowing clients to send context in the POST body instead of on the query string when configured. > > Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 3229755254fca3848334abb55405aa656e0f3228. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot). Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- .release-please-manifest.json | 2 +- CHANGELOG.md | 7 +++++++ gradle.properties | 2 +- 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 7443ba284..78b1d065f 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "5.17.0" + ".": "5.18.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index f0058a5bb..d1123bee9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ All notable changes to the LaunchDarkly Android SDK will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org). +## [5.18.0](https://github.com/launchdarkly/android-client-sdk/compare/5.17.0...5.18.0) (2026-10-30) + + +### Features + +* add support for `usePost` option for FDv2 ([#411](https://github.com/launchdarkly/android-client-sdk/issues/411)) ([d5049ae](https://github.com/launchdarkly/android-client-sdk/commit/d5049aeae84ac10c86563e14c28acc5e9aeeaabd)) + ## [5.17.0](https://github.com/launchdarkly/android-client-sdk/compare/5.16.1...5.17.0) (2026-10-15) diff --git a/gradle.properties b/gradle.properties index cc586b5c4..b25b51ec5 100644 --- a/gradle.properties +++ b/gradle.properties @@ -18,7 +18,7 @@ # org.gradle.parallel=true #x-release-please-start-version -version=5.17.0 +version=5.18.0 #x-release-please-end sonatypeUsername= From b1dd7134616c528598aa19552e44298c09ddf49e Mon Sep 17 00:00:00 2001 From: Andrey Belonogov Date: Wed, 4 Nov 2026 18:03:44 -0800 Subject: [PATCH 3/5] feat: add payloadFilter option to request a filtered environment Co-authored-by: Cursor --- .../launchdarkly/sdktest/Representations.java | 2 + .../launchdarkly/sdktest/SdkClientEntity.java | 6 ++ .../com/launchdarkly/sdktest/TestService.java | 4 +- .../DataSourceBuildInputsInternal.java | 13 ++- .../sdk/android/DataSystemComponents.java | 9 +- .../sdk/android/FDv2DataSourceBuilder.java | 3 +- .../android/FDv2StreamingSynchronizer.java | 6 +- .../sdk/android/HttpFeatureFlagFetcher.java | 7 ++ .../launchdarkly/sdk/android/LDConfig.java | 49 +++++++++++ .../com/launchdarkly/sdk/android/LDUtil.java | 12 +++ .../sdk/android/StreamingDataSource.java | 4 +- .../DataSourceBuildInputsInternalTest.java | 2 +- .../sdk/android/DataSystemComponentsTest.java | 80 +++++++++++++++++- .../FDv2StreamingSynchronizerTest.java | 40 ++++++++- .../sdk/android/LDConfigTest.java | 43 ++++++++++ .../sdk/android/StreamingDataSourceTest.java | 83 ++++++++++++++++++- 16 files changed, 350 insertions(+), 13 deletions(-) diff --git a/contract-tests/src/main/java/com/launchdarkly/sdktest/Representations.java b/contract-tests/src/main/java/com/launchdarkly/sdktest/Representations.java index 5c94b5806..f53488fcc 100644 --- a/contract-tests/src/main/java/com/launchdarkly/sdktest/Representations.java +++ b/contract-tests/src/main/java/com/launchdarkly/sdktest/Representations.java @@ -45,11 +45,13 @@ public static class SdkConfigParams { public static class SdkConfigStreamParams { String baseUri; Long initialRetryDelayMs; + String filter; } public static class SdkConfigPollParams { String baseUri; Long pollIntervalMs; + String filter; } public static class SdkConfigEventParams { diff --git a/contract-tests/src/main/java/com/launchdarkly/sdktest/SdkClientEntity.java b/contract-tests/src/main/java/com/launchdarkly/sdktest/SdkClientEntity.java index 2056d47e2..52e6ce2f9 100644 --- a/contract-tests/src/main/java/com/launchdarkly/sdktest/SdkClientEntity.java +++ b/contract-tests/src/main/java/com/launchdarkly/sdktest/SdkClientEntity.java @@ -327,6 +327,12 @@ private LDConfig buildSdkConfig(SdkConfigParams params, LDLogAdapter logAdapter, builder.events(eventsBuilder); } + if (params.streaming != null && params.streaming.filter != null) { + builder.payloadFilter(params.streaming.filter); + } else if (params.polling != null && params.polling.filter != null) { + builder.payloadFilter(params.polling.filter); + } + builder.evaluationReasons(params.clientSide.evaluationReasons); builder.http( Components.httpConfiguration() diff --git a/contract-tests/src/main/java/com/launchdarkly/sdktest/TestService.java b/contract-tests/src/main/java/com/launchdarkly/sdktest/TestService.java index 246388bc7..cfbda370c 100644 --- a/contract-tests/src/main/java/com/launchdarkly/sdktest/TestService.java +++ b/contract-tests/src/main/java/com/launchdarkly/sdktest/TestService.java @@ -46,7 +46,9 @@ public class TestService extends NanoHTTPD { "client-event-source-http-errors", "retry-conformance-fdv1-streaming", "retry-conformance-fdv1-polling", - "client-use-post" + "client-use-post", + "filtering", + "filtering-strict" }; private static final String MIME_JSON = "application/json"; static final Gson gson = new GsonBuilder() diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DataSourceBuildInputsInternal.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DataSourceBuildInputsInternal.java index 1299859b5..7dfb5fd69 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DataSourceBuildInputsInternal.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DataSourceBuildInputsInternal.java @@ -30,6 +30,9 @@ final class DataSourceBuildInputsInternal extends DataSourceBuildInputs { @Nullable private final PersistentDataStoreWrapper.ReadOnlyPerEnvironmentData perEnvironmentData; + @Nullable + private final String payloadFilter; + DataSourceBuildInputsInternal( LDContext evaluationContext, ServiceEndpoints serviceEndpoints, @@ -39,11 +42,13 @@ final class DataSourceBuildInputsInternal extends DataSourceBuildInputs { ScheduledExecutorService sharedExecutor, @NonNull File cacheDir, LDLogger baseLogger, - @Nullable PersistentDataStoreWrapper.ReadOnlyPerEnvironmentData perEnvironmentData + @Nullable PersistentDataStoreWrapper.ReadOnlyPerEnvironmentData perEnvironmentData, + @Nullable String payloadFilter ) { super(evaluationContext, serviceEndpoints, http, evaluationReasons, selectorSource, sharedExecutor, cacheDir, baseLogger); this.perEnvironmentData = perEnvironmentData; + this.payloadFilter = payloadFilter; } /** @@ -64,6 +69,7 @@ static DataSourceBuildInputsInternal get(DataSourceBuildInputs inputs) { inputs.getSharedExecutor(), inputs.getCacheDir(), inputs.getBaseLogger(), + null, null ); } @@ -72,4 +78,9 @@ static DataSourceBuildInputsInternal get(DataSourceBuildInputs inputs) { PersistentDataStoreWrapper.ReadOnlyPerEnvironmentData getPerEnvironmentDataIfAvailable() { return perEnvironmentData; } + + @Nullable + String getPayloadFilter() { + return payloadFilter; + } } diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DataSystemComponents.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DataSystemComponents.java index 7e6c5ec1d..2c98ea945 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DataSystemComponents.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DataSystemComponents.java @@ -141,7 +141,9 @@ public Synchronizer build(DataSourceBuildInputs inputs) { StandardEndpoints.FDV2_STREAMING_REQUEST_BASE_PATH, requestor, initialReconnectDelayMillis, - inputs.isEvaluationReasons(), inputs.getHttp().shouldUsePost(), + inputs.isEvaluationReasons(), + DataSourceBuildInputsInternal.get(inputs).getPayloadFilter(), + inputs.getHttp().shouldUsePost(), httpProps, inputs.getSharedExecutor(), inputs.getBaseLogger(), null); } @@ -165,6 +167,7 @@ public Synchronizer build(DataSourceBuildInputs inputs) { FeatureFetcher fetcher = new HttpFeatureFlagFetcher( inputs.getServiceEndpoints().getPollingBaseUri(), inputs.isEvaluationReasons(), + DataSourceBuildInputsInternal.get(inputs).getPayloadFilter(), inputs.getHttp().shouldUsePost(), LDUtil.makeHttpProperties(inputs.getHttp()), inputs.getCacheDir(), @@ -366,6 +369,8 @@ private static FDv2Requestor makePollingRequestor(DataSourceBuildInputs inputs, StandardEndpoints.FDV2_POLLING_REQUEST_GET_BASE_PATH, StandardEndpoints.FDV2_POLLING_REQUEST_POST_BASE_PATH, httpProps, inputs.getHttp().shouldUsePost(), - inputs.isEvaluationReasons(), null, inputs.getBaseLogger()); + inputs.isEvaluationReasons(), + DataSourceBuildInputsInternal.get(inputs).getPayloadFilter(), + inputs.getBaseLogger()); } } diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/FDv2DataSourceBuilder.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/FDv2DataSourceBuilder.java index 2fdfc1037..a1c2ead46 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/FDv2DataSourceBuilder.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/FDv2DataSourceBuilder.java @@ -174,7 +174,8 @@ private DataSourceBuildInputsInternal makeInputs(ClientContext clientContext) { sharedExecutor, impl.getPlatformState().getCacheDir(), clientContext.getBaseLogger(), - impl.getPerEnvironmentDataIfAvailable() + impl.getPerEnvironmentDataIfAvailable(), + LDUtil.payloadFilter(clientContext) ); } diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/FDv2StreamingSynchronizer.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/FDv2StreamingSynchronizer.java index c44e0f71d..237443d8d 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/FDv2StreamingSynchronizer.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/FDv2StreamingSynchronizer.java @@ -67,6 +67,7 @@ final class FDv2StreamingSynchronizer implements Synchronizer { @Nullable private final FDv2Requestor requestor; private final boolean evaluationReasons; + private final String payloadFilter; private final int initialReconnectDelayMillis; @Nullable private final DiagnosticStore diagnosticStore; @@ -92,6 +93,7 @@ final class FDv2StreamingSynchronizer implements Synchronizer { * @param requestor optional requestor for handling ping events via poll; may be null * @param initialReconnectDelayMillis delay before reconnecting after an error, in milliseconds * @param evaluationReasons true to request evaluation reasons in the stream + * @param payloadFilter optional payload filter key; sent as {@code filter} query param * @param usePost true to send the context in the request body via HTTP POST * @param httpProperties HTTP configuration for the stream request * @param executor executor used to run the streaming loop on a background @@ -107,6 +109,7 @@ final class FDv2StreamingSynchronizer implements Synchronizer { @Nullable FDv2Requestor requestor, int initialReconnectDelayMillis, boolean evaluationReasons, + @Nullable String payloadFilter, boolean usePost, @NonNull HttpProperties httpProperties, @NonNull Executor executor, @@ -120,6 +123,7 @@ final class FDv2StreamingSynchronizer implements Synchronizer { this.requestor = requestor; this.initialReconnectDelayMillis = initialReconnectDelayMillis; this.evaluationReasons = evaluationReasons; + this.payloadFilter = payloadFilter; this.usePost = usePost; this.httpProperties = httpProperties; this.executor = executor; @@ -250,7 +254,7 @@ private URI getStreamUri() { if (evaluationReasons) { uri = HttpHelpers.addQueryParam(uri, "withReasons", "true"); } - return uri; + return LDUtil.withPayloadFilter(uri, payloadFilter); } private void recordStreamInit(boolean failed) { diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/HttpFeatureFlagFetcher.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/HttpFeatureFlagFetcher.java index 782807dc1..c4607dc10 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/HttpFeatureFlagFetcher.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/HttpFeatureFlagFetcher.java @@ -1,6 +1,7 @@ package com.launchdarkly.sdk.android; import androidx.annotation.NonNull; +import androidx.annotation.Nullable; import com.launchdarkly.logging.LDLogger; import com.launchdarkly.sdk.LDContext; @@ -32,6 +33,7 @@ class HttpFeatureFlagFetcher implements FeatureFetcher { private final URI pollUri; private final boolean evaluationReasons; + private final String payloadFilter; private final boolean useReport; private final HttpProperties httpProperties; private final OkHttpClient client; @@ -43,6 +45,7 @@ class HttpFeatureFlagFetcher implements FeatureFetcher { this( clientContext.getServiceEndpoints().getPollingBaseUri(), clientContext.isEvaluationReasons(), + LDUtil.payloadFilter(clientContext), clientContext.getHttp().isUseReport(), LDUtil.makeHttpProperties(clientContext), ClientContextImpl.get(clientContext).getPlatformState().getCacheDir(), @@ -53,6 +56,7 @@ class HttpFeatureFlagFetcher implements FeatureFetcher { HttpFeatureFlagFetcher( @NonNull URI pollUri, boolean evaluationReasons, + @Nullable String payloadFilter, boolean useReport, @NonNull HttpProperties httpProperties, @NonNull File platformCacheDir, @@ -60,6 +64,7 @@ class HttpFeatureFlagFetcher implements FeatureFetcher { ) { this.pollUri = pollUri; this.evaluationReasons = evaluationReasons; + this.payloadFilter = payloadFilter; this.useReport = useReport; this.httpProperties = httpProperties; this.logger = logger; @@ -159,6 +164,7 @@ private Request getDefaultRequest(LDContext ldContext) throws IOException { if (evaluationReasons) { uri = URI.create(uri.toString() + "?withReasons=true"); } + uri = LDUtil.withPayloadFilter(uri, payloadFilter); logger.debug("Attempting to fetch Feature flags using uri: {}", uri); return new Request.Builder().url(uri.toURL()) .headers(httpProperties.toHeadersBuilder().build()) @@ -170,6 +176,7 @@ private Request getReportRequest(LDContext ldContext) throws IOException { if (evaluationReasons) { uri = URI.create(uri.toString() + "?withReasons=true"); } + uri = LDUtil.withPayloadFilter(uri, payloadFilter); logger.debug("Attempting to report user using uri: {}", uri); String contextJson = JsonSerialization.serialize(ldContext); RequestBody reportBody = RequestBody.create(contextJson, JSON); diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDConfig.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDConfig.java index 9056f9dcc..b2f4d5ac8 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDConfig.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDConfig.java @@ -4,6 +4,7 @@ import com.launchdarkly.logging.LDLogAdapter; import com.launchdarkly.logging.LDLogLevel; +import com.launchdarkly.logging.LDLogger; import com.launchdarkly.logging.Logs; import com.launchdarkly.sdk.ContextKind; import com.launchdarkly.sdk.LDContext; @@ -28,6 +29,7 @@ import java.util.HashSet; import java.util.Map; import java.util.Set; +import java.util.regex.Pattern; import okhttp3.MediaType; @@ -64,6 +66,7 @@ public class LDConfig { static final int DEFAULT_MAX_CACHED_CONTEXTS = 5; static final int DEFAULT_CONNECTION_TIMEOUT_MILLIS = 10_000; // 10 seconds + private static final Pattern PAYLOAD_FILTER_PATTERN = Pattern.compile("^[a-zA-Z0-9][._\\-a-zA-Z0-9]*$"); private final Map mobileKeys; @@ -88,6 +91,7 @@ public class LDConfig { private final int maxCachedContexts; private final boolean offline; private final long connectionModeStateDebounceMs; + private final String payloadFilter; private final PersistentDataStore persistentDataStore; // configurable for testing only LDConfig(Map mobileKeys, @@ -107,6 +111,7 @@ public class LDConfig { boolean generateAnonymousKeys, boolean autoEnvAttributes, long connectionModeStateDebounceMs, + String payloadFilter, PersistentDataStore persistentDataStore, LDLogAdapter logAdapter, String loggerName) { @@ -127,6 +132,7 @@ public class LDConfig { this.generateAnonymousKeys = generateAnonymousKeys; this.autoEnvAttributes = autoEnvAttributes; this.connectionModeStateDebounceMs = connectionModeStateDebounceMs; + this.payloadFilter = payloadFilter; this.persistentDataStore = persistentDataStore; this.logAdapter = logAdapter; this.loggerName = loggerName; @@ -181,6 +187,14 @@ public boolean isEvaluationReasons() { return evaluationReasons; } + /** + * @return the payload filter key, or null if no valid filter was configured + * @see Builder#payloadFilter(String) + */ + public String getPayloadFilter() { + return payloadFilter; + } + /** * @return true if opting out of diagnostics, false otherwise */ @@ -278,6 +292,8 @@ public enum AutoEnvAttributes { private long connectionModeStateDebounceMs = StateDebounceManager.DEFAULT_DEBOUNCE_MS; + private String payloadFilter = null; + private LDLogAdapter logAdapter = defaultLogAdapter(); private String loggerName = LDPackageConsts.DEFAULT_LOGGER_NAME; private LDLogLevel logLevel = null; @@ -594,6 +610,25 @@ public Builder evaluationReasons(boolean evaluationReasons) { return this; } + /** + * Sets the key of a payload filter to apply to flag data requests. + *

+ * Payload filters are defined per project in LaunchDarkly. When a filter key is set, the SDK + * adds it as the {@code filter} query parameter to its streaming and polling requests, and + * LaunchDarkly limits the flags it sends to the ones selected by that filter. + *

+ * The key must contain only alphanumeric characters, periods, underscores, and hyphens, and + * must start with an alphanumeric character. If the key is invalid, the SDK logs an error and + * requests the full environment instead. + * + * @param payloadFilter the payload filter key, or null for no filter + * @return the builder + */ + public Builder payloadFilter(String payloadFilter) { + this.payloadFilter = payloadFilter; + return this; + } + /** * Set to true to opt out of sending diagnostics data. * @@ -774,6 +809,19 @@ private static LDLogAdapter defaultLogAdapter() { return LDTimberLogging.adapter(); } + private String validPayloadFilterOrNull(LDLogAdapter actualLogAdapter) { + if (payloadFilter == null || payloadFilter.isEmpty()) { + return null; + } + if (!PAYLOAD_FILTER_PATTERN.matcher(payloadFilter).matches()) { + LDLogger.withAdapter(actualLogAdapter, loggerName).error( + "Payload filter \"{}\" is invalid; the full environment will be requested instead", + payloadFilter); + return null; + } + return payloadFilter; + } + /** * Returns the configured {@link LDConfig} object. * @return the configuration @@ -840,6 +888,7 @@ public LDConfig build() { generateAnonymousKeys, autoEnvAttributes, connectionModeStateDebounceMs, + validPayloadFilterOrNull(actualLogAdapter), persistentDataStore, actualLogAdapter, loggerName); diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDUtil.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDUtil.java index 4a77849b2..1ff0fe6f2 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDUtil.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/LDUtil.java @@ -13,9 +13,11 @@ import com.launchdarkly.sdk.android.subsystems.ClientContext; import com.launchdarkly.sdk.android.subsystems.HttpConfiguration; import com.launchdarkly.sdk.internal.http.HeadersTransformer; +import com.launchdarkly.sdk.internal.http.HttpHelpers; import com.launchdarkly.sdk.internal.http.HttpProperties; import com.launchdarkly.sdk.json.JsonSerialization; +import java.net.URI; import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -179,6 +181,16 @@ static String urlSafeBase64(LDContext context) { Base64.URL_SAFE + Base64.NO_WRAP); } + @Nullable + static String payloadFilter(ClientContext clientContext) { + LDConfig config = clientContext.getConfig(); + return config == null ? null : config.getPayloadFilter(); + } + + static URI withPayloadFilter(URI uri, @Nullable String payloadFilter) { + return payloadFilter == null ? uri : HttpHelpers.addQueryParam(uri, "filter", payloadFilter); + } + static HttpProperties makeHttpProperties(ClientContext clientContext) { return makeHttpProperties(clientContext.getHttp()); } diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/StreamingDataSource.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/StreamingDataSource.java index 3bf6ab92b..fc67c6e95 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/StreamingDataSource.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/StreamingDataSource.java @@ -62,6 +62,7 @@ final class StreamingDataSource implements DataSource { private final LDContext context; private final HttpProperties httpProperties; private final boolean evaluationReasons; + private final String payloadFilter; final int initialReconnectDelayMillis; // visible for testing private final RetryDelayStrategy normalRetryDelay; private final RetryDelayStrategy extendedRetryDelay; @@ -106,6 +107,7 @@ final class StreamingDataSource implements DataSource { this.streamUri = clientContext.getServiceEndpoints().getStreamingBaseUri(); this.httpProperties = LDUtil.makeHttpProperties(clientContext); this.evaluationReasons = clientContext.isEvaluationReasons(); + this.payloadFilter = LDUtil.payloadFilter(clientContext); this.useReport = clientContext.getHttp().isUseReport(); this.initialReconnectDelayMillis = initialReconnectDelayMillis; this.normalRetryDelay = RetryDelayStrategy.defaultStrategy() @@ -230,7 +232,7 @@ private URI getUri(@Nullable LDContext context) { uri = URI.create(uri.toString() + "?withReasons=true"); } - return uri; + return LDUtil.withPayloadFilter(uri, payloadFilter); } @VisibleForTesting diff --git a/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DataSourceBuildInputsInternalTest.java b/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DataSourceBuildInputsInternalTest.java index 6ea149573..b11c40d3c 100644 --- a/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DataSourceBuildInputsInternalTest.java +++ b/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DataSourceBuildInputsInternalTest.java @@ -34,7 +34,7 @@ private static DataSourceBuildInputsInternal makeInternalInputs( return new DataSourceBuildInputsInternal( CONTEXT, null, null, false, () -> Selector.EMPTY, null, CACHE_DIR, - LDLogger.none(), envData + LDLogger.none(), envData, null ); } diff --git a/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DataSystemComponentsTest.java b/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DataSystemComponentsTest.java index ed30edac1..55e2b356b 100644 --- a/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DataSystemComponentsTest.java +++ b/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DataSystemComponentsTest.java @@ -65,11 +65,16 @@ private static HttpConfiguration httpConfig(boolean useReport, boolean usePost) } private DataSourceBuildInputsInternal makeInputs(HttpServer server, HttpConfiguration http) { + return makeInputs(server, http, null); + } + + private DataSourceBuildInputsInternal makeInputs(HttpServer server, HttpConfiguration http, + String payloadFilter) { ServiceEndpoints endpoints = new ServiceEndpoints( server.getUri(), server.getUri(), server.getUri()); return new DataSourceBuildInputsInternal( CONTEXT, endpoints, http, false, - () -> Selector.EMPTY, executor, cacheDir.getRoot(), LOGGER, null); + () -> Selector.EMPTY, executor, cacheDir.getRoot(), LOGGER, null, payloadFilter); } @Test @@ -178,4 +183,77 @@ public void fdv1FallbackSynchronizerSendsGetByDefault() throws Exception { } } } + + @Test + public void pollingSynchronizerSendsPayloadFilter() throws Exception { + try (HttpServer server = HttpServer.start(Handlers.bodyJson(VALID_POLL_RESPONSE_JSON))) { + Synchronizer sync = new DataSystemComponents.PollingSynchronizerBuilderImpl() + .build(makeInputs(server, httpConfig(false, false), "mobile-flags")); + try { + sync.next().get(5, TimeUnit.SECONDS); + + RequestInfo req = server.getRecorder().requireRequest(); + assertEquals("?filter=mobile-flags", req.getQuery()); + } finally { + sync.close(); + } + } + } + + @Test + public void streamingSynchronizerSendsPayloadFilter() throws Exception { + String serverIntent = "event: server-intent\ndata: {\"payloads\":[{\"id\":\"p1\",\"target\":100,\"intentCode\":\"xfer-full\",\"reason\":\"\"}]}"; + String payloadTransferred = "event: payload-transferred\ndata: {\"state\":\"(p:p1:100)\",\"version\":100}"; + + try (HttpServer server = HttpServer.start(Handlers.all( + Handlers.SSE.start(), + Handlers.SSE.event(serverIntent), + Handlers.SSE.event(payloadTransferred), + Handlers.SSE.leaveOpen()))) { + Synchronizer sync = new DataSystemComponents.StreamingSynchronizerBuilderImpl() + .build(makeInputs(server, httpConfig(false, false), "mobile-flags")); + try { + sync.next().get(5, TimeUnit.SECONDS); + + RequestInfo req = server.getRecorder().requireRequest(); + assertEquals("?filter=mobile-flags", req.getQuery()); + } finally { + sync.close(); + } + } + } + + @Test + public void fdv1FallbackSynchronizerSendsPayloadFilterWithGet() throws Exception { + try (HttpServer server = HttpServer.start(Handlers.bodyJson(VALID_FDV1_JSON))) { + Synchronizer sync = new DataSystemComponents.FDv1PollingSynchronizerBuilderImpl() + .build(makeInputs(server, httpConfig(false, false), "mobile-flags")); + try { + sync.next().get(5, TimeUnit.SECONDS); + + RequestInfo req = server.getRecorder().requireRequest(); + assertEquals("GET", req.getMethod()); + assertEquals("?filter=mobile-flags", req.getQuery()); + } finally { + sync.close(); + } + } + } + + @Test + public void fdv1FallbackSynchronizerSendsPayloadFilterWithReport() throws Exception { + try (HttpServer server = HttpServer.start(Handlers.bodyJson(VALID_FDV1_JSON))) { + Synchronizer sync = new DataSystemComponents.FDv1PollingSynchronizerBuilderImpl() + .build(makeInputs(server, httpConfig(false, true), "mobile-flags")); + try { + sync.next().get(5, TimeUnit.SECONDS); + + RequestInfo req = server.getRecorder().requireRequest(); + assertEquals("REPORT", req.getMethod()); + assertEquals("?filter=mobile-flags", req.getQuery()); + } finally { + sync.close(); + } + } + } } diff --git a/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/FDv2StreamingSynchronizerTest.java b/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/FDv2StreamingSynchronizerTest.java index 17937c138..7646033ab 100644 --- a/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/FDv2StreamingSynchronizerTest.java +++ b/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/FDv2StreamingSynchronizerTest.java @@ -83,6 +83,7 @@ private FDv2StreamingSynchronizer makeSynchronizer( null, 100, false, + null, false, httpProperties(), executor, @@ -93,9 +94,15 @@ private FDv2StreamingSynchronizer makeSynchronizer( private FDv2StreamingSynchronizer makeSynchronizer( URI streamBaseUri, boolean evaluationReasons, boolean usePost) { + return makeSynchronizer(streamBaseUri, evaluationReasons, usePost, null); + } + + private FDv2StreamingSynchronizer makeSynchronizer( + URI streamBaseUri, + boolean evaluationReasons, boolean usePost, String payloadFilter) { return new FDv2StreamingSynchronizer( CONTEXT, EMPTY_SELECTOR_SOURCE, streamBaseUri, STREAM_PATH, - null, 100, evaluationReasons, usePost, + null, 100, evaluationReasons, payloadFilter, usePost, httpProperties(), executor, LOGGER, null); } @@ -1050,6 +1057,33 @@ public void evaluationReasonsAddedToStreamUrl() throws Exception { } } + @Test + public void payloadFilterAddedToStreamUrl() throws Exception { + String serverIntent = makeEvent("server-intent", "{\"payloads\":[{\"id\":\"payload-1\",\"target\":100,\"intentCode\":\"xfer-full\",\"reason\":\"payload-missing\"}]}"); + String payloadTransferred = makeEvent("payload-transferred", "{\"state\":\"(p:payload-1:100)\",\"version\":100}"); + + try (HttpServer server = HttpServer.start(Handlers.all( + Handlers.SSE.start(), + Handlers.SSE.event(serverIntent), + Handlers.SSE.event(payloadTransferred), + Handlers.SSE.leaveOpen()))) { + + FDv2StreamingSynchronizer sync = makeSynchronizer(server.getUri(), + true /* evaluationReasons */, false /* usePost */, "mobile-flags"); + + sync.next().get(5, TimeUnit.SECONDS); + + RequestInfo request = server.getRecorder().requireRequest(); + assertNotNull(request.getQuery()); + assertTrue("query should contain filter=mobile-flags", + request.getQuery().contains("filter=mobile-flags")); + assertTrue("query should still contain withReasons=true", + request.getQuery().contains("withReasons=true")); + + sync.close(); + } + } + @Test public void usePostMethodForStreamRequest() throws Exception { String serverIntent = makeEvent("server-intent", "{\"payloads\":[{\"id\":\"payload-1\",\"target\":100,\"intentCode\":\"xfer-full\",\"reason\":\"payload-missing\"}]}"); @@ -1131,7 +1165,7 @@ public void pingEventWithRequestorTriggersPoll() throws Exception { FDv2StreamingSynchronizer sync = new FDv2StreamingSynchronizer( CONTEXT, EMPTY_SELECTOR_SOURCE, streamServer.getUri(), STREAM_PATH, - requestor, 100, false, false, + requestor, 100, false, null, false, httpProperties(), executor, LOGGER, null); try { @@ -1171,7 +1205,7 @@ public void close() { FDv2StreamingSynchronizer sync = new FDv2StreamingSynchronizer( CONTEXT, EMPTY_SELECTOR_SOURCE, URI.create("http://localhost:9999/"), STREAM_PATH, - trackingRequestor, 100, false, false, + trackingRequestor, 100, false, null, false, httpProperties(), executor, LOGGER, null); assertFalse(requestorClosed.get()); diff --git a/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/LDConfigTest.java b/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/LDConfigTest.java index 5db264615..c44d9206b 100644 --- a/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/LDConfigTest.java +++ b/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/LDConfigTest.java @@ -49,6 +49,49 @@ public void testBuilderEvaluationReasons() { assertTrue(config.isEvaluationReasons()); } + @Test + public void testBuilderPayloadFilterDefaultsToNull() { + LDConfig config = new LDConfig.Builder(AutoEnvAttributes.Disabled).build(); + + assertNull(config.getPayloadFilter()); + } + + @Test + public void testBuilderPayloadFilterValid() { + LDConfig config = new LDConfig.Builder(AutoEnvAttributes.Disabled) + .logAdapter(logging.logAdapter) + .payloadFilter("mobile.flags_v2-a") + .build(); + + assertEquals("mobile.flags_v2-a", config.getPayloadFilter()); + logging.assertNoErrorsLogged(); + } + + @Test + public void testBuilderPayloadFilterEmptyIsIgnored() { + LDConfig config = new LDConfig.Builder(AutoEnvAttributes.Disabled) + .logAdapter(logging.logAdapter) + .payloadFilter("") + .build(); + + assertNull(config.getPayloadFilter()); + logging.assertNoErrorsLogged(); + } + + @Test + public void testBuilderPayloadFilterInvalidIsDroppedWithError() { + String[] invalidKeys = {"-starts-with-hyphen", ".starts-with-period", "has space", "has/slash", "has&"}; + for (String key : invalidKeys) { + LDConfig config = new LDConfig.Builder(AutoEnvAttributes.Disabled) + .logAdapter(logging.logAdapter) + .payloadFilter(key) + .build(); + + assertNull(key, config.getPayloadFilter()); + logging.assertErrorLogged("Payload filter \"" + key + "\" is invalid"); + } + } + @Test public void testBuilderDiagnosticOptOut() { LDConfig config = new LDConfig.Builder(AutoEnvAttributes.Disabled).diagnosticOptOut(true).build(); diff --git a/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/StreamingDataSourceTest.java b/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/StreamingDataSourceTest.java index c0be925de..d68aa0e99 100644 --- a/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/StreamingDataSourceTest.java +++ b/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/StreamingDataSourceTest.java @@ -159,9 +159,18 @@ private ClientContext makeDataSourceClientContext( URI streamBaseUri, MockComponents.MockDataSourceUpdateSink sink, boolean evaluationReasons, boolean useReport) { + return makeDataSourceClientContext(streamBaseUri, sink, evaluationReasons, useReport, null); + } + + private ClientContext makeDataSourceClientContext( + URI streamBaseUri, + MockComponents.MockDataSourceUpdateSink sink, + boolean evaluationReasons, boolean useReport, String payloadFilter) { LDConfig.Builder configBuilder = new LDConfig.Builder(AutoEnvAttributes.Disabled) + .logAdapter(logging.logAdapter) .serviceEndpoints(Components.serviceEndpoints().streaming(streamBaseUri)) - .evaluationReasons(evaluationReasons); + .evaluationReasons(evaluationReasons) + .payloadFilter(payloadFilter); if (useReport) { configBuilder.http(Components.httpConfiguration().useReport(true)); } @@ -592,6 +601,78 @@ public void startSendsRequestWithReasonsWhenEnabled() throws Exception { } } + @Test + public void startSendsPayloadFilterWithGet() throws Exception { + String putEvent = makeSseEvent("put", VALID_PUT_JSON); + + try (HttpServer server = HttpServer.start(Handlers.all( + Handlers.SSE.start(), + Handlers.SSE.event(putEvent), + Handlers.SSE.leaveOpen()))) { + + ClientContext clientContext = makeDataSourceClientContext( + server.getUri(), dataSourceUpdateSink, true, false, "mobile-flags"); + StreamingDataSource sds = (StreamingDataSource) Components.streamingDataSource() + .build(clientContext); + TrackingCallback callback = new TrackingCallback(); + startDataSource(sds, callback); + + assertNotNull(callback.awaitSuccess()); + + RequestInfo request = server.getRecorder().requireRequest(); + assertEquals("GET", request.getMethod()); + assertEquals("?withReasons=true&filter=mobile-flags", request.getQuery()); + } + } + + @Test + public void startSendsPayloadFilterWithReport() throws Exception { + String putEvent = makeSseEvent("put", VALID_PUT_JSON); + + try (HttpServer server = HttpServer.start(Handlers.all( + Handlers.SSE.start(), + Handlers.SSE.event(putEvent), + Handlers.SSE.leaveOpen()))) { + + ClientContext clientContext = makeDataSourceClientContext( + server.getUri(), dataSourceUpdateSink, false, true, "mobile-flags"); + StreamingDataSource sds = (StreamingDataSource) Components.streamingDataSource() + .build(clientContext); + TrackingCallback callback = new TrackingCallback(); + startDataSource(sds, callback); + + assertNotNull(callback.awaitSuccess()); + + RequestInfo request = server.getRecorder().requireRequest(); + assertEquals("REPORT", request.getMethod()); + assertEquals("?filter=mobile-flags", request.getQuery()); + } + } + + @Test + public void startOmitsInvalidPayloadFilter() throws Exception { + String putEvent = makeSseEvent("put", VALID_PUT_JSON); + + try (HttpServer server = HttpServer.start(Handlers.all( + Handlers.SSE.start(), + Handlers.SSE.event(putEvent), + Handlers.SSE.leaveOpen()))) { + + ClientContext clientContext = makeDataSourceClientContext( + server.getUri(), dataSourceUpdateSink, false, false, "not valid"); + StreamingDataSource sds = (StreamingDataSource) Components.streamingDataSource() + .build(clientContext); + TrackingCallback callback = new TrackingCallback(); + startDataSource(sds, callback); + + assertNotNull(callback.awaitSuccess()); + + RequestInfo request = server.getRecorder().requireRequest(); + assertTrue("query should not contain a filter", + request.getQuery() == null || !request.getQuery().contains("filter=")); + } + } + @Test public void startSendsRequestWithoutReasonsWhenDisabled() throws Exception { String putEvent = makeSseEvent("put", VALID_PUT_JSON); From 186c9f1e80663f7ee5e2cf337f5f7eb837f3cfbe Mon Sep 17 00:00:00 2001 From: Andrey Belonogov Date: Tue, 10 Nov 2026 17:46:02 -0800 Subject: [PATCH 4/5] Start a second environment in the test app when a second key is set launchdarkly.secondaryMobileKey in local.properties adds a secondary mobile key to the client's LDConfig. An Env spinner then chooses which environment's client the buttons, the connection status, Post 20 MB and the event storage view use. Flush, Offline, Identify and the persistence restart still reach both, as the SDK applies them to every environment. Co-authored-by: Cursor --- test-app/README.md | 18 ++ test-app/build.gradle | 2 + .../sdk/testapp/MainActivity.java | 233 ++++++++++++++---- .../src/main/res/layout/activity_main.xml | 19 ++ 4 files changed, 222 insertions(+), 50 deletions(-) diff --git a/test-app/README.md b/test-app/README.md index 33897f22d..534b41a2b 100644 --- a/test-app/README.md +++ b/test-app/README.md @@ -11,6 +11,24 @@ launchdarkly.environment=production Set `launchdarkly.environment=staging` to use LaunchDarkly's staging endpoints. +## Two environments + +Add a second key to start a second environment alongside the first, from the same `LDConfig` +through `secondaryMobileKeys`: + +```properties +launchdarkly.secondaryMobileKey=mob-... +``` + +An **Env** spinner then appears next to **Persistence**, and chooses which environment's client the +buttons use: the evaluations, **Track**, the kill, crash, over-refresh and fill-batches buttons, +**Post 20 MB**, the connection status and the event storage view, which shows that environment's own +directory. The choice is saved, so the launch that answers a kill button shows the same environment. + +**Flush**, **Offline**, **Identify** and the restart a persistence change makes reach both +environments whichever is selected, because the SDK applies `flush`, `setOffline`, `setOnline`, +`identify` and `close` to every environment it started. + ## Event-loss scenarios Create a boolean flag named `kill-flag`, or enter another flag key in the app. Tap diff --git a/test-app/build.gradle b/test-app/build.gradle index a5274dc3b..0da334ed7 100644 --- a/test-app/build.gradle +++ b/test-app/build.gradle @@ -27,6 +27,8 @@ android { buildConfigField("String", "MOBILE_KEY", "\"${localProperties.getProperty('launchdarkly.mobileKey', '')}\"") + buildConfigField("String", "SECONDARY_MOBILE_KEY", + "\"${localProperties.getProperty('launchdarkly.secondaryMobileKey', '')}\"") buildConfigField("String", "LD_ENVIRONMENT", "\"${localProperties.getProperty('launchdarkly.environment', 'production')}\"") } diff --git a/test-app/src/main/java/com/launchdarkly/sdk/testapp/MainActivity.java b/test-app/src/main/java/com/launchdarkly/sdk/testapp/MainActivity.java index bc57b223b..6f390658a 100644 --- a/test-app/src/main/java/com/launchdarkly/sdk/testapp/MainActivity.java +++ b/test-app/src/main/java/com/launchdarkly/sdk/testapp/MainActivity.java @@ -37,6 +37,7 @@ import com.launchdarkly.sdk.android.LDConfig.Builder.AutoEnvAttributes; import com.launchdarkly.sdk.android.LDFailure; import com.launchdarkly.sdk.android.LDStatusListener; +import com.launchdarkly.sdk.android.LaunchDarklyException; import com.launchdarkly.sdk.android.integrations.DedupingHook; import com.launchdarkly.sdk.android.integrations.EventPersistence; import com.launchdarkly.sdk.android.integrations.EventProcessorBuilder; @@ -48,8 +49,11 @@ import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.Date; +import java.util.List; import java.util.Locale; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; @@ -72,8 +76,12 @@ public class MainActivity extends AppCompatActivity { private static final String PREFERENCES_NAME = "LaunchDarkly-testapp"; private static final String PERSISTENCE_PREFERENCE = "eventPersistence"; + private static final String ENVIRONMENT_PREFERENCE = "environment"; private static final EventPersistence DEFAULT_PERSISTENCE = EventPersistence.IMMEDIATE; + /** What {@link LDClient#getForMobileKey} knows the second environment by. */ + private static final String SECONDARY_ENVIRONMENT = "secondary"; + /** * The default of {@code LDConfig.Builder#events} capacity. Past this the event store is full until a * flush empties it, so every further full event is dropped. @@ -96,8 +104,13 @@ public class MainActivity extends AppCompatActivity { /** Seven, seven and six: three batches, the last of them not full. */ private static final int LARGE_EVENTS = 20; - /** Null while a persistence change restarts the client, which makes every button a no-op meanwhile. */ + /** + * The primary environment's client, which {@link LDClient#init} returns. Null while a persistence + * change restarts the client, which makes every button a no-op meanwhile. + */ private volatile LDClient ldClient; + /** Whether the buttons act on the secondary environment rather than the primary one. */ + private volatile boolean secondarySelected; private EventPersistence eventPersistence; private LDStatusListener ldStatusListener; private LDAllFlagsListener allFlagsListener; @@ -114,15 +127,61 @@ private static boolean isStaging() { return "staging".equalsIgnoreCase(BuildConfig.LD_ENVIRONMENT); } + /** The SDK refuses a secondary key equal to the primary one, so that counts as no second environment. */ + private static boolean hasSecondaryEnvironment() { + return !BuildConfig.SECONDARY_MOBILE_KEY.isEmpty() + && !BuildConfig.SECONDARY_MOBILE_KEY.equals(BuildConfig.MOBILE_KEY); + } + + private String selectedMobileKey() { + return secondarySelected ? BuildConfig.SECONDARY_MOBILE_KEY : BuildConfig.MOBILE_KEY; + } + + /** + * The selected environment's client, or null while a restart is under way. Some calls reach every + * environment whichever client they are made on: flush, setOffline, setOnline, identify and close. + */ + private LDClient client() { + LDClient primary = ldClient; + if (primary == null || !secondarySelected) { + return primary; + } + return secondaryClient(); + } + + private static LDClient secondaryClient() { + try { + return LDClient.getForMobileKey(SECONDARY_ENVIRONMENT); + } catch (LaunchDarklyException e) { + return null; + } + } + + /** The primary environment's client and, where there is one, the secondary one's. */ + private static List environmentClients(LDClient primary) { + List clients = new ArrayList<>(); + clients.add(primary); + LDClient secondary = hasSecondaryEnvironment() ? secondaryClient() : null; + if (secondary != null) { + clients.add(secondary); + } + return clients; + } + private void updateDedupeStatus() { if (Looper.myLooper() != MainActivity.this.getMainLooper()) { new Handler(MainActivity.this.getMainLooper()).post(this::updateDedupeStatus); return; } + String environment = isStaging() ? "staging" : "production"; + if (hasSecondaryEnvironment()) { + environment += secondarySelected ? " · secondary" : " · primary"; + environment += " (Flush, Offline, Identify: both)"; + } String result = String.format(Locale.US, "Environment: %s\nEvaluations requested: %d\n%s\n%s", - isStaging() ? "staging" : "production", + environment, evaluationsRequested.get(), fastHook.status(FAST_DEDUPE_WINDOW_MILLIS), slowHook.status(SLOW_DEDUPE_WINDOW_MILLIS)); @@ -166,6 +225,7 @@ public void onCreate(Bundle savedInstanceState) { setupOversizedPostButton(); setupOfflineSwitch(); setupPersistenceSpinner(); + setupEnvironmentSpinner(); // Rescues the events for "Eval+Crash now" and cannot run for "Eval+Kill now", which is what // makes the pair worth pressing. LDCrashHandler.install(2, TimeUnit.SECONDS); @@ -201,7 +261,7 @@ protected void onPause() { private void setupStorageInspector() { TextView status = findViewById(R.id.storage_status); - storageInspector = new EventStorageInspector(this, status, BuildConfig.MOBILE_KEY); + storageInspector = new EventStorageInspector(this, status, selectedMobileKey()); status.setOnLongClickListener(v -> { String path = storageInspector.directory().getPath(); ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); @@ -234,6 +294,11 @@ private LDClient startClient(EventPersistence persistence, boolean offline) { .addHook(new DedupingHook(slowHook, SLOW_DEDUPE_WINDOW_MILLIS)) ); + if (hasSecondaryEnvironment()) { + configBuilder.secondaryMobileKeys( + Collections.singletonMap(SECONDARY_ENVIRONMENT, BuildConfig.SECONDARY_MOBILE_KEY)); + } + if (isStaging()) { configBuilder.serviceEndpoints( Components.serviceEndpoints() @@ -251,9 +316,15 @@ private LDClient startClient(EventPersistence persistence, boolean offline) { LDClient client = LDClient.init(this.getApplication(), ldConfig, context, INIT_WAIT_SECONDS); Timber.i("client started with event persistence %s", persistence); - updateStatusString(client.getConnectionInformation()); - client.registerStatusListener(ldStatusListener); - client.registerAllFlagsListener(allFlagsListener); + LDClient selected = secondarySelected ? secondaryClient() : client; + if (selected != null) { + updateStatusString(selected.getConnectionInformation()); + } + // Every environment, so switching shows the other's changes without registering again. + for (LDClient each : environmentClients(client)) { + each.registerStatusListener(ldStatusListener); + each.registerAllFlagsListener(allFlagsListener); + } return client; } @@ -302,6 +373,54 @@ private static EventPersistence parsePersistence(String name) { return DEFAULT_PERSISTENCE; } + /** + * Shown only when local.properties gives a second key, in which case the client starts both + * environments and this chooses which one the buttons, the connection status and the event storage + * view use. Saved like the persistence choice, so the launch that answers a kill button shows the + * environment it was pressed in. + */ + private void setupEnvironmentSpinner() { + if (!hasSecondaryEnvironment()) { + return; + } + final SharedPreferences preferences = getSharedPreferences(PREFERENCES_NAME, MODE_PRIVATE); + secondarySelected = SECONDARY_ENVIRONMENT.equals(preferences.getString(ENVIRONMENT_PREFERENCE, null)); + + final Spinner spinner = findViewById(R.id.environment_spinner); + findViewById(R.id.environment_label).setVisibility(View.VISIBLE); + spinner.setVisibility(View.VISIBLE); + ArrayAdapter adapter = new ArrayAdapter<>(this, + android.R.layout.simple_spinner_item, new String[] {"Primary", "Secondary"}); + adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + spinner.setAdapter(adapter); + spinner.setSelection(secondarySelected ? 1 : 0, false); + + spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + boolean secondary = position == 1; + if (secondary == secondarySelected) { + return; + } + secondarySelected = secondary; + preferences.edit() + .putString(ENVIRONMENT_PREFERENCE, secondary ? SECONDARY_ENVIRONMENT : "primary") + .apply(); + refreshConnectionStatus(); + updateDedupeStatus(); + if (storageInspector != null) { + storageInspector.stopWatching(); + setupStorageInspector(); + storageInspector.startWatching(); + } + } + + @Override + public void onNothingSelected(AdapterView parent) { + } + }); + } + /** * Off the main thread, because closing waits on the event store and starting waits for flags. The * spinner stays disabled until it is done, so restarts never overlap. @@ -320,9 +439,12 @@ private void restartClient(final Spinner spinner, final EventPersistence persist spinner.setEnabled(false); new Thread(() -> { if (previous != null) { - previous.unregisterStatusListener(ldStatusListener); - previous.unregisterAllFlagsListener(allFlagsListener); + for (LDClient each : environmentClients(previous)) { + each.unregisterStatusListener(ldStatusListener); + each.unregisterAllFlagsListener(allFlagsListener); + } try { + // Closes every environment. previous.close(); } catch (IOException e) { Timber.w(e, "closing the client for a persistence change"); @@ -346,11 +468,16 @@ private void restartClient(final Spinner spinner, final EventPersistence persist }, "testapp-restart-client").start(); } + private void refreshConnectionStatus() { + doSafeClientAction(client -> updateStatusString(client.getConnectionInformation())); + } + + /** Registered on every environment, so each shows the selected environment's status, whichever changed. */ private void setupListeners() { ldStatusListener = new LDStatusListener() { @Override public void onConnectionModeChanged(final ConnectionInformation connectionInformation) { - updateStatusString(connectionInformation); + refreshConnectionStatus(); } @Override @@ -358,7 +485,7 @@ public void onInternalFailure(final LDFailure ldFailure) { new Handler(MainActivity.this.getMainLooper()).post(() -> { Toast.makeText(MainActivity.this, ldFailure.toString(), Toast.LENGTH_SHORT).show(); }); - MainActivity.this.doSafeClientAction(() -> updateStatusString(ldClient.getConnectionInformation())); + refreshConnectionStatus(); } }; @@ -370,7 +497,7 @@ public void onInternalFailure(final LDFailure ldFailure) { } Toast.makeText(MainActivity.this, flags.toString(), Toast.LENGTH_SHORT).show(); }); - MainActivity.this.doSafeClientAction(() -> updateStatusString(ldClient.getConnectionInformation())); + refreshConnectionStatus(); }; } @@ -378,33 +505,36 @@ private void setupFlushButton() { Button flushButton = findViewById(R.id.flush_button); flushButton.setOnClickListener(v -> { Timber.i("flush onClick"); - MainActivity.this.doSafeClientAction(() -> ldClient.flush()); + MainActivity.this.doSafeClientAction(LDClient::flush); }); } private interface LDClientAction { - void call(); + void call(LDClient client); } + /** Calls the action with the selected environment's client, if there is one. */ private void doSafeClientAction(LDClientAction function) { - if (ldClient != null) { - function.call(); + LDClient client = client(); + if (client != null) { + function.call(client); } } private interface LDClientGet { - V get(); + V get(LDClient client); } private V doSafeClientGet(LDClientGet function) { - return ldClient != null ? function.get() : null; + LDClient client = client(); + return client != null ? function.get(client) : null; } private void setupTrackButton() { Button trackButton = findViewById(R.id.track_button); trackButton.setOnClickListener(v -> { Timber.i("track onClick"); - MainActivity.this.doSafeClientAction(() -> ldClient.track("Android event name")); + MainActivity.this.doSafeClientAction(client -> client.track("Android event name")); }); } @@ -421,16 +551,17 @@ private String flagKeyToKillOver() { * Records the pair whose survival is in question: an evaluation, which is the exposure, and a * track, standing in for the error an application reports just before it dies. * - *

Returns false when there is no client, in which case nothing was recorded and ending the - * process would demonstrate nothing. + *

Returns the client they were recorded on, or null when there is none, in which case nothing was + * recorded and ending the process would demonstrate nothing. */ - private boolean recordExposureAndError(String flagKey) { - if (ldClient == null) { - return false; + private LDClient recordExposureAndError(String flagKey) { + LDClient client = client(); + if (client == null) { + return null; } - ldClient.boolVariation(flagKey, false); - ldClient.track("$ld:telemetry:error"); - return true; + client.boolVariation(flagKey, false); + client.track("$ld:telemetry:error"); + return client; } /** @@ -444,10 +575,11 @@ private void setupKillUnsentButton() { killUnsentButton.setOnClickListener(v -> { final String flagKey = flagKeyToKillOver(); Timber.w("eval+track+kill flag=%s", flagKey); - if (!recordExposureAndError(flagKey)) { + LDClient client = recordExposureAndError(flagKey); + if (client == null) { return; } - ldClient.flush(); + client.flush(); new Handler(Looper.getMainLooper()).postDelayed( () -> android.os.Process.killProcess(android.os.Process.myPid()), 5_000); @@ -468,7 +600,7 @@ private void setupKillNowButton() { killNowButton.setOnClickListener(v -> { final String flagKey = flagKeyToKillOver(); Timber.w("eval+track+kill now flag=%s", flagKey); - if (!recordExposureAndError(flagKey)) { + if (recordExposureAndError(flagKey) == null) { return; } android.os.Process.killProcess(android.os.Process.myPid()); @@ -489,7 +621,7 @@ private void setupCrashNowButton() { crashNowButton.setOnClickListener(v -> { final String flagKey = flagKeyToKillOver(); Timber.w("eval+track+crash now flag=%s", flagKey); - if (!recordExposureAndError(flagKey)) { + if (recordExposureAndError(flagKey) == null) { return; } throw new RuntimeException( @@ -512,14 +644,15 @@ private void setupCrashNowButton() { private void setupOverRefreshButton() { Button overRefreshButton = findViewById(R.id.over_refresh_button); overRefreshButton.setOnClickListener(v -> { - if (ldClient == null) { + LDClient client = client(); + if (client == null) { return; } final String flagKey = "trackevents-test"; Timber.w("over-refresh eval flag=%s", flagKey); - double filling = averageMicroseconds(flagKey, EVENT_CAPACITY); - double overCapacity = averageMicroseconds(flagKey, OVER_CAPACITY_EVALUATIONS); + double filling = averageMicroseconds(client, flagKey, EVENT_CAPACITY); + double overCapacity = averageMicroseconds(client, flagKey, OVER_CAPACITY_EVALUATIONS); String result = String.format(Locale.US, "Over-refresh %s\n%d filling: %.0f \u00b5s/eval\n%d over capacity: %.0f \u00b5s/eval", @@ -540,14 +673,15 @@ private void setupOverRefreshButton() { private void setupFillBatchesButton() { Button fillBatchesButton = findViewById(R.id.fill_batches_button); fillBatchesButton.setOnClickListener(v -> { - if (ldClient == null) { + LDClient client = client(); + if (client == null) { return; } char[] filler = new char[LARGE_EVENT_DATA_CHARS]; Arrays.fill(filler, 'x'); String padding = new String(filler); for (int i = 1; i <= LARGE_EVENTS; i++) { - ldClient.trackData("fill-batches", LDValue.buildObject() + client.trackData("fill-batches", LDValue.buildObject() .put("index", i) .put("of", LARGE_EVENTS) .put("padding", padding) @@ -626,9 +760,10 @@ private void setupOversizedPostButton() { final Handler main = new Handler(getMainLooper()); final String eventsBaseUri = isStaging() ? "https://mobile." + STAGING_DOMAIN : "https://mobile.launchdarkly.com"; + final String mobileKey = selectedMobileKey(); status.setText("Posting 20 MB…"); new Thread(() -> { - String report = OversizedPostProbe.run(BuildConfig.MOBILE_KEY, eventsBaseUri); + String report = OversizedPostProbe.run(mobileKey, eventsBaseUri); Timber.w("oversized post\n%s", report); main.post(() -> { postButton.setEnabled(true); @@ -680,10 +815,10 @@ private void showResults(final String title, final String results) { /** * @return the mean wall time, in microseconds, of {@code count} evaluations of the flag */ - private double averageMicroseconds(String flagKey, int count) { + private static double averageMicroseconds(LDClient client, String flagKey, int count) { long start = System.nanoTime(); for (int i = 0; i < count; i++) { - ldClient.boolVariation(flagKey, false); + client.boolVariation(flagKey, false); } return (System.nanoTime() - start) / 1_000.0 / count; } @@ -699,9 +834,7 @@ private void setupIdentifyButton() { // an unchanged context still demonstrates that the reset happens either way. final String userKey = typedKey.isEmpty() ? DEFAULT_USER_KEY : typedKey; final LDContext updatedContext = LDContext.create(userKey); - MainActivity.this.doSafeClientAction(() -> { - ldClient.identify(updatedContext); - }); + MainActivity.this.doSafeClientAction(client -> client.identify(updatedContext)); MainActivity.this.updateDedupeStatus(); }); } @@ -712,7 +845,7 @@ private Switch offlineSwitch() { private void setupOfflineSwitch() { offlineSwitch().setOnCheckedChangeListener((compoundButton, isChecked) -> - MainActivity.this.doSafeClientAction(isChecked ? () -> ldClient.setOffline() : () -> ldClient.setOnline()) + MainActivity.this.doSafeClientAction(isChecked ? LDClient::setOffline : LDClient::setOnline) ); } @@ -734,31 +867,31 @@ private void setupEval() { String logResult; switch (type) { case "String": - result = MainActivity.this.doSafeClientGet(() -> ldClient.stringVariation(flagKey, "default")); + result = MainActivity.this.doSafeClientGet(client -> client.stringVariation(flagKey, "default")); logResult = result == null ? "no result" : result; Timber.i(logResult); ((TextView) MainActivity.this.findViewById(R.id.result_textView)).setText(result); - MainActivity.this.doSafeClientAction(() -> { - ldClient.registerFeatureFlagListener(flagKey, flagKey1 -> { + MainActivity.this.doSafeClientAction(client -> { + client.registerFeatureFlagListener(flagKey, flagKey1 -> { evaluationsRequested.incrementAndGet(); ((TextView) MainActivity.this.findViewById(R.id.result_textView)) - .setText(ldClient.stringVariation(flagKey1, "default")); + .setText(client.stringVariation(flagKey1, "default")); MainActivity.this.updateDedupeStatus(); }); }); MainActivity.this.updateDedupeStatus(); return; case "Boolean": - result = MainActivity.this.doSafeClientGet(() -> String.valueOf(ldClient.boolVariation(flagKey, false))); + result = MainActivity.this.doSafeClientGet(client -> String.valueOf(client.boolVariation(flagKey, false))); break; case "Integer": - result = MainActivity.this.doSafeClientGet(() -> String.valueOf(ldClient.intVariation(flagKey, 0))); + result = MainActivity.this.doSafeClientGet(client -> String.valueOf(client.intVariation(flagKey, 0))); break; case "Float": - result = MainActivity.this.doSafeClientGet(() -> String.valueOf(ldClient.doubleVariation(flagKey, 0.0))); + result = MainActivity.this.doSafeClientGet(client -> String.valueOf(client.doubleVariation(flagKey, 0.0))); break; case "Value": - result = MainActivity.this.doSafeClientGet(() -> String.valueOf(ldClient.jsonValueVariation(flagKey, null))); + result = MainActivity.this.doSafeClientGet(client -> String.valueOf(client.jsonValueVariation(flagKey, null))); break; default: result = null; diff --git a/test-app/src/main/res/layout/activity_main.xml b/test-app/src/main/res/layout/activity_main.xml index 3f1fb5185..a1a84cd6f 100644 --- a/test-app/src/main/res/layout/activity_main.xml +++ b/test-app/src/main/res/layout/activity_main.xml @@ -71,6 +71,8 @@ + + + +