@serfab/cadre-core 0.10.0 → 0.12.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 (145) hide show
  1. package/README.md +255 -255
  2. package/dist/announce-addrs.d.ts +49 -0
  3. package/dist/announce-addrs.js +78 -0
  4. package/dist/announce-addrs.js.map +1 -0
  5. package/dist/cadre-node.d.ts +484 -58
  6. package/dist/cadre-node.js +953 -182
  7. package/dist/cadre-node.js.map +1 -1
  8. package/dist/control-cohort.d.ts +26 -0
  9. package/dist/control-cohort.js +26 -0
  10. package/dist/control-cohort.js.map +1 -1
  11. package/dist/control-database.d.ts +222 -125
  12. package/dist/control-database.js +356 -266
  13. package/dist/control-database.js.map +1 -1
  14. package/dist/control-formation-recorder.d.ts +8 -7
  15. package/dist/control-formation-recorder.js +8 -7
  16. package/dist/control-formation-recorder.js.map +1 -1
  17. package/dist/control-read-retry.d.ts +103 -0
  18. package/dist/control-read-retry.js +145 -0
  19. package/dist/control-read-retry.js.map +1 -0
  20. package/dist/control-retry.d.ts +101 -0
  21. package/dist/control-retry.js +108 -0
  22. package/dist/control-retry.js.map +1 -0
  23. package/dist/control-schema.d.ts +1 -1
  24. package/dist/control-schema.js +805 -774
  25. package/dist/control-schema.js.map +1 -1
  26. package/dist/control-write-retry.d.ts +65 -31
  27. package/dist/control-write-retry.js +33 -103
  28. package/dist/control-write-retry.js.map +1 -1
  29. package/dist/delegate-admission.d.ts +17 -15
  30. package/dist/delegate-admission.js +17 -15
  31. package/dist/delegate-admission.js.map +1 -1
  32. package/dist/index.d.ts +7 -5
  33. package/dist/index.js +18 -9
  34. package/dist/index.js.map +1 -1
  35. package/dist/membership-connection-gater.d.ts +211 -25
  36. package/dist/membership-connection-gater.js +309 -29
  37. package/dist/membership-connection-gater.js.map +1 -1
  38. package/dist/peer-addr-book.d.ts +92 -0
  39. package/dist/peer-addr-book.js +220 -0
  40. package/dist/peer-addr-book.js.map +1 -0
  41. package/dist/peer-record.d.ts +26 -0
  42. package/dist/peer-record.js +32 -0
  43. package/dist/peer-record.js.map +1 -1
  44. package/dist/relay-addrs.d.ts +76 -26
  45. package/dist/relay-addrs.js +115 -27
  46. package/dist/relay-addrs.js.map +1 -1
  47. package/dist/relay-reservation.d.ts +20 -15
  48. package/dist/relay-reservation.js +18 -14
  49. package/dist/relay-reservation.js.map +1 -1
  50. package/dist/seed-bootstrap.d.ts +7 -0
  51. package/dist/seed-bootstrap.js +15 -13
  52. package/dist/seed-bootstrap.js.map +1 -1
  53. package/dist/strand-addr-protocol.js +16 -0
  54. package/dist/strand-addr-protocol.js.map +1 -1
  55. package/dist/strand-backfill.js +13 -4
  56. package/dist/strand-backfill.js.map +1 -1
  57. package/dist/strand-cohort.d.ts +4 -37
  58. package/dist/strand-cohort.js +4 -15
  59. package/dist/strand-cohort.js.map +1 -1
  60. package/dist/strand-database.d.ts +11 -16
  61. package/dist/strand-database.js +19 -7
  62. package/dist/strand-database.js.map +1 -1
  63. package/dist/strand-formation-manager.d.ts +18 -17
  64. package/dist/strand-formation-manager.js +25 -27
  65. package/dist/strand-formation-manager.js.map +1 -1
  66. package/dist/strand-formation-protocol.d.ts +7 -7
  67. package/dist/strand-formation-protocol.js +8 -8
  68. package/dist/strand-formation-protocol.js.map +1 -1
  69. package/dist/strand-instance-manager.d.ts +53 -21
  70. package/dist/strand-instance-manager.js +128 -37
  71. package/dist/strand-instance-manager.js.map +1 -1
  72. package/dist/strand-membership-writer.d.ts +113 -19
  73. package/dist/strand-membership-writer.js +219 -51
  74. package/dist/strand-membership-writer.js.map +1 -1
  75. package/dist/strand-solicitation.d.ts +3 -3
  76. package/dist/strand-solicitation.js +4 -5
  77. package/dist/strand-solicitation.js.map +1 -1
  78. package/dist/strand-wake-protocol.d.ts +47 -2
  79. package/dist/strand-wake-protocol.js +76 -6
  80. package/dist/strand-wake-protocol.js.map +1 -1
  81. package/dist/types.d.ts +107 -54
  82. package/dist/types.js.map +1 -1
  83. package/package.json +8 -7
  84. package/src/announce-addrs.ts +93 -0
  85. package/src/arachnode-stub.ts +159 -159
  86. package/src/bootstrap-peer-store-file.ts +44 -44
  87. package/src/bootstrap-peer-store.ts +172 -172
  88. package/src/cadre-node.ts +1026 -194
  89. package/src/canonical-json.ts +30 -30
  90. package/src/control-authorization.ts +114 -114
  91. package/src/control-cohort.ts +130 -103
  92. package/src/control-database.ts +376 -298
  93. package/src/control-formation-recorder.ts +305 -304
  94. package/src/control-read-retry.ts +167 -0
  95. package/src/control-retry.ts +190 -0
  96. package/src/control-schema.ts +817 -786
  97. package/src/control-stream.ts +205 -205
  98. package/src/control-write-retry.ts +383 -473
  99. package/src/delegate-admission.ts +304 -302
  100. package/src/device-token.ts +94 -94
  101. package/src/diagnostics/connection-path.ts +277 -277
  102. package/src/diagnostics/webrtc-turn-tracker.ts +222 -222
  103. package/src/ed25519-key.ts +134 -134
  104. package/src/enrollment.ts +199 -199
  105. package/src/file-durable-slot.ts +61 -61
  106. package/src/formation-approval.ts +604 -604
  107. package/src/fs-atomic.ts +107 -107
  108. package/src/hibernation-manager.ts +437 -437
  109. package/src/identity-key.ts +109 -109
  110. package/src/index.ts +435 -406
  111. package/src/key-store-file.ts +132 -132
  112. package/src/key-store.ts +99 -99
  113. package/src/membership-connection-gater.ts +368 -39
  114. package/src/node-local-snapshot.ts +260 -260
  115. package/src/peer-addr-book.ts +250 -0
  116. package/src/peer-authorization.ts +259 -259
  117. package/src/peer-record.ts +197 -164
  118. package/src/push-credentials.ts +84 -84
  119. package/src/push-node.ts +64 -64
  120. package/src/push-notifier-apns.ts +247 -247
  121. package/src/push-notifier-fcm.ts +220 -220
  122. package/src/push-notifier-shared.ts +28 -28
  123. package/src/push-notifier.ts +52 -52
  124. package/src/relay-addrs.ts +134 -27
  125. package/src/relay-reservation.ts +22 -17
  126. package/src/seed-bootstrap.ts +15 -15
  127. package/src/seed-trust-policy.ts +140 -140
  128. package/src/strand-addr-protocol.ts +458 -441
  129. package/src/strand-backfill.ts +28 -5
  130. package/src/strand-cohort.ts +38 -77
  131. package/src/strand-database.ts +202 -204
  132. package/src/strand-formation-manager.ts +26 -28
  133. package/src/strand-formation-protocol.ts +692 -692
  134. package/src/strand-instance-manager.ts +636 -553
  135. package/src/strand-member-key.ts +39 -39
  136. package/src/strand-member-registry.ts +182 -182
  137. package/src/strand-membership-writer.ts +1627 -1430
  138. package/src/strand-solicitation.ts +471 -472
  139. package/src/strand-transport-key.ts +58 -58
  140. package/src/strand-wake-payload.ts +32 -32
  141. package/src/strand-wake-protocol.ts +400 -314
  142. package/src/strand-watcher.ts +314 -314
  143. package/src/trusted-owner-store-file.ts +41 -41
  144. package/src/trusted-owner-store.ts +171 -171
  145. package/src/types.ts +1354 -1303
