-
Notifications
You must be signed in to change notification settings - Fork 377
feat: SDK-4363: Turbine remote SDK feature flags and foreground refresh #2612
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
abdulraqeeb33
merged 14 commits into
main
from
sdk-4363-android-sdk-turbine-feature-flags
Apr 28, 2026
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
347b359
fix(ci): diff coverage uses PR base SHA and aggregate gate
7693825
SDK-4363: Turbine remote SDK feature flags and foreground refresh
72890cc
Merge branch 'main' into sdk-4363-android-sdk-turbine-feature-flags
c63f686
feature flag PR tweaks
3720ec5
fix(core): address PR 2612 review for FeatureFlagsRefreshService
64a1068
fix(core): PR 2612 follow-ups — fetch outcome, cancellation, docs, ke…
c7a2720
more logging
8f47b9c
chore(core): drop revert-before-merge TODOs on kept diagnostics
ce19184
Addressed comments
0a3d18e
removing features node in ConfigModel
68f2df3
nit(style): fix spotless formatting and core detekt issues
nan-li 2861144
magic numbers
8786852
fix(core): preserve feature flag cache against snapshot race and cont…
98e436d
fix(core): dedup remote feature-flags fetch on same-appId hydrate
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
40 changes: 40 additions & 0 deletions
40
...nal/core/src/main/java/com/onesignal/core/internal/backend/IFeatureFlagsBackendService.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| package com.onesignal.core.internal.backend | ||
|
|
||
| import kotlinx.serialization.json.JsonObject | ||
|
|
||
| /** | ||
| * Result of the dedicated SDK feature-flags endpoint (separate from [IParamsBackendService]). | ||
| * | ||
| * @param enabledKeys Feature keys that should be treated as enabled for this device/SDK. | ||
| * @param metadata Optional per-flag payload (e.g. weights), keyed by flag id. Parsed from sibling | ||
| * keys in the response JSON (see [com.onesignal.core.internal.backend.impl.FeatureFlagsJsonParser]). | ||
| */ | ||
| internal data class RemoteFeatureFlagsResult( | ||
| val enabledKeys: List<String>, | ||
| val metadata: JsonObject?, | ||
| ) { | ||
| companion object { | ||
| val EMPTY = RemoteFeatureFlagsResult(emptyList(), null) | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Outcome of [IFeatureFlagsBackendService.fetchRemoteFeatureFlags]. | ||
| * [Unavailable] means the client did not get a trustworthy response (HTTP error, invalid body, etc.); | ||
| * callers should keep previously cached flags. [Success] includes a valid HTTP parse, including an | ||
| * empty `features` array from the server. | ||
| */ | ||
| internal sealed class RemoteFeatureFlagsFetchOutcome { | ||
| data class Success(val result: RemoteFeatureFlagsResult) : RemoteFeatureFlagsFetchOutcome() | ||
|
|
||
| data object Unavailable : RemoteFeatureFlagsFetchOutcome() | ||
| } | ||
|
|
||
| /** | ||
| * Fetches remote feature flags for the current app via **GET** | ||
| * `apps/{app_id}/sdk/features/{platform}/{sdk_version}` (Turbine; see | ||
| * [com.onesignal.core.internal.backend.impl.FeatureFlagsBackendService]). | ||
| */ | ||
| internal interface IFeatureFlagsBackendService { | ||
| suspend fun fetchRemoteFeatureFlags(appId: String): RemoteFeatureFlagsFetchOutcome | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
120 changes: 120 additions & 0 deletions
120
...core/src/main/java/com/onesignal/core/internal/backend/impl/FeatureFlagsBackendService.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,120 @@ | ||
| package com.onesignal.core.internal.backend.impl | ||
|
|
||
| import com.onesignal.common.OneSignalUtils | ||
| import com.onesignal.core.internal.backend.IFeatureFlagsBackendService | ||
| import com.onesignal.core.internal.backend.RemoteFeatureFlagsFetchOutcome | ||
| import com.onesignal.core.internal.http.IHttpClient | ||
| import com.onesignal.debug.LogLevel | ||
| import com.onesignal.debug.internal.logging.Logging | ||
|
|
||
| /** | ||
| * Turbine SDK feature flags endpoint ([OneSignal/turbine#1681](https://github.com/OneSignal/turbine/pull/1681)). | ||
| * | ||
| * HTTP, logging, and [OneSignalUtils] are platform-specific; path shape and validation live in | ||
| * [TurbineSdkFeatureFlagsPath], and JSON parsing in [FeatureFlagsJsonParser] (both KMP-friendly). | ||
| * | ||
| * **GET** `apps/{app_id}/sdk/features/{platform}/{sdk_version}` relative to | ||
| * [com.onesignal.core.internal.config.ConfigModel.apiUrl] (app-provided base URL). | ||
| * | ||
| * - **platform** is always **`android`** for this SDK client. | ||
| * - **sdk_version** is [OneSignalUtils.sdkVersion] (same label as the `SDK-Version` header segment), e.g. | ||
| * `050801` or `050801-beta`; see [isValidFeaturesSdkVersionLabel]. | ||
| * | ||
| * Response: `{ "features": [ "flag_key", ... ] }`. | ||
| */ | ||
| internal class FeatureFlagsBackendService( | ||
| private val http: IHttpClient, | ||
| ) : IFeatureFlagsBackendService { | ||
| override suspend fun fetchRemoteFeatureFlags(appId: String): RemoteFeatureFlagsFetchOutcome { | ||
| Logging.log(LogLevel.DEBUG, "FeatureFlagsBackendService.fetchRemoteFeatureFlags(appId=$appId)") | ||
|
|
||
| val sdkVersion = OneSignalUtils.sdkVersion | ||
| if (!isValidFeaturesSdkVersionLabel(sdkVersion)) { | ||
| Logging.warn( | ||
| "FeatureFlagsBackendService: sdk version not usable for Turbine path (expected " + | ||
| "6-digit label optional -suffix, e.g. 050801 or 050801-beta): '$sdkVersion'", | ||
| ) | ||
| return RemoteFeatureFlagsFetchOutcome.Unavailable | ||
| } | ||
|
|
||
| val path = | ||
| TurbineSdkFeatureFlagsPath.buildGetPath( | ||
| appId = appId, | ||
| platform = TURBINE_FEATURES_PLATFORM_ANDROID, | ||
| sdkVersion = sdkVersion, | ||
| ) | ||
|
|
||
| val response = http.get(path, null) | ||
| val body = response.payload | ||
| if (!response.isSuccess) { | ||
| val msg = | ||
| "FeatureFlagsBackendService: non-success status=${response.statusCode} body=${bodySnippet(body)}" | ||
| // 4xx is likely a permanent misconfiguration (e.g. 403 Forbidden when the app is not | ||
| // enrolled for Turbine feature flags) and worth surfacing at WARN; other failures are | ||
| // typically transient (network blip, 5xx) and stay at DEBUG to avoid log spam. | ||
| if (response.isClientError) Logging.warn(msg) else Logging.debug(msg) | ||
| return RemoteFeatureFlagsFetchOutcome.Unavailable | ||
|
claude[bot] marked this conversation as resolved.
|
||
| } | ||
| if (body.isNullOrBlank()) { | ||
| Logging.warn( | ||
| "FeatureFlagsBackendService: empty body for success status=${response.statusCode}", | ||
| ) | ||
| return RemoteFeatureFlagsFetchOutcome.Unavailable | ||
| } | ||
|
|
||
| val parsed = FeatureFlagsJsonParser.parseSuccessful(body) | ||
| return if (parsed != null) { | ||
| RemoteFeatureFlagsFetchOutcome.Success(parsed) | ||
| } else { | ||
| Logging.warn( | ||
| "FeatureFlagsBackendService: response body is not valid Turbine feature-flags JSON: " + | ||
| bodySnippet(body), | ||
| ) | ||
| RemoteFeatureFlagsFetchOutcome.Unavailable | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Trim [body] to a short, single-line snippet safe for logcat. Caps at | ||
| * [LOG_BODY_SNIPPET_MAX_CHARS] so we never dump large payloads into logs. | ||
| */ | ||
| private fun bodySnippet(body: String?): String { | ||
| if (body.isNullOrEmpty()) return "<empty>" | ||
| val flattened = body.replace('\n', ' ').replace('\r', ' ') | ||
| return if (flattened.length <= LOG_BODY_SNIPPET_MAX_CHARS) { | ||
| flattened | ||
| } else { | ||
| flattened.take(LOG_BODY_SNIPPET_MAX_CHARS) + "…" | ||
| } | ||
| } | ||
|
|
||
| companion object { | ||
| /** | ||
| * Turbine `:platform` segment for the OneSignal Android SDK (this client). | ||
| */ | ||
| const val TURBINE_FEATURES_PLATFORM_ANDROID = "android" | ||
|
|
||
| /** | ||
| * Max chars of an HTTP response body included in diagnostic logs. Turbine error bodies | ||
| * (e.g. `{"errors":["Forbidden"]}`) are tiny, so 200 chars is plenty and bounds worst-case | ||
| * log size if an unexpected payload is returned. | ||
| */ | ||
| private const val LOG_BODY_SNIPPET_MAX_CHARS = 200 | ||
|
|
||
| /** | ||
| * Returns true when [label] is safe to send as the Turbine `:sdk_version` path segment. | ||
| * @see TurbineSdkFeatureFlagsPath.isValidFeaturesSdkVersionLabel | ||
| */ | ||
| fun isValidFeaturesSdkVersionLabel(label: String): Boolean = TurbineSdkFeatureFlagsPath.isValidFeaturesSdkVersionLabel(label) | ||
|
|
||
| /** | ||
| * Path only (relative to API base), matching `/apps/:app_id/sdk/features/:platform/:sdk_version`. | ||
| * @see TurbineSdkFeatureFlagsPath.buildGetPath | ||
| */ | ||
| internal fun buildFeatureFlagsGetPath( | ||
| appId: String, | ||
| platform: String, | ||
| sdkVersion: String, | ||
| ): String = TurbineSdkFeatureFlagsPath.buildGetPath(appId, platform, sdkVersion) | ||
| } | ||
| } | ||
149 changes: 149 additions & 0 deletions
149
...nal/core/src/main/java/com/onesignal/core/internal/backend/impl/FeatureFlagsJsonParser.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,149 @@ | ||
| package com.onesignal.core.internal.backend.impl | ||
|
|
||
| import com.onesignal.core.internal.backend.RemoteFeatureFlagsResult | ||
| import kotlinx.serialization.json.Json | ||
| import kotlinx.serialization.json.JsonArray | ||
| import kotlinx.serialization.json.JsonElement | ||
| import kotlinx.serialization.json.JsonObject | ||
| import kotlinx.serialization.json.JsonPrimitive | ||
| import kotlinx.serialization.json.buildJsonObject | ||
|
|
||
| /** | ||
| * **What this is:** strict JSON parsing for the Turbine SDK feature-flags response | ||
| * ([OneSignal/turbine#1681](https://github.com/OneSignal/turbine/pull/1681)). | ||
| * | ||
| * **Wire shape:** root object with a `features` array of **string** flag ids. Optional per-flag JSON | ||
| * objects may appear as **sibling root properties** (same name as the id); those are merged into | ||
| * [RemoteFeatureFlagsResult.metadata]. | ||
| * | ||
| * **Optional metadata:** for a string entry `"foo"`, if the root also has a property `"foo"` (or | ||
| * case-insensitive match) whose value is a JSON object, that object is stored per-flag in | ||
| * [RemoteFeatureFlagsResult.metadata]. That lets a future API add per-flag config without a new | ||
| * top-level field; the SDK persists it in [com.onesignal.core.internal.config.ConfigModel.sdkRemoteFeatureFlagMetadata] | ||
| * so a later process or SDK version can read it without re-fetching. | ||
| * | ||
| * **API surface:** [parseSuccessful] for HTTP 200 bodies; [parse] for lenient “best effort”; | ||
| * [encodeMetadata] / [parseStoredMetadataMap] for the persisted metadata column. | ||
| * | ||
| * Uses only Kotlin stdlib + kotlinx.serialization (Kotlin Multiplatform-friendly). | ||
| */ | ||
| internal object FeatureFlagsJsonParser { | ||
|
nan-li marked this conversation as resolved.
|
||
| /** | ||
| * RFC 8259–style JSON only (no lenient tokens like unquoted keys, `NaN`, trailing commas). | ||
| * That keeps [encodeMetadata] strings portable: the same text can be parsed later by | ||
| * `org.json.JSONObject`, Gson, or kotlinx without relying on kotlinx-only quirks. | ||
| */ | ||
| val format = | ||
| Json { | ||
| ignoreUnknownKeys = true | ||
| isLenient = false | ||
| allowSpecialFloatingPointValues = false | ||
| prettyPrint = false | ||
| } | ||
|
|
||
| private const val FEATURES_PROPERTY = "features" | ||
|
|
||
| fun parse(payload: String): RemoteFeatureFlagsResult = parseSuccessful(payload) ?: RemoteFeatureFlagsResult.EMPTY | ||
|
|
||
| /** | ||
| * Parses a 200 response body. Returns `null` if the text is not JSON, not an object, or does not | ||
| * contain a `features` **array** of the expected element types. Returns an empty result for | ||
| * `{"features":[]}`. | ||
| */ | ||
| fun parseSuccessful(payload: String): RemoteFeatureFlagsResult? { | ||
| return try { | ||
| val root = format.parseToJsonElement(payload) as? JsonObject ?: return null | ||
| parseRootStrict(root) | ||
| } catch (_: Throwable) { | ||
| null | ||
| } | ||
| } | ||
|
|
||
| @Suppress("ReturnCount") | ||
| private fun parseRootStrict(root: JsonObject): RemoteFeatureFlagsResult? { | ||
| val featuresEl = root[FEATURES_PROPERTY] ?: return null | ||
| val featuresArray = featuresEl as? JsonArray ?: return null | ||
| val flagEntries = | ||
| featuresArray.mapNotNull { el -> | ||
| (el as? JsonPrimitive) | ||
| ?.takeIf { it.isString } | ||
| ?.content | ||
| ?.trim() | ||
| ?.takeIf { it.isNotEmpty() } | ||
| ?.let { raw -> raw to canonicalFeatureFlagId(raw) } | ||
| }.distinctBy { it.second } | ||
|
|
||
| if (flagEntries.isEmpty()) { | ||
| // `[]` is an authoritative empty config; a non-empty array that filtered down | ||
| // to empty is a contract violation. Null surfaces as Unavailable upstream so | ||
| // callers preserve the cached list instead of overwriting it with []. | ||
| return if (featuresArray.isEmpty()) RemoteFeatureFlagsResult(emptyList(), null) else null | ||
| } | ||
|
|
||
|
claude[bot] marked this conversation as resolved.
|
||
| val keys = flagEntries.map { it.second } | ||
|
|
||
| val metadata = | ||
| buildJsonObject { | ||
| for ((rawKey, canonicalKey) in flagEntries) { | ||
| findSiblingJsonObject(root, rawKey, canonicalKey)?.let { put(canonicalKey, it) } | ||
| } | ||
| } | ||
| val metaOut = if (metadata.isEmpty()) null else metadata | ||
| return RemoteFeatureFlagsResult(keys, metaOut) | ||
| } | ||
|
|
||
| @Suppress("ReturnCount") | ||
| private fun findSiblingJsonObject( | ||
| root: JsonObject, | ||
| rawKeyFromFeaturesArray: String, | ||
| canonicalKey: String, | ||
| ): JsonObject? { | ||
| for (candidate in listOf(rawKeyFromFeaturesArray, canonicalKey)) { | ||
| if (candidate == FEATURES_PROPERTY) { | ||
| continue | ||
| } | ||
| when (val v = root[candidate]) { | ||
| is JsonObject -> return v | ||
| else -> Unit | ||
| } | ||
| } | ||
| for ((k, v) in root) { | ||
| if (k == FEATURES_PROPERTY) { | ||
| continue | ||
| } | ||
| if (k.equals(rawKeyFromFeaturesArray, ignoreCase = true) && v is JsonObject) { | ||
| return v | ||
| } | ||
| } | ||
| return null | ||
| } | ||
|
|
||
| private fun canonicalFeatureFlagId(raw: String): String = | ||
| buildString(raw.length) { | ||
| for (c in raw) { | ||
| append(c.lowercaseChar()) | ||
| } | ||
| } | ||
|
|
||
| fun encodeMetadata(metadata: JsonObject?): String? = | ||
| metadata?.let { format.encodeToString(JsonElement.serializer(), it) } | ||
|
|
||
| /** | ||
| * Decodes [ConfigModel.sdkRemoteFeatureFlagMetadata] (a JSON object of flag id → object) into a map. | ||
| * Non-object values are skipped so each entry stays a [JsonObject] for nested decoding (e.g. with `Json.decodeFromJsonElement`). | ||
| */ | ||
| @Suppress("ReturnCount") | ||
| fun parseStoredMetadataMap(raw: String?): Map<String, JsonObject> { | ||
| if (raw.isNullOrBlank()) { | ||
| return emptyMap() | ||
| } | ||
| return try { | ||
| val root = format.parseToJsonElement(raw) as? JsonObject ?: return emptyMap() | ||
| root.entries.mapNotNull { (key, value) -> | ||
| (value as? JsonObject)?.let { key to it } | ||
| }.toMap() | ||
| } catch (_: Throwable) { | ||
| emptyMap() | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.