diff --git a/DemoApp/REES46Demo/AppDelegate.swift b/DemoApp/REES46Demo/AppDelegate.swift index 22db4d7f..4a517ced 100644 --- a/DemoApp/REES46Demo/AppDelegate.swift +++ b/DemoApp/REES46Demo/AppDelegate.swift @@ -49,8 +49,8 @@ class AppDelegate: UIResponder, UIApplicationDelegate { ) -> Bool { // Under the tests the demo initializes nothing and shows an empty screen: no test reaches a - // server, and the first initialization of a process decides its core (`Rees46Config.coreV2`), - // which is the tests' to choose. + // server, and the first initialization of a process decides its core — the old one for an app, + // the new one for a bridge's `Rees46.initializeBridge` —, which is the tests' to choose. if Self.isRunningTests { window?.rootViewController = UIViewController() return true diff --git a/DemoApp/Rees46DemoTests/CoreGapTests.swift b/DemoApp/Rees46DemoTests/CoreGapTests.swift index 407a3c96..7492b507 100644 --- a/DemoApp/Rees46DemoTests/CoreGapTests.swift +++ b/DemoApp/Rees46DemoTests/CoreGapTests.swift @@ -761,11 +761,14 @@ final class CoreGapTests: CoreScenarioTestCase { let heard = Locked<[Rees46.SdkError?]>([]) let done = expectation(description: "init") done.expectedFulfillmentCount = 2 - let config = Rees46Config(shopId: shop, apiDomain: "stub.test", autoSendPushToken: false, coreV2: coreV2) - let sdk = Rees46.initialize(config, completion: Rees46.BridgeErrors.completion { error in heard.mutate { $0.append(error) }; done.fulfill() }) + let config = Rees46Config(shopId: shop, apiDomain: "stub.test", autoSendPushToken: false) + let start: (@escaping (LegacySdkError?) -> Void) -> PersonalizationSDK = { completion in + coreV2 ? Rees46.initializeBridge(config, completion: completion) : Rees46.initialize(config, completion: completion) + } + let sdk = start(Rees46.BridgeErrors.completion { error in heard.mutate { $0.append(error) }; done.fulfill() }) if coreV2 { // The same shop again: its outcome, once more. - _ = Rees46.initialize(config, completion: Rees46.BridgeErrors.completion { error in heard.mutate { $0.append(error) }; done.fulfill() }) + _ = start(Rees46.BridgeErrors.completion { error in heard.mutate { $0.append(error) }; done.fulfill() }) } else { (sdk as? SimplePersonalizationSDK)?.whenInitializedForTests { error in heard.mutate { $0.append(error) }; done.fulfill() } } @@ -775,6 +778,69 @@ final class CoreGapTests: CoreScenarioTestCase { } } + // MARK: - The bridges' way in: the new core and the A/B group they kept + + private func bridgeConfig(_ shop: String) -> Rees46Config { + Rees46Config(shopId: shop, apiDomain: "stub.test", autoSendPushToken: false) + } + + func test_initialize_bridge_runs_the_new_core_and_an_apps_initialize_the_old_one() { + CoreFlag.reset() + let bridged = newShop() + let sdk = Rees46.initializeBridge(bridgeConfig(bridged)) as? SimplePersonalizationSDK + XCTAssertEqual(sdk?.usesCoreV2, true) + XCTAssertEqual(sdk?.core.kind, .v2) + XCTAssertEqual(CoreFlag.current, true, "the bridge decided the process's core") + sdk?.release() + + CoreFlag.reset() + let app = newShop() + let legacy = Rees46.initialize(bridgeConfig(app)) as? SimplePersonalizationSDK + XCTAssertEqual(legacy?.usesCoreV2, false, "an app's configuration runs the old core") + XCTAssertEqual(legacy?.core.kind, .legacy) + XCTAssertEqual(legacy?.config.coreV2, false) + + // A bridge after the app: the process keeps the core the app decided, and says so. + let late = newShop() + let after = Rees46.initializeBridge(bridgeConfig(late)) as? SimplePersonalizationSDK + XCTAssertEqual(after?.usesCoreV2, false) + XCTAssertTrue(waitForLog(late, "core_flag_mismatch")) + XCTAssertEqual(CoreFlag.current, false) + legacy?.release() + after?.release() + } + + func test_initialize_bridge_brings_its_ab_group_only_to_a_device_that_has_none() { + let deviceSuite = UserDefaults(suiteName: DeviceStore.suiteName) ?? .standard + let before = deviceSuite.string(forKey: DeviceStore.abGroupKey) + defer { deviceSuite.set(before, forKey: DeviceStore.abGroupKey) } + deviceSuite.removeObject(forKey: DeviceStore.abGroupKey) + CoreFlag.reset() + + let first = newShop() + let a = Rees46.initializeBridge(bridgeConfig(first), segment: "B") + XCTAssertEqual(a.segment, "B", "the device had no group: it takes the bridge's") + XCTAssertEqual(DeviceStore.shared.abGroup, "B") + XCTAssertEqual(StoragePartition.store(for: first).string(forKey: StoragePartition.abSegmentKey), "B", "and the shop, for the old core") + XCTAssertTrue(logged(first, "invalid_config").isEmpty) + + let second = newShop() + let b = Rees46.initializeBridge(bridgeConfig(second), segment: "A") + XCTAssertEqual(b.segment, "B", "the device keeps its own") + XCTAssertTrue(waitForLog(second, "invalid_config", reason: "segment_kept")) + + let third = newShop() + let c = Rees46.initializeBridge(bridgeConfig(third), segment: "a") + XCTAssertEqual(c.segment, "B", "only a group the SDK makes is taken") + XCTAssertTrue(waitForLog(third, "invalid_config", reason: "segment_invalid")) + + // The shop's instance is there: its group stays, whatever the bridge brings. + XCTAssertTrue((Rees46.initializeBridge(bridgeConfig(first), segment: "A") as AnyObject) === (a as AnyObject)) + XCTAssertTrue(waitForLog(first, "invalid_config", reason: "segment_kept")) + XCTAssertEqual(DeviceStore.shared.abGroup, "B") + [a, b, c].forEach { $0.release() } + } + func test_queue_event_of_a_refused_or_released_instance_fails_on_main_and_queues_nothing() { let shop = newShop() answer("/init", StubReply(403)) @@ -1006,10 +1072,10 @@ final class CoreGapTests: CoreScenarioTestCase { func test_the_process_keeps_its_core_after_a_release_and_a_pending_shop_of_the_other_core_takes_the_process_one() { CoreFlag.reset() let first = newShop() - let a = Rees46.initialize(Rees46Config(shopId: first, apiDomain: "stub.test", autoSendPushToken: false, coreV2: true)) + let a = Rees46.initializeBridge(Rees46Config(shopId: first, apiDomain: "stub.test", autoSendPushToken: false)) a.release() let second = newShop() - let b = Rees46.initialize(Rees46Config(shopId: second, apiDomain: "stub.test", autoSendPushToken: false, coreV2: false)) + let b = Rees46.initialize(Rees46Config(shopId: second, apiDomain: "stub.test", autoSendPushToken: false)) XCTAssertEqual((b as? SimplePersonalizationSDK)?.usesCoreV2, true, "decided by the first, until the process ends") XCTAssertTrue(waitForLog(second, "core_flag_mismatch")) b.release() @@ -1020,7 +1086,7 @@ final class CoreGapTests: CoreScenarioTestCase { let tracked = Locked<[PendingPush]>([]) Rees46.pendingPushTracker = { push in tracked.mutate { $0.append(push) } } Rees46.register(shops: [ - Rees46Config(shopId: legacy, apiDomain: "stub.test", coreV2: false), + Rees46Config(shopId: legacy, apiDomain: "stub.test"), Rees46Config(shopId: pending, apiDomain: "stub.test", coreV2: true), ]) StoragePartition.store(for: pending).set("d", forKey: StoragePartition.deviceIdKey) diff --git a/DemoApp/Rees46DemoTests/CoreNetworkTests.swift b/DemoApp/Rees46DemoTests/CoreNetworkTests.swift index 83d2e336..158dffc5 100644 --- a/DemoApp/Rees46DemoTests/CoreNetworkTests.swift +++ b/DemoApp/Rees46DemoTests/CoreNetworkTests.swift @@ -8,7 +8,7 @@ // import XCTest -@testable import REES46 +@_spi(Bridge) @testable import REES46 final class CoreNetworkTests: XCTestCase { @@ -451,7 +451,7 @@ final class CoreNetworkTests: XCTestCase { let legacy = createPersonalizationSDK(shopId: shop, apiDomain: "stub.test", autoSendPushToken: false) XCTAssertEqual(CoreFlag.current, false) - let later = Rees46.initialize(Rees46Config(shopId: "\(shop)-2", apiDomain: "stub.test", autoSendPushToken: false, coreV2: true)) + let later = Rees46.initializeBridge(Rees46Config(shopId: "\(shop)-2", apiDomain: "stub.test", autoSendPushToken: false)) XCTAssertEqual((later as? SimplePersonalizationSDK)?.usesCoreV2, false, "the process keeps the old core") withExtendedLifetime([legacy, later] as [AnyObject]) {} StubSDK.removeSavedInit(shopId: shop) @@ -460,7 +460,7 @@ final class CoreNetworkTests: XCTestCase { func test_the_old_core_is_the_default() { XCTAssertFalse(Rees46Config(shopId: "a").coreV2) - XCTAssertTrue(Rees46Config(shopId: "a", coreV2: true).coreV2) + XCTAssertTrue(Rees46Config(shopId: "a").onNewCore().coreV2, "the bridges' configuration") let ready = expectation(description: "init") let sdk = StubSDK.make(shopId: shopId) { _ in ready.fulfill() } wait(for: [ready], timeout: 5) diff --git a/DemoApp/Rees46DemoTests/LegacyParityTests.swift b/DemoApp/Rees46DemoTests/LegacyParityTests.swift index 9c384727..2c528192 100644 --- a/DemoApp/Rees46DemoTests/LegacyParityTests.swift +++ b/DemoApp/Rees46DemoTests/LegacyParityTests.swift @@ -2,7 +2,7 @@ // LegacyParityTests.swift // REES46Tests // -// The old core (`Rees46Config.coreV2 = false`) behaves as 3.37.3 did, but for the fixes named for both +// The old core (an app's `Rees46.initialize`) behaves as 3.37.3 did, but for the fixes named for both // cores: a repeated `initialize` after a failed `/init` or with `needReInitialization`, the request // queue the app sees while `/init` is on its way and the order its requests leave in, the push token it // reads, `enableLogs`, the tracking and push wire, the decoding rules, the error types of `/init`, the @@ -81,10 +81,10 @@ final class LegacyParityTests: CoreScenarioTestCase { CoreFlag.reset(to: true) let v2 = newShop() answer("/init", StubReply(500)) - let v2Config = Rees46Config(shopId: v2, apiDomain: "stub.test", autoSendPushToken: false, coreV2: true) - let made = Rees46.initialize(v2Config) - XCTAssertTrue(same(Rees46.initialize(v2Config), made), "the new core repeats its /init itself") - XCTAssertTrue(same(Rees46.initialize(Rees46Config(shopId: v2, apiDomain: "stub.test", autoSendPushToken: false, needReInitialization: true, coreV2: true)), made)) + let v2Config = Rees46Config(shopId: v2, apiDomain: "stub.test", autoSendPushToken: false) + let made = Rees46.initializeBridge(v2Config) + XCTAssertTrue(same(Rees46.initializeBridge(v2Config), made), "the new core repeats its /init itself") + XCTAssertTrue(same(Rees46.initializeBridge(Rees46Config(shopId: v2, apiDomain: "stub.test", autoSendPushToken: false, needReInitialization: true)), made)) made.release() } diff --git a/REES46/Classes/Core/Core.swift b/REES46/Classes/Core/Core.swift index b60ee777..9efde07c 100644 --- a/REES46/Classes/Core/Core.swift +++ b/REES46/Classes/Core/Core.swift @@ -4,8 +4,9 @@ // // The engine under one SDK instance. Two of them run side by side while the new one is built: // `LegacyCore` — the request paths the SDK has always had — and `CoreV2`, the core of -// `sdk/core/*.md`, behind `Rees46Config.coreV2`. The SDK's request funnel (`sendGet`, -// `postRequest`, `getRequest`) asks the instance's core, so no namespace is written twice. +// `sdk/core/*.md`, behind `Rees46Config.coreV2`, which only the bridges' `Rees46.initializeBridge` +// sets. The SDK's request funnel (`sendGet`, `postRequest`, `getRequest`) asks the instance's core, +// so no namespace is written twice. // import Foundation diff --git a/REES46/Classes/Core/CoreV2.swift b/REES46/Classes/Core/CoreV2.swift index 283e70be..916443d0 100644 --- a/REES46/Classes/Core/CoreV2.swift +++ b/REES46/Classes/Core/CoreV2.swift @@ -2,10 +2,10 @@ // CoreV2.swift // REES46 // -// The new core, behind `Rees46Config.coreV2`: the requests of the funnel go through the new client -// (`NetworkClient`), `/init` is the new core's own (`InitMachine`) and so is the session -// (`SessionWindow`): a call waits until the instance is usable, at most its own timeout, and goes with -// the current `sid`. +// The new core, behind `Rees46Config.coreV2` (`Rees46.initializeBridge`): the requests of the funnel +// go through the new client (`NetworkClient`), `/init` is the new core's own (`InitMachine`) and so +// is the session (`SessionWindow`): a call waits until the instance is usable, at most its own +// timeout, and goes with the current `sid`. // import Foundation diff --git a/REES46/Classes/Sdk/Facade/Rees46+Bridge.swift b/REES46/Classes/Sdk/Facade/Rees46+Bridge.swift index 4bdce3e1..3c6d4913 100644 --- a/REES46/Classes/Sdk/Facade/Rees46+Bridge.swift +++ b/REES46/Classes/Sdk/Facade/Rees46+Bridge.swift @@ -16,6 +16,29 @@ import Foundation @_spi(Bridge) extension Rees46 { + /** + `initialize(_:completion:)` on the new core: the bridges' way in, the only one to that core. It + makes or finds the shop's instance as `initialize` does, with the same `completion`. The core is + still the process's, decided by its first `initialize`, `initializeBridge` or `register`: after an + app's own `initialize` or `register` the instance runs the old core, and the log says + `core_flag_mismatch`. + + `segment` is the device's A/B group the bridge kept in its own storage from before — React Native + kept one per shop. The device takes it only while it has no group of its own, neither in the + device's store nor in the shop's partition; otherwise its own stays and the log says + `invalid_config` with the reason `segment_kept`. Only a group the SDK makes itself — `A` or `B` — + is taken: another is refused, the log says `invalid_config` with the reason `segment_invalid`, and + the device keeps or gets its own as without one. `nil` or empty is none. + */ + @discardableResult + public static func initializeBridge( + _ config: Rees46Config, + segment: String? = nil, + completion: ((LegacySdkError?) -> Void)? = nil + ) -> PersonalizationSDK { + initialize(config.onNewCore(), segment: segment, completion: completion) + } + /// `listener` hears every push event the SDK handles, of every shop, on the main thread, beside the /// app's `PushCallbacks` and whatever they are: once per event of a message, like them, with the /// shop the push went to in `PushPayload.shopId`. Until the handle is cancelled. @@ -88,9 +111,9 @@ extension Rees46 { extension PersonalizationSDK { /// Calls `listener` on the main thread with every new session id (`sid`) until the handle is - /// cancelled, so a bridge tells its app instead of asking for `sessionId` on a timer. With - /// `Rees46Config.coreV2` each `sid` an `/init` brings; on the old core the one - /// `deleteUserCredentials()` makes. Another conformer of the protocol tells nothing. + /// cancelled, so a bridge tells its app instead of asking for `sessionId` on a timer. On the new + /// core each `sid` an `/init` brings; on the old core the one `deleteUserCredentials()` makes. + /// Another conformer of the protocol tells nothing. @discardableResult public func onSessionChange(_ listener: @escaping (String) -> Void) -> Cancellable { guard let instance = self as? SimplePersonalizationSDK else { return .noop } @@ -115,7 +138,7 @@ extension PersonalizationSDK { goes — the device's token changed — hears the answer of the newer one. The old `setPushTokenNotification` keeps telling the app at once that the token waits for the - device id, as it always has; on `Rees46Config.coreV2` it, too, hears the answer once it went. + device id, as it always has; on the new core it, too, hears the answer once it went. */ public func setPushToken(_ token: Rees46.PushToken, completion: @escaping (Result) -> Void) { let finish: (Result) -> Void = { result in @@ -149,8 +172,8 @@ extension PersonalizationSDK { `completion` hears once, on the main thread: success once the event is accepted — on disk, the way the contract's tracking methods complete —, or `invalidArgument` for an event of a push, another - path or a body that is not JSON, `notInitialized`, `shopBlocked`. With `Rees46Config.coreV2 = - false`, which keeps no queue, the event goes at once and `completion` hears the server's answer. + path or a body that is not JSON, `notInitialized`, `shopBlocked`. On the old core, which keeps no + queue, the event goes at once and `completion` hears the server's answer. */ public func queueEvent(path: String, body: [String: Any], completion: @escaping (Result) -> Void) { let finish: (Rees46.SdkError?) -> Void = { error in diff --git a/REES46/Classes/Sdk/Facade/Rees46.swift b/REES46/Classes/Sdk/Facade/Rees46.swift index 2701eeac..bdcc1f93 100644 --- a/REES46/Classes/Sdk/Facade/Rees46.swift +++ b/REES46/Classes/Sdk/Facade/Rees46.swift @@ -77,21 +77,30 @@ public enum Rees46 { A shop that has an instance gets that instance back: no second one is made. A different `config` does not change it — the log says `invalid_config` with the reason `already_initialized` — and `completion` is still called once: with the outcome of the instance's initialization, or when it - settles. `release()` lets the next call make a new instance. Without `Rees46Config.coreV2`, as it - always has, a call after the instance's `/init` failed, or with `needReInitialization`, makes a new - instance of the shop with a new `/init`. + settles. `release()` lets the next call make a new instance. On the old core, as it always has, a + call after the instance's `/init` failed, or with `needReInitialization`, makes a new instance of + the shop with a new `/init`. */ @discardableResult public static func initialize( _ config: Rees46Config, completion: ((LegacySdkError?) -> Void)? = nil + ) -> PersonalizationSDK { + initialize(config, segment: nil, completion: completion) + } + + /// `initialize(_:completion:)` with the device's A/B group a bridge kept (`initializeBridge`). + static func initialize( + _ config: Rees46Config, + segment: String?, + completion: ((LegacySdkError?) -> Void)? ) -> PersonalizationSDK { withCreationLock { lock.lock() pending[config.shopId] = nil lock.unlock() if let existing = SdkRegistry.shared.byShopId(config.shopId), !makesNewLegacyInstance(over: existing, config: config) { - return (existing, joinExisting(existing, config: config, completion: completion)) + return (existing, joinExisting(existing, config: config, segment: segment, completion: completion)) } let sdk = SimplePersonalizationSDK( shopId: config.shopId, @@ -105,6 +114,7 @@ public enum Rees46 { storageKey: config.storageKey, coreV2: config.coreV2, deviceId: config.deviceId, + segment: segment, completion: completion ) sdk.resetSdkCache() @@ -125,6 +135,7 @@ public enum Rees46 { private static func joinExisting( _ existing: PersonalizationSDK, config: Rees46Config, + segment: String?, completion: ((LegacySdkError?) -> Void)? ) -> () -> Void { guard let instance = existing as? SimplePersonalizationSDK else { @@ -138,6 +149,9 @@ public enum Rees46 { ["reason": "already_initialized"] ) } + // The device's group was settled when the instance was made: a bridge's other one is not taken. + let brought = SimplePersonalizationSDK.validBroughtSegment(segment, logger: instance.logger) + SimplePersonalizationSDK.checkBroughtSegment(brought, against: instance.segment, logger: instance.logger) return { instance.whenInitialized(completion) } } @@ -313,12 +327,12 @@ public enum Rees46 { counting it to another shop. `type` and `code` are the top-level `type` and `id` of FCM, or `src.type` and `src.id` of APNs. - - With `Rees46Config.coreV2`, each event goes once per message in the process — a repeat sends - nothing and calls no callback —, through the shop's queue: `track/delivered`, `track/opened`, - `track/clicked`, `track/closed`. A click stores the push as the source of the shop's `/push` - events for 48 hours. - - Without it the events go at once, as they always have — `delivered` and `clicked`; `opened` and - `closed`, which that core never had, send nothing there and only call the callbacks. + - On the new core, the one the Flutter and React Native bridges run, each event goes once per + message in the process — a repeat sends nothing and calls no callback —, through the shop's + queue: `track/delivered`, `track/opened`, `track/clicked`, `track/closed`. A click stores the + push as the source of the shop's `/push` events for 48 hours. + - On the old core the events go at once, as they always have — `delivered` and `clicked`; `opened` + and `closed`, which that core never had, send nothing there and only call the callbacks. A shop that is registered but not created (`register` without `eagerInit`, the app launched by the push) is not created: the event goes with the device id the shop has stored, without `/init` — and @@ -344,9 +358,9 @@ public enum Rees46 { /** The push events of earlier versions; `handlePush(_:event:)` with `Rees46.PushEvent` replaces it. `delivered` and `clicked` are the same events there. `received` — a push that came while the app - was in the background, which the server counts as one more open — is `delivered` with - `Rees46Config.coreV2`, sent once with the `delivered` of the same push; without it, - `track/received` as before. + was in the background, which the server counts as one more open — is `delivered` on the new core, + the bridges', sent once with the `delivered` of the same push; on the old core `track/received` as + before. */ @_disfavoredOverload public static func handlePush(_ payload: [AnyHashable: Any], event: LegacyPushEvent) { diff --git a/REES46/Classes/Sdk/Facade/Rees46Config.swift b/REES46/Classes/Sdk/Facade/Rees46Config.swift index a19f17a3..fa4f0243 100644 --- a/REES46/Classes/Sdk/Facade/Rees46Config.swift +++ b/REES46/Classes/Sdk/Facade/Rees46Config.swift @@ -56,19 +56,51 @@ public struct Rees46Config { /// itself is the shop's storage, shared with the app's extensions as before (shops on one group key /// share it); the shop's files still get a folder of their own. public let storageKey: String? - /// Runs the shop on the new core of the SDK (`false` by default): its network client first, - /// with init, session, queue and pushes to follow. The first `Rees46.initialize` or - /// `Rees46.register` of the process decides for every shop until the app restarts; a shop that - /// asks otherwise gets the process's core, and the log says `core_flag_mismatch`. + /// Runs the shop on the new core of the SDK: its network client, `/init`, session, queue and + /// pushes. Not the app's to choose: a configuration an app makes runs the old core, and only the + /// Flutter and React Native bridges ask for the new one, through `Rees46.initializeBridge` + /// (`@_spi(Bridge)`). The first `Rees46.initialize`, `Rees46.initializeBridge` or `Rees46.register` + /// of the process decides for every shop until the app restarts; a shop that asks otherwise gets + /// the process's core, and the log says `core_flag_mismatch`. /// /// The new core sends through a session of its own. `configureURLSession(configuration:)` and a /// `urlSession` the app sets give it their configuration — proxy, headers, protocols, TLS settings /// — but not a session's delegate: certificate pinning done in a delegate does not apply, and the /// log says `invalid_config` with the reason `url_session_delegate`. A request still fails at once /// without network and keeps its own timeout. On either core the SDK sends and keeps no cookies. - public let coreV2: Bool + private(set) var coreV2: Bool public init( + shopId: String, + apiDomain: String = "api.rees46.ru", + stream: String = "ios", + deviceId: String? = nil, + enableLogs: Bool = false, + logLevel: Rees46.LogLevel = .warning, + autoSendPushToken: Bool = true, + sendAdvertisingId: Bool = false, + enableAutoPopupPresentation: Bool = true, + needReInitialization: Bool = false, + storageKey: String? = nil + ) { + self.init( + shopId: shopId, + apiDomain: apiDomain, + stream: stream, + deviceId: deviceId, + enableLogs: enableLogs, + logLevel: logLevel, + autoSendPushToken: autoSendPushToken, + sendAdvertisingId: sendAdvertisingId, + enableAutoPopupPresentation: enableAutoPopupPresentation, + needReInitialization: needReInitialization, + storageKey: storageKey, + coreV2: false + ) + } + + /// The configuration with the core it asks for: the SDK's own, its bridges' and its tests'. + init( shopId: String, apiDomain: String = "api.rees46.ru", stream: String = "ios", @@ -80,7 +112,7 @@ public struct Rees46Config { enableAutoPopupPresentation: Bool = true, needReInitialization: Bool = false, storageKey: String? = nil, - coreV2: Bool = false + coreV2: Bool ) { self.shopId = shopId self.apiDomain = apiDomain @@ -97,6 +129,13 @@ public struct Rees46Config { self.coreV2 = coreV2 } + /// This configuration on the new core: what `Rees46.initializeBridge` makes of a bridge's one. + func onNewCore() -> Rees46Config { + var config = self + config.coreV2 = true + return config + } + /// Whether an instance made with `other` behaves as one made with this configuration. func hasSameSettings(as other: Rees46Config) -> Bool { shopId == other.shopId diff --git a/REES46/Classes/Sdk/Model/PushEvent.enum.swift b/REES46/Classes/Sdk/Model/PushEvent.enum.swift index 5a615060..a60ca5d3 100644 --- a/REES46/Classes/Sdk/Model/PushEvent.enum.swift +++ b/REES46/Classes/Sdk/Model/PushEvent.enum.swift @@ -16,7 +16,7 @@ import Foundation running app. - `received` tracks a background arrival (`track/received`) — the push landed while the app was backgrounded, with no interaction. Deprecated (decision 0004): the server counts `track/received` as - an open, not a delivery. With `Rees46Config.coreV2` it goes as `delivered`. + an open, not a delivery. On the new core, the bridges', it goes as `delivered`. - `clicked` tracks the tap (`track/clicked`). Navigation (opening the product/category/web the push points to) stays with the host — see diff --git a/REES46/Classes/Sdk/Storage/UserIdentityRepository.swift b/REES46/Classes/Sdk/Storage/UserIdentityRepository.swift index ffbab913..1f05318d 100644 --- a/REES46/Classes/Sdk/Storage/UserIdentityRepository.swift +++ b/REES46/Classes/Sdk/Storage/UserIdentityRepository.swift @@ -40,8 +40,9 @@ protocol UserIdentityRepository: AnyObject { /// keeps it: the segment belongs to the device, not to the user. var abSegment: String? { get set } - /// The shop's A/B segment, assigned once: its own, or the device's when it has none. - func resolveAbSegment() -> String + /// The shop's A/B segment, assigned once: its own, or the device's when it has none; with neither, + /// `candidate` — a valid group a bridge kept from before (`Rees46.initializeBridge`) — or a new one. + func resolveAbSegment(candidate: String?) -> String /// Removes only the device id — used by the forced re-initialization path. func removeDeviceId() @@ -52,17 +53,23 @@ protocol UserIdentityRepository: AnyObject { extension UserIdentityRepository { - /// A repository without the device's store: the segment is the shop's own. + /// The shop's A/B segment with no group brought from before. func resolveAbSegment() -> String { - resolveOwnAbSegment() + resolveAbSegment(candidate: nil) + } + + /// A repository without the device's store: the segment is the shop's own. + func resolveAbSegment(candidate: String?) -> String { + resolveOwnAbSegment(candidate: candidate) } - /// The shop's own segment, assigned once and kept across launches. - func resolveOwnAbSegment() -> String { + /// The shop's own segment, assigned once — `candidate` when it is valid — and kept across launches. + func resolveOwnAbSegment(candidate: String? = nil) -> String { if let stored = abSegment, DeviceStore.abGroups.contains(stored) { return stored } - let assigned = DeviceStore.abGroups.randomElement() ?? "A" + let assigned = candidate.flatMap { DeviceStore.abGroups.contains($0) ? $0 : nil } + ?? DeviceStore.abGroups.randomElement() ?? "A" abSegment = assigned return assigned } diff --git a/REES46/Classes/Sdk/Storage/UserIdentityRepositoryImpl.swift b/REES46/Classes/Sdk/Storage/UserIdentityRepositoryImpl.swift index 878543cd..22422f55 100644 --- a/REES46/Classes/Sdk/Storage/UserIdentityRepositoryImpl.swift +++ b/REES46/Classes/Sdk/Storage/UserIdentityRepositoryImpl.swift @@ -90,14 +90,15 @@ final class UserIdentityRepositoryImpl: UserIdentityRepository { /// The shop's group. A shop that has one keeps it — `LegacyCore` reads exactly what it read before /// — and gives it to the device when the device has none: the first shop's group is the device's - /// (decision 4). A shop without one takes the device's, or a new one the device keeps. - func resolveAbSegment() -> String { - guard let device = device else { return resolveOwnAbSegment() } + /// (decision 4). A shop without one takes the device's; with none there either, `candidate` — the + /// group a bridge kept from before — or a new one, which the device keeps. + func resolveAbSegment(candidate: String?) -> String { + guard let device = device else { return resolveOwnAbSegment(candidate: candidate) } if let own = abSegment, DeviceStore.abGroups.contains(own) { _ = device.resolveAbGroup(candidate: own) return own } - let group = device.resolveAbGroup(candidate: nil) + let group = device.resolveAbGroup(candidate: candidate) abSegment = group return group } diff --git a/REES46/Classes/Sdk/impl/SimplePersonalizationSDK.swift b/REES46/Classes/Sdk/impl/SimplePersonalizationSDK.swift index 81302f63..ced3ea3f 100644 --- a/REES46/Classes/Sdk/impl/SimplePersonalizationSDK.swift +++ b/REES46/Classes/Sdk/impl/SimplePersonalizationSDK.swift @@ -228,6 +228,7 @@ class SimplePersonalizationSDK: PersonalizationSDK { storageKey: String? = nil, coreV2: Bool = false, deviceId configuredDeviceId: String? = nil, + segment broughtSegment: String? = nil, environment: CoreEnvironment? = nil, userIdentity: UserIdentityRepository? = nil, keychainStore: KeychainInitStore? = nil, @@ -317,9 +318,9 @@ class SimplePersonalizationSDK: PersonalizationSDK { // The old core resolves its session (the persisted one within the 2h window, else a new one it // makes); the new core never makes one: its `sid` is the server's (`SessionWindow`). Then the - // device's A/B segment. + // device's A/B segment, the one a bridge brought when the device has none. legacySeance = usesCoreV2 ? "" : self.sessionManager.currentSessionId() - segment = Self.abSegment(of: identity) + segment = Self.abSegment(of: identity, brought: broughtSegment, logger: logger) if needReInitialization { // The new core forgets the customer's device id, the saved answer and its keychain backup @@ -584,8 +585,40 @@ class SimplePersonalizationSDK: PersonalizationSDK { /// Native do, and the same for every shop of the app (decision 4). Picked anew on every launch, it /// moved the device between A and B, and a block under an A/B test showed products on one launch /// and nothing on the next. - static func abSegment(of identity: UserIdentityRepository) -> String { - identity.resolveAbSegment() + /// + /// `brought` is the group a bridge kept from before (`Rees46.initializeBridge`): taken only while + /// the device has none of its own, as `Rees46Config.deviceId` is; one the SDK does not make is + /// refused. + static func abSegment(of identity: UserIdentityRepository, brought: String? = nil, logger: SdkLogger = .process) -> String { + let candidate = validBroughtSegment(brought, logger: logger) + let segment = identity.resolveAbSegment(candidate: candidate) + checkBroughtSegment(candidate, against: segment, logger: logger) + return segment + } + + /// The A/B group a bridge brought when it is one the SDK makes itself (`DeviceStore.abGroups`); + /// another is refused, and the log says so. `nil` or empty is none. + static func validBroughtSegment(_ brought: String?, logger: SdkLogger) -> String? { + guard let brought = brought, !brought.isEmpty else { return nil } + guard DeviceStore.abGroups.contains(brought) else { + logger.warning( + LogCode.invalidConfig, + "the A/B group a bridge brought is not one the SDK makes: the device keeps or gets its own", + ["reason": "segment_invalid"] + ) + return nil + } + return brought + } + + /// Says in the log when the device keeps its own A/B group rather than the one a bridge brought. + static func checkBroughtSegment(_ brought: String?, against segment: String, logger: SdkLogger) { + guard let brought = brought, brought != segment else { return } + logger.warning( + LogCode.invalidConfig, + "the device keeps its own A/B group: the one a bridge brought was not taken", + ["reason": "segment_kept"] + ) } func getShopId() -> String { diff --git a/REES46/Classes/Sdk/protocol/PersonalizationSDK.protocol.swift b/REES46/Classes/Sdk/protocol/PersonalizationSDK.protocol.swift index 75070284..4309429d 100644 --- a/REES46/Classes/Sdk/protocol/PersonalizationSDK.protocol.swift +++ b/REES46/Classes/Sdk/protocol/PersonalizationSDK.protocol.swift @@ -38,21 +38,21 @@ public protocol PersonalizationSDK { func generateString(array : [String]) -> String func setProfileData(userEmail: String?, userPhone: String?, userLoyaltyId: String?, birthday: Date?, age: Int?, firstName: String?, lastName: String?, location: String?, gender: Gender?, advertisingId: String?, fbID: String?, vkID: String?, telegramId: String?, loyaltyCardLocation: String?, loyaltyStatus: String?, loyaltyBonuses: Int?, loyaltyBonusesToNextLevel: Int?, boughtSomething: Bool?, userId: String?, customProperties: [String: Any?]?, completion: @escaping (Result) -> Void) - /// With `Rees46Config.coreV2` the event goes through the shop's queue: `completion` is kept until it + /// On the new core, the bridges', the event goes through the shop's queue: `completion` is kept until it /// was sent — up to seven days, the time an event lives — or failed for good. @available(*, deprecated, message: "Use the tracking namespace: sdk.tracking.productView(itemId:), .addToCart(item:), .storyView(storyId:slideId:) and the rest.") func track(event: Event, recommendedBy: RecomendedBy?, completion: @escaping (Result) -> Void) - /// With `Rees46Config.coreV2` the event goes through the shop's queue: `completion` is kept until it + /// On the new core, the bridges', the event goes through the shop's queue: `completion` is kept until it /// was sent — up to seven days, the time an event lives — or failed for good. @available(*, deprecated, message: "Use the tracking namespace: sdk.tracking.purchase(request).") func trackPurchase(_ request: PurchaseTrackingRequest, recommendedBy: RecomendedBy?, completion: @escaping (Result) -> Void) @available(*, deprecated, message: "Use the tracking namespace: sdk.tracking.setSource(TrackingSource(type:code:)).") func trackSource(source: RecommendedByCase, code: String) - /// With `Rees46Config.coreV2` the event goes through the shop's queue: `completion` is kept until it + /// On the new core, the bridges', the event goes through the shop's queue: `completion` is kept until it /// was sent — up to seven days, the time an event lives — or failed for good. @available(*, deprecated, message: "Use the tracking namespace: sdk.tracking.custom(event:).") func trackEvent(event: String, time: Int?, category: String?, label: String?, value: Int?, customFields: [String: Any]?, completion: @escaping (Result) -> Void) - /// With `Rees46Config.coreV2` the event goes through the shop's queue: `completion` is kept until it + /// On the new core, the bridges', the event goes through the shop's queue: `completion` is kept until it /// was sent — up to seven days, the time an event lives — or failed for good. func trackPopupShown(popupId: Int, completion: @escaping (Result) -> Void) func recommend(blockId: String, currentProductId: String?, currentCategoryId: String?, locations: String?, imageSize: String?,timeOut: Double?, withLocations: Bool, extended: Bool, completion: @escaping (Result) -> Void) @@ -88,13 +88,13 @@ public protocol PersonalizationSDK { func searchBlank(completion: @escaping(Result) -> Void) /// Full search. `excludedMerchants` applies only together with non-empty `locations`, as in `suggest`. func search(query: String, limit: Int?, offset: Int?, categoryLimit: Int?,brandLimit: Int?, categories: [Int]?, extended: String?, sortBy: String?, sortDir: String?, locations: String?, excludedMerchants: [String]?, excludedBrands: [String]?, brands: String?, filters: [String: Any]?, priceMin: Double?, priceMax: Double?, colors: [String]?, fashionSizes: [String]?, exclude: String?, email: String?, timeOut: Double?, disableClarification: Bool?, completion: @escaping(Result) -> Void) - /// With `Rees46Config.coreV2` the event goes through the shop's queue: `completion` is kept until it + /// On the new core, the bridges', the event goes through the shop's queue: `completion` is kept until it /// was sent — up to seven days, the time an event lives — or failed for good. func notificationClicked(type: String, code: String, completion: @escaping (Result) -> Void) - /// With `Rees46Config.coreV2` the event goes through the shop's queue: `completion` is kept until it + /// On the new core, the bridges', the event goes through the shop's queue: `completion` is kept until it /// was sent — up to seven days, the time an event lives — or failed for good. func notificationDelivered(type: String, code: String, completion: @escaping (Result) -> Void) - /// With `Rees46Config.coreV2` the event goes through the shop's queue: `completion` is kept until it + /// On the new core, the bridges', the event goes through the shop's queue: `completion` is kept until it /// was sent — up to seven days, the time an event lives — or failed for good. func notificationReceived(type: String, code: String, completion: @escaping (Result) -> Void) func subscribeForBackInStock( @@ -152,8 +152,8 @@ public protocol PersonalizationSDK { /// Sends the queued events now, without waiting for the SDK's own triggers: `completion` is called /// on the main thread once every event queued at the call was tried — sent, or kept for later /// because there is no network or the server asked to wait; an instance that is not ready yet is - /// waited for, at most a request's read timeout. With `Rees46Config.coreV2 = false`, which keeps no - /// queue, it is called at once; after `release()` with `notInitialized`. Has a default + /// waited for, at most a request's read timeout. On the old core, which keeps no queue, it is + /// called at once; after `release()` with `notInitialized`. Has a default /// implementation, so conforming types keep compiling. func flush(completion: @escaping (Rees46.SdkError?) -> Void) diff --git a/REES46/Classes/Tracking/API/TrackingAPI.swift b/REES46/Classes/Tracking/API/TrackingAPI.swift index dd85c5b8..7e025924 100644 --- a/REES46/Classes/Tracking/API/TrackingAPI.swift +++ b/REES46/Classes/Tracking/API/TrackingAPI.swift @@ -73,8 +73,8 @@ public extension TrackingSourceType { /// /// Reached through an SDK instance: `Rees46.instance().tracking.productView(itemId: "sku-1")`. /// -/// With `Rees46Config.coreV2` an event goes through the shop's queue (`sdk/core/queue.md`): it is kept -/// on the device and sent when it can be, also after no network or a restart. Its `completion` is +/// On the new core, the bridges', an event goes through the shop's queue (`sdk/core/queue.md`): it is +/// kept on the device and sent when it can be, also after no network or a restart. Its `completion` is /// called when the event was sent — or failed for good, or was refused at once —, and is kept until /// then: up to seven days, the time an event lives, and not past the instance (`release()`) or the /// process. Do not hold a screen or another short-lived object in it. diff --git a/Tests/REES46CoreTests/StoragePackageTests.swift b/Tests/REES46CoreTests/StoragePackageTests.swift index ebd28edb..9a5d96b1 100644 --- a/Tests/REES46CoreTests/StoragePackageTests.swift +++ b/Tests/REES46CoreTests/StoragePackageTests.swift @@ -203,6 +203,65 @@ final class StoragePackageTests: XCTestCase { XCTAssertTrue(DeviceStore.abGroups.contains(fresh.resolveAbGroup(candidate: "C")), "an unknown group is replaced") } + /// The reasons of `invalid_config` the log handler heard for `shop`. + private func configReasons(_ shop: String) -> [String] { + SdkLogger.awaitDelivery() + logLock.lock(); defer { logLock.unlock() } + return logged.filter { $0.code == "invalid_config" && $0.shopId == shop }.compactMap { $0.context["reason"] } + } + + func test_the_group_a_bridge_brought_is_the_devices_only_while_the_device_has_none() { + let device = DeviceStore(defaults: suite(), pushTokenDefaults: suite()) + let shop = "shop-\(UUID().uuidString)" + let logger = SdkLogger(shopId: shop, level: .warning) + func shopWith(_ own: String?) -> (UserDefaults, UserIdentityRepositoryImpl) { + let partition = suite() + partition.set(own, forKey: StoragePartition.abSegmentKey) + return (partition, UserIdentityRepositoryImpl(store: partition, device: device)) + } + + let (first, firstRepo) = shopWith(nil) + XCTAssertEqual(SimplePersonalizationSDK.abSegment(of: firstRepo, brought: "B", logger: logger), "B", "the device had none") + XCTAssertEqual(device.abGroup, "B") + XCTAssertEqual(first.string(forKey: StoragePartition.abSegmentKey), "B", "and the shop keeps it, for the old core") + XCTAssertEqual(configReasons(shop), []) + + XCTAssertEqual(SimplePersonalizationSDK.abSegment(of: shopWith(nil).1, brought: "A", logger: logger), "B", "the device keeps its own") + XCTAssertEqual(configReasons(shop), ["segment_kept"]) + XCTAssertEqual(SimplePersonalizationSDK.abSegment(of: shopWith(nil).1, brought: "B", logger: logger), "B") + XCTAssertEqual(configReasons(shop), ["segment_kept"], "the same group is no news") + + // A shop that has a group of its own from an older SDK keeps it, and gives it to a device without one. + let fresh = DeviceStore(defaults: suite(), pushTokenDefaults: suite()) + let own = suite() + own.set("A", forKey: StoragePartition.abSegmentKey) + XCTAssertEqual(SimplePersonalizationSDK.abSegment(of: UserIdentityRepositoryImpl(store: own, device: fresh), brought: "B", logger: logger), "A") + XCTAssertEqual(fresh.abGroup, "A") + XCTAssertEqual(configReasons(shop), ["segment_kept", "segment_kept"]) + + // Without the device's store the shop's own segment takes it the same way. + XCTAssertEqual(SimplePersonalizationSDK.abSegment(of: UserIdentityRepositoryImpl(store: suite()), brought: "A", logger: logger), "A") + } + + func test_a_group_the_sdk_does_not_make_is_refused_and_the_device_gets_its_own() { + let shop = "shop-\(UUID().uuidString)" + let logger = SdkLogger(shopId: shop, level: .warning) + let refused = ["a", "b", "C", " A", "B ", "AB", "0", "segment"] + for brought in refused { + let device = DeviceStore(defaults: suite(), pushTokenDefaults: suite()) + let group = SimplePersonalizationSDK.abSegment(of: UserIdentityRepositoryImpl(store: suite(), device: device), brought: brought, logger: logger) + XCTAssertTrue(DeviceStore.abGroups.contains(group), brought) + XCTAssertEqual(device.abGroup, group, brought) + } + XCTAssertEqual(configReasons(shop), Array(repeating: "segment_invalid", count: refused.count)) + + for none in [nil, ""] as [String?] { + let group = SimplePersonalizationSDK.abSegment(of: UserIdentityRepositoryImpl(store: suite(), device: DeviceStore(defaults: suite(), pushTokenDefaults: suite())), brought: none, logger: logger) + XCTAssertTrue(DeviceStore.abGroups.contains(group)) + } + XCTAssertEqual(configReasons(shop).count, refused.count, "none is not refused") + } + func test_shops_made_at_once_get_one_group() { let device = DeviceStore(defaults: suite(), pushTokenDefaults: suite()) let lock = NSLock()