@serfab/cadre-core 1.8.0 → 1.10.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 (126) hide show
  1. package/dist/cadre-node.d.ts +301 -121
  2. package/dist/cadre-node.js +588 -244
  3. package/dist/cadre-node.js.map +1 -1
  4. package/dist/control-authorization.d.ts +2 -2
  5. package/dist/control-authorization.js +1 -0
  6. package/dist/control-authorization.js.map +1 -1
  7. package/dist/control-cohort.d.ts +1 -1
  8. package/dist/control-cohort.js +1 -1
  9. package/dist/control-database.d.ts +105 -14
  10. package/dist/control-database.js +242 -73
  11. package/dist/control-database.js.map +1 -1
  12. package/dist/control-formation-recorder.d.ts +6 -6
  13. package/dist/control-formation-recorder.js +7 -8
  14. package/dist/control-formation-recorder.js.map +1 -1
  15. package/dist/control-schema.d.ts +1 -1
  16. package/dist/control-schema.js +90 -3
  17. package/dist/control-schema.js.map +1 -1
  18. package/dist/control-write-retry.d.ts +21 -15
  19. package/dist/control-write-retry.js +21 -15
  20. package/dist/control-write-retry.js.map +1 -1
  21. package/dist/index.d.ts +7 -7
  22. package/dist/index.js +16 -13
  23. package/dist/index.js.map +1 -1
  24. package/dist/invitation-bootstrap.d.ts +32 -0
  25. package/dist/invitation-bootstrap.js +30 -0
  26. package/dist/invitation-bootstrap.js.map +1 -0
  27. package/dist/link-budget.d.ts +204 -119
  28. package/dist/link-budget.js +208 -120
  29. package/dist/link-budget.js.map +1 -1
  30. package/dist/membership-connection-gater.d.ts +3 -3
  31. package/dist/membership-connection-gater.js +3 -3
  32. package/dist/node-local-snapshot.d.ts +6 -4
  33. package/dist/node-local-snapshot.js +7 -3
  34. package/dist/node-local-snapshot.js.map +1 -1
  35. package/dist/peer-dial.d.ts +18 -14
  36. package/dist/peer-dial.js +18 -14
  37. package/dist/peer-dial.js.map +1 -1
  38. package/dist/peer-join-backfill.d.ts +3 -12
  39. package/dist/peer-join-backfill.js +2 -3
  40. package/dist/peer-join-backfill.js.map +1 -1
  41. package/dist/pending-join-runner.d.ts +186 -0
  42. package/dist/pending-join-runner.js +649 -0
  43. package/dist/pending-join-runner.js.map +1 -0
  44. package/dist/push-fanout.d.ts +1 -1
  45. package/dist/push-fanout.js +1 -1
  46. package/dist/seed-bootstrap.d.ts +2 -2
  47. package/dist/seed-bootstrap.js +1 -1
  48. package/dist/strand-addr-protocol.js +2 -2
  49. package/dist/strand-formation-deadlines.d.ts +5 -5
  50. package/dist/strand-formation-deadlines.js +5 -5
  51. package/dist/strand-formation-manager.d.ts +18 -4
  52. package/dist/strand-formation-manager.js +48 -33
  53. package/dist/strand-formation-manager.js.map +1 -1
  54. package/dist/strand-formation-protocol.d.ts +71 -25
  55. package/dist/strand-formation-protocol.js +225 -51
  56. package/dist/strand-formation-protocol.js.map +1 -1
  57. package/dist/strand-formation-rejection.d.ts +94 -0
  58. package/dist/strand-formation-rejection.js +77 -0
  59. package/dist/strand-formation-rejection.js.map +1 -0
  60. package/dist/strand-fret-addrs.d.ts +54 -0
  61. package/dist/strand-fret-addrs.js +108 -0
  62. package/dist/strand-fret-addrs.js.map +1 -0
  63. package/dist/strand-instance-manager.d.ts +9 -38
  64. package/dist/strand-instance-manager.js +17 -74
  65. package/dist/strand-instance-manager.js.map +1 -1
  66. package/dist/strand-network-state-file.d.ts +12 -0
  67. package/dist/strand-network-state-file.js +38 -0
  68. package/dist/strand-network-state-file.js.map +1 -0
  69. package/dist/strand-network-state.d.ts +111 -0
  70. package/dist/strand-network-state.js +191 -0
  71. package/dist/strand-network-state.js.map +1 -0
  72. package/dist/strand-solicitation.d.ts +11 -3
  73. package/dist/strand-solicitation.js +9 -0
  74. package/dist/strand-solicitation.js.map +1 -1
  75. package/dist/types.d.ts +123 -40
  76. package/dist/types.js +5 -9
  77. package/dist/types.js.map +1 -1
  78. package/package.json +25 -24
  79. package/src/cadre-node.ts +637 -251
  80. package/src/control-authorization.ts +117 -116
  81. package/src/control-cohort.ts +1 -1
  82. package/src/control-database.ts +303 -82
  83. package/src/control-formation-recorder.ts +8 -9
  84. package/src/control-schema.ts +90 -3
  85. package/src/control-write-retry.ts +21 -15
  86. package/src/index.ts +36 -56
  87. package/src/invitation-bootstrap.ts +40 -0
  88. package/src/link-budget.ts +221 -120
  89. package/src/membership-connection-gater.ts +3 -3
  90. package/src/node-local-snapshot.ts +12 -7
  91. package/src/peer-dial.ts +18 -14
  92. package/src/peer-join-backfill.ts +5 -6
  93. package/src/pending-join-runner.ts +735 -0
  94. package/src/push-fanout.ts +1 -1
  95. package/src/seed-bootstrap.ts +2 -2
  96. package/src/strand-addr-protocol.ts +2 -2
  97. package/src/strand-formation-deadlines.ts +5 -5
  98. package/src/strand-formation-manager.ts +62 -37
  99. package/src/strand-formation-protocol.ts +1036 -803
  100. package/src/strand-formation-rejection.ts +129 -0
  101. package/src/strand-fret-addrs.ts +145 -0
  102. package/src/strand-instance-manager.ts +24 -97
  103. package/src/strand-network-state-file.ts +40 -0
  104. package/src/strand-network-state.ts +243 -0
  105. package/src/strand-solicitation.ts +17 -4
  106. package/src/types.ts +119 -40
  107. package/dist/strand-peer-book-file.d.ts +0 -12
  108. package/dist/strand-peer-book-file.js +0 -37
  109. package/dist/strand-peer-book-file.js.map +0 -1
  110. package/dist/strand-peer-book-protocol.d.ts +0 -168
  111. package/dist/strand-peer-book-protocol.js +0 -356
  112. package/dist/strand-peer-book-protocol.js.map +0 -1
  113. package/dist/strand-peer-book-swap.d.ts +0 -104
  114. package/dist/strand-peer-book-swap.js +0 -284
  115. package/dist/strand-peer-book-swap.js.map +0 -1
  116. package/dist/strand-peer-book.d.ts +0 -159
  117. package/dist/strand-peer-book.js +0 -361
  118. package/dist/strand-peer-book.js.map +0 -1
  119. package/dist/strand-peer-observer.d.ts +0 -88
  120. package/dist/strand-peer-observer.js +0 -180
  121. package/dist/strand-peer-observer.js.map +0 -1
  122. package/src/strand-peer-book-file.ts +0 -39
  123. package/src/strand-peer-book-protocol.ts +0 -466
  124. package/src/strand-peer-book-swap.ts +0 -338
  125. package/src/strand-peer-book.ts +0 -475
  126. package/src/strand-peer-observer.ts +0 -235
