@kerdly/expo 0.0.0-stage → 0.1.1
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.
- package/LICENSE +21 -0
- package/README.md +235 -2
- package/android/build.gradle +61 -0
- package/android/src/main/AndroidManifest.xml +19 -0
- package/android/src/main/java/com/kerdly/expo/KerdlySdkModule.kt +326 -0
- package/android/vendor/kerdly-sdk/.kerdly-sync.json +8 -0
- package/android/vendor/kerdly-sdk/consumer-rules.pro +15 -0
- package/android/vendor/kerdly-sdk/kerdly-sdk.properties +2 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/Kerdly.kt +343 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/KerdlyTypes.kt +89 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Attribution.kt +39 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Batch.kt +159 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Core.kt +991 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/DeepLinks.kt +114 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/DeferredLinks.kt +110 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/DeviceContext.kt +137 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/EventQueue.kt +135 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Events.kt +314 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Json.kt +116 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Logger.kt +49 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Options.kt +47 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Ports.kt +83 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/PublicIp.kt +120 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Referrers.kt +137 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/RemoteConfig.kt +100 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/Storage.kt +271 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/android/AndroidPlatform.kt +274 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/android/AndroidRuntime.kt +187 -0
- package/android/vendor/kerdly-sdk/kotlin/com/kerdly/sdk/internal/android/PlayReferrerReader.kt +97 -0
- package/app.plugin.js +2 -0
- package/build/Kerdly.d.ts +106 -0
- package/build/Kerdly.d.ts.map +1 -0
- package/build/Kerdly.js +494 -0
- package/build/Kerdly.js.map +1 -0
- package/build/index.d.ts +4 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +2 -0
- package/build/index.js.map +1 -0
- package/build/log.d.ts +13 -0
- package/build/log.d.ts.map +1 -0
- package/build/log.js +45 -0
- package/build/log.js.map +1 -0
- package/build/native.d.ts +74 -0
- package/build/native.d.ts.map +1 -0
- package/build/native.js +56 -0
- package/build/native.js.map +1 -0
- package/build/normalize.d.ts +8 -0
- package/build/normalize.d.ts.map +1 -0
- package/build/normalize.js +86 -0
- package/build/normalize.js.map +1 -0
- package/build/types.d.ts +134 -0
- package/build/types.d.ts.map +1 -0
- package/build/types.js +3 -0
- package/build/types.js.map +1 -0
- package/build/validation.d.ts +70 -0
- package/build/validation.d.ts.map +1 -0
- package/build/validation.js +349 -0
- package/build/validation.js.map +1 -0
- package/build/version.d.ts +4 -0
- package/build/version.d.ts.map +1 -0
- package/build/version.js +5 -0
- package/build/version.js.map +1 -0
- package/expo-module.config.json +9 -0
- package/ios/KerdlySDK/.kerdly-sync.json +7 -0
- package/ios/KerdlySDK/Core/Dependencies.swift +163 -0
- package/ios/KerdlySDK/Core/KerdlyCore+API.swift +117 -0
- package/ios/KerdlySDK/Core/KerdlyCore+Collectors.swift +410 -0
- package/ios/KerdlySDK/Core/KerdlyCore+DeferredLinks.swift +220 -0
- package/ios/KerdlySDK/Core/KerdlyCore+Delivery.swift +424 -0
- package/ios/KerdlySDK/Core/KerdlyCore.swift +557 -0
- package/ios/KerdlySDK/Core/Support.swift +95 -0
- package/ios/KerdlySDK/Logic/Backoff.swift +22 -0
- package/ios/KerdlySDK/Logic/Batch.swift +180 -0
- package/ios/KerdlySDK/Logic/Context.swift +85 -0
- package/ios/KerdlySDK/Logic/DeepLinks.swift +93 -0
- package/ios/KerdlySDK/Logic/DeferredLinks.swift +236 -0
- package/ios/KerdlySDK/Logic/Environment.swift +39 -0
- package/ios/KerdlySDK/Logic/EventQueue.swift +85 -0
- package/ios/KerdlySDK/Logic/EventValidator.swift +84 -0
- package/ios/KerdlySDK/Logic/Events.swift +102 -0
- package/ios/KerdlySDK/Logic/IPv6Address.swift +26 -0
- package/ios/KerdlySDK/Logic/InstallIdentity.swift +106 -0
- package/ios/KerdlySDK/Logic/JSONValue.swift +198 -0
- package/ios/KerdlySDK/Logic/Purchases.swift +84 -0
- package/ios/KerdlySDK/Logic/RemoteConfig.swift +185 -0
- package/ios/KerdlySDK/Logic/Skan.swift +343 -0
- package/ios/KerdlySDK/Logic/StandardEvents.swift +126 -0
- package/ios/KerdlySDK/Platform/AdSignals.swift +19 -0
- package/ios/KerdlySDK/Platform/DeferredLinkBundle.swift +25 -0
- package/ios/KerdlySDK/Platform/DeviceInfo.swift +82 -0
- package/ios/KerdlySDK/Platform/Lifecycle.swift +74 -0
- package/ios/KerdlySDK/Platform/PublicIp.swift +33 -0
- package/ios/KerdlySDK/Platform/SkanWriter.swift +70 -0
- package/ios/KerdlySDK/Platform/StoreKitAdapter.swift +185 -0
- package/ios/KerdlySDK/Platform/SystemStores.swift +200 -0
- package/ios/KerdlySDK/Platform/Tracking.swift +124 -0
- package/ios/KerdlySDK/Public/Kerdly.swift +202 -0
- package/ios/KerdlySDK/Public/KerdlyTypes.swift +130 -0
- package/ios/KerdlySDK/Resources/PrivacyInfo.xcprivacy +96 -0
- package/ios/KerdlySDK/Storage/PersistedState.swift +175 -0
- package/ios/KerdlySDK/Storage/StateStore.swift +36 -0
- package/ios/KerdlySdk.podspec +45 -0
- package/ios/KerdlySdkModule.swift +332 -0
- package/package.json +96 -4
- package/plugin/withKerdly.js +163 -0
- package/src/Kerdly.ts +524 -0
- package/src/index.ts +23 -0
- package/src/log.ts +49 -0
- package/src/native.ts +150 -0
- package/src/normalize.ts +82 -0
- package/src/types.ts +182 -0
- package/src/validation.ts +343 -0
- package/src/version.ts +5 -0
|
@@ -0,0 +1,991 @@
|
|
|
1
|
+
package com.kerdly.sdk.internal
|
|
2
|
+
|
|
3
|
+
import com.kerdly.sdk.KerdlyAttribution
|
|
4
|
+
import com.kerdly.sdk.KerdlyDeepLink
|
|
5
|
+
import com.kerdly.sdk.KerdlyNetworkSend
|
|
6
|
+
import com.kerdly.sdk.KerdlyPurchase
|
|
7
|
+
import org.json.JSONObject
|
|
8
|
+
import java.net.URLEncoder
|
|
9
|
+
import kotlin.random.Random
|
|
10
|
+
|
|
11
|
+
internal class CoreConfig(
|
|
12
|
+
val key: String,
|
|
13
|
+
/** Base URL without a trailing slash. */
|
|
14
|
+
val endpoint: String,
|
|
15
|
+
/** `production` | `sandbox` | `development`, already resolved from AUTO. */
|
|
16
|
+
val environment: String,
|
|
17
|
+
val collectAdvertisingId: Boolean,
|
|
18
|
+
val metaAppId: String?,
|
|
19
|
+
val wrapper: String?,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
internal class Launch(
|
|
23
|
+
val installId: String,
|
|
24
|
+
/** No install-id file existed: this launch enqueues `$install`. */
|
|
25
|
+
val fresh: Boolean,
|
|
26
|
+
val ts: Long,
|
|
27
|
+
/** Whether the process was in the foreground when `configure` ran. */
|
|
28
|
+
val foreground: Boolean,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
/** The SDK engine: protocol v1 client rules over the ports in Ports.kt.
|
|
32
|
+
*
|
|
33
|
+
* Threading: every method runs on [scheduler]'s single thread, in submission order. Only
|
|
34
|
+
* [attribution] is read from other threads. Blocking calls (HTTP, the advertising id, the Meta
|
|
35
|
+
* providers) run on that thread too; events submitted meanwhile wait in the executor. */
|
|
36
|
+
internal class Core(
|
|
37
|
+
private val cfg: CoreConfig,
|
|
38
|
+
private val platform: Platform,
|
|
39
|
+
private val transport: Transport,
|
|
40
|
+
private val store: Store,
|
|
41
|
+
private val scheduler: Scheduler,
|
|
42
|
+
private val clock: Clock,
|
|
43
|
+
private val log: Logger,
|
|
44
|
+
private val main: MainDispatcher,
|
|
45
|
+
private val random: Random = Random.Default,
|
|
46
|
+
private val newEventId: () -> String = InstallId::newId,
|
|
47
|
+
) {
|
|
48
|
+
companion object {
|
|
49
|
+
const val FOREGROUND_OPEN_AFTER_MS = 30 * 60_000L
|
|
50
|
+
const val CONFIG_MAX_AGE_MS = 6 * 3_600_000L
|
|
51
|
+
/** A changed `config_etag` refetches at most this often (guards against a server loop). */
|
|
52
|
+
const val CONFIG_MIN_INTERVAL_MS = 60_000L
|
|
53
|
+
/** Waits between config fetches while no config for this app version is in. */
|
|
54
|
+
val CONFIG_RETRY_MS = longArrayOf(5_000, 15_000, 30_000, 60_000, 120_000, 300_000)
|
|
55
|
+
const val REFERRER_TIMEOUT_MS = 10_000L
|
|
56
|
+
const val MAX_DDL_FAILURES = 3
|
|
57
|
+
const val REFERRER_WINDOW_MS = 90L * 86_400_000L
|
|
58
|
+
const val AD_ID_REFRESH_MS = 86_400_000L
|
|
59
|
+
const val PUBLIC_IP_TIMEOUT_MS = 3_000L
|
|
60
|
+
/** `GET /v1/sdk/attribution`: at most 3 polls in the first minute of a fresh install, only
|
|
61
|
+
* while nothing is known; afterwards batch responses carry it. */
|
|
62
|
+
val ATTRIBUTION_POLLS_MS = longArrayOf(5_000, 20_000, 50_000)
|
|
63
|
+
/** One event can never fill a 256 KB batch; anything this big is a bug upstream. */
|
|
64
|
+
const val MAX_EVENT_BYTES = 128 * 1024
|
|
65
|
+
/** The collector's `user_id` limit. */
|
|
66
|
+
const val MAX_USER_ID = 128
|
|
67
|
+
/** The collector's `$ids` limits. */
|
|
68
|
+
const val MAX_TOKEN = 64
|
|
69
|
+
const val MAX_PARTNER_KEY = 64
|
|
70
|
+
const val MAX_PARTNER_VALUE = 256
|
|
71
|
+
const val MAX_PARTNER_IDS = 50
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
private var installId = ""
|
|
75
|
+
private var state = SdkState()
|
|
76
|
+
private var queue = EventQueue()
|
|
77
|
+
private var configCache = ConfigCache.EMPTY
|
|
78
|
+
private var config = RemoteConfig.DEFAULT
|
|
79
|
+
private var pending = PendingLinks()
|
|
80
|
+
private var purchases = ReportedPurchases()
|
|
81
|
+
private var app = AppInfo("", null, null)
|
|
82
|
+
private val listeners = ArrayList<(KerdlyAttribution) -> Unit>()
|
|
83
|
+
|
|
84
|
+
/** Cached attribution; null until the collector decides one. */
|
|
85
|
+
@Volatile
|
|
86
|
+
var attribution: KerdlyAttribution? = null
|
|
87
|
+
private set
|
|
88
|
+
|
|
89
|
+
private var started = false
|
|
90
|
+
/** 401/403: nothing more is sent until the next launch. */
|
|
91
|
+
private var stopped = false
|
|
92
|
+
private var sdkTooOld = false
|
|
93
|
+
private var foreground = false
|
|
94
|
+
private var backgroundedAt: Long? = null
|
|
95
|
+
private var queueDirty = false
|
|
96
|
+
private var persistScheduled = false
|
|
97
|
+
private var flushScheduled = false
|
|
98
|
+
private var timer: Cancellable? = null
|
|
99
|
+
private var retryTask: Cancellable? = null
|
|
100
|
+
/** After a 413: the batch size that last fit. */
|
|
101
|
+
private var batchLimit: Int? = null
|
|
102
|
+
private var referrerInFlight = false
|
|
103
|
+
private var lastConfigAttemptAt: Long? = null
|
|
104
|
+
private var etagHint: String? = null
|
|
105
|
+
/** While no config for this app version is in: the next fetch, backing off. */
|
|
106
|
+
private var configRetryTask: Cancellable? = null
|
|
107
|
+
private var configRetryAttempt = 0
|
|
108
|
+
/** This launch enqueued `$install`: the public IPv6 and the attribution polls are due. */
|
|
109
|
+
private var launchFresh = false
|
|
110
|
+
/** The launch's collectors ran (they wait for this version's config). */
|
|
111
|
+
private var launchWorkDone = false
|
|
112
|
+
/** TikTok's deferred link failed in transit: asked again at the next foreground, not before. */
|
|
113
|
+
private var ddlWaitsForForeground = false
|
|
114
|
+
private var loggedDrop = false
|
|
115
|
+
|
|
116
|
+
// --- Launch ------------------------------------------------------------
|
|
117
|
+
|
|
118
|
+
/** The launch task: the first thing on the executor after `configure`. Calls the app made
|
|
119
|
+
* before `configure` ([buffered]) run after `$install` / `$open`, before anything is sent. */
|
|
120
|
+
fun start(launch: Launch, buffered: List<(Core) -> Unit> = emptyList()) {
|
|
121
|
+
installId = launch.installId
|
|
122
|
+
foreground = launch.foreground
|
|
123
|
+
if (!launch.foreground) backgroundedAt = launch.ts
|
|
124
|
+
load(launch.fresh)
|
|
125
|
+
app = safely("reading the app version", AppInfo("", null, null)) { platform.appInfo() }
|
|
126
|
+
if (launch.fresh) {
|
|
127
|
+
val info = safely("reading the install info", InstallInfo(null, null)) { platform.installInfo() }
|
|
128
|
+
// The device snapshot is always sent: the context's fields at enqueue.
|
|
129
|
+
val device = safely("reading the device context", null) { platform.deviceContext() } ?: DeviceContext.UNKNOWN
|
|
130
|
+
state.firstLaunchAt = launch.ts
|
|
131
|
+
state.installedAt = info.installedAt
|
|
132
|
+
state.ddlEligible = true
|
|
133
|
+
val install = enqueue(
|
|
134
|
+
EventNames.INSTALL,
|
|
135
|
+
ReservedProps.install(info.installedAt, launch.ts, info.installer, null, ContextJson.device(device, app.version, app.build)),
|
|
136
|
+
launch.ts,
|
|
137
|
+
)
|
|
138
|
+
state.installEventId = install?.id
|
|
139
|
+
} else if (state.firstLaunchAt == null) {
|
|
140
|
+
state.firstLaunchAt = launch.ts
|
|
141
|
+
}
|
|
142
|
+
enqueue(EventNames.OPEN, ReservedProps.open("launch"), launch.ts)
|
|
143
|
+
restorePendingLinks()
|
|
144
|
+
started = true
|
|
145
|
+
for (op in buffered) {
|
|
146
|
+
try {
|
|
147
|
+
op(this)
|
|
148
|
+
} catch (t: Throwable) {
|
|
149
|
+
log.error("a call made before configure failed", t)
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
saveState()
|
|
153
|
+
// Nothing but the config fetch goes out, and no collector runs, until the config for this
|
|
154
|
+
// app version is in: Kerdly may have switched this version off. With it cached,
|
|
155
|
+
// the launch flush goes out at once, so the `$install` request IP is the first-launch IP;
|
|
156
|
+
// otherwise it follows the fetch.
|
|
157
|
+
launchFresh = launch.fresh
|
|
158
|
+
requestFlush()
|
|
159
|
+
if (configReady) {
|
|
160
|
+
if (config.off) switchOff() else startLaunchWork()
|
|
161
|
+
}
|
|
162
|
+
scheduler.execute { maybeFetchConfig(force = false) }
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** The config in use was fetched for this app version. */
|
|
166
|
+
private val configReady: Boolean
|
|
167
|
+
get() = configCache.config != null && configCache.appVersion == app.version
|
|
168
|
+
|
|
169
|
+
/** Kerdly is off for this app version: nothing is recorded, collected or sent. */
|
|
170
|
+
private val kerdlyOff: Boolean
|
|
171
|
+
get() = configReady && config.off
|
|
172
|
+
|
|
173
|
+
/** Collectors run only with this version's config in, and Kerdly on for it. */
|
|
174
|
+
private fun collecting(): Boolean = configReady && !config.off
|
|
175
|
+
|
|
176
|
+
/** The launch's collectors, once per launch: the public IPv6 lookup and the attribution
|
|
177
|
+
* polls on the launch with `$install`, then the referrers, GAID and deferred links. */
|
|
178
|
+
private fun startLaunchWork() {
|
|
179
|
+
if (launchWorkDone || !collecting()) return
|
|
180
|
+
launchWorkDone = true
|
|
181
|
+
if (launchFresh) {
|
|
182
|
+
scheduler.execute { collectPublicIp() }
|
|
183
|
+
scheduleAttributionPolls()
|
|
184
|
+
}
|
|
185
|
+
startCollectors()
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** After every config fetch, whatever its outcome. This version's config releases the launch
|
|
189
|
+
* (or, when Kerdly is off for it, empties the queue); without it, the SDK asks again, backing off,
|
|
190
|
+
* and on every foreground. There is no timeout: going ahead without the config is what would
|
|
191
|
+
* let a switched-off version send. */
|
|
192
|
+
private fun afterConfigFetch() {
|
|
193
|
+
if (stopped || !started) return
|
|
194
|
+
if (!configReady) return scheduleConfigRetry()
|
|
195
|
+
configRetryTask?.cancel()
|
|
196
|
+
configRetryTask = null
|
|
197
|
+
configRetryAttempt = 0
|
|
198
|
+
if (config.off) return switchOff()
|
|
199
|
+
// The launch flush first, so the `$install` batch leaves before the collectors' signals.
|
|
200
|
+
requestFlush()
|
|
201
|
+
startLaunchWork()
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
private fun scheduleConfigRetry() {
|
|
205
|
+
if (configRetryTask != null) return
|
|
206
|
+
val delay = CONFIG_RETRY_MS[minOf(configRetryAttempt, CONFIG_RETRY_MS.size - 1)]
|
|
207
|
+
configRetryAttempt++
|
|
208
|
+
configRetryTask = scheduler.schedule(delay) {
|
|
209
|
+
configRetryTask = null
|
|
210
|
+
if (!configReady) maybeFetchConfig(force = false)
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** A foreground asks at once when this version's config is still missing. */
|
|
215
|
+
private fun retryConfigNowIfMissing() {
|
|
216
|
+
if (!started || stopped || configReady) return
|
|
217
|
+
configRetryTask?.cancel()
|
|
218
|
+
configRetryTask = null
|
|
219
|
+
scheduler.execute { maybeFetchConfig(force = false) }
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Kerdly is off for this app version: what the device holds is dropped, and nothing
|
|
223
|
+
* more is recorded ([enqueue]), collected ([collecting]) or sent ([canSend]). The config fetch
|
|
224
|
+
* goes on, so a later config can switch it back on. */
|
|
225
|
+
private fun switchOff() {
|
|
226
|
+
val dropped = queue.remove(queue.events().map { it.id })
|
|
227
|
+
if (!pending.isEmpty()) {
|
|
228
|
+
pending.remove(pending.entries().mapNotNull { it.id })
|
|
229
|
+
savePending()
|
|
230
|
+
}
|
|
231
|
+
markQueueDirty()
|
|
232
|
+
log.info("Kerdly is off for this app version: $dropped queued event(s) dropped, nothing is recorded or sent")
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
private fun load(fresh: Boolean) {
|
|
236
|
+
configCache = ConfigCache.parse(readFile(StoreFiles.CONFIG))
|
|
237
|
+
config = configCache.config ?: RemoteConfig.DEFAULT
|
|
238
|
+
applyConfig()
|
|
239
|
+
if (fresh) {
|
|
240
|
+
// The new id reaches the disk before any event that carries it can be sent.
|
|
241
|
+
if (!InstallId.persist(store, installId)) log.error("could not store the install id; it lasts only for this launch")
|
|
242
|
+
// A new install id starts clean: anything left on disk belonged to an id that is gone.
|
|
243
|
+
for (f in listOf(StoreFiles.QUEUE, StoreFiles.STATE, StoreFiles.PENDING_LINKS, StoreFiles.PURCHASES, StoreFiles.ATTRIBUTION)) {
|
|
244
|
+
store.delete(f)
|
|
245
|
+
}
|
|
246
|
+
return
|
|
247
|
+
}
|
|
248
|
+
state = SdkState.parse(readFile(StoreFiles.STATE), installId) ?: SdkState()
|
|
249
|
+
queue = EventQueue.parse(readFile(StoreFiles.QUEUE), installId) ?: EventQueue()
|
|
250
|
+
pending = PendingLinks.parse(readFile(StoreFiles.PENDING_LINKS))
|
|
251
|
+
purchases = ReportedPurchases.parse(readFile(StoreFiles.PURCHASES))
|
|
252
|
+
attribution = AttributionParser.fromJson(parseObject(readFile(StoreFiles.ATTRIBUTION)))
|
|
253
|
+
// `seq` is never reused, whichever file survived.
|
|
254
|
+
queue.nextSeq = maxOf(queue.nextSeq, state.nextSeq, pending.maxSeq() + 1)
|
|
255
|
+
// A persisted retry time beyond the longest back-off means the clock moved: retry now.
|
|
256
|
+
if (state.retryNextAt - clock.now() > BatchResponses.MAX_RETRY_AFTER_S * 1000) {
|
|
257
|
+
state.retryNextAt = 0
|
|
258
|
+
state.retryAttempt = 0
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
private fun readFile(name: String): String? = try {
|
|
263
|
+
store.read(name)
|
|
264
|
+
} catch (e: Exception) {
|
|
265
|
+
log.warn("could not read $name", e)
|
|
266
|
+
null
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// --- Public operations (each already on the executor) ----------------------------------
|
|
270
|
+
|
|
271
|
+
fun track(name: String, properties: Map<String, Any?>, ts: Long) {
|
|
272
|
+
if (EventNames.isReserved(name)) {
|
|
273
|
+
log.warn("track(\"${name.take(64)}\"): \$ names are reserved for the SDK; event dropped")
|
|
274
|
+
return
|
|
275
|
+
}
|
|
276
|
+
if (!CustomEvents.isValidName(name)) {
|
|
277
|
+
log.warn("track(\"${name.take(64)}\"): names must match [a-z][a-z0-9_]{0,39}; event dropped")
|
|
278
|
+
return
|
|
279
|
+
}
|
|
280
|
+
if (!state.analytics) {
|
|
281
|
+
log.debug { "analytics consent is off: $name dropped" }
|
|
282
|
+
return
|
|
283
|
+
}
|
|
284
|
+
// Before this version's config is in, events are kept: that config decides.
|
|
285
|
+
if (configReady && (!config.enabled || sdkTooOld)) {
|
|
286
|
+
log.debug { "sending is paused: $name dropped" }
|
|
287
|
+
return
|
|
288
|
+
}
|
|
289
|
+
if (name in config.blocked) {
|
|
290
|
+
log.debug { "$name is blocked by the remote config" }
|
|
291
|
+
return
|
|
292
|
+
}
|
|
293
|
+
// A standard name gets its typed checks here too, whoever called.
|
|
294
|
+
val props = StandardEvents.sanitize(name, properties)
|
|
295
|
+
if (props.dropped.isNotEmpty()) log.debug { "$name: dropped props ${props.dropped.joinToString()}" }
|
|
296
|
+
enqueue(name, props.json, ts)
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** A typed standard-event method: its non-null [args] win over the same keys in [properties]. */
|
|
300
|
+
fun trackStandard(name: String, args: Map<String, Any?>, properties: Map<String, Any?>, ts: Long) {
|
|
301
|
+
val (props, ignored) = StandardEvents.merge(args, properties)
|
|
302
|
+
if (ignored.isNotEmpty()) log.debug { "$name: dropped props ${ignored.joinToString { "$it (set by the typed argument)" }}" }
|
|
303
|
+
track(name, props, ts)
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
fun setUserId(userId: String?, ts: Long) {
|
|
307
|
+
val id = userId?.takeIf { it.isNotEmpty() }
|
|
308
|
+
if (id != null && id.length > MAX_USER_ID) {
|
|
309
|
+
log.error("setUserId: ids over $MAX_USER_ID characters are not supported; ignored")
|
|
310
|
+
return
|
|
311
|
+
}
|
|
312
|
+
if (id == state.userId) return
|
|
313
|
+
val previous = state.userId
|
|
314
|
+
state.userId = id // before the enqueue: `$identify` carries the new id as its user_id
|
|
315
|
+
enqueue(EventNames.IDENTIFY, ReservedProps.identify(id, previous), ts)
|
|
316
|
+
saveState()
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
fun setConsent(analytics: Boolean?, ads: Boolean?, ts: Long) {
|
|
320
|
+
val nextAnalytics = analytics ?: state.analytics
|
|
321
|
+
val nextAds = ads ?: state.ads
|
|
322
|
+
if (nextAnalytics == state.analytics && nextAds == state.ads) return
|
|
323
|
+
val adsGranted = nextAds && !state.ads
|
|
324
|
+
state.analytics = nextAnalytics
|
|
325
|
+
state.ads = nextAds
|
|
326
|
+
enqueue(EventNames.CONSENT, ReservedProps.consent(nextAnalytics, nextAds), ts)
|
|
327
|
+
saveState()
|
|
328
|
+
if (adsGranted && started) scheduler.execute { collectAdvertisingId(force = true) }
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
fun handleUrl(link: KerdlyDeepLink, source: String, ts: Long) {
|
|
332
|
+
val event = enqueue(EventNames.DEEPLINK, ReservedProps.deeplink(link, source), ts) ?: return
|
|
333
|
+
if (DeepLinks.isAttributionBearing(link)) {
|
|
334
|
+
pending.add(event.json, clock.now())
|
|
335
|
+
savePending()
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
fun setAppAccountToken(token: String?, ts: Long) {
|
|
340
|
+
// Any string: a UUID, or Superwall's `$SuperwallAlias:<uuid>` obfuscated account id.
|
|
341
|
+
val t = token?.trim()?.takeIf { it.isNotEmpty() }
|
|
342
|
+
if (t != null && t.length > MAX_TOKEN) {
|
|
343
|
+
log.error("setAppAccountToken: tokens over $MAX_TOKEN characters are not supported; ignored")
|
|
344
|
+
return
|
|
345
|
+
}
|
|
346
|
+
if (t == state.appAccountToken) return
|
|
347
|
+
state.appAccountToken = t
|
|
348
|
+
enqueue(EventNames.IDS, ReservedProps.ids(t, state.partner), ts)
|
|
349
|
+
saveState()
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** Merges into the stored map; an empty value removes its key. `$ids` carries the whole map. */
|
|
353
|
+
fun setPartnerIds(ids: Map<String, String>, ts: Long) {
|
|
354
|
+
val merged = LinkedHashMap(state.partner)
|
|
355
|
+
for ((k, v) in ids) {
|
|
356
|
+
if (k.isEmpty() || k.length > MAX_PARTNER_KEY) {
|
|
357
|
+
log.warn("setPartnerIds: key \"${k.take(64)}\" must be 1–$MAX_PARTNER_KEY characters; ignored")
|
|
358
|
+
continue
|
|
359
|
+
}
|
|
360
|
+
when {
|
|
361
|
+
v.isEmpty() -> merged.remove(k)
|
|
362
|
+
v.length > MAX_PARTNER_VALUE -> log.warn("setPartnerIds: $k is over $MAX_PARTNER_VALUE characters; ignored")
|
|
363
|
+
else -> merged[k] = v
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
if (merged.size > MAX_PARTNER_IDS) {
|
|
367
|
+
log.warn("setPartnerIds: at most $MAX_PARTNER_IDS ids are kept")
|
|
368
|
+
val keep = merged.entries.take(MAX_PARTNER_IDS)
|
|
369
|
+
merged.clear()
|
|
370
|
+
for ((k, v) in keep) merged[k] = v
|
|
371
|
+
}
|
|
372
|
+
if (merged == state.partner) return
|
|
373
|
+
state.partner = merged
|
|
374
|
+
enqueue(EventNames.IDS, ReservedProps.ids(state.appAccountToken, merged), ts)
|
|
375
|
+
saveState()
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
fun notifyPurchase(purchase: KerdlyPurchase, ts: Long) {
|
|
379
|
+
if (purchase.purchaseToken.isBlank()) {
|
|
380
|
+
log.warn("notifyPurchase: purchaseToken is empty; ignored")
|
|
381
|
+
return
|
|
382
|
+
}
|
|
383
|
+
if (!config.collectPurchases) {
|
|
384
|
+
log.debug { "purchases are off in the remote config" }
|
|
385
|
+
return
|
|
386
|
+
}
|
|
387
|
+
val hash = ReportedPurchases.tokenHash(purchase.purchaseToken)
|
|
388
|
+
if (purchases.contains(hash)) {
|
|
389
|
+
log.debug { "purchase already reported" }
|
|
390
|
+
return
|
|
391
|
+
}
|
|
392
|
+
enqueue(EventNames.PURCHASE_LINK, ReservedProps.purchaseLink(purchase), ts) ?: return
|
|
393
|
+
purchases.add(hash)
|
|
394
|
+
if (!store.write(StoreFiles.PURCHASES, purchases.serialize())) log.warn("could not write the reported purchases")
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
fun recordNetworkSend(send: KerdlyNetworkSend, ts: Long) {
|
|
398
|
+
if (send.network.isBlank() || send.event.isBlank()) {
|
|
399
|
+
log.warn("recordNetworkSend: network and event are required; ignored")
|
|
400
|
+
return
|
|
401
|
+
}
|
|
402
|
+
enqueue(EventNames.NETWORK_SEND, ReservedProps.networkSend(send), ts)
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
fun flush() = requestFlush()
|
|
406
|
+
|
|
407
|
+
fun addAttributionListener(listener: (KerdlyAttribution) -> Unit) {
|
|
408
|
+
listeners.add(listener)
|
|
409
|
+
attribution?.let { deliver(listener, it) }
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
// --- Lifecycle ---------------------------------------------------------------------------
|
|
413
|
+
|
|
414
|
+
fun onForeground(ts: Long) {
|
|
415
|
+
if (foreground) return
|
|
416
|
+
foreground = true
|
|
417
|
+
val since = backgroundedAt
|
|
418
|
+
backgroundedAt = null
|
|
419
|
+
if (since != null && ts - since >= FOREGROUND_OPEN_AFTER_MS) {
|
|
420
|
+
enqueue(EventNames.OPEN, ReservedProps.open("foreground"), ts)
|
|
421
|
+
}
|
|
422
|
+
retryConfigNowIfMissing()
|
|
423
|
+
ddlWaitsForForeground = false
|
|
424
|
+
startPlayReferrer()
|
|
425
|
+
scheduler.execute { collectAdvertisingId(force = false) }
|
|
426
|
+
scheduler.execute { askDeferredLinks() }
|
|
427
|
+
requestFlush()
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
fun onBackground(ts: Long) {
|
|
431
|
+
if (!foreground) return
|
|
432
|
+
foreground = false
|
|
433
|
+
backgroundedAt = ts
|
|
434
|
+
timer?.cancel()
|
|
435
|
+
timer = null
|
|
436
|
+
requestFlush()
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
// --- Queue -------------------------------------------------------------------------------
|
|
440
|
+
|
|
441
|
+
/** Stamps id, seq and user_id; null when consent or a limit kept the event out. */
|
|
442
|
+
private fun enqueue(name: String, props: JSONObject, ts: Long): QueuedEvent? {
|
|
443
|
+
if (kerdlyOff) {
|
|
444
|
+
log.debug { "Kerdly is off for this app version: $name not recorded" }
|
|
445
|
+
return null
|
|
446
|
+
}
|
|
447
|
+
if (!state.analytics && name !in EventNames.ANALYTICS_OFF_ALLOWED) {
|
|
448
|
+
log.debug { "analytics consent is off: $name not recorded" }
|
|
449
|
+
return null
|
|
450
|
+
}
|
|
451
|
+
val id = newEventId()
|
|
452
|
+
val seq = queue.nextSeq
|
|
453
|
+
val o = JSONObject().put("id", id).put("name", name).put("ts", ts).put("seq", seq)
|
|
454
|
+
state.userId?.let { o.put("user_id", it) }
|
|
455
|
+
o.put("props", props)
|
|
456
|
+
val event = QueuedEvent(id, name, seq, o.toString())
|
|
457
|
+
if (event.bytes > MAX_EVENT_BYTES) {
|
|
458
|
+
log.error("$name dropped: ${event.bytes} bytes is over the $MAX_EVENT_BYTES-byte event limit")
|
|
459
|
+
return null
|
|
460
|
+
}
|
|
461
|
+
queue.nextSeq = seq + 1
|
|
462
|
+
val dropped = queue.add(event)
|
|
463
|
+
if (dropped.isNotEmpty()) log.warn("queue full: dropped ${dropped.size} event(s): ${dropped.joinToString { it.name }}")
|
|
464
|
+
markQueueDirty()
|
|
465
|
+
log.debug { "enqueued $name #$seq" }
|
|
466
|
+
if (event.reserved || queue.size >= config.queueFlushAt) requestFlush() else armTimer()
|
|
467
|
+
return event.takeIf { queue.contains(it.id) }
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/** Writes are coalesced: one write after the burst of calls already on the executor. */
|
|
471
|
+
private fun markQueueDirty() {
|
|
472
|
+
queueDirty = true
|
|
473
|
+
if (persistScheduled) return
|
|
474
|
+
persistScheduled = true
|
|
475
|
+
scheduler.execute {
|
|
476
|
+
persistScheduled = false
|
|
477
|
+
persistQueue()
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
private fun persistQueue() {
|
|
482
|
+
if (!queueDirty) return
|
|
483
|
+
queueDirty = false
|
|
484
|
+
if (!store.write(StoreFiles.QUEUE, queue.serialize(installId))) log.warn("could not write the event queue")
|
|
485
|
+
saveState()
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
private fun saveState() {
|
|
489
|
+
state.nextSeq = maxOf(state.nextSeq, queue.nextSeq)
|
|
490
|
+
if (!store.write(StoreFiles.STATE, state.serialize(installId))) log.warn("could not write the SDK state")
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
private fun savePending() {
|
|
494
|
+
if (!store.write(StoreFiles.PENDING_LINKS, pending.serialize())) log.warn("could not write the pending deep links")
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
private fun restorePendingLinks() {
|
|
498
|
+
val expired = pending.expire(clock.now())
|
|
499
|
+
var restored = 0
|
|
500
|
+
for (entry in pending.entries()) {
|
|
501
|
+
val event = QueuedEvent.fromJson(entry.event) ?: continue
|
|
502
|
+
if (queue.contains(event.id)) continue
|
|
503
|
+
queue.add(event) // same id and seq: the collector dedupes it
|
|
504
|
+
restored++
|
|
505
|
+
}
|
|
506
|
+
if (restored > 0) {
|
|
507
|
+
log.debug { "re-enqueued $restored pending deep link(s)" }
|
|
508
|
+
markQueueDirty()
|
|
509
|
+
requestFlush()
|
|
510
|
+
}
|
|
511
|
+
if (expired) savePending()
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
// --- Delivery ----------------------------------------------------
|
|
515
|
+
|
|
516
|
+
private fun canSend(): Boolean = started && !stopped && configReady && !config.off && config.enabled && !sdkTooOld
|
|
517
|
+
|
|
518
|
+
private fun requestFlush() {
|
|
519
|
+
if (flushScheduled) return
|
|
520
|
+
flushScheduled = true
|
|
521
|
+
scheduler.execute {
|
|
522
|
+
flushScheduled = false
|
|
523
|
+
flushNow()
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
private fun armTimer() {
|
|
528
|
+
if (!foreground || timer != null || !canSend()) return
|
|
529
|
+
timer = scheduler.schedule(config.intervalS * 1000L) {
|
|
530
|
+
timer = null
|
|
531
|
+
flushNow()
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
private fun flushNow() {
|
|
536
|
+
timer?.cancel()
|
|
537
|
+
timer = null
|
|
538
|
+
persistQueue() // a batch's events are on disk before they go out
|
|
539
|
+
if (!canSend() || queue.isEmpty()) return
|
|
540
|
+
val now = clock.now()
|
|
541
|
+
if (state.retryNextAt > now) {
|
|
542
|
+
scheduleRetry(state.retryNextAt - now)
|
|
543
|
+
return
|
|
544
|
+
}
|
|
545
|
+
sendBatch()
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
private fun sendBatch() {
|
|
549
|
+
val device = safely("reading the device context", null) { platform.deviceContext() }
|
|
550
|
+
val context = device?.let { ContextJson.build(it, state.analytics, state.ads, state.lat, app.version, app.build) }
|
|
551
|
+
val contextHash = context?.let { sha1Hex(it.toString()) }
|
|
552
|
+
// The context goes out when it changed since the collector last stored one.
|
|
553
|
+
val sentContextHash = contextHash?.takeIf { it != state.contextHash }
|
|
554
|
+
val envelope = BatchBody.envelope(envelopeInfo(), clock.now(), if (sentContextHash != null) context else null)
|
|
555
|
+
val maxCount = minOf(config.maxBatch, batchLimit ?: BatchBody.MAX_EVENTS).coerceAtLeast(1)
|
|
556
|
+
val batch = BatchBody.select(queue.events(), maxCount, BatchBody.eventBudget(envelope))
|
|
557
|
+
if (batch.isEmpty()) {
|
|
558
|
+
val head = queue.events().first()
|
|
559
|
+
queue.remove(listOf(head.id))
|
|
560
|
+
markQueueDirty()
|
|
561
|
+
log.error("${head.name} dropped: too large for a batch")
|
|
562
|
+
requestFlush()
|
|
563
|
+
return
|
|
564
|
+
}
|
|
565
|
+
val request = HttpRequest(
|
|
566
|
+
"POST",
|
|
567
|
+
url("/v1/sdk/batch"),
|
|
568
|
+
headers(json = true),
|
|
569
|
+
BatchBody.join(envelope, batch).toByteArray(Charsets.UTF_8),
|
|
570
|
+
)
|
|
571
|
+
val response = try {
|
|
572
|
+
transport.execute(request)
|
|
573
|
+
} catch (e: Exception) {
|
|
574
|
+
log.debug { "batch not sent: ${e.javaClass.simpleName}: ${e.message}" }
|
|
575
|
+
null
|
|
576
|
+
}
|
|
577
|
+
val outcome = response?.let { BatchResponses.classify(it.status, it.body, it.retryAfter) }
|
|
578
|
+
?: SendOutcome.Retry(null, null)
|
|
579
|
+
handle(outcome, batch, sentContextHash)
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
private fun handle(outcome: SendOutcome, batch: List<QueuedEvent>, sentContextHash: String?) {
|
|
583
|
+
when (outcome) {
|
|
584
|
+
is SendOutcome.Acked -> onAcked(outcome.ack, batch, sentContextHash)
|
|
585
|
+
is SendOutcome.Drop -> {
|
|
586
|
+
queue.remove(batch.map { it.id })
|
|
587
|
+
markQueueDirty()
|
|
588
|
+
resetRetry()
|
|
589
|
+
if (outcome.stop) {
|
|
590
|
+
stop(outcome.status, outcome.code)
|
|
591
|
+
log.error("${batch.size} event(s) dropped")
|
|
592
|
+
} else if (!loggedDrop) {
|
|
593
|
+
loggedDrop = true
|
|
594
|
+
log.error("HTTP ${outcome.status}${outcome.code?.let { " ($it)" } ?: ""}: the collector refused a batch; ${batch.size} event(s) dropped")
|
|
595
|
+
} else {
|
|
596
|
+
log.debug { "HTTP ${outcome.status}: ${batch.size} event(s) dropped" }
|
|
597
|
+
}
|
|
598
|
+
saveState()
|
|
599
|
+
}
|
|
600
|
+
SendOutcome.Split -> {
|
|
601
|
+
if (batch.size > 1) {
|
|
602
|
+
batchLimit = batch.size / 2
|
|
603
|
+
log.debug { "HTTP 413: retrying with batches of ${batch.size / 2}" }
|
|
604
|
+
} else {
|
|
605
|
+
queue.remove(listOf(batch[0].id))
|
|
606
|
+
markQueueDirty()
|
|
607
|
+
log.error("${batch[0].name} dropped: the collector says it is too large")
|
|
608
|
+
}
|
|
609
|
+
requestFlush()
|
|
610
|
+
}
|
|
611
|
+
is SendOutcome.Retry -> backOff(outcome.status, outcome.retryAfterMs)
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
private fun onAcked(ack: BatchAck, batch: List<QueuedEvent>, sentContextHash: String?) {
|
|
616
|
+
val names = batch.associate { it.id to it.name }
|
|
617
|
+
val answered = HashSet<String>(ack.accepted)
|
|
618
|
+
for (r in ack.rejected) r.id?.let { answered.add(it) }
|
|
619
|
+
if (queue.remove(answered) > 0) markQueueDirty()
|
|
620
|
+
for (r in ack.rejected) {
|
|
621
|
+
log.warn("the collector rejected ${r.id?.let { names[it] } ?: "an event"} (${r.reason}); it is not resent")
|
|
622
|
+
}
|
|
623
|
+
if (pending.remove(answered)) savePending()
|
|
624
|
+
val installEventId = state.installEventId
|
|
625
|
+
if (!state.installAcked && installEventId != null && installEventId in ack.accepted) state.installAcked = true
|
|
626
|
+
if (sentContextHash != null && ack.accepted.isNotEmpty()) state.contextHash = sentContextHash
|
|
627
|
+
ack.configEtag?.let(::onConfigEtag)
|
|
628
|
+
AttributionParser.fromJson(ack.attribution)?.let(::updateAttribution)
|
|
629
|
+
val leftover = batch.count { it.id !in answered }
|
|
630
|
+
if (leftover > 0) {
|
|
631
|
+
// Ids in neither list stay queued; back off instead of resending at once.
|
|
632
|
+
log.debug { "$leftover event(s) neither accepted nor rejected; retrying later" }
|
|
633
|
+
backOff(200, null)
|
|
634
|
+
} else {
|
|
635
|
+
resetRetry()
|
|
636
|
+
batchLimit = batchLimit?.let { limit -> (limit * 2).takeIf { it < config.maxBatch } }
|
|
637
|
+
if (!queue.isEmpty()) requestFlush()
|
|
638
|
+
}
|
|
639
|
+
saveState()
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
private fun backOff(status: Int?, retryAfterMs: Long?) {
|
|
643
|
+
state.retryAttempt += 1
|
|
644
|
+
val delay = retryAfterMs?.coerceAtLeast(Backoff.BASE_MS) ?: Backoff.delayMs(state.retryAttempt, random)
|
|
645
|
+
state.retryNextAt = clock.now() + delay
|
|
646
|
+
saveState()
|
|
647
|
+
log.debug { "batch not delivered (${status?.let { "HTTP $it" } ?: "network error"}); retry #${state.retryAttempt} in $delay ms" }
|
|
648
|
+
scheduleRetry(delay)
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
private fun scheduleRetry(delayMs: Long) {
|
|
652
|
+
retryTask?.cancel()
|
|
653
|
+
retryTask = scheduler.schedule(delayMs) {
|
|
654
|
+
retryTask = null
|
|
655
|
+
flushNow()
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
private fun resetRetry() {
|
|
660
|
+
state.retryAttempt = 0
|
|
661
|
+
state.retryNextAt = 0
|
|
662
|
+
retryTask?.cancel()
|
|
663
|
+
retryTask = null
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
private fun stop(status: Int, code: String?) {
|
|
667
|
+
if (stopped) return
|
|
668
|
+
stopped = true
|
|
669
|
+
timer?.cancel()
|
|
670
|
+
timer = null
|
|
671
|
+
retryTask?.cancel()
|
|
672
|
+
retryTask = null
|
|
673
|
+
log.error("HTTP $status${code?.let { " ($it)" } ?: ""}: the collector refused the key or the package name; sending stops until the next launch")
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
private fun envelopeInfo() = BatchBody.Envelope(
|
|
677
|
+
sdkName = SdkInfo.NAME,
|
|
678
|
+
sdkVersion = SdkInfo.VERSION,
|
|
679
|
+
wrapper = cfg.wrapper,
|
|
680
|
+
bundle = app.bundle,
|
|
681
|
+
appVersion = app.version?.take(32),
|
|
682
|
+
appBuild = app.build?.take(32),
|
|
683
|
+
environment = cfg.environment,
|
|
684
|
+
installId = installId,
|
|
685
|
+
)
|
|
686
|
+
|
|
687
|
+
private fun url(path: String): String = cfg.endpoint + path
|
|
688
|
+
|
|
689
|
+
private fun headers(json: Boolean): MutableMap<String, String> {
|
|
690
|
+
val h = LinkedHashMap<String, String>()
|
|
691
|
+
h["Authorization"] = "Bearer ${cfg.key}"
|
|
692
|
+
h["X-Kerdly-Bundle"] = app.bundle
|
|
693
|
+
h["X-Kerdly-Sdk"] = SdkInfo.header(cfg.wrapper)
|
|
694
|
+
// The app's version picks the config Kerdly serves (its version rules).
|
|
695
|
+
app.version?.takeIf { it.isNotEmpty() }?.let { h["X-Kerdly-App-Version"] = it }
|
|
696
|
+
app.build?.takeIf { it.isNotEmpty() }?.let { h["X-Kerdly-App-Build"] = it }
|
|
697
|
+
h["Accept"] = "application/json"
|
|
698
|
+
if (json) h["Content-Type"] = "application/json"
|
|
699
|
+
return h
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
// --- Remote config --------------------------------------------------------
|
|
703
|
+
|
|
704
|
+
private fun onConfigEtag(etag: String) {
|
|
705
|
+
etagHint = etag
|
|
706
|
+
if (etag != configCache.etag) scheduler.execute { maybeFetchConfig(force = true) }
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
/**
|
|
710
|
+
* At launch when the cache is ≥ 6 h old or was fetched for another app version (the first launch
|
|
711
|
+
* after an update) ([force] false); when a batch names another ETag.
|
|
712
|
+
*/
|
|
713
|
+
private fun maybeFetchConfig(force: Boolean) {
|
|
714
|
+
if (stopped) return
|
|
715
|
+
val now = clock.now()
|
|
716
|
+
if (force) {
|
|
717
|
+
if (configCache.etag != null && configCache.etag == etagHint) return
|
|
718
|
+
} else {
|
|
719
|
+
val fetchedAt = configCache.fetchedAt
|
|
720
|
+
val fresh = fetchedAt != null && now >= fetchedAt && now - fetchedAt < CONFIG_MAX_AGE_MS
|
|
721
|
+
if (configCache.config != null && fresh && configCache.appVersion == app.version) return
|
|
722
|
+
}
|
|
723
|
+
val last = lastConfigAttemptAt
|
|
724
|
+
// Rate-limited once this version's config is in; before, the back-off paces the asks.
|
|
725
|
+
if (configReady && last != null && now >= last && now - last < CONFIG_MIN_INTERVAL_MS) return
|
|
726
|
+
lastConfigAttemptAt = now
|
|
727
|
+
fetchConfig(now)
|
|
728
|
+
afterConfigFetch()
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
private fun fetchConfig(now: Long) {
|
|
732
|
+
val headers = headers(json = false)
|
|
733
|
+
val etag = configCache.etag
|
|
734
|
+
if (etag != null && configCache.config != null) headers["If-None-Match"] = etag
|
|
735
|
+
val response = try {
|
|
736
|
+
transport.execute(HttpRequest("GET", url("/v1/sdk/config"), headers, null))
|
|
737
|
+
} catch (e: Exception) {
|
|
738
|
+
log.debug { "config not fetched: ${e.javaClass.simpleName}: ${e.message}" }
|
|
739
|
+
return
|
|
740
|
+
}
|
|
741
|
+
when (response.status) {
|
|
742
|
+
200 -> {
|
|
743
|
+
val raw = parseObject(response.body)
|
|
744
|
+
if (raw == null) {
|
|
745
|
+
log.warn("ignored an unreadable remote config")
|
|
746
|
+
return
|
|
747
|
+
}
|
|
748
|
+
configCache = ConfigCache(response.etag ?: etagHint, now, raw, app.version)
|
|
749
|
+
if (!store.write(StoreFiles.CONFIG, configCache.serialize())) log.warn("could not write the remote config")
|
|
750
|
+
setConfig(configCache.config ?: RemoteConfig.DEFAULT)
|
|
751
|
+
log.debug { "remote config ${configCache.etag ?: "(no etag)"} applied" }
|
|
752
|
+
}
|
|
753
|
+
304 -> {
|
|
754
|
+
// Unchanged for the version the request named: the cached body is this version's too.
|
|
755
|
+
configCache = ConfigCache(configCache.etag, now, configCache.raw, app.version)
|
|
756
|
+
store.write(StoreFiles.CONFIG, configCache.serialize())
|
|
757
|
+
}
|
|
758
|
+
401, 403 -> stop(response.status, BatchResponses.errorCode(response.body))
|
|
759
|
+
else -> log.debug { "config fetch: HTTP ${response.status}" }
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
private fun setConfig(next: RemoteConfig) {
|
|
764
|
+
val couldSend = canSend()
|
|
765
|
+
config = next
|
|
766
|
+
applyConfig()
|
|
767
|
+
if (!couldSend && canSend() && !queue.isEmpty()) requestFlush()
|
|
768
|
+
// A later config may switch deferred links on; the launch's first config starts the
|
|
769
|
+
// collectors itself (afterConfigFetch).
|
|
770
|
+
if (launchWorkDone) scheduler.execute { askDeferredLinks() }
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
private fun applyConfig() {
|
|
774
|
+
val tooOld = config.minSupportedSdk?.let { Semver.compare(SdkInfo.VERSION, it) < 0 } ?: false
|
|
775
|
+
if (tooOld && !sdkTooOld) {
|
|
776
|
+
log.warn("this SDK (${SdkInfo.VERSION}) is older than min_supported_sdk ${config.minSupportedSdk}; sending is paused")
|
|
777
|
+
}
|
|
778
|
+
sdkTooOld = tooOld
|
|
779
|
+
if (!config.enabled) log.info("sending is paused by the remote config")
|
|
780
|
+
log.verbose = installId.isNotEmpty() && installId in config.debugDevices
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
// --- Attribution --------------------------------------------------------
|
|
784
|
+
|
|
785
|
+
private fun scheduleAttributionPolls() {
|
|
786
|
+
for (delay in ATTRIBUTION_POLLS_MS) scheduler.schedule(delay) { pollAttribution() }
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
private fun pollAttribution() {
|
|
790
|
+
// Polls only help while nothing is known and the collector has the install.
|
|
791
|
+
if (attribution != null || !canSend() || !state.installAcked) return
|
|
792
|
+
val url = url("/v1/sdk/attribution?install_id=" + URLEncoder.encode(installId, "UTF-8"))
|
|
793
|
+
val response = try {
|
|
794
|
+
transport.execute(HttpRequest("GET", url, headers(json = false), null))
|
|
795
|
+
} catch (e: Exception) {
|
|
796
|
+
log.debug { "attribution poll failed: ${e.javaClass.simpleName}" }
|
|
797
|
+
return
|
|
798
|
+
}
|
|
799
|
+
when (response.status) {
|
|
800
|
+
200 -> AttributionParser.fromPollBody(response.body)?.let(::updateAttribution)
|
|
801
|
+
401, 403 -> stop(response.status, BatchResponses.errorCode(response.body))
|
|
802
|
+
else -> log.debug { "attribution poll: HTTP ${response.status}" }
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
private fun updateAttribution(next: KerdlyAttribution) {
|
|
807
|
+
val current = attribution
|
|
808
|
+
if (current != null && jsonEquals(parseObject(current.raw), parseObject(next.raw))) return
|
|
809
|
+
attribution = next
|
|
810
|
+
if (!store.write(StoreFiles.ATTRIBUTION, next.raw)) log.warn("could not write the attribution")
|
|
811
|
+
log.debug { "attribution: ${next.network} / ${next.method} (${next.state})" }
|
|
812
|
+
for (l in listeners) deliver(l, next)
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
private fun deliver(listener: (KerdlyAttribution) -> Unit, value: KerdlyAttribution) {
|
|
816
|
+
main.post {
|
|
817
|
+
try {
|
|
818
|
+
listener(value)
|
|
819
|
+
} catch (t: Throwable) {
|
|
820
|
+
log.error("an onAttribution listener threw", t)
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
// --- Collectors ---------------------------------------------------
|
|
826
|
+
|
|
827
|
+
private fun startCollectors() {
|
|
828
|
+
if (cfg.metaAppId != null && !state.metaDone) scheduler.execute { collectMetaReferrer() }
|
|
829
|
+
scheduler.execute { collectAdvertisingId(force = false) }
|
|
830
|
+
startPlayReferrer()
|
|
831
|
+
scheduler.execute { askDeferredLinks() }
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
/** GAID + LAT: read at launch when the last read is ≥ 24 h old, sent only when it changed. */
|
|
835
|
+
private fun collectAdvertisingId(force: Boolean) {
|
|
836
|
+
if (!collecting()) return
|
|
837
|
+
if (!cfg.collectAdvertisingId || !state.ads || !config.collectAdvertisingId) return
|
|
838
|
+
val now = clock.now()
|
|
839
|
+
val last = state.adIdReadAt
|
|
840
|
+
if (!force && last != null && now >= last && now - last < AD_ID_REFRESH_MS) return
|
|
841
|
+
val result = safely("reading the advertising id", null) { platform.readAdvertisingId() } ?: return
|
|
842
|
+
state.adIdReadAt = now
|
|
843
|
+
state.lat = result.lat
|
|
844
|
+
val hash = sha1Hex("${result.gaid ?: ""}|${result.lat}")
|
|
845
|
+
if (hash != state.adIdHash) {
|
|
846
|
+
if (enqueue(EventNames.SIGNAL, Signals.advertisingIds(result.gaid, result.lat), now) != null) state.adIdHash = hash
|
|
847
|
+
log.debug { "advertising id ${maskId(result.gaid)} (lat ${result.lat})" }
|
|
848
|
+
}
|
|
849
|
+
saveState()
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
/** Once per install, on the launch with `$install`. The answer comes back to this
|
|
853
|
+
* thread, where the gates are checked again: consent withdrawn or a fetched config with
|
|
854
|
+
* `collect.public_ip: false` in the meantime drops it. No answer, or one that is not a global
|
|
855
|
+
* unicast IPv6 address, sends nothing and is never retried. */
|
|
856
|
+
private fun collectPublicIp() {
|
|
857
|
+
if (!collecting() || !publicIpAllowed()) return
|
|
858
|
+
try {
|
|
859
|
+
platform.startPublicIpv6Lookup(config.ipv6EchoUrl, PUBLIC_IP_TIMEOUT_MS) { answer ->
|
|
860
|
+
scheduler.execute { publicIpFinished(answer) }
|
|
861
|
+
}
|
|
862
|
+
} catch (t: Throwable) {
|
|
863
|
+
log.debug { "public IPv6 lookup: ${t.javaClass.simpleName}" }
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
private fun publicIpAllowed(): Boolean = state.ads && config.collectPublicIp
|
|
868
|
+
|
|
869
|
+
private fun publicIpFinished(answer: String?) {
|
|
870
|
+
if (!publicIpAllowed()) {
|
|
871
|
+
log.debug { "public IPv6 answer dropped: ads consent or collect.public_ip is off now" }
|
|
872
|
+
return
|
|
873
|
+
}
|
|
874
|
+
val ipv6 = PublicIp.globalIpv6(answer)
|
|
875
|
+
if (ipv6 == null) {
|
|
876
|
+
log.debug { if (answer == null) "no public IPv6" else "the public IPv6 lookup answered something else; dropped" }
|
|
877
|
+
return
|
|
878
|
+
}
|
|
879
|
+
enqueue(EventNames.SIGNAL, Signals.publicIp(ipv6), clock.now())
|
|
880
|
+
log.info("public IPv6 ${maskId(ipv6)}")
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
/** Once per install, when `metaAppId` is set: the freshest row of the three Meta apps. */
|
|
884
|
+
private fun collectMetaReferrer() {
|
|
885
|
+
if (!collecting()) return
|
|
886
|
+
val appId = cfg.metaAppId ?: return
|
|
887
|
+
if (state.metaDone || !config.collectMetaInstallReferrer) return
|
|
888
|
+
val rows = safely("reading the Meta install referrer", emptyList()) { platform.readMetaReferrer(appId) }
|
|
889
|
+
val best = MetaReferrer.freshest(rows)
|
|
890
|
+
if (best != null) {
|
|
891
|
+
enqueue(EventNames.SIGNAL, Signals.metaInstallReferrer(best), clock.now())
|
|
892
|
+
log.debug { "Meta install referrer from ${best.source}" }
|
|
893
|
+
} else {
|
|
894
|
+
log.debug { "no Meta install referrer" }
|
|
895
|
+
}
|
|
896
|
+
state.metaDone = true
|
|
897
|
+
saveState()
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
/** Until it answers OK or a permanent code; transient failures retry at the next foreground
|
|
901
|
+
* and launch, for 90 days after the install (the first attempt always runs). */
|
|
902
|
+
private fun startPlayReferrer() {
|
|
903
|
+
if (!collecting()) return
|
|
904
|
+
if (!config.collectInstallReferrer || state.referrerDone || referrerInFlight) return
|
|
905
|
+
val since = state.installedAt ?: state.firstLaunchAt
|
|
906
|
+
if (state.referrerAttempts > 0 && since != null && clock.now() - since > REFERRER_WINDOW_MS) {
|
|
907
|
+
state.referrerDone = true
|
|
908
|
+
saveState()
|
|
909
|
+
log.debug { "Play install referrer: no answer within 90 days of the install; giving up" }
|
|
910
|
+
return
|
|
911
|
+
}
|
|
912
|
+
referrerInFlight = true
|
|
913
|
+
state.referrerAttempts += 1
|
|
914
|
+
try {
|
|
915
|
+
platform.startPlayReferrer(REFERRER_TIMEOUT_MS) { result -> scheduler.execute { onPlayReferrer(result) } }
|
|
916
|
+
} catch (t: Throwable) {
|
|
917
|
+
referrerInFlight = false
|
|
918
|
+
log.debug { "Play install referrer: ${t.javaClass.simpleName}" }
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
private fun onPlayReferrer(result: PlayReferrerResult) {
|
|
923
|
+
referrerInFlight = false
|
|
924
|
+
if (state.referrerDone) return
|
|
925
|
+
when (result) {
|
|
926
|
+
is PlayReferrerResult.Ok -> {
|
|
927
|
+
enqueue(EventNames.SIGNAL, Signals.installReferrerOk(result.details), clock.now())
|
|
928
|
+
state.referrerDone = true
|
|
929
|
+
if (state.ddlEligible && !state.ddlTiktokDone) state.ddlReferrer = result.details.referrer
|
|
930
|
+
}
|
|
931
|
+
is PlayReferrerResult.Permanent -> {
|
|
932
|
+
enqueue(EventNames.SIGNAL, Signals.installReferrerUnavailable(result.code), clock.now())
|
|
933
|
+
state.referrerDone = true
|
|
934
|
+
log.debug { "Play install referrer unavailable (code ${result.code}): not installed from Play" }
|
|
935
|
+
}
|
|
936
|
+
is PlayReferrerResult.Transient -> log.debug { "Play install referrer: ${result.reason}; retrying at the next foreground or launch" }
|
|
937
|
+
}
|
|
938
|
+
saveState()
|
|
939
|
+
askDeferredLinks()
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
// --- Deferred deep links -------------------------------------------------
|
|
943
|
+
|
|
944
|
+
/** TikTok, once per install: on the collectors, a fetched config, the Play referrer's answer
|
|
945
|
+
* (TikTok's request carries it, so the SDK waits for Play's first answer) and a foreground (a
|
|
946
|
+
* retry after a failure in transit). Only while the config's `ddl` block is on, the install is
|
|
947
|
+
* younger than `max_age_h` and the `ads` consent is on. The GAID goes only without
|
|
948
|
+
* limit-ad-tracking. Blocking, like the batch: it runs on the SDK's own thread. */
|
|
949
|
+
private fun askDeferredLinks() {
|
|
950
|
+
if (!collecting()) return
|
|
951
|
+
val ddl = config.ddl ?: return
|
|
952
|
+
val appId = ddl.tiktokAppId ?: return
|
|
953
|
+
if (!ddl.enabled || !state.ddlEligible || state.ddlTiktokDone || !state.ads || stopped || ddlWaitsForForeground) return
|
|
954
|
+
val first = state.firstLaunchAt ?: return
|
|
955
|
+
if (clock.now() - first > ddl.maxAgeMs) return
|
|
956
|
+
if (config.collectInstallReferrer && !state.referrerDone && (referrerInFlight || state.referrerAttempts == 0)) return
|
|
957
|
+
val adId = if (cfg.collectAdvertisingId && config.collectAdvertisingId) safely("reading the advertising id", null) { platform.readAdvertisingId() } else null
|
|
958
|
+
val device = safely("reading the device context", null) { platform.deviceContext() } ?: DeviceContext.UNKNOWN
|
|
959
|
+
val request = TikTokDdl.request(
|
|
960
|
+
appId, ddl.storeAppId, app, device, adId?.takeIf { !it.lat }?.gaid, state.ddlReferrer,
|
|
961
|
+
safely("reading the user agent", null) { System.getProperty("http.agent") }, clock.now(),
|
|
962
|
+
)
|
|
963
|
+
val answer = try {
|
|
964
|
+
TikTokDdl.parse(transport.execute(request))
|
|
965
|
+
} catch (e: Exception) {
|
|
966
|
+
DdlAnswer(TikTokDdl.NETWORK, "error", null, null, "${e.javaClass.simpleName}: ${e.message}")
|
|
967
|
+
}
|
|
968
|
+
if (answer.transient) {
|
|
969
|
+
state.ddlTiktokFailures += 1
|
|
970
|
+
if (state.ddlTiktokFailures < MAX_DDL_FAILURES) {
|
|
971
|
+
ddlWaitsForForeground = true
|
|
972
|
+
saveState()
|
|
973
|
+
log.debug { "deferred link: TikTok did not answer (${answer.detail}); retried at the next foreground" }
|
|
974
|
+
return
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
val attempt = if (answer.transient) state.ddlTiktokFailures else state.ddlTiktokFailures + 1
|
|
978
|
+
state.ddlTiktokDone = true
|
|
979
|
+
state.ddlReferrer = null
|
|
980
|
+
saveState()
|
|
981
|
+
enqueue(EventNames.SIGNAL, Signals.deferredLink(answer, attempt), clock.now())
|
|
982
|
+
log.info("deferred link: TikTok ${answer.status}")
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
private inline fun <T> safely(what: String, fallback: T, block: () -> T): T = try {
|
|
986
|
+
block()
|
|
987
|
+
} catch (t: Throwable) {
|
|
988
|
+
log.warn("$what failed", t)
|
|
989
|
+
fallback
|
|
990
|
+
}
|
|
991
|
+
}
|