@app-swiss-knife/react-native-sdk 0.3.1 → 0.3.2

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.
@@ -21,22 +21,46 @@
21
21
  // Architecture:
22
22
  // - `enqueue(_ item: IngestItem)` writes to `OfflineQueueStore<IngestItem>`
23
23
  // synchronously and returns immediately. The item carries an
24
- // `event_id` (UUIDv4) stamped at enqueue time — this is the
25
- // idempotency key the backend dedupes on.
26
- // - Flush is size-threshold + lifecycle-driven only — there is no
27
- // periodic timer. A flush is triggered when the queue crosses
28
- // `batchSize` (default 100), when reachability returns, or when the
29
- // app enters background. A `Task`-driven flush coordinator
30
- // short-circuits redundant schedules so concurrent enqueues coalesce
31
- // into a single drain.
24
+ // `event_id` (UUIDv4) stamped at enqueue time — the idempotency key
25
+ // retries reuse. NOTE: server-side dedupe on it is currently real for
26
+ // `analytics` only (unique `(app_project_id, event_id)`); several
27
+ // other item types mint a fresh id on ingest, so a redelivery of those
28
+ // lands twice. Retry-on-ambiguity is still the right trade (a visible
29
+ // duplicate beats a silently lost crash report) but do not read this
30
+ // line as "retries are free".
31
+ // - A flush is triggered when the queue crosses `batchSize`
32
+ // (default 100), when reachability returns, when the app enters
33
+ // background, when the crash reporter recovers a previous run's
34
+ // report, and by `SKAnalytics` — both its public `flush()` and its
35
+ // periodic flush timer. That is six independent triggers, several of
36
+ // which routinely fire at once (a burst of events crosses the
37
+ // threshold while the timer ticks while the user backgrounds the app).
38
+ // ALL of them enter through `flushBestEffort()`, which guarantees a
39
+ // single in-flight drain and coalesces the rest into at most one
40
+ // follow-up pass. Nothing may call `flush()` directly — that is the
41
+ // uncoordinated primitive, and concurrent copies of it duplicate
42
+ // every row they carry.
32
43
  // - On flush, the client reads `SwissKnife.Identity.current` and stamps
33
44
  // `anonymous_id` + `user_id` into each item's outgoing envelope.
34
45
  // Items enqueued before an identity change get the CURRENT identity at
35
46
  // flush time (matches RC's late-binding behaviour).
36
- // - Retries go through `BackendHttpClient` — 4xx dead-letters
37
- // immediately, 5xx / network errors retry with the shared
38
- // `ExponentialBackoff`. After the bounded retry budget the items go
39
- // to the dead-letter file and are removed from the live queue.
47
+ // - Retries are owned HERE, not by `BackendHttpClient`: each drain makes
48
+ // exactly ONE attempt per batch (`maxRetriesPerAttempt = 0`) and a
49
+ // failure arms the client-wide `BackendBackoffGate`, which the next
50
+ // drain consults before it sends. 4xx still dead-letters immediately.
51
+ // Putting the wait between drains rather than inside one request is
52
+ // what makes the backoff apply to the QUEUE instead of to a single
53
+ // HTTP call — see `BackendBackoffGate` for why the difference is
54
+ // load-bearing, and note the second benefit: items enqueued while the
55
+ // window is closed join the next batch instead of racing out behind
56
+ // it in a request of their own.
57
+ // - A 2xx whose body we cannot decode is an AMBIGUOUS outcome, not a
58
+ // success: we have no evidence the server accepted anything, so the
59
+ // batch stays queued and the next flush retries it. Deletion from the
60
+ // durable queue happens only on evidence of acceptance (a decodable
61
+ // result, or an empty body — the server's no-content ack). The retry
62
+ // is bounded by `maxAmbiguousAttempts`, after which the batch is
63
+ // dead-lettered rather than retried forever.
40
64
 
41
65
  import Foundation
42
66
  import os.log