@@ -0,0 +1,129 @@
1
+ /**
2
+ * How a formation dial fails, as types a joining device can branch on without reading the
3
+ * human-facing wording: a responder's refusal carries a fixed {@link FormationRejectionCode}
4
+ * on the wire and surfaces as a {@link FormationRejectedError}; a dial that never got an
5
+ * answer surfaces as a {@link FormationUnreachableError}.
6
+ */
7
+
8
+ /**
9
+ * Why a formation responder refused a join. Sent beside the free-text `reason` on every
10
+ * `approved: false` result frame (`FormationResultMessage.code`).
11
+ */
12
+ export type FormationRejectionCode =
13
+ /**
14
+ * No invitation row for this token on THIS responder. Retryable: a sibling machine of the
15
+ * inviter may not have received the row yet. Leaks nothing — only a holder of the token can
16
+ * ask, and an unknown token means the same as one never minted.
17
+ */
18
+ | 'token-unknown'
19
+ /**
20
+ * The invitation expired, or every allowed use is recorded. The loser of a redemption race
21
+ * and a latecomer both get this code, so neither can tell the two apart.
22
+ */
23
+ | 'token-spent'
24
+ /** The joiner's consent signature does not verify (or `partyId` does not embed `peerKey`). */
25
+ | 'consent-invalid'
26
+ /** The responder's disclosure validator refused the disclosure. */
27
+ | 'disclosure-invalid'
28
+ | 'disclosure-too-large'
29
+ /** The invitation's outside approval hook answered no. */
30
+ | 'approval-refused'
31
+ /** The invitation's outside approval hook could not be reached or did not answer in time. */
32
+ | 'approval-unavailable'
33
+ /** The inviter's approval setup is wrong: a malformed answer, an unenrolled key, or a misconfigured hook. */
34
+ | 'approval-invalid'
35
+ /**
36
+ * The host strand is not running (or not yet replicated) on this responder, or issuing the
37
+ * joiner's membership invitation into it failed.
38
+ */
39
+ | 'host-strand-unavailable'
40
+ /** The host strand predates the per-party identity split and can never admit a joiner. */
41
+ | 'host-strand-must-be-recreated'
42
+ /** The responder is at its cap on concurrent formation sessions. */
43
+ | 'busy'
44
+ /** Provisioning outran the responder's budget; the invitation is left unspent. */
45
+ | 'provisioning-timeout'
46
+ /** The consent write failed for a reason other than a spent invitation. */
47
+ | 'conflict'
48
+ /** An unexpected responder-side failure. */
49
+ | 'internal';
50
+
51
+ /**
52
+ * Which rejections are worth retrying — the single place that says so. A retry repeats the
53
+ * same redemption later (or against another of the inviter's machines); a final code means
54
+ * no retry of this invitation can succeed.
55
+ */
56
+ export const FORMATION_REJECTION_RETRYABLE: Readonly<Record<FormationRejectionCode, boolean>> = {
57
+ 'token-unknown': true,
58
+ 'token-spent': false,
59
+ 'consent-invalid': false,
60
+ 'disclosure-invalid': false,
61
+ 'disclosure-too-large': false,
62
+ 'approval-refused': false,
63
+ 'approval-unavailable': true,
64
+ 'approval-invalid': false,
65
+ 'host-strand-unavailable': true,
66
+ 'host-strand-must-be-recreated': false,
67
+ 'busy': true,
68
+ 'provisioning-timeout': true,
69
+ 'conflict': true,
70
+ 'internal': true
71
+ };
72
+
73
+ /** Is `value` a code this build knows? Own keys only, so a peer's `'constructor'` does not pass. */
74
+ export function isFormationRejectionCode(value: unknown): value is FormationRejectionCode {
75
+ return typeof value === 'string' && Object.prototype.hasOwnProperty.call(FORMATION_REJECTION_RETRYABLE, value);
76
+ }
77
+
78
+ /**
79
+ * The responder answered and refused the join.
80
+ *
81
+ * `code` is `'unrecognized'` when the frame carried no code or one this build does not know
82
+ * — formation runs between two parties on different versions — and such a rejection counts
83
+ * as retryable: retrying an unknown answer until the invitation expires is safe, while giving
84
+ * up on one that would have succeeded is not.
85
+ */
86
+ export class FormationRejectedError extends Error {
87
+ readonly code: FormationRejectionCode | 'unrecognized';
88
+ readonly reason: string;
89
+ readonly retryable: boolean;
90
+
91
+ /** Both arguments come straight off the wire, so neither is trusted to have its declared type. */
92
+ constructor(code: unknown, reason: unknown) {
93
+ const text = typeof reason === 'string' ? reason : 'no reason provided';
94
+ super(`Formation rejected: ${text}`);
95
+ this.name = 'FormationRejectedError';
96
+ this.code = isFormationRejectionCode(code) ? code : 'unrecognized';
97
+ this.reason = text;
98
+ this.retryable = this.code === 'unrecognized' || FORMATION_REJECTION_RETRYABLE[this.code];
99
+ }
100
+ }
101
+
102
+ /**
103
+ * The dial ended before a result frame was read: no responder address parsed, every address
104
+ * failed to dial, a deadline passed, or the stream closed early. Always retryable. Keeps the
105
+ * underlying failure's message, and the failure itself as `cause`.
106
+ */
107
+ export class FormationUnreachableError extends Error {
108
+ readonly retryable = true;
109
+
110
+ constructor(message: string, options?: { cause?: unknown }) {
111
+ super(message, options);
112
+ this.name = 'FormationUnreachableError';
113
+ }
114
+ }
115
+
116
+ /**
117
+ * The responder approved the join, so the invitation's one-time token is spent, and then a
118
+ * step on the joining machine failed: persisting the party's membership identity, or
119
+ * remembering the join. Never retryable: the same invitation can only answer `token-spent`
120
+ * from now on, so recovery is fixing the local cause and redeeming a fresh invitation.
121
+ */
122
+ export class FormationPostApprovalError extends Error {
123
+ readonly retryable = false;
124
+
125
+ constructor(readonly strandId: string, message: string, options?: { cause?: unknown }) {
126
+ super(message, options);
127
+ this.name = 'FormationPostApprovalError';
128
+ }
129
+ }
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Reading the signed address records a running strand node's FRET routing table holds,
3
+ * as per-peer addresses ready for that node's own address book (`peer-addr-book.ts`).
4
+ *
5
+ * Why a strand node needs this. libp2p's peerStore hides every address one hour after
6
+ * it was first observed (the `NOTE:` on `mergePeerAddrs`), and FRET does not re-apply
7
+ * the records it holds: it hands a record to the peerStore when a neighbour's snapshot
8
+ * delivers it or a saved table is imported, and the peerStore refuses a record whose
9
+ * sequence number it already has. So a strand node that has been up for more than an
10
+ * hour would have no address for a peer whose connection then drops, although FRET
11
+ * still holds that peer's record. `CadreNode.refreshStrandPeerAddrs` re-merges the
12
+ * records on every pass, which is what keeps another party's strand nodes dialable;
13
+ * own-party siblings are re-resolved separately, over the strand-addr RPC.
14
+ *
15
+ * How long a record is available here is FRET's rule, not this module's: while FRET
16
+ * holds the entry, and at most 14 days after the record was last confirmed (a peer
17
+ * connected at export time counts as confirmed then).
18
+ *
19
+ * Every record is opened and verified here rather than taken on FRET's word. A record
20
+ * is self-certifying, the table is reached through a structural type rather than an
21
+ * interface this package depends on, and the address book write is attributed from what
22
+ * the record proves, not from the id the table filed it under.
23
+ */
24
+
25
+ import debug from 'debug';
26
+ import { PeerRecord, RecordEnvelope } from '@libp2p/peer-record';
27
+ import { peerIdFromPublicKey } from '@libp2p/peer-id';
28
+ import { multiaddr, type Multiaddr } from '@multiformats/multiaddr';
29
+ import { fromString as uint8ArrayFromString } from 'uint8arrays';
30
+ import { withTrailingPeerId } from './peer-record.js';
31
+
32
+ const log = debug('sereus:cadre:strand-fret-addrs');
33
+
34
+ /** The slice of FRET's exported routing table read here (`SerializedTable` in `p2p-fret`). */
35
+ interface FretTableSlice {
36
+ entries: ReadonlyArray<{
37
+ id: string;
38
+ /** `envelope` is the base64url of a marshaled libp2p record envelope. */
39
+ addressRecord?: { envelope: string };
40
+ }>;
41
+ }
42
+
43
+ /** The slice of FRET's libp2p service called here. */
44
+ interface FretTableSource {
45
+ exportTable(): FretTableSlice;
46
+ }
47
+
48
+ /**
49
+ * The slice of a strand's libp2p node this module touches. Structurally satisfied by
50
+ * `Libp2p`; db-p2p registers FRET as `services.fret`.
51
+ */
52
+ export interface FretAddrHost {
53
+ peerId: { toString(): string };
54
+ services?: Record<string, unknown>;
55
+ }
56
+
57
+ /** What one read of a strand node's FRET table yields. */
58
+ export interface FretPeerAddrs {
59
+ /** Peer id → the addresses its record lists, each bound to that peer. Table order. */
60
+ peers: Map<string, Multiaddr[]>;
61
+ /**
62
+ * Records left out because they did not decode, did not verify, or were not signed
63
+ * by and about the peer the table filed them under.
64
+ */
65
+ rejected: number;
66
+ }
67
+
68
+ /**
69
+ * The addresses of every peer `host`'s FRET table holds a usable signed record for,
70
+ * `host` itself excluded. A node with no FRET service (a db-p2p build without it, a
71
+ * test double) reads as an empty table. One bad record never costs the others: it is
72
+ * counted in `rejected` and skipped.
73
+ *
74
+ * Throws only what `exportTable()` throws, which a caller treats like any other
75
+ * failure of a pass over a node that may be mid-teardown.
76
+ */
77
+ export async function strandFretPeerAddrs(host: FretAddrHost): Promise<FretPeerAddrs> {
78
+ const result: FretPeerAddrs = { peers: new Map(), rejected: 0 };
79
+ const fret = host.services?.fret;
80
+ if (!isFretTableSource(fret)) {
81
+ return result;
82
+ }
83
+ const selfId = host.peerId.toString();
84
+ for (const entry of fret.exportTable().entries) {
85
+ if (entry.id === selfId || entry.addressRecord === undefined) {
86
+ continue;
87
+ }
88
+ const addrs = await verifiedRecordAddrs(entry.id, entry.addressRecord.envelope);
89
+ if (addrs === null) {
90
+ result.rejected++;
91
+ } else if (addrs.length > 0) {
92
+ result.peers.set(entry.id, addrs);
93
+ }
94
+ }
95
+ return result;
96
+ }
97
+
98
+ function isFretTableSource(service: unknown): service is FretTableSource {
99
+ return typeof service === 'object' && service !== null
100
+ && typeof (service as { exportTable?: unknown }).exportTable === 'function';
101
+ }
102
+
103
+ /**
104
+ * The addresses one record lists, bound to `peerId`; null when the record must not be
105
+ * used. `openAndCertify` proves only that the envelope's own key signed it, so the
106
+ * signer and the peer the payload describes are each held against `peerId` here:
107
+ * without that, any peer could sign a record rewriting another peer's addresses.
108
+ */
109
+ async function verifiedRecordAddrs(peerId: string, envelope: string): Promise<Multiaddr[] | null> {
110
+ try {
111
+ const opened = await RecordEnvelope.openAndCertify(uint8ArrayFromString(envelope, 'base64url'), PeerRecord.DOMAIN);
112
+ const record = PeerRecord.createFromProtobuf(opened.payload);
113
+ const signer = peerIdFromPublicKey(opened.publicKey).toString();
114
+ const subject = record.peerId.toString();
115
+ if (signer !== peerId || subject !== peerId) {
116
+ log('skipping the address record filed under %s: signed by %s about %s', peerId, signer, subject);
117
+ return null;
118
+ }
119
+ return bindToPeer(record.multiaddrs.map((addr) => addr.toString()), peerId);
120
+ } catch (error) {
121
+ log('skipping the address record filed under %s: %o', peerId, error);
122
+ return null;
123
+ }
124
+ }
125
+
126
+ /**
127
+ * A record names its peer once, in `peerId`, so its addresses carry no trailing
128
+ * `/p2p/<peerId>` and a relay-only peer's circuit address ends at the relay hop
129
+ * (`…/p2p/<relay>/p2p-circuit`). Each is given the suffix that makes it a complete
130
+ * dial target; one already terminating in a different peer id does not reach this peer
131
+ * and is dropped.
132
+ *
133
+ * Takes strings because `@libp2p/peer-record` carries its own `@multiformats/multiaddr`
134
+ * copy, a structurally different type from the one `withTrailingPeerId` takes.
135
+ */
136
+ function bindToPeer(addrs: string[], peerId: string): Multiaddr[] {
137
+ const bound: Multiaddr[] = [];
138
+ for (const addr of addrs) {
139
+ const withPeer = withTrailingPeerId(multiaddr(addr), peerId);
140
+ if (withPeer !== null) {
141
+ bound.push(withPeer);
142
+ }
143
+ }
144
+ return bound;
145
+ }
@@ -4,9 +4,7 @@ import { createLibp2pNode, type IRawStorage } from '@optimystic/db-p2p';
4
4
  import { wrapStorageWithCache, disposeStorageCache } from '@serfab/quereus-plugin-sereus';
