From b2967612ce964c2c5f7afd97f086b954f1c84045 Mon Sep 17 00:00:00 2001 From: huhuanming Date: Thu, 26 Nov 2026 17:37:08 +0800 Subject: [PATCH 1/3] feat(device-utils): report SKAdNetwork conversion values Add markSkanMilestones(bits, coarseRule). On iOS 16.1+ it ORs the bits into the stored fine conversion value (0-63), derives the coarse value from the caller's masks, and calls SKAdNetwork.updatePostbackConversionValue with lockWindow false. The value only grows, and an unchanged value skips the system call. The main and background runtimes share one process-wide serial queue, so read, merge, report and persist run as one step and a smaller value is never reported after a larger one. The value is persisted to UserDefaults only after SKAdNetwork accepts it; an error or a 30 second timeout rejects and leaves it for the next call to retry. Android and older iOS resolve to undefined. The pod links StoreKit, and the XCTest suite covers merging, coarse mapping, skips, retries, validation, timeout and concurrent callers. Co-Authored-By: Claude Opus 5.5 --- example/react-native/ios/Podfile.lock | 2 +- .../ReactNativeDeviceUtils.podspec | 2 +- .../ReactNativeDeviceUtils.kt | 8 + .../react-native-device-utils/docs/SPEC.md | 58 ++++++ .../ios/ReactNativeDeviceUtils.swift | 38 ++++ .../ios/SkanConversionStore.swift | 159 +++++++++++++++++ .../ios/tests/SkanConversionTests.swift | 168 ++++++++++++++++++ .../src/ReactNativeDeviceUtils.nitro.ts | 29 +++ 8 files changed, 462 insertions(+), 2 deletions(-) create mode 100644 native-modules/react-native-device-utils/ios/SkanConversionStore.swift create mode 100644 native-modules/react-native-device-utils/ios/tests/SkanConversionTests.swift diff --git a/example/react-native/ios/Podfile.lock b/example/react-native/ios/Podfile.lock index 79eb464e5..b600a2cde 100644 --- a/example/react-native/ios/Podfile.lock +++ b/example/react-native/ios/Podfile.lock @@ -3927,7 +3927,7 @@ SPEC CHECKSUMS: ReactNativeCaptureProtection: ac103d5f2311fc6cb7412b49ebdc821b845bf97a ReactNativeCheckBiometricAuthChanged: 9028250455b331bd52a29bf8223ffd29c158e60f ReactNativeDependencies: d3b7423ba1e52525e42085c8470109abde583d2e - ReactNativeDeviceUtils: d3d18adc9c517eee5d427fa7b68ed3a32da57622 + ReactNativeDeviceUtils: 0664aa178122a925cd134c94b782ccfcc7d82b87 ReactNativeGetRandomValues: a8dd2d44b9f13e6a7c5165bf6fbbbf16d422a388 ReactNativeImageCropPicker: bb1e798732909427df3f83f2d0159f815bacc773 ReactNativeJpush: 7e7958e03c904e0bcc1f45b38688f4ec3bfb823f diff --git a/native-modules/react-native-device-utils/ReactNativeDeviceUtils.podspec b/native-modules/react-native-device-utils/ReactNativeDeviceUtils.podspec index 4b4f98f10..b3144c857 100644 --- a/native-modules/react-native-device-utils/ReactNativeDeviceUtils.podspec +++ b/native-modules/react-native-device-utils/ReactNativeDeviceUtils.podspec @@ -19,7 +19,7 @@ Pod::Spec.new do |s| "cpp/**/*.{hpp,cpp}", ] s.exclude_files = "ios/tests/**/*" - s.frameworks = "AdServices" + s.frameworks = "AdServices", "StoreKit" s.dependency 'React-jsi' s.dependency 'React-callinvoker' diff --git a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/ReactNativeDeviceUtils.kt b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/ReactNativeDeviceUtils.kt index 4bf72f214..8c0e627df 100644 --- a/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/ReactNativeDeviceUtils.kt +++ b/native-modules/react-native-device-utils/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/ReactNativeDeviceUtils.kt @@ -1353,6 +1353,14 @@ class ReactNativeDeviceUtils : HybridReactNativeDeviceUtilsSpec(), LifecycleEven return Promise.resolved(null) } + // SKAdNetwork is iOS-only. + override fun markSkanMilestones( + bits: Double, + coarseRule: SkanCoarseRule + ): Promise { + return Promise.resolved(null) + } + // MARK: - Android Channel & Installer override fun getAndroidChannel(): AndroidChannel { diff --git a/native-modules/react-native-device-utils/docs/SPEC.md b/native-modules/react-native-device-utils/docs/SPEC.md index 87b95d9a7..f0c613b16 100644 --- a/native-modules/react-native-device-utils/docs/SPEC.md +++ b/native-modules/react-native-device-utils/docs/SPEC.md @@ -610,3 +610,61 @@ non-empty string, an empty string, and a thrown error. Android native CI builds the Kotlin implementation and generated JNI bindings. The consumer's Android native harness verifies the result is JavaScript `undefined`. Real AdServices token issuance requires an on-device check. + +# DeviceUtils: SKAdNetwork conversion value + +## Scope and platform contract + +`markSkanMilestones(bits, coarseRule): Promise` +ORs `bits` (an integer from 0 to 63) into the stored SKAdNetwork fine +conversion value. On iOS 16.1 and later it then calls +`SKAdNetwork.updatePostbackConversionValue(_:coarseValue:lockWindow:completionHandler:)` +with `lockWindow: false`. Android and older iOS resolve to `undefined`. + +The coarse value is `high` when the merged value shares a bit with +`coarseRule.highMask`. Otherwise it is `medium` when it shares a bit with +`coarseRule.mediumMask`, and `low` in every other case. Both masks are integers +from 0 to 63. The OneKey app owns the milestone bit schema and the masks, and +must keep them in line with the conversion value schema configured for the ad +network. DeviceUtils assigns no meaning to individual bits. + +The result carries the merged `fineValue`, its `coarseValue`, and `updated`. +`updated` is `false` when neither the fine value nor the coarse value changed +since the last accepted report, in which case SKAdNetwork is not called. The +first call always reports, even with `bits` set to 0. + +## Lifecycle and concurrency + +The main and background React runtimes each create their own HybridObject. +Every call goes through one process-wide store with a serial queue, so the +read, merge, report and persist steps run as one unit. Calls from either +runtime are applied in arrival order, and a smaller value is never reported +after a larger one. The queue waits for the SKAdNetwork completion handler for +up to 30 seconds before the next call runs. + +## Data and retention + +The last accepted fine value and coarse value live in `UserDefaults.standard` +under `so.onekey.deviceutils.skan.fineValue` and +`so.onekey.deviceutils.skan.coarseValue`. They are written only after +SKAdNetwork accepts the update. Deleting the app clears them, which matches a +new install's fresh attribution. The values are not logged and hold no user +or wallet identifiers. + +## Failure + +The Promise rejects when an input is not an integer from 0 to 63, when +SKAdNetwork returns an error (for example after the last conversion window +has closed), or when SKAdNetwork does not answer within 30 seconds. A rejected +call leaves the stored value unchanged, so the next call reports again. + +## Conformance and acceptance + +The contract is defined in `src/ReactNativeDeviceUtils.nitro.ts` and implemented +in `ios/SkanConversionStore.swift`, `ios/ReactNativeDeviceUtils.swift` and +`ReactNativeDeviceUtils.kt`. The iOS pod's XCTest suite injects a reporter and +an isolated `UserDefaults` suite. It covers bit merging, coarse mapping, skipped +unchanged values, a coarse rule change, a rejected report that is retried, +input validation, a timeout, and concurrent callers that only ever report +increasing values. Android native CI builds the Kotlin stub. A real SKAdNetwork +postback needs an on-device check with SKAdNetwork developer mode enabled. diff --git a/native-modules/react-native-device-utils/ios/ReactNativeDeviceUtils.swift b/native-modules/react-native-device-utils/ios/ReactNativeDeviceUtils.swift index a9776c4f8..9b2c5878f 100644 --- a/native-modules/react-native-device-utils/ios/ReactNativeDeviceUtils.swift +++ b/native-modules/react-native-device-utils/ios/ReactNativeDeviceUtils.swift @@ -424,4 +424,42 @@ class ReactNativeDeviceUtils: HybridReactNativeDeviceUtilsSpec { return token } } + + func markSkanMilestones(bits: Double, coarseRule: SkanCoarseRule) throws -> Promise { + guard #available(iOS 16.1, *) else { + return .resolved(withResult: nil) + } + return Self.markSkanMilestones(using: .shared, bits: bits, coarseRule: coarseRule) + } + + static func markSkanMilestones( + using store: SkanConversionStore, + bits: Double, + coarseRule: SkanCoarseRule + ) -> Promise { + let promise = Promise() + store.mark( + bits: bits, + highMask: coarseRule.highMask, + mediumMask: coarseRule.mediumMask + ) { result in + switch result { + case .success(let outcome): + let coarseValue: SkanCoarseValue + switch outcome.coarse { + case .low: coarseValue = .low + case .medium: coarseValue = .medium + case .high: coarseValue = .high + } + promise.resolve(withResult: SkanUpdateResult( + fineValue: Double(outcome.fineValue), + coarseValue: coarseValue, + updated: outcome.updated + )) + case .failure(let error): + promise.reject(withError: error) + } + } + return promise + } } diff --git a/native-modules/react-native-device-utils/ios/SkanConversionStore.swift b/native-modules/react-native-device-utils/ios/SkanConversionStore.swift new file mode 100644 index 000000000..8281f094c --- /dev/null +++ b/native-modules/react-native-device-utils/ios/SkanConversionStore.swift @@ -0,0 +1,159 @@ +import Foundation +import StoreKit + +enum SkanCoarse: String { + case low + case medium + case high +} + +struct SkanMergeOutcome: Equatable { + let fineValue: Int + let coarse: SkanCoarse + let updated: Bool +} + +enum SkanConversionError: Error, Equatable, LocalizedError { + case invalidValue(String) + case unsupported + case timedOut + case reportFailed(String) + + var errorDescription: String? { + switch self { + case .invalidValue(let name): + return "\(name) must be an integer from 0 to 63" + case .unsupported: + return "SKAdNetwork conversion values need iOS 16.1 or later" + case .timedOut: + return "SKAdNetwork did not answer the conversion value update" + case .reportFailed(let message): + return "SKAdNetwork rejected the conversion value update: \(message)" + } + } +} + +/// Merges milestone bits into the SKAdNetwork fine conversion value. +/// +/// Main and background React runtimes each create their own HybridObject, so +/// the shared instance and its serial queue are process-wide. That queue makes +/// read, merge, report and persist one step: two runtimes can never report a +/// smaller value after a larger one. The value is persisted only after +/// SKAdNetwork accepts it, so a failed update is retried by the next call. +final class SkanConversionStore { + typealias Reporter = ( + _ fineValue: Int, + _ coarse: SkanCoarse, + _ completion: @escaping (Error?) -> Void + ) -> Void + + static let fineValueKey = "so.onekey.deviceutils.skan.fineValue" + static let coarseValueKey = "so.onekey.deviceutils.skan.coarseValue" + static let maxValue = 63 + + static let shared = SkanConversionStore( + defaults: .standard, + reporter: SkanConversionStore.systemReporter + ) + + private let defaults: UserDefaults + private let reporter: Reporter + private let reportTimeout: DispatchTimeInterval + private let queue = DispatchQueue(label: "so.onekey.deviceutils.skan", qos: .utility) + + init( + defaults: UserDefaults, + reporter: @escaping Reporter, + reportTimeout: DispatchTimeInterval = .seconds(30) + ) { + self.defaults = defaults + self.reporter = reporter + self.reportTimeout = reportTimeout + } + + static func coarse(for fineValue: Int, highMask: Int, mediumMask: Int) -> SkanCoarse { + if fineValue & highMask != 0 { + return .high + } + if fineValue & mediumMask != 0 { + return .medium + } + return .low + } + + static func validated(_ value: Double, name: String) throws -> Int { + guard value.isFinite, value.rounded() == value, value >= 0, value <= Double(maxValue) else { + throw SkanConversionError.invalidValue(name) + } + return Int(value) + } + + /// Completion runs on the store's private queue. + func mark( + bits: Double, + highMask: Double, + mediumMask: Double, + completion: @escaping (Result) -> Void + ) { + queue.async { [self] in + completion(Result { try markOnQueue(bits: bits, highMask: highMask, mediumMask: mediumMask) }) + } + } + + private func markOnQueue(bits: Double, highMask: Double, mediumMask: Double) throws -> SkanMergeOutcome { + let bits = try Self.validated(bits, name: "bits") + let highMask = try Self.validated(highMask, name: "coarseRule.highMask") + let mediumMask = try Self.validated(mediumMask, name: "coarseRule.mediumMask") + + let hasReported = defaults.object(forKey: Self.fineValueKey) != nil + let previous = defaults.integer(forKey: Self.fineValueKey) & Self.maxValue + let fineValue = previous | bits + let coarse = Self.coarse(for: fineValue, highMask: highMask, mediumMask: mediumMask) + let previousCoarse = defaults.string(forKey: Self.coarseValueKey) + if hasReported && fineValue == previous && previousCoarse == coarse.rawValue { + return SkanMergeOutcome(fineValue: fineValue, coarse: coarse, updated: false) + } + + // The completion handler arrives on a StoreKit queue, never this one, + // so waiting here keeps later calls ordered behind this report. + let semaphore = DispatchSemaphore(value: 0) + var reportError: Error? + reporter(fineValue, coarse) { error in + reportError = error + semaphore.signal() + } + guard semaphore.wait(timeout: .now() + reportTimeout) == .success else { + throw SkanConversionError.timedOut + } + if let reportError { + if let skanError = reportError as? SkanConversionError { + throw skanError + } + throw SkanConversionError.reportFailed(reportError.localizedDescription) + } + + defaults.set(fineValue, forKey: Self.fineValueKey) + defaults.set(coarse.rawValue, forKey: Self.coarseValueKey) + return SkanMergeOutcome(fineValue: fineValue, coarse: coarse, updated: true) + } + + private static let systemReporter: Reporter = { fineValue, coarse, completion in + guard #available(iOS 16.1, *) else { + completion(SkanConversionError.unsupported) + return + } + let coarseValue: SKAdNetwork.CoarseConversionValue + switch coarse { + case .low: coarseValue = .low + case .medium: coarseValue = .medium + case .high: coarseValue = .high + } + // lockWindow stays false: TikTok asks advertisers not to lock windows early. + SKAdNetwork.updatePostbackConversionValue( + fineValue, + coarseValue: coarseValue, + lockWindow: false, + completionHandler: completion + ) + } +} diff --git a/native-modules/react-native-device-utils/ios/tests/SkanConversionTests.swift b/native-modules/react-native-device-utils/ios/tests/SkanConversionTests.swift new file mode 100644 index 000000000..fba1d3c11 --- /dev/null +++ b/native-modules/react-native-device-utils/ios/tests/SkanConversionTests.swift @@ -0,0 +1,168 @@ +import NitroModules +import XCTest +@testable import ReactNativeDeviceUtils + +final class SkanConversionTests: XCTestCase { + private enum ReporterError: Error, LocalizedError { + case windowClosed + + var errorDescription: String? { "window closed" } + } + + private final class RecordingReporter { + private let lock = NSLock() + private var calls: [(Int, SkanCoarse)] = [] + var failNext: Error? + + var recorded: [(Int, SkanCoarse)] { + lock.lock() + defer { lock.unlock() } + return calls + } + + func report(_ fineValue: Int, _ coarse: SkanCoarse, _ completion: @escaping (Error?) -> Void) { + lock.lock() + calls.append((fineValue, coarse)) + let error = failNext + failNext = nil + lock.unlock() + // StoreKit answers on its own queue. + DispatchQueue.global().async { completion(error) } + } + } + + private let rule = SkanCoarseRule(highMask: 0b011000, mediumMask: 0b000110) + private var suiteName = "" + private var defaults: UserDefaults! + private var reporter: RecordingReporter! + private var store: SkanConversionStore! + + override func setUp() { + super.setUp() + suiteName = "SkanConversionTests.\(UUID().uuidString)" + defaults = UserDefaults(suiteName: suiteName) + reporter = RecordingReporter() + let reporter = reporter! + store = SkanConversionStore(defaults: defaults) { reporter.report($0, $1, $2) } + } + + override func tearDown() { + defaults.removePersistentDomain(forName: suiteName) + super.tearDown() + } + + private func mark(_ bits: Double, rule: SkanCoarseRule? = nil) async throws -> SkanUpdateResult? { + try await ReactNativeDeviceUtils + .markSkanMilestones(using: store, bits: bits, coarseRule: rule ?? self.rule) + .await() + } + + func testMergesBitsAndOnlyGrows() async throws { + let first = try await mark(1) + XCTAssertEqual(first?.fineValue, 1) + XCTAssertEqual(first?.coarseValue, .low) + XCTAssertEqual(first?.updated, true) + + let second = try await mark(2) + XCTAssertEqual(second?.fineValue, 3) + XCTAssertEqual(second?.coarseValue, .medium) + + let third = try await mark(8) + XCTAssertEqual(third?.fineValue, 11) + XCTAssertEqual(third?.coarseValue, .high) + + XCTAssertEqual(reporter.recorded.map(\.0), [1, 3, 11]) + XCTAssertEqual(reporter.recorded.map(\.1), [.low, .medium, .high]) + } + + func testSkipsUnchangedValue() async throws { + _ = try await mark(3) + let repeated = try await mark(1) + XCTAssertEqual(repeated?.fineValue, 3) + XCTAssertEqual(repeated?.updated, false) + XCTAssertEqual(reporter.recorded.count, 1) + } + + func testReportsZeroOnceOnFirstCall() async throws { + let first = try await mark(0) + XCTAssertEqual(first?.updated, true) + let second = try await mark(0) + XCTAssertEqual(second?.updated, false) + XCTAssertEqual(reporter.recorded.count, 1) + } + + func testReportsAgainWhenCoarseRuleChanges() async throws { + _ = try await mark(2) + let reclassified = try await mark(0, rule: SkanCoarseRule(highMask: 2, mediumMask: 0)) + XCTAssertEqual(reclassified?.coarseValue, .high) + XCTAssertEqual(reclassified?.updated, true) + XCTAssertEqual(reporter.recorded.count, 2) + } + + func testFailedReportIsNotPersistedAndRetries() async throws { + reporter.failNext = ReporterError.windowClosed + do { + _ = try await mark(4) + XCTFail("Expected the reporter error to reject") + } catch { + XCTAssertEqual( + error.localizedDescription, + "SKAdNetwork rejected the conversion value update: window closed" + ) + } + XCTAssertNil(defaults.object(forKey: SkanConversionStore.fineValueKey)) + + let retried = try await mark(4) + XCTAssertEqual(retried?.fineValue, 4) + XCTAssertEqual(retried?.updated, true) + XCTAssertEqual(reporter.recorded.map(\.0), [4, 4]) + } + + func testRejectsInvalidInput() async { + for bits in [-1, 64, 1.5, Double.nan, Double.infinity] { + do { + _ = try await mark(bits) + XCTFail("Expected \(bits) to reject") + } catch { + XCTAssertEqual(error as? SkanConversionError, .invalidValue("bits")) + } + } + do { + _ = try await mark(1, rule: SkanCoarseRule(highMask: 128, mediumMask: 0)) + XCTFail("Expected an out-of-range mask to reject") + } catch { + XCTAssertEqual(error as? SkanConversionError, .invalidValue("coarseRule.highMask")) + } + XCTAssertTrue(reporter.recorded.isEmpty) + } + + func testTimesOutWithoutPersisting() async { + let silent = SkanConversionStore( + defaults: defaults, + reporter: { _, _, _ in }, + reportTimeout: .milliseconds(50) + ) + do { + _ = try await ReactNativeDeviceUtils + .markSkanMilestones(using: silent, bits: 1, coarseRule: rule) + .await() + XCTFail("Expected a timeout") + } catch { + XCTAssertEqual(error as? SkanConversionError, .timedOut) + } + XCTAssertNil(defaults.object(forKey: SkanConversionStore.fineValueKey)) + } + + func testConcurrentCallersNeverReportASmallerValue() async throws { + try await withThrowingTaskGroup(of: Void.self) { group in + for bit in 0..<6 { + group.addTask { _ = try await self.mark(Double(1 << bit)) } + } + try await group.waitForAll() + } + let values = reporter.recorded.map(\.0) + XCTAssertEqual(values.last, 63) + XCTAssertEqual(values, values.sorted()) + XCTAssertEqual(defaults.integer(forKey: SkanConversionStore.fineValueKey), 63) + } +} diff --git a/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts b/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts index 212e70934..30df7e379 100644 --- a/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts +++ b/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts @@ -87,6 +87,22 @@ export interface GooglePlayServicesStatus { isAvailable: boolean; } +export type SkanCoarseValue = 'low' | 'medium' | 'high'; + +/** Bit masks (0-63) that map a fine conversion value to a coarse value. */ +export interface SkanCoarseRule { + highMask: number; + mediumMask: number; +} + +export interface SkanUpdateResult { + /** Merged fine conversion value now held by SKAdNetwork (0-63). */ + fineValue: number; + coarseValue: SkanCoarseValue; + /** False when the merged value was unchanged and SKAdNetwork was not called. */ + updated: boolean; +} + export interface ReactNativeDeviceUtils extends HybridObject<{ ios: 'swift'; android: 'kotlin' }> { initEventListeners(): void; @@ -182,4 +198,17 @@ export interface ReactNativeDeviceUtils /** Returns an AdServices token on iOS 14.3+, or undefined on unsupported platforms. */ getAppleAdsAttributionToken(): Promise; + + /** + * ORs `bits` (0-63) into the stored SKAdNetwork fine conversion value and + * reports it to SKAdNetwork on iOS 16.1+. The value only grows. The coarse + * value is `high` when the merged value shares a bit with + * `coarseRule.highMask`, else `medium` for `coarseRule.mediumMask`, else + * `low`. Rejects on invalid input or a SKAdNetwork error, keeping the stored + * value so a later call retries. Android and older iOS resolve to undefined. + */ + markSkanMilestones( + bits: number, + coarseRule: SkanCoarseRule + ): Promise; } From 60c72957e0b7703213d09c3fb0b4b911accf0b77 Mon Sep 17 00:00:00 2001 From: huhuanming Date: Thu, 26 Nov 2026 17:48:23 +0800 Subject: [PATCH 2/3] fix(device-utils): report SKAN values in each conversion window --- .../react-native-device-utils/docs/SPEC.md | 58 +++++++++----- .../ios/ReactNativeDeviceUtils.swift | 2 +- .../ios/SkanConversionStore.swift | 42 ++++++---- .../ios/tests/SkanConversionTests.swift | 80 +++++++++++++++++-- .../src/ReactNativeDeviceUtils.nitro.ts | 15 ++-- 5 files changed, 145 insertions(+), 52 deletions(-) diff --git a/native-modules/react-native-device-utils/docs/SPEC.md b/native-modules/react-native-device-utils/docs/SPEC.md index f0c613b16..626916209 100644 --- a/native-modules/react-native-device-utils/docs/SPEC.md +++ b/native-modules/react-native-device-utils/docs/SPEC.md @@ -628,43 +628,57 @@ from 0 to 63. The OneKey app owns the milestone bit schema and the masks, and must keep them in line with the conversion value schema configured for the ad network. DeviceUtils assigns no meaning to individual bits. -The result carries the merged `fineValue`, its `coarseValue`, and `updated`. -`updated` is `false` when neither the fine value nor the coarse value changed -since the last accepted report, in which case SKAdNetwork is not called. The -first call always reports, even with `bits` set to 0. +Supported iOS calls submit to StoreKit even with `bits` set to 0 or with the +same fine and coarse values as the last report, subject to the validation and +in-flight rules below. +SKAdNetwork 4 requires an update during each conversion window for multiple +postbacks. StoreKit manages the windows, and the app must call this API during +each window in which it wants to submit an update. + +The result carries the submitted `fineValue`, its `coarseValue`, and +`updated: true` after StoreKit reports success. StoreKit determines which +values appear in a postback. SKAdNetwork 4 uses only coarse values in the +second and third windows. ## Lifecycle and concurrency The main and background React runtimes each create their own HybridObject. Every call goes through one process-wide store with a serial queue, so the read, merge, report and persist steps run as one unit. Calls from either -runtime are applied in arrival order, and a smaller value is never reported -after a larger one. The queue waits for the SKAdNetwork completion handler for -up to 30 seconds before the next call runs. +runtime are applied in arrival order, and the fine value includes every bit +from prior accepted submissions. The queue waits for the SKAdNetwork +completion handler for up to 30 seconds. A timed-out submission remains in +flight until StoreKit completes it. While it is pending, subsequent valid +calls reject without making another submission. A late success persists the +accepted fine value before submissions resume. A late failure releases the +queue for new submissions with the previous stored value. If StoreKit never +completes a timed-out submission, only a process restart resets this guard. ## Data and retention -The last accepted fine value and coarse value live in `UserDefaults.standard` -under `so.onekey.deviceutils.skan.fineValue` and -`so.onekey.deviceutils.skan.coarseValue`. They are written only after -SKAdNetwork accepts the update. Deleting the app clears them, which matches a -new install's fresh attribution. The values are not logged and hold no user -or wallet identifiers. +The last accepted fine value lives in `UserDefaults.standard` under +`so.onekey.deviceutils.skan.fineValue`. It is written only after SKAdNetwork +accepts the update. The coarse value is derived on every call from the merged +fine value and the caller's masks. Deleting the app clears the stored value, +which matches a new install's fresh attribution. The value is not logged and +holds no user or wallet identifiers. ## Failure -The Promise rejects when an input is not an integer from 0 to 63, when -SKAdNetwork returns an error (for example after the last conversion window -has closed), or when SKAdNetwork does not answer within 30 seconds. A rejected -call leaves the stored value unchanged, so the next call reports again. +The Promise rejects for invalid inputs, StoreKit errors, a 30-second timeout, +or a pending timed-out submission. The last accepted fine value stays in +storage until StoreKit confirms a successful update, including a late +success. The caller can retry with the same bits and masks when submissions +resume. ## Conformance and acceptance The contract is defined in `src/ReactNativeDeviceUtils.nitro.ts` and implemented in `ios/SkanConversionStore.swift`, `ios/ReactNativeDeviceUtils.swift` and `ReactNativeDeviceUtils.kt`. The iOS pod's XCTest suite injects a reporter and -an isolated `UserDefaults` suite. It covers bit merging, coarse mapping, skipped -unchanged values, a coarse rule change, a rejected report that is retried, -input validation, a timeout, and concurrent callers that only ever report -increasing values. Android native CI builds the Kotlin stub. A real SKAdNetwork -postback needs an on-device check with SKAdNetwork developer mode enabled. +an isolated `UserDefaults` suite. It covers bit merging, coarse mapping, the +same fine and coarse values submitted in consecutive simulated windows, zero +values, a coarse rule change, rejected reports and retries, input validation, +a timeout with late completion, and concurrent callers. Android native CI +builds the Kotlin stub. Confirming real postbacks across windows requires an +eligible ad attribution on a test device. diff --git a/native-modules/react-native-device-utils/ios/ReactNativeDeviceUtils.swift b/native-modules/react-native-device-utils/ios/ReactNativeDeviceUtils.swift index 9b2c5878f..7430a4281 100644 --- a/native-modules/react-native-device-utils/ios/ReactNativeDeviceUtils.swift +++ b/native-modules/react-native-device-utils/ios/ReactNativeDeviceUtils.swift @@ -454,7 +454,7 @@ class ReactNativeDeviceUtils: HybridReactNativeDeviceUtilsSpec { promise.resolve(withResult: SkanUpdateResult( fineValue: Double(outcome.fineValue), coarseValue: coarseValue, - updated: outcome.updated + updated: true )) case .failure(let error): promise.reject(withError: error) diff --git a/native-modules/react-native-device-utils/ios/SkanConversionStore.swift b/native-modules/react-native-device-utils/ios/SkanConversionStore.swift index 8281f094c..64343c2a2 100644 --- a/native-modules/react-native-device-utils/ios/SkanConversionStore.swift +++ b/native-modules/react-native-device-utils/ios/SkanConversionStore.swift @@ -1,22 +1,22 @@ import Foundation import StoreKit -enum SkanCoarse: String { +enum SkanCoarse { case low case medium case high } -struct SkanMergeOutcome: Equatable { +struct SkanMergeOutcome { let fineValue: Int let coarse: SkanCoarse - let updated: Bool } enum SkanConversionError: Error, Equatable, LocalizedError { case invalidValue(String) case unsupported case timedOut + case reportInProgress case reportFailed(String) var errorDescription: String? { @@ -27,6 +27,8 @@ enum SkanConversionError: Error, Equatable, LocalizedError { return "SKAdNetwork conversion values need iOS 16.1 or later" case .timedOut: return "SKAdNetwork did not answer the conversion value update" + case .reportInProgress: + return "SKAdNetwork has not completed the previous conversion value update" case .reportFailed(let message): return "SKAdNetwork rejected the conversion value update: \(message)" } @@ -36,10 +38,9 @@ enum SkanConversionError: Error, Equatable, LocalizedError { /// Merges milestone bits into the SKAdNetwork fine conversion value. /// /// Main and background React runtimes each create their own HybridObject, so -/// the shared instance and its serial queue are process-wide. That queue makes -/// read, merge, report and persist one step: two runtimes can never report a -/// smaller value after a larger one. The value is persisted only after -/// SKAdNetwork accepts it, so a failed update is retried by the next call. +/// the shared instance and its serial queue are process-wide. The queue keeps +/// read, merge, report and persist in order so each call includes the bits +/// from prior successful reports. final class SkanConversionStore { typealias Reporter = ( _ fineValue: Int, @@ -48,7 +49,6 @@ final class SkanConversionStore { ) -> Void static let fineValueKey = "so.onekey.deviceutils.skan.fineValue" - static let coarseValueKey = "so.onekey.deviceutils.skan.coarseValue" static let maxValue = 63 static let shared = SkanConversionStore( @@ -60,6 +60,7 @@ final class SkanConversionStore { private let reporter: Reporter private let reportTimeout: DispatchTimeInterval private let queue = DispatchQueue(label: "so.onekey.deviceutils.skan", qos: .utility) + private var timedOutReport: DispatchSemaphore? init( defaults: UserDefaults, @@ -105,24 +106,34 @@ final class SkanConversionStore { let highMask = try Self.validated(highMask, name: "coarseRule.highMask") let mediumMask = try Self.validated(mediumMask, name: "coarseRule.mediumMask") - let hasReported = defaults.object(forKey: Self.fineValueKey) != nil + guard timedOutReport == nil else { + throw SkanConversionError.reportInProgress + } + let previous = defaults.integer(forKey: Self.fineValueKey) & Self.maxValue let fineValue = previous | bits let coarse = Self.coarse(for: fineValue, highMask: highMask, mediumMask: mediumMask) - let previousCoarse = defaults.string(forKey: Self.coarseValueKey) - if hasReported && fineValue == previous && previousCoarse == coarse.rawValue { - return SkanMergeOutcome(fineValue: fineValue, coarse: coarse, updated: false) - } + // An unchanged value can be the first update in a later StoreKit window. // The completion handler arrives on a StoreKit queue, never this one, // so waiting here keeps later calls ordered behind this report. let semaphore = DispatchSemaphore(value: 0) var reportError: Error? - reporter(fineValue, coarse) { error in + reporter(fineValue, coarse) { [weak self] error in reportError = error semaphore.signal() + self?.queue.async { [weak self] in + guard let self, self.timedOutReport === semaphore else { return } + if error == nil { + self.defaults.set(fineValue, forKey: Self.fineValueKey) + } + self.timedOutReport = nil + } } guard semaphore.wait(timeout: .now() + reportTimeout) == .success else { + // StoreKit has no cancellation API. Keep subsequent reports gated + // until the callback reconciles the accepted value on this queue. + timedOutReport = semaphore throw SkanConversionError.timedOut } if let reportError { @@ -133,8 +144,7 @@ final class SkanConversionStore { } defaults.set(fineValue, forKey: Self.fineValueKey) - defaults.set(coarse.rawValue, forKey: Self.coarseValueKey) - return SkanMergeOutcome(fineValue: fineValue, coarse: coarse, updated: true) + return SkanMergeOutcome(fineValue: fineValue, coarse: coarse) } private static let systemReporter: Reporter = { fineValue, coarse, completion in diff --git a/native-modules/react-native-device-utils/ios/tests/SkanConversionTests.swift b/native-modules/react-native-device-utils/ios/tests/SkanConversionTests.swift index fba1d3c11..b5143b10a 100644 --- a/native-modules/react-native-device-utils/ios/tests/SkanConversionTests.swift +++ b/native-modules/react-native-device-utils/ios/tests/SkanConversionTests.swift @@ -75,20 +75,31 @@ final class SkanConversionTests: XCTestCase { XCTAssertEqual(reporter.recorded.map(\.1), [.low, .medium, .high]) } - func testSkipsUnchangedValue() async throws { - _ = try await mark(3) - let repeated = try await mark(1) + func testReportsUnchangedValuesInNextWindow() async throws { + let first = try await mark(3) + XCTAssertEqual(first?.updated, true) + XCTAssertEqual(reporter.recorded.map(\.0), [3]) + XCTAssertEqual(reporter.recorded.map(\.1), [.medium]) + + // Simulate a later window after relaunch, using the same stored bits + // with a fresh store and reporter for the new window. + let nextWindowReporter = RecordingReporter() + store = SkanConversionStore(defaults: defaults, reporter: nextWindowReporter.report) + let repeated = try await mark(0) XCTAssertEqual(repeated?.fineValue, 3) - XCTAssertEqual(repeated?.updated, false) - XCTAssertEqual(reporter.recorded.count, 1) + XCTAssertEqual(repeated?.coarseValue, .medium) + XCTAssertEqual(repeated?.updated, true) + XCTAssertEqual(nextWindowReporter.recorded.map(\.0), [3]) + XCTAssertEqual(nextWindowReporter.recorded.map(\.1), [.medium]) } - func testReportsZeroOnceOnFirstCall() async throws { + func testReportsZeroOnEveryCall() async throws { let first = try await mark(0) XCTAssertEqual(first?.updated, true) let second = try await mark(0) - XCTAssertEqual(second?.updated, false) - XCTAssertEqual(reporter.recorded.count, 1) + XCTAssertEqual(second?.updated, true) + XCTAssertEqual(reporter.recorded.map(\.0), [0, 0]) + XCTAssertEqual(reporter.recorded.map(\.1), [.low, .low]) } func testReportsAgainWhenCoarseRuleChanges() async throws { @@ -153,6 +164,59 @@ final class SkanConversionTests: XCTestCase { XCTAssertNil(defaults.object(forKey: SkanConversionStore.fineValueKey)) } + func testLateSuccessPersistsBeforeSubmissionsResume() async throws { + try await checkLateCompletion(error: nil, expectedStoredValue: 8, expectedNextValue: 9) + } + + func testLateFailureAllowsRetryWithoutPersisting() async throws { + try await checkLateCompletion( + error: ReporterError.windowClosed, + expectedStoredValue: 0, + expectedNextValue: 1 + ) + } + + private func checkLateCompletion( + error: Error?, + expectedStoredValue: Int, + expectedNextValue: Double + ) async throws { + var finishFirstReport: ((Error?) -> Void)? + let reporter = reporter! + store = SkanConversionStore( + defaults: defaults, + reporter: { fineValue, coarse, completion in + if finishFirstReport == nil { + finishFirstReport = completion + } else { + reporter.report(fineValue, coarse, completion) + } + }, + reportTimeout: .milliseconds(50) + ) + do { + _ = try await mark(8) + XCTFail("Expected a timeout") + } catch { + XCTAssertEqual(error as? SkanConversionError, .timedOut) + } + do { + _ = try await mark(1) + XCTFail("Expected the timed-out report to block submissions") + } catch { + XCTAssertEqual(error as? SkanConversionError, .reportInProgress) + } + XCTAssertNil(defaults.object(forKey: SkanConversionStore.fineValueKey)) + + let finish = try XCTUnwrap(finishFirstReport) + finish(error) + let stored = try await mark(0) + let next = try await mark(1) + XCTAssertEqual(stored?.fineValue, Double(expectedStoredValue)) + XCTAssertEqual(next?.fineValue, expectedNextValue) + XCTAssertEqual(reporter.recorded.map(\.0), [expectedStoredValue, Int(expectedNextValue)]) + } + func testConcurrentCallersNeverReportASmallerValue() async throws { try await withThrowingTaskGroup(of: Void.self) { group in for bit in 0..<6 { diff --git a/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts b/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts index 30df7e379..00dd14c78 100644 --- a/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts +++ b/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts @@ -96,10 +96,13 @@ export interface SkanCoarseRule { } export interface SkanUpdateResult { - /** Merged fine conversion value now held by SKAdNetwork (0-63). */ + /** + * Merged fine conversion value submitted to SKAdNetwork (0-63). + * Only the first SKAdNetwork 4 conversion window uses fine values. + */ fineValue: number; coarseValue: SkanCoarseValue; - /** False when the merged value was unchanged and SKAdNetwork was not called. */ + /** True when StoreKit reports a successful submission. */ updated: boolean; } @@ -201,11 +204,13 @@ export interface ReactNativeDeviceUtils /** * ORs `bits` (0-63) into the stored SKAdNetwork fine conversion value and - * reports it to SKAdNetwork on iOS 16.1+. The value only grows. The coarse + * submits it to SKAdNetwork on every call on iOS 16.1+, even if the values + * are unchanged. Call during each conversion window that needs an update. + * The fine value accumulates bits from successful submissions. The coarse * value is `high` when the merged value shares a bit with * `coarseRule.highMask`, else `medium` for `coarseRule.mediumMask`, else - * `low`. Rejects on invalid input or a SKAdNetwork error, keeping the stored - * value so a later call retries. Android and older iOS resolve to undefined. + * `low`. Rejects on invalid input, a StoreKit error, a timeout, or while a + * timed-out submission is still pending. Android and older iOS resolve to undefined. */ markSkanMilestones( bits: number, From 192425e28d066e039d4c793f13cfbff14c09efa0 Mon Sep 17 00:00:00 2001 From: huhuanming Date: Thu, 26 Nov 2026 17:51:31 +0800 Subject: [PATCH 3/3] fix(device-utils): retry pending SKAN milestone bits --- .../react-native-device-utils/docs/SPEC.md | 37 +++++++++------- .../ios/SkanConversionStore.swift | 28 ++++++++++--- .../ios/tests/SkanConversionTests.swift | 42 ++++++++++++------- .../src/ReactNativeDeviceUtils.nitro.ts | 11 ++--- 4 files changed, 75 insertions(+), 43 deletions(-) diff --git a/native-modules/react-native-device-utils/docs/SPEC.md b/native-modules/react-native-device-utils/docs/SPEC.md index 626916209..87f604bac 100644 --- a/native-modules/react-native-device-utils/docs/SPEC.md +++ b/native-modules/react-native-device-utils/docs/SPEC.md @@ -616,8 +616,8 @@ token issuance requires an on-device check. ## Scope and platform contract `markSkanMilestones(bits, coarseRule): Promise` -ORs `bits` (an integer from 0 to 63) into the stored SKAdNetwork fine -conversion value. On iOS 16.1 and later it then calls +ORs `bits` (an integer from 0 to 63), pending bits, and the last accepted +SKAdNetwork fine conversion value. On iOS 16.1 and later it then calls `SKAdNetwork.updatePostbackConversionValue(_:coarseValue:lockWindow:completionHandler:)` with `lockWindow: false`. Android and older iOS resolve to `undefined`. @@ -649,27 +649,32 @@ runtime are applied in arrival order, and the fine value includes every bit from prior accepted submissions. The queue waits for the SKAdNetwork completion handler for up to 30 seconds. A timed-out submission remains in flight until StoreKit completes it. While it is pending, subsequent valid -calls reject without making another submission. A late success persists the -accepted fine value before submissions resume. A late failure releases the -queue for new submissions with the previous stored value. If StoreKit never -completes a timed-out submission, only a process restart resets this guard. +calls retain their new bits and reject without making another submission. +A late success persists the accepted fine value and clears the bits it +reports from pending storage before submissions resume. A late failure +leaves all unreported bits pending. If StoreKit never completes a timed-out +submission, only a process restart resets this guard. ## Data and retention The last accepted fine value lives in `UserDefaults.standard` under `so.onekey.deviceutils.skan.fineValue`. It is written only after SKAdNetwork -accepts the update. The coarse value is derived on every call from the merged -fine value and the caller's masks. Deleting the app clears the stored value, -which matches a new install's fresh attribution. The value is not logged and -holds no user or wallet identifiers. +accepts the update. Valid milestone bits are retained separately under +`so.onekey.deviceutils.skan.pendingBits` before submission. An accepted value +is written before its bits are cleared from pending storage. Reports merge +the two values with bitwise OR, so replaying any leftover bits is safe. +Pending bits survive a process restart. The coarse value is derived on every +call from the merged fine value and the caller's current masks. Deleting the +app clears both stored values. The values hold no user or wallet identifiers +and are not logged. ## Failure The Promise rejects for invalid inputs, StoreKit errors, a 30-second timeout, or a pending timed-out submission. The last accepted fine value stays in storage until StoreKit confirms a successful update, including a late -success. The caller can retry with the same bits and masks when submissions -resume. +success. The next submission includes the pending bits, even when the caller +passes `bits: 0`. Invalid calls leave storage unchanged. ## Conformance and acceptance @@ -678,7 +683,7 @@ in `ios/SkanConversionStore.swift`, `ios/ReactNativeDeviceUtils.swift` and `ReactNativeDeviceUtils.kt`. The iOS pod's XCTest suite injects a reporter and an isolated `UserDefaults` suite. It covers bit merging, coarse mapping, the same fine and coarse values submitted in consecutive simulated windows, zero -values, a coarse rule change, rejected reports and retries, input validation, -a timeout with late completion, and concurrent callers. Android native CI -builds the Kotlin stub. Confirming real postbacks across windows requires an -eligible ad attribution on a test device. +values, a coarse rule change, retry after a rejected report and store +recreation, input validation, a timeout with late completion, and concurrent +callers. Android native CI builds the Kotlin stub. Confirming real postbacks +across windows requires an eligible ad attribution on a test device. diff --git a/native-modules/react-native-device-utils/ios/SkanConversionStore.swift b/native-modules/react-native-device-utils/ios/SkanConversionStore.swift index 64343c2a2..5b6eb0a2f 100644 --- a/native-modules/react-native-device-utils/ios/SkanConversionStore.swift +++ b/native-modules/react-native-device-utils/ios/SkanConversionStore.swift @@ -39,8 +39,8 @@ enum SkanConversionError: Error, Equatable, LocalizedError { /// /// Main and background React runtimes each create their own HybridObject, so /// the shared instance and its serial queue are process-wide. The queue keeps -/// read, merge, report and persist in order so each call includes the bits -/// from prior successful reports. +/// read, merge, report and persist in order so each submission includes +/// accepted and pending milestone bits. final class SkanConversionStore { typealias Reporter = ( _ fineValue: Int, @@ -49,6 +49,7 @@ final class SkanConversionStore { ) -> Void static let fineValueKey = "so.onekey.deviceutils.skan.fineValue" + static let pendingBitsKey = "so.onekey.deviceutils.skan.pendingBits" static let maxValue = 63 static let shared = SkanConversionStore( @@ -106,12 +107,18 @@ final class SkanConversionStore { let highMask = try Self.validated(highMask, name: "coarseRule.highMask") let mediumMask = try Self.validated(mediumMask, name: "coarseRule.mediumMask") + let previous = defaults.integer(forKey: Self.fineValueKey) & Self.maxValue + let pending = defaults.integer(forKey: Self.pendingBitsKey) & Self.maxValue + let mergedPending = (pending | bits) & ~previous + if mergedPending != pending { + defaults.set(mergedPending, forKey: Self.pendingBitsKey) + } + guard timedOutReport == nil else { throw SkanConversionError.reportInProgress } - let previous = defaults.integer(forKey: Self.fineValueKey) & Self.maxValue - let fineValue = previous | bits + let fineValue = previous | mergedPending let coarse = Self.coarse(for: fineValue, highMask: highMask, mediumMask: mediumMask) // An unchanged value can be the first update in a later StoreKit window. @@ -125,7 +132,7 @@ final class SkanConversionStore { self?.queue.async { [weak self] in guard let self, self.timedOutReport === semaphore else { return } if error == nil { - self.defaults.set(fineValue, forKey: Self.fineValueKey) + self.recordAccepted(fineValue) } self.timedOutReport = nil } @@ -143,10 +150,19 @@ final class SkanConversionStore { throw SkanConversionError.reportFailed(reportError.localizedDescription) } - defaults.set(fineValue, forKey: Self.fineValueKey) + recordAccepted(fineValue) return SkanMergeOutcome(fineValue: fineValue, coarse: coarse) } + private func recordAccepted(_ fineValue: Int) { + defaults.set(fineValue, forKey: Self.fineValueKey) + let pending = defaults.integer(forKey: Self.pendingBitsKey) + let remaining = pending & ~fineValue + if remaining != pending { + defaults.set(remaining, forKey: Self.pendingBitsKey) + } + } + private static let systemReporter: Reporter = { fineValue, coarse, completion in guard #available(iOS 16.1, *) else { completion(SkanConversionError.unsupported) diff --git a/native-modules/react-native-device-utils/ios/tests/SkanConversionTests.swift b/native-modules/react-native-device-utils/ios/tests/SkanConversionTests.swift index b5143b10a..3042f0d81 100644 --- a/native-modules/react-native-device-utils/ios/tests/SkanConversionTests.swift +++ b/native-modules/react-native-device-utils/ios/tests/SkanConversionTests.swift @@ -110,10 +110,11 @@ final class SkanConversionTests: XCTestCase { XCTAssertEqual(reporter.recorded.count, 2) } - func testFailedReportIsNotPersistedAndRetries() async throws { + func testPendingBitsSurviveARejectedReportAndStoreRecreation() async throws { + _ = try await mark(1) reporter.failNext = ReporterError.windowClosed do { - _ = try await mark(4) + _ = try await mark(2) XCTFail("Expected the reporter error to reject") } catch { XCTAssertEqual( @@ -121,12 +122,17 @@ final class SkanConversionTests: XCTestCase { "SKAdNetwork rejected the conversion value update: window closed" ) } - XCTAssertNil(defaults.object(forKey: SkanConversionStore.fineValueKey)) + XCTAssertEqual(defaults.integer(forKey: SkanConversionStore.fineValueKey), 1) + XCTAssertEqual(defaults.integer(forKey: SkanConversionStore.pendingBitsKey), 2) + let reporter = reporter! + let reopenedDefaults = try XCTUnwrap(UserDefaults(suiteName: suiteName)) + store = SkanConversionStore(defaults: reopenedDefaults, reporter: reporter.report) let retried = try await mark(4) - XCTAssertEqual(retried?.fineValue, 4) + XCTAssertEqual(retried?.fineValue, 7) XCTAssertEqual(retried?.updated, true) - XCTAssertEqual(reporter.recorded.map(\.0), [4, 4]) + XCTAssertEqual(reporter.recorded.map(\.0), [1, 3, 7]) + XCTAssertEqual(defaults.integer(forKey: SkanConversionStore.pendingBitsKey), 0) } func testRejectsInvalidInput() async { @@ -145,9 +151,10 @@ final class SkanConversionTests: XCTestCase { XCTAssertEqual(error as? SkanConversionError, .invalidValue("coarseRule.highMask")) } XCTAssertTrue(reporter.recorded.isEmpty) + XCTAssertNil(defaults.object(forKey: SkanConversionStore.pendingBitsKey)) } - func testTimesOutWithoutPersisting() async { + func testTimeoutRetainsPendingBitsWithoutAdvancingTheAcceptedValue() async { let silent = SkanConversionStore( defaults: defaults, reporter: { _, _, _ in }, @@ -162,33 +169,35 @@ final class SkanConversionTests: XCTestCase { XCTAssertEqual(error as? SkanConversionError, .timedOut) } XCTAssertNil(defaults.object(forKey: SkanConversionStore.fineValueKey)) + XCTAssertEqual(defaults.integer(forKey: SkanConversionStore.pendingBitsKey), 1) } func testLateSuccessPersistsBeforeSubmissionsResume() async throws { - try await checkLateCompletion(error: nil, expectedStoredValue: 8, expectedNextValue: 9) + try await checkLateCompletion(error: nil, expectedAcceptedValue: 8) } func testLateFailureAllowsRetryWithoutPersisting() async throws { try await checkLateCompletion( error: ReporterError.windowClosed, - expectedStoredValue: 0, - expectedNextValue: 1 + expectedAcceptedValue: 0 ) } private func checkLateCompletion( error: Error?, - expectedStoredValue: Int, - expectedNextValue: Double + expectedAcceptedValue: Int ) async throws { var finishFirstReport: ((Error?) -> Void)? + var acceptedBeforeRetry: Int? let reporter = reporter! + let defaults = defaults! store = SkanConversionStore( defaults: defaults, reporter: { fineValue, coarse, completion in if finishFirstReport == nil { finishFirstReport = completion } else { + acceptedBeforeRetry = defaults.integer(forKey: SkanConversionStore.fineValueKey) reporter.report(fineValue, coarse, completion) } }, @@ -207,14 +216,15 @@ final class SkanConversionTests: XCTestCase { XCTAssertEqual(error as? SkanConversionError, .reportInProgress) } XCTAssertNil(defaults.object(forKey: SkanConversionStore.fineValueKey)) + XCTAssertEqual(defaults.integer(forKey: SkanConversionStore.pendingBitsKey), 9) let finish = try XCTUnwrap(finishFirstReport) finish(error) - let stored = try await mark(0) - let next = try await mark(1) - XCTAssertEqual(stored?.fineValue, Double(expectedStoredValue)) - XCTAssertEqual(next?.fineValue, expectedNextValue) - XCTAssertEqual(reporter.recorded.map(\.0), [expectedStoredValue, Int(expectedNextValue)]) + let retry = try await mark(0) + XCTAssertEqual(acceptedBeforeRetry, expectedAcceptedValue) + XCTAssertEqual(retry?.fineValue, 9) + XCTAssertEqual(reporter.recorded.map(\.0), [9]) + XCTAssertEqual(defaults.integer(forKey: SkanConversionStore.pendingBitsKey), 0) } func testConcurrentCallersNeverReportASmallerValue() async throws { diff --git a/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts b/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts index 00dd14c78..d3f674da1 100644 --- a/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts +++ b/native-modules/react-native-device-utils/src/ReactNativeDeviceUtils.nitro.ts @@ -203,14 +203,15 @@ export interface ReactNativeDeviceUtils getAppleAdsAttributionToken(): Promise; /** - * ORs `bits` (0-63) into the stored SKAdNetwork fine conversion value and - * submits it to SKAdNetwork on every call on iOS 16.1+, even if the values - * are unchanged. Call during each conversion window that needs an update. - * The fine value accumulates bits from successful submissions. The coarse + * ORs `bits` (0-63) with pending bits and the last accepted fine conversion + * value. Submits even unchanged values on iOS 16.1+. Call during each + * conversion window that needs an update. The coarse * value is `high` when the merged value shares a bit with * `coarseRule.highMask`, else `medium` for `coarseRule.mediumMask`, else * `low`. Rejects on invalid input, a StoreKit error, a timeout, or while a - * timed-out submission is still pending. Android and older iOS resolve to undefined. + * timed-out submission is still pending. Valid bits are kept for the next + * submission until StoreKit accepts them. Android and older iOS resolve to + * undefined. */ markSkanMilestones( bits: number,