@@ -70,7 +94,8 @@ internal enum IngestItemType: String, Codable, Sendable {
70
94
  /// Single queued item. `id` is the local idempotency key — stamped at
71
95
  /// `enqueue()` time, used by `OfflineQueueStore.remove(ids:)` after the
72
96
  /// server accepts the batch, and embedded in the outgoing payload via
73
- /// `event_id` so the backend dedupes on it too.
97
+ /// `event_id` so the backend can dedupe on it (see the file header for
98
+ /// which item types actually do).
74
99
  ///
75
100
  /// `data` is type-erased JSON because each `type` has a different schema
76
101
  /// (validated on the server). We can't statically enforce all 8 shapes
@@ -251,6 +276,29 @@ internal struct IngestErrorEntry: Codable, Sendable {
251
276
  let error: String
252
277
  }
253
278
 
279
+ /// The server answered a batch POST with a 2xx status but a non-empty body
280
+ /// we could not decode as an `IngestResult` — a truncated response, an HTML
281
+ /// error page from a misconfigured proxy, a partial write.
282
+ ///
283
+ /// This is deliberately its own error type rather than a
284
+ /// `PurchasesError.backendUnavailable`: `flush()` counts these separately to
285
+ /// bound how long an undecodable-but-successful backend can pin the head of
286
+ /// the queue. See `IngestClient.maxAmbiguousAttempts`.
287
+ internal struct UndecodableIngestResponse: Error {
288
+ /// Size of the body we could not decode — the useful diagnostic, since
289
+ /// a truncated response is the common cause.
290
+ let byteCount: Int
291
+ /// First bytes of the body, for the log line. Bounded so a megabyte of
292
+ /// proxy HTML can't land in os_log.
293
+ let preview: String
294
+
295
+ init(body: Data) {
296
+ self.byteCount = body.count
297
+ let text = String(decoding: body.prefix(200), as: UTF8.self)
298
+ self.preview = text.replacingOccurrences(of: "\n", with: " ")
299
+ }
300
+ }
301
+
254
302
  // ---------------------------------------------------------------------------
255
303
  // MARK: - ContextSnapshot
256
304
  // ---------------------------------------------------------------------------
@@ -307,20 +355,20 @@ internal final class IngestClient: @unchecked Sendable {
307
355
  //
308
356
  // 1. Preferred: the durable `cachesDirectory` JSONL queue.
309
357
  if let queue = try? OfflineQueueStore<IngestItem>(name: "ingest") {
310
- return IngestClient(queue: queue)
358
+ return IngestClient(queue: queue, backoffGate: .shared)
311
359
  }
312
360
  // 2. Fallback: a tmpdir-backed durable queue (caches dir may be
313
361
  // unavailable under sandboxing / disk pressure).
314
362
  let tmp = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
315
363
  .appendingPathComponent("SwissKnife-ingest-fallback-\(IDs.requestId())")
316
364
  if let queue = try? OfflineQueueStore<IngestItem>(directory: tmp, name: "ingest-fb") {
317
- return IngestClient(queue: queue)
365
+ return IngestClient(queue: queue, backoffGate: .shared)
318
366
  }
319
367
  // 3. Last-ditch: a purely in-memory queue. Cannot throw, cannot
320
368
  // crash. Items are lost on process termination, but the SDK —
321
369
  // and the host app — stay alive.
322
370
  let memoryQueue = OfflineQueueStore<IngestItem>(inMemoryName: "ingest-mem")
323
- return IngestClient(queue: memoryQueue)
371
+ return IngestClient(queue: memoryQueue, backoffGate: .shared)
324
372
  }()
325
373
 
326
374
  /// Max items per HTTP request. Mirrors the server's 100-item cap on
@@ -336,14 +384,74 @@ internal final class IngestClient: @unchecked Sendable {
336
384
  private let timestampProvider: @Sendable () -> Date
337
385
  private let log = OSLog(subsystem: "com.swissknife.net", category: "IngestClient")
338
386
 
339
- // Flush coordination — `flushTask` keeps the latest in-flight task
340
- // (`nil` between flushes). `isFlushing` short-circuits redundant
341
- // schedule calls. Both are guarded by `flushQueue` which is a
342
- // serial DispatchQueue (sync-safe from async contexts, unlike
343
- // NSLock which Swift 6 will reject).
387
+ // Flush coordination — see `flushBestEffort()` for the contract.
388
+ // `flushTask` is THE single in-flight drain (`nil` between drains) and
389
+ // doubles as the "is a flush running" flag; `followUpRequested` is the
390
+ // one-bit coalescing slot for callers that arrived while it was
391
+ // running. Both are guarded by `flushQueue`, a serial DispatchQueue
392
+ // (sync-safe from async contexts, unlike NSLock which Swift 6 will
393
+ // reject).
344
394
  private let flushQueue = DispatchQueue(label: "com.swissknife.ingest.flush")
345
395
  private var flushTask: Task<Void, Never>?
346
- private var isFlushing: Bool = false
396
+ private var followUpRequested: Bool = false
397
+
398
+ /// Client-wide "do not send before T" window. Read before every drain,
399
+ /// armed by every retryable answer (here and in `BackendHttpClient`),
400
+ /// cleared only when the server accepts a batch. See
401
+ /// `BackendBackoffGate` for who arms, who clears, and why background
402
+ /// telemetry is the only thing that waits on it.
403
+ private let backoffGate: BackendBackoffGate
404
+
405
+ /// Where the deferred wake-up runs. A queue of its own, never
406
+ /// `flushQueue`: the wake-up calls `flushCoordinated()`, which takes
407
+ /// `flushQueue.sync`, and a `sync` onto the queue you are already
408
+ /// running on is a deadlock.
409
+ private let retryQueue = DispatchQueue(label: "com.swissknife.ingest.retry")
410
+
411
+ /// At most one deferred wake-up may be outstanding. Guarded by
412
+ /// `flushQueue` with the rest of the flush state. Without it, every
413
+ /// gated trigger — and there are six of them — would book its own
414
+ /// timer and they would all fire into the same instant.
415
+ private var retryWakeupPending: Bool = false
416
+
417
+ /// How much past the window the wake-up fires. The gate is checked
418
+ /// again when the drain starts, and a wake-up scheduled for the exact
419
+ /// boundary loses that race often enough to matter: it would find the
420
+ /// gate still closed by a millisecond, re-book itself, and cost a
421
+ /// pointless round trip through the coordinator.
422
+ static let gateWakeupSlack: TimeInterval = 0.05
423
+
424
+ /// Retries `BackendHttpClient` performs on behalf of ONE ingest
425
+ /// attempt. Zero, on purpose.
426
+ ///
427
+ /// The HTTP client's loop retries the same serialized request body, so
428
+ /// every wait it takes is a wait during which newly enqueued items
429
+ /// cannot join. That is what produced the failure this constant exists
430
+ /// to kill: a batch spent its whole `Retry-After` budget inside one
431
+ /// request, and the items enqueued during that window went out in a
432
+ /// SECOND request 126ms after the first one finally succeeded — the
433
+ /// server's five second window honoured, then immediately ignored.
434
+ ///
435
+ /// With the wait between drains instead, the same items ride the next
436
+ /// attempt of the same queue. Nothing is retried less; the retry just
437
+ /// carries everything that has accumulated. The other callers of
438
+ /// `BackendHttpClient` keep their in-request budget, because they have
439
+ /// no queue behind them to merge into.
440
+ static let maxRetriesPerAttempt = 0
441
+
442
+ /// How many consecutive undecodable-success responses the SAME batch may
443
+ /// collect before `flush()` stops retrying it and dead-letters it instead.
444
+ ///
445
+ /// This is a deliberate bound, not a fallback: without it a backend that
446
+ /// permanently answers 200 with garbage would pin the head of the queue
447
+ /// forever, re-sending the same batch on every reachability regain and
448
+ /// every background transition, and the queue behind it would grow to its
449
+ /// 10k cap and start dropping the OLDEST items — reintroducing the silent
450
+ /// loss from the other end. 5 attempts is the same budget the HTTP layer
451
+ /// gives a 5xx, and because these attempts are lifecycle-driven rather
452
+ /// than back-to-back it spans hours-to-days of real-world retrying before
453
+ /// anything is given up on.
454
+ static let maxAmbiguousAttempts = 5
347
455
 
348
456
  /// Whether the network is reachable. Updated by the Reachability
349
457
  /// observer; flush short-circuits to no-op when false.
@@ -351,6 +459,13 @@ internal final class IngestClient: @unchecked Sendable {
351
459
  private var reachabilityToken: UUID?
352
460
  private var lifecycleToken: UUID?
353
461
 
462
+ /// Consecutive undecodable-success responses for the batch currently at
463
+ /// the head of the queue, and the identity of that batch. Guarded by
464
+ /// `flushQueue` like the other flush state. Reset when a batch decodes or
465
+ /// when the head of the queue turns over.
466
+ private var ambiguousAttempts: Int = 0
467
+ private var ambiguousBatchIds: Set<String> = []
468
+
354
469
  init(
355
470
  queue: OfflineQueueStore<IngestItem>,
356
471
  http: BackendHttpClient = BackendHttpClient.shared,
@@ -367,10 +482,17 @@ internal final class IngestClient: @unchecked Sendable {
367
482
  = { Session.shared.current },
368
483
  deviceSnapshot: @escaping @Sendable () -> DeviceContext
369
484
  = { DeviceContextProvider.current() },
370
- timestampProvider: @escaping @Sendable () -> Date = { Clock.now() }
485
+ timestampProvider: @escaping @Sendable () -> Date = { Clock.now() },
486
+ // A FRESH gate by default, not `.shared`: a backoff window is
487
+ // process-wide mutable state, and defaulting to the shared one
488
+ // would let a scripted 503 in one test hold back an unrelated
489
+ // one. Production goes through `IngestClient.shared`, which wires
490
+ // `.shared` explicitly.
491
+ backoffGate: BackendBackoffGate = BackendBackoffGate()
371
492
  ) {
372
493
  _ = flushIntervalSec // intentionally unused — see param doc.
373
494
  self.queue = queue
495
+ self.backoffGate = backoffGate
374
496
  self.http = http
375
497
  self.batchSize = batchSize
376
498
  self.path = path
@@ -440,17 +562,35 @@ internal final class IngestClient: @unchecked Sendable {
440
562
  /// aggregated `IngestResult` across all batches. Items that hit a
441
563
  /// terminal `backendRejected` error are dead-lettered.
442
564
  ///
565
+ /// UNCOORDINATED PRIMITIVE — production code must never call this
566
+ /// directly, only `flushBestEffort()`. The loop below reads the
567
+ /// durable queue, POSTs, and deletes only once the server has
568
+ /// answered; two of these overlapping in that window read the same
569
+ /// rows and upload them twice. `flushBestEffort()` is what guarantees
570
+ /// there is only ever one. It stays non-private solely so tests can
571
+ /// drive a single deterministic drain and observe the thrown error.
572
+ ///
443
573
  /// If the network is unreachable (per the Reachability observer), the
444
574
  /// flush short-circuits to an empty result — items stay queued and
445
575
  /// will be re-attempted when reachability returns. This prevents the
446
576
  /// retry budget from being burned on calls we know will fail at the
447
577
  /// DNS / TCP layer.
578
+ ///
579
+ /// It short-circuits the same way while the client-wide
580
+ /// `BackendBackoffGate` is closed. Both checks are "not now", not
581
+ /// "never": the items stay on disk, and `drainUntilQuiet` books the
582
+ /// wake-up that comes back for them. Note the ORDER — reachability
583
+ /// first — so an offline stretch never arms the gate at all, which is
584
+ /// what keeps an outage from leaving a long window behind it.
448
585
  @discardableResult
449
586
  func flush() async throws -> IngestResult {
450
587
  let reachable = flushQueue.sync { isReachable }
451
588
  if !reachable {
452
589
  return IngestResult(queued: 0, errors: [])
453
590
  }
591
+ if backoffGate.remaining > 0 {
592
+ return IngestResult(queued: 0, errors: [])
593
+ }
454
594
  var aggregateQueued = 0
455
595
  var aggregateErrors: [IngestErrorEntry] = []
456
596
 
@@ -458,7 +598,50 @@ internal final class IngestClient: @unchecked Sendable {
458
598
  let items = try queue.readAll()
459
599
  if items.isEmpty { break }
460
600
  let batch = Array(items.prefix(batchSize))
461
- let result = try await sendBatch(batch)
601
+ let batchIds = Set(batch.map { $0.id })
602
+ let result: IngestResult
603
+ do {
604
+ result = try await sendBatch(batch)
605
+ } catch let ambiguous as UndecodableIngestResponse {
606
+ // We do not know what the server did with this batch, so we
607
+ // must not delete it. Leave it queued and let the next flush
608
+ // (reachability regain / background / size threshold) retry.
609
+ //
610
+ // Retrying an ambiguous batch can duplicate rather than lose:
611
+ // `analytics` items dedupe server-side on
612
+ // `(app_project_id, event_id)`, but several other item types
613
+ // currently mint a fresh id on ingest and would land twice.
614
+ // That trade is taken deliberately — a duplicate is visible
615
+ // and reconcilable, a silently dropped crash report is not.
616
+ let attempts = noteAmbiguousResponse(for: batchIds)
617
+ if attempts < Self.maxAmbiguousAttempts {
618
+ throw ambiguous
619
+ }
620
+ // Budget exhausted. A backend permanently emitting garbage
621
+ // would otherwise pin the head of the queue forever and
622
+ // re-send the same batch on every lifecycle event, so the
623
+ // batch goes to the same terminal, on-disk, recoverable
624
+ // destination a server-rejected item gets — never a silent
625
+ // drop.
626
+ queue.deadLetter(batch)
627
+ os_log(
628
+ "IngestClient dead-lettered %d item(s) after %d undecodable success responses: %{public}@ | last body: %d bytes: %{public}@",
629
+ log: log,
630
+ type: .error,
631
+ batch.count,
632
+ attempts,
633
+ batch.map { $0.type.rawValue }.joined(separator: ","),
634
+ ambiguous.byteCount,
635
+ ambiguous.preview
636
+ )
637
+ try queue.remove(ids: batchIds)
638
+ clearAmbiguousStreak()
639
+ if batch.count < batchSize { break }
640
+ continue
641
+ }
642
+ // A decodable answer — whatever it said, the server is talking
643
+ // sense again, so the ambiguity streak is over.
644
+ clearAmbiguousStreak()
462
645
  aggregateQueued += result.queued
463
646
  aggregateErrors.append(contentsOf: result.errors)
464
647
  // Remove ALL items the server reported on (queued + errors).
@@ -486,7 +669,7 @@ internal final class IngestClient: @unchecked Sendable {
486
669
  result.errors.map { $0.error }.joined(separator: " | ")
487
670
  )
488
671
  }
489
- try queue.remove(ids: Set(batch.map { $0.id }))
672
+ try queue.remove(ids: batchIds)
490
673
  // If the batch was the full size, there might be more — loop.
491
674
  if batch.count < batchSize { break }
492
675
  }
@@ -494,16 +677,177 @@ internal final class IngestClient: @unchecked Sendable {
494
677
  return IngestResult(queued: aggregateQueued, errors: aggregateErrors)
495
678
  }
496
679
 
497
- /// Drain the queue, ignoring all errors. Used by the background
498
- /// timer-driven flush where there's no caller to await an outcome.
680
+ /// Record one undecodable-success response for `batchIds` and return the
681
+ /// running count. A different head-of-queue batch restarts the count —
682
+ /// the budget is per-batch, not a global "server has been flaky" tally.
683
+ private func noteAmbiguousResponse(for batchIds: Set<String>) -> Int {
684
+ flushQueue.sync {
685
+ if ambiguousBatchIds == batchIds {
686
+ ambiguousAttempts += 1
687
+ } else {
688
+ ambiguousBatchIds = batchIds
689
+ ambiguousAttempts = 1
690
+ }
691
+ return ambiguousAttempts
692
+ }
693
+ }
694
+
695
+ private func clearAmbiguousStreak() {
696
+ flushQueue.sync {
697
+ ambiguousAttempts = 0
698
+ ambiguousBatchIds = []
699
+ }
700
+ }
701
+
702
+ /// THE flush entry point. Every trigger in the SDK goes through here:
703
+ /// `SKAnalytics.flush()`, the analytics flush timer, the size
704
+ /// threshold, reachability regain, `didEnterBackground`, and the crash
705
+ /// reporter's launch-time recovery. Errors are logged, not thrown —
706
+ /// none of those callers has anywhere to put one.
707
+ ///
708
+ /// Serialized AND coalescing, and it has to be both.
709
+ ///
710
+ /// Serialized, because `flush()` reads the durable queue, POSTs, and
711
+ /// deletes only after the server answers. Two drains overlapping in
712
+ /// that window read the same rows and upload them twice. The guard
713
+ /// used to live inside `scheduleImmediateFlush()` only, so the two
714
+ /// callers that bypassed it — the public `flush()` and the flush
715
+ /// timer, each spawning a bare `Task` — raced each other and every
716
+ /// other trigger. Measured cost: one event id with `attempts=14,
717
+ /// delivered=4`. Server-side dedupe on `(app_project_id, event_id)`
718
+ /// covers `analytics` only; `session` / `feedback` / `paywall` /
719
+ /// `funnel` / `transaction` / error rows mint a fresh id per delivery
720
+ /// and duplicate for real.
721
+ ///
722
+ /// Coalescing rather than queueing, because the alternative — a
723
+ /// second flag that makes concurrent callers wait their turn — turns
724
+ /// N triggers into N sequential drains, and N-1 of those find an
725
+ /// empty queue. A caller arriving mid-drain instead joins the running
726
+ /// one and sets a single follow-up bit. It needs that bit rather than
727
+ /// just joining: its items may have been enqueued after the running
728
+ /// drain's `readAll()`, so the running drain owes it one more pass.
729
+ /// Ten concurrent callers therefore cost at most one extra pass, not
730
+ /// ten.
731
+ ///
732
+ /// Awaiting this is meaningful for every caller: the drain does not
733
+ /// report finished until the follow-up it owes has also run.
499
734
  func flushBestEffort() async {
500
- do { _ = try await flush() } catch {
501
- os_log(
502
- "IngestClient flush failed: %{public}@",
503
- log: log,
504
- type: .error,
505
- String(describing: error)
506
- )
735
+ await flushCoordinated().value
736
+ }
737
+
738
+ /// Join the in-flight drain or start one, and hand back the task so
739
+ /// callers can await it. The decision and the state mutation happen in
740
+ /// a single `flushQueue` critical section — split them and two callers
741
+ /// both see "no drain running" and both start one, which is the bug
742
+ /// this whole mechanism exists to prevent.
743
+ @discardableResult
744
+ private func flushCoordinated() -> Task<Void, Never> {
745
+ flushQueue.sync {
746
+ if let inFlight = flushTask {
747
+ followUpRequested = true
748
+ return inFlight
749
+ }
750
+ let task = Task<Void, Never> { [weak self] in
751
+ await self?.drainUntilQuiet()
752
+ }
753
+ flushTask = task
754
+ return task
755
+ }
756
+ }
757
+
758
+ /// Body of the single in-flight drain: run `flush()`, then run it once
759
+ /// more if anyone asked for a flush while that pass was in progress.
760
+ ///
761
+ /// Clearing `flushTask` and reading `followUpRequested` happen in the
762
+ /// SAME critical section on purpose. A request landing between those
763
+ /// two either sets the bit before we read it (we run its pass) or
764
+ /// finds `flushTask` already `nil` (it starts a fresh drain). There is
765
+ /// no interleaving where a request is acknowledged and then dropped.
766
+ ///
767
+ /// The loop terminates: `followUpRequested` is one bit, cleared before
768
+ /// each extra pass, and only external triggers set it — so passes are
769
+ /// bounded by the call rate, and a pass over an already-drained queue
770
+ /// costs a single `readAll()` that returns empty.
771
+ private func drainUntilQuiet() async {
772
+ while true {
773
+ var failedRetryably = false
774
+ do {
775
+ _ = try await flush()
776
+ } catch {
777
+ os_log(
778
+ "IngestClient flush failed: %{public}@",
779
+ log: log,
780
+ type: .error,
781
+ String(describing: error)
782
+ )
783
+ failedRetryably = Self.isRetryable(error)
784
+ }
785
+ // Book the wake-up for whatever is still on disk. Nothing else
786
+ // will: flush is threshold- and lifecycle-driven, and an app
787
+ // sitting in the foreground after a failed upload produces
788
+ // neither of those. This is the half of the gate that keeps it
789
+ // from becoming a queue-stopper — the window defers a drain,
790
+ // and the wake-up is the promise to come back for it.
791
+ //
792
+ // `remainingOrArm` on the failure path, plain `remaining` on
793
+ // the rest: a drain the gate itself short-circuited must read
794
+ // 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.
798
+ if ((try? queue.count()) ?? 0) > 0 {
799
+ let wait = failedRetryably
800
+ ? backoffGate.remainingOrArm()
801
+ : backoffGate.remaining
802
+ if wait > 0 { scheduleGatedRetry(after: wait) }
803
+ }
804
+ let owesAnotherPass: Bool = flushQueue.sync {
805
+ if followUpRequested {
806
+ followUpRequested = false
807
+ return true
808
+ }
809
+ flushTask = nil
810
+ return false
811
+ }
812
+ if !owesAnotherPass { return }
813
+ }
814
+ }
815
+
816
+ /// Does this failure describe a backend that might answer differently
817
+ /// in a moment? A rejected payload never will, so it is deliberately
818
+ /// absent — re-offering it on a timer would spin until the ambiguity
819
+ /// budget or the queue cap ended it.
820
+ private static func isRetryable(_ error: Error) -> Bool {
821
+ if error is UndecodableIngestResponse { return true }
822
+ guard let purchases = error as? PurchasesError else { return false }
823
+ switch purchases {
824
+ case .backendUnavailable, .networkError:
825
+ return true
826
+ default:
827
+ return false
828
+ }
829
+ }
830
+
831
+ /// Come back for the queue once `delay` has elapsed, at most one
832
+ /// outstanding wake-up at a time.
833
+ ///
834
+ /// Re-entering through `flushCoordinated()` rather than calling
835
+ /// `flush()` is what stops the gate and the coalescer from fighting:
836
+ /// the wake-up is just one more trigger, so it joins an in-flight
837
+ /// drain instead of starting a competing one, and the single-drain
838
+ /// guarantee that keeps items from uploading twice is untouched.
839
+ private func scheduleGatedRetry(after delay: TimeInterval) {
840
+ let claimed: Bool = flushQueue.sync {
841
+ if retryWakeupPending { return false }
842
+ retryWakeupPending = true
843
+ return true
844
+ }
845
+ guard claimed else { return }
846
+ let fireIn = max(0, delay) + Self.gateWakeupSlack
847
+ retryQueue.asyncAfter(deadline: .now() + fireIn) { [weak self] in
848
+ guard let self = self else { return }
849
+ self.flushQueue.sync { self.retryWakeupPending = false }
850
+ self.flushCoordinated()
507
851
  }
508
852
  }
509
853
 
@@ -515,15 +859,37 @@ internal final class IngestClient: @unchecked Sendable {
515
859
  /// RevenueCat's identify flow.
516
860
  private func sendBatch(_ batch: [IngestItem]) async throws -> IngestResult {
517
861
  let envelope = try buildEnvelope(batch: batch)
518
- let responseData = try await http.postRaw(path: path, body: envelope)
519
- let decoded: IngestResult
862
+ let responseData = try await http.postRaw(
863
+ path: path,
864
+ body: envelope,
865
+ maxRetries: Self.maxRetriesPerAttempt
866
+ )
867
+ // An EMPTY 2xx body is a genuine ack — the server answers 202 with no
868
+ // content on the fast path, and `postRaw` has already thrown for every
869
+ // non-2xx status, so reaching here with nothing to read means "all
870
+ // accepted, nothing rejected". Whitespace-only counts as empty.
871
+ //
872
+ // Both ack paths open the gate; the undecodable one below does not.
873
+ // The gate closes on a promise about the backend and reopens on
874
+ // evidence about the backend, and a 200 we cannot read is neither.
875
+ if responseData.allSatisfy({ $0 == 0x20 || $0 == 0x09 || $0 == 0x0A || $0 == 0x0D }) {
876
+ backoffGate.noteSuccess()
877
+ return IngestResult(queued: batch.count, errors: [])
878
+ }
520
879
  do {
521
- decoded = try JSONDecoder().decode(IngestResult.self, from: responseData)
880
+ let decoded = try JSONDecoder().decode(IngestResult.self, from: responseData)
881
+ backoffGate.noteSuccess()
882
+ return decoded
522
883
  } catch {
523
- // 202 with empty body is acceptable.
524
- decoded = IngestResult(queued: batch.count, errors: [])
884
+ // A NON-EMPTY body we cannot decode is not evidence of acceptance.
885
+ // This used to fabricate `IngestResult(queued: batch.count)`, which
886
+ // `flush()` could not tell apart from a real ack — so it removed the
887
+ // batch from the durable queue and a truncated or corrupted 200
888
+ // destroyed those events permanently. Absence of evidence is not
889
+ // evidence of acceptance: hand `flush()` an error so the batch stays
890
+ // queued and is retried.
891
+ throw UndecodableIngestResponse(body: responseData)
525
892
  }
526
- return decoded
527
893
  }
528
894
 
529
895
  /// Build a `ContextSnapshot` for a given item. Per-item because
@@ -600,25 +966,19 @@ internal final class IngestClient: @unchecked Sendable {
600
966
 
601
967
  // MARK: - Background scheduling
602
968
 
603
- /// Coalescing flush trigger — used by the size threshold, reachability
604
- /// regain, `didEnterBackground`, and the crash reporter's launch-time
605
- /// recovery (a crash recovered from a previous run must not sit in the
606
- /// disk queue until the next lifecycle event). Safe to call from any
607
- /// thread; a no-op when a flush is already in flight.
969
+ /// Fire-and-forget flush trigger — used by the size threshold,
970
+ /// reachability regain, `didEnterBackground`, and the crash reporter's
971
+ /// launch-time recovery (a crash recovered from a previous run must
972
+ /// not sit in the disk queue until the next lifecycle event). Safe to
973
+ /// call from any thread.
974
+ ///
975
+ /// Identical coordination to `flushBestEffort()` — this is only the
976
+ /// synchronous, un-awaited spelling of it. It is deliberately NOT the
977
+ /// old "no-op when a flush is already in flight": dropping the request
978
+ /// lost items that were enqueued after the running drain had already
979
+ /// read the queue. Now it books a follow-up pass instead.
608
980
  func scheduleImmediateFlush() {
609
- let shouldStart = flushQueue.sync { () -> Bool in
610
- if isFlushing { return false }
611
- isFlushing = true
612
- return true
613
- }
614
- guard shouldStart else { return }
615
- let task = Task { [weak self] in
616
- await self?.flushBestEffort()
617
- self?.flushQueue.sync {
618
- self?.isFlushing = false
619
- }
620
- }
621
- flushQueue.sync { self.flushTask = task }
981
+ flushCoordinated()
622
982
  }
623
983
 
624
984
  // MARK: - Reachability / Lifecycle wiring