From 74c956746eca26e7f07d0cc16500a1fc1e115639 Mon Sep 17 00:00:00 2001 From: xyzcancer Date: Tue, 17 Nov 2026 15:06:30 +0400 Subject: [PATCH 1/3] feat(core): the new core is the bridges' only: apps no longer pick it through Rees46Config, Flutter and React Native start it with Rees46.initializeBridge Rees46Config has no coreV2: Rees46.initialize and Rees46.register ask for the legacy core, and source that passes coreV2 no longer compiles. A hidden constructor and copy with the old parameters keep apps built against 2.50 and 2.51 running; their coreV2 = true is ignored and logged as invalid_config (bridge_only). Rees46.initializeBridge(context, config, segment) is @BridgeApi and hidden from Java: initialize on the new core. segment, the A/B group a bridge kept for the device, is taken while the device has no group of its own; a device that has one keeps it and a different segment is logged as invalid_config (segment_kept), a value other than A or B is refused with invalid_argument (invalid_segment). The process still runs one core, decided by the first initialize, register or initializeBridge, with core_flag_mismatch for an instance that asks for the other, now also when a live instance is asked again. --- personalization-sdk/build.gradle | 2 +- .../main/kotlin/com/personalization/Rees46.kt | 127 ++++++- .../com/personalization/Rees46Config.kt | 105 +++-- .../main/kotlin/com/personalization/SDK.kt | 28 +- .../api/managers/TrackEventManager.kt | 2 +- .../api/managers/TrackingApi.kt | 2 +- .../com/personalization/core/BridgeApi.kt | 8 +- .../com/personalization/core/SdkState.kt | 4 +- .../com/personalization/core/internal/Core.kt | 4 +- .../core/internal/CoreSelection.kt | 10 +- .../core/internal/DeviceStorage.kt | 3 + .../core/internal/ShopStorage.kt | 3 + .../core/internal/StorageMigrations.kt | 19 +- .../helpers/NotificationHelper.kt | 2 +- .../com/personalization/logs/SdkLogs.kt | 12 + .../UserSettings.repository.impl.kt | 3 +- .../personalization/Rees46ConfigJavaTest.java | 17 +- .../com/personalization/BridgeInitTest.kt | 359 ++++++++++++++++++ .../personalization/LegacyPushClickTest.kt | 1 - .../NotificationHelperUnseenPushTest.kt | 2 +- .../com/personalization/PushBringUpTest.kt | 35 +- .../com/personalization/PushEventsTest.kt | 43 +-- .../personalization/PushTokenSourcesTest.kt | 21 +- .../com/personalization/PushTokenWeekTest.kt | 11 +- .../com/personalization/SdkCoreGapsTest.kt | 21 +- .../com/personalization/SdkInitRequestTest.kt | 9 +- .../com/personalization/SdkInstanceTest.kt | 31 +- .../com/personalization/SdkLegacyApiTest.kt | 2 +- .../com/personalization/SdkStorageTest.kt | 7 +- .../com/personalization/TrackingQueueTest.kt | 7 +- .../personalization/TrackingValidationTest.kt | 3 +- .../core/internal/CoreFunnelTest.kt | 7 +- .../core/internal/LegacyCoreParityTest.kt | 2 +- 33 files changed, 722 insertions(+), 190 deletions(-) create mode 100644 personalization-sdk/src/test/kotlin/com/personalization/BridgeInitTest.kt diff --git a/personalization-sdk/build.gradle b/personalization-sdk/build.gradle index 086aa639..78ccdbf1 100644 --- a/personalization-sdk/build.gradle +++ b/personalization-sdk/build.gradle @@ -126,7 +126,7 @@ dependencies { // through lifecycle-process; declared because the SDK now relies on it directly. implementation 'androidx.startup:startup-runtime:1.1.1' implementation 'com.google.code.gson:gson:2.11.0' - // The new core's HTTP client (Rees46Config.coreV2): one connection pool for the process. 4.12, not 5: + // The new core's HTTP client (Rees46.initializeBridge): one connection pool for the process. 4.12, not 5: // OkHttp 5 brings kotlin-stdlib 2.2, which asks apps for a Kotlin compiler of 2.1 or later, and adds an // androidx.startup initializer to their manifest. 4.12 brings neither: its kotlin-stdlib is older than // the SDK's own. diff --git a/personalization-sdk/src/main/kotlin/com/personalization/Rees46.kt b/personalization-sdk/src/main/kotlin/com/personalization/Rees46.kt index a6ff5e3b..09ff846c 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/Rees46.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/Rees46.kt @@ -12,6 +12,7 @@ import com.personalization.core.PushEvent import com.personalization.core.PushPayload import com.personalization.core.PushTokenListener import com.personalization.core.internal.CoreSelection +import com.personalization.core.internal.DeviceStorage import com.personalization.core.internal.PushHub import com.personalization.core.internal.ShopStorage import com.personalization.core.internal.StorageLayout @@ -38,7 +39,8 @@ import java.util.concurrent.ConcurrentHashMap */ object Rees46 { - private data class PendingInit(val context: Context, val config: Rees46Config) + /** A shop registered and not yet made, with the core it asked for. */ + private data class PendingInit(val context: Context, val config: Rees46Config, val coreV2: Boolean) private val pending = ConcurrentHashMap() @@ -54,10 +56,71 @@ object Rees46 { * from the one it was made with, `invalid_config` (`already_initialized`) is logged and the instance * keeps its own. After [SDK.release] a call makes a fresh instance. Calls from several threads at * once make one instance. + * + * The instance asks for the legacy core. The process has one core, decided by the first + * [initialize], [register] or [initializeBridge]: an instance that asks for the other one runs on the + * process's and logs `core_flag_mismatch`. + */ + fun initialize(context: Context, config: Rees46Config): SDK = initialize(context, config, coreV2 = false) + + /** + * For the bridges: [initialize] on the new core. The SDK's Flutter and React Native bridges start their + * shops here; apps use [initialize]. The rule of one core per process stands: a process whose core is + * the legacy one already (an [initialize] or [register] came first) runs this instance on it too and + * logs `core_flag_mismatch`. So a bridge does not [register] its shops, which asks for the legacy core: + * it starts each shop here, a lazy one on its first use. + * + * [segment] is the A/B group the bridge kept for this device before it ran on the native SDK (React + * Native kept `A` or `B` for each shop). The start takes it while the device has no A/B group of its + * own, so the device stays in the group the server knows it by; a device that has one keeps it, and a + * different [segment] is logged as `invalid_config` (`segment_kept`). A value the SDK never gives, any + * but `A` and `B`, is refused with `invalid_argument` (`invalid_segment`). Neither throws. The shop's + * group is [SDK.getSegment]: once that is the bridge's, the bridge may stop passing it. + * + * Hidden from Java, which knows no opt-in: the bridges are Kotlin. + * + * The new core differs from the legacy one in: + * - its network client: requests go through OkHttp, a request without a network fails at once, + * `release()` cancels the instance's requests, and a failure without an answer is `onError(-1)` (no + * connection used to be `504`), as is a `2xx` whose body is not JSON (it used to succeed empty); + * - its `/init`: repeated with growing pauses until it gets an answer; a shop that answers `402`, + * `403`, `404` or another `4xx` is refused ([com.personalization.core.SdkState.REFUSED]) until a + * later launch's `/init` succeeds, and every request of a refused shop fails with `onError(402)`; + * - a request waits until the instance is ready, within its own read timeout, instead of going out + * without a `did`: a new device's first requests fail with `onError(-1)` if `/init` does not answer + * in time; + * - [Rees46Config.needReInitialization] really gives the device a new `did`; [Rees46Config.stream] + * goes with `/init` too; the advertising id is read and sent only with + * [Rees46Config.sendAdvertisingId]; + * - its session: the `sid` is the server's, and a session two hours without events ends — the next + * request or event sends `/init` first; requests with a result no longer extend it; + * - its event queue: tracking events (`/push`, `/push/custom`, `track/stories`, `popup/showed`) are + * kept on disk and sent in order, repeated after failures and after a restart, for up to 7 days; + * their listeners hear the server's answer once the event went, or the error that dropped it, and an + * empty id is refused at once; [SDK.flush] sends the queue now; the stored tracking source goes on + * `/push` only, and a popup in an event's answer is shown only within 10 s of the event and in the + * foreground; + * - cookies: the new core's requests never send or keep a cookie. The legacy core's requests, and those + * of the stories v3 and popups v3 clients on either core, follow the app's global + * `java.net.CookieHandler`: an app that installs one (`CookieHandler.setDefault`) has them keep the + * cookies the server sets, the API's year-long `did` cookie among them, and send them back. */ - fun initialize(context: Context, config: Rees46Config): SDK = synchronized(lock) { + @BridgeApi + @JvmSynthetic + fun initializeBridge(context: Context, config: Rees46Config, segment: String? = null): SDK { + segment?.let { offerSegment(context, config, it) } + return initialize(context, config, coreV2 = true) + } + + /** + * [initialize] asking for the core of [coreV2]: the new one for [initializeBridge], which tests use + * through here too. The process's core decides ([CoreSelection]). + */ + internal fun initialize(context: Context, config: Rees46Config, coreV2: Boolean): SDK = synchronized(lock) { val existing = SdkRegistry.byShopId(config.shopId) if (existing != null && !existing.pushOnly) { + // The instance runs on the process's core: one that asks for the other hears it. + CoreSelection.resolve(coreV2, config.shopId) existing.keepConfig(config) pending.remove(config.shopId) return existing.handedToApp() @@ -65,7 +128,7 @@ object Rees46 { val sdk = SDK() // A shop brought up only to track a push gives way to the full instance once it is registered; the // push's tracking in flight still gets through. - sdk.initializeWith(context, config) + sdk.initializeWith(context, config, coreV2) // Removed once the instance is registered: a lookup meanwhile still finds the shop. pending.remove(config.shopId) sdk @@ -76,11 +139,22 @@ object Rees46 { * [instance] for a shop — the region case, where only the current region is needed. Pass * [eagerInit] = true to initialize every shop up front — the super-shop case, where instances must * stay consistent. + * + * The shops ask for the legacy core, and a registration decides the process's core as [initialize] + * does. */ fun register( context: Context, configs: List, eagerInit: Boolean = false + ) = register(context, configs, eagerInit, coreV2 = false) + + /** [register] asking for the core of [coreV2]: for tests, the bridges have [initializeBridge]. */ + internal fun register( + context: Context, + configs: List, + eagerInit: Boolean = false, + coreV2: Boolean, ) { val appContext = context.applicationContext // A lazily registered shop initializes on first use, usually after the first activity @@ -88,11 +162,11 @@ object Rees46 { ForegroundActivity.install(appContext) configs.forEach { config -> // A registration decides the process's core as an initialize does. - CoreSelection.resolve(config.coreV2, config.shopId) + CoreSelection.resolve(coreV2, config.shopId) if (eagerInit) { - initialize(appContext, config) + initialize(appContext, config, coreV2) } else { - pending[config.shopId] = PendingInit(appContext, config) + pending[config.shopId] = PendingInit(appContext, config, coreV2) } } } @@ -226,7 +300,7 @@ object Rees46 { * `shop_id` while several shops are registered, drops the push (`push_dropped`) instead of handing it * to the wrong shop. A shop registered without `eagerInit` is brought up just to send the event: the * app may have been started by the push itself. - * 3. The event goes to the shop. On the new core ([Rees46Config.coreV2]) through its queue to + * 3. The event goes to the shop. On the new core ([initializeBridge]) through its queue to * `track/delivered`, `track/opened`, `track/clicked` or `track/closed`, once per message in a process: * a repeat sends nothing and still returns the shop. A tap also sets the tracking source for 48 hours, * which the `/push` events carry as `source`. The legacy core sends a delivery to `track/received` @@ -431,10 +505,10 @@ object Rees46 { private fun materializeForPush(shopId: String): SDK? = synchronized(lock) { SdkRegistry.byShopId(shopId)?.let { return it } val pendingInit = pending[shopId] ?: return null - if (!CoreSelection.resolve(pendingInit.config.coreV2, shopId) && !legacyHasDid(pendingInit.context, pendingInit.config)) { + if (!CoreSelection.resolve(pendingInit.coreV2, shopId) && !legacyHasDid(pendingInit.context, pendingInit.config)) { return SDK().apply { initializeForPushWithoutDid(pendingInit.context, pendingInit.config) }.also { pending.remove(shopId) } } - SDK().apply { initializeForPush(pendingInit.context, pendingInit.config) }.also { pending.remove(shopId) } + SDK().apply { initializeForPush(pendingInit.context, pendingInit.config, pendingInit.coreV2) }.also { pending.remove(shopId) } } /** @@ -485,9 +559,9 @@ object Rees46 { if (live != null && !live.pushOnly) return live.handedToApp() val pendingInit = pending[shopId] when { - pendingInit != null -> initialize(pendingInit.context, pendingInit.config) + pendingInit != null -> initialize(pendingInit.context, pendingInit.config, pendingInit.coreV2) // Its config is set before it registers: an instance found in the registry has one. - live != null -> live.config?.let { initialize(live.context, it) } + live != null -> live.config?.let { initialize(live.context, it, live.coreV2Requested) } else -> null } } @@ -508,6 +582,37 @@ object Rees46 { return storage.storedDid().isNotEmpty() || storage.takesConfiguredDid(config.deviceId) } + /** + * The A/B group a bridge brings to [initializeBridge]: offered to the shop's one-shot move of its data to + * the device level ([StorageMigrations]), which takes it while neither the device nor the shop has a + * group. Runs before the shop's start, whose own run of the migrations then finds them done. Reads and + * writes the disk. + */ + private fun offerSegment(context: Context, config: Rees46Config, segment: String) { + if (segment !in DeviceStorage.SEGMENTS) { + SdkLogs.log( + LogLevel.WARNING, + LogCodes.INVALID_ARGUMENT, + "initializeBridge: the A/B group is not one the SDK gives; it is not taken", + config.shopId, + mapOf("reason" to LogReasons.INVALID_SEGMENT), + ) + return + } + val layout = StorageLayout(config.shopId, config.storageKey) + StorageMigrations.run(context, layout, segment = segment) + val kept = ShopStorage(context, layout).segment() ?: return + if (kept != segment) { + SdkLogs.log( + LogLevel.WARNING, + LogCodes.INVALID_CONFIG, + "initializeBridge: the A/B group is not taken: the device keeps the one it has", + config.shopId, + mapOf("reason" to LogReasons.SEGMENT_KEPT), + ) + } + } + private fun registeredShopIds(): List = (SdkRegistry.shopIds() + pending.keys).sorted() diff --git a/personalization-sdk/src/main/kotlin/com/personalization/Rees46Config.kt b/personalization-sdk/src/main/kotlin/com/personalization/Rees46Config.kt index 98038006..572f65ad 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/Rees46Config.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/Rees46Config.kt @@ -1,5 +1,9 @@ package com.personalization +import com.personalization.logs.LogCodes +import com.personalization.logs.LogReasons +import com.personalization.logs.SdkLogs + /** * Configuration for one SDK instance (one shop). * @@ -19,32 +23,6 @@ package com.personalization * while no [SDK.popupPresentationListener] is set. * @property logLevel how much this shop's instance writes to the log; [LogLevel.WARNING] by default. * Messages that pass it also reach [Rees46.setLogHandler]. - * @property coreV2 runs the instance on the new core; off by default. The process has one core: the - * first [Rees46.initialize] or [Rees46.register] decides it, and an instance that asks for the other - * one runs on the process's and logs `core_flag_mismatch`. The new core differs in: - * - its network client: requests go through OkHttp, a request without a network fails at once, - * `release()` cancels the instance's requests, and a failure without an answer is `onError(-1)` (no - * connection used to be `504`), as is a `2xx` whose body is not JSON (it used to succeed empty); - * - its `/init`: repeated with growing pauses until it gets an answer; a shop that answers `402`, - * `403`, `404` or another `4xx` is refused ([com.personalization.core.SdkState.REFUSED]) until a - * later launch's `/init` succeeds, and every request of a refused shop fails with `onError(402)`; - * - a request waits until the instance is ready, within its own read timeout, instead of going out - * without a `did`: a new device's first requests fail with `onError(-1)` if `/init` does not answer - * in time; - * - [needReInitialization] really gives the device a new `did`; [stream] goes with `/init` too; the - * advertising id is read and sent only with [sendAdvertisingId]; - * - its session: the `sid` is the server's, and a session two hours without events ends — the next - * request or event sends `/init` first; requests with a result no longer extend it; - * - its event queue: tracking events (`/push`, `/push/custom`, `track/stories`, `popup/showed`) are - * kept on disk and sent in order, repeated after failures and after a restart, for up to 7 days; - * their listeners hear the server's answer once the event went, or the error that dropped it, and an - * empty id is refused at once; [SDK.flush] sends the queue now; the stored tracking source goes on - * `/push` only, and a popup in an event's answer is shown only within 10 s of the event and in the - * foreground; - * - cookies: the new core's requests never send or keep a cookie. The legacy core's requests, and those - * of the stories v3 and popups v3 clients on either core, follow the app's global - * `java.net.CookieHandler`: an app that installs one (`CookieHandler.setDefault`) has them keep the - * cookies the server sets, the API's year-long `did` cookie among them, and send them back. * @property deviceId a `did` the app already keeps, from another SDK or an earlier version of it: taken * only while the shop has no `did` of its own, and sent with the next `/init`. Ignored with * [needReInitialization]. @@ -62,6 +40,14 @@ package com.personalization * Auto Backup restores these files on the user's new device, the `did` among them; see * [SDK.deleteUserCredentials] for the files an app excludes from its backup rules to avoid that. * + * Nothing here picks the core: [Rees46.initialize] and [Rees46.register] ask for the legacy one, and + * the new core is for the SDK's Flutter and React Native bridges, which start it with + * [Rees46.initializeBridge]. The process runs one core: the first of them decides it. + * + * Cookies: the legacy core's requests, and those of the stories v3 and popups v3 clients, follow the + * app's global `java.net.CookieHandler`: an app that installs one (`CookieHandler.setDefault`) has them + * keep the cookies the server sets, the API's year-long `did` cookie among them, and send them back. + * * Constructors are overloaded for Java: every trailing parameter with a default may be left out, so * Java code written against the seven-argument constructor keeps compiling as parameters are added. */ @@ -75,8 +61,71 @@ data class Rees46Config @JvmOverloads constructor( val tag: String = "SDK", val enableAutoPopupPresentation: Boolean = true, val logLevel: LogLevel = LogLevel.WARNING, - val coreV2: Boolean = false, val storageKey: String? = null, val deviceId: String? = null, val sendAdvertisingId: Boolean = false, -) +) { + + /** + * The constructor of the releases with `coreV2`, for apps built against them: `coreV2` is ignored, + * and `true` is logged as `invalid_config` (`bridge_only`). Source that passes it no longer compiles. + */ + @Deprecated(message = BRIDGE_ONLY_CORE, level = DeprecationLevel.HIDDEN) + constructor( + shopId: String, + apiDomain: String = "api.rees46.ru", + stream: String = "android", + autoSendPushToken: Boolean = true, + needReInitialization: Boolean = false, + addTrailingSlash: Boolean = true, + tag: String = "SDK", + enableAutoPopupPresentation: Boolean = true, + logLevel: LogLevel = LogLevel.WARNING, + coreV2: Boolean = false, + storageKey: String? = null, + deviceId: String? = null, + sendAdvertisingId: Boolean = false, + ) : this( + shopId, apiDomain, stream, autoSendPushToken, needReInitialization, addTrailingSlash, tag, + enableAutoPopupPresentation, logLevel, storageKey, deviceId, sendAdvertisingId, + ) { + if (coreV2) ignoredCoreV2(shopId) + } + + /** The `copy` of the releases with `coreV2`, for apps built against them; `coreV2` is ignored as above. */ + @Deprecated(message = BRIDGE_ONLY_CORE, level = DeprecationLevel.HIDDEN) + fun copy( + shopId: String = this.shopId, + apiDomain: String = this.apiDomain, + stream: String = this.stream, + autoSendPushToken: Boolean = this.autoSendPushToken, + needReInitialization: Boolean = this.needReInitialization, + addTrailingSlash: Boolean = this.addTrailingSlash, + tag: String = this.tag, + enableAutoPopupPresentation: Boolean = this.enableAutoPopupPresentation, + logLevel: LogLevel = this.logLevel, + coreV2: Boolean = false, + storageKey: String? = this.storageKey, + deviceId: String? = this.deviceId, + sendAdvertisingId: Boolean = this.sendAdvertisingId, + ): Rees46Config { + if (coreV2) ignoredCoreV2(shopId) + return copy( + shopId, apiDomain, stream, autoSendPushToken, needReInitialization, addTrailingSlash, tag, + enableAutoPopupPresentation, logLevel, storageKey, deviceId, sendAdvertisingId, + ) + } + + private companion object { + const val BRIDGE_ONLY_CORE = "Rees46Config.coreV2 is gone: the new core is for the SDK's Flutter and " + + "React Native bridges, which start it with Rees46.initializeBridge." + + fun ignoredCoreV2(shopId: String) = SdkLogs.log( + LogLevel.WARNING, + LogCodes.INVALID_CONFIG, + "Rees46Config.coreV2 is ignored: the new core is the SDK's bridges', and this config asks for the legacy one", + shopId, + mapOf("reason" to LogReasons.BRIDGE_ONLY), + ) + } +} diff --git a/personalization-sdk/src/main/kotlin/com/personalization/SDK.kt b/personalization-sdk/src/main/kotlin/com/personalization/SDK.kt index b2a36bce..1baa8ef4 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/SDK.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/SDK.kt @@ -358,7 +358,10 @@ open class SDK { /** The level of this instance's log; [Rees46Config.logLevel] sets it for instances made through [Rees46]. */ internal var logLevel: LogLevel = LogLevel.WARNING - /** [Rees46Config.coreV2] of the instance; the process's core decides ([CoreSelection]). */ + /** + * Whether the instance asked for the new core ([Rees46.initializeBridge]); the process's core decides + * ([CoreSelection]). + */ internal var coreV2Requested: Boolean = false /** The instance's core, once it is initialized: the legacy one or [CoreV2]. */ @@ -483,19 +486,21 @@ open class SDK { tag = tag, enableAutoPopupPresentation = enableAutoPopupPresentation, logLevel = logLevel, - coreV2 = coreV2Requested, storageKey = preferencesKey.takeUnless { it == PreferencesPartition.LEGACY_KEY }, - ) + ), + coreV2 = coreV2Requested, ) /** - * Initializes this object for [config]: the entry of [Rees46.initialize] and of the legacy - * [initialize]. An object live for the same shop is left as it is: it keeps the config it was made - * with, and a different [config] is logged as `invalid_config` (`already_initialized`). + * Initializes this object for [config], asking for the new core with [coreV2]: the entry of + * [Rees46.initialize], [Rees46.initializeBridge] and of the legacy [initialize]. An object live for the + * same shop is left as it is: it keeps the config it was made with, and a different [config] is logged + * as `invalid_config` (`already_initialized`). */ - internal fun initializeWith(context: Context, config: Rees46Config) = start( + internal fun initializeWith(context: Context, config: Rees46Config, coreV2: Boolean = false) = start( context, config, + coreV2, autoSendPushToken = config.autoSendPushToken, needReInitialization = config.needReInitialization, pushOnly = false, @@ -510,9 +515,10 @@ open class SDK { * app's first [Rees46.instance] or [Rees46.initialize] of the shop puts a full instance in its place, * and an initialize of this object makes it one. */ - internal fun initializeForPush(context: Context, config: Rees46Config) = start( + internal fun initializeForPush(context: Context, config: Rees46Config, coreV2: Boolean) = start( context, config, + coreV2, autoSendPushToken = false, needReInitialization = false, pushOnly = true, @@ -527,6 +533,7 @@ open class SDK { internal fun initializeForPushWithoutDid(context: Context, config: Rees46Config) = start( context, config, + coreV2 = false, autoSendPushToken = false, needReInitialization = false, pushOnly = false, @@ -549,6 +556,7 @@ open class SDK { private fun start( context: Context, config: Rees46Config, + coreV2: Boolean, autoSendPushToken: Boolean, needReInitialization: Boolean, pushOnly: Boolean, @@ -565,7 +573,7 @@ open class SDK { } enableAutoPopupPresentation = config.enableAutoPopupPresentation logLevel = config.logLevel - coreV2Requested = config.coreV2 + coreV2Requested = coreV2 // Both before the instance registers: a push-only one wakes nobody waiting for the shop's // instance, and whoever finds it in the registry has the config to put a full one in its place. this.pushOnly = pushOnly @@ -1143,7 +1151,7 @@ open class SDK { * request's old callback gets `onError(-1)` (a request still waiting for a `did` too), and * [deleteUserCredentials] throws [SdkException] without deleting anything or asking `/init`. * [state] is [SdkState.NOT_INITIALIZED]: the state listeners hear it and are dropped. On the new - * core ([Rees46Config.coreV2]) the requests in flight are cancelled (`onError(-1)`) and `/init` + * core ([Rees46.initializeBridge]) the requests in flight are cancelled (`onError(-1)`) and `/init` * stops; the legacy one cannot cancel a request in flight. The shop's data stays on the device, and * a new [Rees46.initialize] for the shop makes a fresh instance. */ diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/managers/TrackEventManager.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/TrackEventManager.kt index 44aadd58..9cf64e52 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/api/managers/TrackEventManager.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/TrackEventManager.kt @@ -8,7 +8,7 @@ import com.personalization.api.models.purchase.PurchaseTrackingRequest /** * The tracking methods of earlier releases; [TrackingApi] (`sdk.tracking`) replaces them. * - * On the new core (`Rees46Config.coreV2`) every event goes through the queue: the method returns at + * On the new core (`Rees46.initializeBridge`) every event goes through the queue: the method returns at * once, and a `listener` is kept until the event is sent — after a launch without a network that may be * as long as the queue keeps an event, 7 days — then hears the server's answer, or the error that * dropped the event. Whatever the listener holds stays alive that long. diff --git a/personalization-sdk/src/main/kotlin/com/personalization/api/managers/TrackingApi.kt b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/TrackingApi.kt index 7e957175..21dfc7e8 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/api/managers/TrackingApi.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/api/managers/TrackingApi.kt @@ -10,7 +10,7 @@ import com.personalization.api.models.tracking.TrackingSource * * Reached through an SDK instance: `Rees46.instance().tracking.productView("sku-1")`. * - * On the new core (`Rees46Config.coreV2`) every event goes through the queue: the method returns at + * On the new core (`Rees46.initializeBridge`) every event goes through the queue: the method returns at * once, and a `listener` is kept until the event is sent — after a launch without a network that may be * as long as the queue keeps an event, 7 days — then hears the server's answer, or the error that * dropped the event. An event the queue refuses at once (an empty id, a released instance, a refused diff --git a/personalization-sdk/src/main/kotlin/com/personalization/core/BridgeApi.kt b/personalization-sdk/src/main/kotlin/com/personalization/core/BridgeApi.kt index 914be0f6..696245eb 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/core/BridgeApi.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/core/BridgeApi.kt @@ -1,9 +1,9 @@ package com.personalization.core /** - * Members for the Flutter and React Native bridges, not for apps: the bridges forward the native SDK's - * events and errors to Dart and JavaScript without losing anything, and apps get the same things - * through the public API (`onStateChange`, `PushCallbacks`, the old listeners). + * Members for the Flutter and React Native bridges, not for apps: the bridges start their shops on the + * new core, and forward the native SDK's events and errors to Dart and JavaScript without losing + * anything; apps get those through the public API (`onStateChange`, `PushCallbacks`, the old listeners). * * What it marks may change in any release, without a deprecation. A bridge opts in once per module: * @@ -14,6 +14,8 @@ package com.personalization.core * ``` * * The members: + * - `Rees46.initializeBridge` — a shop on the new core, which apps cannot pick, with the A/B group the + * bridge kept for the device; * - `SDK.onSessionChange` — every new `sid` of the new core; * - `Rees46.onPushEvent` and `Rees46.onPushToken` — every push event and token the SDK sees, beside the * app's `PushCallbacks`; diff --git a/personalization-sdk/src/main/kotlin/com/personalization/core/SdkState.kt b/personalization-sdk/src/main/kotlin/com/personalization/core/SdkState.kt index 016b2683..52a1574b 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/core/SdkState.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/core/SdkState.kt @@ -4,8 +4,8 @@ package com.personalization.core * Where an instance's initialization (`/init`) stands. Read it from `SDK.state`, follow it with * `SDK.onStateChange`. * - * On the legacy core (`Rees46Config.coreV2 = false`) an instance only goes from [INITIALIZING] to - * [READY]; it is never [RETRYING] or [REFUSED]. + * On the legacy core (`Rees46.initialize`) an instance only goes from [INITIALIZING] to [READY]; it is + * never [RETRYING] or [REFUSED]. */ enum class SdkState { /** Not initialized yet, or released with `release()`: every call fails with `notInitialized`. */ diff --git a/personalization-sdk/src/main/kotlin/com/personalization/core/internal/Core.kt b/personalization-sdk/src/main/kotlin/com/personalization/core/internal/Core.kt index 25e3cffb..81caf9dc 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/core/internal/Core.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/core/internal/Core.kt @@ -10,8 +10,8 @@ import org.json.JSONObject * `SendNetworkMethodUseCase`) hands every request to the instance's core, so the namespaces are the * same code for both cores. * - * [LegacyCore] keeps today's paths. [CoreV2] is the new core, chosen by `Rees46Config.coreV2`: its own - * client, `/init` ([CoreInit]), session ([SessionWindow]) and event queue ([EventQueue]). + * [LegacyCore] keeps today's paths. [CoreV2] is the new core, the bridges' (`Rees46.initializeBridge`): its + * own client, `/init` ([CoreInit]), session ([SessionWindow]) and event queue ([EventQueue]). */ internal interface Core { diff --git a/personalization-sdk/src/main/kotlin/com/personalization/core/internal/CoreSelection.kt b/personalization-sdk/src/main/kotlin/com/personalization/core/internal/CoreSelection.kt index 906f458c..eb865509 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/core/internal/CoreSelection.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/core/internal/CoreSelection.kt @@ -5,10 +5,10 @@ import com.personalization.logs.LogCodes import com.personalization.logs.SdkLogs /** - * Which core the process runs: decided by the first `initialize` or `register`, the same for every - * instance after it. An instance that asks for the other one gets the process's and a - * `core_flag_mismatch` warning, once per shop (a registration and the instance it makes later ask - * twice): switching takes a new launch. + * Which core the process runs: decided by the first `initialize`, `register` or `initializeBridge` + * (the new core), the same for every instance after it. An instance that asks for the other one gets + * the process's and a `core_flag_mismatch` warning, once per shop (a registration and the instance it + * makes later ask twice): switching takes a new launch. */ internal object CoreSelection { @@ -25,7 +25,7 @@ internal object CoreSelection { SdkLogs.log( LogLevel.WARNING, LogCodes.CORE_FLAG_MISMATCH, - "Rees46Config.coreV2 differs from the process's core; the instance runs on the process's", + "The instance asks for a core other than the process's; it runs on the process's", shopId, mapOf("requested" to requested, "process" to decided) ) diff --git a/personalization-sdk/src/main/kotlin/com/personalization/core/internal/DeviceStorage.kt b/personalization-sdk/src/main/kotlin/com/personalization/core/internal/DeviceStorage.kt index d8bd1f2e..7d9ab50e 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/core/internal/DeviceStorage.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/core/internal/DeviceStorage.kt @@ -64,6 +64,9 @@ internal class DeviceStorage(context: Context) { const val SEGMENT = StorageKeys.SEGMENT + /** The two groups of the server's A/B tests: the only values the SDK gives a device. */ + val SEGMENTS: List = listOf("A", "B") + /** One lock for the process: the instances of every shop share the file. */ private val LOCK = Any() } diff --git a/personalization-sdk/src/main/kotlin/com/personalization/core/internal/ShopStorage.kt b/personalization-sdk/src/main/kotlin/com/personalization/core/internal/ShopStorage.kt index b1302634..7e3cc327 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/core/internal/ShopStorage.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/core/internal/ShopStorage.kt @@ -115,6 +115,9 @@ internal class ShopStorage(context: Context, val layout: StorageLayout) { return taken } + /** The A/B group the shop sends, as its partition holds it; null before the shop has one. */ + fun segment(): String? = preferences.getString(StorageKeys.SEGMENT, null)?.takeIf { it.isNotEmpty() } + /** The shop's `did` as its partition holds it; empty when there is none. */ fun storedDid(): String = preferences.getString(StorageKeys.DID, null).orEmpty() diff --git a/personalization-sdk/src/main/kotlin/com/personalization/core/internal/StorageMigrations.kt b/personalization-sdk/src/main/kotlin/com/personalization/core/internal/StorageMigrations.kt index eedb257f..8bb479df 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/core/internal/StorageMigrations.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/core/internal/StorageMigrations.kt @@ -22,15 +22,20 @@ import com.personalization.logs.SdkLogs * as before; the flag keeps a shop from taking it again after its data was deleted. * 3. **The device level** ([DeviceStorage]): the shop offers its A/B group, push tokens and advertising * id, which the device takes while it has none of its own. A shop without an A/B group takes the - * device's, so every new shop of the device sends the same group. + * device's, so every new shop of the device sends the same group; a device without one takes the + * group a bridge kept for it (`Rees46.initializeBridge`), or else a random one. * * The writes go through `apply()`: the copy and its flag are one write, so a crash loses both or * neither, and the next start runs the migration again. */ internal object StorageMigrations { - /** Runs what has not run yet for [layout]'s shop. A failure is logged and never stops the start. */ - fun run(context: Context, layout: StorageLayout, device: DeviceStorage = DeviceStorage(context)) { + /** + * Runs what has not run yet for [layout]'s shop. A failure is logged and never stops the start. + * [segment] is the A/B group a bridge kept for the device, one of [DeviceStorage.SEGMENTS]: the device + * takes it while neither it nor the shop has a group. + */ + fun run(context: Context, layout: StorageLayout, device: DeviceStorage = DeviceStorage(context), segment: String? = null) { val shopId = layout.shopId val partition = open(context, layout.partitionName, shopId, OP_OPEN_PARTITION) ?: return layout.namedFile?.let { name -> @@ -39,7 +44,7 @@ internal object StorageMigrations { } } layout.legacyFile?.let { name -> step(shopId, OP_MIGRATE_LEGACY_FILE) { migrateLegacyFile(context, name, partition, shopId) } } - step(shopId, OP_MIGRATE_DEVICE_LEVEL) { adoptDeviceLevel(partition, device) } + step(shopId, OP_MIGRATE_DEVICE_LEVEL) { adoptDeviceLevel(partition, device, segment) } } private fun migrateLegacyFile(context: Context, legacyName: String, partition: SharedPreferences, shopId: String) { @@ -80,7 +85,7 @@ internal object StorageMigrations { editor.putBoolean(flag, true).apply() } - private fun adoptDeviceLevel(partition: SharedPreferences, device: DeviceStorage) { + private fun adoptDeviceLevel(partition: SharedPreferences, device: DeviceStorage, offeredSegment: String?) { if (partition.getBoolean(StorageKeys.MIGRATED_DEVICE_LEVEL, false)) return val editor = partition.edit() val segment = partition.getString(StorageKeys.SEGMENT, null)?.takeIf { it.isNotEmpty() } @@ -88,7 +93,7 @@ internal object StorageMigrations { // The shop keeps sending its own group; the device takes it if it is the first. device.adoptSegment(segment) } else { - editor.putString(StorageKeys.SEGMENT, device.adoptSegment(randomSegment())) + editor.putString(StorageKeys.SEGMENT, device.adoptSegment(offeredSegment ?: randomSegment())) } StorageKeys.PUSH_PROVIDERS.forEach { provider -> val token = partition.getString(StorageKeys.pushToken(provider), null)?.takeIf { it.isNotEmpty() } @@ -100,7 +105,7 @@ internal object StorageMigrations { } /** The two groups of the server's A/B tests, picked at random once per device. */ - internal fun randomSegment(): String = arrayOf("A", "B").random() + internal fun randomSegment(): String = DeviceStorage.SEGMENTS.random() private fun open(context: Context, name: String, shopId: String, op: String): SharedPreferences? = try { context.applicationContext.getSharedPreferences(name, Context.MODE_PRIVATE) diff --git a/personalization-sdk/src/main/kotlin/com/personalization/features/notification/presentation/helpers/NotificationHelper.kt b/personalization-sdk/src/main/kotlin/com/personalization/features/notification/presentation/helpers/NotificationHelper.kt index dbaae3ab..84ee021f 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/features/notification/presentation/helpers/NotificationHelper.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/features/notification/presentation/helpers/NotificationHelper.kt @@ -42,7 +42,7 @@ class NotificationHelper @Inject constructor( /** * Draws [data] as a notification. * - * On the new core ([com.personalization.Rees46Config.coreV2]), a push of the SDK — one with an `id` and + * On the new core ([com.personalization.Rees46.initializeBridge]), a push of the SDK — one with an `id` and * a `type` — is reported as shown (`Rees46.handlePush(push, PushEvent.OPENED)`: `track/opened` and the * `onOpened` callback) and its dismissal without a tap as closed (`track/closed`, `onClosed`), for the * shop the push names in its `shop_id`. The callbacks get the whole push as the SDK received it. A push diff --git a/personalization-sdk/src/main/kotlin/com/personalization/logs/SdkLogs.kt b/personalization-sdk/src/main/kotlin/com/personalization/logs/SdkLogs.kt index f4880e80..751b6cf9 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/logs/SdkLogs.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/logs/SdkLogs.kt @@ -227,6 +227,18 @@ internal object LogReasons { /** `Rees46Config.deviceId` not taken because the shop has a `did` of its own (`invalid_config`, once per shop). */ const val DEVICE_ID_KEPT = "device_id_kept" + + /** The A/B group a bridge brought to `Rees46.initializeBridge` not taken: the device has its own (`invalid_config`). */ + const val SEGMENT_KEPT = "segment_kept" + + /** The A/B group a bridge brought is none the SDK gives, `A` or `B` (`invalid_argument`). */ + const val INVALID_SEGMENT = "invalid_segment" + + /** + * `coreV2 = true` from an app built against the releases that had `Rees46Config.coreV2`: the new core is the + * bridges' (`invalid_config`). + */ + const val BRIDGE_ONLY = "bridge_only" const val NOT_READY = "not_ready" /** A shop brought up only for a push has no `did`: its event cannot go (`push_dropped`). */ diff --git a/personalization-sdk/src/main/kotlin/com/personalization/sdk/data/repositories/userSettings/UserSettings.repository.impl.kt b/personalization-sdk/src/main/kotlin/com/personalization/sdk/data/repositories/userSettings/UserSettings.repository.impl.kt index f9fbdd9b..63057c21 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/sdk/data/repositories/userSettings/UserSettings.repository.impl.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/sdk/data/repositories/userSettings/UserSettings.repository.impl.kt @@ -1,5 +1,6 @@ package com.personalization.sdk.data.repositories.userSettings +import com.personalization.core.internal.DeviceStorage import com.personalization.core.internal.StorageKeys import com.personalization.sdk.data.repositories.preferences.PreferencesDataSource import com.personalization.sdk.data.utils.AdvertisingUtils @@ -119,5 +120,5 @@ class UserSettingsRepositoryImpl @Inject constructor( ) } - private fun generateRandomSegmentValue(): String = arrayOf("A", "B").random() + private fun generateRandomSegmentValue(): String = DeviceStorage.SEGMENTS.random() } diff --git a/personalization-sdk/src/test/java/com/personalization/Rees46ConfigJavaTest.java b/personalization-sdk/src/test/java/com/personalization/Rees46ConfigJavaTest.java index 152ba298..71dfaebd 100644 --- a/personalization-sdk/src/test/java/com/personalization/Rees46ConfigJavaTest.java +++ b/personalization-sdk/src/test/java/com/personalization/Rees46ConfigJavaTest.java @@ -28,22 +28,13 @@ public void trailingDefaultsMayBeLeftOut() { assertEquals("api.rees46.ru", config.getApiDomain()); assertEquals("SDK", config.getTag()); - assertFalse(config.getCoreV2()); + assertEquals(LogLevel.WARNING, config.getLogLevel()); } @Test - public void theNewCoreKeepsItsPlace() { + public void theStorageKeyFollowsTheLogLevel() { Rees46Config config = new Rees46Config( - "shop", "api.rees46.ru", "android", true, false, true, "SDK", true, LogLevel.WARNING, true); - - assertTrue(config.getCoreV2()); - assertNull(config.getStorageKey()); - } - - @Test - public void theStorageKeyKeepsItsPlace() { - Rees46Config config = new Rees46Config( - "shop", "api.rees46.ru", "android", true, false, true, "SDK", true, LogLevel.WARNING, false, "host"); + "shop", "api.rees46.ru", "android", true, false, true, "SDK", true, LogLevel.WARNING, "host"); assertEquals("host", config.getStorageKey()); assertNull(config.getDeviceId()); @@ -53,7 +44,7 @@ public void theStorageKeyKeepsItsPlace() { @Test public void theDeviceIdAndTheAdvertisingIdComeLast() { Rees46Config config = new Rees46Config( - "shop", "api.rees46.ru", "android", true, false, true, "SDK", true, LogLevel.WARNING, false, null, + "shop", "api.rees46.ru", "android", true, false, true, "SDK", true, LogLevel.WARNING, null, "did-from-rn", true); assertEquals("did-from-rn", config.getDeviceId()); diff --git a/personalization-sdk/src/test/kotlin/com/personalization/BridgeInitTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/BridgeInitTest.kt new file mode 100644 index 00000000..d0ca70f6 --- /dev/null +++ b/personalization-sdk/src/test/kotlin/com/personalization/BridgeInitTest.kt @@ -0,0 +1,359 @@ +package com.personalization + +import android.content.Context +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import androidx.test.core.app.ApplicationProvider +import com.personalization.api.OnApiCallbackListener +import com.personalization.core.BridgeApi +import com.personalization.core.SdkState +import com.personalization.core.internal.CoreSelection +import com.personalization.core.internal.CoreV2 +import com.personalization.core.internal.DeviceStorage +import com.personalization.core.internal.LegacyCore +import com.personalization.core.internal.ShopStorage +import com.personalization.core.internal.StorageKeys +import com.personalization.core.internal.StorageLayout +import com.personalization.core.internal.TrackingThreads +import com.personalization.logs.LogCodes +import com.personalization.logs.LogReasons +import com.personalization.logs.SdkLogs +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import okhttp3.HttpUrl +import okhttp3.mockwebserver.Dispatcher +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import okhttp3.mockwebserver.RecordedRequest +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.shadows.ShadowNetworkCapabilities +import java.io.File +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.Executor +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit + +/** + * The new core is the bridges': [Rees46.initializeBridge] starts a shop on it, with the A/B group the bridge + * kept for the device, while [Rees46.initialize], [Rees46.register] and [Rees46Config] give apps no way to it. + */ +@OptIn(BridgeApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class BridgeInitTest { + + private lateinit var context: Context + private var server = MockWebServer() + private val logged = CopyOnWriteArrayList() + private val defaultExecutor = SdkLogs.handlerExecutor + private val requests = LinkedBlockingQueue() + private val threads = TrackingThreads() + + @Before + fun setUp() { + context = ApplicationProvider.getApplicationContext() + CoreSelection.reset() + SdkRegistry.reset() + Rees46.reset() + SdkLogs.reset() + SdkLogs.handlerExecutor = Executor { it.run() } + SdkLogs.handler = SdkLogHandler { logged += it } + logged.clear() + wipeStorage() + // Robolectric's default network has no internet capability: give it one, as a device's has. + val manager = context.getSystemService(ConnectivityManager::class.java) + val capabilities = ShadowNetworkCapabilities.newInstance() + shadowOf(capabilities).addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) + shadowOf(manager).setNetworkCapabilities(manager.activeNetwork, capabilities) + server = MockWebServer() + requests.clear() + LegacyCore.threads = threads + server.dispatcher = object : Dispatcher() { + override fun dispatch(request: RecordedRequest): MockResponse { + val url = request.requestUrl ?: return MockResponse().setResponseCode(400) + requests += url + if (url.encodedPath != "/init") return MockResponse().setBody("{}") + return MockResponse().setBody(JSONObject().put("did", "new-did").put("seance", "S").toString()) + } + } + server.start() + } + + @After + fun tearDown() { + SdkRegistry.all().forEach { it.release() } + server.shutdown() + LegacyCore.threads = LegacyCore.DEFAULT_THREADS + CoreSelection.reset() + SdkRegistry.reset() + Rees46.reset() + SdkLogs.reset() + SdkLogs.handlerExecutor = defaultExecutor + } + + /** A device that never ran the SDK: no partition, no device level, no files. */ + private fun wipeStorage() { + listOf(SHOP, OTHER).forEach { partition(it).edit().clear().commit() } + listOf(PreferencesPartition.LEGACY_KEY, DeviceStorage.NAME).forEach { context.getSharedPreferences(it, Context.MODE_PRIVATE).edit().clear().commit() } + File(context.noBackupFilesDir, ShopStorage.ROOT_DIRECTORY).deleteRecursively() + } + + private fun config(shopId: String = SHOP) = Rees46Config( + shopId = shopId, + apiDomain = server.url("/").toString().trimEnd('/'), + autoSendPushToken = false, + logLevel = LogLevel.DEBUG, + ) + + private fun partition(shopId: String = SHOP) = + context.getSharedPreferences(StorageLayout(shopId, null).partitionName, Context.MODE_PRIVATE) + + private fun deviceSegment(): String? = DeviceStorage(context).segment() + + private fun awaitReady(sdk: SDK) = runBlocking { + withTimeout(5_000) { sdk.instanceState.changes.first { it == SdkState.READY } } + } + + /** Starts over on a device that never ran the SDK, as a new launch of a new install. */ + private fun freshDevice() { + tearDown() + setUp() + } + + private fun logs(code: String, reason: String) = + logged.filter { it.code == code && it.context["reason"] == reason } + + // The core. + + @Test + fun `a bridge's shop runs on the new core, and decides the process's`() { + val sdk = Rees46.initializeBridge(context, config()) + + assertTrue(sdk.core is CoreV2) + assertEquals(true, CoreSelection.decided()) + assertTrue(Rees46.instance(SHOP) === sdk) + awaitReady(sdk) + assertFalse(logged.any { it.code == LogCodes.CORE_FLAG_MISMATCH }) + } + + @Test + fun `an app's initialize and register stay on the legacy core`() { + val sdk = Rees46.initialize(context, config()) + Rees46.register(context, listOf(config(OTHER))) + + assertTrue(sdk.core is LegacyCore) + assertTrue(Rees46.instance(OTHER).core is LegacyCore) + assertEquals(false, CoreSelection.decided()) + assertFalse(logged.any { it.code == LogCodes.CORE_FLAG_MISMATCH }) + } + + @Test + fun `the process keeps the core its first instance asked for, on either side, and warns once`() { + Rees46.initialize(context, config()) + val bridge = Rees46.initializeBridge(context, config(OTHER)) + + assertTrue(bridge.core is LegacyCore) + assertEquals(1, logged.count { it.code == LogCodes.CORE_FLAG_MISMATCH && it.shopId == OTHER }) + + freshDevice() + Rees46.initializeBridge(context, config()) + val app = Rees46.initialize(context, config(OTHER)) + + assertTrue(app.core is CoreV2) + assertEquals(1, logged.count { it.code == LogCodes.CORE_FLAG_MISMATCH && it.shopId == OTHER }) + } + + @Test + fun `a bridge asking again for a shop the app made gets that instance, on its core, and the mismatch is logged`() { + val app = Rees46.initialize(context, config()) + + val bridge = Rees46.initializeBridge(context, config()) + + assertTrue(bridge === app) + assertTrue(bridge.core is LegacyCore) + assertEquals(1, logged.count { it.code == LogCodes.CORE_FLAG_MISMATCH && it.shopId == SHOP }) + } + + // The A/B group a bridge kept. + + @Test + fun `a device without an A B group takes the bridge's, and the shop's requests carry it`() { + // Twice each: a random pick would match a value by chance, not every time. + listOf("A", "B", "A", "B").forEach { segment -> + freshDevice() + + val sdk = Rees46.initializeBridge(context, config(), segment) + + assertEquals(segment, deviceSegment()) + assertEquals(segment, partition().getString(StorageKeys.SEGMENT, null)) + assertEquals(segment, sdk.getSegment()) + assertTrue(logged.none { it.code == LogCodes.INVALID_CONFIG || it.code == LogCodes.INVALID_ARGUMENT }) + } + val sdk = Rees46.instance(SHOP) + awaitReady(sdk) + val answered = LinkedBlockingQueue() + @Suppress("DEPRECATION") + sdk.getAsync("products/get", JSONObject(), object : OnApiCallbackListener() { + override fun onSuccess(response: JSONObject?) { + answered += "success" + } + + override fun onError(code: Int, msg: String?) { + answered += "error:$code" + } + }) + assertEquals("success", answered.poll(10, TimeUnit.SECONDS)) + val request = generateSequence { requests.poll(5, TimeUnit.SECONDS) }.first { it.encodedPath == "/products/get" } + assertEquals("B", request.queryParameter("segment")) + } + + @Test + fun `a device with its own group keeps it, and a different group from the bridge is logged`() { + context.getSharedPreferences(DeviceStorage.NAME, Context.MODE_PRIVATE).edit().putString(DeviceStorage.SEGMENT, "A").commit() + + val sdk = Rees46.initializeBridge(context, config(), "B") + + assertEquals("A", sdk.getSegment()) + assertEquals("A", deviceSegment()) + val kept = logs(LogCodes.INVALID_CONFIG, LogReasons.SEGMENT_KEPT).single() + assertEquals(LogLevel.WARNING, kept.level) + assertEquals(SHOP, kept.shopId) + } + + @Test + fun `the bridge's group equal to the device's is taken silently`() { + context.getSharedPreferences(DeviceStorage.NAME, Context.MODE_PRIVATE).edit().putString(DeviceStorage.SEGMENT, "B").commit() + + val sdk = Rees46.initializeBridge(context, config(), "B") + + assertEquals("B", sdk.getSegment()) + assertTrue(logs(LogCodes.INVALID_CONFIG, LogReasons.SEGMENT_KEPT).isEmpty()) + } + + @Test + fun `a shop that has a group from an earlier release keeps it and gives it to the device`() { + partition().edit().putString(StorageKeys.SEGMENT, "A").commit() + + val sdk = Rees46.initializeBridge(context, config(), "B") + + assertEquals("A", sdk.getSegment()) + assertEquals("A", deviceSegment()) + assertEquals(1, logs(LogCodes.INVALID_CONFIG, LogReasons.SEGMENT_KEPT).size) + } + + @Test + fun `a later launch keeps the group the device took, whatever the bridge brings then`() { + Rees46.initializeBridge(context, config(), "B") + SdkRegistry.all().forEach { it.release() } + CoreSelection.reset() + + val again = Rees46.initializeBridge(context, config(), "A") + + assertEquals("B", again.getSegment()) + assertEquals("B", deviceSegment()) + assertEquals(1, logs(LogCodes.INVALID_CONFIG, LogReasons.SEGMENT_KEPT).size) + } + + @Test + fun `the device's group taken from one shop's bridge goes to the other shops`() { + Rees46.initializeBridge(context, config(), "B") + + val other = Rees46.initializeBridge(context, config(OTHER)) + + assertEquals("B", other.getSegment()) + } + + @Test + fun `a group the SDK never gives is refused with a log, and the shop starts with a group of its own`() { + listOf("", " ", "C", "a", " A", "AB", "null").forEach { segment -> + freshDevice() + + val sdk = Rees46.initializeBridge(context, config(), segment) + + assertTrue("'$segment'", sdk.core is CoreV2) + val refused = logs(LogCodes.INVALID_ARGUMENT, LogReasons.INVALID_SEGMENT).single() + assertEquals(LogLevel.WARNING, refused.level) + assertEquals(SHOP, refused.shopId) + assertTrue("'$segment'", sdk.getSegment() in DeviceStorage.SEGMENTS) + assertTrue("'$segment'", deviceSegment() in DeviceStorage.SEGMENTS) + } + } + + @Test + fun `without a group from the bridge nothing is logged and the device gets one`() { + val sdk = Rees46.initializeBridge(context, config()) + + assertTrue(sdk.getSegment() in DeviceStorage.SEGMENTS) + assertTrue(logged.none { it.code == LogCodes.INVALID_CONFIG || it.code == LogCodes.INVALID_ARGUMENT }) + } + + // What an app compiled against the releases with Rees46Config.coreV2 still finds. + + private val oldParameters = listOf( + String::class.java, String::class.java, String::class.java, Boolean::class.javaPrimitiveType, Boolean::class.javaPrimitiveType, + Boolean::class.javaPrimitiveType, String::class.java, Boolean::class.javaPrimitiveType, LogLevel::class.java, + Boolean::class.javaPrimitiveType, String::class.java, String::class.java, Boolean::class.javaPrimitiveType, + ) + + private val newParameters = oldParameters.filterIndexed { index, _ -> index != 9 } + + @Test + fun `apps get no way to the new core, no constructor or copy takes it and Java does not see the bridges' entry`() { + val visible = Rees46Config::class.java.constructors.filterNot { it.isSynthetic } + visible.forEach { constructor -> + assertEquals(newParameters.take(constructor.parameterCount), constructor.parameterTypes.toList()) + } + assertEquals((1..12).toList(), visible.map { it.parameterCount }.sorted()) + val copies = Rees46Config::class.java.methods.filter { it.name == "copy" && !it.isSynthetic } + assertEquals(listOf(newParameters), copies.map { it.parameterTypes.toList() }) + val bridgeEntries = Rees46::class.java.methods.filter { it.name.startsWith("initializeBridge") } + assertTrue(bridgeEntries.isNotEmpty() && bridgeEntries.all { it.isSynthetic }) + } + + @Test + fun `the constructor of the releases with coreV2 is still there for compiled apps, and ignores the core`() { + val full = Rees46Config::class.java.getConstructor(*oldParameters.toTypedArray()) + assertTrue(full.isSynthetic) + + val made = full.newInstance("shop", "api.rees46.ru", "android", true, false, true, "SDK", true, LogLevel.WARNING, true, null, null, false) + + assertEquals(Rees46Config("shop"), made) + assertEquals(1, logs(LogCodes.INVALID_CONFIG, LogReasons.BRIDGE_ONLY).size) + } + + @Test + fun `the defaults of the releases with coreV2 are still there for compiled Kotlin apps`() { + val marker = Class.forName("kotlin.jvm.internal.DefaultConstructorMarker") + val withDefaults = Rees46Config::class.java.getDeclaredConstructor(*(oldParameters + Int::class.javaPrimitiveType + marker).toTypedArray()) + // Every parameter but the shop and the core left to its default, as `Rees46Config("shop", coreV2 = …)` compiled. + val mask = ((1 shl 13) - 1) and (1 shl 0).inv() and (1 shl 9).inv() + + listOf(false, true).forEach { coreV2 -> + val made = withDefaults.newInstance("shop", null, null, false, false, false, null, false, null, coreV2, null, null, false, mask, null) + assertEquals(Rees46Config("shop"), made) + } + assertEquals(1, logs(LogCodes.INVALID_CONFIG, LogReasons.BRIDGE_ONLY).size) + + val copy = Rees46Config::class.java.getMethod("copy", *oldParameters.toTypedArray()) + assertTrue(copy.isSynthetic) + val copied = copy.invoke(Rees46Config("shop"), "other", "api.rees46.ru", "android", true, false, true, "SDK", true, LogLevel.DEBUG, true, "key", null, false) + assertEquals(Rees46Config("other", logLevel = LogLevel.DEBUG, storageKey = "key"), copied) + assertEquals(2, logs(LogCodes.INVALID_CONFIG, LogReasons.BRIDGE_ONLY).size) + } + + private companion object { + const val SHOP = "bridge-shop" + const val OTHER = "bridge-other" + } +} diff --git a/personalization-sdk/src/test/kotlin/com/personalization/LegacyPushClickTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/LegacyPushClickTest.kt index 5efd0f99..6fd9f225 100644 --- a/personalization-sdk/src/test/kotlin/com/personalization/LegacyPushClickTest.kt +++ b/personalization-sdk/src/test/kotlin/com/personalization/LegacyPushClickTest.kt @@ -117,7 +117,6 @@ class LegacyPushClickTest { shopId = SHOP, apiDomain = server.url("/").toString().trimEnd('/'), autoSendPushToken = false, - coreV2 = false, logLevel = LogLevel.DEBUG, ) diff --git a/personalization-sdk/src/test/kotlin/com/personalization/NotificationHelperUnseenPushTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/NotificationHelperUnseenPushTest.kt index ca127df1..1e4d4431 100644 --- a/personalization-sdk/src/test/kotlin/com/personalization/NotificationHelperUnseenPushTest.kt +++ b/personalization-sdk/src/test/kotlin/com/personalization/NotificationHelperUnseenPushTest.kt @@ -129,9 +129,9 @@ class NotificationHelperUnseenPushTest { shopId = SHOP, apiDomain = server.url("/").toString().trimEnd('/'), autoSendPushToken = false, - coreV2 = true, logLevel = LogLevel.DEBUG, ), + coreV2 = true, ) runBlocking { withTimeout(5_000) { sdk.instanceState.changes.first { it == SdkState.READY } } } return sdk diff --git a/personalization-sdk/src/test/kotlin/com/personalization/PushBringUpTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/PushBringUpTest.kt index 56736272..6bc3e38d 100644 --- a/personalization-sdk/src/test/kotlin/com/personalization/PushBringUpTest.kt +++ b/personalization-sdk/src/test/kotlin/com/personalization/PushBringUpTest.kt @@ -147,11 +147,10 @@ class PushBringUpTest { PushHub.reset() } - private fun config(shop: String = SHOP, coreV2: Boolean = true, deviceId: String? = null) = Rees46Config( + private fun config(shop: String = SHOP, deviceId: String? = null) = Rees46Config( shopId = shop, apiDomain = server.url("/").toString().trimEnd('/'), autoSendPushToken = false, - coreV2 = coreV2, logLevel = LogLevel.DEBUG, deviceId = deviceId, ) @@ -191,7 +190,7 @@ class PushBringUpTest { /** A push-only instance of [config]'s shop whose own work waits for [scheduler], as the push's handling brings it up. */ private fun heldPushInstance(config: Rees46Config, scheduler: TestCoroutineScheduler): SDK { val light = SDK().apply { dispatchers = testCoreDispatchers(scheduler) } - light.initializeForPush(context, config) + light.initializeForPush(context, config, coreV2 = true) assertTrue(light.pushOnly) return light } @@ -201,7 +200,7 @@ class PushBringUpTest { @Test fun `on the legacy core a cold push for a shop without a did sends only init and track received, and the token and profile go once the app takes the instance`() { PushTokenManager.sourceFactory = { listOf(TokenSource("tok")) } - Rees46.register(context, listOf(config(SHOP, coreV2 = false).copy(autoSendPushToken = true))) + Rees46.register(context, listOf(config(SHOP).copy(autoSendPushToken = true))) assertEquals(SHOP, Rees46.handlePush(push(code = "cold"), PushEvent.DELIVERED)) val made = SdkRegistry.byShopId(SHOP) ?: throw AssertionError("no instance") @@ -222,7 +221,7 @@ class PushBringUpTest { // Taken again, however: nothing more goes. assertTrue(Rees46.instance(SHOP) === made) assertTrue(SDK.instance === made) - assertTrue(Rees46.initialize(context, config(SHOP, coreV2 = false).copy(autoSendPushToken = true)) === made) + assertTrue(Rees46.initialize(context, config(SHOP).copy(autoSendPushToken = true)) === made) threads.awaitIdle() assertNull(next("mobile_push_tokens", "profile/set", timeoutMs = 1_000)) assertEquals(listOf("init", "track/received"), seen.map { it.first }.filter { it != "mobile_push_tokens" && it != "profile/set" }) @@ -235,12 +234,12 @@ class PushBringUpTest { @Test fun `a push the app's first call overtakes before the push's instance read its did goes to the app's instance, not dropped for want of a did`() { val scheduler = TestCoroutineScheduler() - Rees46.register(context, listOf(config(SHOP, deviceId = "CONFIGURED"))) + Rees46.register(context, listOf(config(SHOP, deviceId = "CONFIGURED")), coreV2 = true) // The push's instance, whose start has not read the disk yet: only the config brings a did. val light = heldPushInstance(config(SHOP, deviceId = "CONFIGURED"), scheduler) // The app's own instance takes its place; its /init has not answered yet. holdInit = CountDownLatch(1) - val full = Rees46.initialize(context, config(SHOP)) + val full = Rees46.initialize(context, config(SHOP), coreV2 = true) assertTrue(full !== light) assertEquals(SdkState.NOT_INITIALIZED, light.state) assertEquals("", partition().getString(StorageKeys.DID, "").orEmpty()) @@ -264,7 +263,7 @@ class PushBringUpTest { fun `a tap handed to the app's instance sets its source before the app's next view goes`() { val scheduler = TestCoroutineScheduler() partition().edit().putString(StorageKeys.DID, "STORED").commit() - Rees46.register(context, listOf(config(SHOP))) + Rees46.register(context, listOf(config(SHOP)), coreV2 = true) val light = heldPushInstance(config(SHOP), scheduler) val full = Rees46.instance(SHOP) assertTrue(full !== light) @@ -293,7 +292,7 @@ class PushBringUpTest { .putString(StorageKeys.TRACKING_SOURCE_CODE, "kept") .putLong(StorageKeys.TRACKING_SOURCE_SAVED_AT, savedAt) .commit() - val sdk = Rees46.initialize(context, config(SHOP)) + val sdk = Rees46.initialize(context, config(SHOP), coreV2 = true) runBlocking { withTimeout(5_000) { sdk.instanceState.changes.first { it == SdkState.READY } } } sdk.release() @@ -315,7 +314,7 @@ class PushBringUpTest { @Test fun `SDK instance while only the push's instance lives is the shop's full instance, for the old calls and the deprecated initialize`() { partition().edit().putString(StorageKeys.DID, "STORED").commit() - Rees46.register(context, listOf(config(SHOP))) + Rees46.register(context, listOf(config(SHOP)), coreV2 = true) Rees46.handlePush(push(code = "cold"), PushEvent.DELIVERED) val light = SdkRegistry.byShopId(SHOP) ?: throw AssertionError("no instance") assertTrue(light.pushOnly) @@ -341,7 +340,7 @@ class PushBringUpTest { @Test fun `the deprecated initialize of a new object takes the push's instance's place, and each event goes once`() { partition().edit().putString(StorageKeys.DID, "STORED").commit() - Rees46.register(context, listOf(config(SHOP))) + Rees46.register(context, listOf(config(SHOP)), coreV2 = true) Rees46.handlePush(push(code = "cold"), PushEvent.DELIVERED) val light = SdkRegistry.byShopId(SHOP) ?: throw AssertionError("no instance") @@ -367,7 +366,7 @@ class PushBringUpTest { holdInit = CountDownLatch(1) // The push's instance without a did, as it starts should one come without one: /init for a did. val light = SDK() - light.initializeForPush(context, config(SHOP, coreV2 = false)) + light.initializeForPush(context, config(SHOP), coreV2 = false) assertTrue(light.pushOnly) val heard = LinkedBlockingQueue() light.sendNetworkMethodUseCase.postAsync("track/received", JSONObject().put("code", "held").put("type", "bulk"), object : OnApiCallbackListener() { @@ -381,7 +380,7 @@ class PushBringUpTest { }) assertEquals(1, light.networkRepository.waitingForDid) - val full = Rees46.initialize(context, config(SHOP, coreV2 = false)) + val full = Rees46.initialize(context, config(SHOP)) assertEquals(SdkState.NOT_INITIALIZED, light.state) assertEquals("notInitialized, at once", -1, heard.poll(5, TimeUnit.SECONDS)) @@ -397,7 +396,7 @@ class PushBringUpTest { @Test fun `on the legacy core the push's instance that gave way still sends the tracking its push hands it later, with its did`() { partition().edit().putString(StorageKeys.DID, "STORED").commit() - Rees46.register(context, listOf(config(SHOP, coreV2 = false))) + Rees46.register(context, listOf(config(SHOP))) Rees46.handlePush(push(code = "cold"), PushEvent.DELIVERED) val light = SdkRegistry.byShopId(SHOP) ?: throw AssertionError("no instance") assertTrue(light.pushOnly) @@ -416,7 +415,7 @@ class PushBringUpTest { @Test fun `on the legacy core a shop whose did comes from the config or the store of an older release sends its push without init`() { - Rees46.register(context, listOf(config(SHOP, coreV2 = false, deviceId = "CONFIGURED"))) + Rees46.register(context, listOf(config(SHOP, deviceId = "CONFIGURED"))) assertEquals(SHOP, Rees46.handlePush(push(code = "configured"), PushEvent.DELIVERED)) assertTrue(SdkRegistry.byShopId(SHOP)?.pushOnly == true) assertEquals("CONFIGURED", next("track/received")?.second?.getString("did")) @@ -424,7 +423,7 @@ class PushBringUpTest { // Only the store all shops shared before partitions has it. context.getSharedPreferences(PreferencesPartition.LEGACY_KEY, Context.MODE_PRIVATE).edit() .putString(StorageKeys.SHOP_ID, OTHER).putString(StorageKeys.DID, "OLD").commit() - Rees46.register(context, listOf(config(OTHER, coreV2 = false))) + Rees46.register(context, listOf(config(OTHER))) assertEquals(OTHER, Rees46.handlePush(push(code = "old", shop = OTHER), PushEvent.DELIVERED)) assertTrue(SdkRegistry.byShopId(OTHER)?.pushOnly == true) assertEquals("OLD", next("track/received")?.second?.getString("did")) @@ -439,7 +438,7 @@ class PushBringUpTest { fun `a repeat that comes while the first event of a message is handed over is tried again when no queue takes that one, and the message goes later`() { val scheduler = TestCoroutineScheduler() partition().edit().putString(StorageKeys.DID, "STORED").commit() - Rees46.register(context, listOf(config(SHOP))) + Rees46.register(context, listOf(config(SHOP)), coreV2 = true) val light = heldPushInstance(config(SHOP), scheduler) Rees46.instance(SHOP).release() assertTrue(SdkRegistry.byShopId(SHOP) == null) @@ -455,7 +454,7 @@ class PushBringUpTest { assertEquals(2, logged.count { it.message == "The push event was not accepted" }) // Not taken, the message is not counted as sent: it goes when it comes again. - val sdk = Rees46.initialize(context, config(SHOP)) + val sdk = Rees46.initialize(context, config(SHOP), coreV2 = true) assertEquals(SHOP, Rees46.handlePush(push(code = "m"), PushEvent.DELIVERED)) flush(sdk) assertEquals("m", next("track/delivered")?.second?.getString("code")) diff --git a/personalization-sdk/src/test/kotlin/com/personalization/PushEventsTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/PushEventsTest.kt index 67a9c460..cd80eaa2 100644 --- a/personalization-sdk/src/test/kotlin/com/personalization/PushEventsTest.kt +++ b/personalization-sdk/src/test/kotlin/com/personalization/PushEventsTest.kt @@ -152,17 +152,16 @@ class PushEventsTest { PushDismissReceiver.work = defaultWork } - private fun config(shop: String = SHOP, coreV2: Boolean = true, deviceId: String? = null) = Rees46Config( + private fun config(shop: String = SHOP, deviceId: String? = null) = Rees46Config( shopId = shop, apiDomain = server.url("/").toString().trimEnd('/'), autoSendPushToken = false, - coreV2 = coreV2, logLevel = LogLevel.DEBUG, deviceId = deviceId, ) private fun sdk(shop: String = SHOP, coreV2: Boolean = true): SDK { - val sdk = Rees46.initialize(context, config(shop, coreV2)) + val sdk = Rees46.initialize(context, config(shop), coreV2) runBlocking { withTimeout(5_000) { sdk.instanceState.changes.first { it == SdkState.READY } } } return sdk } @@ -268,7 +267,7 @@ class PushEventsTest { Rees46.setPushCallbacks(PushCallbacks(onClicked = { clicked += it.code })) Rees46.onPushEvent { _, payload -> bridge += payload.code } initStatus = 403 - val refused = Rees46.initialize(context, config()) + val refused = Rees46.initialize(context, config(), coreV2 = true) runBlocking { withTimeout(5_000) { refused.instanceState.changes.first { it == SdkState.REFUSED } } } assertEquals(SHOP, Rees46.handlePush(push(code = "again"), PushEvent.CLICKED)) // The queue's refusal comes off the caller's thread. @@ -340,7 +339,7 @@ class PushEventsTest { fun `a shop registered but not created sends its push with its stored did and no init, and becomes a full instance on use`() { // An earlier launch's did; the server would hand out another one. partition().edit().putString("did", "STORED").commit() - Rees46.register(context, listOf(config(SHOP).copy(autoSendPushToken = true))) + Rees46.register(context, listOf(config(SHOP).copy(autoSendPushToken = true)), coreV2 = true) assertFalse(Rees46.isInitialized(SHOP)) assertEquals(SHOP, Rees46.handlePush(push(code = "cold"), PushEvent.DELIVERED)) @@ -368,11 +367,11 @@ class PushEventsTest { @Test fun `initializing the instance brought up for a push makes it a full one, and its push still goes`() { partition().edit().putString("did", "STORED").commit() - Rees46.register(context, listOf(config(SHOP))) + Rees46.register(context, listOf(config(SHOP)), coreV2 = true) Rees46.handlePush(push(code = "cold"), PushEvent.DELIVERED) val light = SdkRegistry.byShopId(SHOP) ?: throw AssertionError("no instance") - light.initializeWith(context, config(SHOP)) + light.initializeWith(context, config(SHOP), coreV2 = true) assertFalse(light.pushOnly) assertTrue(SdkRegistry.byShopId(SHOP) === light) @@ -384,7 +383,7 @@ class PushEventsTest { @Test fun `the instance brought up for a push never reaches the app, nor becomes the default`() { partition().edit().putString("did", "STORED").commit() - Rees46.register(context, listOf(config(SHOP))) + Rees46.register(context, listOf(config(SHOP)), coreV2 = true) Rees46.handlePush(push(code = "cold"), PushEvent.DELIVERED) val light = SdkRegistry.byShopId(SHOP) ?: throw AssertionError("no instance") assertTrue(light.pushOnly) @@ -397,7 +396,7 @@ class PushEventsTest { assertFalse(full.pushOnly) assertTrue(Rees46.instance(SHOP) === full) assertTrue(Rees46.instance() === full) - assertTrue(Rees46.initialize(context, config(SHOP)) === full) + assertTrue(Rees46.initialize(context, config(SHOP), coreV2 = true) === full) assertTrue(SdkRegistry.current() === full) assertTrue(SDK.instance === full) } @@ -405,11 +404,11 @@ class PushEventsTest { @Test fun `initialize of a shop a push brought up gives the app a full instance`() { partition().edit().putString("did", "STORED").commit() - Rees46.register(context, listOf(config(SHOP))) + Rees46.register(context, listOf(config(SHOP)), coreV2 = true) Rees46.handlePush(push(code = "cold"), PushEvent.DELIVERED) val light = SdkRegistry.byShopId(SHOP) ?: throw AssertionError("no instance") - val full = Rees46.initialize(context, config(SHOP)) + val full = Rees46.initialize(context, config(SHOP), coreV2 = true) assertTrue(full !== light) assertFalse(full.pushOnly) @@ -424,7 +423,7 @@ class PushEventsTest { setUp() } partition().edit().putString("did", "STORED").commit() - Rees46.register(context, listOf(config(SHOP))) + Rees46.register(context, listOf(config(SHOP)), coreV2 = true) val barrier = CyclicBarrier(2) val app = AtomicReference() val failure = AtomicReference() @@ -463,7 +462,7 @@ class PushEventsTest { @Test fun `a push event that reaches the instance a push brought up after it gave way goes to the app's instance`() { partition().edit().putString("did", "STORED").commit() - Rees46.register(context, listOf(config(SHOP))) + Rees46.register(context, listOf(config(SHOP)), coreV2 = true) Rees46.handlePush(push(code = "first"), PushEvent.DELIVERED) val light = SdkRegistry.byShopId(SHOP) ?: throw AssertionError("no instance") val full = Rees46.instance(SHOP) @@ -512,7 +511,7 @@ class PushEventsTest { @Test fun `a shop registered but not created and without a did drops its push`() { - Rees46.register(context, listOf(config(SHOP))) + Rees46.register(context, listOf(config(SHOP)), coreV2 = true) assertNull(Rees46.handlePush(push(code = "no-did"), PushEvent.DELIVERED)) val dropped = logged.last { it.code == LogCodes.PUSH_DROPPED } @@ -527,14 +526,14 @@ class PushEventsTest { @Test fun `a shop a push brings up takes its did from the config or the saved init answer, not only the stored one`() { // Only the app's config brings it. - Rees46.register(context, listOf(config(SHOP, deviceId = "CONFIGURED"))) + Rees46.register(context, listOf(config(SHOP, deviceId = "CONFIGURED")), coreV2 = true) assertEquals(SHOP, Rees46.handlePush(push(code = "configured"), PushEvent.DELIVERED)) flush(SdkRegistry.byShopId(SHOP) ?: throw AssertionError("no instance")) assertEquals("CONFIGURED", next("track/delivered")?.second?.getString("did")) // Only the saved answer of an earlier /init has it. ShopStorage(context, StorageLayout(OTHER, null)).saveInitAnswer(JSONObject().put("did", "SAVED").put("seance", "S0")) - Rees46.register(context, listOf(config(OTHER))) + Rees46.register(context, listOf(config(OTHER)), coreV2 = true) assertEquals(OTHER, Rees46.handlePush(push(code = "saved", shop = OTHER), PushEvent.DELIVERED)) flush(SdkRegistry.byShopId(OTHER) ?: throw AssertionError("no instance")) assertEquals("SAVED", next("track/delivered")?.second?.getString("did")) @@ -545,7 +544,7 @@ class PushEventsTest { @Test fun `on the legacy core a push for a shop without a did makes its full instance as before, with one init`() { - Rees46.register(context, listOf(config(SHOP, coreV2 = false))) + Rees46.register(context, listOf(config(SHOP))) assertEquals(SHOP, Rees46.handlePush(push(code = "cold"), PushEvent.DELIVERED)) val made = SdkRegistry.byShopId(SHOP) ?: throw AssertionError("no instance") @@ -566,7 +565,7 @@ class PushEventsTest { fun `on the legacy core the push of a shop a push brought up does not keep its ended session alive`() { val ended = System.currentTimeMillis() - 3 * 60 * 60 * 1000L partition().edit().putString("did", "STORED").putString("sid", "OLD").putLong("sid_last_act", ended).commit() - Rees46.register(context, listOf(config(SHOP, coreV2 = false))) + Rees46.register(context, listOf(config(SHOP))) assertEquals(SHOP, Rees46.handlePush(push(code = "cold"), PushEvent.DELIVERED)) assertEquals("STORED", next("track/received")?.second?.getString("did")) @@ -581,7 +580,7 @@ class PushEventsTest { @Test fun `on the legacy core a shop registered but not created sends its push with its stored did and no init, and without one starts as before`() { partition().edit().putString("did", "STORED").commit() - Rees46.register(context, listOf(config(SHOP, coreV2 = false))) + Rees46.register(context, listOf(config(SHOP))) assertEquals(SHOP, Rees46.handlePush(push(code = "cold"), PushEvent.DELIVERED)) assertEquals("STORED", next("track/received")?.second?.getString("did")) @@ -591,7 +590,7 @@ class PushEventsTest { assertEquals(SdkState.READY, SdkRegistry.byShopId(SHOP)?.state) // Without a did it starts as it always did: /init for a did, then the push's event with it. - Rees46.register(context, listOf(config(OTHER, coreV2 = false))) + Rees46.register(context, listOf(config(OTHER))) assertEquals(OTHER, Rees46.handlePush(push(code = "cold", shop = OTHER), PushEvent.DELIVERED)) assertEquals(OTHER, next("init")?.second?.getString("shop_id")) assertEquals("D1", next("track/received")?.second?.getString("did")) @@ -685,7 +684,7 @@ class PushEventsTest { val hold = java.util.concurrent.CountDownLatch(1).also { holdInit = it } val heardTokens = CopyOnWriteArrayList() Rees46.setPushCallbacks(PushCallbacks(onToken = { heardTokens += it.token })) - val sdk = Rees46.initialize(context, config().copy(autoSendPushToken = true)) + val sdk = Rees46.initialize(context, config().copy(autoSendPushToken = true), coreV2 = true) val answered = LinkedBlockingQueue() SDK.onPushTokenReceived("tok", PushProvider.FCM) @@ -912,7 +911,7 @@ class PushEventsTest { // The completions are handed to the main thread: the test runs them on its own. val main = com.personalization.core.internal.HeldMain() val sdk = SDK().apply { dispatchers = com.personalization.core.internal.CoreDispatchers(main = { main }) } - sdk.initializeWith(context, config()) + sdk.initializeWith(context, config(), coreV2 = true) runBlocking { withTimeout(5_000) { sdk.instanceState.changes.first { it == SdkState.READY } } } val ends = LinkedBlockingQueue>() val completions = com.personalization.core.CompletionListener { ends += it } diff --git a/personalization-sdk/src/test/kotlin/com/personalization/PushTokenSourcesTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/PushTokenSourcesTest.kt index 7d4f5216..cf9d037c 100644 --- a/personalization-sdk/src/test/kotlin/com/personalization/PushTokenSourcesTest.kt +++ b/personalization-sdk/src/test/kotlin/com/personalization/PushTokenSourcesTest.kt @@ -130,11 +130,10 @@ class PushTokenSourcesTest { PushHub.reset() } - private fun config(shop: String = SHOP, coreV2: Boolean = true, autoSend: Boolean = true) = Rees46Config( + private fun config(shop: String = SHOP, autoSend: Boolean = true) = Rees46Config( shopId = shop, apiDomain = server.url("/").toString().trimEnd('/'), autoSendPushToken = autoSend, - coreV2 = coreV2, logLevel = LogLevel.DEBUG, ) @@ -169,7 +168,7 @@ class PushTokenSourcesTest { val host = LinkedBlockingQueue() val hold = CountDownLatch(1).also { holdInit = it } - val sdk = Rees46.initialize(context, config()) + val sdk = Rees46.initialize(context, config(), coreV2 = true) sdk.setOnPushTokenListener { token, provider -> host += "$provider:$token" } hold.countDown() @@ -196,7 +195,7 @@ class PushTokenSourcesTest { val host = LinkedBlockingQueue() val hold = CountDownLatch(1).also { holdInit = it } - val sdk = Rees46.initialize(context, config(coreV2 = false)) + val sdk = Rees46.initialize(context, config()) sdk.setOnPushTokenListener { token, provider -> host += "$provider:$token" } hold.countDown() @@ -218,7 +217,7 @@ class PushTokenSourcesTest { val source = FakeSource(PushProvider.FCM, Result.failure(IOException("no token"))) PushTokenManager.sourceFactory = { listOf(source) } - val sdk = Rees46.initialize(context, config()) + val sdk = Rees46.initialize(context, config(), coreV2 = true) ready(sdk) assertTrue(source.asked.await(5, TimeUnit.SECONDS)) idle(sdk) @@ -237,7 +236,7 @@ class PushTokenSourcesTest { val sdk = SDK() sdk.setOnPushTokenListener { token, _ -> host += token } - sdk.initializeWith(context, config(coreV2 = false)) + sdk.initializeWith(context, config()) assertTrue(source.asked.await(5, TimeUnit.SECONDS)) idle(sdk) @@ -254,7 +253,7 @@ class PushTokenSourcesTest { val sdk = SDK() sdk.setOnPushTokenListener { token, provider -> early += "$provider:$token" } - sdk.initializeWith(context, config(coreV2 = false)) + sdk.initializeWith(context, config()) assertEquals("tok", tokenRequests.poll(5, TimeUnit.SECONDS)?.getString("token")) idle(sdk) @@ -270,8 +269,8 @@ class PushTokenSourcesTest { @Test fun `a new token FCM hands its service reaches every live shop, and each sends it once`() { - val shop = Rees46.initialize(context, config(SHOP)) - val other = Rees46.initialize(context, config(OTHER)) + val shop = Rees46.initialize(context, config(SHOP), coreV2 = true) + val other = Rees46.initialize(context, config(OTHER), coreV2 = true) listOf(shop, other).forEach { ready(it); idle(it) } MessagingService().onNewToken("t2") @@ -289,7 +288,7 @@ class PushTokenSourcesTest { @Test fun `the instance's own onToken wins over the facade's, which hears each token once through the shops without one`() { - val shop = Rees46.initialize(context, config(SHOP, autoSend = false)) + val shop = Rees46.initialize(context, config(SHOP, autoSend = false), coreV2 = true) ready(shop) val own = CopyOnWriteArrayList() val facade = CopyOnWriteArrayList() @@ -307,7 +306,7 @@ class PushTokenSourcesTest { assertEquals(listOf("t", "t2"), bridge) // A shop without callbacks of its own: the facade hears each token once in the process. - val other = Rees46.initialize(context, config(OTHER, autoSend = false)) + val other = Rees46.initialize(context, config(OTHER, autoSend = false), coreV2 = true) ready(other) SDK.onPushTokenReceived("t3", PushProvider.FCM) SDK.onPushTokenReceived("t3", PushProvider.FCM) diff --git a/personalization-sdk/src/test/kotlin/com/personalization/PushTokenWeekTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/PushTokenWeekTest.kt index 6beeca18..1150ca69 100644 --- a/personalization-sdk/src/test/kotlin/com/personalization/PushTokenWeekTest.kt +++ b/personalization-sdk/src/test/kotlin/com/personalization/PushTokenWeekTest.kt @@ -139,12 +139,11 @@ class PushTokenWeekTest { PushHub.reset() } - private fun config(coreV2: Boolean, needReInitialization: Boolean = false) = Rees46Config( + private fun config(needReInitialization: Boolean = false) = Rees46Config( shopId = SHOP, apiDomain = server.url("/").toString().trimEnd('/'), autoSendPushToken = true, needReInitialization = needReInitialization, - coreV2 = coreV2, logLevel = LogLevel.DEBUG, ) @@ -183,7 +182,7 @@ class PushTokenWeekTest { fun `on the new core needReInitialization sends the token sent this week to the new did at once`() { sentYesterday("D0") - val sdk = Rees46.initialize(context, config(coreV2 = true, needReInitialization = true)) + val sdk = Rees46.initialize(context, config(needReInitialization = true), coreV2 = true) assertFalse("/init asks for a new did", next("init")?.has("did") ?: true) val token = next("mobile_push_tokens") ?: throw AssertionError("the token waited for a week") @@ -198,7 +197,7 @@ class PushTokenWeekTest { sentYesterday("D0") PushTokenManager.sourceFactory = { listOf(Fcm()) } - val sdk = Rees46.initialize(context, config(coreV2 = false, needReInitialization = true)) + val sdk = Rees46.initialize(context, config(needReInitialization = true)) val token = next("mobile_push_tokens") ?: throw AssertionError("the token waited for a week") assertEquals("D1", token.getString("did")) @@ -212,7 +211,7 @@ class PushTokenWeekTest { sentYesterday("D1") PushTokenManager.sourceFactory = { listOf(Fcm()) } - val sdk = Rees46.initialize(context, config(coreV2 = false, needReInitialization = true)) + val sdk = Rees46.initialize(context, config(needReInitialization = true)) runBlocking { withTimeout(5_000) { sdk.instanceState.changes.first { it == SdkState.READY } } } next("init") threads.awaitIdle() @@ -226,7 +225,7 @@ class PushTokenWeekTest { fun `a token send on its way when the customer is deleted goes again for the new did at once`() { dids += listOf("D1", "D2") holdTokens = CountDownLatch(1) - val sdk = Rees46.initialize(context, config(coreV2 = true)) + val sdk = Rees46.initialize(context, config(), coreV2 = true) runBlocking { withTimeout(5_000) { sdk.instanceState.changes.first { it == SdkState.READY } } } sdk.setPushToken("tok", PushProvider.FCM) // The server has the send and has not answered yet. diff --git a/personalization-sdk/src/test/kotlin/com/personalization/SdkCoreGapsTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/SdkCoreGapsTest.kt index f55d6cd8..72385439 100644 --- a/personalization-sdk/src/test/kotlin/com/personalization/SdkCoreGapsTest.kt +++ b/personalization-sdk/src/test/kotlin/com/personalization/SdkCoreGapsTest.kt @@ -160,18 +160,17 @@ class SdkCoreGapsTest { PushHub.reset() } - private fun config(shop: String, coreV2: Boolean = true) = Rees46Config( + private fun config(shop: String) = Rees46Config( shopId = shop, apiDomain = server.url("/").toString().trimEnd('/'), autoSendPushToken = false, - coreV2 = coreV2, logLevel = LogLevel.DEBUG, ) private fun ready(sdk: SDK, state: SdkState = SdkState.READY) = runBlocking { withTimeout(5_000) { sdk.instanceState.changes.first { it == state } } } - private fun sdk(shop: String, coreV2: Boolean = true): SDK = Rees46.initialize(context, config(shop, coreV2)).also { ready(it) } + private fun sdk(shop: String, coreV2: Boolean = true): SDK = Rees46.initialize(context, config(shop), coreV2).also { ready(it) } private fun flush(sdk: SDK) = runBlocking { withTimeout(5_000) { sdk.flush() } } @@ -265,7 +264,7 @@ class SdkCoreGapsTest { @Test fun `deleting the customer of a refused shop asks init again, and its answer decides`() { initStatus[A] = 403 - val sdk = Rees46.initialize(context, config(A)) + val sdk = Rees46.initialize(context, config(A), coreV2 = true) ready(sdk, SdkState.REFUSED) assertTrue(partition(A).getBoolean(StorageKeys.REFUSED, false)) @@ -329,7 +328,7 @@ class SdkCoreGapsTest { listOf(false, true).forEach { coreV2 -> tearDown() setUp() - Rees46.register(context, listOf(config(A, coreV2), config(B, coreV2)), eagerInit = true) + Rees46.register(context, listOf(config(A), config(B)), eagerInit = true, coreV2 = coreV2) assertTrue(Rees46.isInitialized(A)) assertTrue(Rees46.isInitialized(B)) @@ -345,7 +344,7 @@ class SdkCoreGapsTest { @Test fun `waiting for a shop registered but not created gets its full instance at once, with one init`() { - Rees46.register(context, listOf(config(A))) + Rees46.register(context, listOf(config(A)), coreV2 = true) var got: SDK? = null Rees46.awaitInstance(A) { got = it } @@ -365,7 +364,7 @@ class SdkCoreGapsTest { val sdk = SDK() sdk.onSessionChange { throw IllegalStateException("the app's session listener") } sdk.onSessionChange { sessions += it } - sdk.initializeWith(context, config(A)) + sdk.initializeWith(context, config(A), coreV2 = true) ready(sdk) assertTrue(eventually { shadowOf(Looper.getMainLooper()).idle() @@ -416,7 +415,7 @@ class SdkCoreGapsTest { sdk.release() shadowOf(Looper.getMainLooper()).idle() - Rees46.initialize(context, config(A, coreV2)).also { ready(it) } + Rees46.initialize(context, config(A), coreV2).also { ready(it) } shadowOf(Looper.getMainLooper()).idle() assertEquals("core $coreV2", listOf(SdkState.READY, SdkState.NOT_INITIALIZED), states) @@ -427,10 +426,10 @@ class SdkCoreGapsTest { @Test fun `a shop initialized with the other flag after a registration decided the process's core runs on that core and is warned once`() { - Rees46.register(context, listOf(config(A, coreV2 = true))) + Rees46.register(context, listOf(config(A)), coreV2 = true) - val b = Rees46.initialize(context, config(B, coreV2 = false)) - Rees46.initialize(context, config(B, coreV2 = false)) + val b = Rees46.initialize(context, config(B)) + Rees46.initialize(context, config(B)) assertTrue(b.core?.isV2 == true) assertEquals(1, logged.count { it.code == LogCodes.CORE_FLAG_MISMATCH && it.shopId == B }) diff --git a/personalization-sdk/src/test/kotlin/com/personalization/SdkInitRequestTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/SdkInitRequestTest.kt index 661eda3e..0c8c00a1 100644 --- a/personalization-sdk/src/test/kotlin/com/personalization/SdkInitRequestTest.kt +++ b/personalization-sdk/src/test/kotlin/com/personalization/SdkInitRequestTest.kt @@ -130,7 +130,6 @@ class SdkInitRequestTest { apiDomain = apiDomain, autoSendPushToken = false, logLevel = LogLevel.DEBUG, - coreV2 = true, sendAdvertisingId = sendAdvertisingId, ) @@ -170,7 +169,7 @@ class SdkInitRequestTest { private fun start(sendAdvertisingId: Boolean, advertising: Advertising): SDK { val gate = Gate() val sdk = SDK().apply { dispatchers = CoreDispatchers(io = gate) } - sdk.initializeWith(context, config(sendAdvertisingId)) + sdk.initializeWith(context, config(sendAdvertisingId), coreV2 = true) sdk.initializeAdvertisingIdUseCase = InitializeAdvertisingIdUseCase(advertising, sdk.userSettingsRepository, context) gate.open() return sdk @@ -282,7 +281,7 @@ class SdkInitRequestTest { tearDown() setUp() CookieHandler.setDefault(handler) - val sdk = Rees46.initialize(context, config()) + val sdk = Rees46.initialize(context, config(), coreV2 = true) next("init") awaitState(sdk, SdkState.READY) @@ -302,7 +301,7 @@ class SdkInitRequestTest { @Test fun `an init that cannot be built is logged as such, nothing goes, and it is repeated as retrying`() { - val sdk = Rees46.initialize(context, config(apiDomain = "bad domain")) + val sdk = Rees46.initialize(context, config(apiDomain = "bad domain"), coreV2 = true) awaitState(sdk, SdkState.RETRYING) awaitLog(LogCodes.INIT_RETRY) @@ -318,7 +317,7 @@ class SdkInitRequestTest { @Test fun `an init answered with JSON cut short is decoding, and repeated as retrying without a did`() { initBody = { """{"did":"D""" } - val sdk = Rees46.initialize(context, config()) + val sdk = Rees46.initialize(context, config(), coreV2 = true) awaitState(sdk, SdkState.RETRYING) awaitLog(LogCodes.INIT_RETRY) diff --git a/personalization-sdk/src/test/kotlin/com/personalization/SdkInstanceTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/SdkInstanceTest.kt index 0a1d2f56..ffa418e7 100644 --- a/personalization-sdk/src/test/kotlin/com/personalization/SdkInstanceTest.kt +++ b/personalization-sdk/src/test/kotlin/com/personalization/SdkInstanceTest.kt @@ -128,7 +128,7 @@ class SdkInstanceTest { SdkLogs.handlerExecutor = defaultExecutor } - private fun config(shopId: String = SHOP, coreV2: Boolean = false, stream: String = "android", needReInitialization: Boolean = false, deviceId: String? = null) = + private fun config(shopId: String = SHOP, stream: String = "android", needReInitialization: Boolean = false, deviceId: String? = null) = Rees46Config( shopId = shopId, apiDomain = server.url("/").toString().trimEnd('/'), @@ -136,7 +136,6 @@ class SdkInstanceTest { autoSendPushToken = false, needReInitialization = needReInitialization, logLevel = LogLevel.DEBUG, - coreV2 = coreV2, deviceId = deviceId, ) @@ -191,10 +190,10 @@ class SdkInstanceTest { fun `initialize for a shop again returns its instance and sends no second init`() { listOf(false, true).forEach { coreV2 -> if (coreV2) tearDown().also { setUp() } - val first = Rees46.initialize(context, config(coreV2 = coreV2)) + val first = Rees46.initialize(context, config(), coreV2) nextRequest("init") - val second = Rees46.initialize(context, config(coreV2 = coreV2)) + val second = Rees46.initialize(context, config(), coreV2) assertSame(first, second) assertEquals(1, SdkRegistry.count()) @@ -282,7 +281,7 @@ class SdkInstanceTest { fun `after release every call fails with notInitialized and nothing is sent or deleted, on both cores`() { listOf(false, true).forEach { coreV2 -> if (coreV2) tearDown().also { setUp() } - val sdk = Rees46.initialize(context, config(coreV2 = coreV2)) + val sdk = Rees46.initialize(context, config(), coreV2) nextRequest("init") awaitState(sdk, SdkState.READY) val did = sdk.deviceId @@ -324,10 +323,10 @@ class SdkInstanceTest { @Test fun `after release initialize makes a fresh instance`() { - val first = Rees46.initialize(context, config(coreV2 = true)) + val first = Rees46.initialize(context, config(), coreV2 = true) first.release() - val second = Rees46.initialize(context, config(coreV2 = true)) + val second = Rees46.initialize(context, config(), coreV2 = true) assertNotSame(first, second) assertSame(second, Rees46.instance(SHOP)) @@ -394,7 +393,7 @@ class SdkInstanceTest { @Test fun `the new core's init carries the stream of the config and tz, and no advertising id`() { - val sdk = Rees46.initialize(context, config(coreV2 = true, stream = "flutter")) + val sdk = Rees46.initialize(context, config(stream = "flutter"), coreV2 = true) val init = nextRequest("init") assertTrue(sdk.core is CoreV2) @@ -415,7 +414,7 @@ class SdkInstanceTest { answer.await(5, TimeUnit.SECONDS) MockResponse().setBody(JSONObject().put("did", did.ifEmpty { "new-did" }).put("seance", "S").toString()) } - val sdk = Rees46.initialize(context, config(coreV2 = true)) + val sdk = Rees46.initialize(context, config(), coreV2 = true) nextRequest("init") assertEquals(SdkState.INITIALIZING, sdk.state) @@ -431,7 +430,7 @@ class SdkInstanceTest { @Test fun `on the new core a refused shop fails every request with 402 and stays refused at the next launch`() { initAnswer = { MockResponse().setResponseCode(403) } - val sdk = Rees46.initialize(context, config(coreV2 = true)) + val sdk = Rees46.initialize(context, config(), coreV2 = true) awaitState(sdk, SdkState.REFUSED) assertEquals("error:402", request(sdk)) @@ -439,7 +438,7 @@ class SdkInstanceTest { sdk.release() initAnswer = { did -> MockResponse().setBody(JSONObject().put("did", did.ifEmpty { "paid-did" }).toString()) } - val next = Rees46.initialize(context, config(coreV2 = true)) + val next = Rees46.initialize(context, config(), coreV2 = true) assertEquals(SdkState.REFUSED, next.state) awaitState(next, SdkState.READY) assertEquals("success", request(next)) @@ -450,7 +449,7 @@ class SdkInstanceTest { partition().edit().putString("did", "old-did").putString("sid", "old-sid").commit() initAnswer = { did -> MockResponse().setBody(JSONObject().put("did", did.ifEmpty { "fresh-did" }).put("seance", "S").toString()) } - val sdk = Rees46.initialize(context, config(coreV2 = true, needReInitialization = true)) + val sdk = Rees46.initialize(context, config(needReInitialization = true), coreV2 = true) assertNull(nextRequest("init").queryParameter("did")) awaitState(sdk, SdkState.READY) @@ -465,7 +464,7 @@ class SdkInstanceTest { val main = HeldMain() val sdk = SDK().apply { dispatchers = CoreDispatchers(main = { main }) } sdk.onSessionChange { heard += it to (Looper.myLooper() == Looper.getMainLooper()) } - sdk.initializeWith(context, config(coreV2 = true)) + sdk.initializeWith(context, config(), coreV2 = true) nextRequest("init") awaitState(sdk, SdkState.READY) // Handed to the main thread from the io dispatcher: run it here, on the test's main thread. @@ -479,7 +478,7 @@ class SdkInstanceTest { fun `on the new core the v3 clients check the session's window and take the live sid`() { var seance = "S1" initAnswer = { _ -> MockResponse().setBody(JSONObject().put("did", "D1").put("seance", seance).toString()) } - val sdk = Rees46.initialize(context, config(coreV2 = true)) + val sdk = Rees46.initialize(context, config(), coreV2 = true) nextRequest("init") awaitState(sdk, SdkState.READY) // Two hours without an event: the window ended, and the sid with it. @@ -498,7 +497,7 @@ class SdkInstanceTest { fun `on the new core a stored did is ready at once and its init still goes`() { partition().edit().putString("did", "stored-did").commit() - val sdk = Rees46.initialize(context, config(coreV2 = true)) + val sdk = Rees46.initialize(context, config(), coreV2 = true) assertEquals(SdkState.READY, sdk.state) assertEquals("stored-did", nextRequest("init").queryParameter("did")) @@ -506,7 +505,7 @@ class SdkInstanceTest { @Test fun `on the new core deleting the customer holds requests until the new did`() { - val sdk = Rees46.initialize(context, config(coreV2 = true)) + val sdk = Rees46.initialize(context, config(), coreV2 = true) awaitState(sdk, SdkState.READY) requests.clear() val second = CountDownLatch(1) diff --git a/personalization-sdk/src/test/kotlin/com/personalization/SdkLegacyApiTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/SdkLegacyApiTest.kt index 074e6f46..47de9c9d 100644 --- a/personalization-sdk/src/test/kotlin/com/personalization/SdkLegacyApiTest.kt +++ b/personalization-sdk/src/test/kotlin/com/personalization/SdkLegacyApiTest.kt @@ -371,7 +371,7 @@ class SdkLegacyApiTest { fun `a bridge's listener gets the answer as a success, an object or an array, on both cores`() { listOf(false, true).forEach { coreV2 -> if (coreV2) tearDown().also { setUp() } - val sdk = Rees46.initialize(context, Rees46Config(shopId = SHOP, apiDomain = apiDomain, autoSendPushToken = false, coreV2 = coreV2)) + val sdk = Rees46.initialize(context, Rees46Config(shopId = SHOP, apiDomain = apiDomain, autoSendPushToken = false), coreV2) awaitState(sdk, SdkState.READY) val results = LinkedBlockingQueue>() diff --git a/personalization-sdk/src/test/kotlin/com/personalization/SdkStorageTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/SdkStorageTest.kt index 7f748573..2d4b86ff 100644 --- a/personalization-sdk/src/test/kotlin/com/personalization/SdkStorageTest.kt +++ b/personalization-sdk/src/test/kotlin/com/personalization/SdkStorageTest.kt @@ -129,12 +129,11 @@ class SdkStorageTest { SdkLogs.handlerExecutor = defaultExecutor } - private fun config(storageKey: String? = null, coreV2: Boolean = false) = Rees46Config( + private fun config(storageKey: String? = null) = Rees46Config( shopId = SHOP, apiDomain = server.url("/").toString().trimEnd('/'), autoSendPushToken = false, logLevel = LogLevel.DEBUG, - coreV2 = coreV2, storageKey = storageKey, ) @@ -259,7 +258,7 @@ class SdkStorageTest { initCount.set(0) inits.clear() context.getSharedPreferences(StorageLayout(SHOP, null).partitionName, Context.MODE_PRIVATE).edit().clear().commit() - val sdk = Rees46.initialize(context, config(coreV2 = coreV2)) + val sdk = Rees46.initialize(context, config(), coreV2) awaitReady(sdk, "did-1") // The io thread is busy until the test lets it go: the wipe waits there. val busy = CountDownLatch(1) @@ -400,7 +399,7 @@ class SdkStorageTest { @Test fun `on the new core the deletion takes the queue too`() { - val sdk = Rees46.initialize(context, config(coreV2 = true)) + val sdk = Rees46.initialize(context, config(), coreV2 = true) val queue = sdk.storage?.queuePath?.also { it.mkdirs() } File(queue, "event").writeText("{}") diff --git a/personalization-sdk/src/test/kotlin/com/personalization/TrackingQueueTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/TrackingQueueTest.kt index b196c39d..fa8d7b4c 100644 --- a/personalization-sdk/src/test/kotlin/com/personalization/TrackingQueueTest.kt +++ b/personalization-sdk/src/test/kotlin/com/personalization/TrackingQueueTest.kt @@ -130,8 +130,8 @@ class TrackingQueueTest { shopId = SHOP, apiDomain = server.url("/").toString().trimEnd('/'), autoSendPushToken = false, - coreV2 = coreV2, - ) + ), + coreV2, ) runBlocking { withTimeout(5_000) { sdk.instanceState.changes.first { it == SdkState.READY } } } return sdk @@ -242,7 +242,8 @@ class TrackingQueueTest { val sdk = SDK().apply { dispatchers = CoreDispatchers(main = { main }) } sdk.initializeWith( context, - Rees46Config(shopId = SHOP, apiDomain = server.url("/").toString().trimEnd('/'), autoSendPushToken = false, coreV2 = true), + Rees46Config(shopId = SHOP, apiDomain = server.url("/").toString().trimEnd('/'), autoSendPushToken = false), + coreV2 = true, ) runBlocking { withTimeout(5_000) { sdk.instanceState.changes.first { it == SdkState.READY } } } val ends = LinkedBlockingQueue, Boolean>>() diff --git a/personalization-sdk/src/test/kotlin/com/personalization/TrackingValidationTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/TrackingValidationTest.kt index cb3af7e7..0a8cd4f5 100644 --- a/personalization-sdk/src/test/kotlin/com/personalization/TrackingValidationTest.kt +++ b/personalization-sdk/src/test/kotlin/com/personalization/TrackingValidationTest.kt @@ -113,7 +113,8 @@ class TrackingValidationTest { private fun sdk(coreV2: Boolean): SDK { val sdk = Rees46.initialize( context, - Rees46Config(shopId = SHOP, apiDomain = server.url("/").toString().trimEnd('/'), autoSendPushToken = false, coreV2 = coreV2), + Rees46Config(shopId = SHOP, apiDomain = server.url("/").toString().trimEnd('/'), autoSendPushToken = false), + coreV2, ) runBlocking { withTimeout(5_000) { sdk.instanceState.changes.first { it == SdkState.READY } } } return sdk diff --git a/personalization-sdk/src/test/kotlin/com/personalization/core/internal/CoreFunnelTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/core/internal/CoreFunnelTest.kt index 410d9e47..494a52f3 100644 --- a/personalization-sdk/src/test/kotlin/com/personalization/core/internal/CoreFunnelTest.kt +++ b/personalization-sdk/src/test/kotlin/com/personalization/core/internal/CoreFunnelTest.kt @@ -8,6 +8,7 @@ import com.personalization.Rees46Config import com.personalization.SDK import com.personalization.SdkRegistry import com.personalization.api.OnApiCallbackListener +import com.personalization.core.BridgeApi import com.personalization.sdk.data.repositories.network.NetworkRepositoryImpl import com.personalization.sdk.domain.repositories.UserSettingsRepository import io.mockk.every @@ -118,8 +119,9 @@ class CoreFunnelTest { verify(exactly = 1) { settings.updateSidLastActTime() } } + @OptIn(BridgeApi::class) @Test - fun `an instance made with coreV2 runs on the new core, its requests on the new client`() { + fun `an instance a bridge starts runs on the new core, its requests on the new client`() { server.enqueue(MockResponse().setResponseCode(200).setBody("""{"did":"server-did","seance":"S"}""")) val context = ApplicationProvider.getApplicationContext() // Robolectric's default network has no internet capability: give it one, as a device's has. @@ -128,13 +130,12 @@ class CoreFunnelTest { shadowOf(capabilities).addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) shadowOf(manager).setNetworkCapabilities(manager.activeNetwork, capabilities) - val sdk = Rees46.initialize( + val sdk = Rees46.initializeBridge( context, Rees46Config( shopId = "core-shop", apiDomain = server.url("/").toString().trimEnd('/'), autoSendPushToken = false, - coreV2 = true, ) ) diff --git a/personalization-sdk/src/test/kotlin/com/personalization/core/internal/LegacyCoreParityTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/core/internal/LegacyCoreParityTest.kt index 720871eb..56319837 100644 --- a/personalization-sdk/src/test/kotlin/com/personalization/core/internal/LegacyCoreParityTest.kt +++ b/personalization-sdk/src/test/kotlin/com/personalization/core/internal/LegacyCoreParityTest.kt @@ -21,7 +21,7 @@ import java.net.ServerSocket import java.util.concurrent.CopyOnWriteArrayList /** - * The answers of the legacy core (`coreV2 = false`) as 2.49.0 gave them to the old callbacks, which the + * The answers of the legacy core (`Rees46.initialize`) as 2.49.0 gave them to the old callbacks, which the * new core gives differently (commit 92e214e): a `2xx` that is not JSON, or JSON cut short, succeeds with * an empty object, and so does one whose connection closes midway through the body; a JSON array reaches * `onSuccess(JSONArray)`; no connection is `onError(504)`. Each request runs on [TrackingThreads], so a test waits From 4ae1b4e66a7ddb98d9d50cac488589dd202ae142 Mon Sep 17 00:00:00 2001 From: xyzcancer Date: Tue, 17 Nov 2026 15:06:30 +0400 Subject: [PATCH 2/3] feat(manifest): the SDK no longer declares AD_ID or allows cleartext traffic for the app; one that sends the advertising id on Android 13 and later, or talks http, declares them in its own manifest AD_ID came with reading the advertising id (5c67a22); play-services-ads-identifier 17.0.0 does not declare it, so without the app's own permission the legacy core's profile/set gets the zeroed id on Android 13 and later, and the new core reads it only with sendAdvertisingId. usesCleartextTraffic came into the SDK's manifest with 1.6.2 (the new stories, with video) without a stated reason; the SDK's own hosts are https, but an apiDomain with http:// and http images or videos of stories, popups and pushes need it. Documented on Rees46Config.apiDomain and Rees46Config.sendAdvertisingId. --- personalization-sdk/src/main/AndroidManifest.xml | 6 ++---- .../main/kotlin/com/personalization/Rees46Config.kt | 10 ++++++++-- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/personalization-sdk/src/main/AndroidManifest.xml b/personalization-sdk/src/main/AndroidManifest.xml index 057e32d0..eeaa8cdf 100644 --- a/personalization-sdk/src/main/AndroidManifest.xml +++ b/personalization-sdk/src/main/AndroidManifest.xml @@ -1,14 +1,12 @@ - + - + diff --git a/personalization-sdk/src/main/kotlin/com/personalization/Rees46Config.kt b/personalization-sdk/src/main/kotlin/com/personalization/Rees46Config.kt index 572f65ad..a02cbce7 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/Rees46Config.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/Rees46Config.kt @@ -13,7 +13,10 @@ import com.personalization.logs.SdkLogs * [PreferencesPartition]. * * @property shopId the shop key; also the partition key and the id used by [Rees46.instance]. - * @property apiDomain API host the instance talks to (a region points here). + * @property apiDomain API host the instance talks to (a region points here). The SDK's manifest does not + * allow cleartext traffic: a host given with `http://`, like images and videos of stories, popups and + * pushes served over `http://`, needs the app's own `android:usesCleartextTraffic="true"` or network + * security config. * @property stream traffic stream label sent with every request. * @property autoSendPushToken whether the SDK registers push tokens with the backend on its own. * @property needReInitialization forces a fresh `init` request instead of reusing stored session data. @@ -27,7 +30,10 @@ import com.personalization.logs.SdkLogs * only while the shop has no `did` of its own, and sent with the next `/init`. Ignored with * [needReInitialization]. * @property sendAdvertisingId sends the advertising id with `/init`; off by default, and then the new - * core does not read it. The legacy core keeps sending it as before, whatever this says. + * core does not read it. The legacy core keeps sending it as before, whatever this says. The SDK's + * manifest does not declare `com.google.android.gms.permission.AD_ID`: on Android 13 and later Google + * Play services give an app without it a zeroed id, so an app that wants the advertising id sent + * declares the permission in its own manifest. * @property storageKey a prefix for the shop's storage, when the app needs its own split of it: the * shop's `SharedPreferences` file becomes `_personalization_sdk_` instead of * `personalization_sdk_`. A file named exactly [storageKey] (the whole store of From f31421a7fd32a3aeb6de56e0a1d1370b6c53b0bf Mon Sep 17 00:00:00 2001 From: xyzcancer Date: Tue, 17 Nov 2026 15:12:22 +0400 Subject: [PATCH 3/3] feat(core): an A/B group the bridge hands over that the SDK never makes is an invalid_config, as on iOS initializeBridge logs a segment other than A or B as invalid_config with the reason segment_invalid, beside segment_kept and device_id_kept, instead of invalid_argument (invalid_segment). --- .../src/main/kotlin/com/personalization/Rees46.kt | 8 ++++---- .../src/main/kotlin/com/personalization/logs/SdkLogs.kt | 4 ++-- .../src/test/kotlin/com/personalization/BridgeInitTest.kt | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/personalization-sdk/src/main/kotlin/com/personalization/Rees46.kt b/personalization-sdk/src/main/kotlin/com/personalization/Rees46.kt index 09ff846c..203a316f 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/Rees46.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/Rees46.kt @@ -74,8 +74,8 @@ object Rees46 { * Native kept `A` or `B` for each shop). The start takes it while the device has no A/B group of its * own, so the device stays in the group the server knows it by; a device that has one keeps it, and a * different [segment] is logged as `invalid_config` (`segment_kept`). A value the SDK never gives, any - * but `A` and `B`, is refused with `invalid_argument` (`invalid_segment`). Neither throws. The shop's - * group is [SDK.getSegment]: once that is the bridge's, the bridge may stop passing it. + * but `A` and `B`, is not taken and logged as `invalid_config` (`segment_invalid`). Neither throws. + * The shop's group is [SDK.getSegment]: once that is the bridge's, the bridge may stop passing it. * * Hidden from Java, which knows no opt-in: the bridges are Kotlin. * @@ -592,10 +592,10 @@ object Rees46 { if (segment !in DeviceStorage.SEGMENTS) { SdkLogs.log( LogLevel.WARNING, - LogCodes.INVALID_ARGUMENT, + LogCodes.INVALID_CONFIG, "initializeBridge: the A/B group is not one the SDK gives; it is not taken", config.shopId, - mapOf("reason" to LogReasons.INVALID_SEGMENT), + mapOf("reason" to LogReasons.SEGMENT_INVALID), ) return } diff --git a/personalization-sdk/src/main/kotlin/com/personalization/logs/SdkLogs.kt b/personalization-sdk/src/main/kotlin/com/personalization/logs/SdkLogs.kt index 751b6cf9..9dd5116c 100644 --- a/personalization-sdk/src/main/kotlin/com/personalization/logs/SdkLogs.kt +++ b/personalization-sdk/src/main/kotlin/com/personalization/logs/SdkLogs.kt @@ -231,8 +231,8 @@ internal object LogReasons { /** The A/B group a bridge brought to `Rees46.initializeBridge` not taken: the device has its own (`invalid_config`). */ const val SEGMENT_KEPT = "segment_kept" - /** The A/B group a bridge brought is none the SDK gives, `A` or `B` (`invalid_argument`). */ - const val INVALID_SEGMENT = "invalid_segment" + /** The A/B group a bridge brought is none the SDK gives, `A` or `B` (`invalid_config`). */ + const val SEGMENT_INVALID = "segment_invalid" /** * `coreV2 = true` from an app built against the releases that had `Rees46Config.coreV2`: the new core is the diff --git a/personalization-sdk/src/test/kotlin/com/personalization/BridgeInitTest.kt b/personalization-sdk/src/test/kotlin/com/personalization/BridgeInitTest.kt index d0ca70f6..b1477ed2 100644 --- a/personalization-sdk/src/test/kotlin/com/personalization/BridgeInitTest.kt +++ b/personalization-sdk/src/test/kotlin/com/personalization/BridgeInitTest.kt @@ -282,7 +282,7 @@ class BridgeInitTest { val sdk = Rees46.initializeBridge(context, config(), segment) assertTrue("'$segment'", sdk.core is CoreV2) - val refused = logs(LogCodes.INVALID_ARGUMENT, LogReasons.INVALID_SEGMENT).single() + val refused = logs(LogCodes.INVALID_CONFIG, LogReasons.SEGMENT_INVALID).single() assertEquals(LogLevel.WARNING, refused.level) assertEquals(SHOP, refused.shopId) assertTrue("'$segment'", sdk.getSegment() in DeviceStorage.SEGMENTS)