@app-swiss-knife/react-native-sdk 0.3.0 → 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.
@@ -42,7 +42,7 @@ internal object DeviceContextProvider {
42
42
  * eventually inject this via `BuildConfig`, but for now keep it in
43
43
  * source so we don't have to thread build settings through every test.
44
44
  */
45
- const val SDK_VERSION: String = "0.3.0"
45
+ const val SDK_VERSION: String = "0.3.2"
46
46
 
47
47
  private val cacheLock = Any()
48
48
 
@@ -26,6 +26,12 @@
26
26
  // - 4xx → dead-letter (validation reject is not retriable).
27
27
  // 5xx / network → retry with shared ExponentialBackoff.
28
28
  // After budget → dead-letter.
29
+ // - 2xx with a body we cannot parse → AMBIGUOUS, not success. We have no
30
+ // evidence the server accepted anything, so the batch stays queued and
31
+ // the worker retries it. Deletion from the durable queue happens only on
32
+ // evidence of acceptance (a parseable result, or an empty body — the
33
+ // server's no-content ack). Bounded by MAX_AMBIGUOUS_ATTEMPTS, after
34
+ // which the batch is dead-lettered rather than retried forever.
29
35
  //
30
36
  // Context primitives (DeviceContext / IDs / Session / Reachability / Clock)
31
37
  // arrive in Commit 3. This commit ships placeholder providers that take
@@ -208,7 +214,7 @@ internal object IngestPlaceholderDevice {
208
214
  appBuild = "unknown",
209
215
  locale = Locale.getDefault().toString(),
210
216
  timezone = TimeZone.getDefault().id,
211
- sdkVersion = "0.3.0",
217
+ sdkVersion = "0.3.2",
212
218
  bundleIdentifier = null,
213
219
  )
214
220
  }
