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