@app-swiss-knife/react-native-sdk 0.3.1 → 0.4.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 (28) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
  3. package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +315 -41
  4. package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +13 -4
  5. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +229 -36
  6. package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +6 -0
  7. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
  8. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +186 -56
  9. package/ios/vendor/SwissKnifeiOS/Net/BackendBackoffGate.swift +182 -0
  10. package/ios/vendor/SwissKnifeiOS/Net/BackendHttpClient.swift +164 -8
  11. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +418 -58
  12. package/lib/commonjs/index.js.map +1 -1
  13. package/lib/commonjs/modules/crash-reporting.js +525 -35
  14. package/lib/commonjs/modules/crash-reporting.js.map +1 -1
  15. package/lib/module/index.js.map +1 -1
  16. package/lib/module/modules/crash-reporting.js +525 -35
  17. package/lib/module/modules/crash-reporting.js.map +1 -1
  18. package/lib/typescript/commonjs/index.d.ts +1 -1
  19. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  20. package/lib/typescript/commonjs/modules/crash-reporting.d.ts +32 -7
  21. package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -1
  22. package/lib/typescript/module/index.d.ts +1 -1
  23. package/lib/typescript/module/index.d.ts.map +1 -1
  24. package/lib/typescript/module/modules/crash-reporting.d.ts +32 -7
  25. package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -1
  26. package/package.json +2 -1
  27. package/src/index.ts +2 -0
  28. package/src/modules/crash-reporting.ts +625 -68