@@ -250,6 +256,22 @@ internal data class IngestErrorEntry(
250
256
  // IngestClient
251
257
  // ---------------------------------------------------------------------------
252
258
 
259
+ /**
260
+ * The server answered a batch POST with a 2xx status but a non-empty body we
261
+ * could not parse — a truncated response, an HTML error page from a
262
+ * misconfigured proxy, a partial write.
263
+ *
264
+ * Extends [IOException] so it flows through [flushSync]'s existing
265
+ * `@Throws(IOException::class)` contract and the worker's IO retry branch.
266
+ * It is its own type, not a bare IOException, because [flushSync] counts
267
+ * these separately to bound how long an undecodable-but-successful backend
268
+ * can pin the head of the queue. See [IngestClient.MAX_AMBIGUOUS_ATTEMPTS].
269
+ */
270
+ internal class UndecodableIngestResponse(
271
+ val byteCount: Int,
272
+ val preview: String,
273
+ ) : IOException("undecodable success response ($byteCount bytes): $preview")
274
+
253
275
  /**
254
276
  * Unified client for `POST /ingest`. Process-wide singleton wired by
255
277
  * SwissKnife.configure (Commit 3); tests construct their own.
@@ -268,6 +290,21 @@ internal class IngestClient(
268
290
  companion object {
269
291
  const val TAG = "SwissKnife.IngestClient"
270
292
 
293
+ /**
294
+ * How many consecutive undecodable-success responses the SAME batch
295
+ * may collect before [flushSync] stops retrying it and dead-letters
296
+ * it instead.
297
+ *
298
+ * A deliberate bound, not a fallback: without it a backend that
299
+ * permanently answers 200 with garbage would pin the head of the
300
+ * queue forever, re-sending the same batch on every worker run, and
301
+ * the queue behind it would grow to its cap and start dropping the
302
+ * OLDEST items — reintroducing silent loss from the other end. 5
303
+ * matches IngestFlushWorker.MAX_ATTEMPTS and the iOS client's
304
+ * `maxAmbiguousAttempts`.
305
+ */
306
+ const val MAX_AMBIGUOUS_ATTEMPTS = 5
307
+
271
308
  /**
272
309
  * Process-wide instance — wired by SwissKnife.configure (Commit 3).
273
310
  * Tests construct their own. Direct read access is internal-only;
@@ -324,6 +361,15 @@ internal class IngestClient(
324
361
  @Volatile
325
362
  private var isReachable: Boolean = true
326
363
 
364
+ /**
365
+ * Consecutive undecodable-success responses for the batch currently at
366
+ * the head of the queue, and the identity of that batch. The budget is
367
+ * per-batch, not a global "server has been flaky" tally. Only ever
368
+ * touched from flushSync, which the worker serialises.
369
+ */
370
+ private var ambiguousAttempts: Int = 0
371
+ private var ambiguousBatchIds: Set<String> = emptySet()
372
+
327
373
  // -------- Public enqueue API --------
328
374
 
329
375
  /**
@@ -425,7 +471,41 @@ internal class IngestClient(
425
471
  queue.remove(batch.map { it.id }.toSet())
426
472
  throw e
427
473
  }
428
- val parsed = parseResult(resp, batch.size)
474
+ val batchIds = batch.map { it.id }.toSet()
475
+ val parsed = try {
476
+ parseResult(resp, batch.size)
477
+ } catch (e: UndecodableIngestResponse) {
478
+ // We do not know what the server did with this batch, so we
479
+ // must not delete it. Leave it queued; the worker's retry
480
+ // brings us back here.
481
+ //
482
+ // Retrying an ambiguous batch can duplicate rather than lose:
483
+ // `analytics` items dedupe server-side on
484
+ // `(app_project_id, event_id)`, but several other item types
485
+ // currently mint a fresh id on ingest and would land twice.
486
+ // That trade is taken deliberately — a duplicate is visible
487
+ // and reconcilable, a silently dropped crash report is not.
488
+ val attempts = noteAmbiguousResponse(batchIds)
489
+ if (attempts < MAX_AMBIGUOUS_ATTEMPTS) throw e
490
+ // Budget spent — retire the batch to the dead-letter file,
491
+ // the same terminal-but-recoverable destination a
492
+ // server-rejected item gets. Never a silent drop.
493
+ Log.w(
494
+ TAG,
495
+ "dead-lettering ${batch.size} item(s) after $attempts undecodable " +
496
+ "success responses; last body: ${e.byteCount} bytes: ${e.preview}",
497
+ )
498
+ queue.deadLetter(batch)
499
+ queue.remove(batchIds)
500
+ clearAmbiguousStreak()
501
+ null
502
+ }
503
+ if (parsed == null) {
504
+ // Batch retired above; keep draining whatever is behind it.
505
+ if (batch.size < batchSize) break else continue
506
+ }
507
+ // A parseable answer — the server is talking sense again.
508
+ clearAmbiguousStreak()
429
509
  totalQueued += parsed.queued
430
510
  aggregateErrors.addAll(parsed.errors)
431
511
  val errorIdxs = parsed.errors.map { it.index }.toSet()
@@ -435,12 +515,31 @@ internal class IngestClient(
435
515
  if (deadLetterItems.isNotEmpty()) {
436
516
  queue.deadLetter(deadLetterItems)
437
517
  }
438
- queue.remove(batch.map { it.id }.toSet())
518
+ queue.remove(batchIds)
439
519
  if (batch.size < batchSize) break
440
520
  }
441
521
  return IngestResult(queued = totalQueued, errors = aggregateErrors)
442
522
  }
443
523
 
524
+ /**
525
+ * Record one undecodable-success response for [batchIds]; returns the
526
+ * running count. A different head-of-queue batch restarts the count.
527
+ */
528
+ private fun noteAmbiguousResponse(batchIds: Set<String>): Int {
529
+ if (batchIds == ambiguousBatchIds) {
530
+ ambiguousAttempts += 1
531
+ } else {
532
+ ambiguousBatchIds = batchIds
533
+ ambiguousAttempts = 1
534
+ }
535
+ return ambiguousAttempts
536
+ }
537
+
538
+ private fun clearAmbiguousStreak() {
539
+ ambiguousAttempts = 0
540
+ ambiguousBatchIds = emptySet()
541
+ }
542
+
444
543
  // -------- Envelope construction --------
445
544
 
446
545
  @VisibleForTesting
@@ -498,8 +597,22 @@ internal class IngestClient(
498
597
  return data
499
598
  }
500
599
 
600
+ /**
601
+ * Parse the server's `{ queued, errors }` answer.
602
+ *
603
+ * An EMPTY body is a genuine ack — the server answers 202 with no content
604
+ * on the fast path, and `postRaw` has already thrown for every non-2xx
605
+ * status, so nothing to read means "all accepted, nothing rejected".
606
+ *
607
+ * A NON-EMPTY body we cannot parse throws [UndecodableIngestResponse].
608
+ * It used to fall through to `IngestResult(queued = batchSize)`, which
609
+ * [flushSync] could not tell apart from a real ack — so it removed the
610
+ * batch from the durable queue and a truncated or corrupted 200 destroyed
611
+ * those items permanently. Absence of evidence is not evidence of
612
+ * acceptance.
613
+ */
501
614
  private fun parseResult(body: String, batchSize: Int): IngestResult {
502
- if (body.isEmpty()) return IngestResult(queued = batchSize, errors = emptyList())
615
+ if (body.isBlank()) return IngestResult(queued = batchSize, errors = emptyList())
503
616
  return runCatching {
504
617
  val obj = JSONObject(body)
505
618
  val queued = obj.optInt("queued", batchSize)
@@ -513,8 +626,10 @@ internal class IngestClient(
513
626
  }
514
627
  IngestResult(queued = queued, errors = errs)
515
628
  }.getOrElse {
516
- // 202 with empty / non-JSON body — assume everything queued.
517
- IngestResult(queued = batchSize, errors = emptyList())
629
+ throw UndecodableIngestResponse(
630
+ byteCount = body.length,
631
+ preview = body.take(200).replace('\n', ' '),
632
+ )
518
633
  }
519
634
  }
520
635
  }
