Repository navigation
feat: [SDK-5581] latch APP_STARTUP flags from a small startup file #2808
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
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
f6aed5d
feat: [SDK-5581] latch APP_STARTUP flags from a small startup file
41f1dcf
refactor: [SDK-5581] move startup flags latching into KMP
4dfb205
fix: [SDK-5581] keep the startup flags file in device-protected storage
b43dcd8
test: [SDK-5581] a locked boot still reads startup flags
8fb7974
fix: [SDK-5581] serialize startup flag mirrors and read the latest fl…
1d32515
chore: [SDK-5581] pin KMP to the Swift-safe startup flags store
5e2a34f
fix: [SDK-5581] follow KMP startup flags review fixes
6091626
test: [SDK-5581] an unreadable startup flags file is rewritten
ce61625
Merge remote-tracking branch 'origin/main' into ar/startup-flags
c4e0a57
chore: [SDK-5581] pin KMP to the main merge of the startup flags latch
13522d3
fix: [SDK-5581] address startup flags review
52dd35b
refactor: [SDK-5581] note the application context instead of reflecti…
5d81c36
docs: [SDK-5581] startup flag writes stay off main because of their c…
2fa086b
fix: [SDK-5581] log a failed startup flag mirror at ERROR
2ef49fe
fix: [SDK-5581] fall back to the given context when applicationContex…
364e3a8
fix: [SDK-5581] log a missing startup flags context at error
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
Submodule OneSignal-KMP-SDK
updated
9 files
30 changes: 30 additions & 0 deletions
30
OneSignalSDK/onesignal/core/src/main/java/com/onesignal/common/AppContext.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,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 | ||
| } | ||
| } |
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
76 changes: 76 additions & 0 deletions
76
...SDK/onesignal/core/src/main/java/com/onesignal/core/internal/features/README.md
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,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. |
101 changes: 101 additions & 0 deletions
101
...DK/onesignal/core/src/main/java/com/onesignal/core/internal/features/StartupFlagsCache.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,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 | ||
|
abdulraqeeb33 marked this conversation as resolved.
|
||
| } | ||
| } | ||
| } | ||
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.