@app-swiss-knife/react-native-sdk 0.4.0 → 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 +385 -2
  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 +365 -206
  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 +56 -31
  24. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +673 -87
  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 +345 -44
  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 +27 -6
  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 +27 -6
  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 +2 -0
  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 +18 -5
  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 +2 -0
  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 +18 -5
  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 +12 -4
  162. package/src/attribution.ts +4 -3
  163. package/src/identity.ts +12 -11
  164. package/src/index.ts +16 -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 +50 -9
  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
@@ -23,8 +23,33 @@
23
23
  // ≤100-item batches → POST /ingest via BackendHttpClient.
24
24
  // - Identity / Session / DeviceContext / Clock are stamped at flush time
25
25
  // (late-bind to mirror RevenueCat's identify semantics).
26
- // - 4xx → dead-letter (validation reject is not retriable).
27
- // 429 / 5xx / network → the batch STAYS QUEUED and a client-wide
26
+ // - A batch the server refuses whole with a 4xx (anything but 429) is
27
+ // sorted by what the status says, the same policy as the iOS client
28
+ // (IngestClient.swift flush()):
29
+ // 401/403 the KEY was refused, not the payload. Keep the batch and hold
30
+ // the queue for the longest window (no background retry is
31
+ // booked for it; see IngestFlushWorker).
32
+ // 408/425 timed out or came too early. Keep the batch, back off like a
33
+ // 5xx.
34
+ // any other, on several items halve the batch and retry within the same
35
+ // drain, so one bad item cannot hold back the rest. A 413 also
36
+ // makes the size that worked the drain's ceiling. The status may
37
+ // describe the server rather than the items (a misrouted proxy
38
+ // answering 404), so no batch is ever dead-lettered whole.
39
+ // any other, on one item dead-letter it, but ONLY on fresh evidence: the
40
+ // server accepted a batch since the last item it retired or set
41
+ // aside. Otherwise it is SET ASIDE: kept, skipped so the items
42
+ // behind it go out, and offered again once the server accepts
43
+ // something. The set-aside ids and the hold a refusing drain
44
+ // arms are kept in `set-aside.json` beside the queue, so a
45
+ // relaunch starts past them and does not re-send to a server
46
+ // that is refusing the queue.
47
+ // A drain stops after MAX_REJECTED_ATTEMPTS_PER_DRAIN such answers. When
48
+ // the server accepted nothing before that, the hold books no background
49
+ // drain at its end (see IngestFlushWorker).
50
+ // All of this used to dead-letter the whole batch, so one bad event (or a
51
+ // proxy 404) lost up to a hundred good ones.
52
+ // - 429 / 5xx / network → the batch STAYS QUEUED and a client-wide
28
53
  // "do not send before" window is armed: the server's Retry-After when it
29
54
  // sent one, else an exponential backoff. The worker books a delayed
30
55
  // flush for the end of that window. Nothing is dropped or dead-lettered
@@ -216,7 +241,7 @@ internal object IngestPlaceholderDevice {
216
241
  appBuild = "unknown",
217
242
  locale = Locale.getDefault().toString(),
218
243
  timezone = TimeZone.getDefault().id,
219
- sdkVersion = "0.4.0",
244
+ sdkVersion = "0.5.0",
220
245
  bundleIdentifier = null,
221
246
  )
222
247
  }
@@ -274,6 +299,79 @@ internal class UndecodableIngestResponse(
274
299
  val preview: String,
275
300
  ) : IOException("undecodable success response ($byteCount bytes): $preview")
276
301
 
302
+ /** What [IngestClient.flushSync] does with a batch the server rejected whole. */
303
+ private enum class RejectedBatchAction {
304
+ /** The key was refused (401/403): keep the items, hold the queue. */
305
+ HoldForKey,
306
+ /** Timed out or too early (408/425): keep the items, back off. */
307
+ RetryLater,
308
+ /** Any other status on several items: halve the batch and search for the item at fault. */
309
+ Split,
310
+ /** Any other status on one item: retire it on fresh evidence, else set it aside. */
311
+ Retire,
312
+ }
313
+
314
+ /**
315
+ * Bisection over one list of items, cut from its head: the size of the next
316
+ * batch, and the batch the search last halved (its size and status) with how
317
+ * many items the server has accepted since. Batches are cut from the head, so
318
+ * once that many are accepted, every item of it went through and none of them
319
+ * explained the rejection. Mirror of iOS `BatchSearch`.
320
+ */
321
+ private class BatchSearch(var limit: Int) {
322
+ private var halvedCount = 0
323
+ private var halvedStatus = 0
324
+ private var acceptedSinceHalving = 0
325
+
326
+ /** Looking for the item a rejected batch was refused for. */
327
+ val inProgress: Boolean get() = halvedCount > 0
328
+
329
+ /** A batch of [count] (> 1) items was refused with [status]: halve it. */
330
+ fun split(count: Int, status: Int) {
331
+ halvedCount = count
332
+ halvedStatus = status
333
+ acceptedSinceHalving = 0
334
+ limit = maxOf(1, count / 2)
335
+ }
336
+
337
+ /** The search is over (it retired or set aside a batch, or its list ran out). */
338
+ fun settle(next: Int) {
339
+ halvedCount = 0
340
+ halvedStatus = 0
341
+ acceptedSinceHalving = 0
342
+ limit = next
343
+ }
344
+
345
+ /**
346
+ * The server accepted [count] items cut from this list. Returns the
347
+ * drain's ceiling, which only a finished 413 search lowers.
348
+ */
349
+ fun accepted(count: Int, ceiling: Int): Int {
350
+ if (!inProgress) {
351
+ // Outside a search the size is below the ceiling only after a
352
+ // batch was set aside or retired one at a time. An acceptance is
353
+ // the answer that size was waiting for.
354
+ limit = ceiling
355
+ return ceiling
356
+ }
357
+ acceptedSinceHalving += count
358
+ if (acceptedSinceHalving < halvedCount) return ceiling
359
+ // Every item of the batch last halved has now been accepted in smaller
360
+ // ones. A 413 was about the size: the size that worked becomes the
361
+ // drain's ceiling. Anything else was the server changing its answer (a
362
+ // deploy finishing), so the drain goes back to full-size batches.
363
+ val next = if (halvedStatus == 413) limit else ceiling
364
+ settle(next)
365
+ return next
366
+ }
367
+ }
368
+
369
+ /** The set-aside ids and the end of the hold (epoch ms), as `set-aside.json` holds them. */
370
+ private data class SetAsideState(val ids: Set<String>, val holdUntilMs: Long?)
371
+
372
+ /** `set-aside.json` as read: the ids as listed (duplicates included) and the hold. */
373
+ private class SetAsideFile(val ids: List<String>, val holdUntilMs: Long?)
374
+
277
375
  /**
278
376
  * Unified client for `POST /ingest`. Process-wide singleton wired by
279
377
  * SwissKnife.configure (Commit 3); tests construct their own.
@@ -318,6 +416,55 @@ internal class IngestClient(
318
416
  /** Unique WorkManager name for the delayed (post-backoff) flush. */
