@serfab/cadre-core 1.8.0 → 1.9.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.
- package/dist/cadre-node.d.ts +153 -104
- package/dist/cadre-node.js +227 -199
- package/dist/cadre-node.js.map +1 -1
- package/dist/index.d.ts +2 -4
- package/dist/index.js +10 -11
- package/dist/index.js.map +1 -1
- package/dist/node-local-snapshot.d.ts +6 -4
- package/dist/node-local-snapshot.js +7 -3
- package/dist/node-local-snapshot.js.map +1 -1
- package/dist/peer-join-backfill.d.ts +0 -9
- package/dist/peer-join-backfill.js +2 -3
- package/dist/peer-join-backfill.js.map +1 -1
- package/dist/strand-formation-protocol.d.ts +0 -11
- package/dist/strand-formation-protocol.js +3 -4
- package/dist/strand-formation-protocol.js.map +1 -1
- package/dist/strand-fret-addrs.d.ts +54 -0
- package/dist/strand-fret-addrs.js +108 -0
- package/dist/strand-fret-addrs.js.map +1 -0
- package/dist/strand-instance-manager.d.ts +9 -38
- package/dist/strand-instance-manager.js +13 -73
- package/dist/strand-instance-manager.js.map +1 -1
- package/dist/strand-network-state-file.d.ts +12 -0
- package/dist/strand-network-state-file.js +38 -0
- package/dist/strand-network-state-file.js.map +1 -0
- package/dist/strand-network-state.d.ts +111 -0
- package/dist/strand-network-state.js +191 -0
- package/dist/strand-network-state.js.map +1 -0
- package/dist/types.d.ts +20 -23
- package/package.json +11 -10
- package/src/cadre-node.ts +238 -205
- package/src/index.ts +15 -55
- package/src/node-local-snapshot.ts +12 -7
- package/src/peer-join-backfill.ts +2 -3
- package/src/strand-formation-protocol.ts +3 -4
- package/src/strand-fret-addrs.ts +145 -0
- package/src/strand-instance-manager.ts +20 -96
- package/src/strand-network-state-file.ts +40 -0
- package/src/strand-network-state.ts +243 -0
- package/src/types.ts +20 -23
- package/dist/strand-peer-book-file.d.ts +0 -12
- package/dist/strand-peer-book-file.js +0 -37
- package/dist/strand-peer-book-file.js.map +0 -1
- package/dist/strand-peer-book-protocol.d.ts +0 -168
- package/dist/strand-peer-book-protocol.js +0 -356
- package/dist/strand-peer-book-protocol.js.map +0 -1
- package/dist/strand-peer-book-swap.d.ts +0 -104
- package/dist/strand-peer-book-swap.js +0 -284
- package/dist/strand-peer-book-swap.js.map +0 -1
- package/dist/strand-peer-book.d.ts +0 -159
- package/dist/strand-peer-book.js +0 -361
- package/dist/strand-peer-book.js.map +0 -1
- package/dist/strand-peer-observer.d.ts +0 -88
- package/dist/strand-peer-observer.js +0 -180
- package/dist/strand-peer-observer.js.map +0 -1
- package/src/strand-peer-book-file.ts +0 -39
- package/src/strand-peer-book-protocol.ts +0 -466
- package/src/strand-peer-book-swap.ts +0 -338
- package/src/strand-peer-book.ts +0 -475
- package/src/strand-peer-observer.ts +0 -235
package/src/strand-peer-book.ts
DELETED
|
@@ -1,475 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Node-local, NON-replicated **strand peer book**: for each strand this node runs,
|
|
3
|
-
* the strand peers it knows an address for — the other parties' strand transport
|
|
4
|
-
* peers, learned at formation and observed on every connection — with their
|
|
5
|
-
* last-known strand-network addresses and when this node last held a connection
|
|
6
|
-
* to them. Read on every launch, hibernation resume and periodic address refresh,
|
|
7
|
-
* so a machine that restarts dials the peers it was talking to BEFORE it does
|
|
8
|
-
* anything else, instead of coming back up alone.
|
|
9
|
-
*
|
|
10
|
-
* Why it exists (gotchoices/sereus#18): a cross-party strand learned the other
|
|
11
|
-
* party's strand addresses exactly once, at formation, into an in-memory map, and
|
|
12
|
-
* the strand-addr RPC answers own-party siblings only. After a restart neither
|
|
13
|
-
* relay-only party had any address for the other: the FRET ring and the Optimystic
|
|
14
|
-
* cohort each held only self, the strand reported `active`, local writes
|
|
15
|
-
* succeeded, nothing replicated.
|
|
16
|
-
*
|
|
17
|
-
* NOTE: interim, to be replaced (maintainer decision, 2026-09-28). FRET's
|
|
18
|
-
* `plan/10-feat-address-hints-in-neighbor-exchange` carries signed peer records in
|
|
19
|
-
* its neighbour exchange and its saved routing table. Once a FRET release with it
|
|
20
|
-
* reaches `@optimystic/db-p2p`, remove this book and the swap and pass db-p2p
|
|
21
|
-
* `persistence` for strand nodes instead; `blocked/retire-strand-peer-book-for-fret-address-hints`
|
|
22
|
-
* tracks that.
|
|
23
|
-
*
|
|
24
|
-
* NOTE: accepted design boundary (maintainer decision, 2026-09-27) — this is a
|
|
25
|
-
* per-machine record in the machine's own storage, NOT a registry inside the
|
|
26
|
-
* strand database. An in-strand registry (`Strand.MemberPeer` rows carrying
|
|
27
|
-
* addresses) would let a member reach peers it has never connected to while they
|
|
28
|
-
* are offline; nothing needs that today, and it is ruled out for now. Revisit only
|
|
29
|
-
* if a case needs addresses to reach members that are offline.
|
|
30
|
-
*
|
|
31
|
-
* Three implementations mirroring `bootstrap-peer-store.ts` (read that first —
|
|
32
|
-
* same "must outlive the process, storage differs per platform" problem, both
|
|
33
|
-
* persistent forms share `node-local-snapshot.ts`):
|
|
34
|
-
* - {@link MemoryStrandPeerBookStore} (this module, cross-platform) — ephemeral;
|
|
35
|
-
* the default when no store is injected via `CadreNodeConfig.strandPeers`. A
|
|
36
|
-
* node using it is exactly the pre-#18 shape after a restart.
|
|
37
|
-
* - {@link PersistentStrandPeerBookStore} (this module, cross-platform) — durable
|
|
38
|
-
* over any `DurableSlot` the embedding app supplies.
|
|
39
|
-
* - `FileStrandPeerBookStore` — the above over a Node file in the node's state
|
|
40
|
-
* directory; Node-only, behind the subpath
|
|
41
|
-
* `@serfab/cadre-core/strand-peer-book-file` (same isolation pattern as
|
|
42
|
-
* `bootstrap-peer-store-file`) so `node:fs` never lands in the RN/browser graph.
|
|
43
|
-
*
|
|
44
|
-
* One store per NODE holding every strand, rather than one slot per strand: the
|
|
45
|
-
* snapshot machinery writes one slot whole, and a node runs a handful of strands
|
|
46
|
-
* with at most {@link MAX_STRAND_PEERS} peers each — a few KB. The embedder
|
|
47
|
-
* therefore wires one slot, like the other node-local stores.
|
|
48
|
-
*
|
|
49
|
-
* **Nothing here is trust-bearing.** An address grants no authority: the dialed
|
|
50
|
-
* peer authenticates by peer id at the handshake, and every address is bound to
|
|
51
|
-
* the peer id it is filed under (see {@link StrandPeerEntry.addrs}), so a dial
|
|
52
|
-
* cannot be redirected to whoever answers. A junk address costs one failed dial per
|
|
53
|
-
* launch until it ages out or the peer's next connection replaces the entry. What a
|
|
54
|
-
* persistent backend's loader DOES owe is dropping structurally junk entries rather
|
|
55
|
-
* than carrying them into the dial loop.
|
|
56
|
-
*/
|
|
57
|
-
import debug from 'debug';
|
|
58
|
-
import { peerIdFromString } from '@libp2p/peer-id';
|
|
59
|
-
import { NodeLocalSnapshot, type DurableSlot, type NodeLocalSnapshotSpec } from './node-local-snapshot.js';
|
|
60
|
-
import { groupAddrsByPeerId } from './peer-addr-book.js';
|
|
61
|
-
import { orderSignalingFirst } from './peer-record.js';
|
|
62
|
-
import { MAX_STRAND_ADDRS } from './strand-formation-protocol.js';
|
|
63
|
-
|
|
64
|
-
const log = debug('sereus:cadre:strand-peer-book');
|
|
65
|
-
|
|
66
|
-
/**
|
|
67
|
-
* Cap on the peers remembered per strand. When full, the entry with the smallest
|
|
68
|
-
* `max(issuedAt, lastSeenAt)` is evicted. Sixteen is generous for the parties a
|
|
69
|
-
* strand has today (two, occasionally a few), and it bounds the worst case of a
|
|
70
|
-
* launch dialing dead entries: a failed relayed dial costs up to 16 s at the
|
|
71
|
-
* declared link, so the cap — with aging — is what keeps a stale book from
|
|
72
|
-
* stalling bring-up for minutes.
|
|
73
|
-
*/
|
|
74
|
-
export const MAX_STRAND_PEERS = 16;
|
|
75
|
-
|
|
76
|
-
/**
|
|
77
|
-
* Default age after which an entry nobody has refreshed is dropped: 14 days from
|
|
78
|
-
* `max(issuedAt, lastSeenAt)`. A live peer refreshes its entry on every connection,
|
|
79
|
-
* so only a peer this node has not reached in two weeks ages out. Overridable per
|
|
80
|
-
* store via {@link StrandPeerBookOptions.maxAgeMs}.
|
|
81
|
-
*/
|
|
82
|
-
export const STRAND_PEER_MAX_AGE_MS = 14 * 24 * 60 * 60 * 1000;
|
|
83
|
-
|
|
84
|
-
/**
|
|
85
|
-
* One strand peer this node knows an address for. `sig` is set only on an entry the
|
|
86
|
-
* peer signed itself and the book swap carried here (`strand-peer-book-protocol.ts`),
|
|
87
|
-
* or on this node's own entry, which the swap files under the node's own strand
|
|
88
|
-
* transport id; a formation-carried or observed entry is unsigned and local-only.
|
|
89
|
-
*/
|
|
90
|
-
export interface StrandPeerEntry {
|
|
91
|
-
/** The peer's STRAND transport peer id (never a control peer id). */
|
|
92
|
-
peerId: string;
|
|
93
|
-
/**
|
|
94
|
-
* Multiaddr strings, each bound to `peerId` (trailing `/p2p/<peerId>`, a relay
|
|
95
|
-
* hop only with that destination behind it), signaling-first, at most
|
|
96
|
-
* `MAX_STRAND_ADDRS`. Anything that does not attribute to `peerId` is dropped
|
|
97
|
-
* at merge.
|
|
98
|
-
*/
|
|
99
|
-
addrs: string[];
|
|
100
|
-
/**
|
|
101
|
-
* Signer's clock, ms: when the peer itself issued these addresses. 0 for an
|
|
102
|
-
* entry this node observed or was handed unsigned.
|
|
103
|
-
*/
|
|
104
|
-
issuedAt: number;
|
|
105
|
-
/**
|
|
106
|
-
* base64url Ed25519 signature by the peer's strand transport key over the canonical
|
|
107
|
-
* JSON of `{ v, strandId, peerId, addrs, issuedAt }` (`signedStrandPeerEntryPayload`);
|
|
108
|
-
* absent = local-only, never forwarded.
|
|
109
|
-
*/
|
|
110
|
-
sig?: string;
|
|
111
|
-
/**
|
|
112
|
-
* This node's clock, ms: when it last held a connection to the peer — or, for a
|
|
113
|
-
* formation-carried entry, when the responder disclosed the addresses live — and 0
|
|
114
|
-
* for an entry it has never connected to. Local, never on the wire.
|
|
115
|
-
*/
|
|
116
|
-
lastSeenAt: number;
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
export interface StrandPeerBookStore {
|
|
120
|
-
/** Party this store is scoped to. */
|
|
121
|
-
readonly partyId: string;
|
|
122
|
-
|
|
123
|
-
/**
|
|
124
|
-
* Snapshot of one strand's LIVE entries, freshest first
|
|
125
|
-
* (`max(issuedAt, lastSeenAt)` descending). Empty for an unknown strand. Aged-out
|
|
126
|
-
* entries are never returned. Every backend copies the entries per call, so the
|
|
127
|
-
* result is decoupled from later {@link merge} / {@link forget} calls.
|
|
128
|
-
*/
|
|
129
|
-
entries(strandId: string): StrandPeerEntry[];
|
|
130
|
-
|
|
131
|
-
/**
|
|
132
|
-
* Insert or replace by `(strandId, entry.peerId)` under the merge rule
|
|
133
|
-
* ({@link mergeStrandPeerEntry}): a signed entry never yields to an unsigned
|
|
134
|
-
* one; between two signed the greater `issuedAt` wins; between two unsigned the
|
|
135
|
-
* greater `lastSeenAt` wins; `lastSeenAt` is always the max of old and new. Then
|
|
136
|
-
* the strand's aged-out entries are dropped and, past {@link MAX_STRAND_PEERS},
|
|
137
|
-
* the stalest evicted.
|
|
138
|
-
*
|
|
139
|
-
* Implementations MUST reflect the merge in {@link entries} SYNCHRONOUSLY; the
|
|
140
|
-
* returned promise tracks durability only. An entry whose peer id does not parse
|
|
141
|
-
* is logged and dropped rather than thrown — every writer is a best-effort event
|
|
142
|
-
* handler.
|
|
143
|
-
*/
|
|
144
|
-
merge(strandId: string, entry: StrandPeerEntry): Promise<void>;
|
|
145
|
-
|
|
146
|
-
/**
|
|
147
|
-
* Drop one peer, or the whole strand when `peerId` is omitted — for a strand this
|
|
148
|
-
* node unpublished or left, whose peers must not stay dial targets. Forgetting
|
|
149
|
-
* something absent is a no-op. Same contract as {@link merge}: reflected
|
|
150
|
-
* synchronously, the promise tracks durability.
|
|
151
|
-
*/
|
|
152
|
-
forget(strandId: string, peerId?: string): Promise<void>;
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
/** Tuning shared by every backend. */
|
|
156
|
-
export interface StrandPeerBookOptions {
|
|
157
|
-
/** Age after which an unrefreshed entry is dropped. Default {@link STRAND_PEER_MAX_AGE_MS}. */
|
|
158
|
-
maxAgeMs?: number;
|
|
159
|
-
/** Clock, for tests. Default `Date.now`. */
|
|
160
|
-
now?: () => number;
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
/** One strand's peers, keyed by peer id — the unit the persistent envelope stores. */
|
|
164
|
-
type StrandPeers = Record<string, StrandPeerEntry>;
|
|
165
|
-
|
|
166
|
-
interface ResolvedOptions {
|
|
167
|
-
maxAgeMs: number;
|
|
168
|
-
now: () => number;
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
function resolveOptions(options?: StrandPeerBookOptions): ResolvedOptions {
|
|
172
|
-
return { maxAgeMs: options?.maxAgeMs ?? STRAND_PEER_MAX_AGE_MS, now: options?.now ?? Date.now };
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
/** The moment an entry was last vouched for, by whichever clock spoke last. */
|
|
176
|
-
export function strandPeerFreshness(entry: StrandPeerEntry): number {
|
|
177
|
-
return Math.max(entry.issuedAt, entry.lastSeenAt);
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
/**
|
|
181
|
-
* The merge rule, in one place. Returns the entry to hold for `incoming.peerId`
|
|
182
|
-
* given what is already held — always a NEW object, so a held entry is never mutated
|
|
183
|
-
* in place (the persistent backend's snapshot `put` replaces rather than patches).
|
|
184
|
-
* `incoming` is assumed sanitized ({@link sanitizeStrandPeerEntry}).
|
|
185
|
-
*
|
|
186
|
-
* - A signed entry never yields to an unsigned one for the same peer: the peer's own
|
|
187
|
-
* statement outranks this node's observation of it.
|
|
188
|
-
* - Between two signed entries the greater `issuedAt` wins; between two unsigned
|
|
189
|
-
* entries the greater `lastSeenAt` wins. A tie goes to `incoming`.
|
|
190
|
-
* - `lastSeenAt` is always the max of old and new whichever entry wins, because it
|
|
191
|
-
* is this node's own observation and no remote statement can lower it.
|
|
192
|
-
*/
|
|
193
|
-
export function mergeStrandPeerEntry(
|
|
194
|
-
existing: StrandPeerEntry | undefined,
|
|
195
|
-
incoming: StrandPeerEntry
|
|
196
|
-
): StrandPeerEntry {
|
|
197
|
-
const winner = existing === undefined || incomingWins(existing, incoming) ? incoming : existing;
|
|
198
|
-
return {
|
|
199
|
-
...winner,
|
|
200
|
-
addrs: [...winner.addrs],
|
|
201
|
-
lastSeenAt: Math.max(existing?.lastSeenAt ?? 0, incoming.lastSeenAt)
|
|
202
|
-
};
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
function incomingWins(existing: StrandPeerEntry, incoming: StrandPeerEntry): boolean {
|
|
206
|
-
if (existing.sig !== undefined && incoming.sig === undefined) return false;
|
|
207
|
-
if (existing.sig === undefined && incoming.sig !== undefined) return true;
|
|
208
|
-
return existing.sig !== undefined
|
|
209
|
-
? incoming.issuedAt >= existing.issuedAt
|
|
210
|
-
: incoming.lastSeenAt >= existing.lastSeenAt;
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
/**
|
|
214
|
-
* Shape an entry for storage: the peer id must parse (else `undefined` — not a dial
|
|
215
|
-
* target at all), and `addrs` is reduced to the entries that attribute to `peerId`
|
|
216
|
-
* under `groupAddrsByPeerId`'s rule, de-duplicated, capped at `MAX_STRAND_ADDRS`, and
|
|
217
|
-
* — for an UNSIGNED entry only — reordered signaling-first. A signed entry keeps the
|
|
218
|
-
* signer's order: its signature covers the address list as signed, and the swap
|
|
219
|
-
* forwards the stored copy, so any reordering here would make every forwarded entry
|
|
220
|
-
* fail verification at the next peer (every signer already orders signaling-first). An
|
|
221
|
-
* entry may legitimately end up with NO addresses — a signed "not reachable right
|
|
222
|
-
* now" from the swap protocol is truthful and displaces a stale reachable list — so
|
|
223
|
-
* an empty list is kept, not rejected.
|
|
224
|
-
*/
|
|
225
|
-
export function sanitizeStrandPeerEntry(entry: StrandPeerEntry): StrandPeerEntry | undefined {
|
|
226
|
-
try {
|
|
227
|
-
peerIdFromString(entry.peerId);
|
|
228
|
-
} catch (error) {
|
|
229
|
-
log('dropping entry for unparsable peer id %s: %o', entry.peerId, error);
|
|
230
|
-
return undefined;
|
|
231
|
-
}
|
|
232
|
-
const attributed = (groupAddrsByPeerId([...entry.addrs]).get(entry.peerId) ?? []).map((ma) => ma.toString());
|
|
233
|
-
const addrs = (entry.sig === undefined ? orderSignalingFirst(attributed) : attributed).slice(0, MAX_STRAND_ADDRS);
|
|
234
|
-
if (addrs.length < entry.addrs.length) {
|
|
235
|
-
log('peer %s: kept %d of %d addr(s) — the rest do not attribute to it or exceed the cap',
|
|
236
|
-
entry.peerId, addrs.length, entry.addrs.length);
|
|
237
|
-
}
|
|
238
|
-
return {
|
|
239
|
-
peerId: entry.peerId,
|
|
240
|
-
addrs,
|
|
241
|
-
issuedAt: entry.issuedAt,
|
|
242
|
-
...(entry.sig !== undefined && { sig: entry.sig }),
|
|
243
|
-
lastSeenAt: entry.lastSeenAt
|
|
244
|
-
};
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
/**
|
|
248
|
-
* Apply {@link mergeStrandPeerEntry} to one strand's map and re-bound it: aged-out
|
|
249
|
-
* entries dropped, then the stalest evicted past {@link MAX_STRAND_PEERS}. Returns a
|
|
250
|
-
* NEW map (the persistent backend's snapshot `put` replaces rather than mutates),
|
|
251
|
-
* or `undefined` when the incoming entry was unusable and nothing changed.
|
|
252
|
-
*
|
|
253
|
-
* NOTE: aging is time-based only. The book cannot see dial outcomes (dials happen
|
|
254
|
-
* inside libp2p and Optimystic), so a dead entry is re-dialed on every launch and
|
|
255
|
-
* refresh until it ages out or the peer's next connection replaces it — bounded by
|
|
256
|
-
* the peer cap and the 14-day age. If a case ever shows a dead entry re-dialed every
|
|
257
|
-
* tick for two weeks, the lever is observing `connection:close` / dial failures
|
|
258
|
-
* here, not a shorter age.
|
|
259
|
-
*/
|
|
260
|
-
function mergeIntoStrand(
|
|
261
|
-
strand: StrandPeers | undefined,
|
|
262
|
-
incoming: StrandPeerEntry,
|
|
263
|
-
options: ResolvedOptions
|
|
264
|
-
): StrandPeers | undefined {
|
|
265
|
-
const entry = sanitizeStrandPeerEntry(incoming);
|
|
266
|
-
if (!entry) return undefined;
|
|
267
|
-
const merged = mergeStrandPeerEntry(strand?.[entry.peerId], entry);
|
|
268
|
-
// Pruned AFTER the insert, so an incoming entry that is already past the age
|
|
269
|
-
// (a swap forwarding a months-old statement) never lands at all.
|
|
270
|
-
return evictPastCap(pruneAged({ ...strand, [entry.peerId]: merged }, options));
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
/**
|
|
274
|
-
* The strand's map without the entries older than `maxAgeMs` (a new object only when
|
|
275
|
-
* something dropped).
|
|
276
|
-
*
|
|
277
|
-
* Nothing is exempt, the node's OWN entry included: the book swap
|
|
278
|
-
* (`strand-peer-book-swap.ts`) keeps the entry it SENDS in memory and re-signs it on
|
|
279
|
-
* every address change and every launch, so the stored copy is a record for
|
|
280
|
-
* diagnostics and the seed's self-skip, and losing it to age costs nothing. That is
|
|
281
|
-
* why the store need not tell self from a peer.
|
|
282
|
-
*/
|
|
283
|
-
function pruneAged(strand: StrandPeers, options: ResolvedOptions): StrandPeers {
|
|
284
|
-
const cutoff = options.now() - options.maxAgeMs;
|
|
285
|
-
const live = Object.values(strand).filter((entry) => strandPeerFreshness(entry) >= cutoff);
|
|
286
|
-
return live.length === Object.keys(strand).length ? strand : Object.fromEntries(live.map((e) => [e.peerId, e]));
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
/**
|
|
290
|
-
* Drop the stalest entries until the strand holds at most {@link MAX_STRAND_PEERS}.
|
|
291
|
-
*
|
|
292
|
-
* NOTE: freshness ranks a forwarded statement (signer's `issuedAt`, up to five minutes
|
|
293
|
-
* ahead of this clock) above a peer this node has itself connected to, so one swap
|
|
294
|
-
* frame of sixteen fresh self-signed entries evicts every met peer — see
|
|
295
|
-
* `backlog/debt-strand-peer-book-remote-write-bounds`.
|
|
296
|
-
*/
|
|
297
|
-
function evictPastCap(strand: StrandPeers): StrandPeers {
|
|
298
|
-
const entries = Object.values(strand);
|
|
299
|
-
if (entries.length <= MAX_STRAND_PEERS) return strand;
|
|
300
|
-
const kept = sortFreshestFirst(entries).slice(0, MAX_STRAND_PEERS);
|
|
301
|
-
log('evicting %d stalest peer(s) past the %d-peer cap', entries.length - kept.length, MAX_STRAND_PEERS);
|
|
302
|
-
return Object.fromEntries(kept.map((e) => [e.peerId, e]));
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
function sortFreshestFirst(entries: StrandPeerEntry[]): StrandPeerEntry[] {
|
|
306
|
-
return [...entries].sort((a, b) => strandPeerFreshness(b) - strandPeerFreshness(a));
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
/** The live entries of one strand, freshest first, copied. */
|
|
310
|
-
function liveEntries(strand: StrandPeers | undefined, options: ResolvedOptions): StrandPeerEntry[] {
|
|
311
|
-
if (!strand) return [];
|
|
312
|
-
return sortFreshestFirst(Object.values(pruneAged(strand, options)))
|
|
313
|
-
.map((entry) => ({ ...entry, addrs: [...entry.addrs] }));
|
|
314
|
-
}
|
|
315
|
-
|
|
316
|
-
/** The strand's map without `peerId`, or `undefined` when that leaves nothing (or nothing was there). */
|
|
317
|
-
function withoutPeer(strand: StrandPeers | undefined, peerId: string): StrandPeers | undefined {
|
|
318
|
-
if (!strand || !(peerId in strand)) return strand;
|
|
319
|
-
const { [peerId]: _dropped, ...rest } = strand;
|
|
320
|
-
return Object.keys(rest).length === 0 ? undefined : rest;
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
/**
|
|
324
|
-
* Ephemeral in-memory book for nodes without durable storage (tests, and the
|
|
325
|
-
* default when nothing is injected). Same contract, no disk: a node using this
|
|
326
|
-
* forgets every strand peer on restart — the #18 shape.
|
|
327
|
-
*/
|
|
328
|
-
export class MemoryStrandPeerBookStore implements StrandPeerBookStore {
|
|
329
|
-
private readonly strands = new Map<string, StrandPeers>();
|
|
330
|
-
private readonly options: ResolvedOptions;
|
|
331
|
-
|
|
332
|
-
constructor(readonly partyId: string, options?: StrandPeerBookOptions) {
|
|
333
|
-
this.options = resolveOptions(options);
|
|
334
|
-
}
|
|
335
|
-
|
|
336
|
-
entries(strandId: string): StrandPeerEntry[] {
|
|
337
|
-
return liveEntries(this.strands.get(strandId), this.options);
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
async merge(strandId: string, entry: StrandPeerEntry): Promise<void> {
|
|
341
|
-
const next = mergeIntoStrand(this.strands.get(strandId), entry, this.options);
|
|
342
|
-
if (next) {
|
|
343
|
-
this.strands.set(strandId, next);
|
|
344
|
-
log('strand %s: peer %s merged (party=%s, addrs=%d)', strandId, entry.peerId, this.partyId, entry.addrs.length);
|
|
345
|
-
}
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
async forget(strandId: string, peerId?: string): Promise<void> {
|
|
349
|
-
if (peerId === undefined) {
|
|
350
|
-
if (this.strands.delete(strandId)) {
|
|
351
|
-
log('strand %s: book forgotten (party=%s)', strandId, this.partyId);
|
|
352
|
-
}
|
|
353
|
-
return;
|
|
354
|
-
}
|
|
355
|
-
const next = withoutPeer(this.strands.get(strandId), peerId);
|
|
356
|
-
if (next === undefined) {
|
|
357
|
-
this.strands.delete(strandId);
|
|
358
|
-
} else {
|
|
359
|
-
this.strands.set(strandId, next);
|
|
360
|
-
}
|
|
361
|
-
}
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
/**
|
|
365
|
-
* What the store persists: `strands` maps strandId -> (peerId -> {@link StrandPeerEntry}).
|
|
366
|
-
*
|
|
367
|
-
* A structurally junk PEER entry is dropped and its siblings retained; a strand
|
|
368
|
-
* whose value is not a record, or that holds no usable peer, is dropped as a whole
|
|
369
|
-
* (`drop-entry`) — nothing here is trust-bearing (see the module comment) and the
|
|
370
|
-
* book is a restarted node's only way back to the other parties, so discarding the
|
|
371
|
-
* whole set over one bad entry would be strictly worse. What "junk" means: a peer id
|
|
372
|
-
* that does not parse, a non-array or non-string address list, a non-number
|
|
373
|
-
* `issuedAt` / `lastSeenAt`, or a non-string `sig`. Aged-out entries are dropped at
|
|
374
|
-
* load too, so a slot last written months ago yields nothing to dial.
|
|
375
|
-
*/
|
|
376
|
-
function strandPeerBookSnapshotSpec(options: ResolvedOptions): NodeLocalSnapshotSpec<StrandPeers> {
|
|
377
|
-
return {
|
|
378
|
-
label: 'strand peer book',
|
|
379
|
-
payloadKey: 'strands',
|
|
380
|
-
unusableEntry: 'drop-entry',
|
|
381
|
-
acceptEntry: (strandId, raw) => {
|
|
382
|
-
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return undefined;
|
|
383
|
-
let strand: StrandPeers = {};
|
|
384
|
-
for (const [peerId, value] of Object.entries(raw as Record<string, unknown>)) {
|
|
385
|
-
const entry = acceptPeerEntry(peerId, value);
|
|
386
|
-
if (!entry) {
|
|
387
|
-
log('strand %s: dropping unusable persisted entry for %s', strandId, peerId);
|
|
388
|
-
continue;
|
|
389
|
-
}
|
|
390
|
-
strand[peerId] = entry;
|
|
391
|
-
}
|
|
392
|
-
strand = pruneAged(strand, options);
|
|
393
|
-
return Object.keys(strand).length === 0 ? undefined : strand;
|
|
394
|
-
}
|
|
395
|
-
};
|
|
396
|
-
}
|
|
397
|
-
|
|
398
|
-
function acceptPeerEntry(peerId: string, value: unknown): StrandPeerEntry | undefined {
|
|
399
|
-
if (typeof value !== 'object' || value === null) return undefined;
|
|
400
|
-
const { addrs, issuedAt, sig, lastSeenAt } = value as Record<string, unknown>;
|
|
401
|
-
if (!Array.isArray(addrs) || addrs.some((addr) => typeof addr !== 'string' || addr.length === 0)) return undefined;
|
|
402
|
-
if (typeof issuedAt !== 'number' || typeof lastSeenAt !== 'number') return undefined;
|
|
403
|
-
if (sig !== undefined && typeof sig !== 'string') return undefined;
|
|
404
|
-
return sanitizeStrandPeerEntry({
|
|
405
|
-
peerId,
|
|
406
|
-
addrs: addrs as string[],
|
|
407
|
-
issuedAt,
|
|
408
|
-
...(sig !== undefined && { sig }),
|
|
409
|
-
lastSeenAt
|
|
410
|
-
});
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
/**
|
|
414
|
-
* Durable {@link StrandPeerBookStore} over an app-supplied {@link DurableSlot} —
|
|
415
|
-
* the cross-platform half of every persistent backend (the Node
|
|
416
|
-
* `FileStrandPeerBookStore` is this class over a file slot).
|
|
417
|
-
*
|
|
418
|
-
* Construct via {@link open}. Load and persist policy — what an absent, corrupt,
|
|
419
|
-
* foreign-party or unreadable slot does (the last one THROWS, as
|
|
420
|
-
* `PersistentBootstrapPeerStore.open` does), and what a failed persist does — is
|
|
421
|
-
* documented once on `NodeLocalSnapshot`; this class only supplies the payload shape
|
|
422
|
-
* and the drop-the-bad-entry policy above. Writes are serialised in-process by the
|
|
423
|
-
* snapshot's write chain, so several strands' identify handlers merging at once
|
|
424
|
-
* cannot interleave partial snapshots.
|
|
425
|
-
*/
|
|
426
|
-
export class PersistentStrandPeerBookStore implements StrandPeerBookStore {
|
|
427
|
-
private constructor(
|
|
428
|
-
private readonly snapshot: NodeLocalSnapshot<StrandPeers>,
|
|
429
|
-
private readonly options: ResolvedOptions
|
|
430
|
-
) {}
|
|
431
|
-
|
|
432
|
-
/** Load (or cold-start) the party's book from `slot`. */
|
|
433
|
-
static async open(
|
|
434
|
-
slot: DurableSlot,
|
|
435
|
-
partyId: string,
|
|
436
|
-
options?: StrandPeerBookOptions
|
|
437
|
-
): Promise<PersistentStrandPeerBookStore> {
|
|
438
|
-
const resolved = resolveOptions(options);
|
|
439
|
-
return new PersistentStrandPeerBookStore(
|
|
440
|
-
await NodeLocalSnapshot.open(slot, partyId, strandPeerBookSnapshotSpec(resolved)),
|
|
441
|
-
resolved
|
|
442
|
-
);
|
|
443
|
-
}
|
|
444
|
-
|
|
445
|
-
get partyId(): string {
|
|
446
|
-
return this.snapshot.partyId;
|
|
447
|
-
}
|
|
448
|
-
|
|
449
|
-
entries(strandId: string): StrandPeerEntry[] {
|
|
450
|
-
return liveEntries(this.snapshot.entrySnapshot().get(strandId), this.options);
|
|
451
|
-
}
|
|
452
|
-
|
|
453
|
-
/** Merge, visible via {@link entries} synchronously, then the full snapshot is persisted. */
|
|
454
|
-
merge(strandId: string, entry: StrandPeerEntry): Promise<void> {
|
|
455
|
-
const next = mergeIntoStrand(this.snapshot.entrySnapshot().get(strandId), entry, this.options);
|
|
456
|
-
if (!next) return Promise.resolve();
|
|
457
|
-
log('strand %s: peer %s merged (party=%s, addrs=%d); persisting',
|
|
458
|
-
strandId, entry.peerId, this.partyId, entry.addrs.length);
|
|
459
|
-
return this.snapshot.put(strandId, next);
|
|
460
|
-
}
|
|
461
|
-
|
|
462
|
-
/** Forget, gone from {@link entries} synchronously, then persisted — unless nothing was there. */
|
|
463
|
-
forget(strandId: string, peerId?: string): Promise<void> {
|
|
464
|
-
if (peerId === undefined) {
|
|
465
|
-
if (this.snapshot.has(strandId)) {
|
|
466
|
-
log('strand %s: book forgotten (party=%s); persisting', strandId, this.partyId);
|
|
467
|
-
}
|
|
468
|
-
return this.snapshot.remove(strandId);
|
|
469
|
-
}
|
|
470
|
-
const current = this.snapshot.entrySnapshot().get(strandId);
|
|
471
|
-
const next = withoutPeer(current, peerId);
|
|
472
|
-
if (next === current) return Promise.resolve();
|
|
473
|
-
return next === undefined ? this.snapshot.remove(strandId) : this.snapshot.put(strandId, next);
|
|
474
|
-
}
|
|
475
|
-
}
|