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
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.onesignal.common

import android.content.Context

/**
* The process's application Context, noted by SDK entry points, so code that runs before init
* (or before ApplicationService starts) can read app storage without a Context of its own.
*/
internal object AppContext {
@Volatile
private var context: Context? = null

fun get(): Context? = context

/** First caller wins. Only the application Context is kept, so an Activity never leaks here. */
@Suppress("TooGenericExceptionCaught", "SwallowedException")
fun note(context: Context) {
if (this.context != null) return
this.context =
try {
context.applicationContext
} catch (_: Throwable) {
null
}
}

internal fun resetForTest() {
context = null
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,9 @@ internal class CoreModule : IModule {

// Params (Config)
builder.register<ConfigModelStore>().provides<ConfigModelStore>()
builder.register<FeatureManager>().provides<IFeatureManager>()
builder.register<FeatureManager>()
.provides<IFeatureManager>()
.provides<IStartableService>()
builder.register<ParamsBackendService>().provides<IParamsBackendService>()
builder.register<FeatureFlagsBackendService>().provides<IFeatureFlagsBackendService>()
builder.register<ConfigModelStoreListener>().provides<IStartableService>()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package com.onesignal.core.internal.application.impl
import android.app.Application
import android.content.Context
import androidx.startup.Initializer
import com.onesignal.common.AppContext
import com.onesignal.common.threading.OneSignalDispatchers
import com.onesignal.core.internal.application.IApplicationService

Expand All @@ -21,6 +22,7 @@ import com.onesignal.core.internal.application.IApplicationService
*/
class ActivityLifecycleInitializer : Initializer<IApplicationService> {
override fun create(context: Context): IApplicationService {
AppContext.note(context)
OneSignalDispatchers.prewarm()
val applicationService = ApplicationService.getInstance()
(context.applicationContext as? Application)?.let { application ->
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
package com.onesignal.core.internal.features

import android.content.Context
import com.onesignal.common.modeling.ISingletonModelStoreChangeHandler
import com.onesignal.common.modeling.ModelChangeTags
import com.onesignal.common.modeling.ModelChangedArgs
import com.onesignal.core.internal.application.IApplicationService
import com.onesignal.core.internal.config.ConfigModel
import com.onesignal.core.internal.config.ConfigModelStore
import com.onesignal.core.internal.startup.IStartableService
import com.onesignal.debug.internal.logging.Logging
import com.onesignal.features.DeferredFeatureActivation
import com.onesignal.features.FeatureFlag
import com.onesignal.features.FeatureFlagMetadata
import com.onesignal.features.StartupFlags
import com.onesignal.features.FeatureManager as SharedFeatureManager

/**
Expand Down Expand Up @@ -38,31 +43,44 @@ interface IFeatureManager {
}

/**
* Android host for the shared [SharedFeatureManager] latch.
*
* Persistence ([ConfigModel]) and store subscriptions stay here. Catalog, activation
* modes, and isEnabled latching live in KMP so iOS can call the same
* [SharedFeatureManager.refresh] with cached keys at process start
* (`applyAppStartupFlags = true`) and again after later fetches (`false`).
*
* Shared [SharedFeatureManager] is thread-safe; this host does not add an extra lock.
* Android host for the shared [SharedFeatureManager]: owns [ConfigModel] persistence, the startup
* flags file, and store subscriptions. Latching lives in KMP. See README.md in this package.
*/
@Suppress("TooGenericExceptionCaught")
internal class FeatureManager(
private val configModelStore: ConfigModelStore,
) : IFeatureManager, ISingletonModelStoreChangeHandler<ConfigModel> {
private val applicationService: IApplicationService,
) : IFeatureManager, IStartableService, ISingletonModelStoreChangeHandler<ConfigModel> {
private val latch = SharedFeatureManager()

// Writes wait for start() and run on the caller's thread, so staying off main is caller-dependent:
// StartupService runs start() on the default lane, and the flag fetches update ConfigModel on IO.
@Volatile
private var started = false

init {
Logging.debug("OneSignal: FeatureManager initializing from cached config features")
if (localFeatureOverrides.isNotEmpty()) {
Logging.warn("OneSignal: Local feature override enabled for testing only: $localFeatureOverrides")
}
// APP_STARTUP flags come from the snapshot pre-init code also latched from, so telemetry
// never reports a startup flag the running process is not using.
val startup = StartupFlagsCache.snapshot { appContextOrNull() }
Comment thread
abdulraqeeb33 marked this conversation as resolved.
Logging.debug("OneSignal: startup flags source=${startup.source} enabled=${startup.keys}")
try {
refreshFrom(configModelStore.model, applyAppStartupFlags = true)
logDeferred(latch.refreshAtStartup(configModelStore.model.sdkRemoteFeatureFlags, startup, localFeatureOverrides))
} catch (t: Throwable) {
Logging.error("OneSignal: Failed to initialize feature states from cached config", t)
latch.refreshAtStartup(emptyList(), startup, localFeatureOverrides)
}
configModelStore.subscribe(this)
}

override fun start() {
started = true
mirrorStartupFlags()
}

override fun isEnabled(feature: FeatureFlag): Boolean = latch.isEnabled(feature)

override fun enabledFeatureKeys(): List<String> = latch.enabledFeatureKeys()
Expand All @@ -81,9 +99,10 @@ internal class FeatureManager(
tag: String,
) {
Logging.debug("OneSignal: FeatureManager.onModelReplaced(tag=$tag)")
if (started) mirrorStartupFlags()
if (tag == ModelChangeTags.HYDRATE || tag == ModelChangeTags.NORMAL) {
try {
refreshFrom(model, applyAppStartupFlags = false)
refreshFrom(model)
} catch (t: Throwable) {
Logging.error("OneSignal: Failed to refresh features on model replace", t)
}
Expand All @@ -99,25 +118,22 @@ internal class FeatureManager(
args.property == ConfigModel::sdkRemoteFeatureFlagMetadata.name
) {
Logging.debug("OneSignal: FeatureManager.onModelUpdated(property=${args.property}, tag=$tag)")
if (started && args.property == ConfigModel::sdkRemoteFeatureFlags.name) {
mirrorStartupFlags()
}
try {
refreshFrom(configModelStore.model, applyAppStartupFlags = false)
refreshFrom(configModelStore.model)
} catch (t: Throwable) {
Logging.error("OneSignal: Failed to refresh features on model update", t)
}
}
}

private fun refreshFrom(
model: ConfigModel,
applyAppStartupFlags: Boolean,
) {
if (localFeatureOverrides.isNotEmpty()) {
Logging.warn(
"OneSignal: Local feature override enabled for testing only: $localFeatureOverrides",
)
}
val deferred =
latch.refresh(model.sdkRemoteFeatureFlags, applyAppStartupFlags, localFeatureOverrides)
private fun refreshFrom(model: ConfigModel) {
logDeferred(latch.refresh(model.sdkRemoteFeatureFlags, false, localFeatureOverrides))
}

private fun logDeferred(deferred: List<DeferredFeatureActivation>) {
for (change in deferred) {
Logging.info(
"OneSignal: Feature ${change.key} changed remotely to ${change.desiredEnabled} " +
Expand All @@ -126,7 +142,30 @@ internal class FeatureManager(
}
}

// Reads the store's model inside the write lock: a list captured by the caller could be stale.
private fun mirrorStartupFlags() {
try {
StartupFlagsCache.write(applicationService.appContext) { configModelStore.model.sdkRemoteFeatureFlags }
} catch (t: Throwable) {
Logging.error("OneSignal: failed to mirror startup flags: ${t.message}", t)
}
}

@Suppress("SwallowedException")
private fun appContextOrNull(): Context? =
try {
applicationService.appContext
} catch (t: Throwable) {
null
}

companion object {
/** APP_STARTUP flags for code that runs before SDK init. Same values [isEnabled] reports. */
fun startupFlags(context: () -> Context?): StartupFlags = StartupFlagsCache.snapshot(context)

/** Forgets this process's startup flags, as a new process would. */
internal fun resetStartupFlagsForTest() = StartupFlagsCache.setSnapshotForTest(null)

/**
* Local-only test hook for forcing features ON without backend config.
* Add feature keys here while testing locally, e.g.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# Startup flags

`FeatureManager` owns every feature flag. For `APP_STARTUP` flags it also keeps a tiny prefs file,
`OneSignalStartupFlags`, so code that runs before SDK init can read them without loading the whole
OneSignal prefs file (operations queue included) on the main thread. Typical pre-init readers make a
choice that lives for the whole process, such as which thread pools or logging pipeline to build.

## Adding a startup flag

1. Add it to `FeatureFlag` in the KMP catalog with `FeatureActivationMode.APP_STARTUP`.
2. Read it:
- After init (anything with an injected `IFeatureManager`): `featureManager.isEnabled(flag)`.
- Before init (no service container yet): `FeatureManager.startupFlags { context }.isEnabled(flag)`.

Nothing else. Both calls return the same value for the life of the process, unless
`FeatureManager.localFeatureOverrides` is set: local overrides only reach `isEnabled` (see Tests).

## Where the logic lives

The snapshot, key filtering, write skipping, and latching are in KMP (`StartupFlagsLatch`,
`StartupFlags`, `FeatureManager.refreshAtStartup`), so iOS gets the same behavior by implementing
`IStartupFlagsStore`. Android only provides that store (`PrefsStartupFlagsStore`) and the
process-wide holder (`StartupFlagsCache`).

## How it works

1. Process starts. The first reader, before or after init, triggers a single read of the file. That
snapshot is the process value for every APP_STARTUP flag.
2. `FeatureManager` is created and latches APP_STARTUP flags from the snapshot, IMMEDIATE flags from
`ConfigModel`.
3. `FeatureManager.start()` (an `IStartableService`, so off main) copies the APP_STARTUP subset of
`ConfigModel.sdkRemoteFeatureFlags` into the file.
4. A flags fetch updates `ConfigModel`. IMMEDIATE flags apply now. APP_STARTUP changes, on or off,
are logged as deferred, and the file is rewritten for the next process. The write uses `commit()`,
so it is on disk before the process can die.

## Rules

- **Only APP_STARTUP flags.** IMMEDIATE flags change mid-run and the file lags the store, so they are
never written and `StartupFlags.isEnabled` returns false for them.
- **The snapshot is the process value.** Telemetry tags and `isEnabled` must match what early code
latched, so APP_STARTUP flags never come from the store at runtime.
- **Missing or unreadable means off.** A missing file, a read that throws, or no application context
all give an empty snapshot. The source (`STORE`, `MISSING`, `UNREADABLE`, `NO_STORE`) is logged at
debug when `FeatureManager` is built.
- **SDK entry points note the context.** When the caller has no context yet (for example, init's
first log builds `FeatureManager` before `ApplicationService` starts), the snapshot uses the one in
`AppContext`, noted by the startup initializer and at the start of init. No reflection: if nothing
noted one, the snapshot is `NO_STORE` and logs a warning.
- **One value per process, even when unreadable.** The first read wins, including an `UNREADABLE`
one. Later readers in the same process (sync jobs, FCM receivers, prewarm) never re-read and get a
different answer, so code that already latched "off" never disagrees with code that runs later.
- **Device-protected storage.** On API 24+ the file lives in device-protected storage
(`createDeviceProtectedStorageContext()`), so receivers and jobs that start before first unlock
read real values instead of `UNREADABLE`. Below 24 there is no direct boot, so the normal context
is used. Never put anything secret in this file: it is readable while the device is locked.
- **One launch behind after an upgrade.** The file does not exist on the first launch of the version
that introduces it, so APP_STARTUP flags are off for that launch even if the store already has them.
- **Writes are serialized and read the latest flags.** `start()` and a flags fetch can mirror at the
same time. Each write reads `ConfigModel` inside the latch's mirror lock, so the last write to finish
always holds the newest flags, never a list captured before another write landed. A file that can't
be read is rewritten rather than skipped, and so is one whose last `commit()` failed, since
`SharedPreferences` keeps the uncommitted value in memory.
- **No writes before `start()`.** `FeatureManager` can be constructed on main; the file is only written
after start.
- **Main thread cost.** The first reader opens one small XML file. Cheap, but StrictMode can still report
it as a disk read when that reader is on main.

## Tests

- `FeatureManager.resetStartupFlagsForTest()` forgets the snapshot, as a new process would.
`OneSignalTestProjectConfig` calls it around every spec.
- `StartupFlagsCache.setSnapshotForTest(...)` installs a fixed snapshot; `readFile` reads the file
without touching the snapshot.
- `FeatureManager.localFeatureOverrides` does not reach the snapshot. Pre-init readers need their own
test hooks.
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
package com.onesignal.core.internal.features

import android.content.Context
import android.content.SharedPreferences
import android.os.Build
import android.util.Log
import com.onesignal.common.AppContext
import com.onesignal.features.IStartupFlagsStore
import com.onesignal.features.StartupFlags
import com.onesignal.features.StartupFlagsLatch

/**
* Process-wide holder for the shared [StartupFlagsLatch], backed by a small prefs file so pre-init
* code (often on main) never loads the OneSignal store. See README.md in this package.
*/
internal object StartupFlagsCache {
@Volatile
private var latch = StartupFlagsLatch()

/** The first caller in the process reads the file; everyone after gets the same answer. */
fun snapshot(context: () -> Context?): StartupFlags = latch.snapshot { storeFor(context() ?: AppContext.get()) }

// The answer is latched for the whole process, so a missing context must be visible in logcat.
private fun storeFor(context: Context?): IStartupFlagsStore? {
if (context == null) Log.e(PrefsStartupFlagsStore.TAG, "startup flags: no application context, all off for this process")
return context?.let(::PrefsStartupFlagsStore)
}

/**
* Mirrors the APP_STARTUP subset of [currentFlags] for the next process. Call off the main thread.
* [currentFlags] runs under the latch's mirror lock, so racing writers always leave the latest flags on disk.
*/
fun write(
context: Context,
currentFlags: () -> List<String>,
) {
latch.mirror(PrefsStartupFlagsStore(context), currentFlags)
}

/** Reads the file now, without touching this process's snapshot. */
internal fun readFile(context: Context?): StartupFlags = StartupFlagsLatch().snapshot { context?.let(::PrefsStartupFlagsStore) }

/** Null forgets the snapshot, as a new process would. */
internal fun setSnapshotForTest(flags: StartupFlags?) {
PrefsStartupFlagsStore.commitFailed = false
latch =
StartupFlagsLatch().also { fresh ->
if (flags != null) fresh.snapshot { FixedStore(flags.keys) }
}
}

private class FixedStore(
private val keys: Set<String>,
) : IStartupFlagsStore {
override fun read(): Set<String> = keys

override fun write(keys: Set<String>) = Unit
}
}

internal class PrefsStartupFlagsStore(
private val context: Context,
) : IStartupFlagsStore {
@Suppress("TooGenericExceptionCaught")
override fun read(): Set<String>? =
try {
check(!commitFailed) { "last startup flags commit failed" }
prefs().getStringSet(KEY_ENABLED, null)?.toSet()
} catch (t: Throwable) {
// android.util.Log, not Logging: Logging can dispatch, and this can run before SDK init.
Log.w(TAG, "startup flags unreadable", t)
throw t
}

// commit, not apply: the next process reads this at startup, so it must be on disk when we return.
override fun write(keys: Set<String>) {
val committed = prefs().edit().putStringSet(KEY_ENABLED, keys).commit()
commitFailed = !committed
check(committed) { "startup flags commit failed" }
}

private fun prefs(): SharedPreferences = storageContext(context).getSharedPreferences(STORE, Context.MODE_PRIVATE)

internal companion object {
const val STORE = "OneSignalStartupFlags"
private const val KEY_ENABLED = "enabled"
const val TAG = "OneSignal"

// A failed commit still updates the in-memory prefs, so reads can't be trusted until a commit lands.
@Volatile
var commitFailed = false

// Device-protected so receivers and jobs that start before first unlock read the real values.
// Must hold nothing secret: this storage is readable while the device is still locked.
fun storageContext(context: Context): Context {
// Null during attachBaseContext and some direct-boot paths.
val app: Context = context.applicationContext ?: context
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) app.createDeviceProtectedStorageContext() else app
Comment thread
abdulraqeeb33 marked this conversation as resolved.
}
}
}
Loading
Loading