@serfab/cadre-core 0.12.0 → 0.13.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 (86) hide show
  1. package/README.md +3 -2
  2. package/dist/cadre-node.d.ts +328 -25
  3. package/dist/cadre-node.js +760 -59
  4. package/dist/cadre-node.js.map +1 -1
  5. package/dist/control-database.d.ts +19 -0
  6. package/dist/control-database.js +51 -9
  7. package/dist/control-database.js.map +1 -1
  8. package/dist/control-schema.d.ts +1 -1
  9. package/dist/control-schema.js +30 -2
  10. package/dist/control-schema.js.map +1 -1
  11. package/dist/enrolled-machine-store-file.d.ts +13 -0
  12. package/dist/enrolled-machine-store-file.js +41 -0
  13. package/dist/enrolled-machine-store-file.js.map +1 -0
  14. package/dist/enrolled-machine-store.d.ts +81 -0
  15. package/dist/enrolled-machine-store.js +225 -0
  16. package/dist/enrolled-machine-store.js.map +1 -0
  17. package/dist/file-durable-slot.js +5 -3
  18. package/dist/file-durable-slot.js.map +1 -1
  19. package/dist/index.d.ts +5 -3
  20. package/dist/index.js +23 -5
  21. package/dist/index.js.map +1 -1
  22. package/dist/membership-connection-gater.d.ts +15 -1
  23. package/dist/membership-connection-gater.js +9 -3
  24. package/dist/membership-connection-gater.js.map +1 -1
  25. package/dist/node-local-snapshot.d.ts +6 -0
  26. package/dist/node-local-snapshot.js +7 -1
  27. package/dist/node-local-snapshot.js.map +1 -1
  28. package/dist/{strand-backfill.d.ts → peer-join-backfill.d.ts} +49 -20
  29. package/dist/{strand-backfill.js → peer-join-backfill.js} +133 -52
  30. package/dist/peer-join-backfill.js.map +1 -0
  31. package/dist/relay-addrs.d.ts +73 -0
  32. package/dist/relay-addrs.js +195 -0
  33. package/dist/relay-addrs.js.map +1 -1
  34. package/dist/strand-database.d.ts +12 -0
  35. package/dist/strand-database.js +16 -0
  36. package/dist/strand-database.js.map +1 -1
  37. package/dist/strand-formation-manager.d.ts +12 -0
  38. package/dist/strand-formation-manager.js +10 -3
  39. package/dist/strand-formation-manager.js.map +1 -1
  40. package/dist/strand-formation-protocol.d.ts +76 -2
  41. package/dist/strand-formation-protocol.js +78 -2
  42. package/dist/strand-formation-protocol.js.map +1 -1
  43. package/dist/strand-instance-manager.d.ts +147 -14
  44. package/dist/strand-instance-manager.js +225 -45
  45. package/dist/strand-instance-manager.js.map +1 -1
  46. package/dist/strand-membership-writer.d.ts +12 -0
  47. package/dist/strand-membership-writer.js +23 -1
  48. package/dist/strand-membership-writer.js.map +1 -1
  49. package/dist/strand-network-config.d.ts +84 -0
  50. package/dist/strand-network-config.js +136 -0
  51. package/dist/strand-network-config.js.map +1 -0
  52. package/dist/strand-revocation-enforcer.d.ts +392 -0
  53. package/dist/strand-revocation-enforcer.js +533 -0
  54. package/dist/strand-revocation-enforcer.js.map +1 -0
  55. package/dist/strand-solicitation.d.ts +7 -0
  56. package/dist/strand-solicitation.js +8 -2
  57. package/dist/strand-solicitation.js.map +1 -1
  58. package/dist/strand-watcher.js +6 -1
  59. package/dist/strand-watcher.js.map +1 -1
  60. package/dist/types.d.ts +210 -16
  61. package/dist/types.js +7 -1
  62. package/dist/types.js.map +1 -1
  63. package/package.json +16 -8
  64. package/src/cadre-node.ts +6353 -5603
  65. package/src/control-database.ts +53 -9
  66. package/src/control-schema.ts +30 -2
  67. package/src/enrolled-machine-store-file.ts +43 -0
  68. package/src/enrolled-machine-store.ts +280 -0
  69. package/src/file-durable-slot.ts +5 -3
  70. package/src/index.ts +52 -10
  71. package/src/membership-connection-gater.ts +9 -3
  72. package/src/node-local-snapshot.ts +13 -1
  73. package/src/peer-addr-book.ts +251 -250
  74. package/src/{strand-backfill.ts → peer-join-backfill.ts} +478 -389
  75. package/src/relay-addrs.ts +218 -0
  76. package/src/strand-database.ts +17 -0
  77. package/src/strand-formation-manager.ts +22 -3
  78. package/src/strand-formation-protocol.ts +808 -692
  79. package/src/strand-instance-manager.ts +317 -54
  80. package/src/strand-membership-writer.ts +23 -1
  81. package/src/strand-network-config.ts +172 -0
  82. package/src/strand-revocation-enforcer.ts +653 -0
  83. package/src/strand-solicitation.ts +484 -471
  84. package/src/strand-watcher.ts +319 -314
  85. package/src/types.ts +1554 -1354
  86. package/dist/strand-backfill.js.map +0 -1
