@kerdly/expo 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +235 -2
  3. package/android/build.gradle +61 -0
  4. package/android/src/main/AndroidManifest.xml +19 -0
  5. package/android/src/main/java/com/kerdly/expo/KerdlySdkModule.kt +326 -0
  6. package/android/vendor/kerdly-sdk/.kerdly-sync.json +8 -0
  7. package/android/vendor/kerdly-sdk/consumer-rules.pro +15 -0
  8. package/android/vendor/kerdly-sdk/kerdly-sdk.properties +2 -0
  9. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/Kerdly.kt +343 -0
  10. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/KerdlyTypes.kt +89 -0
  11. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Attribution.kt +39 -0
  12. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Batch.kt +159 -0
  13. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Core.kt +991 -0
  14. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/DeepLinks.kt +114 -0
  15. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/DeferredLinks.kt +111 -0
  16. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/DeviceContext.kt +137 -0
  17. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/EventQueue.kt +135 -0
  18. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Events.kt +314 -0
  19. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Json.kt +116 -0
  20. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Logger.kt +49 -0
  21. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Options.kt +47 -0
  22. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Ports.kt +83 -0
  23. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/PublicIp.kt +120 -0
  24. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Referrers.kt +137 -0
  25. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/RemoteConfig.kt +100 -0
  26. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Storage.kt +271 -0
  27. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/android/AndroidPlatform.kt +274 -0
  28. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/android/AndroidRuntime.kt +187 -0
  29. package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/android/PlayReferrerReader.kt +97 -0
  30. package/app.plugin.js +2 -0
  31. package/build/Kerdly.d.ts +106 -0
  32. package/build/Kerdly.d.ts.map +1 -0
  33. package/build/Kerdly.js +494 -0
  34. package/build/Kerdly.js.map +1 -0
  35. package/build/index.d.ts +4 -0
  36. package/build/index.d.ts.map +1 -0
  37. package/build/index.js +2 -0
  38. package/build/index.js.map +1 -0
  39. package/build/log.d.ts +13 -0
  40. package/build/log.d.ts.map +1 -0
  41. package/build/log.js +45 -0
  42. package/build/log.js.map +1 -0
  43. package/build/native.d.ts +74 -0
  44. package/build/native.d.ts.map +1 -0
  45. package/build/native.js +56 -0
  46. package/build/native.js.map +1 -0
  47. package/build/normalize.d.ts +8 -0
  48. package/build/normalize.d.ts.map +1 -0
  49. package/build/normalize.js +86 -0
  50. package/build/normalize.js.map +1 -0
  51. package/build/types.d.ts +134 -0
  52. package/build/types.d.ts.map +1 -0
  53. package/build/types.js +3 -0
  54. package/build/types.js.map +1 -0
  55. package/build/validation.d.ts +70 -0
  56. package/build/validation.d.ts.map +1 -0
  57. package/build/validation.js +349 -0
  58. package/build/validation.js.map +1 -0
  59. package/build/version.d.ts +4 -0
  60. package/build/version.d.ts.map +1 -0
  61. package/build/version.js +5 -0
  62. package/build/version.js.map +1 -0
  63. package/expo-module.config.json +9 -0
  64. package/ios/KerdlySDK/.kerdly-sync.json +7 -0
  65. package/ios/KerdlySDK/Core/Dependencies.swift +163 -0
  66. package/ios/KerdlySDK/Core/KerdlyCore+API.swift +117 -0
  67. package/ios/KerdlySDK/Core/KerdlyCore+Collectors.swift +410 -0
  68. package/ios/KerdlySDK/Core/KerdlyCore+DeferredLinks.swift +220 -0
  69. package/ios/KerdlySDK/Core/KerdlyCore+Delivery.swift +424 -0
  70. package/ios/KerdlySDK/Core/KerdlyCore.swift +557 -0
  71. package/ios/KerdlySDK/Core/Support.swift +95 -0
  72. package/ios/KerdlySDK/Logic/Backoff.swift +22 -0
  73. package/ios/KerdlySDK/Logic/Batch.swift +180 -0
  74. package/ios/KerdlySDK/Logic/Context.swift +85 -0
  75. package/ios/KerdlySDK/Logic/DeepLinks.swift +93 -0
  76. package/ios/KerdlySDK/Logic/DeferredLinks.swift +239 -0
  77. package/ios/KerdlySDK/Logic/Environment.swift +39 -0
  78. package/ios/KerdlySDK/Logic/EventQueue.swift +85 -0
  79. package/ios/KerdlySDK/Logic/EventValidator.swift +84 -0
  80. package/ios/KerdlySDK/Logic/Events.swift +102 -0
  81. package/ios/KerdlySDK/Logic/IPv6Address.swift +26 -0
  82. package/ios/KerdlySDK/Logic/InstallIdentity.swift +106 -0
  83. package/ios/KerdlySDK/Logic/JSONValue.swift +198 -0
  84. package/ios/KerdlySDK/Logic/Purchases.swift +84 -0
  85. package/ios/KerdlySDK/Logic/RemoteConfig.swift +185 -0
  86. package/ios/KerdlySDK/Logic/Skan.swift +343 -0
  87. package/ios/KerdlySDK/Logic/StandardEvents.swift +126 -0
  88. package/ios/KerdlySDK/Platform/AdSignals.swift +19 -0
  89. package/ios/KerdlySDK/Platform/DeferredLinkBundle.swift +25 -0
  90. package/ios/KerdlySDK/Platform/DeviceInfo.swift +82 -0
  91. package/ios/KerdlySDK/Platform/Lifecycle.swift +74 -0
  92. package/ios/KerdlySDK/Platform/PublicIp.swift +33 -0
  93. package/ios/KerdlySDK/Platform/SkanWriter.swift +70 -0
  94. package/ios/KerdlySDK/Platform/StoreKitAdapter.swift +185 -0
  95. package/ios/KerdlySDK/Platform/SystemStores.swift +200 -0
  96. package/ios/KerdlySDK/Platform/Tracking.swift +124 -0
  97. package/ios/KerdlySDK/Public/Kerdly.swift +202 -0
  98. package/ios/KerdlySDK/Public/KerdlyTypes.swift +130 -0
  99. package/ios/KerdlySDK/Resources/PrivacyInfo.xcprivacy +95 -0
  100. package/ios/KerdlySDK/Storage/PersistedState.swift +175 -0
  101. package/ios/KerdlySDK/Storage/StateStore.swift +36 -0
  102. package/ios/KerdlySdk.podspec +45 -0
  103. package/ios/KerdlySdkModule.swift +332 -0
  104. package/package.json +92 -4
  105. package/plugin/withKerdly.js +163 -0
  106. package/src/Kerdly.ts +524 -0
  107. package/src/index.ts +23 -0
  108. package/src/log.ts +49 -0
  109. package/src/native.ts +150 -0
  110. package/src/normalize.ts +82 -0
  111. package/src/types.ts +183 -0
  112. package/src/validation.ts +343 -0
  113. package/src/version.ts +5 -0
