@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
@@ -47,7 +47,36 @@
47
47
  // - Retries are owned HERE, not by `BackendHttpClient`: each drain makes
48
48
  // exactly ONE attempt per batch (`maxRetriesPerAttempt = 0`) and a
49
49
  // failure arms the client-wide `BackendBackoffGate`, which the next
50
- // drain consults before it sends. 4xx still dead-letters immediately.
50
+ // drain consults before it sends.
51
+ // - A whole-batch 4xx (anything but 429) is sorted by what it says:
52
+ // 401/403 the KEY was refused, not the payload. Keep the items, hold
53
+ // the queue with a long gate window, retry after it.
54
+ // 408/425 the request timed out or came too early. Keep the items and
55
+ // back off like a 5xx.
56
+ // any other, on a batch of several items halve the batch and retry
57
+ // within the same drain, so one oversized or invalid item cannot
58
+ // hold back the rest. That is a 413 (the size that worked then
59
+ // becomes the drain's ceiling) or a 400, but also a 404 or any
60
+ // other status, which may describe the server rather than the
61
+ // items (a misrouted proxy, one bad instance behind a balancer).
62
+ // The search ends on single items, and one is retired only as
63
+ // below, so no batch is dead-lettered whole. A 404 batch used to
64
+ // be, on fresh evidence: a hundred good items per acceptance on
65
+ // a server answering 404 now and then.
66
+ // any other, on one item retire it to the dead-letter file and keep
67
+ // draining, but ONLY on fresh evidence: the server accepted a
68
+ // batch since the last item it retired or set aside. Without
69
+ // that the rejection may describe the server (a bad deploy, a
70
+ // proxy, a drain that straddles a recovery, a deploy flapping)
71
+ // rather than the item, so it is SET ASIDE: kept, skipped until
72
+ // the server accepts something, then offered again. The
73
+ // set-aside ids and the hold the gate arms after such a drain
74
+ // are kept beside the queue in `set-aside.json`, so a relaunch
75
+ // starts past them and does not re-send to a server that is
76
+ // refusing the queue.
77
+ // It used to escape `flush()` with the batch still at the head of the
78
+ // queue, so every later trigger re-sent the same batch and all telemetry
79
+ // behind it stalled until the 10k cap evicted it.
51
80
  // Putting the wait between drains rather than inside one request is
52
81
  // what makes the backoff apply to the QUEUE instead of to a single
53
82
  // HTTP call — see `BackendBackoffGate` for why the difference is