319
417
  const val DELAYED_FLUSH_WORK_NAME = "swissknife.ingest_flush_delayed"
320
418
 
419
+ /**
420
+ * How many whole-batch 4xx answers one drain may collect before it
421
+ * stops and lets the backoff window space the next one. Bisecting a
422
+ * batch of 100 down to one bad item costs at most 7 rejected
423
+ * requests, so 16 isolates two bad items per drain. Without a bound a
424
+ * server rejecting EVERY request would turn bisection into a hot
425
+ * loop. Matches the iOS client's `maxRejectedAttemptsPerDrain`.
426
+ */
427
+ const val MAX_REJECTED_ATTEMPTS_PER_DRAIN = 16
428
+
429
+ /**
430
+ * The pause after a drain that hit [MAX_REJECTED_ATTEMPTS_PER_DRAIN],
431
+ * or left set-aside items waiting for evidence, while the server WAS
432
+ * accepting other batches. Pinned: the accepted batches earlier in the
433
+ * drain reset the backoff escalation, so an unpinned window would be
434
+ * the first one-second step and the next drain would spend its
435
+ * rejections straight away. A drain in which the server accepted
436
+ * nothing holds for [BACKOFF_MAX_MS] instead; when it spent its whole
437
+ * rejection budget so, the hold books no background drain at its end
438
+ * (see [retryAfterDrainMillis]).
439
+ */
440
+ const val REJECTED_DRAIN_COOLDOWN_MS = 60_000L
441
+
442
+ /**
443
+ * The sidecar, in the queue's directory, that keeps the set-aside ids
444
+ * and the hold a refusing drain armed across relaunches:
445
+ * `{"ids": [...], "holdUntilMs": <epoch ms, absent when none>}`.
446
+ */
447
+ const val SET_ASIDE_FILE_NAME = "set-aside.json"
448
+
449
+ /**
450
+ * The most ids `set-aside.json` is read back with: the default queue's
451
+ * item cap. The set only ever holds ids of items still queued (every
452
+ * drain prunes it against the queue), so nothing else bounds it and no
453
+ * item is turned away for room. This only guards the read of a
454
+ * corrupt file.
455
+ */
456
+ const val MAX_SET_ASIDE_ITEMS = OfflineQueueStoreDefaults.MAX_ITEMS
457
+
458
+ /** Well above the ~400 KB of ids a full default queue can set aside. */
459
+ private const val MAX_SET_ASIDE_FILE_BYTES = 2L * 1024L * 1024L
460
+
461
+ /**
462
+ * Slack on the bound a restored hold must fall within, so a hold
463
+ * written at exactly [BACKOFF_MAX_MS] is not refused for a
464
+ * millisecond of drift between the write and the next launch.
465
+ */
466
+ private const val RESTORED_HOLD_SLACK_MS = 1_000L
467
+
321
468
  /**
322
469
  * Process-wide instance — wired by SwissKnife.configure (Commit 3).
323
470
  * Tests construct their own. Direct read access is internal-only;
@@ -374,26 +521,72 @@ internal class IngestClient(
374
521
  @Volatile
375
522
  private var isReachable: Boolean = true
376
523
 
524
+ /**
525
+ * One drain at a time. The flush worker runs under two unique WorkManager
526
+ * names (the triggered flush and the delayed one), which can overlap; two
527
+ * drains reading the queue before either removes what it sent would
528
+ * upload the same rows twice and race the set-aside state below.
529
+ */
530
+ private val flushLock = Any()
531
+
377
532
  /**
378
533
  * Consecutive undecodable-success responses for the batch currently at
379
534
  * the head of the queue, and the identity of that batch. The budget is
380
- * per-batch, not a global "server has been flaky" tally. Only ever
381
- * touched from flushSync, which the worker serialises.
535
+ * per-batch, not a global "server has been flaky" tally. Guarded by
536
+ * [flushLock].
382
537
  */
383
538
  private var ambiguousAttempts: Int = 0
384
539
  private var ambiguousBatchIds: Set<String> = emptySet()
385
540
 