@@ -0,0 +1,167 @@
1
+ import { chainMessages, retryControlOperation } from './control-retry.js';
2
+ import type { ControlRetryOptions } from './control-retry.js';
3
+ import { isUncommittedTransactorAggregate } from './control-write-retry.js';
4
+
5
+ /**
6
+ * Bounded retry for TRANSIENT control-read failures — the classifier and policy behind
7
+ * `ControlDatabase.readRows`, the single funnel every control read passes through.
8
+ *
9
+ * Why this exists: control WRITES have absorbed transient cluster failures since
10
+ * `control-write-retry.ts` landed, but a read had no second chance — one stream reset
11
+ * during a scan ended the read outright (measured: a rigged single `eval` failure killed
12
+ * `queryRevokedStamps` after exactly one attempt while the same injection against `exec`
13
+ * was absorbed). This module gives reads the same bounded re-presentation with a SHORTER
14
+ * deadline and a NARROWER failure set, because the tightest caller deadline over a control
15
+ * read is the inbound admission gate's 2 s fail-open timeout
16
+ * (`ADMISSION_DECISION_TIMEOUT_MS`, `membership-connection-gater.ts`) — a read budget that
17
+ * does not fit inside it with headroom spends its retries after the gate has already
18
+ * admitted.
19
+ *
20
+ * This is deliberately NOT "the write classifier minus its commit veto" — the retriable
21
+ * set differs in both directions (see {@link isRetriableControlReadFailure}). The loop
22
+ * lives in `control-retry.ts`, shared with the write policy; this module owns only the
23
+ * read policy. And like the write side, classification is by TEXT: optimystic's
24
+ * `OptimysticVirtualTable` catches every scan-path error and rethrows
25
+ * `new Error('Query failed: ' + message)` with NO `cause`
26
+ * (`quereus-plugin-optimystic/src/optimystic-module.ts`), so the typed
27
+ * `BlockUnavailableError` and its `reason` field are destroyed before they reach this
28
+ * repo; Quereus then wraps that as `Error during query on table '<T>': …` preserving
29
+ * `cause` (`quereus/src/runtime/emit/scan.ts`). Every matcher fails CLOSED — an upstream
30
+ * rewording stops the retry engaging, it never makes it unsafe.
31
+ */
32
+
33
+ /**
34
+ * Attempts allowed per control read: the first, plus two retries. Attempts are cheap here —
35
+ * the observed transient failure (the transactor's read-phase aggregate off a stream still
36
+ * forming) surfaces in ~25 ms — and {@link CONTROL_READ_RETRY_BUDGET_MS} is what terminates
37
+ * the loop when an attempt is slow instead.
38
+ */
39
+ export const CONTROL_READ_ATTEMPTS = 3;
40
+
41
+ /**
42
+ * Backoff before read retry N, jittered ±50% and capped at the largest base by the shared
43
+ * loop — so worst case 150 ms + 400 ms = 550 ms of total sleep (the second delay's
44
+ * upside jitter is clipped by the cap). Much shorter than the write list because the
45
+ * whole loop must fit under {@link CONTROL_READ_RETRY_BUDGET_MS}; the spec pins that
46
+ * relationship rather than the number.
47
+ */
48
+ export const CONTROL_READ_RETRY_DELAYS_MS: readonly number[] = [100, 400];
49
+
50
+ /**
51
+ * Elapsed-time ceiling on the whole read-retry loop, checked after a failed attempt BEFORE
52
+ * sleeping — so one slow attempt (e.g. a `cohort-unreachable` read that burned the
53
+ * transactor's own deadline) terminates the loop rather than compounding.
54
+ *
55
+ * 1500 ms, sized against `ADMISSION_DECISION_TIMEOUT_MS` (2000 ms): the inbound admission
56
+ * gate reads the control DB and is FAIL-OPEN on both throw and timeout, so a read that
57
+ * outlives the gate's deadline spends its retries after the gate has already admitted an
58
+ * unplaced peer. Under the deadline, a read that succeeds on its second attempt lets the
59
+ * gate make the real decision instead. `control-read-retry.spec.ts` asserts the
60
+ * relationship so a future edit to either constant reddens instead of silently
61
+ * reintroducing the fail-open admit. NOTE: `queryCadrePeers` / `queryPeerRecord` each
62
+ * issue TWO network reads (the revoked-stamp filter plus the row scan) and the budget is
63
+ * per read, so a membership read can spend up to two budgets back to back — still inside
64
+ * 2 s only because each stays well under it. Do not raise these numbers without
65
+ * re-checking against `ADMISSION_DECISION_TIMEOUT_MS`.
66
+ */
67
+ export const CONTROL_READ_RETRY_BUDGET_MS = 1_500;
68
+
69
+ /**
70
+ * The block-unavailability reasons a repeat read can actually improve on, matched against
71
+ * upstream's exact template `Block <id> is unavailable (<reason>): …`
72
+ * (`BlockUnavailableError`, `db-core/src/network/struct.ts`):
73
+ *
74
+ * - **`peers-unreachable`** — part of the cohort answered and part could not be asked, and
75
+ * OTHER coordinators are reachable, so asking one of them can still settle it. Upstream's
76
+ * own definition invites the second attempt.
77
+ * - **`cohort-unreachable`** — the marginal member of the set. Upstream says the answer
78
+ * will not improve until this node's connectivity does — but during bring-up connectivity
79
+ * DOES improve within a second (the boot-time failure shape recorded in
80
+ * `tickets/blocked/control-read-over-fresh-edge-stream-resets`), and the cost of being
81
+ * wrong is bounded by {@link CONTROL_READ_RETRY_BUDGET_MS}, which is the whole reason it
82
+ * is safe to include.
83
+ *
84
+ * Deliberately NOT matched:
85
+ *
86
+ * - **`claimed-elsewhere`** — a cohort peer positively claims the block exists and nobody
87
+ * could corroborate or acquire it. MEASURED not to clear: reissuing the same call every
88
+ * second for 60 s returned the identical error every time (2026-08-20, recorded in the
89
+ * fix ticket). Retrying spends the whole budget and fails anyway; the root cause is
90
+ * upstream and tracked by `tickets/blocked/block-held-by-only-one-machine-is-unreadable`
91
+ * — this retry must not paper over it.
92
+ * - **`unmaterializable`** — records are held locally but cannot be reassembled. A local
93
+ * data problem; a second read reads the same records.
94
+ * - **`Block <id> may be stale`** (`BlockPossiblyStaleError`) — about currency, not
95
+ * existence: a cohort claim no reachable coordinator could confirm or refute will not
96
+ * resolve inside a few hundred milliseconds of backoff.
97
+ * - Anything unmatched. The default is no retry.
98
+ */
99
+ const RETRIABLE_BLOCK_UNAVAILABLE =
100
+ /Block \S+ is unavailable \((?:peers-unreachable|cohort-unreachable)\)/;
101
+
102
+ /** A block-unavailable read failure whose reason a repeat read can improve on. */
103
+ function isRetriableBlockUnavailable(message: string): boolean {
104
+ return RETRIABLE_BLOCK_UNAVAILABLE.test(message);
105
+ }
106
+
107
+ /**
108
+ * Pacing overrides for {@link retryControlRead} — the read twin of
109
+ * `ControlWriteRetryOptions`. Every field defaults to the shipped read policy
110
+ * ({@link CONTROL_READ_ATTEMPTS}, {@link CONTROL_READ_RETRY_DELAYS_MS},
111
+ * {@link isRetriableControlReadFailure}); field shapes and semantics live on the shared
112
+ * {@link ControlRetryOptions}.
113
+ */
114
+ export type ControlReadRetryOptions = ControlRetryOptions;
115
+
116
+ /**
117
+ * Did this control read fail in a way a repeat read can improve on?
118
+ *
119
+ * Two classes, both meaning "the cluster could not be ASKED properly just now":
120
+ *
121
+ * - the transactor's read-phase aggregate (`Some peers did not complete: …[block:…]`),
122
+ * reused verbatim from the write classifier — a `get` batch formats the single-block
123
+ * `[block:` token, and a read can never produce the commit-phase `[blocks:` token, so
124
+ * the write side's indeterminate-commit veto has nothing to veto here (a read commits
125
+ * nothing and re-running it is always safe);
126
+ * - the block-unavailability reasons in {@link RETRIABLE_BLOCK_UNAVAILABLE} (and only
127
+ * those — see its comment for the measured exclusions).
128
+ *
129
+ * Classifies by MESSAGE, walking the `cause` chain with the shared `chainMessages`,
130
+ * because only text survives the trip out of optimystic (see the module comment).
131
+ * Anything that is not an `Error` is never retried.
132
+ */
133
+ export function isRetriableControlReadFailure(error: unknown): boolean {
134
+ if (!(error instanceof Error)) {
135
+ return false;
136
+ }
137
+ return chainMessages(error).some(message =>
138
+ isUncommittedTransactorAggregate(message) || isRetriableBlockUnavailable(message));
139
+ }
140
+
141
+ /**
142
+ * Run `attempt` — a full drain of one control read — up to
143
+ * {@link CONTROL_READ_ATTEMPTS} times, retrying only failures
144
+ * {@link isRetriableControlReadFailure} calls transient, and only while
145
+ * {@link CONTROL_READ_RETRY_BUDGET_MS} has not elapsed.
146
+ *
147
+ * Reads are idempotent, so `attempt` needs no atomicity contract — but it must be a
148
+ * COLLECTING drain, not a live iterator: a half-consumed iterator cannot be retried
149
+ * without re-yielding rows the caller already saw, which is why
150
+ * `ControlDatabase.readRows` materializes before this loop ever sees a failure.
151
+ *
152
+ * On exhaustion the LAST error is rethrown unchanged. Log lines carry the
153
+ * `Control read [<label>] …` prefix so a read's retries can be attributed among the
154
+ * several reads in flight concurrently in a real party.
155
+ */
156
+ export function retryControlRead<T>(
157
+ attempt: () => Promise<T>,
158
+ options: ControlReadRetryOptions = {}
159
+ ): Promise<T> {
160
+ return retryControlOperation(attempt, {
161
+ attempts: CONTROL_READ_ATTEMPTS,
162
+ delaysMs: CONTROL_READ_RETRY_DELAYS_MS,
163
+ budgetMs: CONTROL_READ_RETRY_BUDGET_MS,
164
+ isRetriable: isRetriableControlReadFailure,
165
+ logPrefix: 'Control read',
166
+ }, options);
167
+ }
@@ -0,0 +1,190 @@
1
+ import debug from 'debug';
2
+ import { unwrapError } from '@quereus/quereus';
3
+
4
+ const log = debug('sereus:cadre:control-db');
5
+
6
+ /**
7
+ * The bounded retry loop shared by the control plane's transient-failure policies:
8
+ * writes (`control-write-retry.ts`, behind `ControlDatabase.lockedWithRetry`) and reads
9
+ * (`control-read-retry.ts`, behind `ControlDatabase.readRows`). One loop, two policy
10
+ * modules — they differ in classifier, attempt count, backoff and elapsed budget, but the
11
+ * loop mechanics (jittered capped backoff, budget checked after a failed attempt BEFORE
12
+ * sleeping, last error rethrown unchanged) are deliberately identical so a fix to one
13
+ * cannot silently miss the other.
14
+ *
15
+ * The log prefix is part of the policy because the write funnel's lines are asserted
16
+ * byte-identically by `control-write-degraded-cohort-member.integration.ts` — extracting
17
+ * this loop must not move a single character of them.
18
+ */
19
+
20
+ /** A retry policy: what to retry, how often, and under which elapsed-time ceiling. */
21
+ export interface ControlRetryPolicy {
22
+ /** Total attempts, first included (floored at 1 by the loop). */
23
+ attempts: number;
24
+ /**
25
+ * Backoff base before retry N (last entry repeats), jittered ±50% — so the jitter can
26
+ * never floor a delay to zero — and each single sleep additionally capped at the
27
+ * LARGEST delay in the list, so a `stop()` racing a backoff is never held up longer
28
+ * than that. There is no `AbortSignal` at this seam to cancel a sleep outright; the
29
+ * cap is the substitute, deliberately not plumbing one through every call path.
30
+ */
31
+ delaysMs: readonly number[];
32
+ /**
33
+ * Elapsed-time ceiling on the whole loop, measured from the START of the first attempt
34
+ * and checked after a failed attempt BEFORE sleeping — so one slow attempt terminates
35
+ * the loop rather than compounding, and retry adds ZERO latency to the case where it
36
+ * cannot help.
37
+ */
38
+ budgetMs: number;
39
+ /** Which failures are transient enough to re-present. */
40
+ isRetriable: (error: unknown) => boolean;
41
+ /**
42
+ * Subject of every log line the loop emits (`<prefix>[ [<label>]] …`). Defaults to
43
+ * `'Control write'`, which keeps the write funnel's lines byte-identical to what it
44
+ * logged before this loop was shared out of `control-write-retry.ts`.
45
+ */
46
+ logPrefix?: string;
47
+ }
48
+
49
+ /**
50
+ * Per-call overrides applied over a policy. Production callers pass at most `label`
51
+ * (usually via the policy module's wrapper); specs inject a recorded `sleep`, a shorter
52
+ * delay list, or a fake clock so no test ever waits out a real backoff.
53
+ */
54
+ export interface ControlRetryOptions {
55
+ /**
56
+ * Total attempts, first included. Default: the policy's, floored at 1 — below that
57
+ * the loop would run the body zero times and rethrow a `lastError` nobody set.
58
+ */
59
+ attempts?: number;
60
+ /** Backoff base before retry N (last entry repeats). Default: the policy's. */
61
+ delaysMs?: readonly number[];
62
+ /** Which failures are transient enough to re-present. Default: the policy's classifier. */
63
+ isRetriable?: (error: unknown) => boolean;
64
+ /**
65
+ * Operation label stamped into every log line this loop emits (rendered as
66
+ * `<prefix> [<label>] …`), and NOTHING else — no behavioural effect. The debug log is
67
+ * the only surface where the loop's decisions are observable (the rethrown error is
68
+ * unchanged and no attempt counter is exposed), and several operations retry
69
+ * CONCURRENTLY in a real party, so an unlabelled line cannot be attributed. The
70
+ * degraded-cohort scenario asserts on the write funnel's lines per-operation.
71
+ */
72
+ label?: string;
73
+ /** The sleep primitive. Default: `setTimeout`. */
74
+ sleep?: (ms: number) => Promise<void>;
75
+ /** Clock for the elapsed-budget check. Default: `Date.now`. */
76
+ now?: () => number;
77
+ }
78
+
79
+ /**
80
+ * Run `attempt` up to the policy's attempt count, retrying only failures its classifier
81
+ * calls transient, and only while its elapsed budget has not run out.
82
+ *
83
+ * `attempt` must be safe to re-run — for writes that means atomic (a failed cluster write
84
+ * rolls back, nothing half-applies; the contract on `ControlDatabase.withWriteLock`), for
85
+ * reads it holds trivially. The backoff sleeps happen with NO lock held; a caller that
86
+ * locks takes and releases its lock inside `attempt`.
87
+ *
88
+ * On exhaustion (attempts or budget) the LAST error is rethrown unchanged — never
89
+ * wrapped, so the exact messages downstream code and the integration scenarios assert on
90
+ * survive. A non-retriable failure propagates from the attempt that raised it.
91
+ */
92
+ export async function retryControlOperation<T>(
93
+ attempt: () => Promise<T>,
94
+ policy: ControlRetryPolicy,
95
+ options: ControlRetryOptions = {}
96
+ ): Promise<T> {
97
+ const attempts = Math.max(1, options.attempts ?? policy.attempts);
98
+ const delays = options.delaysMs ?? policy.delaysMs;
99
+ const isRetriable = options.isRetriable ?? policy.isRetriable;
100
+ const sleep = options.sleep ?? defaultSleep;
101
+ const now = options.now ?? Date.now;
102
+ const prefix = policy.logPrefix ?? 'Control write';
103
+ // Empty when unlabelled, so an unlabelled line is byte-identical to what the write
104
+ // loop logged before labels existed.
105
+ const tag = options.label ? ` [${options.label}]` : '';
106
+ const start = now();
107
+ let lastError: unknown;
108
+ let attemptsMade = 0;
109
+ for (let attemptNumber = 1; attemptNumber <= attempts; attemptNumber++) {
110
+ attemptsMade = attemptNumber;
111
+ try {
112
+ const result = await attempt();
113
+ if (attemptNumber > 1) {
114
+ log('%s%s committed on attempt %d/%d', prefix, tag, attemptNumber, attempts);
115
+ }
116
+ return result;
117
+ } catch (error) {
118
+ if (!isRetriable(error)) {
119
+ // The ONLY trace that this funnel saw a failure and declined it. Without it the
120
+ // log is silent either way, so "the classifier vetoed this one" is
121
+ // indistinguishable from "the retry is not wired into this path at all".
122
+ log('%s%s failed non-transiently on attempt %d/%d, not retried here: %s',
123
+ prefix, tag, attemptNumber, attempts, error);
124
+ throw error;
125
+ }
126
+ lastError = error;
127
+ if (attemptNumber === attempts) {
128
+ break;
129
+ }
130
+ const elapsed = now() - start;
131
+ if (elapsed >= policy.budgetMs) {
132
+ break;
133
+ }
134
+ const delay = jitteredDelay(delays, attemptNumber);
135
+ log('%s%s failed transiently (attempt %d/%d), retrying in %d ms: %s',
136
+ prefix, tag, attemptNumber, attempts, delay, error);
137
+ await sleep(delay);
138
+ }
139
+ }
140
+ log('%s%s failed after %d/%d attempt(s): %s', prefix, tag, attemptsMade, attempts, lastError);
141
+ throw lastError;
142
+ }
143
+
144
+ /**
145
+ * Every message in the failure's `cause` chain — the shared substrate both classifiers
146
+ * match against, since the failures they care about are not recognisable by type (the
147
+ * typed errors are destroyed on the way out of optimystic; only text survives).
148
+ *
149
+ * `unwrapError` declares its `message` as `string`, but it follows `.cause` without checking
150
+ * what that holds — a chain link that is not an `Error` (a stream rejected with a bare string
151
+ * reason, an `AbortSignal.reason` that is a plain object) yields `undefined` there, and
152
+ * calling `.includes` on it would throw a `TypeError` out of a classifier, INSIDE
153
+ * {@link retryControlOperation}'s catch, replacing the real failure with a confusing one.
154
+ * Non-strings are dropped: a link nobody can read is a link that matches nothing, which is
155
+ * already the conservative answer.
156
+ *
157
+ * NOTE: a cause chain with a CYCLE would spin forever inside `unwrapError` itself. No error
158
+ * in this repo builds one; if a hang ever localises to a control retry path, look there.
159
+ */
160
+ export function chainMessages(error: Error): string[] {
161
+ return unwrapError(error)
162
+ .map(({ message }) => message)
163
+ .filter(message => typeof message === 'string');
164
+ }
165
+
166
+ /**
167
+ * Backoff for the retry that follows attempt `attemptNumber`: the matching base delay
168
+ * (last entry repeats), jittered ±50%, then capped at the list's largest base so no single
169
+ * sleep exceeds it (see {@link ControlRetryPolicy.delaysMs} for why). `Math.random` is
170
+ * fine here — the jitter only de-synchronizes concurrent retriers, nothing is derived
171
+ * from it.
172
+ *
173
+ * NOTE: the cap bites on the LAST delay, whose base IS the largest, so ~half of those sleeps
174
+ * land exactly on the cap rather than spread — de-synchronization is only partial there.
175
+ * Harmless while retriers are a handful of party nodes whose attempts already start seconds
176
+ * apart; if a party ever retries in a tight synchronized herd, raise the cap above the
177
+ * largest base instead of jittering about it.
178
+ */
179
+ function jitteredDelay(delays: readonly number[], attemptNumber: number): number {
180
+ if (delays.length === 0) {
181
+ return 0;
182
+ }
183
+ const base = delays[Math.min(attemptNumber - 1, delays.length - 1)]!;
184
+ const jittered = base * (0.5 + Math.random());
185
+ return Math.min(jittered, Math.max(...delays));
186
+ }
187
+
188
+ function defaultSleep(ms: number): Promise<void> {
189
+ return new Promise(resolve => setTimeout(resolve, ms));
190
+ }