5
5
  import { StrandDatabase } from './strand-database.js';
6
6
  import { PeerJoinBackfill, type PeerJoinBackfillConfig } from './peer-join-backfill.js';
7
- import { StrandPeerObserver, type StrandPeerObservation } from './strand-peer-observer.js';
8
- import { StrandPeerBookSwap } from './strand-peer-book-swap.js';
9
- import type { StrandPeerBookStore } from './strand-peer-book.js';
7
+ import { strandNetworkStatePersistence, type StrandNetworkStateStore } from './strand-network-state.js';
10
8
  import {
11
9
  StrandRevocationEnforcer,
12
10
  createRevocationConnectionGater,
@@ -45,7 +43,7 @@ import { DEFAULT_CONNECTION_MONITOR, resolveStrandClusterSize, strandClusterPoli
45
43
  import { strandNodeAddrs } from './strand-network-config.js';
46
44
  import { resolveRelayServer } from './relay-server.js';
47
45
  import { superviseRelayReservation, type RelayReservationSupervisor } from './relay-reservation.js';
48
- import { declaredCohortReadDeadlineMs, peerJoinPushBudget, relayReservationBudgetMs, resolveLinkRoundTripMs } from './link-budget.js';
46
+ import { declaredCohortReadDeadlineMs, optimysticDialLimits, peerJoinPushBudget, relayReservationBudgetMs, resolveLinkRoundTripMs } from './link-budget.js';
49
47
 
50
48
  const log = debug('sereus:cadre:strand-manager');
51
49
  const timing = debug('sereus:cadre:timing');
@@ -274,26 +272,14 @@ export interface StartStrandConfig {
274
272
  announceDelegateToRelay?: (strandId: string, relayAddr: string, delegatePeerId: string) => Promise<void>;
275
273
 
276
274
  /**
277
- * Called when the strand's libp2p node identifies a STRAND peer — one whose
278
- * identify result names this strand's block-transfer protocol, so never the
279
- * circuit relay or a bootstrap node — with the addresses it is dialable at
280
- * (`strand-peer-observer.ts`). Throttled per peer; must not throw. `CadreNode`
281
- * wires it to the node-local strand peer book, which is what lets a restarted
282
- * machine dial the peers it was talking to. Absent ⇒ nothing is observed.
283
- * Retained with the launch config, so a hibernation wake re-arms it on the
284
- * rebuilt node.
275
+ * The node-local strand network state (`strand-network-state.ts`): this strand's
276
+ * slice of it is handed to db-p2p as `persistence`, so the strand node saves its
277
+ * FRET routing table (with each peer's signed address record) on every connection
278
+ * and re-imports it when it is next built. Absent ⇒ nothing is saved and the node
279
+ * starts with an empty table. `CadreNode` passes its store. Retained with the launch
280
+ * config, so a hibernation wake rebuilds the node over the same state.
285
281
  */
286
- onStrandPeerIdentified?: (strandId: string, observation: StrandPeerObservation) => void;
287
-
288
- /**
289
- * The node-local strand peer book the book SWAP reads and writes
290
- * (`strand-peer-book-swap.ts`): the strand node signs its own addresses with
291
- * {@link privateKey}, exchanges signed entries with every strand peer it identifies,
292
- * and files what verifies. Absent ⇒ no swap runs — a peer that dials this node's
293
- * swap handler gets no answer. `CadreNode` passes its book store. Retained with the
294
- * launch config, so a hibernation wake re-arms the swap on the rebuilt node.
295
- */
296
- strandPeerBook?: StrandPeerBookStore;
282
+ networkState?: StrandNetworkStateStore;
297
283
  }
298
284
 
299
285
  /**
@@ -428,24 +414,6 @@ export class StrandInstanceManager {
428
414
  * missed writes).
429
415
  */
430
416
  private backfills: Map<string, PeerJoinBackfill> = new Map();
431
- /**
432
- * The per-strand peer-book observation writer (`strand-peer-observer.ts`), keyed
433
- * by strand id. Same lifecycle rationale as {@link backfills}: started in
434
- * `buildStrandRuntime` right after the libp2p node exists, stopped and dropped in
435
- * `releaseRuntime`, so quiesce → resume re-arms it on the rebuilt node. Only
436
- * present when the launch config supplied `onStrandPeerIdentified`.
437
- */
438
- private peerObservers: Map<string, StrandPeerObserver> = new Map();
439
-
440
- /**
441
- * Per-strand strand peer book SWAP driver ({@link StrandPeerBookSwap}) — the signed
442
- * exchange of book entries between strand peers. Same lifetime as the peer-book
443
- * observer above: armed in `buildStrandRuntime` right after the libp2p node exists
444
- * (its protocol handler must be registered before an early peer dials it), stopped
445
- * and dropped in `releaseRuntime`. Only present when the launch config supplied
446
- * `strandPeerBook`.
447
- */
448
- private peerBookSwaps: Map<string, StrandPeerBookSwap> = new Map();
449
417
  /**
450
418
  * The per-strand revoked-peer enforcer (closed strands only), keyed by strand
451
419
  * id. Same lifecycle rationale as {@link backfills}: created in
@@ -821,6 +789,18 @@ export class StrandInstanceManager {
821
789
  enableRingZulu: config.profile === 'storage'
822
790
  },
823
791
  ...(config.privateKey && { privateKey: config.privateKey }),
792
+ // Built per runtime, not per launch: the adapter stops saving once the strand's
793
+ // state is forgotten, and a rebuilt runtime is what starts it saving again.
794
+ //
795
+ // NOTE: the saved state also restores which peers db-p2p saw serving the strand,
796
+ // and it counts them in the cohort until FRET finds them unreachable. A node built
797
+ // while every other member is offline therefore fails its first writes ("Failed to
798
+ // get super-majority") — for 4-6 s on loopback, the window a running node already
799
+ // sees when a member drops. If apps report failed sends after relaunching alone on
800
+ // a slow relayed link, retry the write in the app or raise it upstream (db-p2p's
801
+ // remembered-serving fallback); dropping `persistence` brings back the split
802
+ // restart.
803
+ ...(config.networkState && { persistence: strandNetworkStatePersistence(config.networkState, strandId) }),
824
804
  ...(config.network?.transports && { transports: config.network.transports }),
825
805
  ...(config.network?.noiseCrypto && { noiseCrypto: config.network.noiseCrypto }),
826
806
  // Unconditional, and the same default the control node takes: every node of
@@ -832,6 +812,9 @@ export class StrandInstanceManager {
832
812
  // node is also the listener for every other member's strand node, and Optimystic
833
813
  // derives that listener's limit from this (`link-budget.ts`).
834
814
  linkRoundTripMs: resolveLinkRoundTripMs(config.network?.linkRoundTripMs),
815
+ // The same dial limits as the control node: a strand node dials the same machines,
816
+ // through the same relays and gates.
817
+ ...optimysticDialLimits(config.network?.linkRoundTripMs),
835
818
  // Listen entries plus the WebSocket transport switch they imply — a strand node
836
819
  // announces nothing the operator configured (`strand-network-config.ts`), and
837
820
  // spreads AFTER `transports` above because the switch is a no-op whenever the
@@ -851,48 +834,6 @@ export class StrandInstanceManager {
851
834
 
852
835
  instance.libp2pNode = node;
853
836
 
854
- // The peer-book observation writer, armed BEFORE the database bring-up below
855
- // (unlike the backfill) because the bootstrap dials that follow `libp2p.start()`
856
- // land during that bring-up, and they are exactly the peers worth remembering:
857
- // identify for an early peer may already have fired by the time anything after
858
- // the database initializes runs. Registered in the map immediately so the
859
- // failure rollback (releaseRuntime) stops it like every other runtime component.
860
- const onStrandPeerIdentified = config.onStrandPeerIdentified;
861
- if (onStrandPeerIdentified) {
862
- const observer = new StrandPeerObserver({
863
- label: strandId,
864
- libp2p: node,
865
- protocolPrefix,
866
- onObserved: (observation) => onStrandPeerIdentified(strandId, observation)
867
- });
868
- this.peerObservers.set(strandId, observer);
869
- observer.start();
870
- }
871
-
872
- // The strand peer book SWAP, armed at the same moment and for the same reason as
873
- // the observer: a peer that dials this node's swap handler before it is registered
874
- // fails its exchange and sits out a ten-minute throttle. The own entry is signed
875
- // now and re-signed on every address change, which covers the relay reservation
876
- // landing below (`self:peer:update` fires when the circuit addr is added), so no
877
- // separate post-relay step is needed. Registered in the map immediately so the
878
- // failure rollback (releaseRuntime) stops it like every other runtime component.
879
- //
880
- // NOTE: this is a third `peer:identify` listener per running strand, beside the
881
- // observer's and the backfill's — see the backfill's NOTE below for when to fold
882
- // them into one dispatcher.
883
- if (config.strandPeerBook) {
884
- const swap = new StrandPeerBookSwap({
885
- strandId,
886
- libp2p: node,
887
- protocolPrefix,
888
- store: config.strandPeerBook,
889
- privateKey: config.privateKey,
890
- linkRoundTripMs: config.network?.linkRoundTripMs
891
- });
892
- this.peerBookSwaps.set(strandId, swap);
893
- swap.start();
894
- }
895
-
896
837
  // One reservation supervisor PER RELAY, started now so the first attempts
897
838
  // overlap the database bring-up below (the relay is never in a strand's
898
839
  // Optimystic cohort — its protocol ids are namespaced `/optimystic/strand-<id>/…`
@@ -1106,20 +1047,6 @@ export class StrandInstanceManager {
1106
1047
  backfill.stop();
1107
1048
  this.backfills.delete(instance.strandId);
1108
1049
  }
1109
- // The peer-book observer goes with the node it listened on; a resume re-arms
1110
- // one on the rebuilt node.
1111
- const peerObserver = this.peerObservers.get(instance.strandId);
1112
- if (peerObserver) {
1113
- peerObserver.stop();
1114
- this.peerObservers.delete(instance.strandId);
1115
- }
1116
- // The book swap likewise: unsubscribed and its handler unregistered while the node is
1117
- // still up; a resume re-arms one, which re-signs the own entry over the new addresses.
1118
- const peerBookSwap = this.peerBookSwaps.get(instance.strandId);
1119
- if (peerBookSwap) {
1120
- this.peerBookSwaps.delete(instance.strandId);
1121
- await peerBookSwap.stop();
1122
- }
1123
1050
  // The revoked-peer enforcer goes with the runtime it gated: a resume
1124
1051
  // rebuilds it with a fresh (initially empty, fail-open) snapshot.
1125
1052
  const revocationEnforcer = this.revocationEnforcers.get(instance.strandId);
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Node-only file-backed {@link StrandNetworkStateStore}: one JSON file per party
3
+ * under a configured directory (the node's state directory — `cadre-cli` passes
4
+ * `ResolvedConfig.nodeStateDir`), holding the node-local, non-replicated network
5
+ * state of every strand this node runs (each strand node's saved FRET routing
6
+ * table, with its peers' signed address records).
7
+ *
8
+ * Nothing but the file itself lives here: the envelope, load policy, per-entry
9
+ * check and the serialised snapshot writes are cross-platform in
10
+ * `PersistentStrandNetworkStateStore` / `node-local-snapshot.ts`, and the file is a
11
+ * `FileDurableSlot`. This module exists only so the `node:fs` edge stays out of the
12
+ * package's cross-platform default entry (`./index.js`) — import it from the
13
+ * dedicated subpath instead:
14
+ *
15
+ * ```ts
16
+ * import { FileStrandNetworkStateStore } from '@serfab/cadre-core/strand-network-state-file';
17
+ * ```
18
+ *
19
+ * Same isolation pattern as `bootstrap-peer-store-file.ts` / `key-store-file.ts`.
20
+ */
21
+ import { FileDurableSlot } from './file-durable-slot.js';
22
+ import { PersistentStrandNetworkStateStore } from './strand-network-state.js';
23
+ import type { StrandNetworkStateStore } from './strand-network-state.js';
24
+
25
+ /** Base name of the store file: `<dir>/strand-network.<encoded partyId>.json`. */
26
+ const SLOT_NAME = 'strand-network';
27
+
28
+ /**
29
+ * File-backed {@link StrandNetworkStateStore}. Open via {@link open}, which loads
30
+ * the existing file and returns the cross-platform store over it; an absent,
31
+ * corrupt, or wrong-party file is a cold start (no saved state) while a
32
+ * present-but-unreadable file throws. Those rules and their reasoning live on
33
+ * `NodeLocalSnapshot.open`.
34
+ */
35
+ export const FileStrandNetworkStateStore = {
36
+ /** Load (or cold-start) the party's strand network state from a file in `dir`. */
37
+ async open(dir: string, partyId: string): Promise<StrandNetworkStateStore> {
38
+ return PersistentStrandNetworkStateStore.open(new FileDurableSlot(dir, SLOT_NAME, partyId), partyId);
39
+ }
40
+ };