@@ -569,6 +684,12 @@ internal class IngestFlushWorker(
569
684
  Log.w(TAG, "ingest 5xx attempt ${runAttemptCount + 1}; will retry", e)
570
685
  Result.retry()
571
686
  }
687
+ } catch (e: UndecodableIngestResponse) {
688
+ // A 2xx we could not parse. flushSync has kept the batch queued
689
+ // and owns the give-up decision (IngestClient.MAX_AMBIGUOUS_ATTEMPTS),
690
+ // so all this branch does is ask WorkManager to come back.
691
+ Log.w(TAG, "ingest undecodable success response; will retry", e)
692
+ Result.retry()
572
693
  } catch (e: IOException) {
573
694
  if (runAttemptCount + 1 >= MAX_ATTEMPTS) {
574
695
  Log.w(TAG, "ingest IO after $MAX_ATTEMPTS attempts; giving up", e)
@@ -415,6 +415,12 @@ public final class SKAnalytics {
415
415
  ///
416
416
  /// Fire-and-forget by design — the SDK doesn't surface a completion
417
417
  /// handler in its public contract.
418
+ ///
419
+ /// The bare `Task` here is safe only because `flushBestEffort()`
420
+ /// serializes: this call and the `startFlushTimer()` tick below are
421
+ /// two of the six triggers that used to race each other, and every
422
+ /// racing pair re-uploaded whatever was in the queue. Do not
423
+ /// "optimise" this into a direct `ingest.flush()`.
418
424
  public func flush() {
419
425
  Task { [ingest] in
420
426
  await ingest.flushBestEffort()
@@ -99,7 +99,7 @@ internal enum DeviceContextProvider {
99
99
  /// Round A baseline. The build pipeline (`swiss-build`) will eventually
100
100
  /// inject this via `-D` flag, but for now keep it in source so we don't
101
101
  /// have to thread build settings through the SPM Package.swift.
102
- static let sdkVersionConstant: String = "0.3.0"
102
+ static let sdkVersionConstant: String = "0.3.2"
103
103
 
104
104
  private static let cacheLock = DispatchQueue(label: "com.swissknife.context.device")
105
105
  private static var cached: DeviceContext?
@@ -1033,6 +1033,13 @@ public final class SKCrashReporting {
1033
1033
  return frames
1034
1034
  }
1035
1035
 
1036
+ /// Path of the running app bundle, resolved once. Everything dyld loaded
1037
+ /// from under it is the app; everything else is the system or the OS's
1038
+ /// shared cache. Resolved lazily rather than at init because this is only
1039
+ /// ever needed while BUILDING a report — never inside a signal handler,
1040
+ /// where a Foundation call would be unsafe.
1041
+ private static let appBundlePath: String = Bundle.main.bundlePath
1042
+
1036
1043
  /// Resolve a single instruction address into a structured frame via
1037
1044
  /// `dladdr()` — symbol name, image name, in-app heuristic. The raw
1038
1045
  /// address is always carried in `instructionAddress` for server-side
@@ -1048,13 +1055,32 @@ public final class SKCrashReporting {
1048
1055
 
1049
1056
  if resolved {
1050
1057
  symbolName = info.dli_sname.map { String(cString: $0) }
1058
+ var imagePath: String?
1051
1059
  if let fname = info.dli_fname {
1052
1060
  let fullPath = String(cString: fname)
1061
+ imagePath = fullPath
1053
1062
  imageName = (fullPath as NSString).lastPathComponent
1054
1063
  } else {
1055
1064
  imageName = nil
1056
1065
  }
1057
- if let appExec = appExecutable {
1066
+ // Anything loaded from INSIDE the app bundle is the app: the main
1067
+ // executable and every embedded framework under `.../Frameworks/`.
1068
+ // System images live in /usr/lib, /System/Library, or the dyld
1069
+ // shared cache, none of which are under the bundle.
1070
+ //
1071
+ // Comparing against the main executable alone — which is what this
1072
+ // did — marks the entire native stack of a React Native app as
1073
+ // NOT-in-app, because such an app's native code is essentially all
1074
+ // frameworks: React, Hermes, whatever the host embeds. Server-side
1075
+ // grouping drops non-in-app frames before fingerprinting, so a
1076
+ // stack of 35 real frames contributed NOTHING and every SIGSEGV in
1077
+ // the app fell back to the constant "Signal|Signal 11" and landed
1078
+ // in one undifferentiated issue.
1079
+ if let path = imagePath,
1080
+ !SKCrashReporting.appBundlePath.isEmpty,
1081
+ path.hasPrefix(SKCrashReporting.appBundlePath) {
1082
+ isInApp = true
1083
+ } else if let appExec = appExecutable {
1058
1084
  isInApp = imageName == appExec
1059
1085
  } else {
1060
1086
  let img = imageName ?? ""
@@ -75,9 +75,32 @@ public extension SwissKnife {
75
75
  public let customerInfo: CustomerInfo
76
76
  public let created: Bool
77
77
 
78
- public init(customerInfo: CustomerInfo, created: Bool) {
78
+ /// A NEWER identity change overtook this call before it could
79
+ /// commit, so this login did not take effect — `customerInfo`
80
+ /// describes the identity that WON, not the one asked for here.
81
+ ///
82
+ /// Being superseded is not a failure, and it is not rare. The
83
+ /// launch sequence this SDK's own setup playbook prescribes —
84
+ /// identify with a bootstrap id, then switch to the real account
85
+ /// (or log out) once the auth listener resolves — produces exactly
86
+ /// this, on every single launch. The earlier call is obsolete
87
+ /// because the host itself said so a moment later; reporting that
88
+ /// as an error trained whole teams to ignore identity errors.
89
+ ///
90
+ /// Hosts that only care about the end state can ignore this flag:
91
+ /// the winning identity is already applied SDK-wide by the time it
92
+ /// is set. Hosts that dispatch on their own call's outcome should
93
+ /// check it before treating the result as "user X is now current".
94
+ public let superseded: Bool
95
+
96
+ public init(
97
+ customerInfo: CustomerInfo,
98
+ created: Bool,
99
+ superseded: Bool = false
100
+ ) {
79
101
  self.customerInfo = customerInfo
80
102
  self.created = created
103
+ self.superseded = superseded
81
104
  }
82
105
  }
83
106
 
@@ -205,11 +228,12 @@ public extension SwissKnife {
205
228
  )
206
229
  } catch {
207
230
  // If a newer mutation (logOut/reset/wipe/another logIn)
208
- // has raced past while we were in flight, swallow the
209
- // error — the caller has already moved on. Otherwise
210
- // surface it. Mirrors Android's Round E behaviour.
231
+ // has raced past while we were in flight, the caller has
232
+ // already moved on — report the supersede rather than this
233
+ // call's own network error, which describes an operation
234
+ // whose outcome no longer matters.
211
235
  let racedPast: Bool = queue.sync { identityGeneration != myGeneration }
212
- if racedPast { throw CancellationError() }
236
+ if racedPast { return try await supersededResult(created: false) }
213
237
  throw error
214
238
  }
215
239
 
@@ -219,7 +243,7 @@ public extension SwissKnife {
219
243
  // mutation's intent wins. Mirrors Android's Round E fix.
220
244
  let generationAfterNetwork: Int = queue.sync { identityGeneration }
221
245
  if generationAfterNetwork != myGeneration {
222
- throw CancellationError()
246
+ return try await supersededResult(created: result.created)
223
247
  }
224
248
 
225
249
  let newSnapshot = Snapshot(
@@ -234,7 +258,7 @@ public extension SwissKnife {
234
258
  return true
235
259
  }
236
260
  guard applied else {
237
- throw CancellationError()
261
+ return try await supersededResult(created: result.created)
238
262
  }
239
263
  // Push the user-id into the rest of the SDK so subscriptions and
240
264
  // attributes get the new identity.
@@ -248,6 +272,21 @@ public extension SwissKnife {
248
272
  return LogInResult(customerInfo: info, created: result.created)
249
273
  }
250
274
 
275
+ /// Describe an identity change that overtook an in-flight `logIn`.
276
+ ///
277
+ /// Reports the identity that WON, which is the only one the caller can
278
+ /// usefully act on: by the time this runs, the newer change is already
279
+ /// applied SDK-wide. Prefers the cached snapshot and only reaches the
280
+ /// network when there is none — at launch, which is precisely when
281
+ /// supersedes happen, the cache is usually still empty.
282
+ private static func supersededResult(created: Bool) async throws -> LogInResult {
283
+ if let cached = EntitlementsService.shared.current() {
284
+ return LogInResult(customerInfo: cached, created: created, superseded: true)
285
+ }
286
+ let info = try await EntitlementsService.shared.refresh()
287
+ return LogInResult(customerInfo: info, created: created, superseded: true)
288
+ }
289
+
251
290
  /// Revert to anonymous. The DeviceID is NOT regenerated — Phase 1
252
291
  /// keeps it stable across logout (analytics continuity for the
253
292
  /// same physical install). Use `wipe()` for a full identity reset.
@@ -255,6 +294,16 @@ public extension SwissKnife {
255
294
  // Core gate — see `logIn(_:)`.
256
295
  guard SwissKnife.isCoreConfigured else { throw PurchasesError.notConfigured }
257
296
  let previous = current
297
+ // NOTE: this bumps even when already anonymous, and that is
298
+ // deliberate. Skipping the bump looks like a free optimisation for
299
+ // the launch-time "signed out before the first sign-in resolved"
300
+ // case, but a `logIn` may be IN FLIGHT with nothing committed yet:
301
+ // the host said log out, so it must win over that login too, and a
302
+ // no-op here would let the login land afterwards and re-identify.
303
+ // `test_logIn_thenImmediate_logOut_doesNotReidentify` pins it.
304
+ //
305
+ // The bump costs nothing now that being superseded returns a
306
+ // flagged result instead of throwing `CancellationError`.
258
307
  let anonId = previous.anonymousId
259
308
  let newSnapshot = Snapshot(anonymousId: anonId, userId: nil)
260
309
  // Bump generation BEFORE clearing state so any in-flight `logIn`
@@ -0,0 +1,182 @@
1
+ // packages/swiss-knife-ios/Sources/SwissKnifeiOS/Net/BackendBackoffGate.swift
2
+ //
3
+ // Client-wide backoff window — the "do not send before T" gate the ingest
4
+ // pipeline consults before it drains.
5
+ //
6
+ // ## The hole this fills
7
+ //
8
+ // `ExponentialBackoff` and `Retry-After` used to be honoured only INSIDE
9
+ // `BackendHttpClient.performWithRetries`, i.e. only between the attempts of
10
+ // the one request that received them. That bounds a single request and
11
+ // nothing else. The moment that request finished — successfully or not —
12
+ // the next drain carrying a DIFFERENT queue item started immediately, and
13
+ // the window the server had just asked for was gone.
14
+ //
15
+ // The fault-injection suite measures exactly that: the smallest gap between
16
+ // two consecutive `POST /ingest` arrivals at the proxy. The observed floor
17
+ // was 99ms under a plain 500 and 126ms under a `Retry-After: 5`, because
18
+ // the drain that finished the retry loop was followed straight away by a
19
+ // second drain carrying the items enqueued while the first one was
20
+ // sleeping.
21
+ //
22
+ // So the window has to live on the CLIENT, not on the request. That is this
23
+ // type: one shared instance, armed by whichever call saw the server say
24
+ // "not yet", read by the ingest flush before it puts anything on the wire.
25
+ // It is the same shape React Native has had since wave B (`_backoffUntil`
26
+ // in `packages/react-native-sdk/src/modules/crash-reporting.ts`), which is
27
+ // why RN passes the same assertions and iOS did not.
28
+ //
29
+ // ## Who arms it, who clears it, and why they are not the same set
30
+ //
31
+ // ARMED by any retryable answer on any `BackendHttpClient` call — an
32
+ // offerings fetch that gets a 429 has learned something true about the
33
+ // backend, and telemetry has no business ignoring it. Arming is the
34
+ // conservative direction: the worst case is that background uploads wait
35
+ // a little longer than strictly necessary.
36
+ //
37
+ // CLEARED only by an ingest batch the server actually accepted. Clearing is
38
+ // the dangerous direction, and letting any successful call do it would
39
+ // defeat the gate outright in the exact case it exists for: the stress
40
+ // suite faults `/ingest` alone, so the app's `/api/sdk/*` calls sail
41
+ // through, and a successful offerings fetch one second into a five second
42
+ // `Retry-After` would re-open the gate and put the hot loop straight back.
43
+ // Evidence about the gated path is what retires a window about the gated
44
+ // path. Everything else just expires on its own.
45
+ //
46
+ // ## What deliberately does NOT consult it
47
+ //
48
+ // Only `IngestClient` — i.e. background telemetry — waits on this gate.
49
+ // User-visible calls (`fetchOfferings`, `purchase`, `customerInfo`,
50
+ // `identify`) go straight through `BackendHttpClient` and are never held
51
+ // back. Blocking a paywall fetch because an analytics batch got a 503
52
+ // trades a real user outcome for a deferred metric, which is the wrong way
53
+ // round; those calls keep their own in-request retry budget, which is
54
+ // bounded by `operationDeadline` and therefore cannot run away.
55
+ //
56
+ // ## Why it cannot starve the queue
57
+ //
58
+ // Three bounds, all deliberate:
59
+ // 1. The escalation is `ExponentialBackoff`'s, capped at `maxSeconds`.
60
+ // 2. A server-supplied `Retry-After` is honoured but clamped to
61
+ // `maxHonouredRetryAfter` (5 min), so a buggy or hostile header
62
+ // cannot park the queue for a day.
63
+ // 3. The gate is in-memory only. A process restart — which is what every
64
+ // recovery flow in the stress suite actually does — starts from open.
65
+ // On top of that, `IngestClient` never arms it while the network is known
66
+ // to be unreachable, because it short-circuits before making the request:
67
+ // an offline stretch costs the gate nothing.
68
+
69
+ import Foundation
70
+
71
+ /// A single "not before" instant plus the failure streak that produced it.
72
+ /// Thread-safe; one shared instance in production, freshly constructed
73
+ /// instances in tests so nothing leaks between them.
74
+ internal final class BackendBackoffGate: @unchecked Sendable {
75
+
76
+ /// The production gate. Wired into `BackendHttpClient.shared` (arms it)
77
+ /// and `IngestClient.shared` (reads and clears it). Tests construct
78
+ /// their own — a shared mutable window is exactly the kind of state
79
+ /// that makes a suite order-dependent.
80
+ static let shared = BackendBackoffGate()
81
+
82
+ /// Ceiling on a server-advertised `Retry-After`. The header is honoured
83
+ /// in full below this and clamped above it: five minutes is far longer
84
+ /// than any legitimate backpressure signal from our own backend, and a
85
+ /// bound is what keeps a single bad response from wedging telemetry
86
+ /// for the lifetime of the process.
87
+ static let maxHonouredRetryAfter: TimeInterval = 300
88
+
89
+ private let lock = NSLock()
90
+ private let backoff: ExponentialBackoff
91
+ private let now: @Sendable () -> Date
92
+
93
+ /// Instant before which the gated path must not send. `nil` == open.
94
+ private var notBefore: Date?
95
+
96
+ /// Consecutive retryable answers since the last accepted ingest batch.
97
+ /// Doubles as the attempt index handed to `ExponentialBackoff`.
98
+ private var consecutiveFailures: Int = 0
99
+
100
+ /// Bound on the attempt index. `pow(2, n)` overflows long before this
101
+ /// matters numerically, but `maxSeconds` has already clamped the delay
102
+ /// by attempt ~5 anyway, so there is nothing to gain by counting higher.
103
+ private static let maxAttemptIndex = 16
104
+
105
+ init(
106
+ backoff: ExponentialBackoff = ExponentialBackoff(),
107
+ now: @escaping @Sendable () -> Date = { Date() }
108
+ ) {
109
+ self.backoff = backoff
110
+ self.now = now
111
+ }
112
+
113
+ /// Seconds the gated path must still wait. `0` means the gate is open.
114
+ var remaining: TimeInterval {
115
+ lock.lock(); defer { lock.unlock() }
116
+ return remainingLocked()
117
+ }
118
+
119
+ /// Record a retryable answer (429, 5xx, or a transport-level error) and
120
+ /// arm the window. Returns the time left once armed.
121
+ ///
122
+ /// The window only ever moves FORWARD: two calls racing on the same
123
+ /// failure must not shorten a longer window that is already in place.
124
+ @discardableResult
125
+ func noteRetryable(retryAfter: TimeInterval?) -> TimeInterval {
126
+ lock.lock(); defer { lock.unlock() }
127
+ return armLocked(retryAfter: retryAfter)
128
+ }
129
+
130
+ /// Record an accepted ingest batch: the gated path is demonstrably
131
+ /// working again, so the window closes and the escalation resets.
132
+ func noteSuccess() {
133
+ lock.lock(); defer { lock.unlock() }
134
+ notBefore = nil
135
+ consecutiveFailures = 0
136
+ }
137
+
138
+ /// Time left if the gate is already armed; otherwise arm it one step
139
+ /// and return that.
140
+ ///
141
+ /// This is what a failed drain calls. Usually `BackendHttpClient` has
142
+ /// already armed the gate from the response it saw, and this just reads
143
+ /// it back; the arming branch covers the failures that never reached a
144
+ /// status code the HTTP layer classifies (a queue write error, an
145
+ /// undecodable 2xx surfaced above the transport) so a failed drain can
146
+ /// never schedule its own retry for "immediately".
147
+ @discardableResult
148
+ func remainingOrArm() -> TimeInterval {
149
+ lock.lock(); defer { lock.unlock() }
150
+ let left = remainingLocked()
151
+ if left > 0 { return left }
152
+ return armLocked(retryAfter: nil)
153
+ }
154
+
155
+ /// Snapshot for tests and diagnostics.
156
+ func snapshot() -> (remaining: TimeInterval, consecutiveFailures: Int) {
157
+ lock.lock(); defer { lock.unlock() }
158
+ return (remainingLocked(), consecutiveFailures)
159
+ }
160
+
161
+ // MARK: - Private (all callers hold `lock`)
162
+
163
+ private func remainingLocked() -> TimeInterval {
164
+ guard let notBefore = notBefore else { return 0 }
165
+ let left = notBefore.timeIntervalSince(now())
166
+ return left > 0 ? left : 0
167
+ }
168
+
169
+ private func armLocked(retryAfter: TimeInterval?) -> TimeInterval {
170
+ let attempt = min(consecutiveFailures, Self.maxAttemptIndex)
171
+ consecutiveFailures = min(consecutiveFailures + 1, Self.maxAttemptIndex)
172
+ let honoured = retryAfter.map { min(max(0, $0), Self.maxHonouredRetryAfter) }
173
+ let delay = backoff.delay(forAttempt: attempt, honoring: honoured)
174
+ let candidate = now().addingTimeInterval(max(0, delay))
175
+ if let current = notBefore, current > candidate {
176
+ // Someone already asked for longer. Keep the longer window.
177
+ } else {
178
+ notBefore = candidate
179
+ }
180
+ return remainingLocked()
181
+ }
182
+ }