Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion example/react-native/ios/Podfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3927,7 +3927,7 @@ SPEC CHECKSUMS:
ReactNativeCaptureProtection: ac103d5f2311fc6cb7412b49ebdc821b845bf97a
ReactNativeCheckBiometricAuthChanged: 9028250455b331bd52a29bf8223ffd29c158e60f
ReactNativeDependencies: d3b7423ba1e52525e42085c8470109abde583d2e
ReactNativeDeviceUtils: d3d18adc9c517eee5d427fa7b68ed3a32da57622
ReactNativeDeviceUtils: 0664aa178122a925cd134c94b782ccfcc7d82b87
ReactNativeGetRandomValues: a8dd2d44b9f13e6a7c5165bf6fbbbf16d422a388
ReactNativeImageCropPicker: bb1e798732909427df3f83f2d0159f815bacc773
ReactNativeJpush: 7e7958e03c904e0bcc1f45b38688f4ec3bfb823f
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1353,6 +1353,14 @@ class ReactNativeDeviceUtils : HybridReactNativeDeviceUtilsSpec(), LifecycleEven
return Promise.resolved(null)
}

// SKAdNetwork is iOS-only.
override fun markSkanMilestones(
bits: Double,
coarseRule: SkanCoarseRule
): Promise<SkanUpdateResult?> {
return Promise.resolved(null)
}

// MARK: - Android Channel & Installer

override fun getAndroidChannel(): AndroidChannel {
Expand Down
77 changes: 77 additions & 0 deletions native-modules/react-native-device-utils/docs/SPEC.md
Original file line number Diff line number Diff line change
Expand Up @@ -610,3 +610,80 @@ 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<SkanUpdateResult | undefined>`
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`.

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.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: [Confirm SKAdNetwork registration on first launch]

docs/SPEC.md:635 tells the app to call this API in each window it wants to update. Apple also requires a conversion update on first launch to register attribution. I can't confirm which OneKey startup path makes that call for a fresh install with no milestones. Apple's advertised-app setup

If the first submission currently waits for a milestone, please add a first-launch call with bits: 0 and document that startup responsibility here. Please reply in this thread with the startup call site or an integration test that shows the first-launch update.

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 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 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. 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 next submission includes the pending bits, even when the caller
passes `bits: 0`. Invalid calls leave storage unchanged.

## 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, the
same fine and coarse values submitted in consecutive simulated windows, zero
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.
Original file line number Diff line number Diff line change
Expand Up @@ -424,4 +424,42 @@ class ReactNativeDeviceUtils: HybridReactNativeDeviceUtilsSpec {
return token
}
}

func markSkanMilestones(bits: Double, coarseRule: SkanCoarseRule) throws -> Promise<SkanUpdateResult?> {
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<SkanUpdateResult?> {
let promise = Promise<SkanUpdateResult?>()
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: true
))
case .failure(let error):
promise.reject(withError: error)
}
}
return promise
}
}
185 changes: 185 additions & 0 deletions native-modules/react-native-device-utils/ios/SkanConversionStore.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
import Foundation
import StoreKit

enum SkanCoarse {
case low
case medium
case high
}

struct SkanMergeOutcome {
let fineValue: Int
let coarse: SkanCoarse
}

enum SkanConversionError: Error, Equatable, LocalizedError {
case invalidValue(String)
case unsupported
case timedOut
case reportInProgress
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 .reportInProgress:
return "SKAdNetwork has not completed the previous 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. The queue keeps
/// read, merge, report and persist in order so each submission includes
/// accepted and pending milestone bits.
final class SkanConversionStore {
typealias Reporter = (
_ fineValue: Int,
_ coarse: SkanCoarse,
_ completion: @escaping (Error?) -> Void
) -> 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(
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)
private var timedOutReport: DispatchSemaphore?

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<SkanMergeOutcome, Error>) -> 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 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 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.
// 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) { [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.recordAccepted(fineValue)
}
self.timedOutReport = nil
}
}
guard semaphore.wait(timeout: .now() + reportTimeout) == .success else {
Comment thread
huhuanming marked this conversation as resolved.
Resolved

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: [Persist new milestones while a StoreKit report is in flight]

If one runtime submits bit 8 and another marks bit 1 while StoreKit is slow, the second call's pending write sits behind this semaphore wait for up to 30 seconds. If the app process exits during the wait, bit 1 exists only in the queued closure. A zero-bit retry after relaunch can recover 8 and omit the second milestone.

Please represent the in-flight report as state on the serial queue so the queue can validate and persist incoming bits during the wait and submit the next report only after reconciling the current callback.

// 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 {
if let skanError = reportError as? SkanConversionError {
throw skanError
}
throw SkanConversionError.reportFailed(reportError.localizedDescription)
}

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)
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
)
}
}
Loading
Loading