@@ -454,9 +454,13 @@ public final class SKCrashReporting {
454
454
  // on disk for the whole next session. Schedule a launch-time flush
455
455
  // BEHIND the recovery enqueues on the same serial queue, so the items
456
456
  // are on the ingest queue before the drain starts.
457
- let recoveredSignalCrash = flushSignalMarker()
458
- let recoveredPendingCrash = flushPendingCrash()
459
- if recoveredSignalCrash || recoveredPendingCrash {
457
+ //
458
+ // The NSException report is recovered FIRST: whether the signal report
459
+ // is a duplicate depends on that report having actually been read,
460
+ // decoded and enqueued (see `isNSExceptionAbortDuplicate`).
461
+ let recoveredNSExceptionAt = flushPendingCrash()
462
+ let recoveredSignalCrash = flushSignalMarker(recoveredNSExceptionAt: recoveredNSExceptionAt)
463
+ if recoveredSignalCrash || recoveredNSExceptionAt != nil {
460
464
  queue.async { [ingest] in
461
465
  ingest.scheduleImmediateFlush()
462
466
  }
@@ -886,27 +890,66 @@ public final class SKCrashReporting {
886
890
 
887
891
  // MARK: - Pending Crash (disk)
888
892
 
889
- /// Returns `true` when a pending crash was recovered and enqueued —
890
- /// `start()` uses this to trigger the launch-time ingest flush.
891
- private func flushPendingCrash() -> Bool {
893
+ /// Returns the crash instant (the file's mtime) when a pending
894
+ /// NSException crash was recovered and enqueued, `nil` otherwise. `start()`
895
+ /// uses it to trigger the launch-time ingest flush and to pair the report
896
+ /// with the SIGABRT the same crash left behind.
897
+ private func flushPendingCrash() -> Date? {
892
898
  let url = SKCrashReporting.pendingCrashURL
893
899
  guard FileManager.default.fileExists(atPath: url.path),
894
- let data = try? Data(contentsOf: url) else { return false }
900
+ let data = try? Data(contentsOf: url) else { return nil }
901
+ let crashedAt = (try? FileManager.default.attributesOfItem(atPath: url.path))?[.modificationDate] as? Date
895
902
 
896
903
  // Delete before sending to avoid re-sending on failure (best-effort delivery)
897
904
  try? FileManager.default.removeItem(at: url)
898
905
 
899
- guard configuration != nil else { return false }
906
+ guard configuration != nil else { return nil }
900
907
  // The crash JSON on disk is a single SKErrorEvent. Decode and
901
908
  // re-enqueue through IngestClient so retry / batching / context
902
909
  // stamping all happen uniformly with live errors.
903
910
  let decoder = JSONDecoder()
904
911
  decoder.dateDecodingStrategy = .iso8601
905
- if let event = try? decoder.decode(SKErrorEvent.self, from: data) {
906
- sendEvent(event)
907
- return true
908
- }
909
- return false
912
+ guard let event = try? decoder.decode(SKErrorEvent.self, from: data) else { return nil }
913
+ sendEvent(event)
914
+ return crashedAt ?? Date.distantPast
915
+ }
916
+
917
+ /// How long after the NSException report was written its `abort()` tail
918
+ /// may land in the signal marker. The gap is the rest of the exception
919
+ /// handler (session close) plus any chained incumbent handler — well under
920
+ /// a second in practice. A relaunch plus a new crash cannot fit inside it.
921
+ internal static let nsExceptionAbortPairingWindow: TimeInterval = 10
922
+
923
+ /// Whether a recovered signal report is the `abort()` tail of an uncaught
924
+ /// NSException, and must therefore be dropped.
925
+ ///
926
+ /// An uncaught NSException does not end the process by itself: the ObjC
927
+ /// runtime calls our handler, which writes `pending-crash.json`, and then
928
+ /// `abort()`s, which raises SIGABRT and runs our signal handler too. Both
929
+ /// used to be reported, so every NSException crash arrived as TWO events —
930
+ /// the real one and a "Signal 6" that grouped into its own issue.
931
+ ///
932
+ /// The signal report is dropped only when ALL of these hold, so a crash is
933
+ /// never left with zero events:
934
+ /// - the signal is SIGABRT (any other signal is a separate fault);
935
+ /// - the NSException report was actually recovered — read, decoded and
936
+ /// enqueued (`recoveredNSExceptionAt != nil`). If the handler died before
937
+ /// finishing the write, or the file no longer decodes, the signal report
938
+ /// is the only record and is kept;
939
+ /// - the two files belong to the same crash: the NSException report was
940
+ /// written at most `nsExceptionAbortPairingWindow` before the signal
941
+ /// marker. A stale report left by an earlier run (e.g. unreadable during
942
+ /// a locked-device relaunch) cannot swallow a later, unrelated abort().
943
+ internal static func isNSExceptionAbortDuplicate(
944
+ signal: Int32?,
945
+ recoveredNSExceptionAt: Date?,
946
+ signalAt: Date
947
+ ) -> Bool {
948
+ guard signal == SIGABRT, let nsExceptionAt = recoveredNSExceptionAt else { return false }
949
+ let gap = signalAt.timeIntervalSince(nsExceptionAt)
950
+ // Small negative slack: both mtimes come from the same clock, but
951
+ // filesystem timestamp granularity can order them either way.
952
+ return gap >= -1 && gap <= nsExceptionAbortPairingWindow
910
953
  }
911
954
 
912
955
  /// On next launch, read the signal marker file + backtrace binary +
@@ -915,7 +958,7 @@ public final class SKCrashReporting {
915
958
  /// marker and raw backtrace addresses to the backtrace-bin file.
916
959
  /// Returns `true` when a signal crash was recovered and enqueued —
917
960
  /// `start()` uses this to trigger the launch-time ingest flush.
918
- private func flushSignalMarker() -> Bool {
961
+ private func flushSignalMarker(recoveredNSExceptionAt: Date? = nil) -> Bool {
919
962
  let markerURL = SKCrashReporting.signalMarkerURL
920
963
  let contextURL = SKCrashReporting.persistedContextURL
921
964
  let backtraceURL = SKCrashReporting.backtraceFileURL
@@ -932,6 +975,21 @@ public final class SKCrashReporting {
932
975
 
933
976
  let signalString = String(data: markerData, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "unknown"
934
977
 
978
+ // The SIGABRT that follows an uncaught NSException is the same crash
979
+ // the NSException handler already recorded (pending-crash.json, just
980
+ // sent by `flushPendingCrash`) — including its crashed-session close,
981
+ // which that handler sends at crash time. Drop the whole signal report
982
+ // and its artifacts rather than emitting a second, worse event.
983
+ if SKCrashReporting.isNSExceptionAbortDuplicate(
984
+ signal: Int32(signalString),
985
+ recoveredNSExceptionAt: recoveredNSExceptionAt,
986
+ signalAt: crashedAt
987
+ ) {
988
+ try? FileManager.default.removeItem(at: backtraceURL)
989
+ try? FileManager.default.removeItem(at: contextURL)
990
+ return false
991
+ }
992
+
935
993
  // Build event from persisted context (if available)
936
994
  var event = SKErrorEvent(level: .fatal)
937
995
  event.exceptionType = "Signal"
@@ -1076,18 +1134,12 @@ public final class SKCrashReporting {
1076
1134
  // stack of 35 real frames contributed NOTHING and every SIGSEGV in
1077
1135
  // the app fell back to the constant "Signal|Signal 11" and landed
1078
1136
  // 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 {
1084
- isInApp = imageName == appExec
1085
- } else {
1086
- let img = imageName ?? ""
1087
- isInApp = !img.hasPrefix("lib") && !img.hasPrefix("_")
1088
- && img != "UIKitCore" && img != "Foundation"
1089
- && img != "CoreFoundation" && img != "libdyld.dylib"
1090
- }
1137
+ isInApp = SKCrashReporting.isInAppImage(
1138
+ imagePath: imagePath,
1139
+ imageName: imageName,
1140
+ appExecutable: appExecutable,
1141
+ appBundlePath: SKCrashReporting.appBundlePath
1142
+ )
1091
1143
  } else {
1092
1144
  symbolName = nil
1093
1145
  imageName = nil
@@ -1105,6 +1157,47 @@ public final class SKCrashReporting {
1105
1157
  )
1106
1158
  }
1107
1159
 
1160
+ /// The ONE in-app rule, shared by `symbolicate(address:)` (signal / ANR
1161
+ /// frames) and `parseCallStackSymbols` (NSException / captured-error
1162
+ /// frames). Two rules used to exist; the symbol-line parser compared the
1163
+ /// image name against the main executable only, so an Xcode 16 debug
1164
+ /// build (whose code lives in `<App>.debug.dylib`) and every embedded
1165
+ /// framework came out not-in-app, and those stacks contributed nothing to
1166
+ /// grouping.
1167
+ ///
1168
+ /// 1. A known image path under the app bundle is in-app — main executable,
1169
+ /// `.debug.dylib`, and everything under `Frameworks/`.
1170
+ /// 2. With no path, the main executable name or its `.debug.dylib` twin.
1171
+ /// 3. With no executable name either, a denylist of system image names.
1172
+ internal static func isInAppImage(
1173
+ imagePath: String?,
1174
+ imageName: String?,
1175
+ appExecutable: String?,
1176
+ appBundlePath: String
1177
+ ) -> Bool {
1178
+ if let path = imagePath, !appBundlePath.isEmpty {
1179
+ let bundle = appBundlePath.hasSuffix("/") ? appBundlePath : appBundlePath + "/"
1180
+ if path.hasPrefix(bundle) { return true }
1181
+ }
1182
+ if let appExec = appExecutable, !appExec.isEmpty {
1183
+ return imageName == appExec || imageName == appExec + ".debug.dylib"
1184
+ }
1185
+ let img = imageName ?? ""
1186
+ return !img.isEmpty && !img.hasPrefix("lib") && !img.hasPrefix("_")
1187
+ && img != "UIKitCore" && img != "Foundation"
1188
+ && img != "CoreFoundation" && img != "libdyld.dylib"
1189
+ }
1190
+
1191
+ /// Image path for a live in-process address, via `dladdr`. Ordinary
1192
+ /// threads only.
1193
+ private static func imagePath(forAddress address: UInt) -> String? {
1194
+ guard address != 0 else { return nil }
1195
+ var info = Dl_info()
1196
+ guard dladdr(UnsafeRawPointer(bitPattern: address), &info) != 0,
1197
+ let fname = info.dli_fname else { return nil }
1198
+ return String(cString: fname)
1199
+ }
1200
+
1108
1201
  internal func writeCrashToDisk(_ event: SKErrorEvent) {
1109
1202
  let encoder = JSONEncoder()
1110
1203
  encoder.dateEncodingStrategy = .iso8601
@@ -1282,18 +1375,35 @@ public final class SKCrashReporting {
1282
1375
  }
1283
1376
 
1284
1377
  private func captureANR() {
1285
- // Capture main thread stack trace via thread_get_state if possible,
1286
- // otherwise fall back to current thread symbols as a hint.
1287
- let frames = captureMainThreadStack()
1288
-
1378
+ // Capture the main thread's stack via thread_get_state. When that is
1379
+ // impossible the event is sent WITHOUT a stack: the only other stack
1380
+ // available is the watchdog thread's own, which is identical for
1381
+ // every ANR and would group them all under the watchdog's frames.
1289
1382
  var event = buildEvent(level: .error)
1290
1383
  event.message = "Application Not Responding"
1291
1384
  event.mechanism = "anr"
1292
- event.stacktrace = frames
1385
+ SKCrashReporting.applyANRStack(captureMainThreadStack(), to: &event)
1293
1386
  guard let finalEvent = applyBeforeSend(event) else { return }
1294
1387
  sendEvent(finalEvent)
1295
1388
  }
1296
1389
 
1390
+ /// Extra key set on an ANR event whose main-thread stack could not be read.
1391
+ internal static let anrStackUnavailableExtraKey = "anr_stack"
1392
+
1393
+ /// Attach the main-thread stack to an ANR event, or — when it could not be
1394
+ /// captured — no stack at all plus an explicit marker, so the dashboard
1395
+ /// can say "stack unavailable" instead of showing the watchdog's frames.
1396
+ internal static func applyANRStack(_ frames: [SKStackFrame]?, to event: inout SKErrorEvent) {
1397
+ if let frames, !frames.isEmpty {
1398
+ event.stacktrace = frames
1399
+ return
1400
+ }
1401
+ event.stacktrace = nil
1402
+ var extra = event.extra ?? [:]
1403
+ extra[anrStackUnavailableExtraKey] = "unavailable"
1404
+ event.extra = extra
1405
+ }
1406
+
1297
1407
  /// Capture the main thread's stack trace using Mach thread APIs.
1298
1408
  ///
1299
1409
  /// The watchdog thread suspends the main thread, reads its register
@@ -1305,21 +1415,20 @@ public final class SKCrashReporting {
1305
1415
  /// here would deadlock the watchdog against it. The address buffer is
1306
1416
  /// therefore pre-allocated before the suspend.
1307
1417
  ///
1308
- /// Falls back to the watchdog thread's own `Thread.callStackSymbols`
1309
- /// (far less useful, but a signal that an ANR happened) if the main
1310
- /// thread cannot be inspected.
1311
- private func captureMainThreadStack() -> [SKStackFrame] {
1418
+ /// Returns `nil` if the main thread cannot be inspected. It deliberately
1419
+ /// does NOT fall back to the watchdog thread's own stack — that is the
1420
+ /// same few frames for every ANR, so it merged unrelated hangs into one
1421
+ /// issue while looking like real data.
1422
+ private func captureMainThreadStack() -> [SKStackFrame]? {
1312
1423
  // Only ever inspect the main thread from OFF the main thread —
1313
1424
  // suspending yourself never resumes.
1314
- guard !Thread.isMainThread else {
1315
- return parseCallStackSymbols(Thread.callStackSymbols)
1316
- }
1425
+ guard !Thread.isMainThread else { return nil }
1317
1426
 
1318
1427
  var threadList: thread_act_array_t?
1319
1428
  var threadCount: mach_msg_type_number_t = 0
1320
1429
  guard task_threads(mach_task_self_, &threadList, &threadCount) == KERN_SUCCESS,
1321
1430
  let threads = threadList, threadCount > 0 else {
1322
- return parseCallStackSymbols(Thread.callStackSymbols)
1431
+ return nil
1323
1432
  }
1324
1433
  defer {
1325
1434
  let ptr = UnsafeMutableRawPointer(threads)
@@ -1338,9 +1447,7 @@ public final class SKCrashReporting {
1338
1447
  var addresses = [UInt](repeating: 0, count: maxFrames)
1339
1448
  var addressCount = 0
1340
1449
 
1341
- guard thread_suspend(mainThread) == KERN_SUCCESS else {
1342
- return parseCallStackSymbols(Thread.callStackSymbols)
1343
- }
1450
+ guard thread_suspend(mainThread) == KERN_SUCCESS else { return nil }
1344
1451
 
1345
1452
  var pc: UInt = 0
1346
1453
  var lr: UInt = 0
@@ -1419,11 +1526,8 @@ public final class SKCrashReporting {
1419
1526
 
1420
1527
  thread_resume(mainThread)
1421
1528
 
1422
- guard addressCount > 0 else {
1423
- // State capture failed — fall back to the watchdog thread's own
1424
- // symbols as a last-resort hint that an ANR happened.
1425
- return parseCallStackSymbols(Thread.callStackSymbols)
1426
- }
1529
+ // State capture failed — no stack rather than the watchdog's own.
1530
+ guard addressCount > 0 else { return nil }
1427
1531
 
1428
1532
  // Main thread is running again — safe to allocate and symbolicate.
1429
1533
  let appExecutable = Bundle.main.infoDictionary?["CFBundleExecutable"] as? String
@@ -1537,8 +1641,31 @@ public final class SKCrashReporting {
1537
1641
  /// Each line has the format:
1538
1642
  /// `<frame_number> <image_name> <address> <symbol> + <offset>`
1539
1643
  /// e.g. `0 MyApp 0x0000000104a8b1c4 $s5MyApp14ViewControllerC11viewDidLoadyyF + 84`
1644
+ ///
1645
+ /// In-app classification goes through `isInAppImage` — the same rule as
1646
+ /// `symbolicate(address:)` — with the image PATH resolved by `dladdr` on
1647
+ /// the frame's address. Symbol lines carry only the image's basename,
1648
+ /// which cannot tell an embedded framework from a system one. This parser
1649
+ /// only ever sees stacks of the current process, so the addresses are
1650
+ /// live.
1540
1651
  internal func parseCallStackSymbols(_ symbols: [String], returnAddresses: [Int] = []) -> [SKStackFrame] {
1541
- let appExecutable = Bundle.main.infoDictionary?["CFBundleExecutable"] as? String
1652
+ parseCallStackSymbols(
1653
+ symbols,
1654
+ returnAddresses: returnAddresses,
1655
+ appExecutable: Bundle.main.infoDictionary?["CFBundleExecutable"] as? String,
1656
+ appBundlePath: SKCrashReporting.appBundlePath
1657
+ )
1658
+ }
1659
+
1660
+ /// Test seam — the parser with the app identity injected, so in-app
1661
+ /// classification is assertable under `swift test` (where the main
1662
+ /// bundle is the test runner's).
1663
+ internal func parseCallStackSymbols(
1664
+ _ symbols: [String],
1665
+ returnAddresses: [Int] = [],
1666
+ appExecutable: String?,
1667
+ appBundlePath: String
1668
+ ) -> [SKStackFrame] {
1542
1669
 
1543
1670
  return symbols.enumerated().map { index, symbol in
1544
1671
  let trimmed = symbol.trimmingCharacters(in: .whitespaces)
@@ -1570,14 +1697,17 @@ public final class SKCrashReporting {
1570
1697
  rawAddress = addressStr.hasPrefix("0x") ? addressStr : nil
1571
1698
  }
1572
1699
 
1573
- let isInApp: Bool
1574
- if let appExec = appExecutable {
1575
- isInApp = imageName == appExec
1576
- } else {
1577
- isInApp = !imageName.hasPrefix("lib") && !imageName.hasPrefix("_")
1578
- && imageName != "UIKitCore" && imageName != "Foundation"
1579
- && imageName != "CoreFoundation" && imageName != "libdyld.dylib"
1580
- }
1700
+ let addressValue: UInt? = {
1701
+ if index < returnAddresses.count { return UInt(bitPattern: returnAddresses[index]) }
1702
+ guard addressStr.hasPrefix("0x") else { return nil }
1703
+ return UInt(addressStr.dropFirst(2), radix: 16)
1704
+ }()
1705
+ let isInApp = SKCrashReporting.isInAppImage(
1706
+ imagePath: addressValue.flatMap { SKCrashReporting.imagePath(forAddress: $0) },
1707
+ imageName: imageName,
1708
+ appExecutable: appExecutable,
1709
+ appBundlePath: appBundlePath
1710
+ )
1581
1711
 
1582
1712
  return SKStackFrame(
1583
1713
  filename: nil,
@@ -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
+ }