@johnhenry/browsermesh-apps 0.1.1 → 0.3.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 (50) hide show
  1. package/README.md +443 -1
  2. package/package.json +18 -3
  3. package/src/agent-runtime.mjs +342 -0
  4. package/src/chunk-replication.mjs +751 -0
  5. package/src/cloud-storage-backend.mjs +932 -0
  6. package/src/cloud-storage.mjs +799 -0
  7. package/src/compat.mjs +98 -0
  8. package/src/gpu-kernel.mjs +242 -0
  9. package/src/gpu.mjs +101 -7
  10. package/src/grant-log.mjs +840 -0
  11. package/src/index.mjs +32 -2
  12. package/src/kernel-mesh.mjs +56 -0
  13. package/src/key-distribution.mjs +525 -0
  14. package/src/manifest-sync.mjs +363 -0
  15. package/src/mesh-agent-swarm.mjs +376 -0
  16. package/src/mesh-bootstrap.mjs +1481 -0
  17. package/src/mesh-compute.mjs +397 -0
  18. package/src/mesh-dht.mjs +182 -0
  19. package/src/mesh-fetch.mjs +246 -0
  20. package/src/mesh-hardening.mjs +226 -0
  21. package/src/mesh-health.mjs +282 -0
  22. package/src/mesh-keepalive.mjs +353 -0
  23. package/src/mesh-kv.mjs +673 -0
  24. package/src/mesh-orchestrator-tools.mjs +251 -0
  25. package/src/mesh-orchestrator.mjs +343 -0
  26. package/src/mesh-relay-backend.mjs +289 -0
  27. package/src/mesh-relay-host.mjs +362 -0
  28. package/src/mesh-rpc.mjs +300 -0
  29. package/src/mesh-service.mjs +403 -0
  30. package/src/mesh-swarm.mjs +677 -0
  31. package/src/mesh-sync.mjs +253 -0
  32. package/src/mesh-timestamp.mjs +265 -0
  33. package/src/mesh-torrent.mjs +683 -0
  34. package/src/mesh-verification.mjs +367 -0
  35. package/src/mesh-websocket.mjs +722 -0
  36. package/src/observability-bridge.mjs +453 -0
  37. package/src/orchestrator.mjs +18 -5
  38. package/src/peer-agent-swarm.mjs +12 -1
  39. package/src/peer-chat.mjs +230 -61
  40. package/src/peer-compute.mjs +66 -3
  41. package/src/peer-escrow.mjs +350 -1
  42. package/src/peer-files.mjs +362 -168
  43. package/src/peer-ipfs.mjs +205 -10
  44. package/src/peer-node.mjs +127 -19
  45. package/src/peer-registry.mjs +242 -18
  46. package/src/peer-routing.mjs +369 -5
  47. package/src/peer-terminal.mjs +400 -130
  48. package/src/signaling.mjs +231 -0
  49. package/src/webrtc-negotiator.mjs +209 -0
  50. package/src/peer-session.mjs +0 -937