@@ -0,0 +1,220 @@
1
+ import Foundation
2
+
3
+ // Deferred deep links: the SDK asks Meta and TikTok, from the device, for the deep
4
+ // link of the ad that led to this install, and reports each answer as `$signal deferred_link`.
5
+ // Everything here runs on `queue`.
6
+ extension KerdlyCore {
7
+ static let maxDdlFailures = 3
8
+
9
+ /// One network to ask, with what its request needs.
10
+ struct DdlTarget: Sendable {
11
+ let network: String
12
+ let request: HTTPRequest
13
+ }
14
+
15
+ /// Asks each configured network once per install: on the launch collectors, when the ATT status
16
+ /// changes, and on a foreground (a retry after a failure in transit). Only while the config's
17
+ /// `ddl` block is on, the install is fresh or a reinstall, it is younger than `max_age_h` and the
18
+ /// `ads` consent is on; and with tracking authorized (the request gives the network the IDFA) or,
19
+ /// under `require_att: false`, denied or restricted (no IDFA; Meta through `ep2`). Never while
20
+ /// the ATT prompt is still to come, so a user who then allows tracking is asked with the IDFA.
21
+ func askDeferredLinks() {
22
+ guard launchCollectorsStarted, !ddlInFlight, let ddl = config.ddl, ddl.enabled, state.ddlEligible else { return }
23
+ guard let first = state.firstLaunchAt, now.timeIntervalSince(Clocks.date(ms: first)) <= ddl.maxAge else { return }
24
+ let att = deps.tracking.status()
25
+ guard state.consentAds, Self.ddlMayAsk(att: att, requireAtt: ddl.requireAtt) else { return }
26
+ let bundle = deps.device.deferredLinkBundle()
27
+ let metaDue = ddl.meta != nil && state.ddl[MetaDdl.network]?.done != true
28
+ let tiktokDue = ddl.tiktok != nil && state.ddl[TikTokDdl.network]?.done != true
29
+ guard metaDue || tiktokDue else { return }
30
+ if metaDue, let meta = ddl.meta, (meta.appId ?? bundle.metaAppId) == nil || (meta.clientToken ?? bundle.metaClientToken) == nil {
31
+ finishDeferredLink(.skipped(MetaDdl.network, .notConfigured, "no Facebook app id or client token"), attempt: 1)
32
+ if !tiktokDue { return }
33
+ }
34
+ ddlInFlight = true
35
+ guard att == .authorized else { return sendDeferredLinks(idfa: nil, att: att, ddl: ddl, bundle: bundle) }
36
+ let provider = deps.advertisingId
37
+ deps.workQueue.async { [self] in
38
+ let idfa = provider.advertisingId()
39
+ queue.async { self.sendDeferredLinks(idfa: idfa, att: att, ddl: ddl, bundle: bundle) }
40
+ }
41
+ }
42
+
43
+ /// Tracking authorized, or, when the config does not require it, denied or restricted.
44
+ static func ddlMayAsk(att: KerdlyAttStatus, requireAtt: Bool) -> Bool {
45
+ att == .authorized || (!requireAtt && (att == .denied || att == .restricted))
46
+ }
47
+
48
+ /// `idfa`: read when tracking is authorized, nil otherwise.
49
+ private func sendDeferredLinks(idfa: String?, att: KerdlyAttStatus, ddl: DdlConfig, bundle: DeferredLinkBundle) {
50
+ // Tracking is authorized but iOS gave no IDFA: try again on a later foreground.
51
+ if att == .authorized, idfa?.isEmpty != false {
52
+ ddlInFlight = false
53
+ return
54
+ }
55
+ let current = snapshot ?? DeviceSnapshot(idfv: nil, screenWidth: 0, screenHeight: 0, screenScale: 0, isForeground: true)
56
+ let targets = ddlTargets(idfa: idfa ?? "", att: att, snapshot: current, bundle: bundle,
57
+ meta: state.ddl[MetaDdl.network]?.done == true ? nil : ddl.meta,
58
+ tiktok: state.ddl[TikTokDdl.network]?.done == true ? nil : ddl.tiktok)
59
+ guard !targets.isEmpty else {
60
+ ddlInFlight = false
61
+ return
62
+ }
63
+ send(targets) { [self] answers in
64
+ ddlInFlight = false
65
+ answers.forEach { recordDeferredLink($0) }
66
+ }
67
+ }
68
+
69
+ /// A transit failure counts towards giving up; any answer, a refusal included, is final.
70
+ private func recordDeferredLink(_ answer: DdlAnswer) {
71
+ var progress = state.ddl[answer.network] ?? DdlNetworkState()
72
+ guard answer.isTransient else { return finishDeferredLink(answer, attempt: progress.failures + 1) }
73
+ progress.failures += 1
74
+ state.ddl[answer.network] = progress
75
+ if progress.failures >= Self.maxDdlFailures {
76
+ finishDeferredLink(answer, attempt: progress.failures)
77
+ } else {
78
+ saveState()
79
+ log.info("deferred link: \(answer.network) did not answer (\(answer.detail ?? "")); retried on a later foreground")
80
+ }
81
+ }
82
+
83
+ /// `attempt`: which try this answer came from (1-based).
84
+ private func finishDeferredLink(_ answer: DdlAnswer, attempt: Int) {
85
+ var progress = state.ddl[answer.network] ?? DdlNetworkState()
86
+ progress.done = true
87
+ state.ddl[answer.network] = progress
88
+ saveState()
89
+ enqueue(ReservedEvent.signal, deferredLinkProps(answer, attempt: attempt))
90
+ log.info("deferred link: \(answer.network) \(answer.status.rawValue)")
91
+ }
92
+
93
+ func deferredLinkProps(_ answer: DdlAnswer, attempt: Int) -> [String: JSONValue] {
94
+ let parsed = answer.url.flatMap(URL.init(string:)).flatMap(DeepLinkParser.parse)
95
+ return [
96
+ "kind": .string("deferred_link"),
97
+ "network": .string(answer.network),
98
+ "status": .string(answer.status.rawValue),
99
+ "url": .string(answer.url.map { String($0.prefix(DeepLinkParser.maxUrlLength)) }),
100
+ "click_ts": .int(answer.clickTimeMs),
101
+ "cpp": .string(parsed?.cpp),
102
+ "ppid": .string(parsed?.ppid),
103
+ "kerdly_c": .string(parsed?.clickId),
104
+ "kerdly_v": .string(parsed?.visitId),
105
+ "campaign_ids": .string(parsed?.campaignIds),
106
+ "http_status": .int(answer.httpStatus.map(Int64.init)),
107
+ "detail": .string(answer.detail.map { String($0.prefix(300)) }),
108
+ "attempt": .int(Int64(attempt)),
109
+ "att": .string(deps.tracking.status().rawValue),
110
+ ]
111
+ }
112
+
113
+ /// The requests for the networks given, built from the device and the bundle, each shaped for the
114
+ /// ATT status: the IDFA goes only with tracking authorized, and Meta without it goes to `ep2`.
115
+ func ddlTargets(idfa: String, att: KerdlyAttStatus, snapshot: DeviceSnapshot, bundle: DeferredLinkBundle,
116
+ meta: DdlConfig.Meta?, tiktok: DdlConfig.TikTok?) -> [DdlTarget] {
117
+ let tracking = att == .authorized && !idfa.isEmpty
118
+ let facts = ddlFacts(idfa: tracking ? idfa : "", snapshot: snapshot, bundle: bundle)
119
+ var targets: [DdlTarget] = []
120
+ if let meta, let appId = meta.appId ?? bundle.metaAppId, let token = meta.clientToken ?? bundle.metaClientToken {
121
+ let installId = state.installId.isEmpty ? deps.newId() : state.installId
122
+ let anonId = state.partnerIds["meta_anon_id"] ?? "XZ\(installId.uppercased())"
123
+ if let request = MetaDdl.request(appId: appId, clientToken: token, anonId: anonId, facts: facts,
124
+ trackingAuthorized: tracking) {
125
+ targets.append(DdlTarget(network: MetaDdl.network, request: request))
126
+ }
127
+ }
128
+ if let tiktok, let request = TikTokDdl.request(tiktokAppId: tiktok.appId, storeAppId: tiktok.storeAppId,
129
+ facts: facts, att: att, now: now) {
130
+ targets.append(DdlTarget(network: TikTokDdl.network, request: request))
131
+ }
132
+ return targets
133
+ }
134
+
135
+ /// Sends every target at once; `completion` runs on `queue` with the answers in target order.
136
+ func send(_ targets: [DdlTarget], completion: @escaping @Sendable ([DdlAnswer]) -> Void) {
137
+ let answers = Locked<[String: DdlAnswer]>([:])
138
+ let group = DispatchGroup()
139
+ for target in targets {
140
+ group.enter()
141
+ log.debug("deferred link: asking \(target.network) at \(target.request.url.host ?? "")")
142
+ let network = target.network
143
+ deps.transport.send(target.request) { result in
144
+ let answer = network == MetaDdl.network ? MetaDdl.parse(result) : TikTokDdl.parse(result)
145
+ answers.update { $0[network] = answer }
146
+ group.leave()
147
+ }
148
+ }
149
+ group.notify(queue: queue) {
150
+ let all = answers.get()
151
+ completion(targets.compactMap { all[$0.network] })
152
+ }
153
+ }
154
+
155
+ // MARK: - Debug
156
+
157
+ /// Debug: asks Meta and TikTok for this device's deferred deep link and hands back their raw
158
+ /// answers. Enqueues nothing and ignores the config's `ddl` block. Answers only in a debug build
159
+ /// (`DEBUG`): a release build gets an `error` answer per network and asks nothing. Asks only with
160
+ /// the `ads` consent on and tracking authorized, as the SDK itself does.
161
+ ///
162
+ /// Not behind `run`: it works before, or without, `configure`, so a build with no Kerdly key can
163
+ /// still test the networks.
164
+ func apiDebugFetchDeferredLinks(tiktokAppId: String?, storeAppId: String?,
165
+ completion: @escaping @Sendable ([DdlAnswer]) -> Void) {
166
+ let device = deps.device
167
+ DispatchQueue.main.async { [self] in
168
+ let fresh = MainActor.assumeIsolated { device.snapshot() }
169
+ queue.async { [self] in
170
+ let networks = [MetaDdl.network, TikTokDdl.network]
171
+ guard device.environmentInputs().isDebugBuild else {
172
+ completion(networks.map { DdlAnswer.skipped($0, .error, "debug builds only") })
173
+ return
174
+ }
175
+ let att = deps.tracking.status()
176
+ guard att == .authorized else {
177
+ completion(networks.map { DdlAnswer.skipped($0, .skippedAtt) })
178
+ return
179
+ }
180
+ guard state.consentAds else {
181
+ completion(networks.map { DdlAnswer.skipped($0, .skippedConsent) })
182
+ return
183
+ }
184
+ let ask = { @Sendable (idfa: String) in
185
+ let bundle = self.deps.device.deferredLinkBundle()
186
+ let targets = self.ddlTargets(idfa: idfa, att: att, snapshot: fresh, bundle: bundle,
187
+ meta: DdlConfig.Meta(appId: nil, clientToken: nil),
188
+ tiktok: tiktokAppId.map { DdlConfig.TikTok(appId: $0, storeAppId: storeAppId) })
189
+ let asked = Set(targets.map(\.network))
190
+ self.send(targets) { answers in
191
+ completion(answers + networks.filter { !asked.contains($0) }.map { DdlAnswer.skipped($0, .notConfigured) })
192
+ }
193
+ }
194
+ let provider = deps.advertisingId
195
+ deps.workQueue.async { [self] in
196
+ let idfa = provider.advertisingId()
197
+ queue.async {
198
+ if let idfa, !idfa.isEmpty { return ask(idfa) }
199
+ completion(networks.map { DdlAnswer.skipped($0, .skippedAtt, "no IDFA") })
200
+ }
201
+ }
202
+ }
203
+ }
204
+ }
205
+
206
+ private func ddlFacts(idfa: String, snapshot: DeviceSnapshot, bundle: DeferredLinkBundle) -> DdlDeviceFacts {
207
+ let facts = deps.device.facts()
208
+ let app = deps.device.appInfo()
209
+ let scale = snapshot.screenScale
210
+ let points = { (pixels: Int) -> Int in scale > 0 ? Int((Double(pixels) / scale).rounded()) : 0 }
211
+ return DdlDeviceFacts(
212
+ bundleId: app.bundle, appName: bundle.appName, appVersion: app.version, appBuild: app.build,
213
+ os: facts.os, model: facts.model, localeIdentifier: facts.locale,
214
+ preferredLanguage: facts.languages.first ?? "", regionCode: bundle.regionCode,
215
+ timeZoneName: facts.timeZone, timeZoneAbbrev: TimeZone.current.abbreviation() ?? "",
216
+ screenWidth: points(snapshot.screenWidth), screenHeight: points(snapshot.screenHeight),
217
+ screenScale: scale, coreCount: ProcessInfo.processInfo.activeProcessorCount,
218
+ idfa: idfa.uppercased(), idfv: snapshot.idfv, urlSchemes: bundle.urlSchemes)
219
+ }
220
+ }
@@ -0,0 +1,424 @@
1
+ import Foundation
2
+
3
+ // Batches, retries, the remote config and the attribution poll. Everything here runs on `queue`.
4
+ extension KerdlyCore {
5
+ static let attributionPollOffsets: [TimeInterval] = [10, 30, 55]
6
+ /// Waits between config fetches while no config for this app version is in.
7
+ static let configRetryDelays: [TimeInterval] = [5, 15, 30, 60, 120, 300]
8
+
9
+ func endpointURL(_ path: String) -> URL? {
10
+ options?.endpoint.appendingPathComponent(path)
11
+ }
12
+
13
+ /// The headers every request carries. The app's version picks the config Kerdly
14
+ /// serves (its version rules).
15
+ func baseHeaders() -> [String: String] {
16
+ var sdk = "\(Self.sdkName)/\(Self.sdkVersion)"
17
+ if let wrapper = options?.wrapper?.trimmingCharacters(in: .whitespaces), !wrapper.isEmpty {
18
+ sdk += " \(wrapper)"
19
+ }
20
+ var headers = [
21
+ "Authorization": "Bearer \(options?.key.trimmingCharacters(in: .whitespacesAndNewlines) ?? "")",
22
+ "X-Kerdly-Bundle": appInfo.bundle,
23
+ "X-Kerdly-Sdk": sdk,
24
+ "Content-Type": "application/json",
25
+ "Accept": "application/json",
26
+ ]
27
+ if !appInfo.version.isEmpty { headers["X-Kerdly-App-Version"] = appInfo.version }
28
+ if !appInfo.build.isEmpty { headers["X-Kerdly-App-Build"] = appInfo.build }
29
+ return headers
30
+ }
31
+
32
+ func makeEnvelope() -> BatchEnvelope {
33
+ let wrapper = options?.wrapper?.trimmingCharacters(in: .whitespaces)
34
+ return BatchEnvelope(
35
+ sdkName: Self.sdkName, sdkVersion: Self.sdkVersion,
36
+ wrapper: (wrapper?.isEmpty ?? true) ? nil : wrapper,
37
+ bundle: appInfo.bundle, appVersion: appInfo.version, appBuild: appInfo.build,
38
+ environment: environment, installId: state.installId)
39
+ }
40
+
41
+ func currentContext() -> JSONValue {
42
+ ContextBuilder.context(facts: facts ?? deps.device.facts(), snapshot: snapshot,
43
+ att: deps.tracking.status(), analytics: state.consentAnalytics,
44
+ ads: state.consentAds, app: appInfo)
45
+ }
46
+
47
+ /// `$install`'s `device`: the same inputs as `currentContext`, without consent.
48
+ func currentDevice() -> JSONValue {
49
+ ContextBuilder.device(facts: facts ?? deps.device.facts(), snapshot: snapshot,
50
+ att: deps.tracking.status(), app: appInfo)
51
+ }
52
+
53
+ // MARK: - Flush
54
+
55
+ /// Coalesces flush triggers that arrive together into one attempt.
56
+ func scheduleFlush() {
57
+ guard !flushScheduled else { return }
58
+ flushScheduled = true
59
+ queue.async { [self] in
60
+ flushScheduled = false
61
+ flushNow(explicit: false)
62
+ }
63
+ }
64
+
65
+ /// Sends the next batch, if one is due. One request in flight at a time.
66
+ /// - Parameter explicit: `flush()` from the app: skips the client back-off (not a server
67
+ /// `Retry-After`).
68
+ func flushNow(explicit: Bool) {
69
+ guard started, launchFlushReleased, options != nil else { return }
70
+ guard !stoppedUntilRelaunch, configReady, sendingEnabled, !config.off else { return endBackgroundTaskIfIdle() }
71
+ guard !eventQueue.isEmpty else { return endBackgroundTaskIfIdle() }
72
+ if inFlight {
73
+ flushAfterInFlight = true
74
+ return
75
+ }
76
+ let at = now
77
+ if let retryAt = state.retryAt {
78
+ let wait = Clocks.date(ms: retryAt).timeIntervalSince(at)
79
+ if wait > 3_600 {
80
+ // A clock that jumped back would otherwise park the queue: forget the deadline.
81
+ state.retryAt = nil
82
+ } else if wait > 0 && (!explicit || state.retryAtFromServer) {
83
+ armRetryTimer()
84
+ return endBackgroundTaskIfIdle()
85
+ }
86
+ }
87
+ guard let url = endpointURL("v1/sdk/batch") else { return }
88
+ let envelope = makeEnvelope()
89
+ let context = currentContext()
90
+ let contextHash = Hashing.sha256(KerdlyJSON.encode(context) ?? Data())
91
+ let sendContext: JSONValue? = contextHash == state.lastAckedContextHash ? nil : context
92
+ let limit = min(config.maxBatch, batchLimitOverride ?? BatchBuilder.maxEvents)
93
+ let batch = eventQueue.nextBatch(
94
+ maxEvents: limit, maxBytes: BatchBuilder.maxBodyBytes,
95
+ overheadBytes: BatchBuilder.overheadBytes(envelope: envelope, context: sendContext))
96
+ guard !batch.isEmpty,
97
+ let body = BatchBuilder.body(envelope: envelope, sentAt: Clocks.ms(at), context: sendContext, events: batch)
98
+ else { return }
99
+ inFlight = true
100
+ let ids = batch.map(\.id)
101
+ let ackContextHash = sendContext == nil ? nil : contextHash
102
+ log.debug("sending \(ids.count) event(s), \(body.count) bytes\(sendContext == nil ? "" : " with context")")
103
+ deps.transport.send(HTTPRequest(method: "POST", url: url, headers: baseHeaders(), body: body)) { [self] result in
104
+ queue.async { self.handleBatchResult(result, ids: ids, contextHash: ackContextHash) }
105
+ }
106
+ }
107
+
108
+ func handleBatchResult(_ result: HTTPResult, ids: [String], contextHash: String?) {
109
+ inFlight = false
110
+ let at = now
111
+ let outcome: DeliveryOutcome
112
+ switch result {
113
+ case .failure(let reason):
114
+ log.debug("batch not delivered: \(reason)")
115
+ outcome = .retry(retryAfter: nil)
116
+ case .response(let status, let headers, let body):
117
+ outcome = DeliveryPolicy.classify(status: status, headers: headers, body: body, now: at)
118
+ }
119
+ apply(outcome, ids: ids, contextHash: contextHash, at: at)
120
+ if flushAfterInFlight {
121
+ flushAfterInFlight = false
122
+ if state.retryAt == nil && !stoppedUntilRelaunch { scheduleFlush() }
123
+ }
124
+ endBackgroundTaskIfIdle()
125
+ }
126
+
127
+ func apply(_ outcome: DeliveryOutcome, ids: [String], contextHash: String?, at: Date) {
128
+ let sent = Set(ids)
129
+ switch outcome {
130
+ case .success(let response):
131
+ let settled = response.settledIds
132
+ eventQueue.remove(ids: settled)
133
+ state.pendingDeepLinks.removeAll { settled.contains($0.id) }
134
+ for rejected in response.rejected where sent.contains(rejected.id) {
135
+ log.warn("event \(rejected.id) rejected: \(rejected.reason)")
136
+ }
137
+ if let contextHash { state.lastAckedContextHash = contextHash }
138
+ if settled.isDisjoint(with: sent) {
139
+ // Nothing of this batch was settled: back off rather than resend it at once.
140
+ scheduleRetry(retryAfter: nil, at: at)
141
+ } else {
142
+ clearBackoff()
143
+ if let limit = batchLimitOverride {
144
+ batchLimitOverride = limit * 2 >= BatchBuilder.maxEvents ? nil : limit * 2
145
+ }
146
+ }
147
+ saveQueue()
148
+ saveState()
149
+ process(response)
150
+ if !eventQueue.isEmpty && state.retryAt == nil { scheduleFlush() }
151
+ case .drop(let code, let stop):
152
+ eventQueue.remove(ids: sent)
153
+ saveQueue()
154
+ if loggedDropCodes.insert(code).inserted {
155
+ log.error("batch of \(ids.count) event(s) dropped: \(code)")
156
+ }
157
+ clearBackoff()
158
+ saveState()
159
+ if stop {
160
+ stoppedUntilRelaunch = true
161
+ log.error("sending stopped until the next launch (\(code))")
162
+ } else if !eventQueue.isEmpty {
163
+ scheduleFlush()
164
+ }
165
+ case .retry(let retryAfter):
166
+ scheduleRetry(retryAfter: retryAfter, at: at)
167
+ case .split:
168
+ // The server answered: the halved batch goes at once.
169
+ clearBackoff()
170
+ saveState()
171
+ if ids.count <= 1 {
172
+ eventQueue.remove(ids: sent)
173
+ saveQueue()
174
+ log.error("an event was dropped: too large even alone (413)")
175
+ } else {
176
+ batchLimitOverride = max(1, ids.count / 2)
177
+ log.debug("413: retrying with batches of \(ids.count / 2)")
178
+ }
179
+ scheduleFlush()
180
+ }
181
+ }
182
+
183
+ /// What a 200 carries besides the acks.
184
+ func process(_ response: BatchResponse) {
185
+ if let attribution = response.attribution {
186
+ updateAttribution(attribution)
187
+ }
188
+ if let etag = response.configEtag, etag != configCache?.etag {
189
+ fetchConfig()
190
+ }
191
+ if response.needs.contains("asa_token") {
192
+ state.asaDue = state.asaAttempts < 3
193
+ saveState()
194
+ requestAsaToken()
195
+ }
196
+ if !response.cvHints.isEmpty {
197
+ log.debug("cv_hints received; server hints are not used by this SDK version")
198
+ }
199
+ }
200
+
201
+ func scheduleRetry(retryAfter: TimeInterval?, at: Date) {
202
+ let delay: TimeInterval
203
+ if let retryAfter {
204
+ delay = retryAfter
205
+ state.retryAtFromServer = true
206
+ } else {
207
+ delay = BackoffPolicy().delay(attempt: state.backoffAttempt, unitRandom: deps.unitRandom())
208
+ state.retryAtFromServer = false
209
+ }
210
+ state.backoffAttempt += 1
211
+ state.retryAt = Clocks.ms(at.addingTimeInterval(delay))
212
+ saveState()
213
+ log.debug("next attempt in \(Int(delay.rounded())) s")
214
+ armRetryTimer()
215
+ }
216
+
217
+ func clearBackoff() {
218
+ state.backoffAttempt = 0
219
+ state.retryAt = nil
220
+ state.retryAtFromServer = false
221
+ retryTimer?.cancel()
222
+ retryTimer = nil
223
+ }
224
+
225
+ func armRetryTimer() {
226
+ retryTimer?.cancel()
227
+ guard let retryAt = state.retryAt else { return }
228
+ let delay = max(0, Clocks.date(ms: retryAt).timeIntervalSince(now))
229
+ retryTimer = scheduler.schedule(after: delay) { [self] in
230
+ retryTimer = nil
231
+ state.retryAt = nil
232
+ flushNow(explicit: false)
233
+ }
234
+ }
235
+
236
+ // MARK: - Foreground timer
237
+
238
+ func startForegroundTimer() {
239
+ guard foregroundTimer == nil else { return }
240
+ foregroundTimer = scheduler.schedule(after: config.flushInterval) { [self] in
241
+ foregroundTimer = nil
242
+ guard started, isForeground else { return }
243
+ if !eventQueue.isEmpty { flushNow(explicit: false) }
244
+ startForegroundTimer()
245
+ }
246
+ }
247
+
248
+ func stopForegroundTimer() {
249
+ foregroundTimer?.cancel()
250
+ foregroundTimer = nil
251
+ }
252
+
253
+ func endBackgroundTaskIfIdle() {
254
+ guard let token = backgroundTaskToken, !inFlight, !flushScheduled else { return }
255
+ backgroundTaskToken = nil
256
+ deps.lifecycle.endBackgroundTask(token)
257
+ }
258
+
259
+ // MARK: - Remote config
260
+
261
+ /// `GET /v1/sdk/config` with `If-None-Match`. Concurrent calls share one request; `completion`
262
+ /// runs when it settles (whatever the outcome).
263
+ func fetchConfig(then completion: (() -> Void)? = nil) {
264
+ if let completion { configFetchWaiters.append(completion) }
265
+ guard !configFetchInFlight else { return }
266
+ guard !stoppedUntilRelaunch, let url = endpointURL("v1/sdk/config") else {
267
+ return finishConfigFetch()
268
+ }
269
+ configFetchInFlight = true
270
+ var headers = baseHeaders()
271
+ if let etag = configCache?.etag { headers["If-None-Match"] = etag }
272
+ deps.transport.send(HTTPRequest(method: "GET", url: url, headers: headers, body: nil)) { [self] result in
273
+ queue.async { self.handleConfigResult(result) }
274
+ }
275
+ }
276
+
277
+ func handleConfigResult(_ result: HTTPResult) {
278
+ configFetchInFlight = false
279
+ let atMs = Clocks.ms(now)
280
+ switch result {
281
+ case .response(let status, let headers, let body) where (200..<300).contains(status):
282
+ if let json = JSONValue.parse(body), json.objectValue != nil {
283
+ let etag = headers["etag"]
284
+ let cache = configCache?.replacing(body: json, etag: etag, fetchedAt: atMs, appVersion: appInfo.version)
285
+ ?? ConfigCache.first(body: json, etag: etag, fetchedAt: atMs, appVersion: appInfo.version)
286
+ if json["skan"].map({ !$0.isNull && SkanSchema.parse($0) == nil }) == true {
287
+ log.warn("the config's SKAN ladder is invalid; keeping the last valid one")
288
+ }
289
+ configCache = cache
290
+ store.save(config: cache)
291
+ apply(cache.config)
292
+ log.debug("config \(cache.config.version.map(String.init) ?? "?") loaded")
293
+ } else {
294
+ log.warn("the config response is not a JSON object")
295
+ }
296
+ case .response(304, _, _):
297
+ // Unchanged for the version the request named: the cached body is this version's too.
298
+ if var cache = configCache {
299
+ cache.fetchedAt = atMs
300
+ cache.appVersion = appInfo.version
301
+ configCache = cache
302
+ store.save(config: cache)
303
+ }
304
+ case .response(let status, _, let body) where status == 401 || status == 403:
305
+ stoppedUntilRelaunch = true
306
+ log.error("config refused (\(DeliveryPolicy.errorCode(body) ?? "http_\(status)")); sending stopped until the next launch")
307
+ case .response(let status, _, _):
308
+ log.debug("config fetch failed: HTTP \(status)")
309
+ case .failure(let reason):
310
+ log.debug("config fetch failed: \(reason)")
311
+ }
312
+ finishConfigFetch()
313
+ }
314
+
315
+ func finishConfigFetch() {
316
+ let waiters = configFetchWaiters
317
+ configFetchWaiters = []
318
+ waiters.forEach { $0() }
319
+ afterConfigFetch()
320
+ }
321
+
322
+ /// After every config fetch, whatever its outcome. This version's config releases the launch
323
+ /// (or, when Kerdly is off for it, empties the queue); without it, the SDK asks again, backing
324
+ /// off, and on every foreground. There is no timeout: going ahead without the
325
+ /// config is what would let a switched-off version send.
326
+ func afterConfigFetch() {
327
+ guard appInfoLoaded, launchPipelineStarted, !stoppedUntilRelaunch else { return }
328
+ guard configReady else { return scheduleConfigRetry() }
329
+ configRetryTimer?.cancel()
330
+ configRetryTimer = nil
331
+ configRetryAttempt = 0
332
+ if config.off { return switchOff() }
333
+ launchConfigReady()
334
+ flushNow(explicit: false)
335
+ }
336
+
337
+ func scheduleConfigRetry() {
338
+ guard configRetryTimer == nil, !configFetchInFlight else { return }
339
+ let delay = Self.configRetryDelays[min(configRetryAttempt, Self.configRetryDelays.count - 1)]
340
+ configRetryAttempt += 1
341
+ configRetryTimer = scheduler.schedule(after: delay) { [self] in
342
+ configRetryTimer = nil
343
+ if !configReady { fetchConfig() }
344
+ }
345
+ }
346
+
347
+ /// A foreground asks at once when this version's config is still missing.
348
+ func retryConfigNowIfMissing() {
349
+ guard appInfoLoaded, !configReady, !stoppedUntilRelaunch else { return }
350
+ configRetryTimer?.cancel()
351
+ configRetryTimer = nil
352
+ fetchConfig()
353
+ }
354
+
355
+ /// Kerdly is off for this app version: what the device holds is dropped and nothing
356
+ /// more is recorded (`enqueue`), collected (the collectors wait for `launchConfigReady`) or
357
+ /// sent (`flushNow`). The config fetch goes on, so a later config can switch it back on.
358
+ func switchOff() {
359
+ let dropped = eventQueue.remove(ids: Set(eventQueue.events.map(\.id)))
360
+ state.pendingDeepLinks = []
361
+ pendingSkanTriggers = []
362
+ saveQueue()
363
+ saveState()
364
+ endBackgroundTaskIfIdle()
365
+ log.info("Kerdly is off for this app version: \(dropped) queued events dropped, nothing is recorded or sent")
366
+ }
367
+
368
+ func apply(_ newConfig: RemoteConfig) {
369
+ let wasEnabled = sendingEnabled
370
+ let oldInterval = config.flushInterval
371
+ config = newConfig
372
+ applyLogLevel()
373
+ if wasEnabled && !sendingEnabled {
374
+ log.warn("sending is disabled by the remote config")
375
+ }
376
+ if !wasEnabled && sendingEnabled {
377
+ scheduleFlush()
378
+ }
379
+ if oldInterval != config.flushInterval && foregroundTimer != nil {
380
+ stopForegroundTimer()
381
+ startForegroundTimer()
382
+ }
383
+ }
384
+
385
+ // MARK: - Attribution poll
386
+
387
+ /// At most 3 polls in the first minute after an install; later, batch responses carry it.
388
+ func scheduleAttributionPolls() {
389
+ guard launchEnqueuedInstall else { return }
390
+ for offset in Self.attributionPollOffsets {
391
+ let delay = max(0, configuredAt.addingTimeInterval(offset).timeIntervalSince(now))
392
+ scheduler.schedule(after: delay) { [self] in pollAttribution() }
393
+ }
394
+ }
395
+
396
+ func pollAttribution() {
397
+ guard state.attribution == nil, attributionPolls < Self.attributionPollOffsets.count,
398
+ !stoppedUntilRelaunch, configReady, sendingEnabled,
399
+ let base = endpointURL("v1/sdk/attribution"),
400
+ var components = URLComponents(url: base, resolvingAgainstBaseURL: false)
401
+ else { return }
402
+ components.queryItems = [URLQueryItem(name: "install_id", value: state.installId)]
403
+ guard let url = components.url else { return }
404
+ attributionPolls += 1
405
+ deps.transport.send(HTTPRequest(method: "GET", url: url, headers: baseHeaders(), body: nil)) { [self] result in
406
+ queue.async { self.handleAttributionPoll(result) }
407
+ }
408
+ }
409
+
410
+ /// Accepts the attribution object itself or `{"attribution": {…} | null, …}`.
411
+ func handleAttributionPoll(_ result: HTTPResult) {
412
+ guard case .response(let status, _, let body) = result else { return }
413
+ if status == 401 || status == 403 {
414
+ stoppedUntilRelaunch = true
415
+ return
416
+ }
417
+ guard (200..<300).contains(status), let object = JSONValue.parse(body)?.objectValue else { return }
418
+ if let wrapped = object["attribution"] {
419
+ if let attribution = wrapped.objectValue { updateAttribution(attribution) }
420
+ } else if object["network"] != nil || object["state"] != nil {
421
+ updateAttribution(object)
422
+ }
423
+ }
424
+ }