@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.
- package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
- package/android/vendor/java/com/appswissknife/net/IngestClient.kt +127 -6
- package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +6 -0
- package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
- package/ios/vendor/SwissKnifeiOS/Net/BackendBackoffGate.swift +182 -0
- package/ios/vendor/SwissKnifeiOS/Net/BackendHttpClient.swift +164 -8
- package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +418 -58
- package/lib/commonjs/modules/crash-reporting.js +199 -10
- package/lib/commonjs/modules/crash-reporting.js.map +1 -1
- package/lib/module/modules/crash-reporting.js +199 -10
- package/lib/module/modules/crash-reporting.js.map +1 -1
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -1
- package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/modules/crash-reporting.ts +200 -11
|
@@ -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.
|
|
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.
|
|
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
|
|
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(
|
|
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.
|
|
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
|
-
|
|
517
|
-
|
|
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.
|
|
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?
|
|
@@ -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
|
+
}
|