@@ -1,389 +1,478 @@
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 BlockCommitProof, 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
- /**
128
- * The cohort commit proof retained for each block's pushed revision, where one exists.
129
- *
130
- * A receiver running the default `requirePushCertificate: true` REJECTS a block pushed
131
- * without one, so this is what makes peer-join catch-up land at all — a push carrying only
132
- * `meta` is the legacy shape and is refused. Sparse deliberately: a block whose proof was
133
- * never retained is still offered with its meta, which is the only thing that lets a
134
- * receiver migrating with the flag off land the replica at this node's revision rather than
135
- * a fabricated rev 1. Upstream's rule is the other direction and holds here by construction:
136
- * a proof is never attached WITHOUT its meta, because both are written from the same
137
- * `latest` in one place.
138
- */
139
- proofs: Record<string, BlockCommitProof>;
140
- bytes: number;
141
- }
142
-
143
- /**
144
- * Base64 wire size of a raw buffer — `pushBlocks` base64-encodes each block into the JSON
145
- * request, so the protocol cap must be judged against the encoded size, not the raw bytes.
146
- */
147
- function base64WireBytes(rawBytes: number): number {
148
- return Math.ceil(rawBytes / 3) * 4;
149
- }
150
-
151
- /**
152
- * Copies every block in one strand's own raw store to each peer its libp2p node connects
153
- * to, so a peer that joined the strand after blocks were committed still ends up holding
154
- * them physically (the receiver persists each push via `saveReplicatedBlock`, which is
155
- * monotonic and idempotent — crossing pushes from both ends cannot regress a revision).
156
- *
157
- * Best-effort throughout: nothing here throws into a libp2p event handler or into
158
- * `buildStrandRuntime`; a failed chunk is logged and the run continues. A peer is marked
159
- * fully caught up ONLY after a run with no thrown chunk and an empty `missing` list, so
160
- * the next `connection:open` from a peer whose catch-up failed retries it.
161
- */
162
- export class StrandBackfill {
163
- private readonly config: Required<StrandBackfillConfig>;
164
- private readonly createPushClient: (peerId: PeerId) => StrandBackfillPushClient;
165
- private started = false;
166
- private stopped = false;
167
- /** Peers fully caught up this runtime (never retried until the runtime is rebuilt). */
168
- private readonly done = new Set<string>();
169
- /** Peers with a catch-up currently running (suppresses concurrent duplicates). */
170
- private readonly inFlight = new Set<string>();
171
- /** Pending per-peer debounce timers, cleared on stop. */
172
- private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();
173
- private readonly onConnectionOpen: (evt: CustomEvent<Connection>) => void;
174
- private loggedNoListBlockIds = false;
175
-
176
- constructor(private readonly deps: StrandBackfillDeps, config?: StrandBackfillConfig) {
177
- this.config = { ...DEFAULT_STRAND_BACKFILL, ...config };
178
- this.createPushClient = deps.createPushClient
179
- ?? ((peerId) => new BlockTransferClient(peerId, deps.peerNetwork, deps.protocolPrefix));
180
- this.onConnectionOpen = (evt) => this.schedulePeer(evt.detail.remotePeer);
181
- }
182
-
183
- /** Subscribe to connection:open AND schedule a catch-up for peers already connected. */
184
- start(): void {
185
- if (this.started || this.stopped || !this.config.enabled) return;
186
- this.started = true;
187
- this.deps.libp2p.addEventListener('connection:open', this.onConnectionOpen);
188
- // A runtime rebuilt over live connections (resumeStrand) never sees their
189
- // connection:open, so walk what is already connected once.
190
- const existing = this.deps.libp2p.getConnections();
191
- for (const connection of existing) {
192
- this.schedulePeer(connection.remotePeer);
193
- }
194
- log('[%s] started (%d peer(s) already connected)', this.deps.strandId, existing.length);
195
- }
196
-
197
- /** Unsubscribe, clear timers; in-flight runs observe the stopped flag and bail. */
198
- stop(): void {
199
- if (this.stopped) return;
200
- this.stopped = true;
201
- if (this.started) {
202
- this.deps.libp2p.removeEventListener('connection:open', this.onConnectionOpen);
203
- }
204
- for (const timer of this.timers.values()) {
205
- clearTimeout(timer);
206
- }
207
- this.timers.clear();
208
- log('[%s] stopped', this.deps.strandId);
209
- }
210
-
211
- /** Debounced entry point for connection churn: one run per peer per settle window. */
212
- private schedulePeer(peerId: PeerId): void {
213
- const key = peerId.toString();
214
- if (this.stopped || this.done.has(key) || this.inFlight.has(key)) return;
215
- const existing = this.timers.get(key);
216
- if (existing) clearTimeout(existing);
217
- this.timers.set(key, setTimeout(() => {
218
- this.timers.delete(key);
219
- void this.catchUpPeer(peerId);
220
- }, this.config.debounceMs));
221
- }
222
-
223
- /**
224
- * Run one peer's catch-up now, bypassing the debounce. Never rejects. Returns an
225
- * all-zero result without pushing when the peer is already caught up, already being
226
- * caught up, or this backfill is stopped.
227
- */
228
- async catchUpPeer(peerId: PeerId): Promise<StrandBackfillResult> {
229
- const key = peerId.toString();
230
- if (this.stopped || this.done.has(key) || this.inFlight.has(key)) {
231
- return emptyResult();
232
- }
233
- this.inFlight.add(key);
234
- try {
235
- const { result, clean } = await this.runCatchUp(peerId);
236
- // NOTE: a run that hit `maxBlocks` is still "clean" and still memoizes the peer, so
237
- // the tail past the ceiling never reaches it. Deliberate: enumeration is not
238
- // resumable, so not memoizing would re-push the same prefix on every reconnect
239
- // without ever advancing. Loud in the log below (capped > 0). If a strand's store can
240
- // realistically exceed maxBlocks, the fix is a resumable cursor, not either policy.
241
- if (clean && !this.stopped) {
242
- this.done.add(key);
243
- }
244
- log('[%s] catch-up peer=%s offered=%d accepted=%d rejected=%d uncommitted=%d unmaterialized=%d capped=%d oversized=%d done=%s',
245
- this.deps.strandId, key, result.offered, result.accepted, result.rejected.length,
246
- result.uncommitted, result.unmaterialized, result.capped, result.oversized.length, clean);
247
- return result;
248
- } catch (error) {
249
- // runCatchUp already contains a per-chunk catch; this guards the enumeration and
250
- // metadata reads too — a backfill fault must never surface through a libp2p event.
251
- log('[%s] catch-up peer=%s failed: %o', this.deps.strandId, key, error);
252
- return emptyResult();
253
- } finally {
254
- this.inFlight.delete(key);
255
- }
256
- }
257
-
258
- /** The actual copy. `clean` = every chunk pushed and the remote persisted every block. */
259
- private async runCatchUp(peerId: PeerId): Promise<{ result: StrandBackfillResult; clean: boolean }> {
260
- const result = emptyResult();
261
- const { storage } = this.deps;
262
-
263
- if (!storage.listBlockIds) {
264
- if (!this.loggedNoListBlockIds) {
265
- this.loggedNoListBlockIds = true;
266
- log('[%s] raw storage does not implement listBlockIds(); backfill is inert', this.deps.strandId);
267
- }
268
- return { result, clean: false };
269
- }
270
-
271
- const client = this.createPushClient(peerId);
272
- const encoder = new TextEncoder();
273
- let chunk: Chunk = { ids: [], buffers: [], meta: {}, proofs: {}, bytes: 0 };
274
- let chunkFailed = false;
275
- let anyChunkDelivered = false;
276
- /**
277
- * A peer that has answered no push at all, and failed one, is not reachable on this
278
- * protocol — abandon rather than spend a dial timeout per remaining chunk. Once ONE
279
- * push has been answered the peer demonstrably speaks it, so a later failure is a
280
- * transient blip and the rest of the store is still worth pushing.
281
- */
282
- const peerUnreachable = (): boolean => chunkFailed && !anyChunkDelivered;
283
-
284
- const flush = async (): Promise<void> => {
285
- if (chunk.ids.length === 0) return;
286
- const { ids, buffers, meta, proofs } = chunk;
287
- chunk = { ids: [], buffers: [], meta: {}, proofs: {}, bytes: 0 };
288
- try {
289
- // ONE certification value rather than two arguments, so a caller cannot pair a proof
290
- // for one revision with meta for another — both were written from the same `latest`.
291
- const response = await client.pushBlocks(ids, buffers, 'replication',
292
- { blockMeta: meta, blockProofs: proofs }, {
293
- dialTimeoutMs: this.config.dialTimeoutMs,
294
- responseTimeoutMs: this.config.responseTimeoutMs
295
- });
296
- anyChunkDelivered = true;
297
- const missing = new Set(response.missing);
298
- for (const id of ids) {
299
- if (missing.has(id)) {
300
- result.rejected.push(id);
301
- } else {
302
- result.accepted += 1;
303
- }
304
- }
305
- if (response.missing.length > 0) {
306
- log('[%s] peer=%s rejected %d block(s): %o', this.deps.strandId, peerId.toString(), response.missing.length, response.missing);
307
- }
308
- } catch (error) {
309
- chunkFailed = true;
310
- log('[%s] push to peer=%s failed for %d block(s): %s', this.deps.strandId, peerId.toString(), ids.length, (error as Error).message);
311
- }
312
- };
313
-
314
- for await (const blockId of storage.listBlockIds()) {
315
- if (this.stopped) break;
316
- if (result.offered >= this.config.maxBlocks) {
317
- // Past the ceiling: count what is left (id enumeration only — no more reads or
318
- // pushes) so the cap is loud in the end-of-run log rather than silent.
319
- result.capped += 1;
320
- continue;
321
- }
322
-
323
- const metadata = await storage.getMetadata(blockId);
324
- const latest = metadata?.latest;
325
- if (!latest) {
326
- result.uncommitted += 1;
327
- continue;
328
- }
329
- // NOTE: a block whose latest revision is a DELETE materializes to nothing (a
330
- // tombstone), so it is skipped here — a peer that joins after such a delete never
331
- // receives the tombstone from this path and relies on read repair for it. Fine
332
- // while nothing deletes whole blocks pre-join; if the whole-store coverage gate in
333
- // strand-membership-closed-strand-e2e ever reports a tombstone residue, teach this
334
- // to push the promoted delete transform instead of skipping.
335
- const block = await storage.getMaterializedBlock(blockId, latest.actionId);
336
- if (!block) {
337
- result.unmaterialized += 1;
338
- log('[%s] block=%s has latest rev %d but no materialized content; skipped', this.deps.strandId, blockId, latest.rev);
339
- continue;
340
- }
341
-
342
- const buffer = encoder.encode(JSON.stringify(block));
343
- // NOTE: MAX_BLOCK_MESSAGE_BYTES caps the whole framed request, not one block, and
344
- // this test ignores the request envelope (ids array, blockMeta, JSON punctuation).
345
- // A lone block within a few KiB of the cap therefore still ships and is rejected by
346
- // the receiver's length-prefix decoder — a permanent chunk failure for that peer. No
347
- // block in a strand comes close today; if one ever can, subtract a measured envelope
348
- // allowance here rather than raising the cap.
349
- if (base64WireBytes(buffer.length) >= MAX_BLOCK_MESSAGE_BYTES) {
350
- result.oversized.push(blockId);
351
- log('[%s] block=%s is %d bytes (%d on the wire) — exceeds the %d-byte protocol cap alone; skipped',
352
- this.deps.strandId, blockId, buffer.length, base64WireBytes(buffer.length), MAX_BLOCK_MESSAGE_BYTES);
353
- continue;
354
- }
355
-
356
- // Flush before adding when this block would overflow either budget. A single block
357
- // larger than maxChunkBytes still ships — alone, in its own chunk.
358
- if (chunk.ids.length > 0
359
- && (chunk.ids.length + 1 > this.config.maxChunkBlocks || chunk.bytes + buffer.length > this.config.maxChunkBytes)) {
360
- await flush();
361
- if (this.stopped || peerUnreachable()) break;
362
- }
363
- chunk.ids.push(blockId);
364
- chunk.buffers.push(buffer);
365
- chunk.meta[blockId] = { rev: latest.rev, actionId: latest.actionId };
366
- // Read the proof for EXACTLY the revision being pushed, from the same `latest` the meta
367
- // above was written from. Absent is normal (nothing retained a proof for that revision);
368
- // the block still ships with its meta and the receiver decides.
369
- const proof = await storage.getBlockProof(blockId, latest.rev);
370
- if (proof) {
371
- chunk.proofs[blockId] = proof;
372
- }
373
- chunk.bytes += buffer.length;
374
- result.offered += 1;
375
- }
376
-
377
- if (!this.stopped && !peerUnreachable()) {
378
- await flush();
379
- }
380
-
381
- if (result.capped > 0) {
382
- log('[%s] peer=%s catch-up CAPPED at %d blocks; %d block id(s) not attempted',
383
- this.deps.strandId, peerId.toString(), this.config.maxBlocks, result.capped);
384
- }
385
-
386
- const clean = !chunkFailed && result.rejected.length === 0;
387
- return { result, clean };
388
- }
389
- }
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 BlockCommitProof, type IRawStorage } from '@optimystic/db-p2p';
5
+
6
+ // Peer-join whole-store block catch-up, shared by the STRAND networks and the CONTROL
7
+ // network. On `connection:open` (debounced) it pushes every committed, materialized block
8
+ // in the local raw store to the new peer, so a machine that joined after blocks were
9
+ // committed still ends up physically holding them. Optimystic has no cohort-join catch-up
10
+ // of its own; a block committed while its writer was alone has exactly one holder forever
11
+ // without this (named collection-header blocks are written once, at collection creation,
12
+ // and their revision never moves again — so no later commit ever carries them anywhere).
13
+ //
14
+ // NOTE: this copies the WHOLE local store to every newly connected peer, which is right
15
+ // while a network is one party's handful of machines (see docs/architecture.md →
16
+ // Replication cluster size — the control network replicates to the whole party by intent,
17
+ // and "On a strand, the machine count is not a party count"). If these meshes ever get
18
+ // large, filter the pushed set by FRET cohort responsibility for each block id instead of
19
+ // pushing everything.
20
+ //
21
+ // NOTE: this lives in cadre-core only because `../optimystic` is read-only from this repo.
22
+ // If Optimystic ever grows a cohort-join catch-up of its own, delete this module rather
23
+ // than running two.
24
+ //
25
+ // Membership — the one place the two networks differ, expressed as the optional
26
+ // `authorizePeer` dep:
27
+ //
28
+ // - STRAND networks pass none. Anything connected on a strand's own libp2p network already
29
+ // receives cohort replicas of new commits, so pushing older blocks to it exposes nothing
30
+ // new; adding a gate would diverge from what ordinary replication already does there. A
31
+ // peer that does NOT speak the strand's block-transfer protocol (a bare circuit relay or
32
+ // bootstrap node the strand node also connects to) cannot receive anything: the protocol
33
+ // id is namespaced per strand, so the dial fails and the push is dropped.
34
+ // - The CONTROL network MUST pass one, because that argument does not carry over: its
35
+ // inbound connection gate deliberately admits non-members in several states (an
36
+ // un-enrolled node taking its seed, an open enrollment window, an outstanding
37
+ // invitation, configured bootstrap/relay peers — see docs/architecture.md, the
38
+ // control-network inbound connection gate). Pushing the whole control store to such a
39
+ // peer would hand a stranger the party's entire membership, addresses and strand list.
40
+ // `CadreNode` passes `isAuthorizedMember`; the gate is consulted at PUSH time, not at
41
+ // schedule time, and fails closed on a thrown check. A denied run is not memoized, so
42
+ // the peer is retried on its next `connection:open` — or sooner, via
43
+ // `scheduleConnectedPeers()` on a membership change (the production join order is
44
+ // connect-then-authorize, so the denial at dial time is the expected first pass).
45
+ //
46
+ // NOTE: a failing dial to a non-speaking peer costs one dial timeout per connection:open
47
+ // from such a peer, and is never memoized (only clean runs are). Bounded today by the
48
+ // debounce plus the unreachable-peer bail in `runCatchUp` — one dial per event, not one
49
+ // per chunk. If a node ever holds many such connections, or the enumeration ahead of the
50
+ // first chunk gets expensive, pre-check `libp2p.peerStore` for this network's
51
+ // block-transfer protocol before enumerating.
52
+ //
53
+ // NOTE: a run that fails is retried only when that peer next opens a connection (or, with
54
+ // an `authorizePeer` gate wired, when `scheduleConnectedPeers()` is driven). Over a stable
55
+ // connection a transient push failure therefore leaves the peer partially copied until the
56
+ // next reconnect (read repair still covers reads meanwhile). If these meshes ever hold
57
+ // long-lived connections where that matters, re-arm the debounce timer with a backoff on a
58
+ // non-clean run instead of waiting for connection:open.
59
+
60
+ const log = debug('sereus:cadre:peer-join-backfill');
61
+
62
+ /**
63
+ * The block-transfer protocol's hard cap on one length-prefixed message. Mirrors
64
+ * `MAX_BLOCK_MESSAGE_BYTES` in `@optimystic/db-p2p`'s `protocol-limits.ts` (8 MiB), which
65
+ * that package does not re-export from its index — keep the two in sync if upstream ever
66
+ * changes it or starts exporting it.
67
+ */
68
+ export const MAX_BLOCK_MESSAGE_BYTES = 8 * 1024 * 1024;
69
+
70
+ /** Tuning for the per-peer catch-up. Every field optional; defaults in {@link DEFAULT_PEER_JOIN_BACKFILL}. */
71
+ export interface PeerJoinBackfillConfig {
72
+ /** Default true. False disables the catch-up entirely (the pre-existing behaviour). */
73
+ enabled?: boolean;
74
+ /** Settle time after a connection opens before catching that peer up, ms. Default 1000. */
75
+ debounceMs?: number;
76
+ /** Ceiling on blocks copied in one catch-up. Default 10_000. Reaching it is LOGGED, never silent. */
77
+ maxBlocks?: number;
78
+ /** Soft byte budget per push message. Default 1 MiB. Protocol hard cap is {@link MAX_BLOCK_MESSAGE_BYTES} (8 MiB). */
79
+ maxChunkBytes?: number;
80
+ /** Max blocks per push message. Default 64. */
81
+ maxChunkBlocks?: number;
82
+ /** Per-push dial deadline, ms. Default 3000 (matches SpreadOnChurnMonitor). */
83
+ dialTimeoutMs?: number;
84
+ /** Per-push response deadline, ms. Default 10_000 (matches SpreadOnChurnMonitor). */
85
+ responseTimeoutMs?: number;
86
+ }
87
+
88
+ /** The resolved defaults every {@link PeerJoinBackfill} starts from. */
89
+ export const DEFAULT_PEER_JOIN_BACKFILL: Required<PeerJoinBackfillConfig> = {
90
+ enabled: true,
91
+ debounceMs: 1000,
92
+ maxBlocks: 10_000,
93
+ maxChunkBytes: 1024 * 1024,
94
+ maxChunkBlocks: 64,
95
+ dialTimeoutMs: 3000,
96
+ responseTimeoutMs: 10_000
97
+ };
98
+
99
+ /**
100
+ * The one capability the catch-up needs from a transfer client. Structural (rather than
101
+ * the concrete `BlockTransferClient`) so unit tests can capture pushes without dialing
102
+ * libp2p — see {@link PeerJoinBackfillDeps.createPushClient}.
103
+ */
104
+ export type PeerJoinBackfillPushClient = Pick<BlockTransferClient, 'pushBlocks'>;
105
+
106
+ export interface PeerJoinBackfillDeps {
107
+ /** Log tag naming which network this catch-up serves (a strand id, or `control-<partyId>`). */
108
+ label: string;
109
+ /** The libp2p node of the network being caught up — source of connection events and peer ids. */
110
+ libp2p: Libp2p;
111
+ /** `node.keyNetwork`, the IPeerNetwork BlockTransferClient dials through. */
112
+ peerNetwork: IPeerNetwork;
113
+ /** This network's own raw block store — the same instance handed to the libp2p node. */
114
+ storage: IRawStorage;
115
+ /** Must equal the prefix the receiver registered its handler under: `/optimystic/<networkName>`. */
116
+ protocolPrefix: string;
117
+ /**
118
+ * Membership gate, consulted at PUSH time (fails closed on a throw). Absent = push to
119
+ * every connected peer — correct for strand networks, NEVER for the control network;
120
+ * see the module comment for why the strand no-gate argument does not carry over.
121
+ */
122
+ authorizePeer?: (peerId: string) => Promise<boolean>;
123
+ /**
124
+ * Test seam: build the per-peer push client. Defaults to a real
125
+ * `BlockTransferClient` over {@link peerNetwork} + {@link protocolPrefix}.
126
+ */
127
+ createPushClient?: (peerId: PeerId) => PeerJoinBackfillPushClient;
128
+ }
129
+
130
+ /** What one peer's catch-up actually did. Returned for tests and logged at the end of each run. */
131
+ export interface PeerJoinBackfillResult {
132
+ /** Blocks offered: had a committed `latest` AND materialized content locally. */
133
+ offered: number;
134
+ /** Blocks the remote reported it persisted. */
135
+ accepted: number;
136
+ /** Block ids the remote reported in `missing` (parse or persist failure on its side). */
137
+ rejected: string[];
138
+ /** Skipped: metadata has no `latest` (pending-only — not yet a durability claim here). */
139
+ uncommitted: number;
140
+ /** Skipped: `latest` exists but no materialized block is stored for that actionId. */
141
+ unmaterialized: number;
142
+ /** Not attempted because `maxBlocks` was reached. */
143
+ capped: number;
144
+ /** Skipped: a single block whose wire size alone exceeds {@link MAX_BLOCK_MESSAGE_BYTES}. */
145
+ oversized: string[];
146
+ /** True when the `authorizePeer` gate refused (or threw) — nothing was pushed, peer not memoized. */
147
+ denied: boolean;
148
+ }
149
+
150
+ function emptyResult(): PeerJoinBackfillResult {
151
+ return { offered: 0, accepted: 0, rejected: [], uncommitted: 0, unmaterialized: 0, capped: 0, oversized: [], denied: false };
152
+ }
153
+
154
+ /** One in-flight push message being accumulated. */
155
+ interface Chunk {
156
+ ids: string[];
157
+ buffers: Uint8Array[];
158
+ meta: Record<string, { rev: number; actionId: ActionId }>;
159
+ /**
160
+ * The cohort commit proof retained for each block's pushed revision, where one exists.
161
+ *
162
+ * A receiver running the default `requirePushCertificate: true` REJECTS a block pushed
163
+ * without one, so this is what makes peer-join catch-up land at all — a push carrying only
164
+ * `meta` is the legacy shape and is refused. Sparse deliberately: a block whose proof was
165
+ * never retained is still offered with its meta, which is the only thing that lets a
166
+ * receiver migrating with the flag off land the replica at this node's revision rather than
167
+ * a fabricated rev 1. Upstream's rule is the other direction and holds here by construction:
168
+ * a proof is never attached WITHOUT its meta, because both are written from the same
169
+ * `latest` in one place.
170
+ */
171
+ proofs: Record<string, BlockCommitProof>;
172
+ bytes: number;
173
+ }
174
+
175
+ /**
176
+ * Base64 wire size of a raw buffer — `pushBlocks` base64-encodes each block into the JSON
177
+ * request, so the protocol cap must be judged against the encoded size, not the raw bytes.
178
+ */
179
+ function base64WireBytes(rawBytes: number): number {
180
+ return Math.ceil(rawBytes / 3) * 4;
181
+ }
182
+
183
+ /**
184
+ * Copies every block in one network's own raw store to each peer its libp2p node connects
185
+ * to, so a peer that joined the network after blocks were committed still ends up holding
186
+ * them physically (the receiver persists each push via `saveReplicatedBlock`, which is
187
+ * monotonic and idempotent — crossing pushes from both ends cannot regress a revision).
188
+ *
189
+ * Best-effort throughout: nothing here throws into a libp2p event handler or into a
190
+ * runtime bring-up; a failed chunk is logged and the run continues. A peer is marked
191
+ * fully caught up ONLY after a run with no thrown chunk and an empty `missing` list, so
192
+ * the next `connection:open` from a peer whose catch-up failed retries it.
193
+ */
194
+ export class PeerJoinBackfill {
195
+ private readonly config: Required<PeerJoinBackfillConfig>;
196
+ private readonly createPushClient: (peerId: PeerId) => PeerJoinBackfillPushClient;
197
+ private started = false;
198
+ private stopped = false;
199
+ /** Peers fully caught up this runtime (never retried until the runtime is rebuilt). */
200
+ private readonly done = new Set<string>();
201
+ /** Peers with a catch-up currently running (suppresses concurrent duplicates). */
202
+ private readonly inFlight = new Set<string>();
203
+ /**
204
+ * Peers whose (re-)schedule arrived while their OWN run was in flight, replayed once
205
+ * that run finishes. Load-bearing for the gated path: the gate's authorization check is
206
+ * a control-database read, so the window between it and the run's end is wide enough for
207
+ * the very membership commit that would have authorized the peer to land inside it —
208
+ * dropping that schedule (rather than deferring it) leaves the denied peer waiting for a
209
+ * reconnect, which is exactly what the re-arm exists to avoid.
210
+ */
211
+ private readonly rearmAfterFlight = new Set<string>();
212
+ /** Pending per-peer debounce timers, cleared on stop. */
213
+ private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();
214
+ private readonly onConnectionOpen: (evt: CustomEvent<Connection>) => void;
215
+ private loggedNoListBlockIds = false;
216
+
217
+ constructor(private readonly deps: PeerJoinBackfillDeps, config?: PeerJoinBackfillConfig) {
218
+ this.config = { ...DEFAULT_PEER_JOIN_BACKFILL, ...config };
219
+ this.createPushClient = deps.createPushClient
220
+ ?? ((peerId) => new BlockTransferClient(peerId, deps.peerNetwork, deps.protocolPrefix));
221
+ this.onConnectionOpen = (evt) => this.schedulePeer(evt.detail.remotePeer);
222
+ }
223
+
224
+ /** Subscribe to connection:open AND schedule a catch-up for peers already connected. */
225
+ start(): void {
226
+ if (this.started || this.stopped || !this.config.enabled) return;
227
+ this.started = true;
228
+ this.deps.libp2p.addEventListener('connection:open', this.onConnectionOpen);
229
+ // A runtime rebuilt over live connections (resumeStrand) never sees their
230
+ // connection:open, so walk what is already connected once.
231
+ const scheduled = this.scheduleConnectedPeers();
232
+ log('[%s] started (%d peer(s) already connected)', this.deps.label, scheduled);
233
+ }
234
+
235
+ /** Unsubscribe, clear timers; in-flight runs observe the stopped flag and bail. */
236
+ stop(): void {
237
+ if (this.stopped) return;
238
+ this.stopped = true;
239
+ if (this.started) {
240
+ this.deps.libp2p.removeEventListener('connection:open', this.onConnectionOpen);
241
+ }
242
+ for (const timer of this.timers.values()) {
243
+ clearTimeout(timer);
244
+ }
245
+ this.timers.clear();
246
+ this.rearmAfterFlight.clear();
247
+ log('[%s] stopped', this.deps.label);
248
+ }
249
+
250
+ /**
251
+ * (Re-)schedule a debounced catch-up for every currently-connected peer not yet caught
252
+ * up. Idempotent and cheap (caught-up peers are skipped before any timer is set, and a
253
+ * peer whose run is in flight is deferred to the end of that run rather than dropped).
254
+ * Driven by {@link start}, and — on a gated network — by the embedder whenever
255
+ * membership changes, so a peer whose first pass was denied (connected before it was
256
+ * authorized: the production join order) is retried without waiting for a reconnect.
257
+ * Returns how many distinct peers were considered (for the start() log) — a peer holding
258
+ * several connections is one peer, and is scheduled once.
259
+ */
260
+ scheduleConnectedPeers(): number {
261
+ if (this.stopped) return 0;
262
+ const peers = new Set<string>();
263
+ for (const connection of this.deps.libp2p.getConnections()) {
264
+ const key = connection.remotePeer.toString();
265
+ if (peers.has(key)) continue;
266
+ peers.add(key);
267
+ this.schedulePeer(connection.remotePeer);
268
+ }
269
+ return peers.size;
270
+ }
271
+
272
+ /** Debounced entry point for connection churn: one run per peer per settle window. */
273
+ private schedulePeer(peerId: PeerId): void {
274
+ const key = peerId.toString();
275
+ if (this.stopped || this.done.has(key)) return;
276
+ if (this.inFlight.has(key)) {
277
+ // Defer rather than drop: the running pass may already be past its gate check (or
278
+ // past the block this schedule was meant to carry), so replay it when that pass ends.
279
+ this.rearmAfterFlight.add(key);
280
+ return;
281
+ }
282
+ const existing = this.timers.get(key);
283
+ if (existing) clearTimeout(existing);
284
+ this.timers.set(key, setTimeout(() => {
285
+ this.timers.delete(key);
286
+ void this.catchUpPeer(peerId);
287
+ }, this.config.debounceMs));
288
+ }
289
+
290
+ /**
291
+ * Run one peer's catch-up now, bypassing the debounce. Never rejects. Returns an
292
+ * all-zero result without pushing when the peer is already caught up, already being
293
+ * caught up, or this backfill is stopped.
294
+ */
295
+ async catchUpPeer(peerId: PeerId): Promise<PeerJoinBackfillResult> {
296
+ const key = peerId.toString();
297
+ if (this.stopped || this.done.has(key) || this.inFlight.has(key)) {
298
+ return emptyResult();
299
+ }
300
+ this.inFlight.add(key);
301
+ try {
302
+ const { result, clean } = await this.runCatchUp(peerId);
303
+ // NOTE: a run that hit `maxBlocks` is still "clean" and still memoizes the peer, so
304
+ // the tail past the ceiling never reaches it. Deliberate: enumeration is not
305
+ // resumable, so not memoizing would re-push the same prefix on every reconnect
306
+ // without ever advancing. Loud in the log below (capped > 0). If a store can
307
+ // realistically exceed maxBlocks, the fix is a resumable cursor, not either policy.
308
+ if (clean && !this.stopped) {
309
+ this.done.add(key);
310
+ }
311
+ log('[%s] catch-up peer=%s offered=%d accepted=%d rejected=%d uncommitted=%d unmaterialized=%d capped=%d oversized=%d denied=%s done=%s',
312
+ this.deps.label, key, result.offered, result.accepted, result.rejected.length,
313
+ result.uncommitted, result.unmaterialized, result.capped, result.oversized.length, result.denied, clean);
314
+ return result;
315
+ } catch (error) {
316
+ // runCatchUp already contains a per-chunk catch; this guards the enumeration and
317
+ // metadata reads too — a backfill fault must never surface through a libp2p event.
318
+ log('[%s] catch-up peer=%s failed: %o', this.deps.label, key, error);
319
+ return emptyResult();
320
+ } finally {
321
+ this.inFlight.delete(key);
322
+ // Replay a schedule that arrived mid-run. `schedulePeer` re-checks `done`, so a run
323
+ // that finished clean re-arms nothing; a denied or failed one gets its retry.
324
+ if (this.rearmAfterFlight.delete(key)) {
325
+ this.schedulePeer(peerId);
326
+ }
327
+ }
328
+ }
329
+
330
+ /** The actual copy. `clean` = every chunk pushed and the remote persisted every block. */
331
+ private async runCatchUp(peerId: PeerId): Promise<{ result: PeerJoinBackfillResult; clean: boolean }> {
332
+ const result = emptyResult();
333
+ const { storage } = this.deps;
334
+
335
+ // The membership gate, judged at push time (never at schedule time — authorization can
336
+ // change during the debounce window in either direction). Fails CLOSED on a throw: a
337
+ // gate that cannot answer must not leak the store. A denied run is not clean, so the
338
+ // peer is retried later rather than memoized as caught up.
339
+ if (this.deps.authorizePeer) {
340
+ let authorized = false;
341
+ try {
342
+ authorized = await this.deps.authorizePeer(peerId.toString());
343
+ } catch (error) {
344
+ log('[%s] authorizePeer(%s) threw — treating as denied: %o', this.deps.label, peerId.toString(), error);
345
+ }
346
+ if (!authorized) {
347
+ result.denied = true;
348
+ return { result, clean: false };
349
+ }
350
+ }
351
+
352
+ if (!storage.listBlockIds) {
353
+ if (!this.loggedNoListBlockIds) {
354
+ this.loggedNoListBlockIds = true;
355
+ log('[%s] raw storage does not implement listBlockIds(); backfill is inert', this.deps.label);
356
+ }
357
+ return { result, clean: false };
358
+ }
359
+
360
+ const client = this.createPushClient(peerId);
361
+ const encoder = new TextEncoder();
362
+ let chunk: Chunk = { ids: [], buffers: [], meta: {}, proofs: {}, bytes: 0 };
363
+ let chunkFailed = false;
364
+ let anyChunkDelivered = false;
365
+ /**
366
+ * A peer that has answered no push at all, and failed one, is not reachable on this
367
+ * protocol — abandon rather than spend a dial timeout per remaining chunk. Once ONE
368
+ * push has been answered the peer demonstrably speaks it, so a later failure is a
369
+ * transient blip and the rest of the store is still worth pushing.
370
+ */
371
+ const peerUnreachable = (): boolean => chunkFailed && !anyChunkDelivered;
372
+
373
+ const flush = async (): Promise<void> => {
374
+ if (chunk.ids.length === 0) return;
375
+ const { ids, buffers, meta, proofs } = chunk;
376
+ chunk = { ids: [], buffers: [], meta: {}, proofs: {}, bytes: 0 };
377
+ try {
378
+ // ONE certification value rather than two arguments, so a caller cannot pair a proof
379
+ // for one revision with meta for another — both were written from the same `latest`.
380
+ const response = await client.pushBlocks(ids, buffers, 'replication',
381
+ { blockMeta: meta, blockProofs: proofs }, {
382
+ dialTimeoutMs: this.config.dialTimeoutMs,
383
+ responseTimeoutMs: this.config.responseTimeoutMs
384
+ });
385
+ anyChunkDelivered = true;
386
+ const missing = new Set(response.missing);
387
+ for (const id of ids) {
388
+ if (missing.has(id)) {
389
+ result.rejected.push(id);
390
+ } else {
391
+ result.accepted += 1;
392
+ }
393
+ }
394
+ if (response.missing.length > 0) {
395
+ log('[%s] peer=%s rejected %d block(s): %o', this.deps.label, peerId.toString(), response.missing.length, response.missing);
396
+ }
397
+ } catch (error) {
398
+ chunkFailed = true;
399
+ log('[%s] push to peer=%s failed for %d block(s): %s', this.deps.label, peerId.toString(), ids.length, (error as Error).message);
400
+ }
401
+ };
402
+
403
+ for await (const blockId of storage.listBlockIds()) {
404
+ if (this.stopped) break;
405
+ if (result.offered >= this.config.maxBlocks) {
406
+ // Past the ceiling: count what is left (id enumeration only — no more reads or
407
+ // pushes) so the cap is loud in the end-of-run log rather than silent.
408
+ result.capped += 1;
409
+ continue;
410
+ }
411
+
412
+ const metadata = await storage.getMetadata(blockId);
413
+ const latest = metadata?.latest;
414
+ if (!latest) {
415
+ result.uncommitted += 1;
416
+ continue;
417
+ }
418
+ // NOTE: a block whose latest revision is a DELETE materializes to nothing (a
419
+ // tombstone), so it is skipped here — a peer that joins after such a delete never
420
+ // receives the tombstone from this path and relies on read repair for it. Fine
421
+ // while nothing deletes whole blocks pre-join; if the whole-store coverage gate in
422
+ // strand-membership-closed-strand-e2e ever reports a tombstone residue, teach this
423
+ // to push the promoted delete transform instead of skipping.
424
+ const block = await storage.getMaterializedBlock(blockId, latest.actionId);
425
+ if (!block) {
426
+ result.unmaterialized += 1;
427
+ log('[%s] block=%s has latest rev %d but no materialized content; skipped', this.deps.label, blockId, latest.rev);
428
+ continue;
429
+ }
430
+
431
+ const buffer = encoder.encode(JSON.stringify(block));
432
+ // NOTE: MAX_BLOCK_MESSAGE_BYTES caps the whole framed request, not one block, and
433
+ // this test ignores the request envelope (ids array, blockMeta, JSON punctuation).
434
+ // A lone block within a few KiB of the cap therefore still ships and is rejected by
435
+ // the receiver's length-prefix decoder — a permanent chunk failure for that peer. No
436
+ // block comes close today; if one ever can, subtract a measured envelope allowance
437
+ // here rather than raising the cap.
438
+ if (base64WireBytes(buffer.length) >= MAX_BLOCK_MESSAGE_BYTES) {
439
+ result.oversized.push(blockId);
440
+ log('[%s] block=%s is %d bytes (%d on the wire) — exceeds the %d-byte protocol cap alone; skipped',
441
+ this.deps.label, blockId, buffer.length, base64WireBytes(buffer.length), MAX_BLOCK_MESSAGE_BYTES);
442
+ continue;
443
+ }
444
+
445
+ // Flush before adding when this block would overflow either budget. A single block
446
+ // larger than maxChunkBytes still ships — alone, in its own chunk.
447
+ if (chunk.ids.length > 0
448
+ && (chunk.ids.length + 1 > this.config.maxChunkBlocks || chunk.bytes + buffer.length > this.config.maxChunkBytes)) {
449
+ await flush();
450
+ if (this.stopped || peerUnreachable()) break;
451
+ }
452
+ chunk.ids.push(blockId);
453
+ chunk.buffers.push(buffer);
454
+ chunk.meta[blockId] = { rev: latest.rev, actionId: latest.actionId };
455
+ // Read the proof for EXACTLY the revision being pushed, from the same `latest` the meta
456
+ // above was written from. Absent is normal (nothing retained a proof for that revision);
457
+ // the block still ships with its meta and the receiver decides.
458
+ const proof = await storage.getBlockProof(blockId, latest.rev);
459
+ if (proof) {
460
+ chunk.proofs[blockId] = proof;
461
+ }
462
+ chunk.bytes += buffer.length;
463
+ result.offered += 1;
464
+ }
465
+
466
+ if (!this.stopped && !peerUnreachable()) {
467
+ await flush();
468
+ }
469
+
470
+ if (result.capped > 0) {
471
+ log('[%s] peer=%s catch-up CAPPED at %d blocks; %d block id(s) not attempted',
472
+ this.deps.label, peerId.toString(), this.config.maxBlocks, result.capped);
473
+ }
474
+
475
+ const clean = !chunkFailed && result.rejected.length === 0;
476
+ return { result, clean };
477
+ }
478
+ }