@serfab/cadre-core 1.10.0 → 1.11.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 (61) hide show
  1. package/dist/cadre-node.d.ts +0 -27
  2. package/dist/cadre-node.js +2 -94
  3. package/dist/cadre-node.js.map +1 -1
  4. package/dist/control-schema.js +1066 -1066
  5. package/dist/diagnostics/connection-path.d.ts +1 -18
  6. package/dist/diagnostics/connection-path.js +1 -20
  7. package/dist/diagnostics/connection-path.js.map +1 -1
  8. package/dist/identity-key.d.ts +0 -30
  9. package/dist/identity-key.js +7 -40
  10. package/dist/identity-key.js.map +1 -1
  11. package/dist/index.d.ts +3 -2
  12. package/dist/index.js +6 -4
  13. package/dist/index.js.map +1 -1
  14. package/dist/relay-stun.d.ts +24 -0
  15. package/dist/relay-stun.js +51 -0
  16. package/dist/relay-stun.js.map +1 -0
  17. package/dist/seed-bootstrap.js +4 -4
  18. package/dist/strand-membership-writer.js +32 -32
  19. package/package.json +2 -2
  20. package/src/cadre-node.ts +8654 -8753
  21. package/src/control-authorization.ts +117 -117
  22. package/src/control-cohort.ts +128 -128
  23. package/src/control-formation-recorder.ts +353 -353
  24. package/src/control-read-retry.ts +216 -216
  25. package/src/control-schema.ts +1078 -1078
  26. package/src/control-write-retry.ts +567 -567
  27. package/src/diagnostics/connection-path.ts +1 -29
  28. package/src/formation-approval.ts +610 -610
  29. package/src/hibernation-manager.ts +638 -638
  30. package/src/identity-key.ts +7 -62
  31. package/src/index.ts +644 -647
  32. package/src/invitation-bootstrap.ts +40 -40
  33. package/src/joined-strand-store.ts +498 -498
  34. package/src/link-budget.ts +684 -684
  35. package/src/membership-connection-gater.ts +570 -570
  36. package/src/node-local-snapshot.ts +298 -298
  37. package/src/peer-dial.ts +315 -315
  38. package/src/peer-join-backfill.ts +710 -710
  39. package/src/pending-join-runner.ts +735 -735
  40. package/src/relay-reservation.ts +1121 -1121
  41. package/src/relay-server.ts +98 -98
  42. package/src/relay-stun.ts +58 -0
  43. package/src/seed-bootstrap.ts +1448 -1448
  44. package/src/strand-addr-protocol.ts +547 -547
  45. package/src/strand-database.ts +287 -287
  46. package/src/strand-first-sync-gate.ts +391 -391
  47. package/src/strand-formation-deadlines.ts +227 -227
  48. package/src/strand-formation-manager.ts +725 -725
  49. package/src/strand-fret-addrs.ts +145 -145
  50. package/src/strand-instance-manager.ts +1789 -1789
  51. package/src/strand-membership-writer.ts +1974 -1974
  52. package/src/strand-network-state-file.ts +40 -40
  53. package/src/strand-network-state.ts +243 -243
  54. package/src/strand-revocation-enforcer.ts +654 -654
  55. package/src/strand-solicitation.ts +532 -532
  56. package/src/strand-wake-protocol.ts +401 -401
  57. package/src/types.ts +2222 -2222
  58. package/dist/diagnostics/webrtc-turn-tracker.d.ts +0 -50
  59. package/dist/diagnostics/webrtc-turn-tracker.js +0 -196
  60. package/dist/diagnostics/webrtc-turn-tracker.js.map +0 -1
  61. package/src/diagnostics/webrtc-turn-tracker.ts +0 -222
