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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 10 additions & 8 deletions OneSignalSDK/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ buildscript {
kotlinVersion = '1.9.25'
dokkaVersion = '1.9.10'
coroutinesVersion = '1.7.3'
kotlinxSerializationJsonVersion = '1.6.3'
Comment thread
fadi-george marked this conversation as resolved.
kotestVersion = '5.8.0'
ioMockVersion = '1.13.2'
// AndroidX Lifecycle and Activity versions
Expand All @@ -38,14 +39,15 @@ buildscript {
maven { url 'https://developer.huawei.com/repo/' }
}
sharedDeps = [
"com.android.tools.build:gradle:$androidGradlePluginVersion",
"com.google.gms:google-services:$googleServicesGradlePluginVersion",
"com.huawei.agconnect:agcp:$huaweiAgconnectVersion",
"org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion",
"org.jetbrains.dokka:dokka-gradle-plugin:$dokkaVersion",
"io.gitlab.arturbosch.detekt:detekt-gradle-plugin:$detektVersion",
"com.diffplug.spotless:spotless-plugin-gradle:$spotlessVersion",
"com.vanniktech.maven.publish:com.vanniktech.maven.publish.gradle.plugin:0.32.0"
"com.android.tools.build:gradle:$androidGradlePluginVersion",
"com.google.gms:google-services:$googleServicesGradlePluginVersion",
"com.huawei.agconnect:agcp:$huaweiAgconnectVersion",
"org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion",
"org.jetbrains.kotlin:kotlin-serialization:$kotlinVersion",
"org.jetbrains.dokka:dokka-gradle-plugin:$dokkaVersion",
"io.gitlab.arturbosch.detekt:detekt-gradle-plugin:$detektVersion",
"com.diffplug.spotless:spotless-plugin-gradle:$spotlessVersion",
"com.vanniktech.maven.publish:com.vanniktech.maven.publish.gradle.plugin:0.32.0"
]
}

Expand Down
2 changes: 2 additions & 0 deletions OneSignalSDK/onesignal/core/build.gradle
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
plugins {
id 'com.android.library'
id 'kotlin-android'
id 'org.jetbrains.kotlin.plugin.serialization'
Comment thread
abdulraqeeb33 marked this conversation as resolved.
id 'com.diffplug.spotless'
id 'com.vanniktech.maven.publish'
id 'io.gitlab.arturbosch.detekt'
Expand Down Expand Up @@ -73,6 +74,7 @@ dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutinesVersion"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutinesVersion"
implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:$kotlinxSerializationJsonVersion"

// AndroidX Lifecycle and Activity
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycleVersion"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@ import com.onesignal.common.modules.IModule
import com.onesignal.common.services.ServiceBuilder
import com.onesignal.core.internal.application.IApplicationService
import com.onesignal.core.internal.application.impl.ApplicationService
import com.onesignal.core.internal.backend.IFeatureFlagsBackendService
import com.onesignal.core.internal.backend.IParamsBackendService
import com.onesignal.core.internal.backend.impl.FeatureFlagsBackendService
import com.onesignal.core.internal.backend.impl.ParamsBackendService
import com.onesignal.core.internal.background.IBackgroundManager
import com.onesignal.core.internal.background.impl.BackgroundManager
import com.onesignal.core.internal.config.ConfigModelStore
import com.onesignal.core.internal.config.impl.ConfigModelStoreListener
import com.onesignal.core.internal.config.impl.FeatureFlagsRefreshService
import com.onesignal.core.internal.database.IDatabaseProvider
import com.onesignal.core.internal.database.impl.DatabaseProvider
import com.onesignal.core.internal.device.IDeviceService
Expand Down Expand Up @@ -61,7 +64,9 @@ internal class CoreModule : IModule {
builder.register<ConfigModelStore>().provides<ConfigModelStore>()
builder.register<FeatureManager>().provides<IFeatureManager>()
builder.register<ParamsBackendService>().provides<IParamsBackendService>()
builder.register<FeatureFlagsBackendService>().provides<IFeatureFlagsBackendService>()
builder.register<ConfigModelStoreListener>().provides<IStartableService>()
builder.register<FeatureFlagsRefreshService>().provides<IStartableService>()

// Operations
builder.register<OperationModelStore>().provides<OperationModelStore>()
Expand Down
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
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ internal class ParamsObject(
var locationShared: Boolean? = null,
var requiresUserPrivacyConsent: Boolean? = null,
var opRepoExecutionInterval: Long? = null,
val features: List<String> = emptyList(),
var influenceParams: InfluenceParamsObject,
var fcmParams: FCMParamsObject,
val remoteLoggingParams: RemoteLoggingParamsObject,
Expand Down
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
Comment thread
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)
}
}
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 {
Comment thread
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
}

Comment thread
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()
}
}
}
Loading
Loading