@serfab/cadre-core 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/README.md +255 -255
  2. package/dist/cadre-node.d.ts +203 -28
  3. package/dist/cadre-node.js +445 -84
  4. package/dist/cadre-node.js.map +1 -1
  5. package/dist/control-cohort.d.ts +26 -0
  6. package/dist/control-cohort.js +26 -0
  7. package/dist/control-cohort.js.map +1 -1
  8. package/dist/control-database.d.ts +82 -117
  9. package/dist/control-database.js +217 -295
  10. package/dist/control-database.js.map +1 -1
  11. package/dist/control-formation-recorder.d.ts +8 -7
  12. package/dist/control-formation-recorder.js +8 -7
  13. package/dist/control-formation-recorder.js.map +1 -1
  14. package/dist/control-schema.d.ts +1 -1
  15. package/dist/control-schema.js +789 -774
  16. package/dist/control-schema.js.map +1 -1
  17. package/dist/control-write-retry.d.ts +15 -5
  18. package/dist/control-write-retry.js +19 -18
  19. package/dist/control-write-retry.js.map +1 -1
  20. package/dist/index.d.ts +1 -1
  21. package/dist/index.js +1 -1
  22. package/dist/index.js.map +1 -1
  23. package/dist/peer-addr-book.d.ts +92 -0
  24. package/dist/peer-addr-book.js +220 -0
  25. package/dist/peer-addr-book.js.map +1 -0
  26. package/dist/seed-bootstrap.d.ts +7 -0
  27. package/dist/seed-bootstrap.js +15 -13
  28. package/dist/seed-bootstrap.js.map +1 -1
  29. package/dist/strand-cohort.d.ts +4 -37
  30. package/dist/strand-cohort.js +4 -15
  31. package/dist/strand-cohort.js.map +1 -1
  32. package/dist/strand-database.d.ts +11 -16
  33. package/dist/strand-database.js +19 -7
  34. package/dist/strand-database.js.map +1 -1
  35. package/dist/strand-formation-manager.d.ts +8 -8
  36. package/dist/strand-formation-manager.js +15 -18
  37. package/dist/strand-formation-manager.js.map +1 -1
  38. package/dist/strand-instance-manager.d.ts +52 -21
  39. package/dist/strand-instance-manager.js +100 -34
  40. package/dist/strand-instance-manager.js.map +1 -1
  41. package/dist/strand-membership-writer.d.ts +6 -4
  42. package/dist/strand-membership-writer.js +38 -36
  43. package/dist/strand-membership-writer.js.map +1 -1
  44. package/dist/types.d.ts +39 -31
  45. package/dist/types.js.map +1 -1
  46. package/package.json +8 -7
  47. package/src/arachnode-stub.ts +159 -159
  48. package/src/bootstrap-peer-store-file.ts +44 -44
  49. package/src/bootstrap-peer-store.ts +172 -172
  50. package/src/cadre-node.ts +5158 -4771
  51. package/src/canonical-json.ts +30 -30
  52. package/src/control-authorization.ts +114 -114
  53. package/src/control-cohort.ts +130 -103
  54. package/src/control-database.ts +2406 -2506
  55. package/src/control-formation-recorder.ts +305 -304
  56. package/src/control-schema.ts +801 -786
  57. package/src/control-stream.ts +205 -205
  58. package/src/control-write-retry.ts +483 -473
  59. package/src/delegate-admission.ts +302 -302
  60. package/src/device-token.ts +94 -94
  61. package/src/diagnostics/connection-path.ts +277 -277
  62. package/src/diagnostics/webrtc-turn-tracker.ts +222 -222
  63. package/src/ed25519-key.ts +134 -134
  64. package/src/enrollment.ts +199 -199
  65. package/src/file-durable-slot.ts +61 -61
  66. package/src/formation-approval.ts +604 -604
  67. package/src/fs-atomic.ts +107 -107
  68. package/src/hibernation-manager.ts +437 -437
  69. package/src/identity-key.ts +109 -109
  70. package/src/index.ts +1 -0
  71. package/src/key-store-file.ts +132 -132
  72. package/src/key-store.ts +99 -99
  73. package/src/membership-connection-gater.ts +204 -204
  74. package/src/node-local-snapshot.ts +260 -260
  75. package/src/peer-addr-book.ts +250 -0
  76. package/src/peer-authorization.ts +259 -259
  77. package/src/peer-record.ts +164 -164
  78. package/src/push-credentials.ts +84 -84
  79. package/src/push-node.ts +64 -64
  80. package/src/push-notifier-apns.ts +247 -247
  81. package/src/push-notifier-fcm.ts +220 -220
  82. package/src/push-notifier-shared.ts +28 -28
  83. package/src/push-notifier.ts +52 -52
  84. package/src/relay-addrs.ts +111 -111
  85. package/src/relay-reservation.ts +823 -823
  86. package/src/seed-bootstrap.ts +15 -15
  87. package/src/seed-trust-policy.ts +140 -140
  88. package/src/strand-addr-protocol.ts +441 -441
  89. package/src/strand-backfill.ts +366 -366
  90. package/src/strand-cohort.ts +38 -77
  91. package/src/strand-database.ts +202 -204
  92. package/src/strand-formation-manager.ts +491 -494
  93. package/src/strand-formation-protocol.ts +692 -692
  94. package/src/strand-instance-manager.ts +108 -50
  95. package/src/strand-member-key.ts +39 -39
  96. package/src/strand-member-registry.ts +182 -182
  97. package/src/strand-membership-writer.ts +1432 -1430
  98. package/src/strand-solicitation.ts +472 -472
  99. package/src/strand-transport-key.ts +58 -58
  100. package/src/strand-wake-payload.ts +32 -32
  101. package/src/strand-wake-protocol.ts +314 -314
  102. package/src/strand-watcher.ts +314 -314
  103. package/src/trusted-owner-store-file.ts +41 -41
  104. package/src/trusted-owner-store.ts +171 -171
  105. package/src/types.ts +1309 -1303
