@app-swiss-knife/react-native-sdk 0.3.2 → 0.5.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 (177) hide show
  1. package/CHANGELOG.md +465 -0
  2. package/LICENSE +21 -0
  3. package/README.md +229 -42
  4. package/SwissKnifePurchases.podspec +1 -1
  5. package/android/build.gradle +24 -2
  6. package/android/consumer-rules.pro +12 -0
  7. package/android/src/main/AndroidManifest.xml +15 -1
  8. package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +5 -4
  9. package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +7 -2
  10. package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +168 -6
  11. package/android/src/play/java/com/swissknife/purchases/StoreIntentHandler.kt +7 -0
  12. package/android/src/rustore/java/com/swissknife/purchases/StoreIntentHandler.kt +9 -0
  13. package/android/vendor/java/com/appswissknife/SwissKnife.kt +107 -38
  14. package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +180 -115
  15. package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +16 -18
  16. package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +13 -13
  17. package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +56 -25
  18. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
  19. package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +641 -208
  20. package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +195 -26
  21. package/android/vendor/java/com/appswissknife/identity/Identity.kt +31 -6
  22. package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +5 -0
  23. package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +69 -35
  24. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +756 -98
  25. package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +214 -30
  26. package/android/vendor/java/com/appswissknife/notifications/NotificationRenderer.kt +195 -0
  27. package/android/vendor/java/com/appswissknife/notifications/PermissionRequestActivity.kt +60 -0
  28. package/android/vendor/java/com/appswissknife/notifications/PermissionStatus.kt +41 -0
  29. package/android/vendor/java/com/appswissknife/notifications/PushEventQueue.kt +143 -0
  30. package/android/vendor/java/com/appswissknife/notifications/PushPayload.kt +72 -0
  31. package/android/vendor/java/com/appswissknife/notifications/PushRegistration.kt +89 -0
  32. package/android/vendor/java/com/appswissknife/notifications/SwissKnifeMessagingService.kt +57 -0
  33. package/android/vendor/java/com/appswissknife/notifications/SwissKnifeNotifications.kt +438 -0
  34. package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +266 -64
  35. package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +1 -0
  36. package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +545 -88
  37. package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +55 -24
  38. package/android/vendor/java/com/appswissknife/purchases/ProductKindHint.kt +21 -0
  39. package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +14 -0
  40. package/android/vendor-rustore/AndroidManifest.xml +59 -0
  41. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreGateway.kt +428 -0
  42. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreInitProvider.kt +43 -0
  43. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStorePriceEnrichmentProvider.kt +85 -0
  44. package/app.plugin.js +287 -0
  45. package/ios/SwissKnifePurchases.m +20 -0
  46. package/ios/SwissKnifePurchases.swift +97 -3
  47. package/ios/SwissKnifePushBootstrap.m +34 -0
  48. package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +138 -89
  49. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
  50. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +531 -100
  51. package/ios/vendor/SwissKnifeiOS/Net/BackendBackoffGate.swift +43 -2
  52. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +495 -16
  53. package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +231 -23
  54. package/ios/vendor/SwissKnifeiOS/Notifications/PushPayload.swift +87 -0
  55. package/ios/vendor/SwissKnifeiOS/Notifications/PushRegistrar.swift +322 -0
  56. package/ios/vendor/SwissKnifeiOS/Notifications/SwissKnife+Notifications.swift +403 -0
  57. package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +1 -0
  58. package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +11 -7
  59. package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +38 -7
  60. package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +34 -6
  61. package/lib/commonjs/attribution.js +4 -3
  62. package/lib/commonjs/attribution.js.map +1 -1
  63. package/lib/commonjs/identity.js +12 -11
  64. package/lib/commonjs/identity.js.map +1 -1
  65. package/lib/commonjs/index.js +16 -5
  66. package/lib/commonjs/index.js.map +1 -1
  67. package/lib/commonjs/internal/config.js +105 -8
  68. package/lib/commonjs/internal/config.js.map +1 -1
  69. package/lib/commonjs/internal/telemetry-context.js +70 -0
  70. package/lib/commonjs/internal/telemetry-context.js.map +1 -0
  71. package/lib/commonjs/modules/analytics.js +18 -25
  72. package/lib/commonjs/modules/analytics.js.map +1 -1
  73. package/lib/commonjs/modules/crash-reporting.js +353 -31
  74. package/lib/commonjs/modules/crash-reporting.js.map +1 -1
  75. package/lib/commonjs/modules/log.js +1 -1
  76. package/lib/commonjs/modules/notifications.js +500 -0
  77. package/lib/commonjs/modules/notifications.js.map +1 -0
  78. package/lib/commonjs/modules/performance.js +57 -8
  79. package/lib/commonjs/modules/performance.js.map +1 -1
  80. package/lib/commonjs/native/module.js +6 -0
  81. package/lib/commonjs/native/module.js.map +1 -1
  82. package/lib/commonjs/native/spec.js +12 -5
  83. package/lib/commonjs/native/spec.js.map +1 -1
  84. package/lib/commonjs/purchases.js +4 -4
  85. package/lib/commonjs/types.js +12 -15
  86. package/lib/commonjs/types.js.map +1 -1
  87. package/lib/module/attribution.js +4 -3
  88. package/lib/module/attribution.js.map +1 -1
  89. package/lib/module/identity.js +12 -11
  90. package/lib/module/identity.js.map +1 -1
  91. package/lib/module/index.js +8 -4
  92. package/lib/module/index.js.map +1 -1
  93. package/lib/module/internal/config.js +103 -8
  94. package/lib/module/internal/config.js.map +1 -1
  95. package/lib/module/internal/telemetry-context.js +63 -0
  96. package/lib/module/internal/telemetry-context.js.map +1 -0
  97. package/lib/module/modules/analytics.js +18 -25
  98. package/lib/module/modules/analytics.js.map +1 -1
  99. package/lib/module/modules/crash-reporting.js +353 -31
  100. package/lib/module/modules/crash-reporting.js.map +1 -1
  101. package/lib/module/modules/log.js +1 -1
  102. package/lib/module/modules/notifications.js +491 -0
  103. package/lib/module/modules/notifications.js.map +1 -0
  104. package/lib/module/modules/performance.js +57 -8
  105. package/lib/module/modules/performance.js.map +1 -1
  106. package/lib/module/native/module.js +6 -1
  107. package/lib/module/native/module.js.map +1 -1
  108. package/lib/module/native/spec.js +11 -4
  109. package/lib/module/native/spec.js.map +1 -1
  110. package/lib/module/purchases.js +4 -4
  111. package/lib/module/types.js +12 -15
  112. package/lib/module/types.js.map +1 -1
  113. package/lib/typescript/commonjs/attribution.d.ts +3 -2
  114. package/lib/typescript/commonjs/attribution.d.ts.map +1 -1
  115. package/lib/typescript/commonjs/identity.d.ts.map +1 -1
  116. package/lib/typescript/commonjs/index.d.ts +3 -1
  117. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  118. package/lib/typescript/commonjs/internal/config.d.ts +16 -2
  119. package/lib/typescript/commonjs/internal/config.d.ts.map +1 -1
  120. package/lib/typescript/commonjs/internal/telemetry-context.d.ts +22 -0
  121. package/lib/typescript/commonjs/internal/telemetry-context.d.ts.map +1 -0
  122. package/lib/typescript/commonjs/modules/analytics.d.ts +8 -11
  123. package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -1
  124. package/lib/typescript/commonjs/modules/crash-reporting.d.ts +50 -12
  125. package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -1
  126. package/lib/typescript/commonjs/modules/notifications.d.ts +110 -0
  127. package/lib/typescript/commonjs/modules/notifications.d.ts.map +1 -0
  128. package/lib/typescript/commonjs/modules/performance.d.ts +13 -0
  129. package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -1
  130. package/lib/typescript/commonjs/native/module.d.ts +2 -0
  131. package/lib/typescript/commonjs/native/module.d.ts.map +1 -1
  132. package/lib/typescript/commonjs/native/spec.d.ts +33 -4
  133. package/lib/typescript/commonjs/native/spec.d.ts.map +1 -1
  134. package/lib/typescript/commonjs/purchases.d.ts +4 -4
  135. package/lib/typescript/commonjs/types.d.ts +4 -5
  136. package/lib/typescript/commonjs/types.d.ts.map +1 -1
  137. package/lib/typescript/module/attribution.d.ts +3 -2
  138. package/lib/typescript/module/attribution.d.ts.map +1 -1
  139. package/lib/typescript/module/identity.d.ts.map +1 -1
  140. package/lib/typescript/module/index.d.ts +3 -1
  141. package/lib/typescript/module/index.d.ts.map +1 -1
  142. package/lib/typescript/module/internal/config.d.ts +16 -2
  143. package/lib/typescript/module/internal/config.d.ts.map +1 -1
  144. package/lib/typescript/module/internal/telemetry-context.d.ts +22 -0
  145. package/lib/typescript/module/internal/telemetry-context.d.ts.map +1 -0
  146. package/lib/typescript/module/modules/analytics.d.ts +8 -11
  147. package/lib/typescript/module/modules/analytics.d.ts.map +1 -1
  148. package/lib/typescript/module/modules/crash-reporting.d.ts +50 -12
  149. package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -1
  150. package/lib/typescript/module/modules/notifications.d.ts +110 -0
  151. package/lib/typescript/module/modules/notifications.d.ts.map +1 -0
  152. package/lib/typescript/module/modules/performance.d.ts +13 -0
  153. package/lib/typescript/module/modules/performance.d.ts.map +1 -1
  154. package/lib/typescript/module/native/module.d.ts +2 -0
  155. package/lib/typescript/module/native/module.d.ts.map +1 -1
  156. package/lib/typescript/module/native/spec.d.ts +33 -4
  157. package/lib/typescript/module/native/spec.d.ts.map +1 -1
  158. package/lib/typescript/module/purchases.d.ts +4 -4
  159. package/lib/typescript/module/types.d.ts +4 -5
  160. package/lib/typescript/module/types.d.ts.map +1 -1
  161. package/package.json +13 -4
  162. package/src/attribution.ts +4 -3
  163. package/src/identity.ts +12 -11
  164. package/src/index.ts +18 -4
  165. package/src/internal/config.ts +113 -8
  166. package/src/internal/telemetry-context.ts +76 -0
  167. package/src/modules/analytics.ts +24 -33
  168. package/src/modules/crash-reporting.ts +476 -67
  169. package/src/modules/log.ts +1 -1
  170. package/src/modules/notifications.ts +557 -0
  171. package/src/modules/performance.ts +94 -14
  172. package/src/native/module.ts +6 -0
  173. package/src/native/spec.ts +45 -10
  174. package/src/purchases.ts +4 -4
  175. package/src/types.ts +12 -15
  176. package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +0 -326
  177. package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +0 -296