@@ -453,6 +482,131 @@ internal final class IngestClient: @unchecked Sendable {
453
482
  /// anything is given up on.
454
483
  static let maxAmbiguousAttempts = 5
455
484
 
485
+ /// How many whole-batch 4xx answers one drain may collect before it
486
+ /// stops and lets the gate space the next one.
487
+ ///
488
+ /// Bisecting a batch of 100 down to one bad item costs at most 7
489
+ /// rejected requests, so 16 isolates two bad items per drain. Without a
490
+ /// bound, a server rejecting EVERY request would turn bisection into a
491
+ /// hot loop: roughly seven requests per queued item, back to back.
492
+ static let maxRejectedAttemptsPerDrain = 16
493
+
494
+ /// The most ids `set-aside.json` is read back with: the default queue's
495
+ /// item cap. Nothing else bounds the set, and nothing needs to: it holds
496
+ /// only ids of items still queued (every drain prunes it against the
497
+ /// queue), so it is never larger than the queue, about 400 KB of ids at
498
+ /// the 10k cap. No item is ever turned away for room; that is what let
499
+ /// more bad items in a row than an older, smaller bound (100) stall the
500
+ /// queue for good. This only guards the read of a corrupt file.
501
+ static let maxSetAsideItems = OfflineQueueStoreDefaults.maxItems
502
+
503
+ /// The sidecar, in the queue's directory, that keeps `setAsideIds` and
504
+ /// the hold a rejecting drain armed across relaunches.
505
+ static let setAsideFileName = "set-aside.json"
506
+
507
+ /// The pause after a drain that hit `maxRejectedAttemptsPerDrain`, or
508
+ /// left set-aside items waiting for evidence, while the server WAS
509
+ /// accepting other batches (a queue holding several bad items). Armed as
510
+ /// a fixed `retryAfter`: the accepted batches earlier in the same drain
511
+ /// reset the gate's escalation, so an unpinned window would be the first
512
+ /// one-second step and the next drain would spend its 16 rejections
513
+ /// straight away. A drain in which the server accepted nothing holds for
514
+ /// `BackendBackoffGate.maxHonouredRetryAfter` instead.
515
+ static let rejectedDrainCooldown: TimeInterval = 60
516
+
517
+ /// What to do with a batch the server rejected whole.
518
+ private enum RejectedBatchAction {
519
+ /// The key was refused (401/403): keep the items, hold the queue.
520
+ case holdForKey
521
+ /// Timed out or too early (408/425): keep the items, back off.
522
+ case retryLater
523
+ /// Any other status on several items: halve the batch and search for
524
+ /// the item at fault. There may be none: the status may describe the
525
+ /// server, not the items.
526
+ case split
527
+ /// Any other status on one item: retire it on fresh evidence that the
528
+ /// server accepts other batches, else set it aside.
529
+ case retire
530
+ }
531
+
532
+ /// Bisection over one list of items, cut from its head: the size of the
533
+ /// next batch, and the batch the search last halved (its size and
534
+ /// status) with how many items the server has accepted since. Batches are
535
+ /// cut from the head, so once that many are accepted, every item of it
536
+ /// went through and none of them explained the rejection.
537
+ private struct BatchSearch {
538
+ var limit: Int
539
+ private var halved: (count: Int, status: Int)?
540
+ private var acceptedSinceHalving = 0
541
+
542
+ init(limit: Int) { self.limit = limit }
543
+
544
+ /// Looking for the item a rejected batch was refused for.
545
+ var inProgress: Bool { halved != nil }
546
+
547
+ /// A batch of `count` items was refused with `status`: halve it.
548
+ mutating func split(_ count: Int, status: Int) {
549
+ halved = (count, status)
550
+ acceptedSinceHalving = 0
551
+ limit = max(1, count / 2)
552
+ }
553
+
554
+ /// The search is over (it retired or set aside a batch, or its list
555
+ /// ran out); go on with batches of `next`.
556
+ mutating func settle(next: Int) {
557
+ halved = nil
558
+ acceptedSinceHalving = 0
559
+ limit = next
560
+ }
561
+
562
+ /// The server accepted `count` items cut from this list.
563
+ mutating func accepted(_ count: Int, ceiling: inout Int) {
564
+ guard let search = halved else {
565
+ // Outside a search the size is below the ceiling only after a
566
+ // batch was set aside or retired one at a time (see `flush()`).
567
+ // An acceptance is the answer that size was waiting for.
568
+ limit = ceiling
569
+ return
570
+ }
571
+ acceptedSinceHalving += count
572
+ if acceptedSinceHalving >= search.count {
573
+ // Every item of the batch last halved has now been accepted in
574
+ // smaller ones, so none of them explained the rejection. A 413
575
+ // was about the size: the size that worked becomes this drain's
576
+ // ceiling. Anything else was the server changing its answer (a
577
+ // deploy finishing), so the drain goes back to full-size batches
578
+ // instead of finishing the queue one item per request.
579
+ if search.status == 413 { ceiling = limit }
580
+ limit = ceiling
581
+ halved = nil
582
+ }
583
+ }
584
+ }
585
+
586
+ /// `set-aside.json`: the set-aside ids, and when the hold a rejecting
587
+ /// drain armed ends (seconds since 1970), if it armed one.
588
+ private struct SetAsideFile: Codable {
589
+ var ids: [String]
590
+ var holdUntil: Double?
591
+ }
592
+
593
+ private static func action(forRejectedStatus status: Int, batchCount: Int) -> RejectedBatchAction {
594
+ switch status {
595
+ case 401, 403:
596
+ return .holdForKey
597
+ case 408, 425:
598
+ return .retryLater
599
+ default:
600
+ // Never a whole batch to the dead-letter file, whatever the
601
+ // status: one acceptance is evidence for one retirement, and a
602
+ // batch is retired one item at a time. A 404 or other status that
603
+ // was not split used to retire up to a hundred good items per
604
+ // acceptance on a server answering it now and then (one bad
605
+ // instance behind a balancer), while a 400 cost one.
606
+ return batchCount > 1 ? .split : .retire
607
+ }
608
+ }
609
+
456
610
  /// Whether the network is reachable. Updated by the Reachability
457
611
  /// observer; flush short-circuits to no-op when false.
458
612
  private var isReachable: Bool = true
@@ -466,6 +620,31 @@ internal final class IngestClient: @unchecked Sendable {
466
620
  private var ambiguousAttempts: Int = 0
467
621
  private var ambiguousBatchIds: Set<String> = []
468
622
 
623
+ /// Items set aside without evidence: each was refused alone with no
624
+ /// acceptance since the last such refusal, so it is either a bad item or
625
+ /// met a broken server.
626
+ /// Drains skip them, so the items behind them can show whether the server
627
+ /// accepts batches, and offer them again once it has (see `flush()`).
628
+ /// Without this, every drain restarted bisection at the same head and
629
+ /// spent its rejection budget on the same bad items: three of them before
630
+ /// the first good batch stalled the queue for good.
631
+ ///
632
+ /// Kept in `set-aside.json` beside the queue (in memory for an in-memory
633
+ /// queue), read back on an instance's first drain and written at the end
634
+ /// of every drain that changed it, so a relaunch starts past them too.
635
+ /// Guarded by `flushQueue`. Never larger than the queue: see
636
+ /// `maxSetAsideItems`.
637
+ private var setAsideIds: Set<String> = []
638
+
639
+ /// Whether `setAsideIds` has been read back from `set-aside.json` yet.
640
+ /// Guarded by `flushQueue`.
641
+ private var setAsideRestored = false
642
+
643
+ /// What `set-aside.json` holds, so a drain that changed nothing does not
644
+ /// rewrite it. `nil` when unknown (an unreadable file), which forces the
645
+ /// next save. Guarded by `flushQueue`.
646
+ private var savedSetAside: (ids: Set<String>, holdUntil: Date?)?
647
+
469
648
  init(
470
649
  queue: OfflineQueueStore<IngestItem>,
471
650
  http: BackendHttpClient = BackendHttpClient.shared,
@@ -511,7 +690,8 @@ internal final class IngestClient: @unchecked Sendable {
511
690
  do {
512
691
  try queue.append(item)
513
692
  // Check size and trigger an immediate flush if we crossed
514
- // the threshold. The size() call is cheap — file-stat only.
693
+ // the threshold. `count()` is O(1): the store keeps a cached
694
+ // count instead of re-reading the file.
515
695
  if let count = try? queue.count(), count >= batchSize {
516
696
  scheduleImmediateFlush()
517
697
  }
@@ -559,8 +739,37 @@ internal final class IngestClient: @unchecked Sendable {
559
739
  // MARK: - Flush
560
740
 
561
741
  /// Drain the queue in batches of up to `batchSize`. Returns the
562
- /// aggregated `IngestResult` across all batches. Items that hit a
563
- /// terminal `backendRejected` error are dead-lettered.
742
+ /// aggregated `IngestResult` across all batches. A batch rejected whole
743
+ /// with a 4xx is handled per `action(forRejectedStatus:batchCount:)`:
744
+ /// 401/403 and 408/425 keep the items and throw; any other status splits
745
+ /// a batch of several items, and retires a lone item on fresh evidence or
746
+ /// sets it aside.
747
+ ///
748
+ /// Fresh evidence is an accepted batch since the last item that was
749
+ /// retired or set aside. Each retirement retires one item and uses the
750
+ /// evidence up, so the server must accept something between any two: a
751
+ /// server that goes bad again right after one acceptance (a deploy
752
+ /// flapping, one bad instance behind a balancer) can cost at most one
753
+ /// item per acceptance, whatever status it answers, and a rejection seen
754
+ /// before the server recovered is never judged by an acceptance after it.
755
+ /// Without the evidence the item is set aside (`setAsideIds`): skipped,
756
+ /// persisted, and offered again first once the server accepts a batch, in
757
+ /// batches searched the same way as the rest of the queue.
758
+ ///
759
+ /// Every drain makes progress past bad items, in this process or the
760
+ /// next: it sees an accepted batch, or sets aside at least the two items
761
+ /// its rejection budget isolates (the set survives a relaunch), or, with
762
+ /// nothing but set-aside items left, offers them once. Good items behind
763
+ /// set-aside ones go out in the same drains, at full size but for the
764
+ /// last few, sent one at a time as the evidence retirements need.
765
+ ///
766
+ /// What can wait is a set-aside item. With no new events to supply
767
+ /// evidence, set-aside items stay queued, costing one request per drain
768
+ /// (they are offered once, as one batch), until the device sends more.
769
+ /// Most of them are bad items, but good items set aside during an outage
770
+ /// wait as well when that batch also carries a bad one: it is refused
771
+ /// whole, and they go out once a new event has brought the evidence that
772
+ /// retires the bad one. They are kept meanwhile, never dead-lettered.
564
773
  ///
565
774
  /// UNCOORDINATED PRIMITIVE — production code must never call this
566
775
  /// directly, only `flushBestEffort()`. The loop below reads the
@@ -584,6 +793,8 @@ internal final class IngestClient: @unchecked Sendable {
584
793
  /// what keeps an outage from leaving a long window behind it.
585
794
  @discardableResult
586
795
  func flush() async throws -> IngestResult {
796
+ // First, so a hold armed before a relaunch closes the gate below.
797
+ restoreSetAsideIfNeeded()
587
798
  let reachable = flushQueue.sync { isReachable }
588
799
  if !reachable {
589
800
  return IngestResult(queued: 0, errors: [])
@@ -593,15 +804,165 @@ internal final class IngestClient: @unchecked Sendable {
593
804
  }
594
805
  var aggregateQueued = 0
595
806
  var aggregateErrors: [IngestErrorEntry] = []
596
-
597
- while true {
598
- let items = try queue.readAll()
599
- if items.isEmpty { break }
600
- let batch = Array(items.prefix(batchSize))
807
+ // The batch size this drain returns to once a search is over. Only a
808
+ // 413 lowers it (see `BatchSearch.accepted`).
809
+ var ceiling = batchSize
810
+ // One search per list: the queue without the set-aside items, and the
811
+ // set-aside items being offered again.
812
+ var main = BatchSearch(limit: batchSize)
813
+ var reoffer = BatchSearch(limit: batchSize)
814
+ var requests = 0
815
+ var rejectedAttempts = 0
816
+ var stoppedOnRejections = false
817
+ // Whether the server accepted a batch in THIS drain, and whether it
818
+ // has accepted one since the last batch retired or set aside: the
819
+ // evidence a retirement needs (see above). Until there is some, a
820
+ // rejection may describe the server (a bad deploy answering 400 to
821
+ // everything, a misrouted proxy) rather than the items, and
822
+ // dead-lettering on it would throw good telemetry away for as long as
823
+ // the server is broken.
824
+ var serverAcceptedABatch = false
825
+ var freshEvidence = false
826
+ var setAside = flushQueue.sync { setAsideIds }
827
+ // The end of the hold this drain arms for rejections, if it arms one.
828
+ var holdUntil: Date?
829
+ defer { saveSetAside(setAside, holdUntil: holdUntil) }
830
+
831
+ drain: while true {
832
+ let queued = try queue.readAll()
833
+ var rest = queued
834
+ var suspects: [IngestItem] = []
835
+ if !setAside.isEmpty {
836
+ // Forget items the queue no longer holds (accepted, retired,
837
+ // or trimmed at its cap). This is what keeps the set no larger
838
+ // than the queue.
839
+ setAside.formIntersection(queued.map { $0.id })
840
+ suspects = queued.filter { setAside.contains($0.id) }
841
+ rest = queued.filter { !setAside.contains($0.id) }
842
+ }
843
+ if rest.isEmpty { main.settle(next: ceiling) }
844
+ if suspects.isEmpty { reoffer.settle(next: ceiling) }
845
+
846
+ // Which list the next batch is cut from. A search runs to its end
847
+ // on its own list. Set-aside items go first on fresh evidence; with
848
+ // nothing else queued they are offered once, as the drain's first
849
+ // request (`probing`): the only way to see that the server has
850
+ // recovered when nothing new is enqueued.
851
+ let fromSuspects: Bool
852
+ var probing = false
853
+ if reoffer.inProgress {
854
+ fromSuspects = true
855
+ } else if main.inProgress {
856
+ fromSuspects = false
857
+ } else if !suspects.isEmpty && freshEvidence {
858
+ fromSuspects = true
859
+ } else if !rest.isEmpty {
860
+ fromSuspects = false
861
+ } else if !suspects.isEmpty && requests == 0 {
862
+ fromSuspects = true
863
+ probing = true
864
+ } else {
865
+ break
866
+ }
867
+ var size = min(fromSuspects ? reoffer.limit : main.limit, ceiling)
868
+ let batch: [IngestItem]
869
+ if fromSuspects {
870
+ batch = Array(suspects.prefix(size))
871
+ } else {
872
+ if !main.inProgress && !suspects.isEmpty && (serverAcceptedABatch || rejectedAttempts == 0) {
873
+ // Each set-aside item retired needs an acceptance before it.
874
+ // Keep back one item per retirement this drain can still
875
+ // afford, so the end of the queue can supply them; the rest
876
+ // still goes out at full size. Not while the drain has only
877
+ // rejections to show: smaller batches would only cost more.
878
+ let reserve = min(suspects.count, Self.maxRejectedAttemptsPerDrain - rejectedAttempts) - 1
879
+ if reserve > 0 { size = min(size, max(1, rest.count - reserve)) }
880
+ }
881
+ batch = Array(rest.prefix(size))
882
+ }
601
883
  let batchIds = Set(batch.map { $0.id })
884
+ // A short batch is the end of the queue; with nothing set aside to
885
+ // offer after it, the drain is done once it is answered.
886
+ let isTail = !fromSuspects && suspects.isEmpty && batch.count < size
887
+ requests += 1
602
888
  let result: IngestResult
603
889
  do {
604
890
  result = try await sendBatch(batch)
891
+ } catch PurchasesError.backendRejected(let status, let message) {
892
+ rejectedAttempts += 1
893
+ let action = Self.action(forRejectedStatus: status, batchCount: batch.count)
894
+ switch action {
895
+ case .holdForKey:
896
+ // The items are fine; the key is not (revoked, mistyped,
897
+ // or a server-side auth blip). Keep everything and hold
898
+ // the whole queue for the longest window the gate honours,
899
+ // rather than re-sending on every trigger. `isRetryable`
900
+ // books the wake-up for the end of it.
901
+ backoffGate.noteRetryable(retryAfter: BackendBackoffGate.maxHonouredRetryAfter)
902
+ os_log(
903
+ "IngestClient: the server refused the API key (%d); keeping %d queued item(s) and retrying later",
904
+ log: log,
905
+ type: .error,
906
+ status,
907
+ queued.count
908
+ )
909
+ throw PurchasesError.backendRejected(statusCode: status, message: message)
910
+ case .retryLater:
911
+ // A proxy gave up on a slow upload (408) or the server
912
+ // asked for a replay later (425). Both are safe to retry:
913
+ // keep the batch and back off exactly as for a 5xx.
914
+ backoffGate.noteRetryable(retryAfter: nil)
915
+ throw PurchasesError.backendRejected(statusCode: status, message: message)
916
+ case .split, .retire:
917
+ if probing {
918
+ // Only set-aside items were left, and nothing in this
919
+ // drain shows that the server accepts anything. Keep
920
+ // them and stop; the hold below spaces the next try.
921
+ break drain
922
+ }
923
+ if action == .split {
924
+ if fromSuspects {
925
+ reoffer.split(batch.count, status: status)
926
+ } else {
927
+ main.split(batch.count, status: status)
928
+ }
929
+ } else if freshEvidence {
930
+ // The server accepted a batch since the last item it
931
+ // refused alone: this one is at fault. The evidence is
932
+ // used up; the next retirement needs its own.
933
+ try retire(batch, status: status, message: message)
934
+ setAside.subtract(batchIds)
935
+ freshEvidence = false
936
+ // The rest of the queue goes back to full-size batches.
937
+ // Set-aside items tend to be bad together (a run at the
938
+ // head of the queue), so they go on one at a time.
939
+ if fromSuspects {
940
+ reoffer.settle(next: 1)
941
+ } else {
942
+ main.settle(next: ceiling)
943
+ }
944
+ } else {
945
+ // No acceptance since the last refusal: set it aside,
946
+ // for this drain and the next ones. The next batch is
947
+ // one item too: the head of the queue may be a run of
948
+ // bad items, and isolating each costs one rejection
949
+ // that way instead of seven.
950
+ setAside.formUnion(batchIds)
951
+ if fromSuspects {
952
+ reoffer.settle(next: 1)
953
+ } else {
954
+ main.settle(next: 1)
955
+ }
956
+ }
957
+ }
958
+ if rejectedAttempts >= Self.maxRejectedAttemptsPerDrain {
959
+ // Something rejects far more than one item in a hundred.
960
+ // Stop here; the gate below spaces the next drain, and the
961
+ // items still queued are untouched.
962
+ stoppedOnRejections = true
963
+ break drain
964
+ }
965
+ continue
605
966
  } catch let ambiguous as UndecodableIngestResponse {
606
967
  // We do not know what the server did with this batch, so we
607
968
  // must not delete it. Leave it queued and let the next flush
@@ -635,8 +996,9 @@ internal final class IngestClient: @unchecked Sendable {
635
996
  ambiguous.preview
636
997
  )
637
998
  try queue.remove(ids: batchIds)
999
+ setAside.subtract(batchIds)
638
1000
  clearAmbiguousStreak()
639
- if batch.count < batchSize { break }
1001
+ if isTail { break }
640
1002
  continue
641
1003
  }
642
1004
  // A decodable answer — whatever it said, the server is talking
@@ -670,13 +1032,113 @@ internal final class IngestClient: @unchecked Sendable {
670
1032
  )
671
1033
  }
672
1034
  try queue.remove(ids: batchIds)
673
- // If the batch was the full size, there might be more — loop.
674
- if batch.count < batchSize { break }
1035
+ serverAcceptedABatch = true
1036
+ freshEvidence = true
1037
+ if fromSuspects {
1038
+ setAside.subtract(batchIds)
1039
+ reoffer.accepted(batch.count, ceiling: &ceiling)
1040
+ } else {
1041
+ main.accepted(batch.count, ceiling: &ceiling)
1042
+ }
1043
+ if isTail { break }
1044
+ }
1045
+
1046
+ if rejectedAttempts > 0 && (stoppedOnRejections || !serverAcceptedABatch || !setAside.isEmpty) {
1047
+ // Pin the window with `retryAfter` either way: the escalation
1048
+ // alone would be one second whenever an accepted batch earlier in
1049
+ // this drain reset it. A drain in which the server accepted
1050
+ // nothing holds as long as for a refused key; one that ran into
1051
+ // several bad items, or left set-aside items waiting for evidence,
1052
+ // pauses for `rejectedDrainCooldown`. The hold is persisted, so a
1053
+ // relaunch inside it does not re-send either.
1054
+ let hold = serverAcceptedABatch
1055
+ ? Self.rejectedDrainCooldown
1056
+ : BackendBackoffGate.maxHonouredRetryAfter
1057
+ backoffGate.noteRetryable(retryAfter: hold)
1058
+ holdUntil = backoffGate.reopensAt
1059
+ os_log(
1060
+ "IngestClient: %d request(s) rejected whole in this drain (server accepted a batch: %{public}@); %d item(s) set aside, next drain in %.0fs",
1061
+ log: log,
1062
+ type: .error,
1063
+ rejectedAttempts,
1064
+ serverAcceptedABatch ? "yes" : "no",
1065
+ setAside.count,
1066
+ hold
1067
+ )
675
1068
  }
676
1069
 
677
1070
  return IngestResult(queued: aggregateQueued, errors: aggregateErrors)
678
1071
  }
679
1072
 
1073
+ /// Retire what the server refused on its own (one item, see
1074
+ /// `action(forRejectedStatus:batchCount:)`): dead-letter it, say so, and
1075
+ /// remove it from the live queue.
1076
+ private func retire(_ batch: [IngestItem], status: Int, message: String?) throws {
1077
+ queue.deadLetter(batch)
1078
+ os_log(
1079
+ "IngestClient dead-lettered %d item(s) the server rejected whole (%d): %{public}@ | reason: %{public}@",
1080
+ log: log,
1081
+ type: .error,
1082
+ batch.count,
1083
+ status,
1084
+ batch.map { $0.type.rawValue }.joined(separator: ","),
1085
+ message ?? ""
1086
+ )
1087
+ try queue.remove(ids: Set(batch.map { $0.id }))
1088
+ }
1089
+
1090
+ /// Read `set-aside.json` back, once per instance, before its first drain:
1091
+ /// the set-aside ids, and the hold a rejecting drain armed before the
1092
+ /// process went away, which goes back on the gate unless it ends further
1093
+ /// ahead than any hold the gate arms (a clock set back since; see
1094
+ /// `restoreWindow(until:)`). The first drain that runs then rewrites the
1095
+ /// file. A missing, unreadable or corrupt file is an empty set and no
1096
+ /// hold.
1097
+ private func restoreSetAsideIfNeeded() {
1098
+ if flushQueue.sync(execute: { setAsideRestored }) { return }
1099
+ var ids = Set<String>()
1100
+ var holdUntil: Date?
1101
+ // What the file holds, if it is known to hold exactly that.
1102
+ var saved: (ids: Set<String>, holdUntil: Date?)? = ([], nil)
1103
+ if let data = queue.readSidecar(named: Self.setAsideFileName) {
1104
+ if let file = try? JSONDecoder().decode(SetAsideFile.self, from: data) {
1105
+ ids = Set(file.ids.prefix(Self.maxSetAsideItems))
1106
+ holdUntil = file.holdUntil.flatMap { $0.isFinite ? Date(timeIntervalSince1970: $0) : nil }
1107
+ saved = ids.count == file.ids.count ? (ids, holdUntil) : nil
1108
+ } else {
1109
+ saved = nil
1110
+ }
1111
+ }
1112
+ let restored: Bool = flushQueue.sync {
1113
+ if setAsideRestored { return false }
1114
+ setAsideRestored = true
1115
+ setAsideIds = ids
1116
+ savedSetAside = saved
1117
+ return true
1118
+ }
1119
+ if restored, let holdUntil { backoffGate.restoreWindow(until: holdUntil) }
1120
+ }
1121
+
1122
+ /// Keep what a drain ends with, and write `set-aside.json` if that
1123
+ /// changed it: the ids, and `holdUntil` when the drain armed a hold for
1124
+ /// rejections. The file is deleted once there is nothing to keep.
1125
+ private func saveSetAside(_ ids: Set<String>, holdUntil: Date?) {
1126
+ let unchanged: Bool = flushQueue.sync {
1127
+ setAsideIds = ids
1128
+ if let saved = savedSetAside, saved.ids == ids, saved.holdUntil == holdUntil { return true }
1129
+ savedSetAside = (ids, holdUntil)
1130
+ return false
1131
+ }
1132
+ if unchanged { return }
1133
+ if ids.isEmpty && holdUntil == nil {
1134
+ queue.writeSidecar(named: Self.setAsideFileName, nil)
1135
+ return
1136
+ }
1137
+ let file = SetAsideFile(ids: ids.sorted(), holdUntil: holdUntil?.timeIntervalSince1970)
1138
+ guard let data = try? JSONEncoder().encode(file) else { return }
1139
+ queue.writeSidecar(named: Self.setAsideFileName, data)
1140
+ }
1141
+
680
1142
  /// Record one undecodable-success response for `batchIds` and return the
681
1143
  /// running count. A different head-of-queue batch restarts the count —
682
1144
  /// the budget is per-batch, not a global "server has been flaky" tally.
@@ -792,9 +1254,14 @@ internal final class IngestClient: @unchecked Sendable {
792
1254
  // `remainingOrArm` on the failure path, plain `remaining` on
793
1255
  // the rest: a drain the gate itself short-circuited must read
794
1256
  // the existing window back, not extend it every time a trigger
795
- // bounces off it. A terminal 4xx arms nothing and books
796
- // nothing, exactly as before — retrying it on a timer would
797
- // only spin.
1257
+ // bounces off it. A rejected payload never reaches here as an
1258
+ // error any more (`flush()` splits, retires or sets it aside and
1259
+ // keeps going); a refused key (401/403) or a 408/425 does, and is
1260
+ // retryable, so it comes back once its window has passed. A drain
1261
+ // that stopped on `maxRejectedAttemptsPerDrain`, or set items
1262
+ // aside, returns normally with the gate armed, so `remaining`
1263
+ // books its wake-up. So does the first drain after a relaunch
1264
+ // inside a persisted hold: it finds the gate closed.
798
1265
  if ((try? queue.count()) ?? 0) > 0 {
799
1266
  let wait = failedRetryably
800
1267
  ? backoffGate.remainingOrArm()
@@ -816,13 +1283,18 @@ internal final class IngestClient: @unchecked Sendable {
816
1283
  /// Does this failure describe a backend that might answer differently
817
1284
  /// in a moment? A rejected payload never will, so it is deliberately
818
1285
  /// absent — re-offering it on a timer would spin until the ambiguity
819
- /// budget or the queue cap ended it.
1286
+ /// budget or the queue cap ended it. A refused KEY (401/403) is
1287
+ /// different: the items are fine and the key can be fixed, so it is
1288
+ /// retried after the long window `flush()` armed for it. So are a 408
1289
+ /// (a proxy timed out on the upload) and a 425 (replay later).
820
1290
  private static func isRetryable(_ error: Error) -> Bool {
821
1291
  if error is UndecodableIngestResponse { return true }
822
1292
  guard let purchases = error as? PurchasesError else { return false }
823
1293
  switch purchases {
824
1294
  case .backendUnavailable, .networkError:
825
1295
  return true
1296
+ case .backendRejected(let status, _):
1297
+ return [401, 403, 408, 425].contains(status)
826
1298
  default:
827
1299
  return false
828
1300
  }
@@ -1052,4 +1524,11 @@ internal final class IngestClient: @unchecked Sendable {
1052
1524
  let task = flushQueue.sync { flushTask }
1053
1525
  if let task = task { await task.value }
1054
1526
  }
1527
+
1528
+ /// How many items the next drain skips until the server accepts a batch
1529
+ /// (`setAsideIds`), read back from `set-aside.json` first if no drain has.
1530
+ func _setAsideCountForTesting() -> Int {
1531
+ restoreSetAsideIfNeeded()
1532
+ return flushQueue.sync { setAsideIds.count }
1533
+ }
1055
1534
  }