@serfab/cadre-core 1.6.0 → 1.7.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 (51) hide show
  1. package/dist/cadre-node.d.ts +204 -65
  2. package/dist/cadre-node.js +392 -95
  3. package/dist/cadre-node.js.map +1 -1
  4. package/dist/index.d.ts +5 -0
  5. package/dist/index.js +16 -0
  6. package/dist/index.js.map +1 -1
  7. package/dist/joined-strand-store.d.ts +112 -0
  8. package/dist/joined-strand-store.js +263 -0
  9. package/dist/joined-strand-store.js.map +1 -0
  10. package/dist/key-store.d.ts +6 -0
  11. package/dist/key-store.js.map +1 -1
  12. package/dist/node-local-snapshot.d.ts +5 -4
  13. package/dist/node-local-snapshot.js +6 -3
  14. package/dist/node-local-snapshot.js.map +1 -1
  15. package/dist/peer-join-backfill.d.ts +33 -14
  16. package/dist/peer-join-backfill.js +109 -50
  17. package/dist/peer-join-backfill.js.map +1 -1
  18. package/dist/strand-instance-manager.d.ts +39 -0
  19. package/dist/strand-instance-manager.js +74 -1
  20. package/dist/strand-instance-manager.js.map +1 -1
  21. package/dist/strand-peer-book-file.d.ts +12 -0
  22. package/dist/strand-peer-book-file.js +37 -0
  23. package/dist/strand-peer-book-file.js.map +1 -0
  24. package/dist/strand-peer-book-protocol.d.ts +159 -0
  25. package/dist/strand-peer-book-protocol.js +360 -0
  26. package/dist/strand-peer-book-protocol.js.map +1 -0
  27. package/dist/strand-peer-book-swap.d.ts +104 -0
  28. package/dist/strand-peer-book-swap.js +284 -0
  29. package/dist/strand-peer-book-swap.js.map +1 -0
  30. package/dist/strand-peer-book.d.ts +159 -0
  31. package/dist/strand-peer-book.js +354 -0
  32. package/dist/strand-peer-book.js.map +1 -0
  33. package/dist/strand-peer-observer.d.ts +88 -0
  34. package/dist/strand-peer-observer.js +180 -0
  35. package/dist/strand-peer-observer.js.map +1 -0
  36. package/dist/types.d.ts +58 -0
  37. package/dist/types.js.map +1 -1
  38. package/package.json +6 -2
  39. package/src/cadre-node.ts +7776 -7449
  40. package/src/index.ts +67 -0
  41. package/src/joined-strand-store.ts +308 -0
  42. package/src/key-store.ts +6 -0
  43. package/src/node-local-snapshot.ts +293 -289
  44. package/src/peer-join-backfill.ts +112 -51
  45. package/src/strand-instance-manager.ts +100 -1
  46. package/src/strand-peer-book-file.ts +39 -0
  47. package/src/strand-peer-book-protocol.ts +463 -0
  48. package/src/strand-peer-book-swap.ts +338 -0
  49. package/src/strand-peer-book.ts +468 -0
  50. package/src/strand-peer-observer.ts +235 -0
  51. package/src/types.ts +60 -0
