diff --git a/.changeset/android-v4-major.md b/.changeset/android-v4-major.md index 104bc40b3..302cf21d5 100644 --- a/.changeset/android-v4-major.md +++ b/.changeset/android-v4-major.md @@ -7,11 +7,13 @@ - **Breaking:** remove the deprecated `propertiesSanitizer` config option and the `PostHogPropertiesSanitizer` interface; use `addBeforeSend` instead - **Breaking:** remove the deprecated `evaluationEnvironments` config option; use `evaluationContexts` instead - **Breaking:** remove the deprecated `getFeatureFlagPayload()`; use `getFeatureFlagResult(key, sendFeatureFlagEvent = false)?.payload` instead to keep not sending `$feature_flag_called` +- **Breaking:** remove the `defaultValue` parameter from `getFeatureFlag()`, which returns `null` for a flag with no value or a disabled SDK, so use `getFeatureFlag(key) ?: default` instead; a positional `Boolean` second argument now sets `sendFeatureFlagEvent`, and `$feature_flag_called` no longer reports a fallback from `getFeatureFlag()` or `isFeatureEnabled()` as the flag's value - **Breaking:** remove the deprecated `PostHogSessionReplayConfig.debouncerDelayMs`; use `throttleDelayMs` instead - **Breaking:** return `null` instead of the raw string for a malformed, empty, whitespace-only or lenient-only (unquoted or single-quoted) feature flag payload from `getFeatureFlagResult(key)?.payload`; payloads must be valid JSON (a JSON `null` payload now also reads as `null` instead of the string `"null"`) - **Breaking:** make SDK-internal helpers in the `com.posthog.internal`, `com.posthog.android.internal` and `com.posthog.android.replay.internal` packages non-public - **Breaking:** remove the deprecated `remoteConfig` config option; the SDK now always loads remote config at setup -- **Breaking:** replace `PostHogOnFeatureFlags` with `PostHogFeatureFlagsCallback` in `PostHogConfig.onFeatureFlags` and `reloadFeatureFlags()`; it receives a `PostHogFeatureFlagsLoaded` with the enabled flags, their values, and `errorsLoading` +- **Breaking:** remove `PostHogConfig.onFeatureFlags`; call `PostHog.onFeatureFlags(callback)` before `setup()` instead, which also covers the first load +- **Breaking:** replace `PostHogOnFeatureFlags` with `PostHogFeatureFlagsCallback` in `reloadFeatureFlags()`; it receives a `PostHogFeatureFlagsLoaded` with the enabled flags, their values, and `errorsLoading` - **Breaking:** add the abstract `onFeatureFlags()` method to `PostHogInterface`; classes that implement it must add the method - Add `onFeatureFlags()` to get notified after every feature flags load (on the main thread on Android), returning a `PostHogFeatureFlagsSubscription` you can `unsubscribe()` - See the [3.x to 4.0 migration guide](https://github.com/PostHog/posthog-android/blob/main/docs/migration-3.x-to-4.0.md) for upgrade steps diff --git a/docs/migration-3.x-to-4.0.md b/docs/migration-3.x-to-4.0.md index a6423911a..43835e3a7 100644 --- a/docs/migration-3.x-to-4.0.md +++ b/docs/migration-3.x-to-4.0.md @@ -33,8 +33,10 @@ All of these are compile errors. Calling them from an already-compiled library t | `PostHogConfig.propertiesSanitizer`, `PostHogPropertiesSanitizer` | `addBeforeSend` | | `PostHogConfig.evaluationEnvironments` | `evaluationContexts` | | `getFeatureFlagPayload()`, on the instance and on `PostHog` | `getFeatureFlagResult()` | +| `defaultValue` on `getFeatureFlag()` | `getFeatureFlag(key) ?: default` | | `PostHogSessionReplayConfig.debouncerDelayMs` | `throttleDelayMs` | | `PostHogConfig.remoteConfig` | nothing; remote config always loads | +| `PostHogConfig.onFeatureFlags` | `PostHog.onFeatureFlags()` before `setup()` | | `PostHogOnFeatureFlags` | `PostHogFeatureFlagsCallback` | The constructor parameters of `PostHogConfig` and `PostHogSessionReplayConfig` move up where these were removed. If you pass arguments by position, check them, or switch to named arguments. @@ -94,6 +96,24 @@ val payload = PostHog.getFeatureFlagPayload("checkout", defaultValue = "fallback val payload = PostHog.getFeatureFlagResult("checkout", sendFeatureFlagEvent = false)?.payload ?: "fallback" ``` +### `getFeatureFlag()` default value + +```kotlin +// 3.x +val value = PostHog.getFeatureFlag("checkout", defaultValue = "fallback") + +// 4.0 +val value = PostHog.getFeatureFlag("checkout") ?: "fallback" +``` + +The second parameter is now `sendFeatureFlagEvent`, which affects code that still compiles: + +- `getFeatureFlag("checkout", true)` compiles, but `true` now means `sendFeatureFlagEvent` rather than the default value. +- A disabled SDK now returns `null`, not your default. +- `$feature_flag_called` no longer reports a fallback as the flag's value. `isFeatureEnabled("missing", true)` still returns `true`, but its event reports an empty response. + +Classes that implement `PostHogInterface` update the signature. + ### `debouncerDelayMs` ```kotlin @@ -123,7 +143,7 @@ If you set it to `false`, your app's behavior changes: ## Feature flags callback -`PostHogConfig.onFeatureFlags` and `reloadFeatureFlags()` now take a `PostHogFeatureFlagsCallback`, which receives a `PostHogFeatureFlagsLoaded`: +`PostHogConfig.onFeatureFlags` is removed. Call `PostHog.onFeatureFlags()` before `setup()` instead, which also covers the first load. `reloadFeatureFlags()` now takes a `PostHogFeatureFlagsCallback`. Both callbacks receive a `PostHogFeatureFlagsLoaded`: - `flags`: the keys of the enabled flags - `variants`: their values, either `true` or the variant string @@ -135,14 +155,20 @@ config.onFeatureFlags = PostHogOnFeatureFlags { refreshUi() } -// 4.0 -config.onFeatureFlags = PostHogFeatureFlagsCallback { loaded -> +// 4.0, before PostHogAndroid.setup() +PostHog.onFeatureFlags { loaded -> if (!loaded.errorsLoading) { refreshUi() } } ``` +The listener differs from the removed option in three ways: + +- It runs on the main thread on Android. The option ran on a background thread. +- Bootstrapped flags arrive just after `setup()` is called, not synchronously inside it. +- A reload on a disabled SDK doesn't call listeners. `reloadFeatureFlags(callback)` still gets `errorsLoading = true` in that case. + ```java // 3.x PostHog.Companion.reloadFeatureFlags(() -> refreshUi()); @@ -155,7 +181,7 @@ A Kotlin trailing lambda such as `PostHog.reloadFeatureFlags { refreshUi() }` co `errorsLoading` is `false` when PostHog answers that the project is over its feature flags quota, and the values are the cached flags. It's `true` when no request was made, such as when the device is offline or the distinct ID is blank, and when the SDK is disabled or isn't set up, with no values in that last case. -These callbacks still run on a background thread, or right away on the calling thread when no load is attempted, so switch to the main thread before touching UI. With bootstrapped flags, `PostHogConfig.onFeatureFlags` also runs once on the thread calling `setup()`. +The `reloadFeatureFlags()` callback still runs on a background thread, or right away on the calling thread when no load is attempted, so switch to the main thread before touching UI. ## `PostHogInterface` implementations @@ -216,7 +242,7 @@ The code you end up with after these two migrations compiles, so they're easy to ## New: `onFeatureFlags()` -If you need flag updates outside of `PostHogConfig`, for example from a screen or a library, register a listener you can remove: +`onFeatureFlags()` is now the way to listen for flag loads, for example from a screen or a library. You can remove the listener later: ```kotlin val subscription = PostHog.onFeatureFlags { loaded -> diff --git a/posthog-android/src/test/java/com/posthog/android/PostHogAndroidEventSnapshotsTest.kt b/posthog-android/src/test/java/com/posthog/android/PostHogAndroidEventSnapshotsTest.kt index a29635090..e9912e7dd 100644 --- a/posthog-android/src/test/java/com/posthog/android/PostHogAndroidEventSnapshotsTest.kt +++ b/posthog-android/src/test/java/com/posthog/android/PostHogAndroidEventSnapshotsTest.kt @@ -24,6 +24,7 @@ import java.util.Date import java.util.TimeZone import java.util.UUID import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executor import java.util.concurrent.TimeUnit import java.util.zip.GZIPInputStream import kotlin.test.AfterTest @@ -67,8 +68,10 @@ internal class PostHogAndroidEventSnapshotsTest { fun `batch request and enriched event shapes match snapshot`() { val fixture = createFixture() val flagsLoaded = CountDownLatch(1) - fixture.config.onFeatureFlags = PostHogFeatureFlagsCallback { flagsLoaded.countDown() } val sut = fixture.client + // this test blocks the main thread, where listeners otherwise run + fixture.config.featureFlagsListenerExecutor = Executor { it.run() } + sut.onFeatureFlags { flagsLoaded.countDown() } sut.capture( event = "checkout completed", diff --git a/posthog-android/src/test/java/com/posthog/android/surveys/PostHogSurveysLinkedFlagVariantTest.kt b/posthog-android/src/test/java/com/posthog/android/surveys/PostHogSurveysLinkedFlagVariantTest.kt index 230796ec2..b7512e36d 100644 --- a/posthog-android/src/test/java/com/posthog/android/surveys/PostHogSurveysLinkedFlagVariantTest.kt +++ b/posthog-android/src/test/java/com/posthog/android/surveys/PostHogSurveysLinkedFlagVariantTest.kt @@ -67,7 +67,7 @@ internal class PostHogSurveysLinkedFlagVariantTest( val value = flagValues[it.getArgument(0)] value == true || value is String } - whenever(postHog.getFeatureFlag(any(), anyOrNull(), anyOrNull())).thenAnswer { + whenever(postHog.getFeatureFlag(any(), anyOrNull())).thenAnswer { flagValues[it.getArgument(0)] } val survey = diff --git a/posthog-android/src/test/java/com/posthog/android/surveys/PostHogSurveysSelectionTest.kt b/posthog-android/src/test/java/com/posthog/android/surveys/PostHogSurveysSelectionTest.kt index 626a0bbc0..2b27a1cbc 100644 --- a/posthog-android/src/test/java/com/posthog/android/surveys/PostHogSurveysSelectionTest.kt +++ b/posthog-android/src/test/java/com/posthog/android/surveys/PostHogSurveysSelectionTest.kt @@ -77,7 +77,7 @@ internal class PostHogSurveysSelectionTest { val value = flags[it.getArgument(0)] value == true || value is String } - whenever(postHog.getFeatureFlag(any(), anyOrNull(), anyOrNull())).thenAnswer { flags[it.getArgument(0)] } + whenever(postHog.getFeatureFlag(any(), anyOrNull())).thenAnswer { flags[it.getArgument(0)] } val integration = PostHogSurveysIntegration(context, config) integration.install(postHog) try { diff --git a/posthog-samples/posthog-android-sample/src/main/java/com/posthog/android/sample/MyApp.kt b/posthog-samples/posthog-android-sample/src/main/java/com/posthog/android/sample/MyApp.kt index bfdb0e45e..b1ebd89c4 100644 --- a/posthog-samples/posthog-android-sample/src/main/java/com/posthog/android/sample/MyApp.kt +++ b/posthog-samples/posthog-android-sample/src/main/java/com/posthog/android/sample/MyApp.kt @@ -2,7 +2,6 @@ package com.posthog.android.sample import android.app.Application import android.os.StrictMode -import com.posthog.PostHogFeatureFlagsCallback import com.posthog.android.PostHogAndroid import com.posthog.android.PostHogAndroidConfig @@ -39,7 +38,6 @@ class MyApp : Application() { sessionReplay = true preloadFeatureFlags = true sendFeatureFlagEvent = false - onFeatureFlags = PostHogFeatureFlagsCallback { print("feature flags loaded") } addBeforeSend { event -> if (event.event == "test_event") { null diff --git a/posthog-server/src/test/java/com/posthog/server/PostHogConfigTest.kt b/posthog-server/src/test/java/com/posthog/server/PostHogConfigTest.kt index f77668c76..f63920e87 100644 --- a/posthog-server/src/test/java/com/posthog/server/PostHogConfigTest.kt +++ b/posthog-server/src/test/java/com/posthog/server/PostHogConfigTest.kt @@ -180,7 +180,6 @@ internal class PostHogConfigTest { assertEquals(30, coreConfig.maxBatchSize) assertEquals(45, coreConfig.flushIntervalSeconds) assertEquals(mockEncryption, coreConfig.encryption) - assertNull(coreConfig.onFeatureFlags) } @Test diff --git a/posthog/api/posthog.api b/posthog/api/posthog.api index 162a27452..4c6968839 100644 --- a/posthog/api/posthog.api +++ b/posthog/api/posthog.api @@ -38,7 +38,7 @@ public final class com/posthog/PostHog : com/posthog/PostHogStateless, com/posth public fun getAnonymousId ()Ljava/lang/String; public fun getConfig ()Lcom/posthog/PostHogConfig; public fun getDeviceId ()Ljava/lang/String; - public fun getFeatureFlag (Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Boolean;)Ljava/lang/Object; + public fun getFeatureFlag (Ljava/lang/String;Ljava/lang/Boolean;)Ljava/lang/Object; public fun getFeatureFlagResult (Ljava/lang/String;Ljava/lang/Boolean;)Lcom/posthog/FeatureFlagResult; public fun getLogger ()Lcom/posthog/logs/PostHogLogger; public fun getSessionId ()Ljava/util/UUID; @@ -88,7 +88,7 @@ public final class com/posthog/PostHog$Companion : com/posthog/PostHogInterface public fun getAnonymousId ()Ljava/lang/String; public fun getConfig ()Lcom/posthog/PostHogConfig; public fun getDeviceId ()Ljava/lang/String; - public fun getFeatureFlag (Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Boolean;)Ljava/lang/Object; + public fun getFeatureFlag (Ljava/lang/String;Ljava/lang/Boolean;)Ljava/lang/Object; public fun getFeatureFlagResult (Ljava/lang/String;Ljava/lang/Boolean;)Lcom/posthog/FeatureFlagResult; public fun getLogger ()Lcom/posthog/logs/PostHogLogger; public fun getSessionId ()Ljava/util/UUID; @@ -159,8 +159,8 @@ public class com/posthog/PostHogConfig { public static final field DEFAULT_MAX_QUEUE_SIZE I public static final field DEFAULT_US_ASSETS_HOST Ljava/lang/String; public static final field DEFAULT_US_HOST Ljava/lang/String; - public fun (Ljava/lang/String;Ljava/lang/String;ZZZIZLjava/util/List;ZIIIIIILcom/posthog/PostHogEncryption;Lcom/posthog/PostHogFeatureFlagsCallback;ZLkotlin/jvm/functions/Function1;ZLcom/posthog/PersonProfiles;ZLjava/net/Proxy;Lcom/posthog/surveys/PostHogSurveysConfig;Lcom/posthog/logs/PostHogLogsConfig;Lkotlin/jvm/functions/Function6;Lkotlin/jvm/functions/Function5;Lcom/posthog/errortracking/PostHogErrorTrackingConfig;Ljava/lang/String;Lcom/posthog/PostHogBootstrapConfig;Lkotlin/jvm/functions/Function3;)V - public synthetic fun (Ljava/lang/String;Ljava/lang/String;ZZZIZLjava/util/List;ZIIIIIILcom/posthog/PostHogEncryption;Lcom/posthog/PostHogFeatureFlagsCallback;ZLkotlin/jvm/functions/Function1;ZLcom/posthog/PersonProfiles;ZLjava/net/Proxy;Lcom/posthog/surveys/PostHogSurveysConfig;Lcom/posthog/logs/PostHogLogsConfig;Lkotlin/jvm/functions/Function6;Lkotlin/jvm/functions/Function5;Lcom/posthog/errortracking/PostHogErrorTrackingConfig;Ljava/lang/String;Lcom/posthog/PostHogBootstrapConfig;Lkotlin/jvm/functions/Function3;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun (Ljava/lang/String;Ljava/lang/String;ZZZIZLjava/util/List;ZIIIIIILcom/posthog/PostHogEncryption;ZLkotlin/jvm/functions/Function1;ZLcom/posthog/PersonProfiles;ZLjava/net/Proxy;Lcom/posthog/surveys/PostHogSurveysConfig;Lcom/posthog/logs/PostHogLogsConfig;Lkotlin/jvm/functions/Function6;Lkotlin/jvm/functions/Function5;Lcom/posthog/errortracking/PostHogErrorTrackingConfig;Ljava/lang/String;Lcom/posthog/PostHogBootstrapConfig;Lkotlin/jvm/functions/Function3;)V + public synthetic fun (Ljava/lang/String;Ljava/lang/String;ZZZIZLjava/util/List;ZIIIIIILcom/posthog/PostHogEncryption;ZLkotlin/jvm/functions/Function1;ZLcom/posthog/PersonProfiles;ZLjava/net/Proxy;Lcom/posthog/surveys/PostHogSurveysConfig;Lcom/posthog/logs/PostHogLogsConfig;Lkotlin/jvm/functions/Function6;Lkotlin/jvm/functions/Function5;Lcom/posthog/errortracking/PostHogErrorTrackingConfig;Ljava/lang/String;Lcom/posthog/PostHogBootstrapConfig;Lkotlin/jvm/functions/Function3;ILkotlin/jvm/internal/DefaultConstructorMarker;)V public final fun addBeforeSend (Lcom/posthog/PostHogBeforeSend;)V public final fun addIntegration (Lcom/posthog/PostHogIntegration;)V public final fun getBeforeSendList ()Ljava/util/List; @@ -190,7 +190,6 @@ public class com/posthog/PostHogConfig { public final fun getMaxQueueSize ()I public final fun getMaxRetries ()I public final fun getNetworkStatus ()Lcom/posthog/internal/PostHogNetworkStatus; - public final fun getOnFeatureFlags ()Lcom/posthog/PostHogFeatureFlagsCallback; public final fun getOptOut ()Z public final fun getPersistOptOut ()Z public final fun getPersonProfiles ()Lcom/posthog/PersonProfiles; @@ -242,7 +241,6 @@ public class com/posthog/PostHogConfig { public final fun setMaxQueueSize (I)V public final fun setMaxRetries (I)V public final fun setNetworkStatus (Lcom/posthog/internal/PostHogNetworkStatus;)V - public final fun setOnFeatureFlags (Lcom/posthog/PostHogFeatureFlagsCallback;)V public final fun setOptOut (Z)V public final fun setPersistOptOut (Z)V public final fun setPersonProfiles (Lcom/posthog/PersonProfiles;)V @@ -403,8 +401,8 @@ public abstract interface class com/posthog/PostHogInterface : com/posthog/PostH public abstract fun getAnonymousId ()Ljava/lang/String; public abstract fun getConfig ()Lcom/posthog/PostHogConfig; public abstract fun getDeviceId ()Ljava/lang/String; - public abstract fun getFeatureFlag (Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Boolean;)Ljava/lang/Object; - public static synthetic fun getFeatureFlag$default (Lcom/posthog/PostHogInterface;Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Boolean;ILjava/lang/Object;)Ljava/lang/Object; + public abstract fun getFeatureFlag (Ljava/lang/String;Ljava/lang/Boolean;)Ljava/lang/Object; + public static synthetic fun getFeatureFlag$default (Lcom/posthog/PostHogInterface;Ljava/lang/String;Ljava/lang/Boolean;ILjava/lang/Object;)Ljava/lang/Object; public abstract fun getFeatureFlagResult (Ljava/lang/String;Ljava/lang/Boolean;)Lcom/posthog/FeatureFlagResult; public static synthetic fun getFeatureFlagResult$default (Lcom/posthog/PostHogInterface;Ljava/lang/String;Ljava/lang/Boolean;ILjava/lang/Object;)Lcom/posthog/FeatureFlagResult; public abstract fun getLogger ()Lcom/posthog/logs/PostHogLogger; @@ -449,7 +447,7 @@ public final class com/posthog/PostHogInterface$DefaultImpls { public static synthetic fun captureFeatureView$default (Lcom/posthog/PostHogInterface;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)V public static synthetic fun captureLog$default (Lcom/posthog/PostHogInterface;Ljava/lang/String;Lcom/posthog/logs/PostHogLogSeverity;Ljava/util/Map;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Integer;ILjava/lang/Object;)V public static synthetic fun capturePushNotificationOpened$default (Lcom/posthog/PostHogInterface;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;Ljava/lang/String;ILjava/lang/Object;)V - public static synthetic fun getFeatureFlag$default (Lcom/posthog/PostHogInterface;Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Boolean;ILjava/lang/Object;)Ljava/lang/Object; + public static synthetic fun getFeatureFlag$default (Lcom/posthog/PostHogInterface;Ljava/lang/String;Ljava/lang/Boolean;ILjava/lang/Object;)Ljava/lang/Object; public static synthetic fun getFeatureFlagResult$default (Lcom/posthog/PostHogInterface;Ljava/lang/String;Ljava/lang/Boolean;ILjava/lang/Object;)Lcom/posthog/FeatureFlagResult; public static synthetic fun group$default (Lcom/posthog/PostHogInterface;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;ILjava/lang/Object;)V public static synthetic fun isFeatureEnabled$default (Lcom/posthog/PostHogInterface;Ljava/lang/String;ZLjava/lang/Boolean;ILjava/lang/Object;)Z diff --git a/posthog/src/main/java/com/posthog/PostHog.kt b/posthog/src/main/java/com/posthog/PostHog.kt index 2f3ef881a..de65a0ca2 100644 --- a/posthog/src/main/java/com/posthog/PostHog.kt +++ b/posthog/src/main/java/com/posthog/PostHog.kt @@ -431,8 +431,8 @@ public class PostHog private constructor( super.enabled = true - // Captured before any user callout below (integrations, session hooks, the bootstrap - // config callback), any of which may close() and so supersede setup's flags load. + // Captured before any user callout below (integrations, session hooks), any of + // which may close() and so supersede setup's flags load. val generation = featureFlagsGeneration // Queued before integrations install, so a reload one starts there can't hold the @@ -478,20 +478,16 @@ public class PostHog private constructor( // only because of testing in isolation, this flag is always enabled if (reloadFeatureFlags) { - // Bootstrap already seeded the flags in RemoteConfig's init; fire the flags-loaded - // callbacks now so listeners aren't blocked on the first network response. + // Bootstrap already seeded the flags in RemoteConfig's init, so replay can start + // without waiting for the first network response. if (remoteConfig?.hasBootstrapFlags() == true) { try { startSessionReplayOnFeatureFlagsLoaded() } catch (e: Throwable) { config.logger.log("Executing the internal feature flags callback failed: $e") } - notifyFeatureFlagsCallback(config.onFeatureFlags, remoteConfig?.getFeatureFlags(), errorsLoading = false) } - loadRemoteConfigRequest( - internalOnFeatureFlagsLoaded(generation), - config.onFeatureFlags, - ) + loadRemoteConfigRequest(internalOnFeatureFlagsLoaded(generation)) } // Reconcile a differing identified bootstrap after the setup reload is dispatched. @@ -1749,7 +1745,7 @@ public class PostHog private constructor( // only because of testing in isolation, this flag is always enabled if (reloadFeatureFlags) { - reloadFeatureFlags(config?.onFeatureFlags) + reloadFeatureFlags() } // we need to make sure the user props update is for the same user // otherwise they have to reset and identify again @@ -1778,7 +1774,7 @@ public class PostHog private constructor( // The identified state itself is not part of the flags request; reload only when the // caller supplied properties that can affect flag evaluation. if ((userProperties?.isNotEmpty() == true || userPropertiesSetOnce?.isNotEmpty() == true) && reloadFeatureFlags) { - reloadFeatureFlags(config?.onFeatureFlags) + reloadFeatureFlags() } } else if (!hasDifferentDistinctId && (userProperties?.isNotEmpty() == true || userPropertiesSetOnce?.isNotEmpty() == true)) { if (shouldCapturePersonPropertiesEvent( @@ -2006,7 +2002,7 @@ public class PostHog private constructor( // only because of testing in isolation, this flag is always enabled if (reloadFeatureFlags && reloadFeatureFlagsIfNewGroup) { - reloadFeatureFlags(config?.onFeatureFlags) + reloadFeatureFlags() } } @@ -2082,10 +2078,7 @@ public class PostHog private constructor( ) } - private fun loadRemoteConfigRequest( - internalOnFeatureFlags: ((errorsLoading: Boolean) -> Unit)?, - onFeatureFlags: PostHogFeatureFlagsCallback?, - ) { + private fun loadRemoteConfigRequest(internalOnFeatureFlags: ((errorsLoading: Boolean) -> Unit)?) { @Suppress("UNCHECKED_CAST") val groups = getPreferences().getValue(GROUPS) as? Map @@ -2101,7 +2094,6 @@ public class PostHog private constructor( anonymousId = anonymousId, groups, internalOnFeatureFlags, - onFeatureFlags, ) } @@ -2110,7 +2102,7 @@ public class PostHog private constructor( defaultValue: Boolean, sendFeatureFlagEvent: Boolean?, ): Boolean { - val value = getFeatureFlag(key, defaultValue, sendFeatureFlagEvent) + val value = getFeatureFlag(key, sendFeatureFlagEvent) ?: defaultValue if (value is Boolean) { return value @@ -2191,11 +2183,10 @@ public class PostHog private constructor( public override fun getFeatureFlag( key: String, - defaultValue: Any?, sendFeatureFlagEvent: Boolean?, ): Any? { - if (!isEnabled()) return defaultValue - val flagValue = remoteConfig?.getFeatureFlagResult(key)?.value ?: defaultValue + if (!isEnabled()) return null + val flagValue = remoteConfig?.getFeatureFlagResult(key)?.value sendFeatureFlagCalled(key, flagValue, sendFeatureFlagEvent) return flagValue } @@ -2366,7 +2357,7 @@ public class PostHog private constructor( // reload flags as anon user // only because of testing in isolation, this flag is always enabled if (reloadFeatureFlags) { - reloadFeatureFlags(config?.onFeatureFlags) + reloadFeatureFlags() } } @@ -2865,9 +2856,8 @@ public class PostHog private constructor( public override fun getFeatureFlag( key: String, - defaultValue: Any?, sendFeatureFlagEvent: Boolean?, - ): Any? = shared.getFeatureFlag(key, defaultValue = defaultValue, sendFeatureFlagEvent) + ): Any? = shared.getFeatureFlag(key, sendFeatureFlagEvent) override fun getAllFeatureFlags(): List? { return shared.getAllFeatureFlags() diff --git a/posthog/src/main/java/com/posthog/PostHogConfig.kt b/posthog/src/main/java/com/posthog/PostHogConfig.kt index f36d38c38..929b639dd 100644 --- a/posthog/src/main/java/com/posthog/PostHogConfig.kt +++ b/posthog/src/main/java/com/posthog/PostHogConfig.kt @@ -154,12 +154,6 @@ public open class PostHogConfig( * Defaults to no encryption */ public var encryption: PostHogEncryption? = null, - /** - * Hook that is called when feature flags are loaded, or loading them failed - * It receives a [PostHogFeatureFlagsLoaded]; see [PostHogFeatureFlagsCallback] for the thread it runs on - * Defaults to no callback - */ - public var onFeatureFlags: PostHogFeatureFlagsCallback? = null, /** * Enable Recording of Session Replays for Android * Requires Record user sessions to be enabled in the PostHog Project Settings diff --git a/posthog/src/main/java/com/posthog/PostHogFeatureFlagsCallback.kt b/posthog/src/main/java/com/posthog/PostHogFeatureFlagsCallback.kt index 355b9714f..6c39fc9f7 100644 --- a/posthog/src/main/java/com/posthog/PostHogFeatureFlagsCallback.kt +++ b/posthog/src/main/java/com/posthog/PostHogFeatureFlagsCallback.kt @@ -3,19 +3,17 @@ package com.posthog /** * Callback invoked when a feature flags load finishes, whether it succeeded or failed. * - * It's used by `PostHogConfig.onFeatureFlags`, `reloadFeatureFlags` and `onFeatureFlags`. - * - * For `PostHogConfig.onFeatureFlags` and `reloadFeatureFlags`, it runs on a background thread, or right - * away on the calling thread when no load is attempted (for example, the SDK is disabled). With - * bootstrapped flags, `PostHogConfig.onFeatureFlags` also runs once on the thread calling `setup()`, - * before the first load finishes. Hop to the main thread before touching UI. + * It's used by `onFeatureFlags` and `reloadFeatureFlags`. * * For `onFeatureFlags`, it runs on the main thread on Android, and on the SDK's background remote * config thread on the JVM. * + * For `reloadFeatureFlags`, it runs on a background thread, or right away on the calling thread when + * no load is attempted (for example, the SDK is disabled). Hop to the main thread before touching UI. + * * Example: * ```kotlin - * config.onFeatureFlags = PostHogFeatureFlagsCallback { loaded -> + * val subscription = PostHog.onFeatureFlags { loaded -> * if (!loaded.errorsLoading && "new-checkout" in loaded.flags) { * // The flag is enabled * } diff --git a/posthog/src/main/java/com/posthog/PostHogInterface.kt b/posthog/src/main/java/com/posthog/PostHogInterface.kt index f4cbd455c..4e1be761d 100644 --- a/posthog/src/main/java/com/posthog/PostHogInterface.kt +++ b/posthog/src/main/java/com/posthog/PostHogInterface.kt @@ -186,16 +186,21 @@ public interface PostHogInterface : PostHogCoreInterface { ): Boolean /** - * Returns the feature flag + * Returns the feature flag value, or null if the flag has no value or the SDK is disabled. + * Use `?:` for a fallback; it is never reported in the $feature_flag_called event. + * + * ```kotlin + * val variant = PostHog.getFeatureFlag("my-flag") ?: "control" + * ``` + * * Docs https://posthog.com/docs/feature-flags and https://posthog.com/docs/experiments * @param key the Key - * @param defaultValue the default value if not found * @param sendFeatureFlagEvent (optional) If false, we won't send an $feature_flag_called event to PostHog. - * @return The feature flag value, or [defaultValue] if not found. + * Defaults to [PostHogConfig.sendFeatureFlagEvent]. + * @return The feature flag value, or null if not found. */ public fun getFeatureFlag( key: String, - defaultValue: Any? = null, sendFeatureFlagEvent: Boolean? = null, ): Any? diff --git a/posthog/src/main/java/com/posthog/internal/PostHogRemoteConfig.kt b/posthog/src/main/java/com/posthog/internal/PostHogRemoteConfig.kt index f9bec33c9..b63a91e32 100644 --- a/posthog/src/main/java/com/posthog/internal/PostHogRemoteConfig.kt +++ b/posthog/src/main/java/com/posthog/internal/PostHogRemoteConfig.kt @@ -889,9 +889,9 @@ public class PostHogRemoteConfig( distinctId = distinctId, anonymousId = anonymousId, groups = groups, - // distinct(): the SDK's own listeners and config.onFeatureFlags are singleton - // instances reused across reloads, so appending each queued reload would fire - // them once per coalesced reload instead of once per response. + // distinct(): the SDK's own listeners are singleton instances reused across reloads, + // so appending each queued reload would fire them once per coalesced reload + // instead of once per response. internalOnFeatureFlags = (displaced?.internalOnFeatureFlags.orEmpty() + listOfNotNull(internalOnFeatureFlags)) .distinct(), diff --git a/posthog/src/test/java/com/posthog/PostHogBootstrapTest.kt b/posthog/src/test/java/com/posthog/PostHogBootstrapTest.kt index 8fb56afdd..689411319 100644 --- a/posthog/src/test/java/com/posthog/PostHogBootstrapTest.kt +++ b/posthog/src/test/java/com/posthog/PostHogBootstrapTest.kt @@ -18,13 +18,11 @@ import java.util.concurrent.CountDownLatch import java.util.concurrent.Executors import java.util.concurrent.LinkedBlockingQueue import java.util.concurrent.TimeUnit -import java.util.concurrent.atomic.AtomicBoolean import kotlin.test.AfterTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNotEquals -import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue @@ -51,7 +49,6 @@ internal class PostHogBootstrapTest { storagePrefix: String = tmpDir.newFolder().absolutePath, logger: TestLogger? = null, optOut: Boolean = false, - onFeatureFlags: PostHogFeatureFlagsCallback? = null, ): PostHogInterface { config = PostHogConfig(PROJECT_TOKEN, host).apply { @@ -63,7 +60,6 @@ internal class PostHogBootstrapTest { this.cachePreferences = cachePreferences this.bootstrap = bootstrap this.optOut = optOut - this.onFeatureFlags = onFeatureFlags if (logger != null) { this.logger = logger } @@ -372,25 +368,6 @@ internal class PostHogBootstrapTest { http.shutdown() } - @Test - fun `bootstrap flags fire the flags-loaded callback immediately`() { - var loaded: PostHogFeatureFlagsLoaded? = null - val sut = - getSut( - host = "http://127.0.0.1:1", - // the callback fires from setup's flag loading, before /config answers - reloadFeatureFlags = true, - bootstrap = PostHogBootstrapConfig(featureFlags = mapOf("beta-ui" to true, "checkout" to "test")), - onFeatureFlags = PostHogFeatureFlagsCallback { loaded = it }, - ) - - assertEquals(mapOf("beta-ui" to true, "checkout" to "test"), loaded!!.variants) - assertFalse(loaded!!.errorsLoading) - assertEquals(true, sut.getFeatureFlag("beta-ui", sendFeatureFlagEvent = false)) - - sut.close() - } - @Test fun `onFeatureFlags replays bootstrapped flags to a listener registered after setup`() { val sut = @@ -448,6 +425,7 @@ internal class PostHogBootstrapTest { // the integration's /flags request is held, so this can only be the bootstrap delivery val loaded = updates.poll(5, TimeUnit.SECONDS) assertEquals(mapOf("beta-ui" to true), loaded?.variants) + assertFalse(loaded!!.errorsLoading) } finally { subscription.unsubscribe() release.countDown() @@ -457,29 +435,26 @@ internal class PostHogBootstrapTest { } @Test - fun `closing from the bootstrap flags callback drops setup's load for listeners`() { + fun `closing from an integration drops the bootstrap delivery and setup's load for listeners`() { val http = mockHttp(total = 5, response = MockResponse().setBody("""{"hasFeatureFlags":false}""")) - val completed = LinkedBlockingQueue() - val first = AtomicBoolean(true) val config = PostHogConfig(PROJECT_TOKEN, http.url("/").toString()).apply { storagePrefix = tmpDir.newFolder().absolutePath cachePreferences = PostHogMemoryPreferences() bootstrap = PostHogBootstrapConfig(featureFlags = mapOf("beta-ui" to true)) - onFeatureFlags = - PostHogFeatureFlagsCallback { - // the bootstrap delivery closes the SDK; setup's own load completes later - if (first.compareAndSet(true, false)) PostHog.close() else completed.add(it) - } + addIntegration( + object : PostHogIntegration { + override fun install(postHog: PostHogInterface) { + PostHog.close() + } + }, + ) } try { PostHog.setup(config) + http.takeRequest(5, TimeUnit.SECONDS) - // setup's load notifies listeners just before this completion - assertNotNull(completed.poll(5, TimeUnit.SECONDS)) - - // close() cleared the snapshot, so only a load it superseded could refill it val updates = LinkedBlockingQueue() val subscription = PostHog.onFeatureFlags { updates.add(it) } assertNull(updates.poll(500, TimeUnit.MILLISECONDS)) diff --git a/posthog/src/test/java/com/posthog/PostHogConfigTest.kt b/posthog/src/test/java/com/posthog/PostHogConfigTest.kt index 7903540c3..db419ba18 100644 --- a/posthog/src/test/java/com/posthog/PostHogConfigTest.kt +++ b/posthog/src/test/java/com/posthog/PostHogConfigTest.kt @@ -105,11 +105,6 @@ internal class PostHogConfigTest { assertEquals(listOf("api.example.com"), config.tracingHeaders) } - @Test - fun `onFeatureFlags is not set by default`() { - assertNull(config.onFeatureFlags) - } - @Test fun `logger uses NoOp by default`() { assertTrue(config.logger is PostHogNoOpLogger) diff --git a/posthog/src/test/java/com/posthog/PostHogFeatureFlagsTest.kt b/posthog/src/test/java/com/posthog/PostHogFeatureFlagsTest.kt index 8c02709ce..9da19fd32 100644 --- a/posthog/src/test/java/com/posthog/PostHogFeatureFlagsTest.kt +++ b/posthog/src/test/java/com/posthog/PostHogFeatureFlagsTest.kt @@ -348,49 +348,77 @@ internal class PostHogFeatureFlagsTest { sut.close() } - @Test - fun `getFeatureFlag with non-existent flag sends defaultValue in event`() { - val file = File("src/test/resources/json/basic-flags-with-non-active-flags.json") - val responseFlagsApi = file.readText() - + private fun assertMissingFlagReportsNoValue(read: (PostHogInterface) -> Unit) { val http = mockHttp( response = MockResponse() - .setBody(responseFlagsApi), + .setBody(File("src/test/resources/json/basic-flags-with-non-active-flags.json").readText()), ) - http.enqueue( - MockResponse() - .setBody(""), - ) - val url = http.url("/") - val sut = getSut(url.toString(), preloadFeatureFlags = false, sendFeatureFlagEvent = true) + http.enqueue(MockResponse().setBody("")) + val sut = getSut(http.url("/").toString(), preloadFeatureFlags = false, sendFeatureFlagEvent = true) sut.reloadFeatureFlags() - remoteConfigExecutor.shutdownAndAwaitTermination() - - // remove from the http queue http.takeRequest() - val defaultValue = "my-default" - val result = sut.getFeatureFlag("nonExistentFlag", defaultValue) - + read(sut) queueExecutor.shutdownAndAwaitTermination() - // Function should return the defaultValue - assertEquals(defaultValue, result) + val batch = serializer.deserialize(http.takeRequest().body.unGzip().reader()) + val theEvent = batch.batch.first() + assertEquals("\$feature_flag_called", theEvent.event) + assertEquals("nonExistentFlag", theEvent.properties!!["\$feature_flag"]) + assertEquals("", theEvent.properties!!["\$feature_flag_response"]) + sut.close() + } - val request = http.takeRequest() - val content = request.body.unGzip() - val batch = serializer.deserialize(content.reader()) + @Test + fun `getFeatureFlag returns null and reports no value for a missing flag`() { + assertMissingFlagReportsNoValue { sut -> + assertNull(sut.getFeatureFlag("nonExistentFlag")) + } + } - val theEvent = batch.batch.firstOrNull() - assertEquals("\$feature_flag_called", theEvent?.event) - // The event's $feature_flag_response should be the defaultValue, not null - assertEquals(defaultValue, theEvent?.properties!!["\$feature_flag_response"]) - assertEquals("nonExistentFlag", theEvent.properties!!["\$feature_flag"]) + @Test + fun `isFeatureEnabled returns the default but does not report it for a missing flag`() { + assertMissingFlagReportsNoValue { sut -> + assertTrue(sut.isFeatureEnabled("nonExistentFlag", defaultValue = true)) + } + } + + @Test + fun `isFeatureEnabled prefers a false flag value over the default`() { + val http = + mockHttp( + response = + MockResponse() + .setBody(File("src/test/resources/json/basic-flags-with-non-active-flags.json").readText()), + ) + val sut = getSut(http.url("/").toString(), preloadFeatureFlags = false) + + sut.reloadFeatureFlags() + remoteConfigExecutor.shutdownAndAwaitTermination() + + assertFalse(sut.isFeatureEnabled("IAmInactive", defaultValue = true)) + } + + @Test + fun `disabled SDK returns null from getFeatureFlag and the default from isFeatureEnabled`() { + val http = + mockHttp( + response = + MockResponse() + .setBody(File("src/test/resources/json/basic-flags-with-non-active-flags.json").readText()), + ) + val sut = getSut(http.url("/").toString(), preloadFeatureFlags = false) + + sut.reloadFeatureFlags() + remoteConfigExecutor.shutdownAndAwaitTermination() sut.close() + + assertNull(sut.getFeatureFlag("4535-funnel-bar-viz")) + assertTrue(sut.isFeatureEnabled("IAmInactive", defaultValue = true)) } @Test diff --git a/posthog/src/testFixtures/java/com/posthog/PostHogFake.kt b/posthog/src/testFixtures/java/com/posthog/PostHogFake.kt index 6ae4674f0..00a37fcf4 100644 --- a/posthog/src/testFixtures/java/com/posthog/PostHogFake.kt +++ b/posthog/src/testFixtures/java/com/posthog/PostHogFake.kt @@ -96,7 +96,6 @@ public class PostHogFake : PostHogInterface, PostHogPushSubscriptionReceiver { override fun getFeatureFlag( key: String, - defaultValue: Any?, sendFeatureFlagEvent: Boolean?, ): Any? { return null