@@ -3,32 +3,33 @@
3
3
  // Amplitude/Mixpanel-compatible analytics SDK for swiss-knife (Android).
4
4
  // Drop-in replacement — migrate from Amplitude by changing the import.
5
5
  //
6
- // Phase 2.2 change (persistent event queue):
7
- // - track() now writes the event synchronously to EventQueueStore on disk
8
- // (cacheDir/swissknife/events.jsonl). Events survive process death.
9
- // - flush() enqueues a unique-named WorkManager OneTimeWorkRequest for
10
- // FlushEventsWorker, which handles HTTP + exponential backoff + 5-attempt
11
- // cap + dead-letter. Pending events are drained from any prior session
12
- // on the next foreground flush.
13
- // - In-memory eventQueue is gone — disk is the only queue.
6
+ // Delivery has ONE pipeline: every event becomes an `analytics` item on
7
+ // IngestClient (disk queue, POST /ingest, backoff), which SwissKnife.configure,
8
+ // configureCore and ensureObservabilityBackend wire. A host may call
9
+ // [SKAnalytics.initialize] before that. Events tracked in between wait in a
10
+ // bounded in-memory buffer and are handed to IngestClient, in order, by the
11
+ // first track or flush (including the flush-timer tick) after it is wired.
12
+ // Nothing leaves the device before then. The wiring keeps the host's
13
+ // configuration; it initializes analytics with the defaults only when the host
14
+ // has not.
15
+ //
16
+ // The pre-Round-C pipeline (EventQueueStore + FlushEventsWorker: POST
17
+ // /api/sdk/events/batch, dead-letter on any 4xx, the api key in WorkManager
18
+ // input data) is gone, as on iOS (Round E). [SKAnalytics.initialize] retires
19
+ // what an older SDK version may have left behind: its enqueued WorkManager job
20
+ // and its cacheDir/swissknife/events.jsonl queue file.
14
21
 