@@ -1,289 +1,293 @@
1
- /**
2
- * Shared machinery for the node's **node-local** records — the small,
3
- * NEVER-replicated, per-party sets a node keeps for itself and never sources
4
- * from shared group state:
5
- *
6
- * - the trusted-owner anchor (`trusted-owner-store.ts`),
7
- * - the cold-start bootstrap-peer store (`bootstrap-peer-store.ts`).
8
- *
9
- * A THIRD node-local record — the enrolled-machine count
10
- * (`enrolled-machine-store.ts`) — reuses {@link DurableSlot} but deliberately
11
- * NOT this module's snapshot machinery: it is one scalar rather than an entry
12
- * map, and it must cold-start rather than throw on an unreadable slot. Its
13
- * module comment carries the reasoning; do not fold it in here.
14
- *
15
- * Both records here are the same mechanism with a different payload: a
16
- * `{ version, partyId, <entries> }` envelope, snapshot-written whole on every
17
- * change, loaded under one fail-safe-but-not-fail-silent policy. The only part
18
- * that differs per platform is WHERE the bytes are kept — Node writes a file,
19
- * a browser writes IndexedDB, React Native writes SecureStore or its LevelDB
20
- * KV, NativeScript writes SQLite. That difference is the whole of
21
- * {@link DurableSlot}, which the embedding app supplies; everything else lives
22
- * here.
23
- *
24
- * This module is cross-platform (no `node:` imports), so it is safe in the
25
- * package's default entry — the Node-only `FileDurableSlot`
26
- * (`file-durable-slot.ts`) is what stays behind the `*-store-file` subpaths.
27
- */
28
- import debug from 'debug';
29
-
30
- const log = debug('sereus:cadre:node-local-snapshot');
31
-
32
- /**
33
- * A single durable text slot, supplied by the embedding app. The only
34
- * platform-specific part of a persistent node-local store.
35
- */
36
- export interface DurableSlot {
37
- /**
38
- * The slot's persisted text, or `undefined` when it was never written.
39
- *
40
- * MUST throw (not return `undefined`) when the slot exists but cannot be
41
- * read. That distinction is load-bearing: `undefined` means "cold start,
42
- * nothing was ever here", and callers snapshot-write the whole record, so a
43
- * failed read reported as `undefined` silently converts a recoverable error
44
- * (permissions, a blocked database upgrade, an I/O fault) into destruction
45
- * of a still-intact record on the next save.
46
- *
47
- * A slot always reports the fault; what a READER does with it is the
48
- * reader's policy. The two records here rethrow it; the enrolled-machine
49
- * count catches it and cold-starts, because losing a repair hint must not
50
- * stop a node. So an implementation must never soften this to `undefined`
51
- * on a reader's behalf.
52
- */
53
- load(): Promise<string | undefined>;
54
- /**
55
- * Durably replace the slot's text. Callers snapshot-write the whole record,
56
- * so an implementation never needs to merge.
57
- */
58
- save(text: string): Promise<void>;
59
- }
60
-
61
- /** Envelope version. Guards future migrations; an unknown version loads empty. */
62
- const ENVELOPE_VERSION = 1;
63
-
64
- /**
65
- * What one unusable entry means for its siblings — the single intentional
66
- * difference between the two records:
67
- *
68
- * - `'discard-all'` (the trusted-owner anchor): a record that cannot be read
69
- * in full is not an anchor. Trusting a *subset* of the keys a file claims is
70
- * a silent, security-relevant downgrade, so the whole record is discarded
71
- * and the node trusts no one until re-seeded out of band.
72
- * - `'drop-entry'` (the bootstrap-peer store): the record is a best-effort
73
- * retry list and nothing in it is trust-bearing, so one junk entry must not
74
- * discard a stranded node's only remaining way back into its party.
75
- */
76
- export type UnusableEntryPolicy = 'discard-all' | 'drop-entry';
77
-
78
- /** What a particular node-local record persists, and how it validates it. */
79
- export interface NodeLocalSnapshotSpec<E> {
80
- /** Human name of the record, used in load errors and logs. */
81
- readonly label: string;
82
- /** Envelope property holding the `key -> entry` record (`owners`, `peers`). */
83
- readonly payloadKey: string;
84
- /** See {@link UnusableEntryPolicy}. */
85
- readonly unusableEntry: UnusableEntryPolicy;
86
- /**
87
- * Validate one persisted entry, returning the value to hold in memory
88
- * (copied, so later mutation of the parsed JSON cannot reach it) or
89
- * `undefined` when the entry is unusable.
90
- */
91
- readonly acceptEntry: (key: string, entry: unknown) => E | undefined;
92
- }
93
-
94
- /**
95
- * A loaded node-local record over a {@link DurableSlot}: an in-memory
96
- * `key -> entry` map plus a serialised full-snapshot write chain.
97
- *
98
- * NOTE: writes are serialised in-process only. Two processes (or two browser
99
- * tabs) sharing ONE slot for ONE party would each snapshot-write their own
100
- * view, so the loser's entries are dropped. Fine for every backend today —
101
- * each node gets its own directory / origin database — but a single slot
102
- * backing two concurrent nodes of one party needs a lock or a merge-on-write,
103
- * not a snapshot replace.
104
- */
105
- export class NodeLocalSnapshot<E> {
106
- /**
107
- * Serialises persists: every write ({@link put}, {@link remove}) snapshot-writes
108
- * the full entry set, so chaining writes keeps them ordered and the last landed
109
- * snapshot complete.
110
- */
111
- private writeChain: Promise<void> = Promise.resolve();
112
-
113
- private constructor(
114
- private readonly slot: DurableSlot,
115
- readonly partyId: string,
116
- private readonly spec: NodeLocalSnapshotSpec<E>,
117
- private readonly entries: Map<string, E>
118
- ) {}
119
-
120
- /**
121
- * Load (or cold-start) the party's record from `slot`. Failure policy, per
122
- * the trust model of the anchor this was first written for: only a real,
123
- * well-formed, matching-party record yields entries.
124
- *
125
- * A *decidable* non-record — slot never written, unparsable JSON, unknown
126
- * envelope shape, `partyId` mismatch (a slot reused for a different party
127
- * must not leak into this one) — yields an EMPTY record, the safe direction:
128
- * the node holds nothing until it is re-seeded, rather than acting on stale
129
- * or foreign state.
130
- *
131
- * A slot that is *present but unreadable* ({@link DurableSlot.load} threw)
132
- * is NOT decidable and **throws** instead — mirroring `FileKeyStore.get`.
133
- * Loading empty there would both hide a real misconfiguration and let the
134
- * next {@link put} snapshot-write silently destroy a still-intact record.
135
- */
136
- static async open<E>(
137
- slot: DurableSlot,
138
- partyId: string,
139
- spec: NodeLocalSnapshotSpec<E>
140
- ): Promise<NodeLocalSnapshot<E>> {
141
- return new NodeLocalSnapshot(slot, partyId, spec, await loadEntries(slot, partyId, spec));
142
- }
143
-
144
- has(key: string): boolean {
145
- return this.entries.has(key);
146
- }
147
-
148
- /** Fresh copy of the keys — a snapshot decoupled from later {@link put} / {@link remove} calls. */
149
- keySnapshot(): Set<string> {
150
- return new Set(this.entries.keys());
151
- }
152
-
153
- /**
154
- * Fresh copy of the `key -> entry` map — a snapshot decoupled from later
155
- * {@link put} / {@link remove} calls. The entries themselves need no copy:
156
- * {@link put} REPLACES an entry rather than mutating it in place.
157
- */
158
- entrySnapshot(): Map<string, E> {
159
- return new Map(this.entries);
160
- }
161
-
162
- /**
163
- * Add or replace an entry: the in-memory map updates SYNCHRONOUSLY (so a
164
- * synchronous caller may consult the store the moment this returns), then
165
- * the full snapshot is persisted. A persist failure rejects the returned
166
- * promise but leaves the entry in memory — this session's decision stands,
167
- * and any later successful write re-lands the complete set.
168
- */
169
- put(key: string, entry: E): Promise<void> {
170
- this.entries.set(key, entry);
171
- return this.queuePersist();
172
- }
173
-
174
- /**
175
- * Remove an entry, with {@link put}'s contract: the in-memory map updates
176
- * SYNCHRONOUSLY, then the full snapshot is persisted. Removing an absent key
177
- * changes nothing, so it writes nothing.
178
- */
179
- remove(key: string): Promise<void> {
180
- if (!this.entries.delete(key)) {
181
- return Promise.resolve();
182
- }
183
- return this.queuePersist();
184
- }
185
-
186
- /** Chain a full-snapshot write behind every earlier one (see {@link put}). */
187
- private queuePersist(): Promise<void> {
188
- const persist = this.writeChain.then(() => this.persistSnapshot());
189
- // The chain itself must survive a failed persist (the next write retries the
190
- // full snapshot); the caller still observes the rejection via `persist`.
191
- this.writeChain = persist.catch((error) => {
192
- log('%s: persist failed for party %s: %o', this.spec.label, this.partyId, error);
193
- });
194
- return persist;
195
- }
196
-
197
- private async persistSnapshot(): Promise<void> {
198
- const envelope: Record<string, unknown> = {
199
- version: ENVELOPE_VERSION,
200
- partyId: this.partyId,
201
- [this.spec.payloadKey]: Object.fromEntries(this.entries),
202
- };
203
- await this.slot.save(JSON.stringify(envelope, null, '\t'));
204
- }
205
- }
206
-
207
- /** Read + validate the slot's text into the initial entry map (see {@link NodeLocalSnapshot.open}). */
208
- async function loadEntries<E>(
209
- slot: DurableSlot,
210
- partyId: string,
211
- spec: NodeLocalSnapshotSpec<E>
212
- ): Promise<Map<string, E>> {
213
- const entries = new Map<string, E>();
214
- let text: string | undefined;
215
- try {
216
- text = await slot.load();
217
- } catch (error) {
218
- // Present but unreadable: the one non-decidable case, and the one that must
219
- // not cold-start empty (see NodeLocalSnapshot.open). The slot's own text is
220
- // folded into the message, not left only on `cause`: the operator-facing
221
- // print sites (e.g. `cadre-cli start`) log `error.message` alone, and the
222
- // slot is what knows the platform detail worth acting on (which file, which
223
- // database).
224
- throw new Error(
225
- `failed to read the ${spec.label} for party ${partyId}: ${error instanceof Error ? error.message : String(error)}`,
226
- { cause: error }
227
- );
228
- }
229
- if (text === undefined) return entries;
230
-
231
- let parsed: unknown;
232
- try {
233
- parsed = JSON.parse(text);
234
- } catch (error) {
235
- log('%s: corrupt slot for party %s (cold start): %o', spec.label, partyId, error);
236
- return entries;
237
- }
238
-
239
- const payload = envelopePayload(parsed, partyId, spec.payloadKey);
240
- if (!payload) {
241
- log('%s: slot for party %s has an unknown shape or a foreign partyId (cold start)', spec.label, partyId);
242
- return entries;
243
- }
244
-
245
- for (const [key, raw] of Object.entries(payload)) {
246
- const entry = spec.acceptEntry(key, raw);
247
- if (entry === undefined) {
248
- if (spec.unusableEntry === 'discard-all') {
249
- log('%s: unusable entry for %s discards the whole record (party %s, cold start)', spec.label, key, partyId);
250
- return new Map();
251
- }
252
- log('%s: dropping unusable entry for %s (party %s)', spec.label, key, partyId);
253
- continue;
254
- }
255
- entries.set(key, entry);
256
- }
257
- log('%s: loaded %d entr(ies) for party %s', spec.label, entries.size, partyId);
258
- return entries;
259
- }
260
-
261
- /**
262
- * The envelope's `key -> entry` record, or undefined on any envelope mismatch —
263
- * wrong version, wrong (or absent) `partyId`, missing or non-record payload.
264
- * Individual entries are judged separately by
265
- * {@link NodeLocalSnapshotSpec.acceptEntry}, because one bad entry does not
266
- * always mean a bad record.
267
- */
268
- function envelopePayload(
269
- value: unknown,
270
- partyId: string,
271
- payloadKey: string
272
- ): Record<string, unknown> | undefined {
273
- if (!isRecord(value)) return undefined;
274
- // A non-string partyId cannot equal the requested one, so this covers both
275
- // "malformed partyId" and "another party's record".
276
- if (value.version !== ENVELOPE_VERSION || value.partyId !== partyId) return undefined;
277
- const payload = value[payloadKey];
278
- return isRecord(payload) ? payload : undefined;
279
- }
280
-
281
- /**
282
- * A plain JSON object usable as a `key -> value` record. Arrays are excluded
283
- * explicitly: they are `typeof 'object'`, so an array payload would otherwise
284
- * reach `acceptEntry` once per numeric index — the entries all get rejected in
285
- * the end, but by accident rather than by decision, and noisily.
286
- */
287
- function isRecord(value: unknown): value is Record<string, unknown> {
288
- return typeof value === 'object' && value !== null && !Array.isArray(value);
289
- }
1
+ /**
2
+ * Shared machinery for the node's **node-local** records — the small,
3
+ * NEVER-replicated, per-party sets a node keeps for itself and never sources
4
+ * from shared group state:
5
+ *
6
+ * - the trusted-owner anchor (`trusted-owner-store.ts`),
7
+ * - the cold-start bootstrap-peer store (`bootstrap-peer-store.ts`),
8
+ * - the strand peer book (`strand-peer-book.ts`), whose entries are one map per
9
+ * strand rather than one value per key — the validation hook below is what
10
+ * lets it drop a single junk peer without dropping the strand.
11
+ *
12
+ * ANOTHER node-local record — the enrolled-machine count
13
+ * (`enrolled-machine-store.ts`) — reuses {@link DurableSlot} but deliberately
14
+ * NOT this module's snapshot machinery: it is one scalar rather than an entry
15
+ * map, and it must cold-start rather than throw on an unreadable slot. Its
16
+ * module comment carries the reasoning; do not fold it in here.
17
+ *
18
+ * Every record here is the same mechanism with a different payload: a
19
+ * `{ version, partyId, <entries> }` envelope, snapshot-written whole on every
20
+ * change, loaded under one fail-safe-but-not-fail-silent policy. The only part
21
+ * that differs per platform is WHERE the bytes are kept — Node writes a file,
22
+ * a browser writes IndexedDB, React Native writes SecureStore or its LevelDB
23
+ * KV, NativeScript writes SQLite. That difference is the whole of
24
+ * {@link DurableSlot}, which the embedding app supplies; everything else lives
25
+ * here.
26
+ *
27
+ * This module is cross-platform (no `node:` imports), so it is safe in the
28
+ * package's default entry — the Node-only `FileDurableSlot`
29
+ * (`file-durable-slot.ts`) is what stays behind the `*-store-file` subpaths.
30
+ */
31
+ import debug from 'debug';
32
+
33
+ const log = debug('sereus:cadre:node-local-snapshot');
34
+
35
+ /**
36
+ * A single durable text slot, supplied by the embedding app. The only
37
+ * platform-specific part of a persistent node-local store.
38
+ */
39
+ export interface DurableSlot {
40
+ /**
41
+ * The slot's persisted text, or `undefined` when it was never written.
42
+ *
43
+ * MUST throw (not return `undefined`) when the slot exists but cannot be
44
+ * read. That distinction is load-bearing: `undefined` means "cold start,
45
+ * nothing was ever here", and callers snapshot-write the whole record, so a
46
+ * failed read reported as `undefined` silently converts a recoverable error
47
+ * (permissions, a blocked database upgrade, an I/O fault) into destruction
48
+ * of a still-intact record on the next save.
49
+ *
50
+ * A slot always reports the fault; what a READER does with it is the
51
+ * reader's policy. The two records here rethrow it; the enrolled-machine
52
+ * count catches it and cold-starts, because losing a repair hint must not
53
+ * stop a node. So an implementation must never soften this to `undefined`
54
+ * on a reader's behalf.
55
+ */
56
+ load(): Promise<string | undefined>;
57
+ /**
58
+ * Durably replace the slot's text. Callers snapshot-write the whole record,
59
+ * so an implementation never needs to merge.
60
+ */
61
+ save(text: string): Promise<void>;
62
+ }
63
+
64
+ /** Envelope version. Guards future migrations; an unknown version loads empty. */
65
+ const ENVELOPE_VERSION = 1;
66
+
67
+ /**
68
+ * What one unusable entry means for its siblings — the single intentional
69
+ * difference between the records:
70
+ *
71
+ * - `'discard-all'` (the trusted-owner anchor): a record that cannot be read
72
+ * in full is not an anchor. Trusting a *subset* of the keys a file claims is
73
+ * a silent, security-relevant downgrade, so the whole record is discarded
74
+ * and the node trusts no one until re-seeded out of band.
75
+ * - `'drop-entry'` (the bootstrap-peer store and the strand peer book): the
76
+ * record is a best-effort dial list and nothing in it is trust-bearing, so one
77
+ * junk entry must not discard a stranded node's only remaining way back to
78
+ * its party or its strand's peers.
79
+ */
80
+ export type UnusableEntryPolicy = 'discard-all' | 'drop-entry';
81
+
82
+ /** What a particular node-local record persists, and how it validates it. */
83
+ export interface NodeLocalSnapshotSpec<E> {
84
+ /** Human name of the record, used in load errors and logs. */
85
+ readonly label: string;
86
+ /** Envelope property holding the `key -> entry` record (`owners`, `peers`). */
87
+ readonly payloadKey: string;
88
+ /** See {@link UnusableEntryPolicy}. */
89
+ readonly unusableEntry: UnusableEntryPolicy;
90
+ /**
91
+ * Validate one persisted entry, returning the value to hold in memory
92
+ * (copied, so later mutation of the parsed JSON cannot reach it) or
93
+ * `undefined` when the entry is unusable.
94
+ */
95
+ readonly acceptEntry: (key: string, entry: unknown) => E | undefined;
96
+ }
97
+
98
+ /**
99
+ * A loaded node-local record over a {@link DurableSlot}: an in-memory
100
+ * `key -> entry` map plus a serialised full-snapshot write chain.
101
+ *
102
+ * NOTE: writes are serialised in-process only. Two processes (or two browser
103
+ * tabs) sharing ONE slot for ONE party would each snapshot-write their own
104
+ * view, so the loser's entries are dropped. Fine for every backend today —
105
+ * each node gets its own directory / origin database — but a single slot
106
+ * backing two concurrent nodes of one party needs a lock or a merge-on-write,
107
+ * not a snapshot replace.
108
+ */
109
+ export class NodeLocalSnapshot<E> {
110
+ /**
111
+ * Serialises persists: every write ({@link put}, {@link remove}) snapshot-writes
112
+ * the full entry set, so chaining writes keeps them ordered and the last landed
113
+ * snapshot complete.
114
+ */
115
+ private writeChain: Promise<void> = Promise.resolve();
116
+
117
+ private constructor(
118
+ private readonly slot: DurableSlot,
119
+ readonly partyId: string,
120
+ private readonly spec: NodeLocalSnapshotSpec<E>,
121
+ private readonly entries: Map<string, E>
122
+ ) {}
123
+
124
+ /**
125
+ * Load (or cold-start) the party's record from `slot`. Failure policy, per
126
+ * the trust model of the anchor this was first written for: only a real,
127
+ * well-formed, matching-party record yields entries.
128
+ *
129
+ * A *decidable* non-record — slot never written, unparsable JSON, unknown
130
+ * envelope shape, `partyId` mismatch (a slot reused for a different party
131
+ * must not leak into this one) — yields an EMPTY record, the safe direction:
132
+ * the node holds nothing until it is re-seeded, rather than acting on stale
133
+ * or foreign state.
134
+ *
135
+ * A slot that is *present but unreadable* ({@link DurableSlot.load} threw)
136
+ * is NOT decidable and **throws** instead — mirroring `FileKeyStore.get`.
137
+ * Loading empty there would both hide a real misconfiguration and let the
138
+ * next {@link put} snapshot-write silently destroy a still-intact record.
139
+ */
140
+ static async open<E>(
141
+ slot: DurableSlot,
142
+ partyId: string,
143
+ spec: NodeLocalSnapshotSpec<E>
144
+ ): Promise<NodeLocalSnapshot<E>> {
145
+ return new NodeLocalSnapshot(slot, partyId, spec, await loadEntries(slot, partyId, spec));
146
+ }
147
+
148
+ has(key: string): boolean {
149
+ return this.entries.has(key);
150
+ }
151
+
152
+ /** Fresh copy of the keys — a snapshot decoupled from later {@link put} / {@link remove} calls. */
153
+ keySnapshot(): Set<string> {
154
+ return new Set(this.entries.keys());
155
+ }
156
+
157
+ /**
158
+ * Fresh copy of the `key -> entry` map — a snapshot decoupled from later
159
+ * {@link put} / {@link remove} calls. The entries themselves need no copy:
160
+ * {@link put} REPLACES an entry rather than mutating it in place.
161
+ */
162
+ entrySnapshot(): Map<string, E> {
163
+ return new Map(this.entries);
164
+ }
165
+
166
+ /**
167
+ * Add or replace an entry: the in-memory map updates SYNCHRONOUSLY (so a
168
+ * synchronous caller may consult the store the moment this returns), then
169
+ * the full snapshot is persisted. A persist failure rejects the returned
170
+ * promise but leaves the entry in memory — this session's decision stands,
171
+ * and any later successful write re-lands the complete set.
172
+ */
173
+ put(key: string, entry: E): Promise<void> {
174
+ this.entries.set(key, entry);
175
+ return this.queuePersist();
176
+ }
177
+
178
+ /**
179
+ * Remove an entry, with {@link put}'s contract: the in-memory map updates
180
+ * SYNCHRONOUSLY, then the full snapshot is persisted. Removing an absent key
181
+ * changes nothing, so it writes nothing.
182
+ */
183
+ remove(key: string): Promise<void> {
184
+ if (!this.entries.delete(key)) {
185
+ return Promise.resolve();
186
+ }
187
+ return this.queuePersist();
188
+ }
189
+
190
+ /** Chain a full-snapshot write behind every earlier one (see {@link put}). */
191
+ private queuePersist(): Promise<void> {
192
+ const persist = this.writeChain.then(() => this.persistSnapshot());
193
+ // The chain itself must survive a failed persist (the next write retries the
194
+ // full snapshot); the caller still observes the rejection via `persist`.
195
+ this.writeChain = persist.catch((error) => {
196
+ log('%s: persist failed for party %s: %o', this.spec.label, this.partyId, error);
197
+ });
198
+ return persist;
199
+ }
200
+
201
+ private async persistSnapshot(): Promise<void> {
202
+ const envelope: Record<string, unknown> = {
203
+ version: ENVELOPE_VERSION,
204
+ partyId: this.partyId,
205
+ [this.spec.payloadKey]: Object.fromEntries(this.entries),
206
+ };
207
+ await this.slot.save(JSON.stringify(envelope, null, '\t'));
208
+ }
209
+ }
210
+
211
+ /** Read + validate the slot's text into the initial entry map (see {@link NodeLocalSnapshot.open}). */
212
+ async function loadEntries<E>(
213
+ slot: DurableSlot,
214
+ partyId: string,
215
+ spec: NodeLocalSnapshotSpec<E>
216
+ ): Promise<Map<string, E>> {
217
+ const entries = new Map<string, E>();
218
+ let text: string | undefined;
219
+ try {
220
+ text = await slot.load();
221
+ } catch (error) {
222
+ // Present but unreadable: the one non-decidable case, and the one that must
223
+ // not cold-start empty (see NodeLocalSnapshot.open). The slot's own text is
224
+ // folded into the message, not left only on `cause`: the operator-facing
225
+ // print sites (e.g. `cadre-cli start`) log `error.message` alone, and the
226
+ // slot is what knows the platform detail worth acting on (which file, which
227
+ // database).
228
+ throw new Error(
229
+ `failed to read the ${spec.label} for party ${partyId}: ${error instanceof Error ? error.message : String(error)}`,
230
+ { cause: error }
231
+ );
232
+ }
233
+ if (text === undefined) return entries;
234
+
235
+ let parsed: unknown;
236
+ try {
237
+ parsed = JSON.parse(text);
238
+ } catch (error) {
239
+ log('%s: corrupt slot for party %s (cold start): %o', spec.label, partyId, error);
240
+ return entries;
241
+ }
242
+
243
+ const payload = envelopePayload(parsed, partyId, spec.payloadKey);
244
+ if (!payload) {
245
+ log('%s: slot for party %s has an unknown shape or a foreign partyId (cold start)', spec.label, partyId);
246
+ return entries;
247
+ }
248
+
249
+ for (const [key, raw] of Object.entries(payload)) {
250
+ const entry = spec.acceptEntry(key, raw);
251
+ if (entry === undefined) {
252
+ if (spec.unusableEntry === 'discard-all') {
253
+ log('%s: unusable entry for %s discards the whole record (party %s, cold start)', spec.label, key, partyId);
254
+ return new Map();
255
+ }
256
+ log('%s: dropping unusable entry for %s (party %s)', spec.label, key, partyId);
257
+ continue;
258
+ }
259
+ entries.set(key, entry);
260
+ }
261
+ log('%s: loaded %d entr(ies) for party %s', spec.label, entries.size, partyId);
262
+ return entries;
263
+ }
264
+
265
+ /**
266
+ * The envelope's `key -> entry` record, or undefined on any envelope mismatch —
267
+ * wrong version, wrong (or absent) `partyId`, missing or non-record payload.
268
+ * Individual entries are judged separately by
269
+ * {@link NodeLocalSnapshotSpec.acceptEntry}, because one bad entry does not
270
+ * always mean a bad record.
271
+ */
272
+ function envelopePayload(
273
+ value: unknown,
274
+ partyId: string,
275
+ payloadKey: string
276
+ ): Record<string, unknown> | undefined {
277
+ if (!isRecord(value)) return undefined;
278
+ // A non-string partyId cannot equal the requested one, so this covers both
279
+ // "malformed partyId" and "another party's record".
280
+ if (value.version !== ENVELOPE_VERSION || value.partyId !== partyId) return undefined;
281
+ const payload = value[payloadKey];
282
+ return isRecord(payload) ? payload : undefined;
283
+ }
284
+
285
+ /**
286
+ * A plain JSON object usable as a `key -> value` record. Arrays are excluded
287
+ * explicitly: they are `typeof 'object'`, so an array payload would otherwise
288
+ * reach `acceptEntry` once per numeric index — the entries all get rejected in
289
+ * the end, but by accident rather than by decision, and noisily.
290
+ */
291
+ function isRecord(value: unknown): value is Record<string, unknown> {
292
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
293
+ }