541
+ /**
542
+ * Items set aside without evidence: each was refused alone with no
543
+ * acceptance since the last such refusal, so it is either a bad item or
544
+ * met a broken server. Drains skip them, so the items behind them can
545
+ * show whether the server accepts batches, and offer them again once it
546
+ * has (see [flushSync]). Without this every drain would restart bisection
547
+ * at the same head and spend its rejection budget on the same bad items.
548
+ *
549
+ * Kept in [SET_ASIDE_FILE_NAME] beside the queue, read back on this
550
+ * instance's first drain and written at the end of every drain that
551
+ * changed it, so a relaunch starts past them too. Never larger than the
552
+ * queue (every drain prunes it). Written under [flushLock]; volatile so
553
+ * [retryAfterDrainMillis] can read it while another drain runs.
554
+ */
555
+ @Volatile
556
+ private var setAsideIds: Set<String> = emptySet()
557
+
558
+ /** Whether [setAsideIds] has been read back from disk yet. Guarded by [flushLock]. */
559
+ private var setAsideRestored = false
560
+
561
+ /**
562
+ * What [SET_ASIDE_FILE_NAME] holds, so a drain that changed nothing does
563
+ * not rewrite it. `null` when unknown (an unreadable or corrupt file, a
564
+ * failed write), which forces the next save. Guarded by [flushLock].
565
+ */
566
+ private var savedSetAside: SetAsideState? = null
567
+
386
568
  /**
387
569
  * Client-wide backoff window: no drain sends before [backoffUntilMs].
388
- * Armed by a 429 / 5xx / network failure, cleared by the first accepted
389
- * batch. [consecutiveFailures] drives the exponential step when the
390
- * server gave no Retry-After.
570
+ * Armed by a 429 / 5xx / network failure, a 408/425, a refused key, or
571
+ * the hold after a drain that collected whole-batch rejections; cleared by
572
+ * the first accepted batch. [consecutiveFailures] drives the exponential
573
+ * step when the server gave no Retry-After.
391
574
  */
392
575
  @Volatile
393
576
  private var backoffUntilMs: Long = 0L
394
577
  @Volatile
395
578
  private var consecutiveFailures: Int = 0
396
579
 
580
+ /**
581
+ * Whether the current window books no background drain at its end (see
582
+ * [retryAfterDrainMillis]): it was armed for a refused key (401/403), or
583
+ * as the hold after a drain that spent its whole rejection budget without
584
+ * one acceptance. Cleared by an accepted batch; any other arming of the
585
+ * window replaces it.
586
+ */
587
+ @Volatile
588
+ private var quietHold: Boolean = false
589
+
397
590
  // -------- Public enqueue API --------
398
591
 
399
592
  /**
@@ -410,7 +603,15 @@ internal class IngestClient(
410
603
  return false
411
604
  }
412
605
  val count = runCatching { queue.count() }.getOrNull() ?: return true
413
- if (count >= batchSize) {
606
+ // Inside a backoff window the worker would only return early. A
607
+ // 429/5xx window, or the hold after a drain that ran into rejections,
608
+ // has its delayed flush booked when the worker last ran with items
609
+ // waiting behind it; a refused key, a drain that spent its rejection
610
+ // budget without one acceptance, or a hold that left only set-aside
611
+ // items has none. The next trigger (the analytics flush timer, an
612
+ // explicit flush, the first threshold crossing after the window)
613
+ // books or runs it, not a job per tracked event.
614
+ if (count >= batchSize && backoffRemainingMillis() == 0L) {
414
615
  scheduleFlush(context)
415
616
  }
416
617
  return true
@@ -459,101 +660,431 @@ internal class IngestClient(
459
660
  // -------- Synchronous flush (called by IngestFlushWorker) --------
460
661
 
461
662
  /**
462
- * Drain the queue in ≤batchSize batches. Returns aggregate result.
463
- * Items hit by `BackendRejected` (4xx) go to dead-letter. After the
464
- * retry budget for `BackendUnavailable` exhausts, the batch is
465
- * dead-lettered and removed.
663
+ * Drain the queue in batches of up to batchSize. Returns the aggregate
664
+ * result. A batch the server rejects whole with a 4xx is handled per
665
+ * [actionFor]: 401/403 and 408/425 keep the items and throw
666
+ * [BackendRejected]; any other status splits a batch of several items,
667
+ * and retires a lone item on fresh evidence or sets it aside, without
668
+ * throwing. 429 / 5xx / network keep the batch, arm the backoff window
669
+ * and throw [BackendUnavailable].
670
+ *
671
+ * Fresh evidence is an accepted batch since the last item that was
672
+ * retired or set aside. Each retirement retires one item and uses the
673
+ * evidence up, so the server must accept something between any two: a
674
+ * server that goes bad again right after one acceptance (a deploy
675
+ * flapping, one bad instance behind a balancer) can cost at most one item
676
+ * per acceptance, whatever status it answers, and a rejection seen before
677
+ * the server recovered is never judged by an acceptance after it. Without
678
+ * the evidence the item is set aside ([setAsideIds]): skipped, persisted,
679
+ * and offered again first once the server accepts a batch, in batches
680
+ * searched the same way as the rest of the queue.
466
681
  *
467
- * Reachability gating: if `isReachable` is false, returns
468
- * (0, []) without touching the queue.
682
+ * Every drain makes progress past bad items, in this process or the next:
683
+ * it sees an accepted batch, or sets aside at least the two items its
684
+ * rejection budget isolates (the set survives a relaunch), or, with
685
+ * nothing but set-aside items left, offers them once. What can wait is a
686
+ * set-aside item: with no new events to supply evidence it stays queued
687
+ * (kept, never dead-lettered) until the app sends more.
688
+ *
689
+ * Serialised on [flushLock]. Reachability and the backoff window
690
+ * short-circuit it to (0, []) without touching the network: not now, not
691
+ * never.
469
692
  */
470
693
  @Throws(IOException::class)
