@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,366 +1,366 @@
1
- import debug from 'debug';
2
- import type { Connection, Libp2p, PeerId } from '@libp2p/interface';
3
- import type { ActionId, IPeerNetwork } from '@optimystic/db-core';
4
- import { BlockTransferClient, type IRawStorage } from '@optimystic/db-p2p';
5
-
6
- // NOTE: this copies the WHOLE local store to every newly connected strand peer, which is
7
- // right while a strand mesh is one party's handful of machines (see docs/architecture.md →
8
- // Replication cluster size, "On a strand, the machine count is not a party count"). If
9
- // strand meshes ever get large, filter the pushed set by FRET cohort responsibility for
10
- // each block id instead of pushing everything.
11
- //
12
- // NOTE: this lives in cadre-core only because `../optimystic` is read-only from this repo.
13
- // If Optimystic ever grows a cohort-join catch-up of its own, delete this module rather
14
- // than running two.
15
- //
16
- // Membership: anything connected on the strand's own libp2p network already receives
17
- // cohort replicas of new commits, so pushing older blocks to it exposes nothing new. No
18
- // membership gate here — adding one would diverge from what ordinary replication already
19
- // does on this network. A peer that does NOT speak this strand's block-transfer protocol
20
- // (a bare circuit relay or bootstrap node the strand node also connects to) cannot receive
21
- // anything: the protocol id is namespaced per strand, so the dial fails and the push is
22
- // dropped.
23
- //
24
- // NOTE: that failing case costs one dial timeout per connection:open from such a peer, and
25
- // is never memoized (only clean runs are). Bounded today by the debounce plus the
26
- // unreachable-peer bail in `runCatchUp` — one dial per event, not one per chunk. If a strand
27
- // node ever holds many non-strand connections, or the enumeration ahead of the first chunk
28
- // gets expensive, pre-check `libp2p.peerStore` for this strand's block-transfer protocol
29
- // before enumerating.
30
- //
31
- // NOTE: a run that fails is retried only when that peer next opens a connection. Over a
32
- // stable connection a transient push failure therefore leaves the peer partially copied
33
- // until the next reconnect (read repair still covers reads meanwhile). If strand meshes
34
- // ever hold long-lived connections where that matters, re-arm the debounce timer with a
35
- // backoff on a non-clean run instead of waiting for connection:open.
36
-
37
- const log = debug('sereus:cadre:strand-backfill');
38
-
39
- /**
40
- * The block-transfer protocol's hard cap on one length-prefixed message. Mirrors
41
- * `MAX_BLOCK_MESSAGE_BYTES` in `@optimystic/db-p2p`'s `protocol-limits.ts` (8 MiB), which
42
- * that package does not re-export from its index — keep the two in sync if upstream ever
43
- * changes it or starts exporting it.
44
- */
45
- export const MAX_BLOCK_MESSAGE_BYTES = 8 * 1024 * 1024;
46
-
47
- /** Tuning for the per-peer strand catch-up. Every field optional; defaults in {@link DEFAULT_STRAND_BACKFILL}. */
48
- export interface StrandBackfillConfig {
49
- /** Default true. False disables the catch-up entirely (the pre-existing behaviour). */
50
- enabled?: boolean;
51
- /** Settle time after a connection opens before catching that peer up, ms. Default 1000. */
52
- debounceMs?: number;
53
- /** Ceiling on blocks copied in one catch-up. Default 10_000. Reaching it is LOGGED, never silent. */
54
- maxBlocks?: number;
55
- /** Soft byte budget per push message. Default 1 MiB. Protocol hard cap is {@link MAX_BLOCK_MESSAGE_BYTES} (8 MiB). */
56
- maxChunkBytes?: number;
57
- /** Max blocks per push message. Default 64. */
58
- maxChunkBlocks?: number;
59
- /** Per-push dial deadline, ms. Default 3000 (matches SpreadOnChurnMonitor). */
60
- dialTimeoutMs?: number;
61
- /** Per-push response deadline, ms. Default 10_000 (matches SpreadOnChurnMonitor). */
62
- responseTimeoutMs?: number;
63
- }
64
-
65
- /** The resolved defaults every {@link StrandBackfill} starts from. */
66
- export const DEFAULT_STRAND_BACKFILL: Required<StrandBackfillConfig> = {
67
- enabled: true,
68
- debounceMs: 1000,
69
- maxBlocks: 10_000,
70
- maxChunkBytes: 1024 * 1024,
71
- maxChunkBlocks: 64,
72
- dialTimeoutMs: 3000,
73
- responseTimeoutMs: 10_000
74
- };
75
-
76
- /**
77
- * The one capability the catch-up needs from a transfer client. Structural (rather than
78
- * the concrete `BlockTransferClient`) so unit tests can capture pushes without dialing
79
- * libp2p — see {@link StrandBackfillDeps.createPushClient}.
80
- */
81
- export type StrandBackfillPushClient = Pick<BlockTransferClient, 'pushBlocks'>;
82
-
83
- export interface StrandBackfillDeps {
84
- strandId: string;
85
- /** The STRAND's libp2p node (not the control node) — source of connection events and peer ids. */
86
- libp2p: Libp2p;
87
- /** `node.keyNetwork`, the IPeerNetwork BlockTransferClient dials through. */
88
- peerNetwork: IPeerNetwork;
89
- /** This strand's own raw block store — the same instance handed to the libp2p node. */
90
- storage: IRawStorage;
91
- /** Must equal the prefix the receiver registered its handler under: `/optimystic/strand-<strandId>`. */
92
- protocolPrefix: string;
93
- /**
94
- * Test seam: build the per-peer push client. Defaults to a real
95
- * `BlockTransferClient` over {@link peerNetwork} + {@link protocolPrefix}.
96
- */
97
- createPushClient?: (peerId: PeerId) => StrandBackfillPushClient;
98
- }
99
-
100
- /** What one peer's catch-up actually did. Returned for tests and logged at the end of each run. */
101
- export interface StrandBackfillResult {
102
- /** Blocks offered: had a committed `latest` AND materialized content locally. */
103
- offered: number;
104
- /** Blocks the remote reported it persisted. */
105
- accepted: number;
106
- /** Block ids the remote reported in `missing` (parse or persist failure on its side). */
107
- rejected: string[];
108
- /** Skipped: metadata has no `latest` (pending-only — not yet a durability claim here). */
109
- uncommitted: number;
110
- /** Skipped: `latest` exists but no materialized block is stored for that actionId. */
111
- unmaterialized: number;
112
- /** Not attempted because `maxBlocks` was reached. */
113
- capped: number;
114
- /** Skipped: a single block whose wire size alone exceeds {@link MAX_BLOCK_MESSAGE_BYTES}. */
115
- oversized: string[];
116
- }
117
-
118
- function emptyResult(): StrandBackfillResult {
119
- return { offered: 0, accepted: 0, rejected: [], uncommitted: 0, unmaterialized: 0, capped: 0, oversized: [] };
120
- }
121
-
122
- /** One in-flight push message being accumulated. */
123
- interface Chunk {
124
- ids: string[];
125
- buffers: Uint8Array[];
126
- meta: Record<string, { rev: number; actionId: ActionId }>;
127
- bytes: number;
128
- }
129
-
130
- /**
131
- * Base64 wire size of a raw buffer — `pushBlocks` base64-encodes each block into the JSON
132
- * request, so the protocol cap must be judged against the encoded size, not the raw bytes.
133
- */
134
- function base64WireBytes(rawBytes: number): number {
135
- return Math.ceil(rawBytes / 3) * 4;
136
- }
137
-
138
- /**
139
- * Copies every block in one strand's own raw store to each peer its libp2p node connects
140
- * to, so a peer that joined the strand after blocks were committed still ends up holding
141
- * them physically (the receiver persists each push via `saveReplicatedBlock`, which is
142
- * monotonic and idempotent — crossing pushes from both ends cannot regress a revision).
143
- *
144
- * Best-effort throughout: nothing here throws into a libp2p event handler or into
145
- * `buildStrandRuntime`; a failed chunk is logged and the run continues. A peer is marked
146
- * fully caught up ONLY after a run with no thrown chunk and an empty `missing` list, so
147
- * the next `connection:open` from a peer whose catch-up failed retries it.
148
- */
149
- export class StrandBackfill {
150
- private readonly config: Required<StrandBackfillConfig>;
151
- private readonly createPushClient: (peerId: PeerId) => StrandBackfillPushClient;
152
- private started = false;
153
- private stopped = false;
154
- /** Peers fully caught up this runtime (never retried until the runtime is rebuilt). */
155
- private readonly done = new Set<string>();
156
- /** Peers with a catch-up currently running (suppresses concurrent duplicates). */
157
- private readonly inFlight = new Set<string>();
158
- /** Pending per-peer debounce timers, cleared on stop. */
159
- private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();
160
- private readonly onConnectionOpen: (evt: CustomEvent<Connection>) => void;
161
- private loggedNoListBlockIds = false;
162
-
163
- constructor(private readonly deps: StrandBackfillDeps, config?: StrandBackfillConfig) {
164
- this.config = { ...DEFAULT_STRAND_BACKFILL, ...config };
165
- this.createPushClient = deps.createPushClient
166
- ?? ((peerId) => new BlockTransferClient(peerId, deps.peerNetwork, deps.protocolPrefix));
167
- this.onConnectionOpen = (evt) => this.schedulePeer(evt.detail.remotePeer);
168
- }
169
-
170
- /** Subscribe to connection:open AND schedule a catch-up for peers already connected. */
171
- start(): void {
172
- if (this.started || this.stopped || !this.config.enabled) return;
173
- this.started = true;
174
- this.deps.libp2p.addEventListener('connection:open', this.onConnectionOpen);
175
- // A runtime rebuilt over live connections (resumeStrand) never sees their
176
- // connection:open, so walk what is already connected once.
177
- const existing = this.deps.libp2p.getConnections();
178
- for (const connection of existing) {
179
- this.schedulePeer(connection.remotePeer);
180
- }
181
- log('[%s] started (%d peer(s) already connected)', this.deps.strandId, existing.length);
182
- }
183
-
184
- /** Unsubscribe, clear timers; in-flight runs observe the stopped flag and bail. */
185
- stop(): void {
186
- if (this.stopped) return;
187
- this.stopped = true;
188
- if (this.started) {
189
- this.deps.libp2p.removeEventListener('connection:open', this.onConnectionOpen);
190
- }
191
- for (const timer of this.timers.values()) {
192
- clearTimeout(timer);
193
- }
194
- this.timers.clear();
195
- log('[%s] stopped', this.deps.strandId);
196
- }
197
-
198
- /** Debounced entry point for connection churn: one run per peer per settle window. */
199
- private schedulePeer(peerId: PeerId): void {
200
- const key = peerId.toString();
201
- if (this.stopped || this.done.has(key) || this.inFlight.has(key)) return;
202
- const existing = this.timers.get(key);
203
- if (existing) clearTimeout(existing);
204
- this.timers.set(key, setTimeout(() => {
205
- this.timers.delete(key);
206
- void this.catchUpPeer(peerId);
207
- }, this.config.debounceMs));
208
- }
209
-
210
- /**
211
- * Run one peer's catch-up now, bypassing the debounce. Never rejects. Returns an
212
- * all-zero result without pushing when the peer is already caught up, already being
213
- * caught up, or this backfill is stopped.
214
- */
215
- async catchUpPeer(peerId: PeerId): Promise<StrandBackfillResult> {
216
- const key = peerId.toString();
217
- if (this.stopped || this.done.has(key) || this.inFlight.has(key)) {
218
- return emptyResult();
219
- }
220
- this.inFlight.add(key);
221
- try {
222
- const { result, clean } = await this.runCatchUp(peerId);
223
- // NOTE: a run that hit `maxBlocks` is still "clean" and still memoizes the peer, so
224
- // the tail past the ceiling never reaches it. Deliberate: enumeration is not
225
- // resumable, so not memoizing would re-push the same prefix on every reconnect
226
- // without ever advancing. Loud in the log below (capped > 0). If a strand's store can
227
- // realistically exceed maxBlocks, the fix is a resumable cursor, not either policy.
228
- if (clean && !this.stopped) {
229
- this.done.add(key);
230
- }
231
- log('[%s] catch-up peer=%s offered=%d accepted=%d rejected=%d uncommitted=%d unmaterialized=%d capped=%d oversized=%d done=%s',
232
- this.deps.strandId, key, result.offered, result.accepted, result.rejected.length,
233
- result.uncommitted, result.unmaterialized, result.capped, result.oversized.length, clean);
234
- return result;
235
- } catch (error) {
236
- // runCatchUp already contains a per-chunk catch; this guards the enumeration and
237
- // metadata reads too — a backfill fault must never surface through a libp2p event.
238
- log('[%s] catch-up peer=%s failed: %o', this.deps.strandId, key, error);
239
- return emptyResult();
240
- } finally {
241
- this.inFlight.delete(key);
242
- }
243
- }
244
-
245
- /** The actual copy. `clean` = every chunk pushed and the remote persisted every block. */
246
- private async runCatchUp(peerId: PeerId): Promise<{ result: StrandBackfillResult; clean: boolean }> {
247
- const result = emptyResult();
248
- const { storage } = this.deps;
249
-
250
- if (!storage.listBlockIds) {
251
- if (!this.loggedNoListBlockIds) {
252
- this.loggedNoListBlockIds = true;
253
- log('[%s] raw storage does not implement listBlockIds(); backfill is inert', this.deps.strandId);
254
- }
255
- return { result, clean: false };
256
- }
257
-
258
- const client = this.createPushClient(peerId);
259
- const encoder = new TextEncoder();
260
- let chunk: Chunk = { ids: [], buffers: [], meta: {}, bytes: 0 };
261
- let chunkFailed = false;
262
- let anyChunkDelivered = false;
263
- /**
264
- * A peer that has answered no push at all, and failed one, is not reachable on this
265
- * protocol — abandon rather than spend a dial timeout per remaining chunk. Once ONE
266
- * push has been answered the peer demonstrably speaks it, so a later failure is a
267
- * transient blip and the rest of the store is still worth pushing.
268
- */
269
- const peerUnreachable = (): boolean => chunkFailed && !anyChunkDelivered;
270
-
271
- const flush = async (): Promise<void> => {
272
- if (chunk.ids.length === 0) return;
273
- const { ids, buffers, meta } = chunk;
274
- chunk = { ids: [], buffers: [], meta: {}, bytes: 0 };
275
- try {
276
- const response = await client.pushBlocks(ids, buffers, 'replication', meta, {
277
- dialTimeoutMs: this.config.dialTimeoutMs,
278
- responseTimeoutMs: this.config.responseTimeoutMs
279
- });
280
- anyChunkDelivered = true;
281
- const missing = new Set(response.missing);
282
- for (const id of ids) {
283
- if (missing.has(id)) {
284
- result.rejected.push(id);
285
- } else {
286
- result.accepted += 1;
287
- }
288
- }
289
- if (response.missing.length > 0) {
290
- log('[%s] peer=%s rejected %d block(s): %o', this.deps.strandId, peerId.toString(), response.missing.length, response.missing);
291
- }
292
- } catch (error) {
293
- chunkFailed = true;
294
- log('[%s] push to peer=%s failed for %d block(s): %s', this.deps.strandId, peerId.toString(), ids.length, (error as Error).message);
295
- }
296
- };
297
-
298
- for await (const blockId of storage.listBlockIds()) {
299
- if (this.stopped) break;
300
- if (result.offered >= this.config.maxBlocks) {
301
- // Past the ceiling: count what is left (id enumeration only — no more reads or
302
- // pushes) so the cap is loud in the end-of-run log rather than silent.
303
- result.capped += 1;
304
- continue;
305
- }
306
-
307
- const metadata = await storage.getMetadata(blockId);
308
- const latest = metadata?.latest;
309
- if (!latest) {
310
- result.uncommitted += 1;
311
- continue;
312
- }
313
- // NOTE: a block whose latest revision is a DELETE materializes to nothing (a
314
- // tombstone), so it is skipped here — a peer that joins after such a delete never
315
- // receives the tombstone from this path and relies on read repair for it. Fine
316
- // while nothing deletes whole blocks pre-join; if the whole-store coverage gate in
317
- // strand-membership-closed-strand-e2e ever reports a tombstone residue, teach this
318
- // to push the promoted delete transform instead of skipping.
319
- const block = await storage.getMaterializedBlock(blockId, latest.actionId);
320
- if (!block) {
321
- result.unmaterialized += 1;
322
- log('[%s] block=%s has latest rev %d but no materialized content; skipped', this.deps.strandId, blockId, latest.rev);
323
- continue;
324
- }
325
-
326
- const buffer = encoder.encode(JSON.stringify(block));
327
- // NOTE: MAX_BLOCK_MESSAGE_BYTES caps the whole framed request, not one block, and
328
- // this test ignores the request envelope (ids array, blockMeta, JSON punctuation).
329
- // A lone block within a few KiB of the cap therefore still ships and is rejected by
330
- // the receiver's length-prefix decoder — a permanent chunk failure for that peer. No
331
- // block in a strand comes close today; if one ever can, subtract a measured envelope
332
- // allowance here rather than raising the cap.
333
- if (base64WireBytes(buffer.length) >= MAX_BLOCK_MESSAGE_BYTES) {
334
- result.oversized.push(blockId);
335
- log('[%s] block=%s is %d bytes (%d on the wire) — exceeds the %d-byte protocol cap alone; skipped',
336
- this.deps.strandId, blockId, buffer.length, base64WireBytes(buffer.length), MAX_BLOCK_MESSAGE_BYTES);
337
- continue;
338
- }
339
-
340
- // Flush before adding when this block would overflow either budget. A single block
341
- // larger than maxChunkBytes still ships — alone, in its own chunk.
342
- if (chunk.ids.length > 0
343
- && (chunk.ids.length + 1 > this.config.maxChunkBlocks || chunk.bytes + buffer.length > this.config.maxChunkBytes)) {
344
- await flush();
345
- if (this.stopped || peerUnreachable()) break;
346
- }
347
- chunk.ids.push(blockId);
348
- chunk.buffers.push(buffer);
349
- chunk.meta[blockId] = { rev: latest.rev, actionId: latest.actionId };
350
- chunk.bytes += buffer.length;
351
- result.offered += 1;
352
- }
353
-
354
- if (!this.stopped && !peerUnreachable()) {
355
- await flush();
356
- }
357
-
358
- if (result.capped > 0) {
359
- log('[%s] peer=%s catch-up CAPPED at %d blocks; %d block id(s) not attempted',
360
- this.deps.strandId, peerId.toString(), this.config.maxBlocks, result.capped);
361
- }
362
-
363
- const clean = !chunkFailed && result.rejected.length === 0;
364
- return { result, clean };
365
- }
366
- }
1
+ import debug from 'debug';
2
+ import type { Connection, Libp2p, PeerId } from '@libp2p/interface';
3
+ import type { ActionId, IPeerNetwork } from '@optimystic/db-core';
4
+ import { BlockTransferClient, type IRawStorage } from '@optimystic/db-p2p';
5
+
6
+ // NOTE: this copies the WHOLE local store to every newly connected strand peer, which is
7
+ // right while a strand mesh is one party's handful of machines (see docs/architecture.md →
8
+ // Replication cluster size, "On a strand, the machine count is not a party count"). If
9
+ // strand meshes ever get large, filter the pushed set by FRET cohort responsibility for
10
+ // each block id instead of pushing everything.
11
+ //
12
+ // NOTE: this lives in cadre-core only because `../optimystic` is read-only from this repo.
13
+ // If Optimystic ever grows a cohort-join catch-up of its own, delete this module rather
14
+ // than running two.
15
+ //
16
+ // Membership: anything connected on the strand's own libp2p network already receives
17
+ // cohort replicas of new commits, so pushing older blocks to it exposes nothing new. No
18
+ // membership gate here — adding one would diverge from what ordinary replication already
19
+ // does on this network. A peer that does NOT speak this strand's block-transfer protocol
20
+ // (a bare circuit relay or bootstrap node the strand node also connects to) cannot receive
21
+ // anything: the protocol id is namespaced per strand, so the dial fails and the push is
22
+ // dropped.
23
+ //
24
+ // NOTE: that failing case costs one dial timeout per connection:open from such a peer, and
25
+ // is never memoized (only clean runs are). Bounded today by the debounce plus the
26
+ // unreachable-peer bail in `runCatchUp` — one dial per event, not one per chunk. If a strand
27
+ // node ever holds many non-strand connections, or the enumeration ahead of the first chunk
28
+ // gets expensive, pre-check `libp2p.peerStore` for this strand's block-transfer protocol
29
+ // before enumerating.
30
+ //
31
+ // NOTE: a run that fails is retried only when that peer next opens a connection. Over a
32
+ // stable connection a transient push failure therefore leaves the peer partially copied
33
+ // until the next reconnect (read repair still covers reads meanwhile). If strand meshes
34
+ // ever hold long-lived connections where that matters, re-arm the debounce timer with a
35
+ // backoff on a non-clean run instead of waiting for connection:open.
36
+
37
+ const log = debug('sereus:cadre:strand-backfill');
38
+
39
+ /**
40
+ * The block-transfer protocol's hard cap on one length-prefixed message. Mirrors
41
+ * `MAX_BLOCK_MESSAGE_BYTES` in `@optimystic/db-p2p`'s `protocol-limits.ts` (8 MiB), which
42
+ * that package does not re-export from its index — keep the two in sync if upstream ever
43
+ * changes it or starts exporting it.
44
+ */
45
+ export const MAX_BLOCK_MESSAGE_BYTES = 8 * 1024 * 1024;
46
+
47
+ /** Tuning for the per-peer strand catch-up. Every field optional; defaults in {@link DEFAULT_STRAND_BACKFILL}. */
48
+ export interface StrandBackfillConfig {
49
+ /** Default true. False disables the catch-up entirely (the pre-existing behaviour). */
50
+ enabled?: boolean;
51
+ /** Settle time after a connection opens before catching that peer up, ms. Default 1000. */
52
+ debounceMs?: number;
53
+ /** Ceiling on blocks copied in one catch-up. Default 10_000. Reaching it is LOGGED, never silent. */
54
+ maxBlocks?: number;
55
+ /** Soft byte budget per push message. Default 1 MiB. Protocol hard cap is {@link MAX_BLOCK_MESSAGE_BYTES} (8 MiB). */
56
+ maxChunkBytes?: number;
57
+ /** Max blocks per push message. Default 64. */
58
+ maxChunkBlocks?: number;
59
+ /** Per-push dial deadline, ms. Default 3000 (matches SpreadOnChurnMonitor). */
60
+ dialTimeoutMs?: number;
61
+ /** Per-push response deadline, ms. Default 10_000 (matches SpreadOnChurnMonitor). */
62
+ responseTimeoutMs?: number;
63
+ }
64
+
65
+ /** The resolved defaults every {@link StrandBackfill} starts from. */
66
+ export const DEFAULT_STRAND_BACKFILL: Required<StrandBackfillConfig> = {
67
+ enabled: true,
68
+ debounceMs: 1000,
69
+ maxBlocks: 10_000,
70
+ maxChunkBytes: 1024 * 1024,
71
+ maxChunkBlocks: 64,
72
+ dialTimeoutMs: 3000,
73
+ responseTimeoutMs: 10_000
74
+ };
75
+
76
+ /**
77
+ * The one capability the catch-up needs from a transfer client. Structural (rather than
78
+ * the concrete `BlockTransferClient`) so unit tests can capture pushes without dialing
79
+ * libp2p — see {@link StrandBackfillDeps.createPushClient}.
80
+ */
81
+ export type StrandBackfillPushClient = Pick<BlockTransferClient, 'pushBlocks'>;
82
+
83
+ export interface StrandBackfillDeps {
84
+ strandId: string;
85
+ /** The STRAND's libp2p node (not the control node) — source of connection events and peer ids. */
86
+ libp2p: Libp2p;
87
+ /** `node.keyNetwork`, the IPeerNetwork BlockTransferClient dials through. */
88
+ peerNetwork: IPeerNetwork;
89
+ /** This strand's own raw block store — the same instance handed to the libp2p node. */
90
+ storage: IRawStorage;
91
+ /** Must equal the prefix the receiver registered its handler under: `/optimystic/strand-<strandId>`. */
92
+ protocolPrefix: string;
93
+ /**
94
+ * Test seam: build the per-peer push client. Defaults to a real
95
+ * `BlockTransferClient` over {@link peerNetwork} + {@link protocolPrefix}.
96
+ */
97
+ createPushClient?: (peerId: PeerId) => StrandBackfillPushClient;
98
+ }
99
+
100
+ /** What one peer's catch-up actually did. Returned for tests and logged at the end of each run. */
101
+ export interface StrandBackfillResult {
102
+ /** Blocks offered: had a committed `latest` AND materialized content locally. */
103
+ offered: number;
104
+ /** Blocks the remote reported it persisted. */
105
+ accepted: number;
106
+ /** Block ids the remote reported in `missing` (parse or persist failure on its side). */
107
+ rejected: string[];
108
+ /** Skipped: metadata has no `latest` (pending-only — not yet a durability claim here). */
109
+ uncommitted: number;
110
+ /** Skipped: `latest` exists but no materialized block is stored for that actionId. */
111
+ unmaterialized: number;
112
+ /** Not attempted because `maxBlocks` was reached. */
113
+ capped: number;
114
+ /** Skipped: a single block whose wire size alone exceeds {@link MAX_BLOCK_MESSAGE_BYTES}. */
115
+ oversized: string[];
116
+ }
117
+
118
+ function emptyResult(): StrandBackfillResult {
119
+ return { offered: 0, accepted: 0, rejected: [], uncommitted: 0, unmaterialized: 0, capped: 0, oversized: [] };
120
+ }
121
+
122
+ /** One in-flight push message being accumulated. */
123
+ interface Chunk {
124
+ ids: string[];
125
+ buffers: Uint8Array[];
126
+ meta: Record<string, { rev: number; actionId: ActionId }>;
127
+ bytes: number;
128
+ }
129
+
130
+ /**
131
+ * Base64 wire size of a raw buffer — `pushBlocks` base64-encodes each block into the JSON
132
+ * request, so the protocol cap must be judged against the encoded size, not the raw bytes.
133
+ */
134
+ function base64WireBytes(rawBytes: number): number {
135
+ return Math.ceil(rawBytes / 3) * 4;
136
+ }
137
+
138
+ /**
139
+ * Copies every block in one strand's own raw store to each peer its libp2p node connects
140
+ * to, so a peer that joined the strand after blocks were committed still ends up holding
141
+ * them physically (the receiver persists each push via `saveReplicatedBlock`, which is
142
+ * monotonic and idempotent — crossing pushes from both ends cannot regress a revision).
143
+ *
144
+ * Best-effort throughout: nothing here throws into a libp2p event handler or into
145
+ * `buildStrandRuntime`; a failed chunk is logged and the run continues. A peer is marked
146
+ * fully caught up ONLY after a run with no thrown chunk and an empty `missing` list, so
147
+ * the next `connection:open` from a peer whose catch-up failed retries it.
148
+ */
149
+ export class StrandBackfill {
150
+ private readonly config: Required<StrandBackfillConfig>;
151
+ private readonly createPushClient: (peerId: PeerId) => StrandBackfillPushClient;
152
+ private started = false;
153
+ private stopped = false;
154
+ /** Peers fully caught up this runtime (never retried until the runtime is rebuilt). */
155
+ private readonly done = new Set<string>();
156
+ /** Peers with a catch-up currently running (suppresses concurrent duplicates). */
157
+ private readonly inFlight = new Set<string>();
158
+ /** Pending per-peer debounce timers, cleared on stop. */
159
+ private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();
160
+ private readonly onConnectionOpen: (evt: CustomEvent<Connection>) => void;
161
+ private loggedNoListBlockIds = false;
162
+
163
+ constructor(private readonly deps: StrandBackfillDeps, config?: StrandBackfillConfig) {
164
+ this.config = { ...DEFAULT_STRAND_BACKFILL, ...config };
165
+ this.createPushClient = deps.createPushClient
166
+ ?? ((peerId) => new BlockTransferClient(peerId, deps.peerNetwork, deps.protocolPrefix));
167
+ this.onConnectionOpen = (evt) => this.schedulePeer(evt.detail.remotePeer);
168
+ }
169
+
170
+ /** Subscribe to connection:open AND schedule a catch-up for peers already connected. */
171
+ start(): void {
172
+ if (this.started || this.stopped || !this.config.enabled) return;
173
+ this.started = true;
174
+ this.deps.libp2p.addEventListener('connection:open', this.onConnectionOpen);
175
+ // A runtime rebuilt over live connections (resumeStrand) never sees their
176
+ // connection:open, so walk what is already connected once.
177
+ const existing = this.deps.libp2p.getConnections();
178
+ for (const connection of existing) {
179
+ this.schedulePeer(connection.remotePeer);
180
+ }
181
+ log('[%s] started (%d peer(s) already connected)', this.deps.strandId, existing.length);
182
+ }
183
+
184
+ /** Unsubscribe, clear timers; in-flight runs observe the stopped flag and bail. */
185
+ stop(): void {
186
+ if (this.stopped) return;
187
+ this.stopped = true;
188
+ if (this.started) {
189
+ this.deps.libp2p.removeEventListener('connection:open', this.onConnectionOpen);
190
+ }
191
+ for (const timer of this.timers.values()) {
192
+ clearTimeout(timer);
193
+ }
194
+ this.timers.clear();
195
+ log('[%s] stopped', this.deps.strandId);
196
+ }
197
+
198
+ /** Debounced entry point for connection churn: one run per peer per settle window. */
199
+ private schedulePeer(peerId: PeerId): void {
200
+ const key = peerId.toString();
201
+ if (this.stopped || this.done.has(key) || this.inFlight.has(key)) return;
202
+ const existing = this.timers.get(key);
203
+ if (existing) clearTimeout(existing);
204
+ this.timers.set(key, setTimeout(() => {
205
+ this.timers.delete(key);
206
+ void this.catchUpPeer(peerId);
207
+ }, this.config.debounceMs));
208
+ }
209
+
210
+ /**
211
+ * Run one peer's catch-up now, bypassing the debounce. Never rejects. Returns an
212
+ * all-zero result without pushing when the peer is already caught up, already being
213
+ * caught up, or this backfill is stopped.
214
+ */
215
+ async catchUpPeer(peerId: PeerId): Promise<StrandBackfillResult> {
216
+ const key = peerId.toString();
217
+ if (this.stopped || this.done.has(key) || this.inFlight.has(key)) {
218
+ return emptyResult();
219
+ }
220
+ this.inFlight.add(key);
221
+ try {
222
+ const { result, clean } = await this.runCatchUp(peerId);
223
+ // NOTE: a run that hit `maxBlocks` is still "clean" and still memoizes the peer, so
224
+ // the tail past the ceiling never reaches it. Deliberate: enumeration is not
225
+ // resumable, so not memoizing would re-push the same prefix on every reconnect
226
+ // without ever advancing. Loud in the log below (capped > 0). If a strand's store can
227
+ // realistically exceed maxBlocks, the fix is a resumable cursor, not either policy.
228
+ if (clean && !this.stopped) {
229
+ this.done.add(key);
230
+ }
231
+ log('[%s] catch-up peer=%s offered=%d accepted=%d rejected=%d uncommitted=%d unmaterialized=%d capped=%d oversized=%d done=%s',
232
+ this.deps.strandId, key, result.offered, result.accepted, result.rejected.length,
233
+ result.uncommitted, result.unmaterialized, result.capped, result.oversized.length, clean);
234
+ return result;
235
+ } catch (error) {
236
+ // runCatchUp already contains a per-chunk catch; this guards the enumeration and
237
+ // metadata reads too — a backfill fault must never surface through a libp2p event.
238
+ log('[%s] catch-up peer=%s failed: %o', this.deps.strandId, key, error);
239
+ return emptyResult();
240
+ } finally {
241
+ this.inFlight.delete(key);
242
+ }
243
+ }
244
+
245
+ /** The actual copy. `clean` = every chunk pushed and the remote persisted every block. */
246
+ private async runCatchUp(peerId: PeerId): Promise<{ result: StrandBackfillResult; clean: boolean }> {
247
+ const result = emptyResult();
248
+ const { storage } = this.deps;
249
+
250
+ if (!storage.listBlockIds) {
251
+ if (!this.loggedNoListBlockIds) {
252
+ this.loggedNoListBlockIds = true;
253
+ log('[%s] raw storage does not implement listBlockIds(); backfill is inert', this.deps.strandId);
254
+ }
255
+ return { result, clean: false };
256
+ }
257
+
258
+ const client = this.createPushClient(peerId);
259
+ const encoder = new TextEncoder();
260
+ let chunk: Chunk = { ids: [], buffers: [], meta: {}, bytes: 0 };
261
+ let chunkFailed = false;
262
+ let anyChunkDelivered = false;
263
+ /**
264
+ * A peer that has answered no push at all, and failed one, is not reachable on this
265
+ * protocol — abandon rather than spend a dial timeout per remaining chunk. Once ONE
266
+ * push has been answered the peer demonstrably speaks it, so a later failure is a
267
+ * transient blip and the rest of the store is still worth pushing.
268
+ */
269
+ const peerUnreachable = (): boolean => chunkFailed && !anyChunkDelivered;
270
+
271
+ const flush = async (): Promise<void> => {
272
+ if (chunk.ids.length === 0) return;
273
+ const { ids, buffers, meta } = chunk;
274
+ chunk = { ids: [], buffers: [], meta: {}, bytes: 0 };
275
+ try {
276
+ const response = await client.pushBlocks(ids, buffers, 'replication', meta, {
277
+ dialTimeoutMs: this.config.dialTimeoutMs,
278
+ responseTimeoutMs: this.config.responseTimeoutMs
279
+ });
280
+ anyChunkDelivered = true;
281
+ const missing = new Set(response.missing);
282
+ for (const id of ids) {
283
+ if (missing.has(id)) {
284
+ result.rejected.push(id);
285
+ } else {
286
+ result.accepted += 1;
287
+ }
288
+ }
289
+ if (response.missing.length > 0) {
290
+ log('[%s] peer=%s rejected %d block(s): %o', this.deps.strandId, peerId.toString(), response.missing.length, response.missing);
291
+ }
292
+ } catch (error) {
293
+ chunkFailed = true;
294
+ log('[%s] push to peer=%s failed for %d block(s): %s', this.deps.strandId, peerId.toString(), ids.length, (error as Error).message);
295
+ }
296
+ };
297
+
298
+ for await (const blockId of storage.listBlockIds()) {
299
+ if (this.stopped) break;
300
+ if (result.offered >= this.config.maxBlocks) {
301
+ // Past the ceiling: count what is left (id enumeration only — no more reads or
302
+ // pushes) so the cap is loud in the end-of-run log rather than silent.
303
+ result.capped += 1;
304
+ continue;
305
+ }
306
+
307
+ const metadata = await storage.getMetadata(blockId);
308
+ const latest = metadata?.latest;
309
+ if (!latest) {
310
+ result.uncommitted += 1;
311
+ continue;
312
+ }
313
+ // NOTE: a block whose latest revision is a DELETE materializes to nothing (a
314
+ // tombstone), so it is skipped here — a peer that joins after such a delete never
315
+ // receives the tombstone from this path and relies on read repair for it. Fine
316
+ // while nothing deletes whole blocks pre-join; if the whole-store coverage gate in
317
+ // strand-membership-closed-strand-e2e ever reports a tombstone residue, teach this
318
+ // to push the promoted delete transform instead of skipping.
319
+ const block = await storage.getMaterializedBlock(blockId, latest.actionId);
320
+ if (!block) {
321
+ result.unmaterialized += 1;
322
+ log('[%s] block=%s has latest rev %d but no materialized content; skipped', this.deps.strandId, blockId, latest.rev);
323
+ continue;
324
+ }
325
+
326
+ const buffer = encoder.encode(JSON.stringify(block));
327
+ // NOTE: MAX_BLOCK_MESSAGE_BYTES caps the whole framed request, not one block, and
328
+ // this test ignores the request envelope (ids array, blockMeta, JSON punctuation).
329
+ // A lone block within a few KiB of the cap therefore still ships and is rejected by
330
+ // the receiver's length-prefix decoder — a permanent chunk failure for that peer. No
331
+ // block in a strand comes close today; if one ever can, subtract a measured envelope
332
+ // allowance here rather than raising the cap.
333
+ if (base64WireBytes(buffer.length) >= MAX_BLOCK_MESSAGE_BYTES) {
334
+ result.oversized.push(blockId);
335
+ log('[%s] block=%s is %d bytes (%d on the wire) — exceeds the %d-byte protocol cap alone; skipped',
336
+ this.deps.strandId, blockId, buffer.length, base64WireBytes(buffer.length), MAX_BLOCK_MESSAGE_BYTES);
337
+ continue;
338
+ }
339
+
340
+ // Flush before adding when this block would overflow either budget. A single block
341
+ // larger than maxChunkBytes still ships — alone, in its own chunk.
342
+ if (chunk.ids.length > 0
343
+ && (chunk.ids.length + 1 > this.config.maxChunkBlocks || chunk.bytes + buffer.length > this.config.maxChunkBytes)) {
344
+ await flush();
345
+ if (this.stopped || peerUnreachable()) break;
346
+ }
347
+ chunk.ids.push(blockId);
348
+ chunk.buffers.push(buffer);
349
+ chunk.meta[blockId] = { rev: latest.rev, actionId: latest.actionId };
350
+ chunk.bytes += buffer.length;
351
+ result.offered += 1;
352
+ }
353
+
354
+ if (!this.stopped && !peerUnreachable()) {
355
+ await flush();
356
+ }
357
+
358
+ if (result.capped > 0) {
359
+ log('[%s] peer=%s catch-up CAPPED at %d blocks; %d block id(s) not attempted',
360
+ this.deps.strandId, peerId.toString(), this.config.maxBlocks, result.capped);
361
+ }
362
+
363
+ const clean = !chunkFailed && result.rejected.length === 0;
364
+ return { result, clean };
365
+ }
366
+ }