15
22
  package com.appswissknife.analytics
16
23
 
17
24
  import android.content.Context
18
- import android.os.Build
19
25
  import androidx.annotation.VisibleForTesting
20
- import androidx.work.BackoffPolicy
21
- import androidx.work.Constraints
22
- import androidx.work.ExistingWorkPolicy
23
- import androidx.work.NetworkType
24
- import androidx.work.OneTimeWorkRequestBuilder
25
26
  import androidx.work.WorkManager
26
- import com.appswissknife.context.IDs
27
27
  import com.appswissknife.device.DeviceID
28
+ import com.appswissknife.diagnostics.SKLog
28
29
  import com.appswissknife.net.IngestClient
29
- import com.appswissknife.net.IngestItem
30
30
  import com.appswissknife.net.IngestItemType
31
31
  import org.json.JSONObject
32
+ import java.io.File
32
33
  import java.util.UUID
33
34
  import java.util.concurrent.Executors
34
35
  import java.util.concurrent.ScheduledFuture
@@ -36,6 +37,12 @@ import java.util.concurrent.TimeUnit
36
37
 
37
38
  // MARK: - Configuration
38
39
 
40
+ /**
41
+ * Events are delivered through the backend that `SwissKnife.configureCore`
42
+ * (or `configure`) wires: its api key and server URL authenticate and address
43
+ * every POST /ingest. [apiKey], [serverURL] and [flushQueueSize] are kept for
44
+ * source compatibility and are not used for delivery.
45
+ */
39
46
  data class SKAnalyticsConfiguration(
40
47
  val apiKey: String,
41
48
  val serverURL: String = "",
@@ -114,8 +121,39 @@ class SKAnalytics private constructor() {
114
121
  @JvmStatic
115
122
  val instance = SKAnalytics()
116
123
 
124
+ /**
125
+ * Most events held while IngestClient is not wired yet. Past it the
126
+ * OLDEST is dropped (with one warning), so a host that never calls
127
+ * `SwissKnife.configureCore` costs a fixed amount of memory (events
128
+ * are small JSON objects, typically well under 1 KB each).
129
+ */
130
+ internal const val PRE_CONFIGURE_BUFFER_LIMIT = 1_000
131
+
132
+ /**
133
+ * Unique work name and worker class of the removed legacy flush job.
134
+ * An app upgraded from an older SDK may still have one enqueued; it is
135
+ * cancelled at [initialize]. Were it to run first, WorkManager fails
136
+ * it quietly ("Could not create Worker") because the class is gone.
137
+ */
138
+ internal const val LEGACY_FLUSH_WORK_NAME = "swissknife.flush_events"
139
+ internal const val LEGACY_FLUSH_WORKER_CLASS = "com.appswissknife.analytics.FlushEventsWorker"
140
+
141
+ /** The removed legacy queue file (and its rewrite temp), under cacheDir. */
142
+ internal val LEGACY_QUEUE_FILES = listOf("swissknife/events.jsonl", "swissknife/events.jsonl.tmp")
143
+
144
+ /**
145
+ * Held by [initialize] and [initializeUnlessInitialized], so a core
146
+ * wiring on another thread cannot replace the host's configuration
147
+ * between its check and its own initialize.
148
+ */
149
+ private val initializeLock = Any()
150
+
117
151
  @JvmStatic
118
152
  fun initialize(context: Context, configuration: SKAnalyticsConfiguration) {
153
+ synchronized(initializeLock) { initializeLocked(context, configuration) }
154
+ }
155
+
156
+ private fun initializeLocked(context: Context, configuration: SKAnalyticsConfiguration) {
119
157
  // Always pin appContext to the Application context to avoid leaking
120
158
  // an Activity. DeviceID also internally does .applicationContext but
121
159
  // we want the same guarantee for our cached reference.
@@ -126,19 +164,59 @@ class SKAnalytics private constructor() {
126
164
  // is enqueued. Subsequent reads (via [getDeviceId]) are in-memory.
127
165
  instance.deviceId = DeviceID.get(appCtx)
128
166
  instance.sessionId = System.currentTimeMillis()
129
- // (Re)build the on-disk queue handle bound to this Context.
130
- instance.eventStore = EventQueueStore(appCtx)
167
+ retireLegacyQueue(appCtx)
131
168
  instance.startFlushTimer()
132
169
 
133
170
  if (configuration.trackingSessionEvents) {
134
171
  instance.track("[SwissKnife] Session Start")
135
172
  }
136
173
 
137
- // Best-effort: drain any pending events left over from a prior
138
- // session (process killed before they flushed). Safe because
139
- // event_id idempotency guarantees no double-counting on retry.
174
+ // Hands the pre-configure buffer over when IngestClient is wired.
140
175
  instance.flush()
141
176
  }
177
+
178
+ /**
179
+ * The core wiring's call (`SwissKnife.ensureObservabilityBackend`,
180
+ * reached from `configure` / `configureCore` and the React Native
181
+ * bridges), made right after it installs IngestClient.
182
+ *
183
+ * When the host already called [initialize], its configuration stands
184
+ * (opt-out, session events, flush interval, session id) and no second
185
+ * Session Start is tracked: this only hands the events held since then
186
+ * to IngestClient. Otherwise it initializes with [defaultConfiguration],
187
+ * which sets the appContext that every track needs.
188
+ */
189
+ internal fun initializeUnlessInitialized(
190
+ context: Context,
191
+ defaultConfiguration: SKAnalyticsConfiguration,
192
+ ) {
193
+ synchronized(initializeLock) {
194
+ if (instance.config != null) {
195
+ instance.flush()
196
+ } else {
197
+ initializeLocked(context, defaultConfiguration)
198
+ }
199
+ }
200
+ }
201
+
202
+ /**
203
+ * Best-effort cleanup of what the removed legacy pipeline left on an
204
+ * upgraded install. Each step is independent: WorkManager may not be
205
+ * initialised in this host, and the files may not exist. A cancelled
206
+ * job's row keeps its input data (the old SDK key) until WorkManager
207
+ * prunes finished work; pruneWork() is not called because it would
208
+ * also drop the host's own finished work.
209
+ */
210
+ private fun retireLegacyQueue(context: Context) {
211
+ runCatching {
212
+ val wm = WorkManager.getInstance(context)
213
+ wm.cancelUniqueWork(LEGACY_FLUSH_WORK_NAME)
214
+ wm.cancelAllWorkByTag(LEGACY_FLUSH_WORKER_CLASS)
215
+ }
216
+ for (path in LEGACY_QUEUE_FILES) {
217
+ runCatching { File(context.cacheDir, path).delete() }
218
+ }
219
+ }
142
220
  }
143
221
 
144
222
  private var config: SKAnalyticsConfiguration? = null
@@ -151,12 +229,13 @@ class SKAnalytics private constructor() {
151
229
  private var sessionId: Long = 0
152
230
 
153
231
  /**
154
- * Persistent on-disk event queue. Created in [initialize]; null until then.
155
- * track() before initialize() is a no-op (matches prior behavior — we'd
156
- * have nothing to persist against without a Context anyway).
232
+ * Events tracked after [initialize] but before IngestClient is wired, oldest
233
+ * first. Guarded by itself: every hand-off drains it under the same lock as
234
+ * the enqueue that follows, so order is kept. track() before initialize()
235
+ * stays a no-op (there is no Context to deliver with).
157
236
  */
158
- @VisibleForTesting
159
- internal var eventStore: EventQueueStore? = null
237
+ private val preConfigureBuffer = java.util.ArrayDeque<JSONObject>()
238
+ private var preConfigureOverflowLogged = false
160
239
  private val userProperties = mutableMapOf<String, Any>()
161
240
  private val groups = mutableMapOf<String, Any>()
162
241
  private val superProperties = mutableMapOf<String, Any>()
@@ -205,43 +284,58 @@ class SKAnalytics private constructor() {
205
284
  fun track(eventType: String) = track(eventType, null)
206
285
 
207
286
  /**
208
- * Round-C ingest path. Enqueues an analytics-typed IngestItem on the
209
- * unified IngestClient queue. Falls back to the legacy EventQueueStore
210
- * + FlushEventsWorker only when IngestClient.shared is null (i.e. the
211
- * SDK wasn't configured via SwissKnife.configure).
287
+ * Enqueue an analytics-typed IngestItem on the unified IngestClient queue,
288
+ * after anything still waiting in [preConfigureBuffer]. Before
289
+ * IngestClient is wired the event waits in that buffer instead.
290
+ *
291
+ * Nothing is enqueued while opted out: identify and groupIdentify reach
292
+ * the queue only through here (as on iOS, `ingestEnqueueLocked`).
212
293
  */
213
294
  private fun enqueueAnalyticsItem(data: JSONObject, ctx: Context) {
214
- val client = IngestClient.shared
215
- if (client != null) {
295
+ if (config?.optOut == true) return
296
+ synchronized(preConfigureBuffer) {
297
+ val client = IngestClient.shared
298
+ if (client == null) {
299
+ bufferUntilConfiguredLocked(data)
300
+ return
301
+ }
302
+ drainPreConfigureBufferLocked(client, ctx)
216
303
  client.enqueue(IngestItemType.Analytics, data, ctx)
217
- return
218
304
  }
219
- // Legacy fallback — pre-Round-C path. Kept so unit tests that
220
- // exercise initialize() without configure() still observe events
221
- // on disk.
222
- val store = eventStore ?: return
223
- val legacy = JSONObject(data.toString()).apply {
224
- put("event_id", IDs.eventId())
225
- put("time", System.currentTimeMillis())
226
- put("platform", "Android")
227
- put("os_name", "android")
228
- put("os_version", Build.VERSION.RELEASE)
305
+ }
306
+
307
+ private fun bufferUntilConfiguredLocked(data: JSONObject) {
308
+ if (preConfigureBuffer.size >= PRE_CONFIGURE_BUFFER_LIMIT) {
309
+ preConfigureBuffer.pollFirst()
310
+ if (!preConfigureOverflowLogged) {
311
+ preConfigureOverflowLogged = true
312
+ SKLog.warn("analytics") {
313
+ "IngestClient is not wired (call SwissKnife.configureCore); holding the newest " +
314
+ "$PRE_CONFIGURE_BUFFER_LIMIT events in memory and dropping older ones"
315
+ }
316
+ }
317
+ }
318
+ preConfigureBuffer.addLast(data)
319
+ }
320
+
321
+ /** Caller holds the [preConfigureBuffer] lock. */
322
+ private fun drainPreConfigureBufferLocked(client: IngestClient, ctx: Context) {
323
+ while (true) {
324
+ val data = preConfigureBuffer.pollFirst() ?: break
325
+ client.enqueue(IngestItemType.Analytics, data, ctx)
229
326
  }
230
- store.append(legacy)
231
- val threshold = config?.flushQueueSize ?: 30
232
- if (store.count() >= threshold) flush()
233
327
  }
234
328
 
235
329
  /**
236
- * Persist a pre-built event map directly to the disk-backed queue.
330
+ * Enqueue a pre-built event map on the same pipeline as [track].
237
331
  *
238
332
  * **For the React Native bridge.** The RN JS layer builds the full event
239
333
  * payload (with `event_id`, `device_id`, super properties, timed-event
240
334
  * duration, identify merges) and hands it off here. We bypass [track]'s
241
335
  * event-construction logic — that logic lives in JS so JS-only state
242
336
  * (super properties, timed events) is honored without round-tripping
243
- * through native. Native owns the *queue* (disk persistence, WorkManager
244
- * back-off, dead-letter); JS owns the *payload shape*.
337
+ * through native. Native owns the *queue* (IngestClient's disk queue and
338
+ * back-off); JS owns the *payload shape*.
245
339
  *
246
340
  * The event map must already carry an `event_id` (idempotency key) and
247
341
  * `device_id`. Anything JSON-serializable is accepted.
@@ -249,19 +343,9 @@ class SKAnalytics private constructor() {
249
343
  fun trackPreBuiltEvent(event: Map<String, Any?>) {
250
344
  if (config?.optOut == true) return
251
345
  val ctx = appContext ?: return
252
- // Round-C: the RN JS layer builds the full event; we pass it
253
- // verbatim into the IngestClient data block. ContextSnapshot still
254
- // wraps it on flush.
255
- val data = toJSONObject(event)
256
- val client = IngestClient.shared
257
- if (client != null) {
258
- client.enqueue(IngestItemType.Analytics, data, ctx)
259
- return
260
- }
261
- val store = eventStore ?: return
262
- store.append(data)
263
- val threshold = config?.flushQueueSize ?: 30
264
- if (store.count() >= threshold) flush()
346
+ // The RN JS layer builds the full event; we pass it verbatim into the
347
+ // IngestClient data block. ContextSnapshot still wraps it on flush.
348
+ enqueueAnalyticsItem(toJSONObject(event), ctx)
265
349
  }
266
350
 
267
351
  /**
@@ -428,67 +512,48 @@ class SKAnalytics private constructor() {
428
512
  // MARK: Flush
429
513
 
430
514
  /**
431
- * Enqueue a [FlushEventsWorker] run. Idempotent: calling this multiple
432
- * times in quick succession coalesces into a single run via the
433
- * KEEP existing-work policy on the unique work name.
515
+ * Hand the pre-configure buffer to IngestClient and schedule its
516
+ * WorkManager flush (POST /ingest; KEEP coalesces repeated calls).
517
+ * Before IngestClient is wired this does nothing: the buffer waits.
434
518
  *
435
- * Why KEEP (not REPLACE)?
436
- * - REPLACE cancels the in-flight worker, which causes its IDs to NOT
437
- * be removed from disk even if its HTTP request is mid-fly — the
438
- * follow-up enqueue then re-reads the same events. That's harmless
439
- * correctness-wise (backend idempotency dedupes), but it doubles the
440
- * network spend and the wall-clock latency.
441
- * - KEEP preserves the in-flight attempt's retry chain. If the running
442
- * worker is in backoff state, follow-up flush() calls coalesce into
443
- * the existing chain rather than restarting backoff from 1s.
444
- * - KEEP also avoids the well-known WM 1.x/2.x bug where REPLACE on a
445
- * unique work name briefly leaves the queue in REPLACED state and
446
- * drops the enqueue.
519
+ * Without the scheduleFlush, IngestClient-queued events would only be
520
+ * flushed at its batch size (100) or on a reachability transition, so a
521
+ * handful of events would never be sent.
447
522
  */
448
523
  fun flush() {
449
524
  val ctx = appContext ?: return
450
- val cfg = config ?: return
451
-
452
- // Route the flush to whichever queue trackPreBuiltEvent enqueues into.
453
- // When the unified IngestClient is wired, events go to ITS disk queue
454
- // (POST /ingest), so we must drain that — not the legacy EventQueueStore
455
- // via FlushEventsWorker. Without this, IngestClient-queued events are
456
- // only flushed at batchSize (100) or on a reachability transition, so a
457
- // handful of events never get sent.
458
- val ingest = IngestClient.shared
459
- if (ingest != null) {
460
- ingest.scheduleFlush(ctx)
461
- return
462
- }
463
-
464
- val constraints = Constraints.Builder()
465
- .setRequiredNetworkType(NetworkType.CONNECTED)
466
- .build()
467
-
468
- val request = OneTimeWorkRequestBuilder<FlushEventsWorker>()
469
- .setConstraints(constraints)
470
- // Exponential backoff with a 1s initial delay. WM caps the
471
- // backoff at 5h regardless; for our 5-attempt budget the
472
- // delays are 1s/2s/4s/8s (next attempt would be 16s but we
473
- // DLQ at attempt 5).
474
- .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 1, TimeUnit.SECONDS)
475
- .setInputData(
476
- FlushEventsWorker.buildInput(
477
- apiKey = cfg.apiKey,
478
- serverURL = cfg.serverURL,
479
- )
480
- )
481
- .build()
482
-
483
- WorkManager.getInstance(ctx).enqueueUniqueWork(
484
- FlushEventsWorker.UNIQUE_WORK_NAME,
485
- ExistingWorkPolicy.KEEP,
486
- request,
487
- )
525
+ val ingest = IngestClient.shared ?: return
526
+ synchronized(preConfigureBuffer) { drainPreConfigureBufferLocked(ingest, ctx) }
527
+ ingest.scheduleFlush(ctx)
488
528
  }
489
529
 
490
530
  fun setOptOut(optOut: Boolean) {
491
531
  config = config?.copy(optOut = optOut)
532
+ // Nothing held before configure has left the device: an opt-out drops it.
533
+ if (optOut) synchronized(preConfigureBuffer) { preConfigureBuffer.clear() }
534
+ }
535
+
536
+ /** Test seam: events waiting for IngestClient, oldest first. */
537
+ @VisibleForTesting
538
+ internal fun _preConfigureBufferForTesting(): List<JSONObject> =
539
+ synchronized(preConfigureBuffer) { preConfigureBuffer.toList() }
540
+
541
+ /** Test seam: forget the pre-configure buffer (it is process-global). */
542
+ @VisibleForTesting
543
+ internal fun _resetPreConfigureBufferForTesting() {
544
+ synchronized(preConfigureBuffer) {
545
+ preConfigureBuffer.clear()
546
+ preConfigureOverflowLogged = false
547
+ }
548
+ }
549
+
550
+ /** Test seam: back to "the host never called [initialize]" (it is process-global). */
551
+ @VisibleForTesting
552
+ internal fun _resetInitializationForTesting() {
553
+ flushFuture?.cancel(false)
554
+ flushFuture = null
555
+ config = null
556
+ appContext = null
492
557
  }
493
558
 
494
559
  // MARK: Private
@@ -1,24 +1,22 @@
1
1
  // packages/swiss-knife-android/src/main/java/com/appswissknife/attributes/AttributesClient.kt
2
2
  //
3
- // Phase 3 of the RC rip-and-replace — user attributes now flow to our own
4
- // `/api/sdk/users/attributes` endpoint instead of RevenueCat's attribution
5
- // service. Mirrors the iOS `AttributesClient`: the entry-point setters on
3
+ // User attributes go to `POST /api/sdk/users/attributes`. Mirrors the iOS
4
+ // `AttributesClient`: the entry-point setters on
6
5
  // [com.appswissknife.SwissKnife] (`setEmail`, `setPhoneNumber`,
7
6
  // `setDisplayName`, `setPushToken`, `setAttributes`) delegate here.
8
7
  //
9
- // Why a separate file from FlushEventsWorker?
8
+ // Why not the telemetry pipeline?
9
+ // - Analytics events, errors and performance data all go through ONE
10
+ // pipeline: IngestClient's durable queue, drained in batches to
11
+ // `POST /ingest` (swiss-ingest). Attributes are a different endpoint on
12
+ // the web app with an incompatible payload.
10
13
  // - Attributes are infrequent (a handful per session), unlike analytics
11
- // events (one per user action). Coalescing all attribute writes into the
12
- // analytics flush would couple attribute latency to the threshold-driven
13
- // event flush cadence — the dashboard would not see a freshly-set email
14
- // until the user did 30 things.
15
- // - Endpoint is different (`/users/attributes` vs `/events/batch`) and the
16
- // payload shape is incompatible. Sharing a worker would mean branching
17
- // inside doWork(), which is exactly the thing the per-worker pattern
18
- // avoids.
19
- // - WorkManager's unique-work-name policy is per-name; using separate
20
- // workers gives each pipeline its own retry chain. A burst of setEmail
21
- // calls won't block the analytics flush, and vice versa.
14
+ // events (one per user action). Riding the batched telemetry drain would
15
+ // couple attribute latency to its flush cadence, so the dashboard would
16
+ // not see a freshly-set email until the next drain.
17
+ // - Each write is its own WorkManager job with its own retry chain, so a
18
+ // burst of setEmail calls never waits on the telemetry drain, and the
19
+ // drain never waits on them.
22
20
  //
23
21
  // Delivery guarantee
24
22
  // ------------------
@@ -30,9 +28,9 @@
30
28
  // uniqueWorkName suffixed with the run id, so concurrent setEmail +
31
29
  // setPhoneNumber both make it through without one overwriting the other.
32
30
  // - Retry policy is BackoffPolicy.EXPONENTIAL (1/2/4/8/16s) capped at 5
33
- // attempts via [SetAttributesWorker.MAX_ATTEMPTS] — same shape as the
34
- // analytics flush. Once the cap is hit, the worker returns success with
35
- // `dead_lettered=true` in its output and the payload is dropped.
31
+ // attempts via [SetAttributesWorker.MAX_ATTEMPTS]. Once the cap is hit,
32
+ // the worker returns success with `dead_lettered=true` in its output and
33
+ // the payload is dropped.
36
34
 
37
35
  package com.appswissknife.attributes
38
36
 
@@ -1,21 +1,22 @@
1
1
  // packages/swiss-knife-android/src/main/java/com/appswissknife/attributes/SetAttributesWorker.kt
2
2
  //
3
- // CoroutineWorker that POSTs a single user-attributes payload to our backend.
4
- // Parallel in shape to [com.appswissknife.analytics.FlushEventsWorker]:
5
- // - Same exponential-back-off policy (BackoffPolicy.EXPONENTIAL, 1s base).
6
- // - Same 5-attempt cap via runAttemptCount (0-indexed; DLQ on the 5th).
7
- // - Same error-class semantics:
3
+ // CoroutineWorker that POSTs a single user-attributes payload to
4
+ // `/api/sdk/users/attributes`. Telemetry (analytics, errors, performance)
5
+ // does not come through here: it goes through IngestClient's durable queue
6
+ // to `POST /ingest`, see net/IngestClient.kt. This worker's policy:
7
+ // - Exponential back-off (BackoffPolicy.EXPONENTIAL, 1s base, set by
8
+ // AttributesClient when it enqueues the work).
9
+ // - A 5-attempt cap via runAttemptCount (0-indexed; DLQ on the 5th).
10
+ // - Error classes:
8
11
  // 2xx → success
9
12
  // 4xx (not 429) → dead-letter immediately, no retry
10
13
  // 429 → retry, surface Retry-After in output
11
14
  // 5xx / IOException → retry until cap, then DLQ
12
- //
13
- // Differences vs FlushEventsWorker:
14
- // - The payload IS the input Data — no disk queue. Attributes are
15
- // infrequent (a handful per session) so WM's own SQLite-backed queue is
16
- // enough persistence. We don't need an EventQueueStore equivalent.
15
+ // - The payload IS the input Data, so there is no disk queue. Attributes
16
+ // are infrequent (a handful per session), so WorkManager's own
17
+ // SQLite-backed queue is enough persistence.
17
18
  // - Dead-letter means "drop the payload + log a warning". There is no
18
- // separate DLQ file (same policy as FlushEventsWorker).
19
+ // separate DLQ file.
19
20
 
20
21
  package com.appswissknife.attributes
21
22
 
@@ -47,8 +48,7 @@ internal class SetAttributesWorker(
47
48
  const val KEY_SERVER_URL = "server_url"
48
49
  const val KEY_BODY = "body"
49
50
 
50
- // Output keys mirror FlushEventsWorker so external observers can
51
- // process both pipelines uniformly.
51
+ // Output keys read by an observer of the work (tests, WorkInfo).
52
52
  const val OUTPUT_HTTP_STATUS = "http_status"
53
53
  const val OUTPUT_RETRY_AFTER_SECONDS = "retry_after_seconds"
54
54
  const val OUTPUT_DEAD_LETTERED = "dead_lettered"
@@ -16,15 +16,15 @@
16
16
  // "Advertising ID" being readable) is governed by Play Services
17
17
  // consent and the user's device settings, NOT a runtime prompt
18
18
  // the SDK initiates.
19
- // - **AdvertisingIdClient + InstallReferrerClient are pluggable
20
- // seams.** This keeps the Wave 2 commit transitive-dependency
21
- // free (no `play-services-ads-identifier` / `installreferrer`
22
- // hard requirements; hosts that ship those libraries inject a
23
- // real implementation via `Attribution.setCollectorsForTesting`
24
- // in tests, and a production wire-up via `setProductionCollectors`).
25
- // Apps that DO have the libs can call `registerInstall(...)`
26
- // directly with whatever IDs they collected — same shape as iOS's
27
- // manual path.
19
+ // - **The advertising id and install referrer are host-supplied.** The
20
+ // SDK ships no collector and adds no `play-services-ads-identifier` /
21
+ // `installreferrer` dependency, so out of the box an Android install
22
+ // carries neither and resolves as fingerprint or organic. A host that
23
+ // ships those libraries (and has the user's consent for the advertising
24
+ // id) passes its own [AdvertisingIdCollector] / [InstallReferrerCollector]
25
+ // to [Attribution.setCollectors] before `SwissKnife.configure`, or calls
26
+ // `registerInstall(...)` itself with whatever it collected — the same
27
+ // shape as iOS's manual path.
28
28
  // - **Persistence via EncryptedSharedPreferences** (already used by
29
29
  // DeviceID and AttributesClient — reusing the same prefs file
30
30
  // keeps the threat model coherent). Key `attribution_resolved`
@@ -65,9 +65,15 @@ object Attribution {
65
65
  * and calling `registerInstall(...)` explicitly.
66
66
  */
67
67
  val autoPromptATT: Boolean = true,
68
- /** Pull advertising_id via the injected collector. */
68
+ /**
69
+ * Ask the host's [AdvertisingIdCollector] (see [setCollectors]) for
70
+ * advertising_id. Without a host collector nothing is collected.
71
+ */
69
72
  val collectAdvertisingId: Boolean = true,
70
- /** Pull install_referrer via the injected collector. */
73
+ /**
74
+ * Ask the host's [InstallReferrerCollector] (see [setCollectors]) for
75
+ * install_referrer. Without a host collector nothing is collected.
76
+ */
71
77
  val collectInstallReferrer: Boolean = true,
72
78
  /** Run the install POST automatically on first launch. */
73
79
  val sendInstallOnFirstLaunch: Boolean = true,
@@ -98,18 +104,16 @@ object Attribution {
98
104
  internal var httpClient: BillingHttpClient = BackendHttpClientAdapter()
99
105
 
100
106
  /**
101
- * AdvertisingId collector. The production wire-up uses
102
- * `AdvertisingIdClient` from `play-services-ads-identifier`, but
103
- * this Wave-2 commit ships with a no-op default so the SDK does
104
- * not impose a transitive on every consumer. Hosts that want the
105
- * collector enable it via `setProductionCollectors(...)` or supply
106
- * their own via the same setter.
107
+ * Advertising id source. No-op until the host supplies one through
108
+ * [setCollectors]: the SDK deliberately does not depend on
109
+ * `play-services-ads-identifier`, and reading the id needs the user's
110
+ * consent, which only the host can obtain.
107
111
  */
108
112
  @Volatile
109
113
  @VisibleForTesting
110
114
  internal var advertisingIdCollector: AdvertisingIdCollector = NoopAdvertisingIdCollector()
111
115
 
112
- /** Install referrer collector — same rationale as the IDFA one. */
116
+ /** Install referrer source. No-op until the host supplies one through [setCollectors]. */
113
117
  @Volatile
114
118
  @VisibleForTesting
115
119
  internal var installReferrerCollector: InstallReferrerCollector = NoopInstallReferrerCollector()
@@ -215,6 +219,29 @@ object Attribution {
215
219
 
216
220
  // ---- Public surface ----------------------------------------------------
217
221
 
222
+ /**
223
+ * Supply the sources [collectAndRegister] (and the first-launch install
224
+ * POST) reads the advertising id and install referrer from. The SDK ships
225
+ * none: wrap Google's `AdvertisingIdClient` (after the user's consent) and
226
+ * `InstallReferrerClient` in your app and pass them here. `null` collects
227
+ * nothing for that field. Replaces both collectors.
228
+ *
229
+ * Call before `SwissKnife.configure(...)`: the first-launch install POST
230
+ * captures the collectors when it is scheduled. A collector runs on the SDK's
231
+ * attribution thread, never the main thread, so it may block (for example
232
+ * on the referrer service connection); returning null or throwing just
233
+ * leaves that field out of the POST.
234
+ */
235
+ fun setCollectors(
236
+ advertisingId: AdvertisingIdCollector?,
237
+ installReferrer: InstallReferrerCollector?,
238
+ ) {
239
+ synchronized(lock) {
240
+ advertisingIdCollector = advertisingId ?: NoopAdvertisingIdCollector()
241
+ installReferrerCollector = installReferrer ?: NoopInstallReferrerCollector()
242
+ }
243
+ }
244
+
218
245
  /** Latest resolved attribution. Null if no install POST has succeeded. */
219
246
  fun resolved(): ResolvedAttribution? {
220
247
  loadFromDiskIfNeeded()
@@ -359,12 +386,14 @@ object Attribution {
359
386
  if (apiKey.isEmpty()) return null
360
387
  val identity = Identity.current()
361
388
  val anonymousId = identity.anonymousId
362
- // For an anonymous user, user_id falls back to the anonymous_id
363
- // since the backend's appUsers row keys off `externalUserId`.
364
- val userId = identity.userId ?: anonymousId
389
+ // user_id is sent only for a logged-in user, as on iOS
390
+ // (Attribution.swift postInstall). The server stores user_id as
391
+ // app_users.external_user_id, so the anonymous id must never go there;
392
+ // an anonymous install is keyed by anonymous_id alone.
393
+ val userId = identity.userId
365
394
 
366
395
  val bodyJson = JSONObject().apply {
367
- put("user_id", userId)
396
+ if (userId != null) put("user_id", userId)
368
397
  put("anonymous_id", anonymousId)
369
398
  if (advertisingId != null && advertisingId.isNotEmpty()) {
370
399
  put("advertising_id", advertisingId)
@@ -579,8 +608,9 @@ object Attribution {
579
608
  private const val KEY_RESOLVED = "attribution_resolved"
580
609
  }
581
610
 
582
- /** Pluggable advertising_id source. Default impl returns null so the
583
- * SDK does not impose a GMS transitive on every consumer. */
611
+ /** Host-supplied advertising_id source, set with [Attribution.setCollectors].
612
+ * The SDK's default returns null so it does not impose a GMS dependency on
613
+ * every consumer. */
584
614
  interface AdvertisingIdCollector {
585
615
  fun get(context: Context): String?
586
616
  }
@@ -589,7 +619,8 @@ internal class NoopAdvertisingIdCollector : AdvertisingIdCollector {
589
619
  override fun get(context: Context): String? = null
590
620
  }
591
621
 
592
- /** Pluggable install_referrer source. Default impl returns null. */
622
+ /** Host-supplied install_referrer source, set with [Attribution.setCollectors].
623
+ * The SDK's default returns null. */
593
624
  interface InstallReferrerCollector {
594
625
  fun get(context: Context): String?
595
626
  }
@@ -42,7 +42,7 @@ internal object DeviceContextProvider {
42
42
  * eventually inject this via `BuildConfig`, but for now keep it in
43
43
  * source so we don't have to thread build settings through every test.
44
44
  */
45
- const val SDK_VERSION: String = "0.3.2"
45
+ const val SDK_VERSION: String = "0.5.0"
46
46
 
47
47
  private val cacheLock = Any()
48
48