@@ -1,1121 +1,1121 @@
1
- /**
2
- * Relay reservation for nodes that reserve through the SEARCH listen addr — the
3
- * dial, the explicit reservation request, the retry loop that keeps it, and the
4
- * (live) status derivation.
5
- *
6
- * `@libp2p/circuit-relay-v2`'s listener branches on the SHAPE of the listen
7
- * address:
8
- *
9
- * | listen addr | libp2p behaviour | unreachable relay |
10
- * | ------------------------------------------------- | ------------------------------------------------------------------------------------ | -------------------------- |
11
- * | `<dial addr>/p2p/<relayPeerId>/p2p-circuit` | CONFIGURED reservation: dial that exact relay and reserve, or fail | `listen()` throws |
12
- * | bare `/p2p-circuit` | SEARCH mode: register a pending reservation, to be filled by relay discovery | nothing throws, no reserve |
13
- *
14
- * A search listener needs someone to (a) dial the relay and (b) fill the pending
15
- * reservation it created, then report whether one actually landed. That is this
16
- * module. It is **fail-soft by construction**: nothing here throws.
17
- *
18
- * EVERY cadre CONTROL node now takes that route — `network.relayAddrs` resolves
19
- * to the bare search entry (`relay-addrs.ts` → `resolveListenAddrs`) and
20
- * `CadreNode.start()` drives this module once the control database is up. The
21
- * configured shape would dial the relay from inside `libp2p.start()`, putting a
22
- * sibling in this node's cohort before its own control database existed, and a
23
- * sibling that has not yet replicated this node's `CadrePeer` row correctly
24
- * refuses its control-DB streams — which killed `start()` outright.
25
- *
26
- * So the two shapes are no longer alternative ROUTES, only alternative failure
27
- * postures on top of the same drive: a node that names `network.relayAddrs` gets
28
- * a `RelayReservationFailedError` out of `start()` when the first attempt lands
29
- * nothing (fail-fast, the operator asked for this relay), while a node that calls
30
- * `CadreNode.reserveRelays()` itself gets a non-`reserved` status and stays up
31
- * (fail-soft, the browser-tab posture). `network.requireRelay: false` gives a
32
- * CONFIGURED relay the fail-soft posture too, for a node that must boot with no
33
- * network at all — same drive, same supervisor, only the throw is dropped.
34
- * Configuring both is now redundant, not fatal.
35
- *
36
- * STRAND nodes take the same route, ONE supervisor PER RELAY
37
- * (`strand-instance-manager.ts` → `buildStrandRuntime`): each configured relay
38
- * gets its own bare `/p2p-circuit` listener (`strand-network-config.ts`) and its
39
- * own {@link superviseRelayReservation} over just that relay's addr, fail-soft
40
- * like the browser tab. The configured shape they used to take
41
- * (`<relay>/p2p-circuit`, reserved from inside `libp2p.start()`) is gone from
42
- * cadre-built nodes entirely, because it loses its address and never recovers in
43
- * three situations — the relay restarts, either side hangs up the relay
44
- * connection, and libp2p's OWN reservation refresh (which removes the reservation
45
- * before re-creating it, and a configured listener republishes only from inside
46
- * its own `listen()`). The last one needs no network event at all: at the relay
47
- * default TTL of two hours every configured-shape node went undialable ~1 h 55 min
48
- * after reserving. A search listener republishes on `relay:created-reservation`
49
- * for its own pending id, which the refresh re-queues, and the supervisor covers
50
- * the other two.
51
- *
52
- * Because a strand node runs one supervisor per relay, "is the reservation held"
53
- * is asked PER RELAY ({@link circuitMultiaddrsVia}): relay X's supervisor must not
54
- * be satisfied by relay Y's circuit addr, or it would never re-drive X.
55
- *
56
- * ⚠️ WHY THE RESERVATION IS REQUESTED EXPLICITLY RATHER THAN LEFT TO DISCOVERY.
57
- * libp2p fills a search listener's pending reservation from `RelayDiscovery`,
58
- * which nominates a peer only once it can see the relay-hop protocol id in that
59
- * peer's PEER-STORE protocol list — and that list is written exclusively by the
60
- * IDENTIFY handshake. `@optimystic/db-p2p` gives every cadre node a
61
- * network-namespaced identify protocol id (`/optimystic/control-<partyId>/id/1.0.0`)
62
- * while the relay `ops/docker/libp2p-infra` deploys runs stock identify
63
- * (`/ipfs/id/1.0.0`), so the two never identify each other, the peer store stays
64
- * empty of protocols, and discovery never nominates the relay. The TCP/WebSocket
65
- * connection itself is fine, which is why leaving it to discovery surfaced as a
66
- * generic timeout.
67
- *
68
- * Identify is incidental to relaying, though: the reservation
69
- * (`/libp2p/circuit/relay/0.2.0/hop`), a third peer's CONNECT through the relay,
70
- * and the STOP handler on this node all use STOCK, un-namespaced protocol ids the
71
- * deployed relay already serves. Discovery's only job is to GUESS which connected
72
- * peer is a relay, and this module does not need to guess — it was handed the
73
- * relay's address. So it asks the relay for a slot directly, via the
74
- * circuit-relay transport's own reservation store.
75
- *
76
- * Status is derived from the node's LIVE multiaddrs on every read rather than
77
- * cached at drive time: when a relay restarts or the connection drops, libp2p's
78
- * listener clears its listening addrs and the circuit multiaddr disappears, so a
79
- * cached snapshot would keep claiming `reserved` for a node nothing can dial.
80
- *
81
- * And because discovery is out of reach, nothing would ever ASK again either —
82
- * so {@link driveRelayReservation} stays a single-shot primitive and
83
- * {@link superviseRelayReservation} owns the retry cadence on top of it. That
84
- * loop is what makes a lost reservation recover without a page reload. Single-shot
85
- * but not unstoppable: the primitive takes an `AbortSignal` and the loop trips it
86
- * from `stop()`, because a drive left running against a node being torn down both
87
- * logs failures that read as real and — through the timers it still holds — keeps
88
- * the process alive for the rest of its `timeoutMs`.
89
- *
90
- * One measured refinement to "out of reach": libp2p 3.1.3's `connection.newStream`
91
- * records every protocol OUR OWN outbound stream negotiated into the peer store, so
92
- * the explicit reservation request writes the relay-hop protocol id against the
93
- * relay itself. From then on, discovery CAN refill a freed slot on its own — but
94
- * only when the relay answers at that moment (a hangup while the relay stays up;
95
- * measured at ~25 ms). A relay that is down when the slot frees fails that one
96
- * discovery attempt, which poisons the store's `relayFilter` against it, and
97
- * nothing in libp2p tries again: a relay RESTART still needs the supervisor, which
98
- * un-poisons the filter before every attempt ({@link clearRelayFilterEntry}). Two
99
- * mechanisms in production, one guarantee; the specs disable discovery's half
100
- * (`forgetRelayProtocol` in `relay-reservation.spec.ts`) so they prove the
101
- * supervisor's.
102
- */
103
-
104
- import debug from 'debug';
105
- import { multiaddr } from '@multiformats/multiaddr';
106
- import { peerIdFromString } from '@libp2p/peer-id';
107
- import type { Libp2p, PeerId } from '@libp2p/interface';
108
- import { trailingPeerId } from './peer-record.js';
109
- import { relayReservationBudgetMs } from './link-budget.js';
110
-
111
- const log = debug('sereus:cadre:relay-reservation');
112
-
113
- /**
114
- * Relay-reservation posture for a node that reserves through the SEARCH listen
115
- * addr (bare `/p2p-circuit`) — every cadre control node, whether its relays came
116
- * from `network.relayAddrs` or from an explicit `CadreNode.reserveRelays()` call.
117
- * - `none` — no relay addrs supplied; the node is undialable by design.
118
- * - `dialing` — a drive is in flight.
119
- * - `reserved` — the node currently holds at least one `/p2p-circuit` addr.
120
- * - `retrying` — no reservation right now, but a {@link RelayReservationSupervisor}
121
- * has the next attempt scheduled. Recoverable without a caller.
122
- * - `error` — no reservation, and NOBODY IS GOING TO TRY AGAIN: no supervisor
123
- * is running (or there is no node at all).
124
- */
125
- export type RelayReservationStatus = 'none' | 'dialing' | 'reserved' | 'retrying' | 'error';
126
-
127
- export interface RelayReservationState {
128
- status: RelayReservationStatus;
129
- /** The relay multiaddrs this node was asked to reserve through. */
130
- addrs: string[];
131
- /** LIVE `/p2p-circuit` multiaddrs, recomputed on every read. */
132
- circuitAddrs: string[];
133
- error: string | null;
134
- /**
135
- * Epoch ms of the supervisor's next scheduled tick, or `null` when a drive is
136
- * in flight, no supervisor is running, or no addrs were supplied. A UI can turn
137
- * this into "reconnecting, next try in 8s" rather than showing a bare error for
138
- * a node that is in fact recovering.
139
- */
140
- retryAtMs: number | null;
141
- }
142
-
143
- /**
144
- * How long {@link driveRelayReservation} waits for a reservation to appear, at the DEFAULT
145
- * declared link round trip: `RELAY_RESERVATION_ROUND_TRIPS` (4) x `DECLARED_LINK_ROUND_TRIP_MS`
146
- * (3500 ms), plus 2 x `ADMISSION_DECISION_TIMEOUT_MS` (2000 ms) for a party-run relay's
147
- * connection and reservation decisions, = 18 000 ms (`relayReservationBudgetMs`), where it was a
148
- * fixed 10_000 before it was derived.
149
- *
150
- * Counted rather than chosen because this one deadline bounds the whole drive — dial the relay,
151
- * request the reservation, wait — and each of those costs a fixed number of exchanges, not a
152
- * fixed number of milliseconds. `link-budget.ts` carries the counts, the measurement behind
153
- * them, and what still fails at the supported link whatever this says.
154
- *
155
- * A host on a slower link moves it by declaring `NetworkConfig.linkRoundTripMs`, which both
156
- * call sites thread in (`CadreNode.reserveRelays` for the control node,
157
- * `StrandInstanceManager`'s per-relay supervisors for a strand). This constant is the fallback
158
- * for a caller that declares nothing.
159
- */
160
- export const DEFAULT_RELAY_RESERVE_TIMEOUT_MS = relayReservationBudgetMs();
161
- export const DEFAULT_RELAY_RESERVE_POLL_MS = 250;
162
-
163
- export interface RelayReserveOptions {
164
- timeoutMs?: number;
165
- pollMs?: number;
166
- /**
167
- * Ends an in-flight drive early. Aborting is not a failure: the drive returns
168
- * `{ error: null, cancelled: true }` and clears every timer it holds, so the
169
- * process is free to exit immediately instead of trailing the teardown that
170
- * cancelled it.
171
- */
172
- signal?: AbortSignal;
173
- }
174
-
175
- /** What one {@link driveRelayReservation} came back with. */
176
- export interface RelayReserveResult {
177
- /** Why no reservation landed; `null` when one did — or when the drive was cancelled. */
178
- error: string | null;
179
- /**
180
- * The drive ended because its caller's `signal` tripped, not because of anything
181
- * the relay did. Separate from `error` because `error: null` means "a reservation
182
- * landed" and a cancelled drive landed nothing: folded together, a caller would
183
- * read cancellation as success. `cancelled: true` always implies `error: null`.
184
- */
185
- cancelled: boolean;
186
- }
187
-
188
- /**
189
- * The slice of `@libp2p/utils`' `Filter` (a cuckoo filter) that the reservation
190
- * store uses to remember relays whose reservation request failed. `remove` is
191
- * OPTIONAL on that interface, so every use here has to cope with its absence —
192
- * see {@link clearRelayFilterEntry}.
193
- */
194
- export interface RelayFilterLike {
195
- has(item: Uint8Array): boolean;
196
- remove?(item: Uint8Array): boolean;
197
- }
198
-
199
- /**
200
- * The slice of `@libp2p/circuit-relay-v2`'s `ReservationStore` this module drives.
201
- * Declared structurally because the class is internal to that package: naming only
202
- * the members we call keeps the coupling small, explicit and greppable, and lets
203
- * {@link findCircuitRelayTransport} duck-type rather than brand-match.
204
- *
205
- * `relayFilter` is optional because it is not required to DRIVE a reservation,
206
- * only to RE-drive one (see {@link clearRelayFilterEntry}); a libp2p version that
207
- * renames or drops it must degrade, not break.
208
- */
209
- export interface RelayReservationStoreLike {
210
- addRelay(peerId: PeerId, type: 'discovered' | 'configured'): Promise<unknown>;
211
- hasReservation(peerId: PeerId): boolean;
212
- relayFilter?: RelayFilterLike;
213
- }
214
-
215
- /** The slice of libp2p's circuit-relay transport that owns the reservation store. */
216
- export interface CircuitRelayTransportLike {
217
- reservationStore: RelayReservationStoreLike;
218
- }
219
-
220
- /** `components` is a real field on libp2p's node class but not on the `Libp2p` interface. */
221
- interface Libp2pComponentsLike {
222
- components?: {
223
- transportManager?: {
224
- getTransports?: () => readonly unknown[];
225
- };
226
- };
227
- }
228
-
229
- /**
230
- * The node's `/p2p-circuit` multiaddrs — the addresses a peer can dial it at
231
- * while it holds a relay reservation. Empty means "not dialable via a relay
232
- * right now", which is exactly what makes {@link resolveRelayReservationState}
233
- * live rather than a stale snapshot.
234
- */
235
- export function circuitMultiaddrs(node: Libp2p): string[] {
236
- return node
237
- .getMultiaddrs()
238
- .map((ma) => ma.toString())
239
- .filter((addr) => addr.includes('/p2p-circuit'));
240
- }
241
-
242
- /**
243
- * The node's `/p2p-circuit` multiaddrs THROUGH the relays `addrs` name — the ones
244
- * whose `/p2p/<relayPeerId>/p2p-circuit` component names one of them. This is the
245
- * "held" question a supervisor over a SUBSET of the node's relays has to ask: a
246
- * strand node runs one supervisor per relay, and relay X's supervisor must not be
247
- * satisfied by relay Y's addr, or a lost X is never re-driven.
248
- *
249
- * Falls back to EVERY circuit addr when any entry names no relay peer id (no
250
- * `/p2p/` component, or unparsable): such an addr can still be dialed and reserved
251
- * through, but the addr it earns cannot be attributed to it, so "any circuit addr"
252
- * is the only answer that does not mark a live reservation as lost. The control
253
- * node passes its whole relay list, so its answer is the same either way.
254
- */
255
- export function circuitMultiaddrsVia(node: Libp2p, addrs: readonly string[]): string[] {
256
- const held = circuitMultiaddrs(node);
257
- const relayIds = addrs.map(relayPeerIdOf);
258
- if (relayIds.some((id) => id === null)) {
259
- return held;
260
- }
261
- return held.filter((circuit) => relayIds.includes(relayPeerIdOf(circuit)));
262
- }
263
-
264
- /**
265
- * The NORMALIZED peer id of the relay `addr` names: the `/p2p/` component just
266
- * before `/p2p-circuit` when there is one, else the trailing `/p2p/` component
267
- * (a relay DIAL addr). `null` when there is none, or `addr` does not parse.
268
- *
269
- * Normalized through `peerIdFromString(…).toString()` so a relay written in a
270
- * different encoding than libp2p publishes (a CID form, say) still matches.
271
- */
272
- function relayPeerIdOf(addr: string): string | null {
273
- try {
274
- const components = multiaddr(addr).getComponents();
275
- const circuitIdx = components.findIndex((c) => c.name === 'p2p-circuit');
276
- const relayScope = circuitIdx >= 0 ? components.slice(0, circuitIdx) : components;
277
- const raw = trailingPeerId(multiaddr(relayScope));
278
- return raw === null ? null : peerIdFromString(raw).toString();
279
- } catch {
280
- return null;
281
- }
282
- }
283
-
284
- /**
285
- * The running node's circuit-relay transport, or `null` when it has none.
286
- *
287
- * There is no public libp2p API for "reserve on THIS specific relay", so this
288
- * reaches through `node.components.transportManager` — libp2p's internal layout.
289
- * That coupling is deliberate and bounded: every step is optional-chained and the
290
- * whole thing returns `null` rather than throwing, and a spec pins the seam so a
291
- * libp2p upgrade that moves it fails loudly instead of silently reverting this
292
- * module to the discovery wait that never fires.
293
- */
294
- export function findCircuitRelayTransport(node: Libp2p): CircuitRelayTransportLike | null {
295
- for (const transport of nodeTransports(node)) {
296
- const store = (transport as { reservationStore?: unknown }).reservationStore;
297
- if (isReservationStore(store)) {
298
- return { reservationStore: store };
299
- }
300
- }
301
- return null;
302
- }
303
-
304
- function nodeTransports(node: Libp2p): readonly unknown[] {
305
- const manager = (node as Libp2p & Libp2pComponentsLike).components?.transportManager;
306
- if (typeof manager?.getTransports !== 'function') {
307
- log('No transportManager.getTransports() on this node — libp2p internals moved?');
308
- return [];
309
- }
310
- try {
311
- return manager.getTransports();
312
- } catch (err) {
313
- log('transportManager.getTransports() threw: %o', err);
314
- return [];
315
- }
316
- }
317
-
318
- function isReservationStore(value: unknown): value is RelayReservationStoreLike {
319
- if (typeof value !== 'object' || value === null) {
320
- return false;
321
- }
322
- const store = value as Partial<RelayReservationStoreLike>;
323
- return typeof store.addRelay === 'function' && typeof store.hasReservation === 'function';
324
- }
325
-
326
- /** Sentinel resolved by the wait arm of {@link requestOneReservation}'s race. */
327
- const WAIT_OVER = Symbol('relay-reservation-wait-over');
328
-
329
- /** A relay that answered its dial, paired with the address it was dialed at. */
330
- interface ConnectedRelay {
331
- addr: string;
332
- peerId: PeerId;
333
- }
334
-
335
- /**
336
- * Whether `signal` has been aborted.
337
- *
338
- * A function rather than an inline `signal?.aborted` because a signal's `aborted` flag
339
- * is a readonly boolean: one `if (signal?.aborted)` narrows every LATER read of it
340
- * to `false`, and TypeScript then rejects the re-check as a comparison that can
341
- * never hold. Re-checking after each await is exactly what cancellation is, so the
342
- * narrowing is the thing that is wrong, not the check.
343
- */
344
- function aborted(signal: AbortSignal | undefined): boolean {
345
- return signal !== undefined && signal.aborted;
346
- }
347
-
348
- /**
349
- * `setTimeout` as a promise, cut short by `signal`.
350
- *
351
- * EVERY wait inside a drive routes through here, because a wait that merely LOSES
352
- * a `Promise.race` leaves its timer pending — and a pending timer keeps a Node
353
- * process alive for the rest of its duration, which is exactly the delay a
354
- * cancelled drive exists to shed. So the timer is cleared on both endings, not
355
- * only on its own.
356
- *
357
- * NOTE: no spec catches a wait that skips this helper. The cancellation specs
358
- * assert prompt RETURN, which a `Promise.race` gives with its losing timer still
359
- * pending — only the process actually exiting proves the clearing, and that was
360
- * measured by hand rather than pinned. If a wait is ever added outside this
361
- * helper, pin it with a spawned-child process-exit test instead.
362
- */
363
- function delay(ms: number, signal?: AbortSignal): Promise<void> {
364
- if (aborted(signal)) {
365
- return Promise.resolve();
366
- }
367
- return new Promise((resolve) => {
368
- const finish = (): void => {
369
- clearTimeout(timer);
370
- signal?.removeEventListener('abort', finish);
371
- resolve();
372
- };
373
- const timer = setTimeout(finish, ms);
374
- signal?.addEventListener('abort', finish, { once: true });
375
- });
376
- }
377
-
378
- /**
379
- * Relay `from`'s abort into `to`, and hand back the detach that must run on every
380
- * exit path.
381
- *
382
- * By hand rather than through `AbortSignal.any`, for the same reason this module
383
- * builds its deadline from an explicit `AbortController` rather than
384
- * `AbortSignal.timeout`: React Native/Hermes runs this same code, and `any` is
385
- * newer still — its polyfill also leaks listeners onto inputs that never abort,
386
- * which is what the returned detach avoids here.
387
- */
388
- function linkAbort(from: AbortSignal | undefined, to: AbortController): () => void {
389
- if (from === undefined) {
390
- return () => { /* nothing was attached */ };
391
- }
392
- if (from.aborted) {
393
- to.abort();
394
- return () => { /* nothing was attached */ };
395
- }
396
- const forward = (): void => to.abort();
397
- from.addEventListener('abort', forward, { once: true });
398
- return () => from.removeEventListener('abort', forward);
399
- }
400
-
401
- /**
402
- * Dial every relay in `addrs`, ask the first one that answers for a reservation
403
- * slot, then wait until a `/p2p-circuit` address appears.
404
- *
405
- * Never throws — a dial rejection, a rejected reservation, a MALFORMED address,
406
- * or a timeout all come back as an `error` string. A dial that throws does NOT
407
- * cost the rest of the list: one dead relay among two must not cost the
408
- * reservation on the live one, so every addr is dialed and the first error (in
409
- * list order) is kept. A reservation that lands wins over any earlier error
410
- * (`error: null`).
411
- *
412
- * `timeoutMs` bounds the WHOLE drive — dials, reservation requests and the wait
413
- * share one deadline. `opts.signal` bounds it from the other side: every phase
414
- * below returns as soon as it trips, and the drive reports `cancelled` rather than
415
- * inventing a failure for a relay that was never given a chance to answer.
416
- */
417
- export async function driveRelayReservation(
418
- node: Libp2p,
419
- addrs: readonly string[],
420
- opts?: RelayReserveOptions
421
- ): Promise<RelayReserveResult> {
422
- if (addrs.length === 0) {
423
- return { error: null, cancelled: false };
424
- }
425
- const signal = opts?.signal;
426
- if (aborted(signal)) {
427
- return { error: null, cancelled: true };
428
- }
429
- const timeoutMs = opts?.timeoutMs ?? DEFAULT_RELAY_RESERVE_TIMEOUT_MS;
430
- // Clamped: a caller-supplied 0 would spin the poll loop hot until the deadline.
431
- const pollMs = Math.max(1, opts?.pollMs ?? DEFAULT_RELAY_RESERVE_POLL_MS);
432
- const deadline = Date.now() + timeoutMs;
433
-
434
- const { connected, error: dialError } = await dialRelays(node, addrs, deadline, signal);
435
- const attempt = await requestReservation(node, connected, deadline, signal);
436
- // NOTE: a REJECTED reservation still spends the rest of the deadline polling,
437
- // because discovery may independently land one (only the no-transport case is
438
- // `fatal`). So a misconfigured node reports its now-legible reason a full
439
- // `timeoutMs` late. If startup latency on that path ever matters, shorten the
440
- // wait once every connected relay has rejected — do not skip it outright.
441
- if (!attempt.fatal && (await waitForCircuitReservation(node, addrs, deadline, pollMs, signal))) {
442
- return { error: null, cancelled: false };
443
- }
444
- // Checked AFTER the success above, so a reservation that landed in the same turn
445
- // the signal tripped is still reported as landed. Below it, the reasons the
446
- // phases assembled describe the cancellation rather than the relay, so they are
447
- // dropped: a cancelled drive has nothing to say about the relay's health.
448
- if (aborted(signal)) {
449
- return { error: null, cancelled: true };
450
- }
451
- return {
452
- error: attempt.error ?? dialError ?? `no circuit reservation within ${timeoutMs}ms`,
453
- cancelled: false
454
- };
455
- }
456
-
457
- /**
458
- * Dial every relay CONCURRENTLY under the drive's shared deadline. Reports the
459
- * relays that answered (in list order, for the reservation step) and the first
460
- * failure in LIST order (`null` when every dial connected).
461
- *
462
- * Concurrent and deadline-bound because this whole drive is awaited on a browser
463
- * tab's startup path: dialing serially with libp2p's own (much longer) per-dial
464
- * timeout meant N unreachable relays cost N dial timeouts before the reservation
465
- * request even began, so `timeoutMs` bounded only the tail of the operation.
466
- *
467
- * Aborting a dial at the deadline is not a lost reservation — the steps that
468
- * follow have no time left either, so the drive would report `error` regardless.
469
- *
470
- * The caller's `signal` aborts the same dials, through the same controller: a
471
- * hanging dial is the longest thing a cancelled drive can be sitting in.
472
- */
473
- async function dialRelays(
474
- node: Libp2p,
475
- addrs: readonly string[],
476
- deadline: number,
477
- signal?: AbortSignal
478
- ): Promise<{ connected: ConnectedRelay[]; error: string | null }> {
479
- // An explicit controller, not `AbortSignal.timeout` — the latter is not
480
- // reliably present on React Native/Hermes, which runs this same module.
481
- const controller = new AbortController();
482
- const timer = setTimeout(() => controller.abort(), Math.max(0, deadline - Date.now()));
483
- const unlink = linkAbort(signal, controller);
484
- try {
485
- const results = await Promise.allSettled(
486
- addrs.map((addr) => dialOne(node, addr, controller.signal))
487
- );
488
- return { connected: connectedRelays(addrs, results), error: firstDialError(addrs, results) };
489
- } finally {
490
- clearTimeout(timer);
491
- unlink();
492
- }
493
- }
494
-
495
- /**
496
- * One dial, with the address PARSED INSIDE the promise.
497
- *
498
- * `multiaddr()` throws SYNCHRONOUSLY on a malformed string, and a throw out of
499
- * the `map` callback escapes `Promise.allSettled` altogether — it would reject
500
- * the whole drive (breaking the never-throws contract) and discard the dials to
501
- * the other, perfectly good, addrs. `async` demotes it to a settled rejection,
502
- * which is already exactly how a dial failure is reported.
503
- */
504
- async function dialOne(
505
- node: Libp2p,
506
- addr: string,
507
- signal: AbortSignal
508
- ): Promise<{ remotePeer: PeerId }> {
509
- return node.dial(multiaddr(addr), { signal });
510
- }
511
-
512
- function connectedRelays(
513
- addrs: readonly string[],
514
- results: readonly PromiseSettledResult<{ remotePeer: PeerId }>[]
515
- ): ConnectedRelay[] {
516
- const connected: ConnectedRelay[] = [];
517
- results.forEach((result, index) => {
518
- if (result.status !== 'fulfilled') return;
519
- connected.push({ addr: addrs[index], peerId: result.value.remotePeer });
520
- });
521
- return connected;
522
- }
523
-
524
- /** Log every dial rejection; return the first one in list order. */
525
- function firstDialError(
526
- addrs: readonly string[],
527
- results: readonly PromiseSettledResult<unknown>[]
528
- ): string | null {
529
- let first: string | null = null;
530
- results.forEach((result, index) => {
531
- if (result.status !== 'rejected') return;
532
- const message = result.reason instanceof Error ? result.reason.message : String(result.reason);
533
- log('Relay dial failed (%s): %s', addrs[index], message);
534
- first ??= message;
535
- });
536
- return first;
537
- }
538
-
539
- /**
540
- * Outcome of the explicit reservation request.
541
- *
542
- * `fatal` means no `/p2p-circuit` address can EVER appear (the node has no
543
- * circuit-relay transport at all), so the caller must report immediately rather
544
- * than spend the rest of the deadline polling for something that cannot happen.
545
- * A rejected request is NOT fatal: discovery may still land a reservation for a
546
- * relay that does happen to share this node's identify prefix.
547
- */
548
- interface ReservationAttempt {
549
- error: string | null;
550
- fatal: boolean;
551
- }
552
-
553
- /**
554
- * Ask the connected relays, in list order, for a reservation slot; stop at the
555
- * first success.
556
- *
557
- * `'discovered'`, not `'configured'`: the search listener's
558
- * `relay:created-reservation` handler ignores `configured` reservations outright,
559
- * so the `/p2p-circuit` listen address would never be published and
560
- * `getMultiaddrs()` would stay empty even though the reservation succeeded.
561
- * `'discovered'` consumes the pending-reservation id the bare `/p2p-circuit`
562
- * listener registered, which is exactly what that handler matches on.
563
- *
564
- * Sequential, not concurrent: a bare `/p2p-circuit` listener registers exactly
565
- * ONE pending reservation, so a second concurrent `addRelay` would be rejected
566
- * with `HadEnoughRelaysError` — noise, not a failure. Running discovery is not a
567
- * conflict either; `addRelay` dedupes through its own peer queue, so a relay that
568
- * genuinely is discoverable still reserves exactly once.
569
- */
570
- async function requestReservation(
571
- node: Libp2p,
572
- connected: readonly ConnectedRelay[],
573
- deadline: number,
574
- signal?: AbortSignal
575
- ): Promise<ReservationAttempt> {
576
- if (connected.length === 0) {
577
- // Nothing answered — the dial error is the whole story.
578
- return { error: null, fatal: false };
579
- }
580
- const transport = findCircuitRelayTransport(node);
581
- if (transport === null) {
582
- return {
583
- error: 'node has no circuit-relay transport — add circuitRelayTransport() to its transports',
584
- fatal: true
585
- };
586
- }
587
- let firstError: string | null = null;
588
- for (const relay of connected) {
589
- if (transport.reservationStore.hasReservation(relay.peerId)) {
590
- return { error: null, fatal: false };
591
- }
592
- // A cancelled drive stops here rather than asking the next relay: the caller is
593
- // tearing this node down, so another hop request against it can only fail.
594
- if (Date.now() >= deadline || aborted(signal)) {
595
- break;
596
- }
597
- const failure = await requestOneReservation(
598
- transport.reservationStore,
599
- relay,
600
- deadline,
601
- signal
602
- );
603
- if (failure === null) {
604
- return { error: null, fatal: false };
605
- }
606
- firstError ??= failure;
607
- }
608
- return { error: firstError, fatal: false };
609
- }
610
-
611
- /**
612
- * One `addRelay` call, bounded by the drive's deadline and by the caller's signal.
613
- * Returns `null` on success, or the reason it stopped waiting.
614
- *
615
- * Raced rather than passed a signal because `addRelay` accepts none and runs on
616
- * libp2p's own (much longer) reservation timeout: without the race a drive given
617
- * 1.5 s would sit on a silent relay for libp2p's timeout instead. The abandoned
618
- * promise stays handled — `Promise.race` attaches its own handlers — so a later
619
- * rejection is not unhandled, and is not logged either: a request abandoned at a
620
- * cancellation must not print a relay failure the caller would read as real.
621
- *
622
- * `waitOver` ends the wait on BOTH routes — the caller's abort, relayed in, and the
623
- * race settling some other way, aborted in the `finally`. Out-racing the deadline
624
- * timer is not enough: the loser stays pending, and a pending timer is what holds
625
- * a Node process open past the stop that asked for it.
626
- */
627
- async function requestOneReservation(
628
- store: RelayReservationStoreLike,
629
- relay: ConnectedRelay,
630
- deadline: number,
631
- signal?: AbortSignal
632
- ): Promise<string | null> {
633
- const waitOver = new AbortController();
634
- const unlink = linkAbort(signal, waitOver);
635
- try {
636
- const outcome = await Promise.race([
637
- store.addRelay(relay.peerId, 'discovered'),
638
- delay(Math.max(0, deadline - Date.now()), waitOver.signal).then(() => WAIT_OVER)
639
- ]);
640
- if (outcome !== WAIT_OVER) {
641
- return null;
642
- }
643
- if (aborted(signal)) {
644
- return `relay reservation request to ${relay.addr} was cancelled`;
645
- }
646
- log('Relay reservation request (%s) still pending at the deadline', relay.addr);
647
- return `relay reservation request to ${relay.addr} did not complete before the deadline`;
648
- } catch (err) {
649
- const message = describeReservationFailure(err, relay.addr);
650
- log('Relay reservation failed (%s): %s', relay.addr, message);
651
- return message;
652
- } finally {
653
- unlink();
654
- waitOver.abort();
655
- }
656
- }
657
-
658
- /**
659
- * Turn libp2p's reservation rejection into a reason that names the actual cause.
660
- *
661
- * `HadEnoughRelaysError` needs translating rather than passing through: its own
662
- * message ("we do not need any more relays") says the opposite of what happened.
663
- * A `'discovered'` reservation is refused when the node holds NO pending
664
- * reservation id, and a node holds one only while it listens on the bare
665
- * `/p2p-circuit` search address — so the real cause is a missing listen address.
666
- */
667
- function describeReservationFailure(err: unknown, addr: string): string {
668
- // NOTE: libp2p adds a peer to the reservation store's `relayFilter` when a
669
- // request fails with `DialError` or `UnsupportedProtocolError`, and the failure
670
- // path does not reset that filter (it only resets when a reservation is actually
671
- // removed). So a SECOND drive against the same relay in the same process reports
672
- // `ListenError: The relay was previously invalid` even if the relay has since
673
- // recovered. `RelayReservationLoop` clears the entry before every attempt (see
674
- // {@link clearRelayFilterEntry}); a caller that re-drives WITHOUT the supervisor
675
- // still has to deal with the filter itself.
676
- const name = err instanceof Error ? err.name : '';
677
- const message = err instanceof Error ? err.message : String(err);
678
- switch (name) {
679
- case 'HadEnoughRelaysError':
680
- return `relay reservation on ${addr} was not requested: this node holds no pending circuit reservation — it is not listening on the bare /p2p-circuit address`;
681
- case 'UnsupportedProtocolError':
682
- return `peer at ${addr} does not speak the circuit-relay hop protocol — it is not a relay`;
683
- default:
684
- return `relay reservation on ${addr} failed: ${message}`;
685
- }
686
- }
687
-
688
- /**
689
- * Poll until the node advertises a `/p2p-circuit` address through one of `addrs`'
690
- * relays ({@link circuitMultiaddrsVia}), the deadline passes, or the drive is
691
- * cancelled. This is the phase a cancellation has to reach: whatever the dial and
692
- * the reservation request shed, an abandoned drive used to spend here instead,
693
- * polling a node whose transports were already being torn down.
694
- *
695
- * Still a poll even though the reservation is now requested explicitly: `addRelay`
696
- * resolving means the RELAY accepted, while the listen address is published a tick
697
- * later by the listener's `relay:created-reservation` handler, and a reservation
698
- * that discovery lands independently has no return value to await at all.
699
- *
700
- * NOTE: polls rather than subscribing to libp2p's `self:peer:update` — it keeps
701
- * this free of libp2p event-name coupling. If 250 ms of reservation latency ever
702
- * matters, switch to the event and keep the poll as a fallback.
703
- */
704
- async function waitForCircuitReservation(
705
- node: Libp2p,
706
- addrs: readonly string[],
707
- deadline: number,
708
- pollMs: number,
709
- signal?: AbortSignal
710
- ): Promise<boolean> {
711
- for (;;) {
712
- if (circuitMultiaddrsVia(node, addrs).length > 0) {
713
- return true;
714
- }
715
- if (Date.now() >= deadline || aborted(signal)) {
716
- return false;
717
- }
718
- await delay(Math.min(pollMs, Math.max(0, deadline - Date.now())), signal);
719
- }
720
- }
721
-
722
- /** Gap between liveness checks while a reservation is held. */
723
- export const DEFAULT_RELAY_CHECK_MS = 5_000;
724
- /** Backoff before the first re-drive after a failed attempt. */
725
- export const DEFAULT_RELAY_MIN_BACKOFF_MS = 2_000;
726
- /** Ceiling the backoff doubles up to. */
727
- export const DEFAULT_RELAY_MAX_BACKOFF_MS = 60_000;
728
-
729
- /**
730
- * Everything one drive takes, minus its `signal`, plus the loop's own cadence.
731
- *
732
- * `signal` is omitted rather than inherited because these options are handed
733
- * straight to every drive: a caller-supplied one would cancel each attempt without
734
- * the loop knowing, leaving it to reschedule drives that return immediately and
735
- * forever. The way to cancel a supervisor is
736
- * {@link RelayReservationSupervisor.stop}, which owns the signal it passes down.
737
- */
738
- export interface RelayReservationSupervisorOptions extends Omit<RelayReserveOptions, 'signal'> {
739
- /** Gap between liveness checks while a reservation is held. Default 5_000. */
740
- checkMs?: number;
741
- /** Backoff before the first re-drive after a failure. Default 2_000. */
742
- minBackoffMs?: number;
743
- /** Backoff ceiling. Default 60_000. */
744
- maxBackoffMs?: number;
745
- /**
746
- * Awaited before every drive AFTER the first — never before the first attempt,
747
- * which the caller has typically prepared for already. A hook that throws or
748
- * rejects is logged and the drive still runs: the hook is preparation, and a
749
- * failed preparation must not cost the attempt itself.
750
- *
751
- * What a strand node uses it for: re-announcing its delegate peer id to the relay
752
- * about to be re-dialed. A party control node running the relay server admits a
753
- * strand node on an in-memory delegate grant, and a relay restart drops every
754
- * grant it held — so a re-drive that did not re-announce first would be denied
755
- * at the relay's connection gate.
756
- */
757
- beforeRedrive?: () => Promise<void> | void;
758
- }
759
-
760
- /**
761
- * A running retry loop for one node + relay list. Obtained from
762
- * {@link superviseRelayReservation}; its only imperative is {@link stop}.
763
- */
764
- export interface RelayReservationSupervisor {
765
- /**
766
- * Resolves once the FIRST attempt has settled — so a caller can await startup
767
- * exactly as it awaited a single {@link driveRelayReservation}, and the retries
768
- * carry on in the background afterwards. Also resolves on {@link stop}, so an
769
- * awaiting caller is never left hanging.
770
- */
771
- readonly firstAttempt: Promise<void>;
772
- /** True while a drive is in flight. */
773
- readonly driving: boolean;
774
- /** Epoch ms of the next scheduled tick; `null` while a drive is running. */
775
- readonly retryAtMs: number | null;
776
- /** Reason the last drive produced no reservation; `null` once one is held. */
777
- readonly lastError: string | null;
778
- /**
779
- * Idempotent. Clears the timer so no further drive is scheduled, and CANCELS the
780
- * drive already in flight: it stops dialing or polling, clears every timer it
781
- * holds and reports `cancelled`, so a teardown does not trail an attempt against
782
- * the node it is dismantling. That result is discarded — a cancelled drive is
783
- * not a failure — and nothing follows it.
784
- */
785
- stop(): void;
786
- }
787
-
788
- /**
789
- * Keep asking for a relay reservation until one is held, then keep watching that
790
- * it still is — the thing that makes a lost reservation recover on its own.
791
- *
792
- * Needed because nothing else re-drives: libp2p re-fills a search listener's
793
- * freed slot from relay DISCOVERY, and a cadre node's namespaced identify puts
794
- * discovery permanently out of reach (see the module header). Without this loop a
795
- * relay restart left a browser tab undialable until the user reloaded the page.
796
- *
797
- * Per tick:
798
- * - a reservation is held → reset the backoff, clear the error, re-check in
799
- * `checkMs`. No drive: a healthy node must not re-request every few seconds.
800
- * - otherwise → un-poison the reservation store's relay filter (see
801
- * {@link clearRelayFilterEntry}) and run ONE {@link driveRelayReservation}.
802
- * If that lands a reservation, rejoin the healthy path above; if not, sleep
803
- * the current backoff and double it up to `maxBackoffMs`.
804
- *
805
- * "Held" is judged PER RELAY — a circuit addr through one of `addrs`' relays
806
- * ({@link circuitMultiaddrsVia}) — so several loops over one node, one relay each
807
- * (a strand node), each re-drive exactly the relay they own. Every drive after the
808
- * first is preceded by the optional `beforeRedrive` hook
809
- * ({@link RelayReservationSupervisorOptions}).
810
- *
811
- * Starts immediately; the first tick runs before this returns.
812
- */
813
- export function superviseRelayReservation(
814
- node: Libp2p,
815
- addrs: readonly string[],
816
- opts?: RelayReservationSupervisorOptions
817
- ): RelayReservationSupervisor {
818
- return new RelayReservationLoop(node, [...addrs], opts ?? {});
819
- }
820
-
821
- /**
822
- * Forget that `addr`'s peer ever failed a reservation request, so the next
823
- * attempt is actually made rather than refused out of hand.
824
- *
825
- * `ReservationStore` records a peer in `relayFilter` when its reservation request
826
- * fails with `DialError` or `UnsupportedProtocolError`, and NOTHING on that path
827
- * ever clears it: the reset lives in `#checkReservationCount`, which only runs
828
- * when a reservation is genuinely removed, and `#removeReservation` early-returns
829
- * when there was never one. So a relay that was briefly not-a-relay (or died
830
- * between our dial and the hop request) stays permanently rejected with
831
- * `The relay was previously invalid` — measured, not inferred.
832
- *
833
- * Fails soft in every direction: no `relayFilter`, no `remove`, an addr with no
834
- * peer id, a malformed addr — all mean "no un-poisoning", never a throw. The
835
- * retry loop still recovers the common case without this, because a relay that is
836
- * simply DOWN fails our own dial first and never reaches the filter.
837
- *
838
- * Returns whether an entry was actually removed (for specs; callers ignore it).
839
- */
840
- export function clearRelayFilterEntry(store: RelayReservationStoreLike, addr: string): boolean {
841
- const filter = store.relayFilter;
842
- if (typeof filter?.remove !== 'function') {
843
- log('Reservation store has no removable relayFilter — cannot un-poison %s', addr);
844
- return false;
845
- }
846
- try {
847
- // The peer id is in the multiaddr, so this costs no dial and can run before one.
848
- const peerId = trailingPeerId(multiaddr(addr));
849
- if (peerId === null) {
850
- // NOTE: an addr with no `/p2p/` component can still be dialed and reserved
851
- // through (the peer id comes off the connection), but it can never be
852
- // un-poisoned — so for THAT addr a poisoned filter is permanent again. No
853
- // caller supplies such an addr today; if one ever does, resolve the peer id
854
- // from the live connection instead of the multiaddr.
855
- return false;
856
- }
857
- return filter.remove(peerIdFromString(peerId).toMultihash().bytes);
858
- } catch (err) {
859
- log('Could not clear the relayFilter entry for %s: %o', addr, err);
860
- return false;
861
- }
862
- }
863
-
864
- /** The self-rescheduling loop behind {@link superviseRelayReservation}. */
865
- class RelayReservationLoop implements RelayReservationSupervisor {
866
- readonly firstAttempt: Promise<void>;
867
-
868
- private readonly checkMs: number;
869
- private readonly minBackoffMs: number;
870
- private readonly maxBackoffMs: number;
871
- private backoffMs: number;
872
- private timer: ReturnType<typeof setTimeout> | null = null;
873
- /** Tripped by {@link stop}; the only thing that cancels a drive of this loop's. */
874
- private readonly cancel = new AbortController();
875
- private stopped = false;
876
- private inFlight = false;
877
- /** Drives started so far — the `beforeRedrive` hook runs from the second one on. */
878
- private drives = 0;
879
- private nextTickAtMs: number | null = null;
880
- private failure: string | null = null;
881
- private settleFirstAttempt: () => void = () => {};
882
- private firstAttemptSettled = false;
883
-
884
- constructor(
885
- private readonly node: Libp2p,
886
- private readonly addrs: readonly string[],
887
- private readonly opts: RelayReservationSupervisorOptions
888
- ) {
889
- // Clamped away from 0: a caller-supplied 0 would spin the loop hot.
890
- this.checkMs = Math.max(1, opts.checkMs ?? DEFAULT_RELAY_CHECK_MS);
891
- this.minBackoffMs = Math.max(1, opts.minBackoffMs ?? DEFAULT_RELAY_MIN_BACKOFF_MS);
892
- this.maxBackoffMs = Math.max(
893
- this.minBackoffMs,
894
- opts.maxBackoffMs ?? DEFAULT_RELAY_MAX_BACKOFF_MS
895
- );
896
- this.backoffMs = this.minBackoffMs;
897
- this.firstAttempt = new Promise((resolve) => {
898
- this.settleFirstAttempt = resolve;
899
- });
900
- void this.tick();
901
- }
902
-
903
- get driving(): boolean {
904
- return this.inFlight;
905
- }
906
-
907
- get retryAtMs(): number | null {
908
- return this.nextTickAtMs;
909
- }
910
-
911
- get lastError(): string | null {
912
- return this.failure;
913
- }
914
-
915
- stop(): void {
916
- if (this.stopped) {
917
- return;
918
- }
919
- this.stopped = true;
920
- // The scheduled attempt and the running one are two different things to end:
921
- // the timer covers the first, the signal the second.
922
- this.cancel.abort();
923
- if (this.timer !== null) {
924
- clearTimeout(this.timer);
925
- this.timer = null;
926
- }
927
- this.nextTickAtMs = null;
928
- this.settleFirst();
929
- }
930
-
931
- private async tick(): Promise<void> {
932
- if (this.stopped) {
933
- return;
934
- }
935
- this.nextTickAtMs = null;
936
- if (this.reservationHeld()) {
937
- this.onReservationHeld();
938
- return;
939
- }
940
- await this.driveOnce();
941
- if (this.stopped) {
942
- return;
943
- }
944
- this.settleFirst();
945
- // A drive that LANDED a reservation resumes the healthy cadence immediately.
946
- // Backing off here instead would leave the first liveness check after a long
947
- // outage a fully grown backoff away (up to `maxBackoffMs`), so a reservation
948
- // lost again right after recovery would go unnoticed for that whole window.
949
- if (this.reservationHeld()) {
950
- this.onReservationHeld();
951
- return;
952
- }
953
- this.scheduleBackoff();
954
- }
955
-
956
- /** Per relay: only a circuit addr THROUGH one of this loop's relays counts. */
957
- private reservationHeld(): boolean {
958
- return circuitMultiaddrsVia(this.node, this.addrs).length > 0;
959
- }
960
-
961
- /** Healthy tick: nothing to request, so only reset and re-check later. */
962
- private onReservationHeld(): void {
963
- this.backoffMs = this.minBackoffMs;
964
- this.failure = null;
965
- this.settleFirst();
966
- this.schedule(this.checkMs);
967
- }
968
-
969
- private async driveOnce(): Promise<void> {
970
- this.inFlight = true;
971
- try {
972
- if (this.drives > 0) {
973
- await this.runBeforeRedrive();
974
- // A stop that arrived while the hook ran: nothing follows it, so do not dial
975
- // a node that is being torn down.
976
- if (this.stopped) {
977
- return;
978
- }
979
- }
980
- this.drives += 1;
981
- this.unpoisonRelayFilter();
982
- const { error, cancelled } = await driveRelayReservation(this.node, this.addrs, {
983
- ...this.opts,
984
- signal: this.cancel.signal
985
- });
986
- // A cancelled drive landed nothing AND failed at nothing, so it has no status
987
- // to report: recording it would surface a teardown artifact through
988
- // `getRelayReservationState()` as if the relay had refused.
989
- if (!this.stopped && !cancelled) {
990
- this.failure = error;
991
- }
992
- } catch (err) {
993
- // `driveRelayReservation` is fail-soft by contract, so reaching here means
994
- // that contract broke. The loop must survive it anyway: an escaping
995
- // rejection would leave `firstAttempt` pending FOREVER (hanging every
996
- // caller that awaits a reservation at startup) and schedule no further
997
- // attempt, which is the failure this whole supervisor exists to prevent.
998
- const message = err instanceof Error ? err.message : String(err);
999
- log('Relay reservation drive threw, which it should not: %s', message);
1000
- if (!this.stopped) {
1001
- this.failure = message;
1002
- }
1003
- } finally {
1004
- this.inFlight = false;
1005
- }
1006
- }
1007
-
1008
- private scheduleBackoff(): void {
1009
- const wait = this.backoffMs;
1010
- this.backoffMs = Math.min(this.backoffMs * 2, this.maxBackoffMs);
1011
- this.schedule(wait);
1012
- }
1013
-
1014
- /** The caller's `beforeRedrive` hook, contained: a throw or rejection is logged, never propagated. */
1015
- private async runBeforeRedrive(): Promise<void> {
1016
- const hook = this.opts.beforeRedrive;
1017
- if (hook === undefined) {
1018
- return;
1019
- }
1020
- try {
1021
- await hook();
1022
- } catch (err) {
1023
- log('beforeRedrive hook failed (%o); driving the reservation anyway: %o', this.addrs, err);
1024
- }
1025
- }
1026
-
1027
- private unpoisonRelayFilter(): void {
1028
- const transport = findCircuitRelayTransport(this.node);
1029
- if (transport === null) {
1030
- return;
1031
- }
1032
- for (const addr of this.addrs) {
1033
- clearRelayFilterEntry(transport.reservationStore, addr);
1034
- }
1035
- }
1036
-
1037
- private schedule(ms: number): void {
1038
- if (this.stopped) {
1039
- return;
1040
- }
1041
- this.nextTickAtMs = Date.now() + ms;
1042
- this.timer = setTimeout(() => {
1043
- this.timer = null;
1044
- void this.tick();
1045
- }, ms);
1046
- // Node keeps the process alive while a timer is pending, so an un-unref'd
1047
- // supervisor would hang every CLI run and vitest worker that ever reserved.
1048
- // Cast + optional-chain: browsers and React Native have no `unref`.
1049
- (this.timer as { unref?: () => void }).unref?.();
1050
- }
1051
-
1052
- private settleFirst(): void {
1053
- if (this.firstAttemptSettled) {
1054
- return;
1055
- }
1056
- this.firstAttemptSettled = true;
1057
- this.settleFirstAttempt();
1058
- }
1059
- }
1060
-
1061
- /**
1062
- * Derive the reservation posture, reading the node's circuit addrs LIVE. Pure
1063
- * apart from that read, so the precedence is testable on its own:
1064
- *
1065
- * | condition | status |
1066
- * | ------------------------ | ----------------------------------------------- |
1067
- * | no addrs supplied | `none` |
1068
- * | live circuit addrs held | `reserved` (`error: null`) |
1069
- * | a drive is in flight | `dialing` |
1070
- * | a retry is scheduled | `retrying` |
1071
- * | otherwise | `error` |
1072
- *
1073
- * `reserved` is checked BEFORE `error` on purpose: the circuit addrs are read
1074
- * live, so a reservation that lands by ANY route supersedes a stale error string
1075
- * without a second drive.
1076
- *
1077
- * `retrying` sits between the two so that `error` carries a sharper meaning:
1078
- * NOBODY IS GOING TO TRY AGAIN. A lost reservation does come back on its own now,
1079
- * as long as a {@link RelayReservationSupervisor} is running — that loop is the
1080
- * only thing that re-drives, since libp2p re-fills a search listener's freed slot
1081
- * from relay DISCOVERY, which a cadre node's namespaced identify puts permanently
1082
- * out of reach (see the module header). So `error` means the supervisor was
1083
- * stopped, was never started, or there is no node at all.
1084
- *
1085
- * `retryAtMs` is the supervisor's next scheduled tick (`null` while a drive runs
1086
- * or when there is no supervisor); it both selects `retrying` and is passed
1087
- * through so a UI can count down to the next attempt.
1088
- */
1089
- export function resolveRelayReservationState(
1090
- node: Libp2p | null,
1091
- addrs: readonly string[],
1092
- lastError: string | null,
1093
- driving: boolean,
1094
- retryAtMs: number | null
1095
- ): RelayReservationState {
1096
- if (addrs.length === 0) {
1097
- return { status: 'none', addrs: [], circuitAddrs: [], error: null, retryAtMs: null };
1098
- }
1099
- const supplied = [...addrs];
1100
- const circuitAddrs = node ? circuitMultiaddrs(node) : [];
1101
- if (circuitAddrs.length > 0) {
1102
- return { status: 'reserved', addrs: supplied, circuitAddrs, error: null, retryAtMs };
1103
- }
1104
- if (driving) {
1105
- return {
1106
- status: 'dialing',
1107
- addrs: supplied,
1108
- circuitAddrs: [],
1109
- error: lastError,
1110
- retryAtMs: null
1111
- };
1112
- }
1113
- // `driveRelayReservation` always reports a reason when it finishes without a
1114
- // reservation, so `lastError` is normally set below. The fallback only covers
1115
- // addrs recorded without a completed drive.
1116
- const error = lastError ?? 'no circuit reservation held';
1117
- if (retryAtMs !== null) {
1118
- return { status: 'retrying', addrs: supplied, circuitAddrs: [], error, retryAtMs };
1119
- }
1120
- return { status: 'error', addrs: supplied, circuitAddrs: [], error, retryAtMs: null };
1121
- }
1
+ /**
2
+ * Relay reservation for nodes that reserve through the SEARCH listen addr — the
3
+ * dial, the explicit reservation request, the retry loop that keeps it, and the
4
+ * (live) status derivation.
5
+ *
6
+ * `@libp2p/circuit-relay-v2`'s listener branches on the SHAPE of the listen
7
+ * address:
8
+ *
9
+ * | listen addr | libp2p behaviour | unreachable relay |
10
+ * | ------------------------------------------------- | ------------------------------------------------------------------------------------ | -------------------------- |
11
+ * | `<dial addr>/p2p/<relayPeerId>/p2p-circuit` | CONFIGURED reservation: dial that exact relay and reserve, or fail | `listen()` throws |
12
+ * | bare `/p2p-circuit` | SEARCH mode: register a pending reservation, to be filled by relay discovery | nothing throws, no reserve |
13
+ *
14
+ * A search listener needs someone to (a) dial the relay and (b) fill the pending
15
+ * reservation it created, then report whether one actually landed. That is this
16
+ * module. It is **fail-soft by construction**: nothing here throws.
17
+ *
18
+ * EVERY cadre CONTROL node now takes that route — `network.relayAddrs` resolves
19
+ * to the bare search entry (`relay-addrs.ts` → `resolveListenAddrs`) and
20
+ * `CadreNode.start()` drives this module once the control database is up. The
21
+ * configured shape would dial the relay from inside `libp2p.start()`, putting a
22
+ * sibling in this node's cohort before its own control database existed, and a
23
+ * sibling that has not yet replicated this node's `CadrePeer` row correctly
24
+ * refuses its control-DB streams — which killed `start()` outright.
25
+ *
26
+ * So the two shapes are no longer alternative ROUTES, only alternative failure
27
+ * postures on top of the same drive: a node that names `network.relayAddrs` gets
28
+ * a `RelayReservationFailedError` out of `start()` when the first attempt lands
29
+ * nothing (fail-fast, the operator asked for this relay), while a node that calls
30
+ * `CadreNode.reserveRelays()` itself gets a non-`reserved` status and stays up
31
+ * (fail-soft, the browser-tab posture). `network.requireRelay: false` gives a
32
+ * CONFIGURED relay the fail-soft posture too, for a node that must boot with no
33
+ * network at all — same drive, same supervisor, only the throw is dropped.
34
+ * Configuring both is now redundant, not fatal.
35
+ *
36
+ * STRAND nodes take the same route, ONE supervisor PER RELAY
37
+ * (`strand-instance-manager.ts` → `buildStrandRuntime`): each configured relay
38
+ * gets its own bare `/p2p-circuit` listener (`strand-network-config.ts`) and its
39
+ * own {@link superviseRelayReservation} over just that relay's addr, fail-soft
40
+ * like the browser tab. The configured shape they used to take
41
+ * (`<relay>/p2p-circuit`, reserved from inside `libp2p.start()`) is gone from
42
+ * cadre-built nodes entirely, because it loses its address and never recovers in
43
+ * three situations — the relay restarts, either side hangs up the relay
44
+ * connection, and libp2p's OWN reservation refresh (which removes the reservation
45
+ * before re-creating it, and a configured listener republishes only from inside
46
+ * its own `listen()`). The last one needs no network event at all: at the relay
47
+ * default TTL of two hours every configured-shape node went undialable ~1 h 55 min
48
+ * after reserving. A search listener republishes on `relay:created-reservation`
49
+ * for its own pending id, which the refresh re-queues, and the supervisor covers
50
+ * the other two.
51
+ *
52
+ * Because a strand node runs one supervisor per relay, "is the reservation held"
53
+ * is asked PER RELAY ({@link circuitMultiaddrsVia}): relay X's supervisor must not
54
+ * be satisfied by relay Y's circuit addr, or it would never re-drive X.
55
+ *
56
+ * ⚠️ WHY THE RESERVATION IS REQUESTED EXPLICITLY RATHER THAN LEFT TO DISCOVERY.
57
+ * libp2p fills a search listener's pending reservation from `RelayDiscovery`,
58
+ * which nominates a peer only once it can see the relay-hop protocol id in that
59
+ * peer's PEER-STORE protocol list — and that list is written exclusively by the
60
+ * IDENTIFY handshake. `@optimystic/db-p2p` gives every cadre node a
61
+ * network-namespaced identify protocol id (`/optimystic/control-<partyId>/id/1.0.0`)
62
+ * while the relay `ops/docker/libp2p-infra` deploys runs stock identify
63
+ * (`/ipfs/id/1.0.0`), so the two never identify each other, the peer store stays
64
+ * empty of protocols, and discovery never nominates the relay. The TCP/WebSocket
65
+ * connection itself is fine, which is why leaving it to discovery surfaced as a
66
+ * generic timeout.
67
+ *
68
+ * Identify is incidental to relaying, though: the reservation
69
+ * (`/libp2p/circuit/relay/0.2.0/hop`), a third peer's CONNECT through the relay,
70
+ * and the STOP handler on this node all use STOCK, un-namespaced protocol ids the
71
+ * deployed relay already serves. Discovery's only job is to GUESS which connected
72
+ * peer is a relay, and this module does not need to guess — it was handed the
73
+ * relay's address. So it asks the relay for a slot directly, via the
74
+ * circuit-relay transport's own reservation store.
75
+ *
76
+ * Status is derived from the node's LIVE multiaddrs on every read rather than
77
+ * cached at drive time: when a relay restarts or the connection drops, libp2p's
78
+ * listener clears its listening addrs and the circuit multiaddr disappears, so a
79
+ * cached snapshot would keep claiming `reserved` for a node nothing can dial.
80
+ *
81
+ * And because discovery is out of reach, nothing would ever ASK again either —
82
+ * so {@link driveRelayReservation} stays a single-shot primitive and
83
+ * {@link superviseRelayReservation} owns the retry cadence on top of it. That
84
+ * loop is what makes a lost reservation recover without a page reload. Single-shot
85
+ * but not unstoppable: the primitive takes an `AbortSignal` and the loop trips it
86
+ * from `stop()`, because a drive left running against a node being torn down both
87
+ * logs failures that read as real and — through the timers it still holds — keeps
88
+ * the process alive for the rest of its `timeoutMs`.
89
+ *
90
+ * One measured refinement to "out of reach": libp2p 3.1.3's `connection.newStream`
91
+ * records every protocol OUR OWN outbound stream negotiated into the peer store, so
92
+ * the explicit reservation request writes the relay-hop protocol id against the
93
+ * relay itself. From then on, discovery CAN refill a freed slot on its own — but
94
+ * only when the relay answers at that moment (a hangup while the relay stays up;
95
+ * measured at ~25 ms). A relay that is down when the slot frees fails that one
96
+ * discovery attempt, which poisons the store's `relayFilter` against it, and
97
+ * nothing in libp2p tries again: a relay RESTART still needs the supervisor, which
98
+ * un-poisons the filter before every attempt ({@link clearRelayFilterEntry}). Two
99
+ * mechanisms in production, one guarantee; the specs disable discovery's half
100
+ * (`forgetRelayProtocol` in `relay-reservation.spec.ts`) so they prove the
101
+ * supervisor's.
102
+ */
103
+
104
+ import debug from 'debug';
105
+ import { multiaddr } from '@multiformats/multiaddr';
106
+ import { peerIdFromString } from '@libp2p/peer-id';
107
+ import type { Libp2p, PeerId } from '@libp2p/interface';
108
+ import { trailingPeerId } from './peer-record.js';
109
+ import { relayReservationBudgetMs } from './link-budget.js';
110
+
111
+ const log = debug('sereus:cadre:relay-reservation');
112
+
113
+ /**
114
+ * Relay-reservation posture for a node that reserves through the SEARCH listen
115
+ * addr (bare `/p2p-circuit`) — every cadre control node, whether its relays came
116
+ * from `network.relayAddrs` or from an explicit `CadreNode.reserveRelays()` call.
117
+ * - `none` — no relay addrs supplied; the node is undialable by design.
118
+ * - `dialing` — a drive is in flight.
119
+ * - `reserved` — the node currently holds at least one `/p2p-circuit` addr.
120
+ * - `retrying` — no reservation right now, but a {@link RelayReservationSupervisor}
121
+ * has the next attempt scheduled. Recoverable without a caller.
122
+ * - `error` — no reservation, and NOBODY IS GOING TO TRY AGAIN: no supervisor
123
+ * is running (or there is no node at all).
124
+ */
125
+ export type RelayReservationStatus = 'none' | 'dialing' | 'reserved' | 'retrying' | 'error';
126
+
127
+ export interface RelayReservationState {
128
+ status: RelayReservationStatus;
129
+ /** The relay multiaddrs this node was asked to reserve through. */
130
+ addrs: string[];
131
+ /** LIVE `/p2p-circuit` multiaddrs, recomputed on every read. */
132
+ circuitAddrs: string[];
133
+ error: string | null;
134
+ /**
135
+ * Epoch ms of the supervisor's next scheduled tick, or `null` when a drive is
136
+ * in flight, no supervisor is running, or no addrs were supplied. A UI can turn
137
+ * this into "reconnecting, next try in 8s" rather than showing a bare error for
138
+ * a node that is in fact recovering.
139
+ */
140
+ retryAtMs: number | null;
141
+ }
142
+
143
+ /**
144
+ * How long {@link driveRelayReservation} waits for a reservation to appear, at the DEFAULT
145
+ * declared link round trip: `RELAY_RESERVATION_ROUND_TRIPS` (4) x `DECLARED_LINK_ROUND_TRIP_MS`
146
+ * (3500 ms), plus 2 x `ADMISSION_DECISION_TIMEOUT_MS` (2000 ms) for a party-run relay's
147
+ * connection and reservation decisions, = 18 000 ms (`relayReservationBudgetMs`), where it was a
148
+ * fixed 10_000 before it was derived.
149
+ *
150
+ * Counted rather than chosen because this one deadline bounds the whole drive — dial the relay,
151
+ * request the reservation, wait — and each of those costs a fixed number of exchanges, not a
152
+ * fixed number of milliseconds. `link-budget.ts` carries the counts, the measurement behind
153
+ * them, and what still fails at the supported link whatever this says.
154
+ *
155
+ * A host on a slower link moves it by declaring `NetworkConfig.linkRoundTripMs`, which both
156
+ * call sites thread in (`CadreNode.reserveRelays` for the control node,
157
+ * `StrandInstanceManager`'s per-relay supervisors for a strand). This constant is the fallback
158
+ * for a caller that declares nothing.
159
+ */
160
+ export const DEFAULT_RELAY_RESERVE_TIMEOUT_MS = relayReservationBudgetMs();
161
+ export const DEFAULT_RELAY_RESERVE_POLL_MS = 250;
162
+
163
+ export interface RelayReserveOptions {
164
+ timeoutMs?: number;
165
+ pollMs?: number;
166
+ /**
167
+ * Ends an in-flight drive early. Aborting is not a failure: the drive returns
168
+ * `{ error: null, cancelled: true }` and clears every timer it holds, so the
169
+ * process is free to exit immediately instead of trailing the teardown that
170
+ * cancelled it.
171
+ */
172
+ signal?: AbortSignal;
173
+ }
174
+
175
+ /** What one {@link driveRelayReservation} came back with. */
176
+ export interface RelayReserveResult {
177
+ /** Why no reservation landed; `null` when one did — or when the drive was cancelled. */
178
+ error: string | null;
179
+ /**
180
+ * The drive ended because its caller's `signal` tripped, not because of anything
181
+ * the relay did. Separate from `error` because `error: null` means "a reservation
182
+ * landed" and a cancelled drive landed nothing: folded together, a caller would
183
+ * read cancellation as success. `cancelled: true` always implies `error: null`.
184
+ */
185
+ cancelled: boolean;
186
+ }
187
+
188
+ /**
189
+ * The slice of `@libp2p/utils`' `Filter` (a cuckoo filter) that the reservation
190
+ * store uses to remember relays whose reservation request failed. `remove` is
191
+ * OPTIONAL on that interface, so every use here has to cope with its absence —
192
+ * see {@link clearRelayFilterEntry}.
193
+ */
194
+ export interface RelayFilterLike {
195
+ has(item: Uint8Array): boolean;
196
+ remove?(item: Uint8Array): boolean;
197
+ }
198
+
199
+ /**
200
+ * The slice of `@libp2p/circuit-relay-v2`'s `ReservationStore` this module drives.
201
+ * Declared structurally because the class is internal to that package: naming only
202
+ * the members we call keeps the coupling small, explicit and greppable, and lets
203
+ * {@link findCircuitRelayTransport} duck-type rather than brand-match.
204
+ *
205
+ * `relayFilter` is optional because it is not required to DRIVE a reservation,
206
+ * only to RE-drive one (see {@link clearRelayFilterEntry}); a libp2p version that
207
+ * renames or drops it must degrade, not break.
208
+ */
209
+ export interface RelayReservationStoreLike {
210
+ addRelay(peerId: PeerId, type: 'discovered' | 'configured'): Promise<unknown>;
211
+ hasReservation(peerId: PeerId): boolean;
212
+ relayFilter?: RelayFilterLike;
213
+ }
214
+
215
+ /** The slice of libp2p's circuit-relay transport that owns the reservation store. */
216
+ export interface CircuitRelayTransportLike {
217
+ reservationStore: RelayReservationStoreLike;
218
+ }
219
+
220
+ /** `components` is a real field on libp2p's node class but not on the `Libp2p` interface. */
221
+ interface Libp2pComponentsLike {
222
+ components?: {
223
+ transportManager?: {
224
+ getTransports?: () => readonly unknown[];
225
+ };
226
+ };
227
+ }
228
+
229
+ /**
230
+ * The node's `/p2p-circuit` multiaddrs — the addresses a peer can dial it at
231
+ * while it holds a relay reservation. Empty means "not dialable via a relay
232
+ * right now", which is exactly what makes {@link resolveRelayReservationState}
233
+ * live rather than a stale snapshot.
234
+ */
235
+ export function circuitMultiaddrs(node: Libp2p): string[] {
236
+ return node
237
+ .getMultiaddrs()
238
+ .map((ma) => ma.toString())
239
+ .filter((addr) => addr.includes('/p2p-circuit'));
240
+ }
241
+
242
+ /**
243
+ * The node's `/p2p-circuit` multiaddrs THROUGH the relays `addrs` name — the ones
244
+ * whose `/p2p/<relayPeerId>/p2p-circuit` component names one of them. This is the
245
+ * "held" question a supervisor over a SUBSET of the node's relays has to ask: a
246
+ * strand node runs one supervisor per relay, and relay X's supervisor must not be
247
+ * satisfied by relay Y's addr, or a lost X is never re-driven.
248
+ *
249
+ * Falls back to EVERY circuit addr when any entry names no relay peer id (no
250
+ * `/p2p/` component, or unparsable): such an addr can still be dialed and reserved
251
+ * through, but the addr it earns cannot be attributed to it, so "any circuit addr"
252
+ * is the only answer that does not mark a live reservation as lost. The control
253
+ * node passes its whole relay list, so its answer is the same either way.
254
+ */
255
+ export function circuitMultiaddrsVia(node: Libp2p, addrs: readonly string[]): string[] {
256
+ const held = circuitMultiaddrs(node);
257
+ const relayIds = addrs.map(relayPeerIdOf);
258
+ if (relayIds.some((id) => id === null)) {
259
+ return held;
260
+ }
261
+ return held.filter((circuit) => relayIds.includes(relayPeerIdOf(circuit)));
262
+ }
263
+
264
+ /**
265
+ * The NORMALIZED peer id of the relay `addr` names: the `/p2p/` component just
266
+ * before `/p2p-circuit` when there is one, else the trailing `/p2p/` component
267
+ * (a relay DIAL addr). `null` when there is none, or `addr` does not parse.
268
+ *
269
+ * Normalized through `peerIdFromString(…).toString()` so a relay written in a
270
+ * different encoding than libp2p publishes (a CID form, say) still matches.
271
+ */
272
+ function relayPeerIdOf(addr: string): string | null {
273
+ try {
274
+ const components = multiaddr(addr).getComponents();
275
+ const circuitIdx = components.findIndex((c) => c.name === 'p2p-circuit');
276
+ const relayScope = circuitIdx >= 0 ? components.slice(0, circuitIdx) : components;
277
+ const raw = trailingPeerId(multiaddr(relayScope));
278
+ return raw === null ? null : peerIdFromString(raw).toString();
279
+ } catch {
280
+ return null;
281
+ }
282
+ }
283
+
284
+ /**
285
+ * The running node's circuit-relay transport, or `null` when it has none.
286
+ *
287
+ * There is no public libp2p API for "reserve on THIS specific relay", so this
288
+ * reaches through `node.components.transportManager` — libp2p's internal layout.
289
+ * That coupling is deliberate and bounded: every step is optional-chained and the
290
+ * whole thing returns `null` rather than throwing, and a spec pins the seam so a
291
+ * libp2p upgrade that moves it fails loudly instead of silently reverting this
292
+ * module to the discovery wait that never fires.
293
+ */
294
+ export function findCircuitRelayTransport(node: Libp2p): CircuitRelayTransportLike | null {
295
+ for (const transport of nodeTransports(node)) {
296
+ const store = (transport as { reservationStore?: unknown }).reservationStore;
297
+ if (isReservationStore(store)) {
298
+ return { reservationStore: store };
299
+ }
300
+ }
301
+ return null;
302
+ }
303
+
304
+ function nodeTransports(node: Libp2p): readonly unknown[] {
305
+ const manager = (node as Libp2p & Libp2pComponentsLike).components?.transportManager;
306
+ if (typeof manager?.getTransports !== 'function') {
307
+ log('No transportManager.getTransports() on this node — libp2p internals moved?');
308
+ return [];
309
+ }
310
+ try {
311
+ return manager.getTransports();
312
+ } catch (err) {
313
+ log('transportManager.getTransports() threw: %o', err);
314
+ return [];
315
+ }
316
+ }
317
+
318
+ function isReservationStore(value: unknown): value is RelayReservationStoreLike {
319
+ if (typeof value !== 'object' || value === null) {
320
+ return false;
321
+ }
322
+ const store = value as Partial<RelayReservationStoreLike>;
323
+ return typeof store.addRelay === 'function' && typeof store.hasReservation === 'function';
324
+ }
325
+
326
+ /** Sentinel resolved by the wait arm of {@link requestOneReservation}'s race. */
327
+ const WAIT_OVER = Symbol('relay-reservation-wait-over');
328
+
329
+ /** A relay that answered its dial, paired with the address it was dialed at. */
330
+ interface ConnectedRelay {
331
+ addr: string;
332
+ peerId: PeerId;
333
+ }
334
+
335
+ /**
336
+ * Whether `signal` has been aborted.
337
+ *
338
+ * A function rather than an inline `signal?.aborted` because a signal's `aborted` flag
339
+ * is a readonly boolean: one `if (signal?.aborted)` narrows every LATER read of it
340
+ * to `false`, and TypeScript then rejects the re-check as a comparison that can
341
+ * never hold. Re-checking after each await is exactly what cancellation is, so the
342
+ * narrowing is the thing that is wrong, not the check.
343
+ */
344
+ function aborted(signal: AbortSignal | undefined): boolean {
345
+ return signal !== undefined && signal.aborted;
346
+ }
347
+
348
+ /**
349
+ * `setTimeout` as a promise, cut short by `signal`.
350
+ *
351
+ * EVERY wait inside a drive routes through here, because a wait that merely LOSES
352
+ * a `Promise.race` leaves its timer pending — and a pending timer keeps a Node
353
+ * process alive for the rest of its duration, which is exactly the delay a
354
+ * cancelled drive exists to shed. So the timer is cleared on both endings, not
355
+ * only on its own.
356
+ *
357
+ * NOTE: no spec catches a wait that skips this helper. The cancellation specs
358
+ * assert prompt RETURN, which a `Promise.race` gives with its losing timer still
359
+ * pending — only the process actually exiting proves the clearing, and that was
360
+ * measured by hand rather than pinned. If a wait is ever added outside this
361
+ * helper, pin it with a spawned-child process-exit test instead.
362
+ */
363
+ function delay(ms: number, signal?: AbortSignal): Promise<void> {
364
+ if (aborted(signal)) {
365
+ return Promise.resolve();
366
+ }
367
+ return new Promise((resolve) => {
368
+ const finish = (): void => {
369
+ clearTimeout(timer);
370
+ signal?.removeEventListener('abort', finish);
371
+ resolve();
372
+ };
373
+ const timer = setTimeout(finish, ms);
374
+ signal?.addEventListener('abort', finish, { once: true });
375
+ });
376
+ }
377
+
378
+ /**
379
+ * Relay `from`'s abort into `to`, and hand back the detach that must run on every
380
+ * exit path.
381
+ *
382
+ * By hand rather than through `AbortSignal.any`, for the same reason this module
383
+ * builds its deadline from an explicit `AbortController` rather than
384
+ * `AbortSignal.timeout`: React Native/Hermes runs this same code, and `any` is
385
+ * newer still — its polyfill also leaks listeners onto inputs that never abort,
386
+ * which is what the returned detach avoids here.
387
+ */
388
+ function linkAbort(from: AbortSignal | undefined, to: AbortController): () => void {
389
+ if (from === undefined) {
390
+ return () => { /* nothing was attached */ };
391
+ }
392
+ if (from.aborted) {
393
+ to.abort();
394
+ return () => { /* nothing was attached */ };
395
+ }
396
+ const forward = (): void => to.abort();
397
+ from.addEventListener('abort', forward, { once: true });
398
+ return () => from.removeEventListener('abort', forward);
399
+ }
400
+
401
+ /**
402
+ * Dial every relay in `addrs`, ask the first one that answers for a reservation
403
+ * slot, then wait until a `/p2p-circuit` address appears.
404
+ *
405
+ * Never throws — a dial rejection, a rejected reservation, a MALFORMED address,
406
+ * or a timeout all come back as an `error` string. A dial that throws does NOT
407
+ * cost the rest of the list: one dead relay among two must not cost the
408
+ * reservation on the live one, so every addr is dialed and the first error (in
409
+ * list order) is kept. A reservation that lands wins over any earlier error
410
+ * (`error: null`).
411
+ *
412
+ * `timeoutMs` bounds the WHOLE drive — dials, reservation requests and the wait
413
+ * share one deadline. `opts.signal` bounds it from the other side: every phase
414
+ * below returns as soon as it trips, and the drive reports `cancelled` rather than
415
+ * inventing a failure for a relay that was never given a chance to answer.
416
+ */
417
+ export async function driveRelayReservation(
418
+ node: Libp2p,
419
+ addrs: readonly string[],
420
+ opts?: RelayReserveOptions
421
+ ): Promise<RelayReserveResult> {
422
+ if (addrs.length === 0) {
423
+ return { error: null, cancelled: false };
424
+ }
425
+ const signal = opts?.signal;
426
+ if (aborted(signal)) {
427
+ return { error: null, cancelled: true };
428
+ }
429
+ const timeoutMs = opts?.timeoutMs ?? DEFAULT_RELAY_RESERVE_TIMEOUT_MS;
430
+ // Clamped: a caller-supplied 0 would spin the poll loop hot until the deadline.
431
+ const pollMs = Math.max(1, opts?.pollMs ?? DEFAULT_RELAY_RESERVE_POLL_MS);
432
+ const deadline = Date.now() + timeoutMs;
433
+
434
+ const { connected, error: dialError } = await dialRelays(node, addrs, deadline, signal);
435
+ const attempt = await requestReservation(node, connected, deadline, signal);
436
+ // NOTE: a REJECTED reservation still spends the rest of the deadline polling,
437
+ // because discovery may independently land one (only the no-transport case is
438
+ // `fatal`). So a misconfigured node reports its now-legible reason a full
439
+ // `timeoutMs` late. If startup latency on that path ever matters, shorten the
440
+ // wait once every connected relay has rejected — do not skip it outright.
441
+ if (!attempt.fatal && (await waitForCircuitReservation(node, addrs, deadline, pollMs, signal))) {
442
+ return { error: null, cancelled: false };
443
+ }
444
+ // Checked AFTER the success above, so a reservation that landed in the same turn
445
+ // the signal tripped is still reported as landed. Below it, the reasons the
446
+ // phases assembled describe the cancellation rather than the relay, so they are
447
+ // dropped: a cancelled drive has nothing to say about the relay's health.
448
+ if (aborted(signal)) {
449
+ return { error: null, cancelled: true };
450
+ }
451
+ return {
452
+ error: attempt.error ?? dialError ?? `no circuit reservation within ${timeoutMs}ms`,
453
+ cancelled: false
454
+ };
455
+ }
456
+
457
+ /**
458
+ * Dial every relay CONCURRENTLY under the drive's shared deadline. Reports the
459
+ * relays that answered (in list order, for the reservation step) and the first
460
+ * failure in LIST order (`null` when every dial connected).
461
+ *
462
+ * Concurrent and deadline-bound because this whole drive is awaited on a browser
463
+ * tab's startup path: dialing serially with libp2p's own (much longer) per-dial
464
+ * timeout meant N unreachable relays cost N dial timeouts before the reservation
465
+ * request even began, so `timeoutMs` bounded only the tail of the operation.
466
+ *
467
+ * Aborting a dial at the deadline is not a lost reservation — the steps that
468
+ * follow have no time left either, so the drive would report `error` regardless.
469
+ *
470
+ * The caller's `signal` aborts the same dials, through the same controller: a
471
+ * hanging dial is the longest thing a cancelled drive can be sitting in.
472
+ */
473
+ async function dialRelays(
474
+ node: Libp2p,
475
+ addrs: readonly string[],
476
+ deadline: number,
477
+ signal?: AbortSignal
478
+ ): Promise<{ connected: ConnectedRelay[]; error: string | null }> {
479
+ // An explicit controller, not `AbortSignal.timeout` — the latter is not
480
+ // reliably present on React Native/Hermes, which runs this same module.
481
+ const controller = new AbortController();
482
+ const timer = setTimeout(() => controller.abort(), Math.max(0, deadline - Date.now()));
483
+ const unlink = linkAbort(signal, controller);
484
+ try {
485
+ const results = await Promise.allSettled(
486
+ addrs.map((addr) => dialOne(node, addr, controller.signal))
487
+ );
488
+ return { connected: connectedRelays(addrs, results), error: firstDialError(addrs, results) };
489
+ } finally {
490
+ clearTimeout(timer);
491
+ unlink();
492
+ }
493
+ }
494
+
495
+ /**
496
+ * One dial, with the address PARSED INSIDE the promise.
497
+ *
498
+ * `multiaddr()` throws SYNCHRONOUSLY on a malformed string, and a throw out of
499
+ * the `map` callback escapes `Promise.allSettled` altogether — it would reject
500
+ * the whole drive (breaking the never-throws contract) and discard the dials to
501
+ * the other, perfectly good, addrs. `async` demotes it to a settled rejection,
502
+ * which is already exactly how a dial failure is reported.
503
+ */
504
+ async function dialOne(
505
+ node: Libp2p,
506
+ addr: string,
507
+ signal: AbortSignal
508
+ ): Promise<{ remotePeer: PeerId }> {
509
+ return node.dial(multiaddr(addr), { signal });
510
+ }
511
+
512
+ function connectedRelays(
513
+ addrs: readonly string[],
514
+ results: readonly PromiseSettledResult<{ remotePeer: PeerId }>[]
515
+ ): ConnectedRelay[] {
516
+ const connected: ConnectedRelay[] = [];
517
+ results.forEach((result, index) => {
518
+ if (result.status !== 'fulfilled') return;
519
+ connected.push({ addr: addrs[index], peerId: result.value.remotePeer });
520
+ });
521
+ return connected;
522
+ }
523
+
524
+ /** Log every dial rejection; return the first one in list order. */
525
+ function firstDialError(
526
+ addrs: readonly string[],
527
+ results: readonly PromiseSettledResult<unknown>[]
528
+ ): string | null {
529
+ let first: string | null = null;
530
+ results.forEach((result, index) => {
531
+ if (result.status !== 'rejected') return;
532
+ const message = result.reason instanceof Error ? result.reason.message : String(result.reason);
533
+ log('Relay dial failed (%s): %s', addrs[index], message);
534
+ first ??= message;
535
+ });
536
+ return first;
537
+ }
538
+
539
+ /**
540
+ * Outcome of the explicit reservation request.
541
+ *
542
+ * `fatal` means no `/p2p-circuit` address can EVER appear (the node has no
543
+ * circuit-relay transport at all), so the caller must report immediately rather
544
+ * than spend the rest of the deadline polling for something that cannot happen.
545
+ * A rejected request is NOT fatal: discovery may still land a reservation for a
546
+ * relay that does happen to share this node's identify prefix.
547
+ */
548
+ interface ReservationAttempt {
549
+ error: string | null;
550
+ fatal: boolean;
551
+ }
552
+
553
+ /**
554
+ * Ask the connected relays, in list order, for a reservation slot; stop at the
555
+ * first success.
556
+ *
557
+ * `'discovered'`, not `'configured'`: the search listener's
558
+ * `relay:created-reservation` handler ignores `configured` reservations outright,
559
+ * so the `/p2p-circuit` listen address would never be published and
560
+ * `getMultiaddrs()` would stay empty even though the reservation succeeded.
561
+ * `'discovered'` consumes the pending-reservation id the bare `/p2p-circuit`
562
+ * listener registered, which is exactly what that handler matches on.
563
+ *
564
+ * Sequential, not concurrent: a bare `/p2p-circuit` listener registers exactly
565
+ * ONE pending reservation, so a second concurrent `addRelay` would be rejected
566
+ * with `HadEnoughRelaysError` — noise, not a failure. Running discovery is not a
567
+ * conflict either; `addRelay` dedupes through its own peer queue, so a relay that
568
+ * genuinely is discoverable still reserves exactly once.
569
+ */
570
+ async function requestReservation(
571
+ node: Libp2p,
572
+ connected: readonly ConnectedRelay[],
573
+ deadline: number,
574
+ signal?: AbortSignal
575
+ ): Promise<ReservationAttempt> {
576
+ if (connected.length === 0) {
577
+ // Nothing answered — the dial error is the whole story.
578
+ return { error: null, fatal: false };
579
+ }
580
+ const transport = findCircuitRelayTransport(node);
581
+ if (transport === null) {
582
+ return {
583
+ error: 'node has no circuit-relay transport — add circuitRelayTransport() to its transports',
584
+ fatal: true
585
+ };
586
+ }
587
+ let firstError: string | null = null;
588
+ for (const relay of connected) {
589
+ if (transport.reservationStore.hasReservation(relay.peerId)) {
590
+ return { error: null, fatal: false };
591
+ }
592
+ // A cancelled drive stops here rather than asking the next relay: the caller is
593
+ // tearing this node down, so another hop request against it can only fail.
594
+ if (Date.now() >= deadline || aborted(signal)) {
595
+ break;
596
+ }
597
+ const failure = await requestOneReservation(
598
+ transport.reservationStore,
599
+ relay,
600
+ deadline,
601
+ signal
602
+ );
603
+ if (failure === null) {
604
+ return { error: null, fatal: false };
605
+ }
606
+ firstError ??= failure;
607
+ }
608
+ return { error: firstError, fatal: false };
609
+ }
610
+
611
+ /**
612
+ * One `addRelay` call, bounded by the drive's deadline and by the caller's signal.
613
+ * Returns `null` on success, or the reason it stopped waiting.
614
+ *
615
+ * Raced rather than passed a signal because `addRelay` accepts none and runs on
616
+ * libp2p's own (much longer) reservation timeout: without the race a drive given
617
+ * 1.5 s would sit on a silent relay for libp2p's timeout instead. The abandoned
618
+ * promise stays handled — `Promise.race` attaches its own handlers — so a later
619
+ * rejection is not unhandled, and is not logged either: a request abandoned at a
620
+ * cancellation must not print a relay failure the caller would read as real.
621
+ *
622
+ * `waitOver` ends the wait on BOTH routes — the caller's abort, relayed in, and the
623
+ * race settling some other way, aborted in the `finally`. Out-racing the deadline
624
+ * timer is not enough: the loser stays pending, and a pending timer is what holds
625
+ * a Node process open past the stop that asked for it.
626
+ */
627
+ async function requestOneReservation(
628
+ store: RelayReservationStoreLike,
629
+ relay: ConnectedRelay,
630
+ deadline: number,
631
+ signal?: AbortSignal
632
+ ): Promise<string | null> {
633
+ const waitOver = new AbortController();
634
+ const unlink = linkAbort(signal, waitOver);
635
+ try {
636
+ const outcome = await Promise.race([
637
+ store.addRelay(relay.peerId, 'discovered'),
638
+ delay(Math.max(0, deadline - Date.now()), waitOver.signal).then(() => WAIT_OVER)
639
+ ]);
640
+ if (outcome !== WAIT_OVER) {
641
+ return null;
642
+ }
643
+ if (aborted(signal)) {
644
+ return `relay reservation request to ${relay.addr} was cancelled`;
645
+ }
646
+ log('Relay reservation request (%s) still pending at the deadline', relay.addr);
647
+ return `relay reservation request to ${relay.addr} did not complete before the deadline`;
648
+ } catch (err) {
649
+ const message = describeReservationFailure(err, relay.addr);
650
+ log('Relay reservation failed (%s): %s', relay.addr, message);
651
+ return message;
652
+ } finally {
653
+ unlink();
654
+ waitOver.abort();
655
+ }
656
+ }
657
+
658
+ /**
659
+ * Turn libp2p's reservation rejection into a reason that names the actual cause.
660
+ *
661
+ * `HadEnoughRelaysError` needs translating rather than passing through: its own
662
+ * message ("we do not need any more relays") says the opposite of what happened.
663
+ * A `'discovered'` reservation is refused when the node holds NO pending
664
+ * reservation id, and a node holds one only while it listens on the bare
665
+ * `/p2p-circuit` search address — so the real cause is a missing listen address.
666
+ */
667
+ function describeReservationFailure(err: unknown, addr: string): string {
668
+ // NOTE: libp2p adds a peer to the reservation store's `relayFilter` when a
669
+ // request fails with `DialError` or `UnsupportedProtocolError`, and the failure
670
+ // path does not reset that filter (it only resets when a reservation is actually
671
+ // removed). So a SECOND drive against the same relay in the same process reports
672
+ // `ListenError: The relay was previously invalid` even if the relay has since
673
+ // recovered. `RelayReservationLoop` clears the entry before every attempt (see
674
+ // {@link clearRelayFilterEntry}); a caller that re-drives WITHOUT the supervisor
675
+ // still has to deal with the filter itself.
676
+ const name = err instanceof Error ? err.name : '';
677
+ const message = err instanceof Error ? err.message : String(err);
678
+ switch (name) {
679
+ case 'HadEnoughRelaysError':
680
+ return `relay reservation on ${addr} was not requested: this node holds no pending circuit reservation — it is not listening on the bare /p2p-circuit address`;
681
+ case 'UnsupportedProtocolError':
682
+ return `peer at ${addr} does not speak the circuit-relay hop protocol — it is not a relay`;
683
+ default:
684
+ return `relay reservation on ${addr} failed: ${message}`;
685
+ }
686
+ }
687
+
688
+ /**
689
+ * Poll until the node advertises a `/p2p-circuit` address through one of `addrs`'
690
+ * relays ({@link circuitMultiaddrsVia}), the deadline passes, or the drive is
691
+ * cancelled. This is the phase a cancellation has to reach: whatever the dial and
692
+ * the reservation request shed, an abandoned drive used to spend here instead,
693
+ * polling a node whose transports were already being torn down.
694
+ *
695
+ * Still a poll even though the reservation is now requested explicitly: `addRelay`
696
+ * resolving means the RELAY accepted, while the listen address is published a tick
697
+ * later by the listener's `relay:created-reservation` handler, and a reservation
698
+ * that discovery lands independently has no return value to await at all.
699
+ *
700
+ * NOTE: polls rather than subscribing to libp2p's `self:peer:update` — it keeps
701
+ * this free of libp2p event-name coupling. If 250 ms of reservation latency ever
702
+ * matters, switch to the event and keep the poll as a fallback.
703
+ */
704
+ async function waitForCircuitReservation(
705
+ node: Libp2p,
706
+ addrs: readonly string[],
707
+ deadline: number,
708
+ pollMs: number,
709
+ signal?: AbortSignal
710
+ ): Promise<boolean> {
711
+ for (;;) {
712
+ if (circuitMultiaddrsVia(node, addrs).length > 0) {
713
+ return true;
714
+ }
715
+ if (Date.now() >= deadline || aborted(signal)) {
716
+ return false;
717
+ }
718
+ await delay(Math.min(pollMs, Math.max(0, deadline - Date.now())), signal);
719
+ }
720
+ }
721
+
722
+ /** Gap between liveness checks while a reservation is held. */
723
+ export const DEFAULT_RELAY_CHECK_MS = 5_000;
724
+ /** Backoff before the first re-drive after a failed attempt. */
725
+ export const DEFAULT_RELAY_MIN_BACKOFF_MS = 2_000;
726
+ /** Ceiling the backoff doubles up to. */
727
+ export const DEFAULT_RELAY_MAX_BACKOFF_MS = 60_000;
728
+
729
+ /**
730
+ * Everything one drive takes, minus its `signal`, plus the loop's own cadence.
731
+ *
732
+ * `signal` is omitted rather than inherited because these options are handed
733
+ * straight to every drive: a caller-supplied one would cancel each attempt without
734
+ * the loop knowing, leaving it to reschedule drives that return immediately and
735
+ * forever. The way to cancel a supervisor is
736
+ * {@link RelayReservationSupervisor.stop}, which owns the signal it passes down.
737
+ */
738
+ export interface RelayReservationSupervisorOptions extends Omit<RelayReserveOptions, 'signal'> {
739
+ /** Gap between liveness checks while a reservation is held. Default 5_000. */
740
+ checkMs?: number;
741
+ /** Backoff before the first re-drive after a failure. Default 2_000. */
742
+ minBackoffMs?: number;
743
+ /** Backoff ceiling. Default 60_000. */
744
+ maxBackoffMs?: number;
745
+ /**
746
+ * Awaited before every drive AFTER the first — never before the first attempt,
747
+ * which the caller has typically prepared for already. A hook that throws or
748
+ * rejects is logged and the drive still runs: the hook is preparation, and a
749
+ * failed preparation must not cost the attempt itself.
750
+ *
751
+ * What a strand node uses it for: re-announcing its delegate peer id to the relay
752
+ * about to be re-dialed. A party control node running the relay server admits a
753
+ * strand node on an in-memory delegate grant, and a relay restart drops every
754
+ * grant it held — so a re-drive that did not re-announce first would be denied
755
+ * at the relay's connection gate.
756
+ */
757
+ beforeRedrive?: () => Promise<void> | void;
758
+ }
759
+
760
+ /**
761
+ * A running retry loop for one node + relay list. Obtained from
762
+ * {@link superviseRelayReservation}; its only imperative is {@link stop}.
763
+ */
764
+ export interface RelayReservationSupervisor {
765
+ /**
766
+ * Resolves once the FIRST attempt has settled — so a caller can await startup
767
+ * exactly as it awaited a single {@link driveRelayReservation}, and the retries
768
+ * carry on in the background afterwards. Also resolves on {@link stop}, so an
769
+ * awaiting caller is never left hanging.
770
+ */
771
+ readonly firstAttempt: Promise<void>;
772
+ /** True while a drive is in flight. */
773
+ readonly driving: boolean;
774
+ /** Epoch ms of the next scheduled tick; `null` while a drive is running. */
775
+ readonly retryAtMs: number | null;
776
+ /** Reason the last drive produced no reservation; `null` once one is held. */
777
+ readonly lastError: string | null;
778
+ /**
779
+ * Idempotent. Clears the timer so no further drive is scheduled, and CANCELS the
780
+ * drive already in flight: it stops dialing or polling, clears every timer it
781
+ * holds and reports `cancelled`, so a teardown does not trail an attempt against
782
+ * the node it is dismantling. That result is discarded — a cancelled drive is
783
+ * not a failure — and nothing follows it.
784
+ */
785
+ stop(): void;
786
+ }
787
+
788
+ /**
789
+ * Keep asking for a relay reservation until one is held, then keep watching that
790
+ * it still is — the thing that makes a lost reservation recover on its own.
791
+ *
792
+ * Needed because nothing else re-drives: libp2p re-fills a search listener's
793
+ * freed slot from relay DISCOVERY, and a cadre node's namespaced identify puts
794
+ * discovery permanently out of reach (see the module header). Without this loop a
795
+ * relay restart left a browser tab undialable until the user reloaded the page.
796
+ *
797
+ * Per tick:
798
+ * - a reservation is held → reset the backoff, clear the error, re-check in
799
+ * `checkMs`. No drive: a healthy node must not re-request every few seconds.
800
+ * - otherwise → un-poison the reservation store's relay filter (see
801
+ * {@link clearRelayFilterEntry}) and run ONE {@link driveRelayReservation}.
802
+ * If that lands a reservation, rejoin the healthy path above; if not, sleep
803
+ * the current backoff and double it up to `maxBackoffMs`.
804
+ *
805
+ * "Held" is judged PER RELAY — a circuit addr through one of `addrs`' relays
806
+ * ({@link circuitMultiaddrsVia}) — so several loops over one node, one relay each
807
+ * (a strand node), each re-drive exactly the relay they own. Every drive after the
808
+ * first is preceded by the optional `beforeRedrive` hook
809
+ * ({@link RelayReservationSupervisorOptions}).
810
+ *
811
+ * Starts immediately; the first tick runs before this returns.
812
+ */
813
+ export function superviseRelayReservation(
814
+ node: Libp2p,
815
+ addrs: readonly string[],
816
+ opts?: RelayReservationSupervisorOptions
817
+ ): RelayReservationSupervisor {
818
+ return new RelayReservationLoop(node, [...addrs], opts ?? {});
819
+ }
820
+
821
+ /**
822
+ * Forget that `addr`'s peer ever failed a reservation request, so the next
823
+ * attempt is actually made rather than refused out of hand.
824
+ *
825
+ * `ReservationStore` records a peer in `relayFilter` when its reservation request
826
+ * fails with `DialError` or `UnsupportedProtocolError`, and NOTHING on that path
827
+ * ever clears it: the reset lives in `#checkReservationCount`, which only runs
828
+ * when a reservation is genuinely removed, and `#removeReservation` early-returns
829
+ * when there was never one. So a relay that was briefly not-a-relay (or died
830
+ * between our dial and the hop request) stays permanently rejected with
831
+ * `The relay was previously invalid` — measured, not inferred.
832
+ *
833
+ * Fails soft in every direction: no `relayFilter`, no `remove`, an addr with no
834
+ * peer id, a malformed addr — all mean "no un-poisoning", never a throw. The
835
+ * retry loop still recovers the common case without this, because a relay that is
836
+ * simply DOWN fails our own dial first and never reaches the filter.
837
+ *
838
+ * Returns whether an entry was actually removed (for specs; callers ignore it).
839
+ */
840
+ export function clearRelayFilterEntry(store: RelayReservationStoreLike, addr: string): boolean {
841
+ const filter = store.relayFilter;
842
+ if (typeof filter?.remove !== 'function') {
843
+ log('Reservation store has no removable relayFilter — cannot un-poison %s', addr);
844
+ return false;
845
+ }
846
+ try {
847
+ // The peer id is in the multiaddr, so this costs no dial and can run before one.
848
+ const peerId = trailingPeerId(multiaddr(addr));
849
+ if (peerId === null) {
850
+ // NOTE: an addr with no `/p2p/` component can still be dialed and reserved
851
+ // through (the peer id comes off the connection), but it can never be
852
+ // un-poisoned — so for THAT addr a poisoned filter is permanent again. No
853
+ // caller supplies such an addr today; if one ever does, resolve the peer id
854
+ // from the live connection instead of the multiaddr.
855
+ return false;
856
+ }
857
+ return filter.remove(peerIdFromString(peerId).toMultihash().bytes);
858
+ } catch (err) {
859
+ log('Could not clear the relayFilter entry for %s: %o', addr, err);
860
+ return false;
861
+ }
862
+ }
863
+
864
+ /** The self-rescheduling loop behind {@link superviseRelayReservation}. */
865
+ class RelayReservationLoop implements RelayReservationSupervisor {
866
+ readonly firstAttempt: Promise<void>;
867
+
868
+ private readonly checkMs: number;
869
+ private readonly minBackoffMs: number;
870
+ private readonly maxBackoffMs: number;
871
+ private backoffMs: number;
872
+ private timer: ReturnType<typeof setTimeout> | null = null;
873
+ /** Tripped by {@link stop}; the only thing that cancels a drive of this loop's. */
874
+ private readonly cancel = new AbortController();
875
+ private stopped = false;
876
+ private inFlight = false;
877
+ /** Drives started so far — the `beforeRedrive` hook runs from the second one on. */
878
+ private drives = 0;
879
+ private nextTickAtMs: number | null = null;
880
+ private failure: string | null = null;
881
+ private settleFirstAttempt: () => void = () => {};
882
+ private firstAttemptSettled = false;
883
+
884
+ constructor(
885
+ private readonly node: Libp2p,
886
+ private readonly addrs: readonly string[],
887
+ private readonly opts: RelayReservationSupervisorOptions
888
+ ) {
889
+ // Clamped away from 0: a caller-supplied 0 would spin the loop hot.
890
+ this.checkMs = Math.max(1, opts.checkMs ?? DEFAULT_RELAY_CHECK_MS);
891
+ this.minBackoffMs = Math.max(1, opts.minBackoffMs ?? DEFAULT_RELAY_MIN_BACKOFF_MS);
892
+ this.maxBackoffMs = Math.max(
893
+ this.minBackoffMs,
894
+ opts.maxBackoffMs ?? DEFAULT_RELAY_MAX_BACKOFF_MS
895
+ );
896
+ this.backoffMs = this.minBackoffMs;
897
+ this.firstAttempt = new Promise((resolve) => {
898
+ this.settleFirstAttempt = resolve;
899
+ });
900
+ void this.tick();
901
+ }
902
+
903
+ get driving(): boolean {
904
+ return this.inFlight;
905
+ }
906
+
907
+ get retryAtMs(): number | null {
908
+ return this.nextTickAtMs;
909
+ }
910
+
911
+ get lastError(): string | null {
912
+ return this.failure;
913
+ }
914
+
915
+ stop(): void {
916
+ if (this.stopped) {
917
+ return;
918
+ }
919
+ this.stopped = true;
920
+ // The scheduled attempt and the running one are two different things to end:
921
+ // the timer covers the first, the signal the second.
922
+ this.cancel.abort();
923
+ if (this.timer !== null) {
924
+ clearTimeout(this.timer);
925
+ this.timer = null;
926
+ }
927
+ this.nextTickAtMs = null;
928
+ this.settleFirst();
929
+ }
930
+
931
+ private async tick(): Promise<void> {
932
+ if (this.stopped) {
933
+ return;
934
+ }
935
+ this.nextTickAtMs = null;
936
+ if (this.reservationHeld()) {
937
+ this.onReservationHeld();
938
+ return;
939
+ }
940
+ await this.driveOnce();
941
+ if (this.stopped) {
942
+ return;
943
+ }
944
+ this.settleFirst();
945
+ // A drive that LANDED a reservation resumes the healthy cadence immediately.
946
+ // Backing off here instead would leave the first liveness check after a long
947
+ // outage a fully grown backoff away (up to `maxBackoffMs`), so a reservation
948
+ // lost again right after recovery would go unnoticed for that whole window.
949
+ if (this.reservationHeld()) {
950
+ this.onReservationHeld();
951
+ return;
952
+ }
953
+ this.scheduleBackoff();
954
+ }
955
+
956
+ /** Per relay: only a circuit addr THROUGH one of this loop's relays counts. */
957
+ private reservationHeld(): boolean {
958
+ return circuitMultiaddrsVia(this.node, this.addrs).length > 0;
959
+ }
960
+
961
+ /** Healthy tick: nothing to request, so only reset and re-check later. */
962
+ private onReservationHeld(): void {
963
+ this.backoffMs = this.minBackoffMs;
964
+ this.failure = null;
965
+ this.settleFirst();
966
+ this.schedule(this.checkMs);
967
+ }
968
+
969
+ private async driveOnce(): Promise<void> {
970
+ this.inFlight = true;
971
+ try {
972
+ if (this.drives > 0) {
973
+ await this.runBeforeRedrive();
974
+ // A stop that arrived while the hook ran: nothing follows it, so do not dial
975
+ // a node that is being torn down.
976
+ if (this.stopped) {
977
+ return;
978
+ }
979
+ }
980
+ this.drives += 1;
981
+ this.unpoisonRelayFilter();
982
+ const { error, cancelled } = await driveRelayReservation(this.node, this.addrs, {
983
+ ...this.opts,
984
+ signal: this.cancel.signal
985
+ });
986
+ // A cancelled drive landed nothing AND failed at nothing, so it has no status
987
+ // to report: recording it would surface a teardown artifact through
988
+ // `getRelayReservationState()` as if the relay had refused.
989
+ if (!this.stopped && !cancelled) {
990
+ this.failure = error;
991
+ }
992
+ } catch (err) {
993
+ // `driveRelayReservation` is fail-soft by contract, so reaching here means
994
+ // that contract broke. The loop must survive it anyway: an escaping
995
+ // rejection would leave `firstAttempt` pending FOREVER (hanging every
996
+ // caller that awaits a reservation at startup) and schedule no further
997
+ // attempt, which is the failure this whole supervisor exists to prevent.
998
+ const message = err instanceof Error ? err.message : String(err);
999
+ log('Relay reservation drive threw, which it should not: %s', message);
1000
+ if (!this.stopped) {
1001
+ this.failure = message;
1002
+ }
1003
+ } finally {
1004
+ this.inFlight = false;
1005
+ }
1006
+ }
1007
+
1008
+ private scheduleBackoff(): void {
1009
+ const wait = this.backoffMs;
1010
+ this.backoffMs = Math.min(this.backoffMs * 2, this.maxBackoffMs);
1011
+ this.schedule(wait);
1012
+ }
1013
+
1014
+ /** The caller's `beforeRedrive` hook, contained: a throw or rejection is logged, never propagated. */
1015
+ private async runBeforeRedrive(): Promise<void> {
1016
+ const hook = this.opts.beforeRedrive;
1017
+ if (hook === undefined) {
1018
+ return;
1019
+ }
1020
+ try {
1021
+ await hook();
1022
+ } catch (err) {
1023
+ log('beforeRedrive hook failed (%o); driving the reservation anyway: %o', this.addrs, err);
1024
+ }
1025
+ }
1026
+
1027
+ private unpoisonRelayFilter(): void {
1028
+ const transport = findCircuitRelayTransport(this.node);
1029
+ if (transport === null) {
1030
+ return;
1031
+ }
1032
+ for (const addr of this.addrs) {
1033
+ clearRelayFilterEntry(transport.reservationStore, addr);
1034
+ }
1035
+ }
1036
+
1037
+ private schedule(ms: number): void {
1038
+ if (this.stopped) {
1039
+ return;
1040
+ }
1041
+ this.nextTickAtMs = Date.now() + ms;
1042
+ this.timer = setTimeout(() => {
1043
+ this.timer = null;
1044
+ void this.tick();
1045
+ }, ms);
1046
+ // Node keeps the process alive while a timer is pending, so an un-unref'd
1047
+ // supervisor would hang every CLI run and vitest worker that ever reserved.
1048
+ // Cast + optional-chain: browsers and React Native have no `unref`.
1049
+ (this.timer as { unref?: () => void }).unref?.();
1050
+ }
1051
+
1052
+ private settleFirst(): void {
1053
+ if (this.firstAttemptSettled) {
1054
+ return;
1055
+ }
1056
+ this.firstAttemptSettled = true;
1057
+ this.settleFirstAttempt();
1058
+ }
1059
+ }
1060
+
1061
+ /**
1062
+ * Derive the reservation posture, reading the node's circuit addrs LIVE. Pure
1063
+ * apart from that read, so the precedence is testable on its own:
1064
+ *
1065
+ * | condition | status |
1066
+ * | ------------------------ | ----------------------------------------------- |
1067
+ * | no addrs supplied | `none` |
1068
+ * | live circuit addrs held | `reserved` (`error: null`) |
1069
+ * | a drive is in flight | `dialing` |
1070
+ * | a retry is scheduled | `retrying` |
1071
+ * | otherwise | `error` |
1072
+ *
1073
+ * `reserved` is checked BEFORE `error` on purpose: the circuit addrs are read
1074
+ * live, so a reservation that lands by ANY route supersedes a stale error string
1075
+ * without a second drive.
1076
+ *
1077
+ * `retrying` sits between the two so that `error` carries a sharper meaning:
1078
+ * NOBODY IS GOING TO TRY AGAIN. A lost reservation does come back on its own now,
1079
+ * as long as a {@link RelayReservationSupervisor} is running — that loop is the
1080
+ * only thing that re-drives, since libp2p re-fills a search listener's freed slot
1081
+ * from relay DISCOVERY, which a cadre node's namespaced identify puts permanently
1082
+ * out of reach (see the module header). So `error` means the supervisor was
1083
+ * stopped, was never started, or there is no node at all.
1084
+ *
1085
+ * `retryAtMs` is the supervisor's next scheduled tick (`null` while a drive runs
1086
+ * or when there is no supervisor); it both selects `retrying` and is passed
1087
+ * through so a UI can count down to the next attempt.
1088
+ */
1089
+ export function resolveRelayReservationState(
1090
+ node: Libp2p | null,
1091
+ addrs: readonly string[],
1092
+ lastError: string | null,
1093
+ driving: boolean,
1094
+ retryAtMs: number | null
1095
+ ): RelayReservationState {
1096
+ if (addrs.length === 0) {
1097
+ return { status: 'none', addrs: [], circuitAddrs: [], error: null, retryAtMs: null };
1098
+ }
1099
+ const supplied = [...addrs];
1100
+ const circuitAddrs = node ? circuitMultiaddrs(node) : [];
1101
+ if (circuitAddrs.length > 0) {
1102
+ return { status: 'reserved', addrs: supplied, circuitAddrs, error: null, retryAtMs };
1103
+ }
1104
+ if (driving) {
1105
+ return {
1106
+ status: 'dialing',
1107
+ addrs: supplied,
1108
+ circuitAddrs: [],
1109
+ error: lastError,
1110
+ retryAtMs: null
1111
+ };
1112
+ }
1113
+ // `driveRelayReservation` always reports a reason when it finishes without a
1114
+ // reservation, so `lastError` is normally set below. The fallback only covers
1115
+ // addrs recorded without a completed drive.
1116
+ const error = lastError ?? 'no circuit reservation held';
1117
+ if (retryAtMs !== null) {
1118
+ return { status: 'retrying', addrs: supplied, circuitAddrs: [], error, retryAtMs };
1119
+ }
1120
+ return { status: 'error', addrs: supplied, circuitAddrs: [], error, retryAtMs: null };
1121
+ }