471
- fun flushSync(): IngestResult {
694
+ fun flushSync(): IngestResult = synchronized(flushLock) { drainLocked() }
695
+
696
+ @Throws(IOException::class)
697
+ private fun drainLocked(): IngestResult {
698
+ // First, so a hold armed before a relaunch closes the window below.
699
+ restoreSetAsideLocked()
472
700
  if (!isReachable) return IngestResult(queued = 0, errors = emptyList())
473
- // Inside a backoff window: not now, not never. The items stay on disk
474
- // and the delayed flush booked with the window comes back for them.
701
+ // Inside a backoff window: not now, not never. The items stay on disk;
702
+ // the delayed flush booked with the window, or the next trigger after
703
+ // a quiet one, comes back for them.
475
704
  if (backoffRemainingMillis() > 0L) return IngestResult(queued = 0, errors = emptyList())
476
705
  var totalQueued = 0
477
706
  val aggregateErrors = mutableListOf<IngestErrorEntry>()
478
- while (true) {
479
- val items = queue.readAll()
480
- if (items.isEmpty()) break
481
- val batch = items.take(batchSize)
482
- val envelope = buildEnvelope(batch)
483
- val resp = try {
484
- // One attempt per drain: the retry lives between drains (the
485
- // backoff window below), not inside one request — sleeping
486
- // through Retry-After in-call would hold the worker hostage.
487
- http.postRaw(path, envelope.toString(), maxRetries = 0)
488
- } catch (e: BackendRejected) {
489
- // Whole batch rejected → dead-letter all.
490
- queue.deadLetter(batch)
491
- queue.remove(batch.map { it.id }.toSet())
492
- throw e
493
- } catch (e: BackendUnavailable) {
494
- // 429 / 5xx / network: the server may answer differently in a
495
- // moment, so the batch stays queued (it used to be
496
- // dead-lettered here, which silently lost rate-limited crash
497
- // reports). Arm the window; the worker books the retry.
498
- armBackoff(e.retryAfterMillis)
499
- throw e
707
+ // The batch size this drain returns to once a search is over. Only a
708
+ // 413 lowers it (see BatchSearch.accepted).
709
+ var ceiling = batchSize
710
+ // One search per list: the queue without the set-aside items, and the
711
+ // set-aside items being offered again.
712
+ val main = BatchSearch(batchSize)
713
+ val reoffer = BatchSearch(batchSize)
714
+ var requests = 0
715
+ var rejectedAttempts = 0
716
+ var stoppedOnRejections = false
717
+ // Whether the server accepted a batch in THIS drain, and whether it
718
+ // has accepted one since the last batch retired or set aside: the
719
+ // evidence a retirement needs. Until there is some, a rejection may
720
+ // describe the server (a bad deploy answering 400 to everything, a
721
+ // misrouted proxy) rather than the items.
722
+ var serverAcceptedABatch = false
723
+ var freshEvidence = false
724
+ val setAside = HashSet(setAsideIds)
725
+ // The end of the hold this drain arms for rejections, if it arms one.
726
+ var holdUntilMs: Long? = null
727
+ try {
728
+ drain@ while (true) {
729
+ val queued = queue.readAll()
730
+ var rest = queued
731
+ var suspects = emptyList<IngestItem>()
732
+ if (setAside.isNotEmpty()) {
733
+ // Forget items the queue no longer holds (accepted, retired,
734
+ // or trimmed at its cap): what keeps the set no larger than
735
+ // the queue.
736
+ setAside.retainAll(queued.mapTo(HashSet()) { it.id })
737
+ suspects = queued.filter { it.id in setAside }
738
+ rest = queued.filter { it.id !in setAside }
739
+ }
740
+ if (rest.isEmpty()) main.settle(ceiling)
741
+ if (suspects.isEmpty()) reoffer.settle(ceiling)
742
+
743
+ // Which list the next batch is cut from. A search runs to its
744
+ // end on its own list. Set-aside items go first on fresh
745
+ // evidence; with nothing else queued they are offered once, as
746
+ // the drain's first request (`probing`): the only way to see
747
+ // that the server has recovered when nothing new is enqueued.
748
+ val fromSuspects: Boolean
749
+ var probing = false
750
+ when {
751
+ reoffer.inProgress -> fromSuspects = true
752
+ main.inProgress -> fromSuspects = false
753
+ suspects.isNotEmpty() && freshEvidence -> fromSuspects = true
754
+ rest.isNotEmpty() -> fromSuspects = false
755
+ suspects.isNotEmpty() && requests == 0 -> {
756
+ fromSuspects = true
757
+ probing = true
758
+ }
759
+ else -> break@drain
760
+ }
761
+ var size = minOf(if (fromSuspects) reoffer.limit else main.limit, ceiling)
762
+ val batch: List<IngestItem> = if (fromSuspects) {
763
+ suspects.take(size)
764
+ } else {
765
+ if (!main.inProgress && suspects.isNotEmpty() && (serverAcceptedABatch || rejectedAttempts == 0)) {
766
+ // Each set-aside item retired needs an acceptance before
767
+ // it. Keep back one item per retirement this drain can
768
+ // still afford, so the end of the queue can supply them;
769
+ // the rest still goes out at full size. Not while the
770
+ // drain has only rejections to show: smaller batches
771
+ // would only cost more.
772
+ val reserve = minOf(suspects.size, MAX_REJECTED_ATTEMPTS_PER_DRAIN - rejectedAttempts) - 1
773
+ if (reserve > 0) size = minOf(size, maxOf(1, rest.size - reserve))
774
+ }
775
+ rest.take(size)
776
+ }
777
+ val batchIds = batch.mapTo(HashSet()) { it.id }
778
+ // A short batch is the end of the queue; with nothing set aside
779
+ // to offer after it, the drain is done once it is answered.
780
+ val isTail = !fromSuspects && suspects.isEmpty() && batch.size < size
781
+ requests += 1
782
+ val resp = try {
783
+ // One attempt per request: the retry lives between drains
784
+ // (the backoff window), not inside one request — sleeping
785
+ // through Retry-After in-call would hold the worker hostage.
786
+ http.postRaw(path, buildEnvelope(batch).toString(), maxRetries = 0)
787
+ } catch (e: BackendRejected) {
788
+ rejectedAttempts += 1
789
+ val action = actionFor(e.code, batch.size)
790
+ when (action) {
791
+ RejectedBatchAction.HoldForKey -> {
792
+ // The key was refused (revoked, mistyped, a
793
+ // server-side auth blip): the items are fine. Keep
794
+ // them, and hold the queue for the longest window
795
+ // instead of re-sending on every trigger. Nothing
796
+ // books a background retry: the first foreground
797
+ // trigger after the window tries again.
798
+ armBackoff(BACKOFF_MAX_MS, quiet = true)
799
+ throw e
800
+ }
801
+ RejectedBatchAction.RetryLater -> {
802
+ // A proxy gave up on a slow upload (408) or the
803
+ // server asked for a replay later (425). Both are
804
+ // safe to retry: keep the batch, back off as for a
805
+ // 5xx; the worker books the retry.
806
+ armBackoff(null)
807
+ throw e
808
+ }
809
+ RejectedBatchAction.Split, RejectedBatchAction.Retire -> {
810
+ if (probing) {
811
+ // Only set-aside items were left, and nothing in
812
+ // this drain shows that the server accepts
813
+ // anything. Keep them and stop; the hold below
814
+ // spaces the next try.
815
+ break@drain
816
+ }
817
+ if (action == RejectedBatchAction.Split) {
818
+ (if (fromSuspects) reoffer else main).split(batch.size, e.code)
819
+ } else if (freshEvidence) {
820
+ // The server accepted a batch since the last
821
+ // item it refused alone: this one is at fault.
822
+ // The evidence is used up; the next retirement
823
+ // needs its own.
824
+ retire(batch, e)
825
+ setAside.removeAll(batchIds)
826
+ freshEvidence = false
827
+ // The rest of the queue goes back to full-size
828
+ // batches. Set-aside items tend to be bad
829
+ // together (a run at the head of the queue), so
830
+ // they go on one at a time.
831
+ if (fromSuspects) reoffer.settle(1) else main.settle(ceiling)
832
+ } else {
833
+ // No acceptance since the last refusal: set it
834
+ // aside, for this drain and the next ones. The
835
+ // next batch is one item too: the head of the
836
+ // queue may be a run of bad items, and isolating
837
+ // each costs one rejection that way, not seven.
838
+ setAside.addAll(batchIds)
839
+ (if (fromSuspects) reoffer else main).settle(1)
840
+ }
841
+ }
842
+ }
843
+ if (rejectedAttempts >= MAX_REJECTED_ATTEMPTS_PER_DRAIN) {
844
+ // Something rejects far more than one item in a
845
+ // hundred. Stop here; the hold below spaces the next
846
+ // drain, and the items still queued are untouched.
847
+ stoppedOnRejections = true
848
+ break@drain
849
+ }
850
+ continue@drain
851
+ } catch (e: BackendUnavailable) {
852
+ // 429 / 5xx / network: the server may answer differently in
853
+ // a moment, so the batch stays queued (it used to be
854
+ // dead-lettered here, which silently lost rate-limited crash
855
+ // reports). Arm the window; the worker books the retry.
856
+ armBackoff(e.retryAfterMillis)
857
+ throw e
858
+ }
859
+ val parsed = try {
860
+ parseResult(resp, batch.size)
861
+ } catch (e: UndecodableIngestResponse) {
862
+ // We do not know what the server did with this batch, so
863
+ // we must not delete it. Leave it queued; the worker's
864
+ // retry brings us back here.
865
+ //
866
+ // Retrying an ambiguous batch can duplicate rather than
867
+ // lose: `analytics` items dedupe server-side on
868
+ // `(app_project_id, event_id)`, but several other item
869
+ // types currently mint a fresh id on ingest and would land
870
+ // twice. That trade is taken deliberately — a duplicate is
871
+ // visible and reconcilable, a silently dropped crash report
872
+ // is not.
873
+ val attempts = noteAmbiguousResponse(batchIds)
874
+ if (attempts < MAX_AMBIGUOUS_ATTEMPTS) throw e
875
+ // Budget spent — retire the batch to the dead-letter file,
876
+ // the same terminal-but-recoverable destination a
877
+ // server-rejected item gets. Never a silent drop.
878
+ Log.w(
879
+ TAG,
880
+ "dead-lettering ${batch.size} item(s) after $attempts undecodable " +
881
+ "success responses; last body: ${e.byteCount} bytes: ${e.preview}",
882
+ )
883
+ queue.deadLetter(batch)
884
+ queue.remove(batchIds)
885
+ setAside.removeAll(batchIds)
886
+ clearAmbiguousStreak()
887
+ // Batch retired; keep draining whatever is behind it.
888
+ if (isTail) break@drain else continue@drain
889
+ }
890
+ // A parseable answer — the server is talking sense again.
891
+ clearAmbiguousStreak()
892
+ clearBackoff()
893
+ totalQueued += parsed.queued
894
+ aggregateErrors.addAll(parsed.errors)
895
+ val errorIdxs = parsed.errors.map { it.index }.toSet()
896
+ val deadLetterItems = batch.withIndex()
897
+ .filter { it.index in errorIdxs }
898
+ .map { it.value }
899
+ if (deadLetterItems.isNotEmpty()) {
900
+ queue.deadLetter(deadLetterItems)
901
+ }
902
+ queue.remove(batchIds)
903
+ serverAcceptedABatch = true
904
+ freshEvidence = true
905
+ if (fromSuspects) {
906
+ setAside.removeAll(batchIds)
907
+ ceiling = reoffer.accepted(batch.size, ceiling)
908
+ } else {
909
+ ceiling = main.accepted(batch.size, ceiling)
910
+ }
911
+ if (isTail) break@drain
500
912
  }
501
- val batchIds = batch.map { it.id }.toSet()
502
- val parsed = try {
503
- parseResult(resp, batch.size)
504
- } catch (e: UndecodableIngestResponse) {
505
- // We do not know what the server did with this batch, so we
506
- // must not delete it. Leave it queued; the worker's retry
507
- // brings us back here.
913
+
914
+ if (rejectedAttempts > 0 && (stoppedOnRejections || !serverAcceptedABatch || setAside.isNotEmpty())) {
915
+ // Pin the window either way: the escalation alone would be one
916
+ // second whenever an accepted batch earlier in this drain reset
917
+ // it. A drain in which the server accepted nothing holds as long
918
+ // as for a refused key; one that ran into several bad items, or
919
+ // left set-aside items waiting for evidence, pauses for
920
+ // REJECTED_DRAIN_COOLDOWN_MS. The hold is persisted, so a
921
+ // relaunch inside it does not re-send either.
508
922
  //
509
- // Retrying an ambiguous batch can duplicate rather than lose:
510
- // `analytics` items dedupe server-side on
511
- // `(app_project_id, event_id)`, but several other item types
512
- // currently mint a fresh id on ingest and would land twice.
513
- // That trade is taken deliberately — a duplicate is visible
514
- // and reconcilable, a silently dropped crash report is not.
515
- val attempts = noteAmbiguousResponse(batchIds)
516
- if (attempts < MAX_AMBIGUOUS_ATTEMPTS) throw e
517
- // Budget spent — retire the batch to the dead-letter file,
518
- // the same terminal-but-recoverable destination a
519
- // server-rejected item gets. Never a silent drop.
923
+ // A drain that spent its whole rejection budget without one
924
+ // acceptance books no background drain at its end: a server
925
+ // refusing everything (a misrouted proxy, a bad deploy) would
926
+ // otherwise wake the app every five minutes for a full budget
927
+ // of rejected requests until the whole queue was set aside. As
928
+ // for a refused key, the next trigger after the hold while the
929
+ // app runs tries again.
930
+ val hold = if (serverAcceptedABatch) REJECTED_DRAIN_COOLDOWN_MS else BACKOFF_MAX_MS
931
+ armBackoff(hold, quiet = stoppedOnRejections && !serverAcceptedABatch)
932
+ holdUntilMs = reopensAtMillis()
520
933
  Log.w(
521
934
  TAG,
522
- "dead-lettering ${batch.size} item(s) after $attempts undecodable " +
523
- "success responses; last body: ${e.byteCount} bytes: ${e.preview}",
935
+ "$rejectedAttempts request(s) rejected whole in this drain (server accepted a " +
936
+ "batch: $serverAcceptedABatch); ${setAside.size} item(s) set aside, next drain in ${hold / 1000}s",
524
937
  )
525
- queue.deadLetter(batch)
526
- queue.remove(batchIds)
527
- clearAmbiguousStreak()
528
- null
529
- }
530
- if (parsed == null) {
531
- // Batch retired above; keep draining whatever is behind it.
532
- if (batch.size < batchSize) break else continue
533
938
  }
534
- // A parseable answer — the server is talking sense again.
535
- clearAmbiguousStreak()
536
- clearBackoff()
537
- totalQueued += parsed.queued
538
- aggregateErrors.addAll(parsed.errors)
539
- val errorIdxs = parsed.errors.map { it.index }.toSet()
540
- val deadLetterItems = batch.withIndex()
541
- .filter { it.index in errorIdxs }
542
- .map { it.value }
543
- if (deadLetterItems.isNotEmpty()) {
544
- queue.deadLetter(deadLetterItems)
939
+ return IngestResult(queued = totalQueued, errors = aggregateErrors)
940
+ } finally {
941
+ saveSetAsideLocked(setAside, holdUntilMs)
942
+ }
943
+ }
944
+
945
+ /** What to do with a batch of [batchCount] items the server rejected whole with [status]. */
946
+ private fun actionFor(status: Int, batchCount: Int): RejectedBatchAction = when {
947
+ isKeyRejection(status) -> RejectedBatchAction.HoldForKey
948
+ status == 408 || status == 425 -> RejectedBatchAction.RetryLater
949
+ // Never a whole batch to the dead-letter file, whatever the status:
950
+ // one acceptance is evidence for one retirement, and a batch is
951
+ // retired one item at a time.
952
+ batchCount > 1 -> RejectedBatchAction.Split
953
+ else -> RejectedBatchAction.Retire
954
+ }
955
+
956
+ /**
957
+ * Retire what the server refused on its own (one item, see [actionFor]):
958
+ * dead-letter it, say so, and remove it from the live queue.
959
+ */
960
+ private fun retire(batch: List<IngestItem>, rejection: BackendRejected) {
961
+ queue.deadLetter(batch)
962
+ Log.w(
963
+ TAG,
964
+ "dead-lettered ${batch.size} item(s) the server rejected whole (${rejection.code}): " +
965
+ "${batch.joinToString(",") { it.type.wire }} | reason: ${rejection.serverMessage ?: ""}",
966
+ )
967
+ queue.remove(batch.mapTo(HashSet()) { it.id })
968
+ }
969
+
970
+ /**
971
+ * Read [SET_ASIDE_FILE_NAME] back, once per instance, before its first
972
+ * drain: the set-aside ids, and the hold a refusing drain armed before
973
+ * the process went away, which goes back on the window unless it ends
974
+ * further ahead than any hold this client arms (see [restoreHold]). A
975
+ * missing, unreadable or corrupt file is an empty set and no hold.
976
+ */
977
+ private fun restoreSetAsideLocked() {
978
+ if (setAsideRestored) return
979
+ setAsideRestored = true
980
+ var ids: Set<String> = emptySet()
981
+ var holdUntilMs: Long? = null
982
+ // What the file holds, when it is known to hold exactly that.
983
+ var saved: SetAsideState? = SetAsideState(emptySet(), null)
984
+ val text = try {
985
+ queue.readSidecar(SET_ASIDE_FILE_NAME, MAX_SET_ASIDE_FILE_BYTES)
986
+ } catch (e: IOException) {
987
+ Log.w(TAG, "unreadable $SET_ASIDE_FILE_NAME; starting with nothing set aside", e)
988
+ saved = null
989
+ null
990
+ }
991
+ if (text != null) {
992
+ val file = parseSetAsideFile(text)
993
+ if (file == null) {
994
+ Log.w(TAG, "corrupt $SET_ASIDE_FILE_NAME; starting with nothing set aside")
995
+ saved = null
996
+ } else {
997
+ ids = file.ids.asSequence().take(MAX_SET_ASIDE_ITEMS).toHashSet()
998
+ holdUntilMs = file.holdUntilMs
999
+ saved = if (ids.size == file.ids.size) SetAsideState(ids, holdUntilMs) else null
545
1000
  }
546
- queue.remove(batchIds)
547
- if (batch.size < batchSize) break
548
1001
  }
549
- return IngestResult(queued = totalQueued, errors = aggregateErrors)
1002
+ setAsideIds = ids
1003
+ savedSetAside = saved
1004
+ if (holdUntilMs != null) restoreHold(holdUntilMs)
550
1005
  }
551
1006
 
1007
+ /** The file's ids (as listed) and hold, or null when it is not a set-aside file. */
1008
+ private fun parseSetAsideFile(text: String): SetAsideFile? = runCatching {
1009
+ val obj = JSONObject(text)
1010
+ val array = obj.getJSONArray("ids")
1011
+ val ids = ArrayList<String>(array.length())
1012
+ for (i in 0 until array.length()) {
1013
+ ids.add(array.get(i) as? String ?: return null)
1014
+ }
1015
+ val hold = when (val raw = obj.opt("holdUntilMs")) {
1016
+ null, JSONObject.NULL -> null
1017
+ is Int -> raw.toLong()
1018
+ is Long -> raw
1019
+ is Number -> raw.toDouble().takeIf { it.isFinite() }?.toLong()
1020
+ else -> return null
1021
+ }
1022
+ SetAsideFile(ids, hold)
1023
+ }.getOrNull()
1024
+
1025
+ /**
1026
+ * Keep what a drain ends with, and write [SET_ASIDE_FILE_NAME] if that
1027
+ * changed it: the ids, and [holdUntilMs] when the drain armed a hold for
1028
+ * rejections. The file is deleted once there is nothing to keep.
1029
+ */
1030
+ private fun saveSetAsideLocked(ids: Set<String>, holdUntilMs: Long?) {
1031
+ val kept = ids.toHashSet()
1032
+ setAsideIds = kept
1033
+ val saved = savedSetAside
1034
+ if (saved != null && saved.ids == kept && saved.holdUntilMs == holdUntilMs) return
1035
+ val written = if (kept.isEmpty() && holdUntilMs == null) {
1036
+ queue.writeSidecar(SET_ASIDE_FILE_NAME, null)
1037
+ } else {
1038
+ val json = JSONObject().put("ids", JSONArray(kept.sorted()))
1039
+ if (holdUntilMs != null) json.put("holdUntilMs", holdUntilMs)
1040
+ queue.writeSidecar(SET_ASIDE_FILE_NAME, json.toString())
1041
+ }
1042
+ // A failed write leaves the file unknown: the next drain writes again.
1043
+ savedSetAside = if (written) SetAsideState(kept, holdUntilMs) else null
1044
+ }
1045
+
1046
+ /**
1047
+ * How long [IngestFlushWorker] should wait before it drains again, after
1048
+ * a drain that returned normally: what is left of the backoff window when
1049
+ * that window holds back items that are not set aside, else 0: the hold
1050
+ * after a drain that ran into rejections, one an earlier process
1051
+ * persisted, or a 429/5xx/408/425 window a trigger found open.
1052
+ *
1053
+ * A quiet window ([quietHold]) books nothing: a refused key, or the hold
1054
+ * after a drain that spent its whole rejection budget without one
1055
+ * acceptance. The next trigger after it while the app runs (the analytics
1056
+ * flush timer, an explicit flush, the next launch) tries again, so a
1057
+ * server refusing every batch does not wake the process in the
1058
+ * background for a drain of rejections every five minutes. A relaunch
1059
+ * inside a persisted hold books its end once; if the server is still
1060
+ * refusing everything, that drain's hold is quiet. Set-aside items wait
1061
+ * for the evidence the app's next events bring, so they book nothing
1062
+ * either.
1063
+ */
1064
+ fun retryAfterDrainMillis(): Long {
1065
+ if (quietHold) return 0L
1066
+ val remaining = backoffRemainingMillis()
1067
+ if (remaining == 0L) return 0L
1068
+ val queued = runCatching { queue.count() }.getOrDefault(0)
1069
+ return if (queued > setAsideIds.size) remaining else 0L
1070
+ }
1071
+
1072
+ /** Set-aside items, read back from disk first if no drain has. */
1073
+ @VisibleForTesting
1074
+ internal fun setAsideCountForTesting(): Int = synchronized(flushLock) {
1075
+ restoreSetAsideLocked()
1076
+ setAsideIds.size
1077
+ }
1078
+
1079
+ /** 401/403: the server refused the API key, not the batch. */
1080
+ internal fun isKeyRejection(code: Int): Boolean = code == 401 || code == 403
1081
+
552
1082
  /** Milliseconds left in the backoff window; 0 when sends may go out. */
553
1083
  fun backoffRemainingMillis(): Long =
554
1084
  (backoffUntilMs - nowMillis()).coerceAtLeast(0L)
555
1085
 
556
- private fun armBackoff(retryAfterMillis: Long?) {
1086
+ /** [quiet]: the window books no background drain at its end (see [quietHold]). */
1087
+ private fun armBackoff(retryAfterMillis: Long?, quiet: Boolean = false) {
557
1088
  val step = BACKOFF_INITIAL_MS shl consecutiveFailures.coerceAtMost(20)
558
1089
  consecutiveFailures += 1
559
1090
  val scheduled = step.coerceAtMost(BACKOFF_MAX_MS)
@@ -561,11 +1092,36 @@ internal class IngestClient(
561
1092
  val wait = maxOf(scheduled, honoured ?: 0L)
562
1093
  // The window only ever moves forward.
563
1094
  backoffUntilMs = maxOf(backoffUntilMs, nowMillis() + wait)
1095
+ quietHold = quiet
564
1096
  }
565
1097
 
566
1098
  private fun clearBackoff() {
567
1099
  consecutiveFailures = 0
568
1100
  backoffUntilMs = 0L
1101
+ quietHold = false
1102
+ }
1103
+
1104
+ /** When the backoff window ends, or null while it is open. */
1105
+ private fun reopensAtMillis(): Long? = if (backoffRemainingMillis() > 0L) backoffUntilMs else null
1106
+
1107
+ /**
1108
+ * Keep the window closed until [untilMs], a hold an earlier process armed.
1109
+ * It only ever extends the window and leaves the escalation alone: this
1110
+ * restores a window, it is not a new failure.
1111
+ *
1112
+ * A hold ending more than [BACKOFF_MAX_MS] from now is ignored. No hold
1113
+ * this client arms is longer, so the wall clock has moved back since it
1114
+ * was written (the user setting the time back, an NTP correction), or the
1115
+ * value was never a hold. Clamping it to five minutes from each launch
1116
+ * instead would stall a device with short sessions until the wall clock
1117
+ * caught up, since a drain the window holds off writes nothing back.
1118
+ * Ignored, it costs one drain: if the server is still refusing, that drain
1119
+ * arms a hold of its own. Mirror of iOS `BackendBackoffGate.restoreWindow`.
1120
+ */
1121
+ private fun restoreHold(untilMs: Long) {
1122
+ val left = untilMs - nowMillis()
1123
+ if (left <= 0L || left > BACKOFF_MAX_MS + RESTORED_HOLD_SLACK_MS) return
1124
+ backoffUntilMs = maxOf(backoffUntilMs, untilMs)
569
1125
  }
570
1126
 
571
1127
  /**
@@ -719,8 +1275,11 @@ internal class IngestClient(
719
1275
  * - Survives process death — system reschedules after a kill.
720
1276
  * - Network constraint is system-managed — waits for connectivity.
721
1277
  * - Backoff without an in-app retry loop burning wakelocks: a throttled
722
- * or failed drain books a delayed one-time request for the end of the
723
- * client's backoff window (which honours the server's Retry-After).
1278
+ * or failed drain, or one that ran into rejections and left items still
1279
+ * to send, books a delayed one-time request for the end of the client's
1280
+ * backoff window (which honours the server's Retry-After). A refused key,
1281
+ * and a drain that spent its rejection budget without one acceptance,
1282
+ * book none: the next trigger while the app runs retries them.
724
1283
  * - Doze + App Standby aware out of the box.
725
1284
  */
726
1285
  internal class IngestFlushWorker(
@@ -742,10 +1301,37 @@ internal class IngestFlushWorker(
742
1301
  }
743
1302
  return try {
744
1303
  client.flushSync()
1304
+ // A drain that ran into rejections returns normally with a hold
1305
+ // armed, and so does one that finds a hold an earlier process
1306
+ // persisted. Come back at its end for the items that are not set
1307
+ // aside; nothing else would while the app sits idle. A hold after
1308
+ // a drain that spent its rejection budget without one acceptance
1309
+ // books nothing (see IngestClient.retryAfterDrainMillis).
1310
+ val delay = client.retryAfterDrainMillis()
1311
+ if (delay > 0L) {
1312
+ Log.w(TAG, "ingest drain held; continuing in ${delay}ms")
1313
+ client.scheduleDelayedFlush(applicationContext, delay)
1314
+ }
745
1315
  Result.success()
746
1316
  } catch (e: BackendRejected) {
747
- // 4xx → already dead-lettered by flushSync.
748
- Log.w(TAG, "ingest 4xx rejected: ${e.code}", e)
1317
+ if (client.isKeyRejection(e.code)) {
1318
+ // 401/403: flushSync kept the batch and armed the longest
1319
+ // backoff window. Deliberately NO delayed flush: a revoked
1320
+ // key never recovers on its own, and re-booking after every
1321
+ // 401 would wake the process in the background every five
1322
+ // minutes for as long as the install keeps that key. The
1323
+ // next trigger past the window while the app runs (an
1324
+ // enqueue crossing the batch size, the analytics flush timer
1325
+ // or an explicit flush, the next launch) tries again.
1326
+ Log.w(TAG, "ingest key rejected (${e.code}); keeping the queue until the next trigger", e)
1327
+ } else {
1328
+ // 408/425 (no other 4xx leaves flushSync: it splits, retires
1329
+ // or sets the batch aside). The batch is kept and the window
1330
+ // armed like a 5xx's; come back when it closes.
1331
+ val delay = client.backoffRemainingMillis()
1332
+ Log.w(TAG, "ingest ${e.code}; retrying in ${delay}ms", e)
1333
+ client.scheduleDelayedFlush(applicationContext, delay)
1334
+ }
749
1335
  Result.success()
750
1336
  } catch (e: BackendUnavailable) {
751
1337
  // 429 / 5xx / network. The batch is still queued and flushSync