@@ -1,823 +1,823 @@
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, and the two shapes are alternatives, not layers:
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
- * The configured shape is what `relay-addrs.ts` builds out of `network.relayAddrs`.
15
- * It is **fail-fast by construction**: libp2p's transport manager throws
16
- * `UnsupportedListenAddressesError` when any configured listen address fails to
17
- * listen under the default `FATAL_ALL` fault tolerance, so naming a relay that is
18
- * down means the node does not start. Good for a server; wrong for a browser tab,
19
- * which must still boot (solo, undialable) when its relay is down.
20
- *
21
- * So a browser-shaped node listens on bare `/p2p-circuit` and needs someone to
22
- * (a) dial the relay and (b) fill the pending reservation that listener created,
23
- * then report whether one actually landed. That is this module. It is **fail-soft
24
- * by construction**: nothing here throws.
25
- *
26
- * Do NOT "consolidate" the two by also setting `network.relayAddrs` on a node
27
- * that reserves this way — that re-introduces the fatal configured listener
28
- * alongside the search listener and the tab stops booting when the relay is down.
29
- *
30
- * ⚠️ WHY THE RESERVATION IS REQUESTED EXPLICITLY RATHER THAN LEFT TO DISCOVERY.
31
- * libp2p fills a search listener's pending reservation from `RelayDiscovery`,
32
- * which nominates a peer only once it can see the relay-hop protocol id in that
33
- * peer's PEER-STORE protocol list — and that list is written exclusively by the
34
- * IDENTIFY handshake. `@optimystic/db-p2p` gives every cadre node a
35
- * network-namespaced identify protocol id (`/optimystic/control-<partyId>/id/1.0.0`)
36
- * while the relay `ops/docker/libp2p-infra` deploys runs stock identify
37
- * (`/ipfs/id/1.0.0`), so the two never identify each other, the peer store stays
38
- * empty of protocols, and discovery never nominates the relay. The TCP/WebSocket
39
- * connection itself is fine, which is why leaving it to discovery surfaced as a
40
- * generic timeout.
41
- *
42
- * Identify is incidental to relaying, though: the reservation
43
- * (`/libp2p/circuit/relay/0.2.0/hop`), a third peer's CONNECT through the relay,
44
- * and the STOP handler on this node all use STOCK, un-namespaced protocol ids the
45
- * deployed relay already serves. Discovery's only job is to GUESS which connected
46
- * peer is a relay, and this module does not need to guess — it was handed the
47
- * relay's address. So it asks the relay for a slot directly, via the
48
- * circuit-relay transport's own reservation store.
49
- *
50
- * Status is derived from the node's LIVE multiaddrs on every read rather than
51
- * cached at drive time: when a relay restarts or the connection drops, libp2p's
52
- * listener clears its listening addrs and the circuit multiaddr disappears, so a
53
- * cached snapshot would keep claiming `reserved` for a node nothing can dial.
54
- *
55
- * And because discovery is out of reach, nothing would ever ASK again either —
56
- * so {@link driveRelayReservation} stays a single-shot primitive and
57
- * {@link superviseRelayReservation} owns the retry cadence on top of it. That
58
- * loop is what makes a lost reservation recover without a page reload.
59
- */
60
-
61
- import debug from 'debug';
62
- import { multiaddr } from '@multiformats/multiaddr';
63
- import { peerIdFromString } from '@libp2p/peer-id';
64
- import type { Libp2p, PeerId } from '@libp2p/interface';
65
- import { trailingPeerId } from './peer-record.js';
66
-
67
- const log = debug('sereus:cadre:relay-reservation');
68
-
69
- /**
70
- * Relay-reservation posture for a node that reserves through the SEARCH listen
71
- * addr (bare `/p2p-circuit`) rather than a configured `network.relayAddrs` entry.
72
- * - `none` — no relay addrs supplied; the node is undialable by design.
73
- * - `dialing` — a drive is in flight.
74
- * - `reserved` — the node currently holds at least one `/p2p-circuit` addr.
75
- * - `retrying` — no reservation right now, but a {@link RelayReservationSupervisor}
76
- * has the next attempt scheduled. Recoverable without a caller.
77
- * - `error` — no reservation, and NOBODY IS GOING TO TRY AGAIN: no supervisor
78
- * is running (or there is no node at all).
79
- */
80
- export type RelayReservationStatus = 'none' | 'dialing' | 'reserved' | 'retrying' | 'error';
81
-
82
- export interface RelayReservationState {
83
- status: RelayReservationStatus;
84
- /** The relay multiaddrs this node was asked to reserve through. */
85
- addrs: string[];
86
- /** LIVE `/p2p-circuit` multiaddrs, recomputed on every read. */
87
- circuitAddrs: string[];
88
- error: string | null;
89
- /**
90
- * Epoch ms of the supervisor's next scheduled tick, or `null` when a drive is
91
- * in flight, no supervisor is running, or no addrs were supplied. A UI can turn
92
- * this into "reconnecting, next try in 8s" rather than showing a bare error for
93
- * a node that is in fact recovering.
94
- */
95
- retryAtMs: number | null;
96
- }
97
-
98
- /** How long {@link driveRelayReservation} waits for a reservation to appear. */
99
- export const DEFAULT_RELAY_RESERVE_TIMEOUT_MS = 10_000;
100
- export const DEFAULT_RELAY_RESERVE_POLL_MS = 250;
101
-
102
- export interface RelayReserveOptions {
103
- timeoutMs?: number;
104
- pollMs?: number;
105
- }
106
-
107
- /**
108
- * The slice of `@libp2p/utils`' `Filter` (a cuckoo filter) that the reservation
109
- * store uses to remember relays whose reservation request failed. `remove` is
110
- * OPTIONAL on that interface, so every use here has to cope with its absence —
111
- * see {@link clearRelayFilterEntry}.
112
- */
113
- export interface RelayFilterLike {
114
- has(item: Uint8Array): boolean;
115
- remove?(item: Uint8Array): boolean;
116
- }
117
-
118
- /**
119
- * The slice of `@libp2p/circuit-relay-v2`'s `ReservationStore` this module drives.
120
- * Declared structurally because the class is internal to that package: naming only
121
- * the members we call keeps the coupling small, explicit and greppable, and lets
122
- * {@link findCircuitRelayTransport} duck-type rather than brand-match.
123
- *
124
- * `relayFilter` is optional because it is not required to DRIVE a reservation,
125
- * only to RE-drive one (see {@link clearRelayFilterEntry}); a libp2p version that
126
- * renames or drops it must degrade, not break.
127
- */
128
- export interface RelayReservationStoreLike {
129
- addRelay(peerId: PeerId, type: 'discovered' | 'configured'): Promise<unknown>;
130
- hasReservation(peerId: PeerId): boolean;
131
- relayFilter?: RelayFilterLike;
132
- }
133
-
134
- /** The slice of libp2p's circuit-relay transport that owns the reservation store. */
135
- export interface CircuitRelayTransportLike {
136
- reservationStore: RelayReservationStoreLike;
137
- }
138
-
139
- /** `components` is a real field on libp2p's node class but not on the `Libp2p` interface. */
140
- interface Libp2pComponentsLike {
141
- components?: {
142
- transportManager?: {
143
- getTransports?: () => readonly unknown[];
144
- };
145
- };
146
- }
147
-
148
- /**
149
- * The node's `/p2p-circuit` multiaddrs — the addresses a peer can dial it at
150
- * while it holds a relay reservation. Empty means "not dialable via a relay
151
- * right now", which is exactly what makes {@link resolveRelayReservationState}
152
- * live rather than a stale snapshot.
153
- */
154
- export function circuitMultiaddrs(node: Libp2p): string[] {
155
- return node
156
- .getMultiaddrs()
157
- .map((ma) => ma.toString())
158
- .filter((addr) => addr.includes('/p2p-circuit'));
159
- }
160
-
161
- /**
162
- * The running node's circuit-relay transport, or `null` when it has none.
163
- *
164
- * There is no public libp2p API for "reserve on THIS specific relay", so this
165
- * reaches through `node.components.transportManager` — libp2p's internal layout.
166
- * That coupling is deliberate and bounded: every step is optional-chained and the
167
- * whole thing returns `null` rather than throwing, and a spec pins the seam so a
168
- * libp2p upgrade that moves it fails loudly instead of silently reverting this
169
- * module to the discovery wait that never fires.
170
- */
171
- export function findCircuitRelayTransport(node: Libp2p): CircuitRelayTransportLike | null {
172
- for (const transport of nodeTransports(node)) {
173
- const store = (transport as { reservationStore?: unknown }).reservationStore;
174
- if (isReservationStore(store)) {
175
- return { reservationStore: store };
176
- }
177
- }
178
- return null;
179
- }
180
-
181
- function nodeTransports(node: Libp2p): readonly unknown[] {
182
- const manager = (node as Libp2p & Libp2pComponentsLike).components?.transportManager;
183
- if (typeof manager?.getTransports !== 'function') {
184
- log('No transportManager.getTransports() on this node — libp2p internals moved?');
185
- return [];
186
- }
187
- try {
188
- return manager.getTransports();
189
- } catch (err) {
190
- log('transportManager.getTransports() threw: %o', err);
191
- return [];
192
- }
193
- }
194
-
195
- function isReservationStore(value: unknown): value is RelayReservationStoreLike {
196
- if (typeof value !== 'object' || value === null) {
197
- return false;
198
- }
199
- const store = value as Partial<RelayReservationStoreLike>;
200
- return typeof store.addRelay === 'function' && typeof store.hasReservation === 'function';
201
- }
202
-
203
- /** Sentinel resolved by the deadline race in {@link requestOneReservation}. */
204
- const DEADLINE_PASSED = Symbol('relay-reservation-deadline-passed');
205
-
206
- /** A relay that answered its dial, paired with the address it was dialed at. */
207
- interface ConnectedRelay {
208
- addr: string;
209
- peerId: PeerId;
210
- }
211
-
212
- /**
213
- * Dial every relay in `addrs`, ask the first one that answers for a reservation
214
- * slot, then wait until a `/p2p-circuit` address appears.
215
- *
216
- * Never throws — a dial rejection, a rejected reservation, a MALFORMED address,
217
- * or a timeout all come back as an `error` string. A dial that throws does NOT
218
- * cost the rest of the list: one dead relay among two must not cost the
219
- * reservation on the live one, so every addr is dialed and the first error (in
220
- * list order) is kept. A reservation that lands wins over any earlier error
221
- * (`error: null`).
222
- *
223
- * `timeoutMs` bounds the WHOLE drive — dials, reservation requests and the wait
224
- * share one deadline.
225
- */
226
- export async function driveRelayReservation(
227
- node: Libp2p,
228
- addrs: readonly string[],
229
- opts?: RelayReserveOptions
230
- ): Promise<{ error: string | null }> {
231
- if (addrs.length === 0) {
232
- return { error: null };
233
- }
234
- const timeoutMs = opts?.timeoutMs ?? DEFAULT_RELAY_RESERVE_TIMEOUT_MS;
235
- // Clamped: a caller-supplied 0 would spin the poll loop hot until the deadline.
236
- const pollMs = Math.max(1, opts?.pollMs ?? DEFAULT_RELAY_RESERVE_POLL_MS);
237
- const deadline = Date.now() + timeoutMs;
238
-
239
- const { connected, error: dialError } = await dialRelays(node, addrs, deadline);
240
- const attempt = await requestReservation(node, connected, deadline);
241
- // NOTE: a REJECTED reservation still spends the rest of the deadline polling,
242
- // because discovery may independently land one (only the no-transport case is
243
- // `fatal`). So a misconfigured node reports its now-legible reason a full
244
- // `timeoutMs` late. If startup latency on that path ever matters, shorten the
245
- // wait once every connected relay has rejected — do not skip it outright.
246
- if (!attempt.fatal && (await waitForCircuitReservation(node, deadline, pollMs))) {
247
- return { error: null };
248
- }
249
- return {
250
- error: attempt.error ?? dialError ?? `no circuit reservation within ${timeoutMs}ms`
251
- };
252
- }
253
-
254
- /**
255
- * Dial every relay CONCURRENTLY under the drive's shared deadline. Reports the
256
- * relays that answered (in list order, for the reservation step) and the first
257
- * failure in LIST order (`null` when every dial connected).
258
- *
259
- * Concurrent and deadline-bound because this whole drive is awaited on a browser
260
- * tab's startup path: dialing serially with libp2p's own (much longer) per-dial
261
- * timeout meant N unreachable relays cost N dial timeouts before the reservation
262
- * request even began, so `timeoutMs` bounded only the tail of the operation.
263
- *
264
- * Aborting a dial at the deadline is not a lost reservation — the steps that
265
- * follow have no time left either, so the drive would report `error` regardless.
266
- */
267
- async function dialRelays(
268
- node: Libp2p,
269
- addrs: readonly string[],
270
- deadline: number
271
- ): Promise<{ connected: ConnectedRelay[]; error: string | null }> {
272
- // An explicit controller, not `AbortSignal.timeout` — the latter is not
273
- // reliably present on React Native/Hermes, which runs this same module.
274
- const controller = new AbortController();
275
- const timer = setTimeout(() => controller.abort(), Math.max(0, deadline - Date.now()));
276
- try {
277
- const results = await Promise.allSettled(
278
- addrs.map((addr) => dialOne(node, addr, controller.signal))
279
- );
280
- return { connected: connectedRelays(addrs, results), error: firstDialError(addrs, results) };
281
- } finally {
282
- clearTimeout(timer);
283
- }
284
- }
285
-
286
- /**
287
- * One dial, with the address PARSED INSIDE the promise.
288
- *
289
- * `multiaddr()` throws SYNCHRONOUSLY on a malformed string, and a throw out of
290
- * the `map` callback escapes `Promise.allSettled` altogether — it would reject
291
- * the whole drive (breaking the never-throws contract) and discard the dials to
292
- * the other, perfectly good, addrs. `async` demotes it to a settled rejection,
293
- * which is already exactly how a dial failure is reported.
294
- */
295
- async function dialOne(
296
- node: Libp2p,
297
- addr: string,
298
- signal: AbortSignal
299
- ): Promise<{ remotePeer: PeerId }> {
300
- return node.dial(multiaddr(addr), { signal });
301
- }
302
-
303
- function connectedRelays(
304
- addrs: readonly string[],
305
- results: readonly PromiseSettledResult<{ remotePeer: PeerId }>[]
306
- ): ConnectedRelay[] {
307
- const connected: ConnectedRelay[] = [];
308
- results.forEach((result, index) => {
309
- if (result.status !== 'fulfilled') return;
310
- connected.push({ addr: addrs[index], peerId: result.value.remotePeer });
311
- });
312
- return connected;
313
- }
314
-
315
- /** Log every dial rejection; return the first one in list order. */
316
- function firstDialError(
317
- addrs: readonly string[],
318
- results: readonly PromiseSettledResult<unknown>[]
319
- ): string | null {
320
- let first: string | null = null;
321
- results.forEach((result, index) => {
322
- if (result.status !== 'rejected') return;
323
- const message = result.reason instanceof Error ? result.reason.message : String(result.reason);
324
- log('Relay dial failed (%s): %s', addrs[index], message);
325
- first ??= message;
326
- });
327
- return first;
328
- }
329
-
330
- /**
331
- * Outcome of the explicit reservation request.
332
- *
333
- * `fatal` means no `/p2p-circuit` address can EVER appear (the node has no
334
- * circuit-relay transport at all), so the caller must report immediately rather
335
- * than spend the rest of the deadline polling for something that cannot happen.
336
- * A rejected request is NOT fatal: discovery may still land a reservation for a
337
- * relay that does happen to share this node's identify prefix.
338
- */
339
- interface ReservationAttempt {
340
- error: string | null;
341
- fatal: boolean;
342
- }
343
-
344
- /**
345
- * Ask the connected relays, in list order, for a reservation slot; stop at the
346
- * first success.
347
- *
348
- * `'discovered'`, not `'configured'`: the search listener's
349
- * `relay:created-reservation` handler ignores `configured` reservations outright,
350
- * so the `/p2p-circuit` listen address would never be published and
351
- * `getMultiaddrs()` would stay empty even though the reservation succeeded.
352
- * `'discovered'` consumes the pending-reservation id the bare `/p2p-circuit`
353
- * listener registered, which is exactly what that handler matches on.
354
- *
355
- * Sequential, not concurrent: a bare `/p2p-circuit` listener registers exactly
356
- * ONE pending reservation, so a second concurrent `addRelay` would be rejected
357
- * with `HadEnoughRelaysError` — noise, not a failure. Running discovery is not a
358
- * conflict either; `addRelay` dedupes through its own peer queue, so a relay that
359
- * genuinely is discoverable still reserves exactly once.
360
- */
361
- async function requestReservation(
362
- node: Libp2p,
363
- connected: readonly ConnectedRelay[],
364
- deadline: number
365
- ): Promise<ReservationAttempt> {
366
- if (connected.length === 0) {
367
- // Nothing answered — the dial error is the whole story.
368
- return { error: null, fatal: false };
369
- }
370
- const transport = findCircuitRelayTransport(node);
371
- if (transport === null) {
372
- return {
373
- error: 'node has no circuit-relay transport — add circuitRelayTransport() to its transports',
374
- fatal: true
375
- };
376
- }
377
- let firstError: string | null = null;
378
- for (const relay of connected) {
379
- if (transport.reservationStore.hasReservation(relay.peerId)) {
380
- return { error: null, fatal: false };
381
- }
382
- if (Date.now() >= deadline) {
383
- break;
384
- }
385
- const failure = await requestOneReservation(transport.reservationStore, relay, deadline);
386
- if (failure === null) {
387
- return { error: null, fatal: false };
388
- }
389
- firstError ??= failure;
390
- }
391
- return { error: firstError, fatal: false };
392
- }
393
-
394
- /**
395
- * One `addRelay` call, bounded by the drive's deadline. Returns `null` on
396
- * success, or the reason it failed.
397
- *
398
- * Deadline-raced because `addRelay` runs on libp2p's own (much longer) reservation
399
- * timeout and takes no signal: without the race a drive given 1.5 s would sit on a
400
- * silent relay for libp2p's timeout instead. The abandoned promise stays handled —
401
- * `Promise.race` attaches its own handlers — so a later rejection is not unhandled.
402
- */
403
- async function requestOneReservation(
404
- store: RelayReservationStoreLike,
405
- relay: ConnectedRelay,
406
- deadline: number
407
- ): Promise<string | null> {
408
- let timer: ReturnType<typeof setTimeout> | undefined;
409
- const expired = new Promise<typeof DEADLINE_PASSED>((resolve) => {
410
- timer = setTimeout(() => resolve(DEADLINE_PASSED), Math.max(0, deadline - Date.now()));
411
- });
412
- try {
413
- const outcome = await Promise.race([store.addRelay(relay.peerId, 'discovered'), expired]);
414
- if (outcome === DEADLINE_PASSED) {
415
- log('Relay reservation request (%s) still pending at the deadline', relay.addr);
416
- return `relay reservation request to ${relay.addr} did not complete before the deadline`;
417
- }
418
- return null;
419
- } catch (err) {
420
- const message = describeReservationFailure(err, relay.addr);
421
- log('Relay reservation failed (%s): %s', relay.addr, message);
422
- return message;
423
- } finally {
424
- clearTimeout(timer);
425
- }
426
- }
427
-
428
- /**
429
- * Turn libp2p's reservation rejection into a reason that names the actual cause.
430
- *
431
- * `HadEnoughRelaysError` needs translating rather than passing through: its own
432
- * message ("we do not need any more relays") says the opposite of what happened.
433
- * A `'discovered'` reservation is refused when the node holds NO pending
434
- * reservation id, and a node holds one only while it listens on the bare
435
- * `/p2p-circuit` search address — so the real cause is a missing listen address.
436
- */
437
- function describeReservationFailure(err: unknown, addr: string): string {
438
- // NOTE: libp2p adds a peer to the reservation store's `relayFilter` when a
439
- // request fails with `DialError` or `UnsupportedProtocolError`, and the failure
440
- // path does not reset that filter (it only resets when a reservation is actually
441
- // removed). So a SECOND drive against the same relay in the same process reports
442
- // `ListenError: The relay was previously invalid` even if the relay has since
443
- // recovered. `RelayReservationLoop` clears the entry before every attempt (see
444
- // {@link clearRelayFilterEntry}); a caller that re-drives WITHOUT the supervisor
445
- // still has to deal with the filter itself.
446
- const name = err instanceof Error ? err.name : '';
447
- const message = err instanceof Error ? err.message : String(err);
448
- switch (name) {
449
- case 'HadEnoughRelaysError':
450
- 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`;
451
- case 'UnsupportedProtocolError':
452
- return `peer at ${addr} does not speak the circuit-relay hop protocol — it is not a relay`;
453
- default:
454
- return `relay reservation on ${addr} failed: ${message}`;
455
- }
456
- }
457
-
458
- /**
459
- * Poll until the node advertises a `/p2p-circuit` address, or the deadline passes.
460
- *
461
- * Still a poll even though the reservation is now requested explicitly: `addRelay`
462
- * resolving means the RELAY accepted, while the listen address is published a tick
463
- * later by the listener's `relay:created-reservation` handler, and a reservation
464
- * that discovery lands independently has no return value to await at all.
465
- *
466
- * NOTE: polls rather than subscribing to libp2p's `self:peer:update` — it keeps
467
- * this free of libp2p event-name coupling. If 250 ms of reservation latency ever
468
- * matters, switch to the event and keep the poll as a fallback.
469
- */
470
- async function waitForCircuitReservation(
471
- node: Libp2p,
472
- deadline: number,
473
- pollMs: number
474
- ): Promise<boolean> {
475
- for (;;) {
476
- if (circuitMultiaddrs(node).length > 0) {
477
- return true;
478
- }
479
- if (Date.now() >= deadline) {
480
- return false;
481
- }
482
- await delay(Math.min(pollMs, Math.max(0, deadline - Date.now())));
483
- }
484
- }
485
-
486
- function delay(ms: number): Promise<void> {
487
- return new Promise((resolve) => setTimeout(resolve, ms));
488
- }
489
-
490
- /** Gap between liveness checks while a reservation is held. */
491
- export const DEFAULT_RELAY_CHECK_MS = 5_000;
492
- /** Backoff before the first re-drive after a failed attempt. */
493
- export const DEFAULT_RELAY_MIN_BACKOFF_MS = 2_000;
494
- /** Ceiling the backoff doubles up to. */
495
- export const DEFAULT_RELAY_MAX_BACKOFF_MS = 60_000;
496
-
497
- export interface RelayReservationSupervisorOptions extends RelayReserveOptions {
498
- /** Gap between liveness checks while a reservation is held. Default 5_000. */
499
- checkMs?: number;
500
- /** Backoff before the first re-drive after a failure. Default 2_000. */
501
- minBackoffMs?: number;
502
- /** Backoff ceiling. Default 60_000. */
503
- maxBackoffMs?: number;
504
- }
505
-
506
- /**
507
- * A running retry loop for one node + relay list. Obtained from
508
- * {@link superviseRelayReservation}; its only imperative is {@link stop}.
509
- */
510
- export interface RelayReservationSupervisor {
511
- /**
512
- * Resolves once the FIRST attempt has settled — so a caller can await startup
513
- * exactly as it awaited a single {@link driveRelayReservation}, and the retries
514
- * carry on in the background afterwards. Also resolves on {@link stop}, so an
515
- * awaiting caller is never left hanging.
516
- */
517
- readonly firstAttempt: Promise<void>;
518
- /** True while a drive is in flight. */
519
- readonly driving: boolean;
520
- /** Epoch ms of the next scheduled tick; `null` while a drive is running. */
521
- readonly retryAtMs: number | null;
522
- /** Reason the last drive produced no reservation; `null` once one is held. */
523
- readonly lastError: string | null;
524
- /**
525
- * Idempotent. Clears the timer so no further drive is scheduled. A drive that
526
- * is ALREADY in flight is not aborted — {@link driveRelayReservation} takes no
527
- * signal — but its result is discarded and nothing follows it.
528
- */
529
- stop(): void;
530
- }
531
-
532
- /**
533
- * Keep asking for a relay reservation until one is held, then keep watching that
534
- * it still is — the thing that makes a lost reservation recover on its own.
535
- *
536
- * Needed because nothing else re-drives: libp2p re-fills a search listener's
537
- * freed slot from relay DISCOVERY, and a cadre node's namespaced identify puts
538
- * discovery permanently out of reach (see the module header). Without this loop a
539
- * relay restart left a browser tab undialable until the user reloaded the page.
540
- *
541
- * Per tick:
542
- * - a reservation is held → reset the backoff, clear the error, re-check in
543
- * `checkMs`. No drive: a healthy node must not re-request every few seconds.
544
- * - otherwise → un-poison the reservation store's relay filter (see
545
- * {@link clearRelayFilterEntry}) and run ONE {@link driveRelayReservation}.
546
- * If that lands a reservation, rejoin the healthy path above; if not, sleep
547
- * the current backoff and double it up to `maxBackoffMs`.
548
- *
549
- * Starts immediately; the first tick runs before this returns.
550
- */
551
- export function superviseRelayReservation(
552
- node: Libp2p,
553
- addrs: readonly string[],
554
- opts?: RelayReservationSupervisorOptions
555
- ): RelayReservationSupervisor {
556
- return new RelayReservationLoop(node, [...addrs], opts ?? {});
557
- }
558
-
559
- /**
560
- * Forget that `addr`'s peer ever failed a reservation request, so the next
561
- * attempt is actually made rather than refused out of hand.
562
- *
563
- * `ReservationStore` records a peer in `relayFilter` when its reservation request
564
- * fails with `DialError` or `UnsupportedProtocolError`, and NOTHING on that path
565
- * ever clears it: the reset lives in `#checkReservationCount`, which only runs
566
- * when a reservation is genuinely removed, and `#removeReservation` early-returns
567
- * when there was never one. So a relay that was briefly not-a-relay (or died
568
- * between our dial and the hop request) stays permanently rejected with
569
- * `The relay was previously invalid` — measured, not inferred.
570
- *
571
- * Fails soft in every direction: no `relayFilter`, no `remove`, an addr with no
572
- * peer id, a malformed addr — all mean "no un-poisoning", never a throw. The
573
- * retry loop still recovers the common case without this, because a relay that is
574
- * simply DOWN fails our own dial first and never reaches the filter.
575
- *
576
- * Returns whether an entry was actually removed (for specs; callers ignore it).
577
- */
578
- export function clearRelayFilterEntry(store: RelayReservationStoreLike, addr: string): boolean {
579
- const filter = store.relayFilter;
580
- if (typeof filter?.remove !== 'function') {
581
- log('Reservation store has no removable relayFilter — cannot un-poison %s', addr);
582
- return false;
583
- }
584
- try {
585
- // The peer id is in the multiaddr, so this costs no dial and can run before one.
586
- const peerId = trailingPeerId(multiaddr(addr));
587
- if (peerId === null) {
588
- // NOTE: an addr with no `/p2p/` component can still be dialed and reserved
589
- // through (the peer id comes off the connection), but it can never be
590
- // un-poisoned — so for THAT addr a poisoned filter is permanent again. No
591
- // caller supplies such an addr today; if one ever does, resolve the peer id
592
- // from the live connection instead of the multiaddr.
593
- return false;
594
- }
595
- return filter.remove(peerIdFromString(peerId).toMultihash().bytes);
596
- } catch (err) {
597
- log('Could not clear the relayFilter entry for %s: %o', addr, err);
598
- return false;
599
- }
600
- }
601
-
602
- /** The self-rescheduling loop behind {@link superviseRelayReservation}. */
603
- class RelayReservationLoop implements RelayReservationSupervisor {
604
- readonly firstAttempt: Promise<void>;
605
-
606
- private readonly checkMs: number;
607
- private readonly minBackoffMs: number;
608
- private readonly maxBackoffMs: number;
609
- private backoffMs: number;
610
- private timer: ReturnType<typeof setTimeout> | null = null;
611
- private stopped = false;
612
- private inFlight = false;
613
- private nextTickAtMs: number | null = null;
614
- private failure: string | null = null;
615
- private settleFirstAttempt: () => void = () => {};
616
- private firstAttemptSettled = false;
617
-
618
- constructor(
619
- private readonly node: Libp2p,
620
- private readonly addrs: readonly string[],
621
- private readonly opts: RelayReservationSupervisorOptions
622
- ) {
623
- // Clamped away from 0: a caller-supplied 0 would spin the loop hot.
624
- this.checkMs = Math.max(1, opts.checkMs ?? DEFAULT_RELAY_CHECK_MS);
625
- this.minBackoffMs = Math.max(1, opts.minBackoffMs ?? DEFAULT_RELAY_MIN_BACKOFF_MS);
626
- this.maxBackoffMs = Math.max(
627
- this.minBackoffMs,
628
- opts.maxBackoffMs ?? DEFAULT_RELAY_MAX_BACKOFF_MS
629
- );
630
- this.backoffMs = this.minBackoffMs;
631
- this.firstAttempt = new Promise((resolve) => {
632
- this.settleFirstAttempt = resolve;
633
- });
634
- void this.tick();
635
- }
636
-
637
- get driving(): boolean {
638
- return this.inFlight;
639
- }
640
-
641
- get retryAtMs(): number | null {
642
- return this.nextTickAtMs;
643
- }
644
-
645
- get lastError(): string | null {
646
- return this.failure;
647
- }
648
-
649
- stop(): void {
650
- if (this.stopped) {
651
- return;
652
- }
653
- this.stopped = true;
654
- if (this.timer !== null) {
655
- clearTimeout(this.timer);
656
- this.timer = null;
657
- }
658
- this.nextTickAtMs = null;
659
- this.settleFirst();
660
- }
661
-
662
- private async tick(): Promise<void> {
663
- if (this.stopped) {
664
- return;
665
- }
666
- this.nextTickAtMs = null;
667
- if (this.reservationHeld()) {
668
- this.onReservationHeld();
669
- return;
670
- }
671
- await this.driveOnce();
672
- if (this.stopped) {
673
- return;
674
- }
675
- this.settleFirst();
676
- // A drive that LANDED a reservation resumes the healthy cadence immediately.
677
- // Backing off here instead would leave the first liveness check after a long
678
- // outage a fully grown backoff away (up to `maxBackoffMs`), so a reservation
679
- // lost again right after recovery would go unnoticed for that whole window.
680
- if (this.reservationHeld()) {
681
- this.onReservationHeld();
682
- return;
683
- }
684
- this.scheduleBackoff();
685
- }
686
-
687
- private reservationHeld(): boolean {
688
- return circuitMultiaddrs(this.node).length > 0;
689
- }
690
-
691
- /** Healthy tick: nothing to request, so only reset and re-check later. */
692
- private onReservationHeld(): void {
693
- this.backoffMs = this.minBackoffMs;
694
- this.failure = null;
695
- this.settleFirst();
696
- this.schedule(this.checkMs);
697
- }
698
-
699
- private async driveOnce(): Promise<void> {
700
- this.inFlight = true;
701
- try {
702
- this.unpoisonRelayFilter();
703
- const { error } = await driveRelayReservation(this.node, this.addrs, this.opts);
704
- if (!this.stopped) {
705
- this.failure = error;
706
- }
707
- } catch (err) {
708
- // `driveRelayReservation` is fail-soft by contract, so reaching here means
709
- // that contract broke. The loop must survive it anyway: an escaping
710
- // rejection would leave `firstAttempt` pending FOREVER (hanging every
711
- // caller that awaits a reservation at startup) and schedule no further
712
- // attempt, which is the failure this whole supervisor exists to prevent.
713
- const message = err instanceof Error ? err.message : String(err);
714
- log('Relay reservation drive threw, which it should not: %s', message);
715
- if (!this.stopped) {
716
- this.failure = message;
717
- }
718
- } finally {
719
- this.inFlight = false;
720
- }
721
- }
722
-
723
- private scheduleBackoff(): void {
724
- const wait = this.backoffMs;
725
- this.backoffMs = Math.min(this.backoffMs * 2, this.maxBackoffMs);
726
- this.schedule(wait);
727
- }
728
-
729
- private unpoisonRelayFilter(): void {
730
- const transport = findCircuitRelayTransport(this.node);
731
- if (transport === null) {
732
- return;
733
- }
734
- for (const addr of this.addrs) {
735
- clearRelayFilterEntry(transport.reservationStore, addr);
736
- }
737
- }
738
-
739
- private schedule(ms: number): void {
740
- if (this.stopped) {
741
- return;
742
- }
743
- this.nextTickAtMs = Date.now() + ms;
744
- this.timer = setTimeout(() => {
745
- this.timer = null;
746
- void this.tick();
747
- }, ms);
748
- // Node keeps the process alive while a timer is pending, so an un-unref'd
749
- // supervisor would hang every CLI run and vitest worker that ever reserved.
750
- // Cast + optional-chain: browsers and React Native have no `unref`.
751
- (this.timer as { unref?: () => void }).unref?.();
752
- }
753
-
754
- private settleFirst(): void {
755
- if (this.firstAttemptSettled) {
756
- return;
757
- }
758
- this.firstAttemptSettled = true;
759
- this.settleFirstAttempt();
760
- }
761
- }
762
-
763
- /**
764
- * Derive the reservation posture, reading the node's circuit addrs LIVE. Pure
765
- * apart from that read, so the precedence is testable on its own:
766
- *
767
- * | condition | status |
768
- * | ------------------------ | ----------------------------------------------- |
769
- * | no addrs supplied | `none` |
770
- * | live circuit addrs held | `reserved` (`error: null`) |
771
- * | a drive is in flight | `dialing` |
772
- * | a retry is scheduled | `retrying` |
773
- * | otherwise | `error` |
774
- *
775
- * `reserved` is checked BEFORE `error` on purpose: the circuit addrs are read
776
- * live, so a reservation that lands by ANY route supersedes a stale error string
777
- * without a second drive.
778
- *
779
- * `retrying` sits between the two so that `error` carries a sharper meaning:
780
- * NOBODY IS GOING TO TRY AGAIN. A lost reservation does come back on its own now,
781
- * as long as a {@link RelayReservationSupervisor} is running — that loop is the
782
- * only thing that re-drives, since libp2p re-fills a search listener's freed slot
783
- * from relay DISCOVERY, which a cadre node's namespaced identify puts permanently
784
- * out of reach (see the module header). So `error` means the supervisor was
785
- * stopped, was never started, or there is no node at all.
786
- *
787
- * `retryAtMs` is the supervisor's next scheduled tick (`null` while a drive runs
788
- * or when there is no supervisor); it both selects `retrying` and is passed
789
- * through so a UI can count down to the next attempt.
790
- */
791
- export function resolveRelayReservationState(
792
- node: Libp2p | null,
793
- addrs: readonly string[],
794
- lastError: string | null,
795
- driving: boolean,
796
- retryAtMs: number | null
797
- ): RelayReservationState {
798
- if (addrs.length === 0) {
799
- return { status: 'none', addrs: [], circuitAddrs: [], error: null, retryAtMs: null };
800
- }
801
- const supplied = [...addrs];
802
- const circuitAddrs = node ? circuitMultiaddrs(node) : [];
803
- if (circuitAddrs.length > 0) {
804
- return { status: 'reserved', addrs: supplied, circuitAddrs, error: null, retryAtMs };
805
- }
806
- if (driving) {
807
- return {
808
- status: 'dialing',
809
- addrs: supplied,
810
- circuitAddrs: [],
811
- error: lastError,
812
- retryAtMs: null
813
- };
814
- }
815
- // `driveRelayReservation` always reports a reason when it finishes without a
816
- // reservation, so `lastError` is normally set below. The fallback only covers
817
- // addrs recorded without a completed drive.
818
- const error = lastError ?? 'no circuit reservation held';
819
- if (retryAtMs !== null) {
820
- return { status: 'retrying', addrs: supplied, circuitAddrs: [], error, retryAtMs };
821
- }
822
- return { status: 'error', addrs: supplied, circuitAddrs: [], error, retryAtMs: null };
823
- }
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, and the two shapes are alternatives, not layers:
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
+ * The configured shape is what `relay-addrs.ts` builds out of `network.relayAddrs`.
15
+ * It is **fail-fast by construction**: libp2p's transport manager throws
16
+ * `UnsupportedListenAddressesError` when any configured listen address fails to
17
+ * listen under the default `FATAL_ALL` fault tolerance, so naming a relay that is
18
+ * down means the node does not start. Good for a server; wrong for a browser tab,
19
+ * which must still boot (solo, undialable) when its relay is down.
20
+ *
21
+ * So a browser-shaped node listens on bare `/p2p-circuit` and needs someone to
22
+ * (a) dial the relay and (b) fill the pending reservation that listener created,
23
+ * then report whether one actually landed. That is this module. It is **fail-soft
24
+ * by construction**: nothing here throws.
25
+ *
26
+ * Do NOT "consolidate" the two by also setting `network.relayAddrs` on a node
27
+ * that reserves this way — that re-introduces the fatal configured listener
28
+ * alongside the search listener and the tab stops booting when the relay is down.
29
+ *
30
+ * ⚠️ WHY THE RESERVATION IS REQUESTED EXPLICITLY RATHER THAN LEFT TO DISCOVERY.
31
+ * libp2p fills a search listener's pending reservation from `RelayDiscovery`,
32
+ * which nominates a peer only once it can see the relay-hop protocol id in that
33
+ * peer's PEER-STORE protocol list — and that list is written exclusively by the
34
+ * IDENTIFY handshake. `@optimystic/db-p2p` gives every cadre node a
35
+ * network-namespaced identify protocol id (`/optimystic/control-<partyId>/id/1.0.0`)
36
+ * while the relay `ops/docker/libp2p-infra` deploys runs stock identify
37
+ * (`/ipfs/id/1.0.0`), so the two never identify each other, the peer store stays
38
+ * empty of protocols, and discovery never nominates the relay. The TCP/WebSocket
39
+ * connection itself is fine, which is why leaving it to discovery surfaced as a
40
+ * generic timeout.
41
+ *
42
+ * Identify is incidental to relaying, though: the reservation
43
+ * (`/libp2p/circuit/relay/0.2.0/hop`), a third peer's CONNECT through the relay,
44
+ * and the STOP handler on this node all use STOCK, un-namespaced protocol ids the
45
+ * deployed relay already serves. Discovery's only job is to GUESS which connected
46
+ * peer is a relay, and this module does not need to guess — it was handed the
47
+ * relay's address. So it asks the relay for a slot directly, via the
48
+ * circuit-relay transport's own reservation store.
49
+ *
50
+ * Status is derived from the node's LIVE multiaddrs on every read rather than
51
+ * cached at drive time: when a relay restarts or the connection drops, libp2p's
52
+ * listener clears its listening addrs and the circuit multiaddr disappears, so a
53
+ * cached snapshot would keep claiming `reserved` for a node nothing can dial.
54
+ *
55
+ * And because discovery is out of reach, nothing would ever ASK again either —
56
+ * so {@link driveRelayReservation} stays a single-shot primitive and
57
+ * {@link superviseRelayReservation} owns the retry cadence on top of it. That
58
+ * loop is what makes a lost reservation recover without a page reload.
59
+ */
60
+
61
+ import debug from 'debug';
62
+ import { multiaddr } from '@multiformats/multiaddr';
63
+ import { peerIdFromString } from '@libp2p/peer-id';
64
+ import type { Libp2p, PeerId } from '@libp2p/interface';
65
+ import { trailingPeerId } from './peer-record.js';
66
+
67
+ const log = debug('sereus:cadre:relay-reservation');
68
+
69
+ /**
70
+ * Relay-reservation posture for a node that reserves through the SEARCH listen
71
+ * addr (bare `/p2p-circuit`) rather than a configured `network.relayAddrs` entry.
72
+ * - `none` — no relay addrs supplied; the node is undialable by design.
73
+ * - `dialing` — a drive is in flight.
74
+ * - `reserved` — the node currently holds at least one `/p2p-circuit` addr.
75
+ * - `retrying` — no reservation right now, but a {@link RelayReservationSupervisor}
76
+ * has the next attempt scheduled. Recoverable without a caller.
77
+ * - `error` — no reservation, and NOBODY IS GOING TO TRY AGAIN: no supervisor
78
+ * is running (or there is no node at all).
79
+ */
80
+ export type RelayReservationStatus = 'none' | 'dialing' | 'reserved' | 'retrying' | 'error';
81
+
82
+ export interface RelayReservationState {
83
+ status: RelayReservationStatus;
84
+ /** The relay multiaddrs this node was asked to reserve through. */
85
+ addrs: string[];
86
+ /** LIVE `/p2p-circuit` multiaddrs, recomputed on every read. */
87
+ circuitAddrs: string[];
88
+ error: string | null;
89
+ /**
90
+ * Epoch ms of the supervisor's next scheduled tick, or `null` when a drive is
91
+ * in flight, no supervisor is running, or no addrs were supplied. A UI can turn
92
+ * this into "reconnecting, next try in 8s" rather than showing a bare error for
93
+ * a node that is in fact recovering.
94
+ */
95
+ retryAtMs: number | null;
96
+ }
97
+
98
+ /** How long {@link driveRelayReservation} waits for a reservation to appear. */
99
+ export const DEFAULT_RELAY_RESERVE_TIMEOUT_MS = 10_000;
100
+ export const DEFAULT_RELAY_RESERVE_POLL_MS = 250;
101
+
102
+ export interface RelayReserveOptions {
103
+ timeoutMs?: number;
104
+ pollMs?: number;
105
+ }
106
+
107
+ /**
108
+ * The slice of `@libp2p/utils`' `Filter` (a cuckoo filter) that the reservation
109
+ * store uses to remember relays whose reservation request failed. `remove` is
110
+ * OPTIONAL on that interface, so every use here has to cope with its absence —
111
+ * see {@link clearRelayFilterEntry}.
112
+ */
113
+ export interface RelayFilterLike {
114
+ has(item: Uint8Array): boolean;
115
+ remove?(item: Uint8Array): boolean;
116
+ }
117
+
118
+ /**
119
+ * The slice of `@libp2p/circuit-relay-v2`'s `ReservationStore` this module drives.
120
+ * Declared structurally because the class is internal to that package: naming only
121
+ * the members we call keeps the coupling small, explicit and greppable, and lets
122
+ * {@link findCircuitRelayTransport} duck-type rather than brand-match.
123
+ *
124
+ * `relayFilter` is optional because it is not required to DRIVE a reservation,
125
+ * only to RE-drive one (see {@link clearRelayFilterEntry}); a libp2p version that
126
+ * renames or drops it must degrade, not break.
127
+ */
128
+ export interface RelayReservationStoreLike {
129
+ addRelay(peerId: PeerId, type: 'discovered' | 'configured'): Promise<unknown>;
130
+ hasReservation(peerId: PeerId): boolean;
131
+ relayFilter?: RelayFilterLike;
132
+ }
133
+
134
+ /** The slice of libp2p's circuit-relay transport that owns the reservation store. */
135
+ export interface CircuitRelayTransportLike {
136
+ reservationStore: RelayReservationStoreLike;
137
+ }
138
+
139
+ /** `components` is a real field on libp2p's node class but not on the `Libp2p` interface. */
140
+ interface Libp2pComponentsLike {
141
+ components?: {
142
+ transportManager?: {
143
+ getTransports?: () => readonly unknown[];
144
+ };
145
+ };
146
+ }
147
+
148
+ /**
149
+ * The node's `/p2p-circuit` multiaddrs — the addresses a peer can dial it at
150
+ * while it holds a relay reservation. Empty means "not dialable via a relay
151
+ * right now", which is exactly what makes {@link resolveRelayReservationState}
152
+ * live rather than a stale snapshot.
153
+ */
154
+ export function circuitMultiaddrs(node: Libp2p): string[] {
155
+ return node
156
+ .getMultiaddrs()
157
+ .map((ma) => ma.toString())
158
+ .filter((addr) => addr.includes('/p2p-circuit'));
159
+ }
160
+
161
+ /**
162
+ * The running node's circuit-relay transport, or `null` when it has none.
163
+ *
164
+ * There is no public libp2p API for "reserve on THIS specific relay", so this
165
+ * reaches through `node.components.transportManager` — libp2p's internal layout.
166
+ * That coupling is deliberate and bounded: every step is optional-chained and the
167
+ * whole thing returns `null` rather than throwing, and a spec pins the seam so a
168
+ * libp2p upgrade that moves it fails loudly instead of silently reverting this
169
+ * module to the discovery wait that never fires.
170
+ */
171
+ export function findCircuitRelayTransport(node: Libp2p): CircuitRelayTransportLike | null {
172
+ for (const transport of nodeTransports(node)) {
173
+ const store = (transport as { reservationStore?: unknown }).reservationStore;
174
+ if (isReservationStore(store)) {
175
+ return { reservationStore: store };
176
+ }
177
+ }
178
+ return null;
179
+ }
180
+
181
+ function nodeTransports(node: Libp2p): readonly unknown[] {
182
+ const manager = (node as Libp2p & Libp2pComponentsLike).components?.transportManager;
183
+ if (typeof manager?.getTransports !== 'function') {
184
+ log('No transportManager.getTransports() on this node — libp2p internals moved?');
185
+ return [];
186
+ }
187
+ try {
188
+ return manager.getTransports();
189
+ } catch (err) {
190
+ log('transportManager.getTransports() threw: %o', err);
191
+ return [];
192
+ }
193
+ }
194
+
195
+ function isReservationStore(value: unknown): value is RelayReservationStoreLike {
196
+ if (typeof value !== 'object' || value === null) {
197
+ return false;
198
+ }
199
+ const store = value as Partial<RelayReservationStoreLike>;
200
+ return typeof store.addRelay === 'function' && typeof store.hasReservation === 'function';
201
+ }
202
+
203
+ /** Sentinel resolved by the deadline race in {@link requestOneReservation}. */
204
+ const DEADLINE_PASSED = Symbol('relay-reservation-deadline-passed');
205
+
206
+ /** A relay that answered its dial, paired with the address it was dialed at. */
207
+ interface ConnectedRelay {
208
+ addr: string;
209
+ peerId: PeerId;
210
+ }
211
+
212
+ /**
213
+ * Dial every relay in `addrs`, ask the first one that answers for a reservation
214
+ * slot, then wait until a `/p2p-circuit` address appears.
215
+ *
216
+ * Never throws — a dial rejection, a rejected reservation, a MALFORMED address,
217
+ * or a timeout all come back as an `error` string. A dial that throws does NOT
218
+ * cost the rest of the list: one dead relay among two must not cost the
219
+ * reservation on the live one, so every addr is dialed and the first error (in
220
+ * list order) is kept. A reservation that lands wins over any earlier error
221
+ * (`error: null`).
222
+ *
223
+ * `timeoutMs` bounds the WHOLE drive — dials, reservation requests and the wait
224
+ * share one deadline.
225
+ */
226
+ export async function driveRelayReservation(
227
+ node: Libp2p,
228
+ addrs: readonly string[],
229
+ opts?: RelayReserveOptions
230
+ ): Promise<{ error: string | null }> {
231
+ if (addrs.length === 0) {
232
+ return { error: null };
233
+ }
234
+ const timeoutMs = opts?.timeoutMs ?? DEFAULT_RELAY_RESERVE_TIMEOUT_MS;
235
+ // Clamped: a caller-supplied 0 would spin the poll loop hot until the deadline.
236
+ const pollMs = Math.max(1, opts?.pollMs ?? DEFAULT_RELAY_RESERVE_POLL_MS);
237
+ const deadline = Date.now() + timeoutMs;
238
+
239
+ const { connected, error: dialError } = await dialRelays(node, addrs, deadline);
240
+ const attempt = await requestReservation(node, connected, deadline);
241
+ // NOTE: a REJECTED reservation still spends the rest of the deadline polling,
242
+ // because discovery may independently land one (only the no-transport case is
243
+ // `fatal`). So a misconfigured node reports its now-legible reason a full
244
+ // `timeoutMs` late. If startup latency on that path ever matters, shorten the
245
+ // wait once every connected relay has rejected — do not skip it outright.
246
+ if (!attempt.fatal && (await waitForCircuitReservation(node, deadline, pollMs))) {
247
+ return { error: null };
248
+ }
249
+ return {
250
+ error: attempt.error ?? dialError ?? `no circuit reservation within ${timeoutMs}ms`
251
+ };
252
+ }
253
+
254
+ /**
255
+ * Dial every relay CONCURRENTLY under the drive's shared deadline. Reports the
256
+ * relays that answered (in list order, for the reservation step) and the first
257
+ * failure in LIST order (`null` when every dial connected).
258
+ *
259
+ * Concurrent and deadline-bound because this whole drive is awaited on a browser
260
+ * tab's startup path: dialing serially with libp2p's own (much longer) per-dial
261
+ * timeout meant N unreachable relays cost N dial timeouts before the reservation
262
+ * request even began, so `timeoutMs` bounded only the tail of the operation.
263
+ *
264
+ * Aborting a dial at the deadline is not a lost reservation — the steps that
265
+ * follow have no time left either, so the drive would report `error` regardless.
266
+ */
267
+ async function dialRelays(
268
+ node: Libp2p,
269
+ addrs: readonly string[],
270
+ deadline: number
271
+ ): Promise<{ connected: ConnectedRelay[]; error: string | null }> {
272
+ // An explicit controller, not `AbortSignal.timeout` — the latter is not
273
+ // reliably present on React Native/Hermes, which runs this same module.
274
+ const controller = new AbortController();
275
+ const timer = setTimeout(() => controller.abort(), Math.max(0, deadline - Date.now()));
276
+ try {
277
+ const results = await Promise.allSettled(
278
+ addrs.map((addr) => dialOne(node, addr, controller.signal))
279
+ );
280
+ return { connected: connectedRelays(addrs, results), error: firstDialError(addrs, results) };
281
+ } finally {
282
+ clearTimeout(timer);
283
+ }
284
+ }
285
+
286
+ /**
287
+ * One dial, with the address PARSED INSIDE the promise.
288
+ *
289
+ * `multiaddr()` throws SYNCHRONOUSLY on a malformed string, and a throw out of
290
+ * the `map` callback escapes `Promise.allSettled` altogether — it would reject
291
+ * the whole drive (breaking the never-throws contract) and discard the dials to
292
+ * the other, perfectly good, addrs. `async` demotes it to a settled rejection,
293
+ * which is already exactly how a dial failure is reported.
294
+ */
295
+ async function dialOne(
296
+ node: Libp2p,
297
+ addr: string,
298
+ signal: AbortSignal
299
+ ): Promise<{ remotePeer: PeerId }> {
300
+ return node.dial(multiaddr(addr), { signal });
301
+ }
302
+
303
+ function connectedRelays(
304
+ addrs: readonly string[],
305
+ results: readonly PromiseSettledResult<{ remotePeer: PeerId }>[]
306
+ ): ConnectedRelay[] {
307
+ const connected: ConnectedRelay[] = [];
308
+ results.forEach((result, index) => {
309
+ if (result.status !== 'fulfilled') return;
310
+ connected.push({ addr: addrs[index], peerId: result.value.remotePeer });
311
+ });
312
+ return connected;
313
+ }
314
+
315
+ /** Log every dial rejection; return the first one in list order. */
316
+ function firstDialError(
317
+ addrs: readonly string[],
318
+ results: readonly PromiseSettledResult<unknown>[]
319
+ ): string | null {
320
+ let first: string | null = null;
321
+ results.forEach((result, index) => {
322
+ if (result.status !== 'rejected') return;
323
+ const message = result.reason instanceof Error ? result.reason.message : String(result.reason);
324
+ log('Relay dial failed (%s): %s', addrs[index], message);
325
+ first ??= message;
326
+ });
327
+ return first;
328
+ }
329
+
330
+ /**
331
+ * Outcome of the explicit reservation request.
332
+ *
333
+ * `fatal` means no `/p2p-circuit` address can EVER appear (the node has no
334
+ * circuit-relay transport at all), so the caller must report immediately rather
335
+ * than spend the rest of the deadline polling for something that cannot happen.
336
+ * A rejected request is NOT fatal: discovery may still land a reservation for a
337
+ * relay that does happen to share this node's identify prefix.
338
+ */
339
+ interface ReservationAttempt {
340
+ error: string | null;
341
+ fatal: boolean;
342
+ }
343
+
344
+ /**
345
+ * Ask the connected relays, in list order, for a reservation slot; stop at the
346
+ * first success.
347
+ *
348
+ * `'discovered'`, not `'configured'`: the search listener's
349
+ * `relay:created-reservation` handler ignores `configured` reservations outright,
350
+ * so the `/p2p-circuit` listen address would never be published and
351
+ * `getMultiaddrs()` would stay empty even though the reservation succeeded.
352
+ * `'discovered'` consumes the pending-reservation id the bare `/p2p-circuit`
353
+ * listener registered, which is exactly what that handler matches on.
354
+ *
355
+ * Sequential, not concurrent: a bare `/p2p-circuit` listener registers exactly
356
+ * ONE pending reservation, so a second concurrent `addRelay` would be rejected
357
+ * with `HadEnoughRelaysError` — noise, not a failure. Running discovery is not a
358
+ * conflict either; `addRelay` dedupes through its own peer queue, so a relay that
359
+ * genuinely is discoverable still reserves exactly once.
360
+ */
361
+ async function requestReservation(
362
+ node: Libp2p,
363
+ connected: readonly ConnectedRelay[],
364
+ deadline: number
365
+ ): Promise<ReservationAttempt> {
366
+ if (connected.length === 0) {
367
+ // Nothing answered — the dial error is the whole story.
368
+ return { error: null, fatal: false };
369
+ }
370
+ const transport = findCircuitRelayTransport(node);
371
+ if (transport === null) {
372
+ return {
373
+ error: 'node has no circuit-relay transport — add circuitRelayTransport() to its transports',
374
+ fatal: true
375
+ };
376
+ }
377
+ let firstError: string | null = null;
378
+ for (const relay of connected) {
379
+ if (transport.reservationStore.hasReservation(relay.peerId)) {
380
+ return { error: null, fatal: false };
381
+ }
382
+ if (Date.now() >= deadline) {
383
+ break;
384
+ }
385
+ const failure = await requestOneReservation(transport.reservationStore, relay, deadline);
386
+ if (failure === null) {
387
+ return { error: null, fatal: false };
388
+ }
389
+ firstError ??= failure;
390
+ }
391
+ return { error: firstError, fatal: false };
392
+ }
393
+
394
+ /**
395
+ * One `addRelay` call, bounded by the drive's deadline. Returns `null` on
396
+ * success, or the reason it failed.
397
+ *
398
+ * Deadline-raced because `addRelay` runs on libp2p's own (much longer) reservation
399
+ * timeout and takes no signal: without the race a drive given 1.5 s would sit on a
400
+ * silent relay for libp2p's timeout instead. The abandoned promise stays handled —
401
+ * `Promise.race` attaches its own handlers — so a later rejection is not unhandled.
402
+ */
403
+ async function requestOneReservation(
404
+ store: RelayReservationStoreLike,
405
+ relay: ConnectedRelay,
406
+ deadline: number
407
+ ): Promise<string | null> {
408
+ let timer: ReturnType<typeof setTimeout> | undefined;
409
+ const expired = new Promise<typeof DEADLINE_PASSED>((resolve) => {
410
+ timer = setTimeout(() => resolve(DEADLINE_PASSED), Math.max(0, deadline - Date.now()));
411
+ });
412
+ try {
413
+ const outcome = await Promise.race([store.addRelay(relay.peerId, 'discovered'), expired]);
414
+ if (outcome === DEADLINE_PASSED) {
415
+ log('Relay reservation request (%s) still pending at the deadline', relay.addr);
416
+ return `relay reservation request to ${relay.addr} did not complete before the deadline`;
417
+ }
418
+ return null;
419
+ } catch (err) {
420
+ const message = describeReservationFailure(err, relay.addr);
421
+ log('Relay reservation failed (%s): %s', relay.addr, message);
422
+ return message;
423
+ } finally {
424
+ clearTimeout(timer);
425
+ }
426
+ }
427
+
428
+ /**
429
+ * Turn libp2p's reservation rejection into a reason that names the actual cause.
430
+ *
431
+ * `HadEnoughRelaysError` needs translating rather than passing through: its own
432
+ * message ("we do not need any more relays") says the opposite of what happened.
433
+ * A `'discovered'` reservation is refused when the node holds NO pending
434
+ * reservation id, and a node holds one only while it listens on the bare
435
+ * `/p2p-circuit` search address — so the real cause is a missing listen address.
436
+ */
437
+ function describeReservationFailure(err: unknown, addr: string): string {
438
+ // NOTE: libp2p adds a peer to the reservation store's `relayFilter` when a
439
+ // request fails with `DialError` or `UnsupportedProtocolError`, and the failure
440
+ // path does not reset that filter (it only resets when a reservation is actually
441
+ // removed). So a SECOND drive against the same relay in the same process reports
442
+ // `ListenError: The relay was previously invalid` even if the relay has since
443
+ // recovered. `RelayReservationLoop` clears the entry before every attempt (see
444
+ // {@link clearRelayFilterEntry}); a caller that re-drives WITHOUT the supervisor
445
+ // still has to deal with the filter itself.
446
+ const name = err instanceof Error ? err.name : '';
447
+ const message = err instanceof Error ? err.message : String(err);
448
+ switch (name) {
449
+ case 'HadEnoughRelaysError':
450
+ 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`;
451
+ case 'UnsupportedProtocolError':
452
+ return `peer at ${addr} does not speak the circuit-relay hop protocol — it is not a relay`;
453
+ default:
454
+ return `relay reservation on ${addr} failed: ${message}`;
455
+ }
456
+ }
457
+
458
+ /**
459
+ * Poll until the node advertises a `/p2p-circuit` address, or the deadline passes.
460
+ *
461
+ * Still a poll even though the reservation is now requested explicitly: `addRelay`
462
+ * resolving means the RELAY accepted, while the listen address is published a tick
463
+ * later by the listener's `relay:created-reservation` handler, and a reservation
464
+ * that discovery lands independently has no return value to await at all.
465
+ *
466
+ * NOTE: polls rather than subscribing to libp2p's `self:peer:update` — it keeps
467
+ * this free of libp2p event-name coupling. If 250 ms of reservation latency ever
468
+ * matters, switch to the event and keep the poll as a fallback.
469
+ */
470
+ async function waitForCircuitReservation(
471
+ node: Libp2p,
472
+ deadline: number,
473
+ pollMs: number
474
+ ): Promise<boolean> {
475
+ for (;;) {
476
+ if (circuitMultiaddrs(node).length > 0) {
477
+ return true;
478
+ }
479
+ if (Date.now() >= deadline) {
480
+ return false;
481
+ }
482
+ await delay(Math.min(pollMs, Math.max(0, deadline - Date.now())));
483
+ }
484
+ }
485
+
486
+ function delay(ms: number): Promise<void> {
487
+ return new Promise((resolve) => setTimeout(resolve, ms));
488
+ }
489
+
490
+ /** Gap between liveness checks while a reservation is held. */
491
+ export const DEFAULT_RELAY_CHECK_MS = 5_000;
492
+ /** Backoff before the first re-drive after a failed attempt. */
493
+ export const DEFAULT_RELAY_MIN_BACKOFF_MS = 2_000;
494
+ /** Ceiling the backoff doubles up to. */
495
+ export const DEFAULT_RELAY_MAX_BACKOFF_MS = 60_000;
496
+
497
+ export interface RelayReservationSupervisorOptions extends RelayReserveOptions {
498
+ /** Gap between liveness checks while a reservation is held. Default 5_000. */
499
+ checkMs?: number;
500
+ /** Backoff before the first re-drive after a failure. Default 2_000. */
501
+ minBackoffMs?: number;
502
+ /** Backoff ceiling. Default 60_000. */
503
+ maxBackoffMs?: number;
504
+ }
505
+
506
+ /**
507
+ * A running retry loop for one node + relay list. Obtained from
508
+ * {@link superviseRelayReservation}; its only imperative is {@link stop}.
509
+ */
510
+ export interface RelayReservationSupervisor {
511
+ /**
512
+ * Resolves once the FIRST attempt has settled — so a caller can await startup
513
+ * exactly as it awaited a single {@link driveRelayReservation}, and the retries
514
+ * carry on in the background afterwards. Also resolves on {@link stop}, so an
515
+ * awaiting caller is never left hanging.
516
+ */
517
+ readonly firstAttempt: Promise<void>;
518
+ /** True while a drive is in flight. */
519
+ readonly driving: boolean;
520
+ /** Epoch ms of the next scheduled tick; `null` while a drive is running. */
521
+ readonly retryAtMs: number | null;
522
+ /** Reason the last drive produced no reservation; `null` once one is held. */
523
+ readonly lastError: string | null;
524
+ /**
525
+ * Idempotent. Clears the timer so no further drive is scheduled. A drive that
526
+ * is ALREADY in flight is not aborted — {@link driveRelayReservation} takes no
527
+ * signal — but its result is discarded and nothing follows it.
528
+ */
529
+ stop(): void;
530
+ }
531
+
532
+ /**
533
+ * Keep asking for a relay reservation until one is held, then keep watching that
534
+ * it still is — the thing that makes a lost reservation recover on its own.
535
+ *
536
+ * Needed because nothing else re-drives: libp2p re-fills a search listener's
537
+ * freed slot from relay DISCOVERY, and a cadre node's namespaced identify puts
538
+ * discovery permanently out of reach (see the module header). Without this loop a
539
+ * relay restart left a browser tab undialable until the user reloaded the page.
540
+ *
541
+ * Per tick:
542
+ * - a reservation is held → reset the backoff, clear the error, re-check in
543
+ * `checkMs`. No drive: a healthy node must not re-request every few seconds.
544
+ * - otherwise → un-poison the reservation store's relay filter (see
545
+ * {@link clearRelayFilterEntry}) and run ONE {@link driveRelayReservation}.
546
+ * If that lands a reservation, rejoin the healthy path above; if not, sleep
547
+ * the current backoff and double it up to `maxBackoffMs`.
548
+ *
549
+ * Starts immediately; the first tick runs before this returns.
550
+ */
551
+ export function superviseRelayReservation(
552
+ node: Libp2p,
553
+ addrs: readonly string[],
554
+ opts?: RelayReservationSupervisorOptions
555
+ ): RelayReservationSupervisor {
556
+ return new RelayReservationLoop(node, [...addrs], opts ?? {});
557
+ }
558
+
559
+ /**
560
+ * Forget that `addr`'s peer ever failed a reservation request, so the next
561
+ * attempt is actually made rather than refused out of hand.
562
+ *
563
+ * `ReservationStore` records a peer in `relayFilter` when its reservation request
564
+ * fails with `DialError` or `UnsupportedProtocolError`, and NOTHING on that path
565
+ * ever clears it: the reset lives in `#checkReservationCount`, which only runs
566
+ * when a reservation is genuinely removed, and `#removeReservation` early-returns
567
+ * when there was never one. So a relay that was briefly not-a-relay (or died
568
+ * between our dial and the hop request) stays permanently rejected with
569
+ * `The relay was previously invalid` — measured, not inferred.
570
+ *
571
+ * Fails soft in every direction: no `relayFilter`, no `remove`, an addr with no
572
+ * peer id, a malformed addr — all mean "no un-poisoning", never a throw. The
573
+ * retry loop still recovers the common case without this, because a relay that is
574
+ * simply DOWN fails our own dial first and never reaches the filter.
575
+ *
576
+ * Returns whether an entry was actually removed (for specs; callers ignore it).
577
+ */
578
+ export function clearRelayFilterEntry(store: RelayReservationStoreLike, addr: string): boolean {
579
+ const filter = store.relayFilter;
580
+ if (typeof filter?.remove !== 'function') {
581
+ log('Reservation store has no removable relayFilter — cannot un-poison %s', addr);
582
+ return false;
583
+ }
584
+ try {
585
+ // The peer id is in the multiaddr, so this costs no dial and can run before one.
586
+ const peerId = trailingPeerId(multiaddr(addr));
587
+ if (peerId === null) {
588
+ // NOTE: an addr with no `/p2p/` component can still be dialed and reserved
589
+ // through (the peer id comes off the connection), but it can never be
590
+ // un-poisoned — so for THAT addr a poisoned filter is permanent again. No
591
+ // caller supplies such an addr today; if one ever does, resolve the peer id
592
+ // from the live connection instead of the multiaddr.
593
+ return false;
594
+ }
595
+ return filter.remove(peerIdFromString(peerId).toMultihash().bytes);
596
+ } catch (err) {
597
+ log('Could not clear the relayFilter entry for %s: %o', addr, err);
598
+ return false;
599
+ }
600
+ }
601
+
602
+ /** The self-rescheduling loop behind {@link superviseRelayReservation}. */
603
+ class RelayReservationLoop implements RelayReservationSupervisor {
604
+ readonly firstAttempt: Promise<void>;
605
+
606
+ private readonly checkMs: number;
607
+ private readonly minBackoffMs: number;
608
+ private readonly maxBackoffMs: number;
609
+ private backoffMs: number;
610
+ private timer: ReturnType<typeof setTimeout> | null = null;
611
+ private stopped = false;
612
+ private inFlight = false;
613
+ private nextTickAtMs: number | null = null;
614
+ private failure: string | null = null;
615
+ private settleFirstAttempt: () => void = () => {};
616
+ private firstAttemptSettled = false;
617
+
618
+ constructor(
619
+ private readonly node: Libp2p,
620
+ private readonly addrs: readonly string[],
621
+ private readonly opts: RelayReservationSupervisorOptions
622
+ ) {
623
+ // Clamped away from 0: a caller-supplied 0 would spin the loop hot.
624
+ this.checkMs = Math.max(1, opts.checkMs ?? DEFAULT_RELAY_CHECK_MS);
625
+ this.minBackoffMs = Math.max(1, opts.minBackoffMs ?? DEFAULT_RELAY_MIN_BACKOFF_MS);
626
+ this.maxBackoffMs = Math.max(
627
+ this.minBackoffMs,
628
+ opts.maxBackoffMs ?? DEFAULT_RELAY_MAX_BACKOFF_MS
629
+ );
630
+ this.backoffMs = this.minBackoffMs;
631
+ this.firstAttempt = new Promise((resolve) => {
632
+ this.settleFirstAttempt = resolve;
633
+ });
634
+ void this.tick();
635
+ }
636
+
637
+ get driving(): boolean {
638
+ return this.inFlight;
639
+ }
640
+
641
+ get retryAtMs(): number | null {
642
+ return this.nextTickAtMs;
643
+ }
644
+
645
+ get lastError(): string | null {
646
+ return this.failure;
647
+ }
648
+
649
+ stop(): void {
650
+ if (this.stopped) {
651
+ return;
652
+ }
653
+ this.stopped = true;
654
+ if (this.timer !== null) {
655
+ clearTimeout(this.timer);
656
+ this.timer = null;
657
+ }
658
+ this.nextTickAtMs = null;
659
+ this.settleFirst();
660
+ }
661
+
662
+ private async tick(): Promise<void> {
663
+ if (this.stopped) {
664
+ return;
665
+ }
666
+ this.nextTickAtMs = null;
667
+ if (this.reservationHeld()) {
668
+ this.onReservationHeld();
669
+ return;
670
+ }
671
+ await this.driveOnce();
672
+ if (this.stopped) {
673
+ return;
674
+ }
675
+ this.settleFirst();
676
+ // A drive that LANDED a reservation resumes the healthy cadence immediately.
677
+ // Backing off here instead would leave the first liveness check after a long
678
+ // outage a fully grown backoff away (up to `maxBackoffMs`), so a reservation
679
+ // lost again right after recovery would go unnoticed for that whole window.
680
+ if (this.reservationHeld()) {
681
+ this.onReservationHeld();
682
+ return;
683
+ }
684
+ this.scheduleBackoff();
685
+ }
686
+
687
+ private reservationHeld(): boolean {
688
+ return circuitMultiaddrs(this.node).length > 0;
689
+ }
690
+
691
+ /** Healthy tick: nothing to request, so only reset and re-check later. */
692
+ private onReservationHeld(): void {
693
+ this.backoffMs = this.minBackoffMs;
694
+ this.failure = null;
695
+ this.settleFirst();
696
+ this.schedule(this.checkMs);
697
+ }
698
+
699
+ private async driveOnce(): Promise<void> {
700
+ this.inFlight = true;
701
+ try {
702
+ this.unpoisonRelayFilter();
703
+ const { error } = await driveRelayReservation(this.node, this.addrs, this.opts);
704
+ if (!this.stopped) {
705
+ this.failure = error;
706
+ }
707
+ } catch (err) {
708
+ // `driveRelayReservation` is fail-soft by contract, so reaching here means
709
+ // that contract broke. The loop must survive it anyway: an escaping
710
+ // rejection would leave `firstAttempt` pending FOREVER (hanging every
711
+ // caller that awaits a reservation at startup) and schedule no further
712
+ // attempt, which is the failure this whole supervisor exists to prevent.
713
+ const message = err instanceof Error ? err.message : String(err);
714
+ log('Relay reservation drive threw, which it should not: %s', message);
715
+ if (!this.stopped) {
716
+ this.failure = message;
717
+ }
718
+ } finally {
719
+ this.inFlight = false;
720
+ }
721
+ }
722
+
723
+ private scheduleBackoff(): void {
724
+ const wait = this.backoffMs;
725
+ this.backoffMs = Math.min(this.backoffMs * 2, this.maxBackoffMs);
726
+ this.schedule(wait);
727
+ }
728
+
729
+ private unpoisonRelayFilter(): void {
730
+ const transport = findCircuitRelayTransport(this.node);
731
+ if (transport === null) {
732
+ return;
733
+ }
734
+ for (const addr of this.addrs) {
735
+ clearRelayFilterEntry(transport.reservationStore, addr);
736
+ }
737
+ }
738
+
739
+ private schedule(ms: number): void {
740
+ if (this.stopped) {
741
+ return;
742
+ }
743
+ this.nextTickAtMs = Date.now() + ms;
744
+ this.timer = setTimeout(() => {
745
+ this.timer = null;
746
+ void this.tick();
747
+ }, ms);
748
+ // Node keeps the process alive while a timer is pending, so an un-unref'd
749
+ // supervisor would hang every CLI run and vitest worker that ever reserved.
750
+ // Cast + optional-chain: browsers and React Native have no `unref`.
751
+ (this.timer as { unref?: () => void }).unref?.();
752
+ }
753
+
754
+ private settleFirst(): void {
755
+ if (this.firstAttemptSettled) {
756
+ return;
757
+ }
758
+ this.firstAttemptSettled = true;
759
+ this.settleFirstAttempt();
760
+ }
761
+ }
762
+
763
+ /**
764
+ * Derive the reservation posture, reading the node's circuit addrs LIVE. Pure
765
+ * apart from that read, so the precedence is testable on its own:
766
+ *
767
+ * | condition | status |
768
+ * | ------------------------ | ----------------------------------------------- |
769
+ * | no addrs supplied | `none` |
770
+ * | live circuit addrs held | `reserved` (`error: null`) |
771
+ * | a drive is in flight | `dialing` |
772
+ * | a retry is scheduled | `retrying` |
773
+ * | otherwise | `error` |
774
+ *
775
+ * `reserved` is checked BEFORE `error` on purpose: the circuit addrs are read
776
+ * live, so a reservation that lands by ANY route supersedes a stale error string
777
+ * without a second drive.
778
+ *
779
+ * `retrying` sits between the two so that `error` carries a sharper meaning:
780
+ * NOBODY IS GOING TO TRY AGAIN. A lost reservation does come back on its own now,
781
+ * as long as a {@link RelayReservationSupervisor} is running — that loop is the
782
+ * only thing that re-drives, since libp2p re-fills a search listener's freed slot
783
+ * from relay DISCOVERY, which a cadre node's namespaced identify puts permanently
784
+ * out of reach (see the module header). So `error` means the supervisor was
785
+ * stopped, was never started, or there is no node at all.
786
+ *
787
+ * `retryAtMs` is the supervisor's next scheduled tick (`null` while a drive runs
788
+ * or when there is no supervisor); it both selects `retrying` and is passed
789
+ * through so a UI can count down to the next attempt.
790
+ */
791
+ export function resolveRelayReservationState(
792
+ node: Libp2p | null,
793
+ addrs: readonly string[],
794
+ lastError: string | null,
795
+ driving: boolean,
796
+ retryAtMs: number | null
797
+ ): RelayReservationState {
798
+ if (addrs.length === 0) {
799
+ return { status: 'none', addrs: [], circuitAddrs: [], error: null, retryAtMs: null };
800
+ }
801
+ const supplied = [...addrs];
802
+ const circuitAddrs = node ? circuitMultiaddrs(node) : [];
803
+ if (circuitAddrs.length > 0) {
804
+ return { status: 'reserved', addrs: supplied, circuitAddrs, error: null, retryAtMs };
805
+ }
806
+ if (driving) {
807
+ return {
808
+ status: 'dialing',
809
+ addrs: supplied,
810
+ circuitAddrs: [],
811
+ error: lastError,
812
+ retryAtMs: null
813
+ };
814
+ }
815
+ // `driveRelayReservation` always reports a reason when it finishes without a
816
+ // reservation, so `lastError` is normally set below. The fallback only covers
817
+ // addrs recorded without a completed drive.
818
+ const error = lastError ?? 'no circuit reservation held';
819
+ if (retryAtMs !== null) {
820
+ return { status: 'retrying', addrs: supplied, circuitAddrs: [], error, retryAtMs };
821
+ }
822
+ return { status: 'error', addrs: supplied, circuitAddrs: [], error, retryAtMs: null };
823
+ }