@@ -0,0 +1,751 @@
1
+ /**
2
+ * chunk-replication.mjs -- Phase G of the mesh-native-services plan
3
+ * ("CloudStorage: S3-like object storage"): moves actual ciphertext CHUNK
4
+ * BYTES between peers, closing the gap Phases E/F deliberately left open --
5
+ * Phase F (`manifest-sync.mjs`) replicates the manifest CRDT (the
6
+ * `{chunks: [{cid, iv}], ...}` pointer), and Phase E (`key-distribution.mjs`)
7
+ * delivers the bucket's symmetric key, but neither phase ever moves the
8
+ * chunk-store bytes a manifest entry's `cid`s point at. A peer that receives
9
+ * a manifest entry via Phase F (or is designated a replica but was offline
10
+ * when a `put()` happened) has a pointer to content it does not yet hold.
11
+ * This file is what actually moves those bytes.
12
+ *
13
+ * Built as a `MeshService` (Phase C, `mesh-service.mjs`), following
14
+ * `manifest-sync.mjs`/`key-distribution.mjs` as the closest precedents: wire
15
+ * payloads travel over `ctx.onIncomingData()`/`ctx.sendTo()`, filtered by
16
+ * `envelope.type` (default `'chunk-replication'`), on the SAME dispatch bus
17
+ * every other `MeshService` in this family uses.
18
+ *
19
+ * ---------------------------------------------------------------------------
20
+ * IMPORTANT DEVIATION FROM THE PLAN'S ORIGINAL TEXT (read this first):
21
+ *
22
+ * The plan's own Phase G section says to "investigate peer-files.mjs's
23
+ * existing FileClient/PeerSession-based transfer machinery first for a
24
+ * server-side counterpart to extend". That investigation happened (tracked
25
+ * as github.com/johnhenry/browsermesh issue #84) and found that
26
+ * `peer-files.mjs`/`PeerSession`/`SessionManager` form an ENTIRELY SEPARATE,
27
+ * unwired session architecture that the real `PeerNode` composition root
28
+ * (which every phase A-F of this plan builds on, and every real caller of
29
+ * `createMeshNode()`/`attachService()` uses) never touches -- there is no
30
+ * live bridge from a `PeerNode`'s sessions to a `PeerSession`. Building this
31
+ * phase on top of `PeerSession`/`FileClient` would require first solving
32
+ * issue #84's much larger "bridge two independent session architectures"
33
+ * problem, which is explicitly out of scope for this phase. This file
34
+ * therefore builds BOTH the control-plane and the data-plane directly on
35
+ * `PeerNode.sendTo()`/`onIncomingData()` (via `ctx.sendTo()`/
36
+ * `ctx.onIncomingData()`), the exact same mechanism every other phase in
37
+ * this plan (C through F) already uses -- not a new bespoke transport, and
38
+ * not `PeerSession`.
39
+ *
40
+ * ---------------------------------------------------------------------------
41
+ * TRANSPORT DESIGN: one `sendTo()` call per chunk, not a smaller-frame
42
+ * streaming protocol.
43
+ *
44
+ * `CloudStorageBackend.#encryptAndChunk()` (Phase B) already caps every
45
+ * chunk at 256KB (`TRANSFER_DEFAULTS.chunkSize`, `browsermesh-sync/src/
46
+ * files.mjs`) before it ever reaches the chunk store. Since that upper
47
+ * bound already exists on the write side, this phase's data-plane simply
48
+ * base64-encodes one whole ciphertext chunk into one JSON envelope and
49
+ * sends it with one `ctx.sendTo()` call (`chunk-push` for eager replication,
50
+ * `chunk-fetch-response` for lazy pull) -- no further fragmentation, no
51
+ * reassembly state machine, no flow-control window. This is a deliberate
52
+ * "simplest thing that works" choice, not an oversight:
53
+ *
54
+ * - Pro: reuses the exact same envelope-type-filtered dispatch every
55
+ * control message already uses, so there is exactly one transport
56
+ * concept in this file, not two. A 256KB ciphertext chunk base64-encodes
57
+ * to ~342KB of JSON payload -- comfortably inside what every transport
58
+ * this family targets (WebRTC data channels, in-memory loopback) can
59
+ * move in a single message today.
60
+ * - Con (throughput tradeoff, stated plainly): base64 inflates the wire
61
+ * size by ~33%, and JSON.stringify/parse of a several-hundred-KB string
62
+ * is not free CPU-wise. There is also no windowing/pipelining here --
63
+ * `replicatePut()` fires all (target x chunk) pushes concurrently via
64
+ * `Promise.all`, but a single slow/unresponsive peer's chunks are not
65
+ * retried or resumed mid-flight; a failed push simply never gets acked,
66
+ * and that peer is absent from `replicatedTo`.
67
+ * - This is fine as a v1: none of the OTHER phases' contracts (the
68
+ * durability flag's shape, the manifest CRDT, the GrantLog) depend on
69
+ * HOW bytes moved. A future revision (raw binary WebRTC datachannel
70
+ * frames instead of base64-in-JSON, real backpressure/windowing,
71
+ * resumable transfer) can replace this file's internals without
72
+ * touching any other phase.
73
+ *
74
+ * ---------------------------------------------------------------------------
75
+ * Wire protocol -- six message kinds sharing one envelope `type` (default
76
+ * `'chunk-replication'`), every message scoped to one `bucketId`:
77
+ *
78
+ * Eager push (writer -> admin-designated replica), fired from the
79
+ * `CloudStorageBackend.setReplicationHook()` hook this service installs,
80
+ * itself invoked by `#opPut()` after the local write is already durable:
81
+ * `{ type, bucketId, kind: 'chunk-push', requestId, cid, data }`
82
+ * -- `data` is base64 ciphertext for one chunk.
83
+ * `{ type, bucketId, kind: 'replicate-ack', requestId, cid }`
84
+ * -- sent back by the replica once `putChunkRaw()` verifies and
85
+ * stores the chunk.
86
+ *
87
+ * Lazy pull / read-repair, step 1 (broadcast "who has X"):
88
+ * `{ type, bucketId, kind: 'chunk-have-query', queryId, cid }`
89
+ * `{ type, bucketId, kind: 'chunk-have-response', queryId, cid, has: true }`
90
+ * -- a peer that does NOT have the chunk stays silent (see "Known
91
+ * limitation" below) rather than sending a negative response;
92
+ * the requester's `queryHave()` simply times out if nobody answers.
93
+ *
94
+ * Lazy pull / read-repair, step 2 (fetch from a peer that answered "have"):
95
+ * `{ type, bucketId, kind: 'chunk-fetch-request', requestId, cid }`
96
+ * `{ type, bucketId, kind: 'chunk-fetch-response', requestId, cid, data }`
97
+ * -- or `{ ..., error: 'unauthorized' | 'not found' }` instead of `data`.
98
+ *
99
+ * None of these messages carry a signature. This matches `manifest-sync.mjs`'s
100
+ * own established precedent (its module doc comment's "Known, deliberate
101
+ * limitation" section): the trust boundary is the connection-authenticated
102
+ * `fromPubKey` `ctx.onIncomingData()` already supplies (established at
103
+ * session/transport level), not an additional per-message signature layer.
104
+ * What IS cryptographically verified is the CHUNK CONTENT itself --
105
+ * `CloudStorageBackend.putChunkRaw()` (Phase G's own addition to that file)
106
+ * recomputes the CID from received bytes and refuses to store anything that
107
+ * doesn't hash to the CID it was sent under, so a chunk's *integrity* is
108
+ * verified independent of who relayed it, exactly the property content-
109
+ * addressing is supposed to buy.
110
+ *
111
+ * ---------------------------------------------------------------------------
112
+ * AUTHORIZATION on every chunk transfer (this phase's core security
113
+ * property, mirroring `manifest-sync.mjs`'s "gate before merge/serve, never
114
+ * after" discipline):
115
+ *
116
+ * - `chunk-push` (inbound, we are a designated replica receiving pushed
117
+ * content): the sender must currently hold `s3:<bucketId>:write` --
118
+ * accepting arbitrary ciphertext from a peer with no write access would
119
+ * let anyone plant content in this bucket's chunk store under a CID of
120
+ * their choosing (content-addressing prevents CID *spoofing*, not
121
+ * unauthorized *origination*).
122
+ * - `chunk-have-query` / `chunk-fetch-request` (inbound, someone wants to
123
+ * know about or download a chunk): the sender must currently hold
124
+ * `s3:<bucketId>:read` -- checked via `registry.checkAccess()` BEFORE
125
+ * `hasChunkRaw()`/`getChunkRaw()` is ever consulted, so an unauthorized
126
+ * peer cannot even confirm a chunk exists, let alone download it, even
127
+ * if it somehow learned a valid CID from elsewhere (e.g. a leaked
128
+ * manifest snapshot).
129
+ *
130
+ * Known, deliberate limitation (silence-on-"don't have it", stated
131
+ * explicitly rather than left implicit): `chunk-have-query` never sends a
132
+ * negative response -- both "you're unauthorized" and "I don't have it"
133
+ * look identical to the requester (silence). This is intentional: an
134
+ * unauthorized peer probing for a chunk's existence should not be able to
135
+ * distinguish "denied" from "not found" (that distinction itself would leak
136
+ * information about the bucket's replica topology to someone with no access
137
+ * at all). The requester's `queryHave()` is timeout-bounded regardless (see
138
+ * "Never hangs" below), so this costs latency, not correctness.
139
+ *
140
+ * ---------------------------------------------------------------------------
141
+ * DURABILITY CONTRACT (`put()`'s `{durability, replicatedTo}`, the plan's
142
+ * explicit, non-negotiable choice -- restated here because this file is
143
+ * what actually computes it):
144
+ *
145
+ * `replicatePut()` (installed as `CloudStorageBackend`'s replication hook)
146
+ * is invoked by `#opPut()` AFTER the local encrypted write is already
147
+ * durable -- it can never make `put()` fail, and its own timeout
148
+ * (`replicationTimeoutMs`, default 2000ms -- see the constant's own doc
149
+ * comment for the reasoning) bounds how long `put()`'s response is ever
150
+ * delayed. `durability` is `'replicated'` if `replicatedTo` (peers that
151
+ * fully acknowledged EVERY chunk of this write) is non-empty, `'local-only'`
152
+ * otherwise -- including the case where there are zero currently-connected
153
+ * `replica`-scoped peers at all, which returns immediately without waiting
154
+ * out the timeout (nothing to wait for).
155
+ *
156
+ * ---------------------------------------------------------------------------
157
+ * LAZY PULL / READ-REPAIR (`fetchChunk()`/`syncMissingChunks()`, exposed on
158
+ * this service's `api`):
159
+ *
160
+ * `fetchChunk(cid)` is the mechanism this phase provides; deciding WHEN to
161
+ * call it (e.g. a `get()` that finds a manifest entry but a missing chunk)
162
+ * is deliberately left to a higher layer -- the plan's own Phase H
163
+ * ("falls back to a remote peer request... when content isn't held
164
+ * locally") is explicitly where that wiring belongs, not here. This keeps
165
+ * this phase's scope to "provide the mechanism", matching how Phase F
166
+ * provides manifest merge and Phase E provides key delivery without either
167
+ * of those phases deciding when the application calls `get()`.
168
+ *
169
+ * `syncMissingChunks()` is the "reconnecting designated replica catching
170
+ * up" case: it walks the current manifest snapshot, collects every
171
+ * referenced (non-tombstoned) CID, and calls `fetchChunk()` for anything
172
+ * missing locally -- best-effort, never throws (a single unreachable chunk
173
+ * is logged and skipped, not fatal to the rest of the sweep). Like
174
+ * `fetchChunk()` itself, WHEN to call this (on reconnect, on being granted
175
+ * `replica`, on a timer) is a caller/integration decision, not decided here.
176
+ *
177
+ * Both never hang: `queryHave()` and `fetchFrom()` are both timeout-bounded
178
+ * (`haveQueryTimeoutMs` / `fetchTimeoutMs`), and `fetchChunk()` throws a
179
+ * plain `Error` -- never leaves a caller waiting forever -- when either no
180
+ * peer answers "have" at all, or every peer that claimed to have it fails
181
+ * to actually deliver it.
182
+ *
183
+ * ---------------------------------------------------------------------------
184
+ * Observability events (`ctx.emit()`, Phase 1 of the mesh-KV-and-
185
+ * observability plan -- see `mesh-service.mjs`'s module doc comment for the
186
+ * full convention this follows). Four curated events, not a mechanical
187
+ * conversion of this file's `onLog` calls:
188
+ *
189
+ * - `chunk-replication:chunk-replicated` `{bucketId, cids, replicatedTo}`
190
+ * -- one `replicatePut()` call finished with `durability: 'replicated'`
191
+ * (at least one designated replica fully acknowledged every pushed cid).
192
+ * - `chunk-replication:read-repair` `{bucketId, cid, from}` -- a missing
193
+ * chunk was successfully fetched from a peer via lazy pull
194
+ * (`fetchChunk()`), the mechanism `syncMissingChunks()`/a `get()` miss
195
+ * both rely on.
196
+ * - `chunk-replication:push-rejected` `{bucketId, from, cid}` -- an
197
+ * inbound `chunk-push` was refused because the sender did not currently
198
+ * hold `write` on this bucket -- the core security property this file's
199
+ * "AUTHORIZATION on every chunk transfer" section describes.
200
+ * - `chunk-replication:fetch-exhausted` `{bucketId, cid}` -- `fetchChunk()`
201
+ * gave up on a cid because either nobody answered "have" or every
202
+ * responder failed to actually deliver it.
203
+ *
204
+ * No browser-only imports at module level.
205
+ */
206
+
207
+ /** Default `envelope.type` used to route chunk-replication payloads on the shared `onIncomingData()` bus. */
208
+ const DEFAULT_ENVELOPE_TYPE = 'chunk-replication'
209
+
210
+ /**
211
+ * How long `replicatePut()` waits for admin-designated replica peers to
212
+ * acknowledge a push before giving up and reporting whatever subset (if
213
+ * any) actually confirmed in time. Chosen as "long enough for a real
214
+ * WebRTC/loopback round trip of a base64'd 256KB-ish chunk under ordinary
215
+ * load, short enough that a `put()` call feels responsive rather than
216
+ * hung" -- this is a starting default, not a tuned constant; callers with
217
+ * different latency/throughput expectations should override it via
218
+ * `createChunkReplicationService({ replicationTimeoutMs })`.
219
+ */
220
+ const DEFAULT_REPLICATION_TIMEOUT_MS = 2000
221
+
222
+ /** How long `queryHave()` waits for the FIRST "have" response (it resolves immediately once one arrives) before giving up on a chunk with no known holder. */
223
+ const DEFAULT_HAVE_QUERY_TIMEOUT_MS = 1500
224
+
225
+ /** How long `fetchFrom()` waits for one specific peer's `chunk-fetch-response` before treating that peer as unreachable and (in `fetchChunk()`) trying the next candidate. */
226
+ const DEFAULT_FETCH_TIMEOUT_MS = 3000
227
+
228
+ // ---------------------------------------------------------------------------
229
+ // Base64 helpers -- deliberately duplicated rather than shared, matching
230
+ // this family's established convention of small, self-contained per-file
231
+ // helpers (see cloud-storage-backend.mjs's / key-distribution.mjs's own
232
+ // identical duplication).
233
+ // ---------------------------------------------------------------------------
234
+
235
+ /** @param {Uint8Array} bytes @returns {string} */
236
+ function toBase64(bytes) {
237
+ if (typeof Buffer !== 'undefined') return Buffer.from(bytes).toString('base64')
238
+ let bin = ''
239
+ for (const b of bytes) bin += String.fromCharCode(b)
240
+ return btoa(bin)
241
+ }
242
+
243
+ /** @param {string} str @returns {Uint8Array} */
244
+ function fromBase64(str) {
245
+ if (typeof Buffer !== 'undefined') return new Uint8Array(Buffer.from(str, 'base64'))
246
+ const bin = atob(str)
247
+ const bytes = new Uint8Array(bin.length)
248
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
249
+ return bytes
250
+ }
251
+
252
+ /** @param {string} bucketId @returns {string} The scope-grammar resource string GrantLog/PeerRegistry expect (`s3:<bucketId>`). */
253
+ function resourceFor(bucketId) {
254
+ return `s3:${bucketId}`
255
+ }
256
+
257
+ // ---------------------------------------------------------------------------
258
+ // createChunkReplicationService
259
+ // ---------------------------------------------------------------------------
260
+
261
+ /**
262
+ * Build a `MeshService` descriptor (`mesh-service.mjs`, Phase C) that
263
+ * replicates one bucket's chunk-store bytes -- both eager push-to-replicas
264
+ * (installed as `cloudStorageBackend`'s replication hook, driving `put()`'s
265
+ * `{durability, replicatedTo}`) and lazy pull/read-repair (`api.fetchChunk()`/
266
+ * `api.syncMissingChunks()`). See this file's module doc comment for the
267
+ * full protocol/authorization/durability writeup.
268
+ *
269
+ * @param {object} opts
270
+ * @param {string} opts.bucketId - Bucket identifier. The ACL resource
271
+ * checked is `s3:<bucketId>`, matching `manifest-sync.mjs`/`grant-log.mjs`.
272
+ * @param {import('./cloud-storage-backend.mjs').CloudStorageBackend} opts.cloudStorageBackend
273
+ * Must expose `hasChunkRaw()`/`getChunkRaw()`/`putChunkRaw()`/
274
+ * `setReplicationHook()`/`getManifestSnapshot()` (Phase G's own additions
275
+ * plus Phase F's manifest-snapshot surface).
276
+ * @param {string} [opts.envelopeType='chunk-replication']
277
+ * @param {number} [opts.replicationTimeoutMs=2000] - See `DEFAULT_REPLICATION_TIMEOUT_MS`'s doc comment.
278
+ * @param {number} [opts.haveQueryTimeoutMs=1500] - See `DEFAULT_HAVE_QUERY_TIMEOUT_MS`'s doc comment.
279
+ * @param {number} [opts.fetchTimeoutMs=3000] - See `DEFAULT_FETCH_TIMEOUT_MS`'s doc comment.
280
+ * @param {Function} [opts.onLog]
281
+ * @returns {import('./mesh-service.mjs').MeshService}
282
+ */
283
+ export function createChunkReplicationService({
284
+ bucketId,
285
+ cloudStorageBackend,
286
+ envelopeType = DEFAULT_ENVELOPE_TYPE,
287
+ replicationTimeoutMs = DEFAULT_REPLICATION_TIMEOUT_MS,
288
+ haveQueryTimeoutMs = DEFAULT_HAVE_QUERY_TIMEOUT_MS,
289
+ fetchTimeoutMs = DEFAULT_FETCH_TIMEOUT_MS,
290
+ onLog,
291
+ } = {}) {
292
+ if (!bucketId || typeof bucketId !== 'string') {
293
+ throw new Error('createChunkReplicationService: bucketId is required and must be a non-empty string')
294
+ }
295
+ if (!cloudStorageBackend ||
296
+ typeof cloudStorageBackend.hasChunkRaw !== 'function' ||
297
+ typeof cloudStorageBackend.getChunkRaw !== 'function' ||
298
+ typeof cloudStorageBackend.putChunkRaw !== 'function' ||
299
+ typeof cloudStorageBackend.setReplicationHook !== 'function') {
300
+ throw new Error('createChunkReplicationService: cloudStorageBackend is required (a CloudStorageBackend instance with Phase G raw-chunk methods)')
301
+ }
302
+
303
+ const resource = resourceFor(bucketId)
304
+ const log = onLog || (() => {})
305
+
306
+ return {
307
+ name: `chunk-replication:${bucketId}`,
308
+
309
+ attach(peerNode, ctx) {
310
+ let reqSeq = 0
311
+ /** Monotonic-ish unique id for correlating a request/query with its eventual response(s). */
312
+ const nextRequestId = () => `${peerNode?.podId || 'local'}:${Date.now()}:${++reqSeq}`
313
+
314
+ /**
315
+ * @type {Map<string, {expectedByTarget: Map<string, Set<string>>,
316
+ * ackedByTarget: Map<string, Set<string>>, fullyAcked: Set<string>,
317
+ * resolve: () => void, timer: ReturnType<typeof setTimeout>}>}
318
+ * requestId -> in-flight eager-push tracking, see `replicatePut()`.
319
+ */
320
+ const pendingReplications = new Map()
321
+
322
+ /**
323
+ * @type {Map<string, {responders: Set<string>, timer: ReturnType<typeof setTimeout>}>}
324
+ * queryId -> in-flight "who has X" tracking, see `queryHave()`.
325
+ */
326
+ const pendingHaveQueries = new Map()
327
+
328
+ /**
329
+ * @type {Map<string, {resolve: (bytes: Uint8Array) => void, reject: (err: Error) => void, timer: ReturnType<typeof setTimeout>}>}
330
+ * requestId -> in-flight chunk-fetch tracking, see `fetchFrom()`.
331
+ */
332
+ const pendingFetches = new Map()
333
+
334
+ /** @returns {string[]} Every peer this node's own registry currently considers connected. */
335
+ function connectedPeers() {
336
+ return ctx.registry.listPeers()
337
+ .filter((p) => p && (p.status === 'connected' || p.status === 'authenticated'))
338
+ .map((p) => p.fingerprint)
339
+ .filter(Boolean)
340
+ }
341
+
342
+ /** @param {string} action @returns {string[]} Currently-connected peers holding `s3:<bucketId>:<action>`. */
343
+ function connectedPeersWithAccess(action) {
344
+ return connectedPeers().filter((pubKey) => ctx.registry.checkAccess(pubKey, resource, action).allowed)
345
+ }
346
+
347
+ // -----------------------------------------------------------------
348
+ // Inbound dispatch
349
+ // -----------------------------------------------------------------
350
+ const handlers = {
351
+ 'chunk-push': handleChunkPush,
352
+ 'replicate-ack': handleReplicateAck,
353
+ 'chunk-have-query': handleHaveQuery,
354
+ 'chunk-have-response': handleHaveResponse,
355
+ 'chunk-fetch-request': handleFetchRequest,
356
+ 'chunk-fetch-response': handleFetchResponse,
357
+ }
358
+
359
+ const unsubscribe = ctx.onIncomingData(envelopeType, (fromPubKey, msg) => {
360
+ if (!msg || msg.bucketId !== bucketId || typeof msg.kind !== 'string') return
361
+ const handler = handlers[msg.kind]
362
+ if (!handler) return
363
+ Promise.resolve(handler(fromPubKey, msg)).catch((err) => {
364
+ log('chunk-replication:handler-error', { bucketId, kind: msg.kind, from: fromPubKey, error: err?.message || String(err) })
365
+ })
366
+ })
367
+
368
+ // -----------------------------------------------------------------
369
+ // Receiving a pushed chunk (we are a designated replica)
370
+ // -----------------------------------------------------------------
371
+
372
+ /** @param {string} fromPubKey @param {object} msg */
373
+ async function handleChunkPush(fromPubKey, msg) {
374
+ if (!ctx.registry.checkAccess(fromPubKey, resource, 'write').allowed) {
375
+ log('chunk-replication:reject-unauthorized-push', { bucketId, from: fromPubKey, cid: msg.cid })
376
+ ctx.emit('chunk-replication:push-rejected', { bucketId, from: fromPubKey, cid: msg.cid })
377
+ return
378
+ }
379
+ if (typeof msg.cid !== 'string' || typeof msg.data !== 'string') return
380
+
381
+ try {
382
+ const bytes = fromBase64(msg.data)
383
+ await cloudStorageBackend.putChunkRaw(msg.cid, bytes)
384
+ } catch (err) {
385
+ log('chunk-replication:push-store-failed', { bucketId, from: fromPubKey, cid: msg.cid, error: err?.message || String(err) })
386
+ return
387
+ }
388
+
389
+ try {
390
+ await ctx.sendTo(fromPubKey, envelopeType, { bucketId, kind: 'replicate-ack', requestId: msg.requestId, cid: msg.cid })
391
+ } catch (err) {
392
+ log('chunk-replication:ack-send-failed', { bucketId, to: fromPubKey, cid: msg.cid, error: err?.message || String(err) })
393
+ }
394
+ }
395
+
396
+ /** @param {string} fromPubKey @param {object} msg */
397
+ function handleReplicateAck(fromPubKey, msg) {
398
+ const pending = pendingReplications.get(msg.requestId)
399
+ if (!pending) return
400
+ const expected = pending.expectedByTarget.get(fromPubKey)
401
+ const acked = pending.ackedByTarget.get(fromPubKey)
402
+ if (!expected || !acked || typeof msg.cid !== 'string') return
403
+
404
+ acked.add(msg.cid)
405
+ if (acked.size < expected.size) return
406
+
407
+ pending.fullyAcked.add(fromPubKey)
408
+ if (pending.fullyAcked.size >= pending.expectedByTarget.size) {
409
+ clearTimeout(pending.timer)
410
+ pendingReplications.delete(msg.requestId)
411
+ pending.resolve()
412
+ }
413
+ }
414
+
415
+ // -----------------------------------------------------------------
416
+ // "who has cid X" query/response (lazy pull, step 1)
417
+ // -----------------------------------------------------------------
418
+
419
+ /** @param {string} fromPubKey @param {object} msg */
420
+ async function handleHaveQuery(fromPubKey, msg) {
421
+ if (typeof msg.cid !== 'string' || typeof msg.queryId !== 'string') return
422
+ // Unauthorized peers get silence, identical to "don't have it" --
423
+ // see module doc comment's "Known, deliberate limitation" section.
424
+ if (!ctx.registry.checkAccess(fromPubKey, resource, 'read').allowed) return
425
+
426
+ const has = await cloudStorageBackend.hasChunkRaw(msg.cid)
427
+ if (!has) return
428
+
429
+ await ctx.sendTo(fromPubKey, envelopeType, { bucketId, kind: 'chunk-have-response', queryId: msg.queryId, cid: msg.cid, has: true }).catch((err) => {
430
+ log('chunk-replication:have-response-send-failed', { bucketId, to: fromPubKey, cid: msg.cid, error: err?.message || String(err) })
431
+ })
432
+ }
433
+
434
+ /**
435
+ * @param {string} fromPubKey @param {object} msg
436
+ * The FIRST "have" response resolves `queryHave()`'s wait immediately
437
+ * (see that function's doc comment for why: a broadcast-and-first-
438
+ * response design, not "collect every answer within the window") --
439
+ * `pendingHaveQueries.get()` returning `undefined` on every response
440
+ * after the first is what makes this a no-op rather than a double-
441
+ * resolve.
442
+ */
443
+ function handleHaveResponse(fromPubKey, msg) {
444
+ const pending = pendingHaveQueries.get(msg.queryId)
445
+ if (!pending || !msg.has) return
446
+ pending.responders.add(fromPubKey)
447
+ pending.resolveEarly()
448
+ }
449
+
450
+ // -----------------------------------------------------------------
451
+ // Chunk fetch request/response (lazy pull, step 2)
452
+ // -----------------------------------------------------------------
453
+
454
+ /** @param {string} fromPubKey @param {object} msg */
455
+ async function handleFetchRequest(fromPubKey, msg) {
456
+ if (typeof msg.cid !== 'string' || typeof msg.requestId !== 'string') return
457
+
458
+ if (!ctx.registry.checkAccess(fromPubKey, resource, 'read').allowed) {
459
+ log('chunk-replication:reject-unauthorized-fetch', { bucketId, from: fromPubKey, cid: msg.cid })
460
+ await ctx.sendTo(fromPubKey, envelopeType, { bucketId, kind: 'chunk-fetch-response', requestId: msg.requestId, cid: msg.cid, error: 'unauthorized' }).catch(() => {})
461
+ return
462
+ }
463
+
464
+ const bytes = await cloudStorageBackend.getChunkRaw(msg.cid)
465
+ if (!bytes) {
466
+ await ctx.sendTo(fromPubKey, envelopeType, { bucketId, kind: 'chunk-fetch-response', requestId: msg.requestId, cid: msg.cid, error: 'not found' }).catch(() => {})
467
+ return
468
+ }
469
+
470
+ await ctx.sendTo(fromPubKey, envelopeType, { bucketId, kind: 'chunk-fetch-response', requestId: msg.requestId, cid: msg.cid, data: toBase64(bytes) }).catch((err) => {
471
+ log('chunk-replication:fetch-response-send-failed', { bucketId, to: fromPubKey, cid: msg.cid, error: err?.message || String(err) })
472
+ })
473
+ }
474
+
475
+ /** @param {string} fromPubKey @param {object} msg */
476
+ function handleFetchResponse(fromPubKey, msg) {
477
+ const pending = pendingFetches.get(msg.requestId)
478
+ if (!pending) return
479
+ pendingFetches.delete(msg.requestId)
480
+ clearTimeout(pending.timer)
481
+
482
+ if (msg.error) {
483
+ pending.reject(new Error(`chunk-replication: fetch of ${msg.cid} from ${fromPubKey} failed: ${msg.error}`))
484
+ return
485
+ }
486
+ if (typeof msg.data !== 'string') {
487
+ pending.reject(new Error(`chunk-replication: malformed fetch response from ${fromPubKey}`))
488
+ return
489
+ }
490
+ pending.resolve(fromBase64(msg.data))
491
+ }
492
+
493
+ // -----------------------------------------------------------------
494
+ // Eager push -- the replication hook CloudStorageBackend.put() awaits.
495
+ // -----------------------------------------------------------------
496
+
497
+ /**
498
+ * @param {{key: string, entry: {chunks: Array<{cid: string, iv: string}>}}} info
499
+ * @returns {Promise<{durability: 'local-only'|'replicated', replicatedTo: string[]}>}
500
+ */
501
+ async function replicatePut({ entry }) {
502
+ const targets = connectedPeersWithAccess('replica')
503
+ const cids = [...new Set((entry?.chunks || []).map((c) => c?.cid).filter(Boolean))]
504
+ if (targets.length === 0 || cids.length === 0) {
505
+ return { durability: 'local-only', replicatedTo: [] }
506
+ }
507
+
508
+ const chunkBytesByCid = new Map()
509
+ for (const cid of cids) {
510
+ const bytes = await cloudStorageBackend.getChunkRaw(cid)
511
+ if (bytes) chunkBytesByCid.set(cid, bytes)
512
+ }
513
+
514
+ const requestId = nextRequestId()
515
+ const expectedByTarget = new Map(targets.map((t) => [t, new Set(cids)]))
516
+ const ackedByTarget = new Map(targets.map((t) => [t, new Set()]))
517
+ const fullyAcked = new Set()
518
+
519
+ const donePromise = new Promise((resolve) => {
520
+ const timer = setTimeout(() => {
521
+ pendingReplications.delete(requestId)
522
+ resolve()
523
+ }, replicationTimeoutMs)
524
+ pendingReplications.set(requestId, { expectedByTarget, ackedByTarget, fullyAcked, resolve, timer })
525
+ })
526
+
527
+ const sends = []
528
+ for (const target of targets) {
529
+ for (const cid of cids) {
530
+ const bytes = chunkBytesByCid.get(cid)
531
+ if (!bytes) continue // we don't hold this chunk ourselves -- nothing to push
532
+ sends.push(
533
+ ctx.sendTo(target, envelopeType, { bucketId, kind: 'chunk-push', requestId, cid, data: toBase64(bytes) }).catch((err) => {
534
+ log('chunk-replication:push-send-failed', { bucketId, to: target, cid, error: err?.message || String(err) })
535
+ }),
536
+ )
537
+ }
538
+ }
539
+ await Promise.all(sends)
540
+ await donePromise
541
+
542
+ const replicatedTo = [...fullyAcked]
543
+ if (replicatedTo.length > 0) {
544
+ ctx.emit('chunk-replication:chunk-replicated', { bucketId, cids, replicatedTo })
545
+ }
546
+
547
+ return {
548
+ durability: replicatedTo.length > 0 ? 'replicated' : 'local-only',
549
+ replicatedTo,
550
+ }
551
+ }
552
+
553
+ cloudStorageBackend.setReplicationHook(replicatePut)
554
+
555
+ // -----------------------------------------------------------------
556
+ // Lazy pull / read-repair
557
+ // -----------------------------------------------------------------
558
+
559
+ /**
560
+ * Broadcast "who has cid X" to every currently-connected peer.
561
+ * Broadcast-and-first-response, per the module doc comment's stated
562
+ * design ("doesn't need to be sophisticated"): resolves as soon as
563
+ * the FIRST "have" response arrives (typically one network round
564
+ * trip, not the full timeout window) -- `haveQueryTimeoutMs` is only
565
+ * the upper bound for the "nobody has it" case, where nothing ever
566
+ * arrives to resolve early.
567
+ * @param {string} cid
568
+ * @returns {Promise<string[]>} pubKeys that responded "have" by the
569
+ * time this resolves -- one element in the common case (the first
570
+ * responder), possibly more than one if several answers land in
571
+ * the same event-loop turn, empty if nobody answered in time.
572
+ */
573
+ async function queryHave(cid) {
574
+ // Broadcast to every currently-connected peer, not just ones this
575
+ // requester's own registry already believes hold a grant on this
576
+ // bucket -- requiring the requester to already know who else is
577
+ // authorized would be a real-world chicken-and-egg problem (that
578
+ // knowledge only exists once the GrantLog has fully propagated,
579
+ // which is exactly the kind of ordering this file shouldn't
580
+ // depend on). Safety is unaffected either way: the actual gate is
581
+ // `handleHaveQuery()`'s own `checkAccess()` on the RESPONDER's
582
+ // registry, not any filtering done here -- an unrelated/
583
+ // unauthorized peer that gets asked and cannot answer just stays
584
+ // silent (see the module doc comment's "Known, deliberate
585
+ // limitation" section).
586
+ const candidates = connectedPeers()
587
+ if (candidates.length === 0) return []
588
+
589
+ const queryId = nextRequestId()
590
+ const responders = new Set()
591
+
592
+ const donePromise = new Promise((resolve) => {
593
+ const timer = setTimeout(() => {
594
+ pendingHaveQueries.delete(queryId)
595
+ resolve()
596
+ }, haveQueryTimeoutMs)
597
+ pendingHaveQueries.set(queryId, {
598
+ responders,
599
+ timer,
600
+ resolveEarly() {
601
+ clearTimeout(timer)
602
+ pendingHaveQueries.delete(queryId)
603
+ resolve()
604
+ },
605
+ })
606
+ })
607
+
608
+ await Promise.all(candidates.map((pubKey) =>
609
+ ctx.sendTo(pubKey, envelopeType, { bucketId, kind: 'chunk-have-query', queryId, cid }).catch(() => {}),
610
+ ))
611
+ await donePromise
612
+ return [...responders]
613
+ }
614
+
615
+ /**
616
+ * Request one specific chunk from one specific peer. Timeout-bounded;
617
+ * never hangs.
618
+ * @param {string} pubKey
619
+ * @param {string} cid
620
+ * @returns {Promise<Uint8Array>}
621
+ */
622
+ async function fetchFrom(pubKey, cid) {
623
+ const requestId = nextRequestId()
624
+ const promise = new Promise((resolve, reject) => {
625
+ const timer = setTimeout(() => {
626
+ pendingFetches.delete(requestId)
627
+ reject(new Error(`chunk-replication: fetch of ${cid} from ${pubKey} timed out after ${fetchTimeoutMs}ms`))
628
+ }, fetchTimeoutMs)
629
+ pendingFetches.set(requestId, { resolve, reject, timer })
630
+ })
631
+
632
+ try {
633
+ await ctx.sendTo(pubKey, envelopeType, { bucketId, kind: 'chunk-fetch-request', requestId, cid })
634
+ } catch (err) {
635
+ const pending = pendingFetches.get(requestId)
636
+ if (pending) {
637
+ clearTimeout(pending.timer)
638
+ pendingFetches.delete(requestId)
639
+ }
640
+ throw err
641
+ }
642
+
643
+ return promise
644
+ }
645
+
646
+ /**
647
+ * Fetch and locally persist (via `putChunkRaw()`, which re-verifies
648
+ * the CID) a chunk this peer doesn't hold, from whichever currently-
649
+ * connected, authorized peer answers "have" and successfully delivers
650
+ * it. Resolves immediately (no network round trip) if this peer
651
+ * already holds the chunk. Throws a plain `Error` -- never hangs --
652
+ * if nobody currently connected has it, or every responder fails to
653
+ * actually deliver it.
654
+ * @param {string} cid
655
+ * @returns {Promise<Uint8Array>}
656
+ */
657
+ async function fetchChunk(cid) {
658
+ const already = await cloudStorageBackend.getChunkRaw(cid)
659
+ if (already) return already
660
+
661
+ const responders = await queryHave(cid)
662
+ if (responders.length === 0) {
663
+ ctx.emit('chunk-replication:fetch-exhausted', { bucketId, cid })
664
+ throw new Error(`chunk-replication: no connected peer has chunk ${cid} for bucket ${bucketId}`)
665
+ }
666
+
667
+ let lastErr = null
668
+ for (const pubKey of responders) {
669
+ try {
670
+ const bytes = await fetchFrom(pubKey, cid)
671
+ await cloudStorageBackend.putChunkRaw(cid, bytes)
672
+ ctx.emit('chunk-replication:read-repair', { bucketId, cid, from: pubKey })
673
+ return bytes
674
+ } catch (err) {
675
+ lastErr = err
676
+ log('chunk-replication:fetch-attempt-failed', { bucketId, cid, from: pubKey, error: err?.message || String(err) })
677
+ }
678
+ }
679
+ ctx.emit('chunk-replication:fetch-exhausted', { bucketId, cid })
680
+ throw lastErr || new Error(`chunk-replication: failed to fetch chunk ${cid} from any responder`)
681
+ }
682
+
683
+ /**
684
+ * Walk the current manifest, fetching (via `fetchChunk()`) any
685
+ * referenced, non-tombstoned chunk this peer doesn't hold locally yet.
686
+ * Best-effort catch-up for a reconnecting designated replica, or any
687
+ * authorized reader whose manifest sync arrived before the content
688
+ * did -- never throws; a single unreachable/missing chunk is logged
689
+ * and skipped rather than aborting the rest of the sweep.
690
+ * @returns {Promise<{checked: number, fetched: number, failed: number}>}
691
+ */
692
+ async function syncMissingChunks() {
693
+ const snapshot = await cloudStorageBackend.getManifestSnapshot()
694
+ const entries = snapshot?.entries || {}
695
+ const cids = new Set()
696
+ for (const reg of Object.values(entries)) {
697
+ if (!reg || reg.tombstone) continue
698
+ for (const c of reg.value?.chunks || []) {
699
+ if (c?.cid) cids.add(c.cid)
700
+ }
701
+ }
702
+
703
+ let fetched = 0
704
+ let failed = 0
705
+ for (const cid of cids) {
706
+ const has = await cloudStorageBackend.hasChunkRaw(cid)
707
+ if (has) continue
708
+ try {
709
+ await fetchChunk(cid)
710
+ fetched += 1
711
+ } catch (err) {
712
+ failed += 1
713
+ log('chunk-replication:sync-missing-failed', { bucketId, cid, error: err?.message || String(err) })
714
+ }
715
+ }
716
+ return { checked: cids.size, fetched, failed }
717
+ }
718
+
719
+ const api = {
720
+ bucketId,
721
+ resource,
722
+ fetchChunk,
723
+ syncMissingChunks,
724
+ /** @returns {string[]} Currently-connected peers holding the `replica` scope, per this peer's own registry -- exposed for tests/introspection. */
725
+ listReplicaPeers: () => connectedPeersWithAccess('replica'),
726
+ }
727
+
728
+ return {
729
+ api,
730
+ teardown() {
731
+ unsubscribe()
732
+ cloudStorageBackend.setReplicationHook(null)
733
+
734
+ for (const p of pendingReplications.values()) clearTimeout(p.timer)
735
+ pendingReplications.clear()
736
+ for (const p of pendingHaveQueries.values()) clearTimeout(p.timer)
737
+ pendingHaveQueries.clear()
738
+ for (const p of pendingFetches.values()) clearTimeout(p.timer)
739
+ pendingFetches.clear()
740
+ },
741
+ }
742
+ },
743
+ }
744
+ }
745
+
746
+ export {
747
+ DEFAULT_ENVELOPE_TYPE,
748
+ DEFAULT_REPLICATION_TIMEOUT_MS,
749
+ DEFAULT_HAVE_QUERY_TIMEOUT_MS,
750
+ DEFAULT_FETCH_TIMEOUT_MS,
751
+ }