@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,397 @@
1
+ /**
2
+ * mesh-compute.mjs -- Phase 11 of the browsermesh-app-layer-migration plan
3
+ * (issue #118): wraps `peer-compute.mjs`'s `FederatedCompute` as a
4
+ * `MeshService` (`mesh-service.mjs`, Phase C's `attach()`/`ctx` convention).
5
+ *
6
+ * `FederatedCompute` splits a job into chunks (via a caller-supplied
7
+ * `splitFn`), dispatches each chunk to a peer via an injected
8
+ * `scheduler.dispatch(peerId, job) -> Promise<result>`, retries on failure,
9
+ * and merges completed results (via a caller-supplied `mergeFn`). "Federated
10
+ * compute orchestration... enables 'nomadic supercomputer' and 'compute
11
+ * marketplace' scenarios" (see that file's own header) -- this is exactly
12
+ * the "dispatch code to a remote peer and have it run" scenario issue #86's
13
+ * design pass was about. This file is the mesh wiring that pass unblocked;
14
+ * see issue #86's resolution comment and `mesh-verification.mjs`'s own
15
+ * header comment (Phase 4, the closest possible precedent -- this file
16
+ * mirrors its structure and reasoning almost verbatim, one layer over for
17
+ * compute instead of verification).
18
+ *
19
+ * ---------------------------------------------------------------------------
20
+ * WHAT `FederatedCompute` ITSELF DOES AND DOES NOT DO -- read directly off
21
+ * its constructor and `#dispatchChunk()`:
22
+ *
23
+ * - `scheduler.dispatch(peerId, job) -> Promise<result>` and
24
+ * `scheduler.listAvailablePeers() -> string[]` are REQUIRED constructor
25
+ * dependencies (`FederatedCompute` throws immediately if either is
26
+ * missing). `FederatedCompute` never sends a byte over any network
27
+ * itself -- it is "a pure orchestrator that delegates real execution to
28
+ * an injected scheduler.dispatch() entirely outside the file" (this
29
+ * plan's own "Context" section). `#dispatchChunk()` calls
30
+ * `this.#scheduler.dispatch(chunk.assignee, { chunkId, jobId, index,
31
+ * payload })` and interprets whatever it resolves to as `{ output?,
32
+ * cost? }` (falling back to the raw value as `output` if it isn't
33
+ * shaped that way).
34
+ *
35
+ * THE ONE GENUINELY NEW PIECE OF LOGIC THIS FILE CONTRIBUTES, THEREFORE, IS
36
+ * THE WIRE PROTOCOL BEHIND A REAL `scheduler` -- turning "ask peer X to run
37
+ * this chunk and tell me the result" into actual `ctx.sendTo()` /
38
+ * `ctx.onIncomingData()` traffic, exactly the same shape of gap
39
+ * `mesh-verification.mjs` closes for `VerificationQuorum.submitVerified()`'s
40
+ * `scheduler.dispatch()`. `scheduler.dispatch()` is the NETWORK-COMMUNICATION
41
+ * seam (this file builds a real implementation of it); it is explicitly NOT
42
+ * the "run untrusted code" seam -- that boundary is one layer further in,
43
+ * at `executeFn` below.
44
+ *
45
+ * ---------------------------------------------------------------------------
46
+ * LOCAL/ADMIN vs. PEER-INITIATED -- the actual real flow, traced end to end:
47
+ *
48
+ * - `api.submit(jobSpec)` / `api.cancel(jobId)` / `api.getJob(id)` /
49
+ * `api.listJobs(filter)` / `api.getStats()` are LOCAL calls: this node's
50
+ * own operator/application code deciding to submit (or inspect) a
51
+ * federated compute job. Nothing about calling these requires anything
52
+ * from a remote peer first.
53
+ * - `submit()` -> `scheduler.listAvailablePeers()` (when `jobSpec.peers`
54
+ * isn't supplied) is ALSO local: it consults this node's OWN connected-
55
+ * peer view (this file's default `listAvailablePeers` reads
56
+ * `peerNode.listPeers({status:'connected'})` -- never a remote query).
57
+ * - `submit()` -> `scheduler.dispatch(peerId, job)` is where a PEER gets
58
+ * involved: this file's default `scheduler` sends a real
59
+ * `'compute-request'` envelope to `peerId` and awaits a matching
60
+ * `'compute-response'` reply.
61
+ * - Receiving a `'compute-request'` FROM a peer -- i.e., being asked to
62
+ * RUN SOMEONE ELSE'S CODE -- is the genuinely PEER-INITIATED action, and
63
+ * the one that needs an authorization check: before this node ever
64
+ * executes anyone else's chunk, it gates the request through
65
+ * `ctx.registry.checkAccess(fromPubKey, accessResource, accessAction)`
66
+ * (default resource/action: `'compute'`/`'execute'`), exactly the
67
+ * `registry.checkAccess()` gate `mesh-verification.mjs`/
68
+ * `chunk-replication.mjs`/`mesh-kv.mjs`/`mesh-relay-host.mjs` already
69
+ * established for "a peer wants this node to do something on its
70
+ * behalf." A denied or ungranted peer gets an explicit
71
+ * `{error: 'access denied'}` response (not a silent drop) -- see
72
+ * "WHY AN EXPLICIT DENIAL RESPONSE" below.
73
+ *
74
+ * ---------------------------------------------------------------------------
75
+ * `executeFn` -- REQUIRED FOR THIS NODE TO SERVE AS A COMPUTE WORKER, NOT
76
+ * PROVIDED BY THIS FILE. Even after `checkAccess()` authorizes the
77
+ * requesting peer, "what does it mean to actually run a chunk's payload" is
78
+ * left ENTIRELY to a caller-supplied `opts.executeFn(job) -> Promise<result>`
79
+ * (`job` here is the SAME `{ chunkId, jobId, index, payload }` shape
80
+ * `FederatedCompute` itself hands to `scheduler.dispatch()` -- this file adds
81
+ * no extra wrapping or unwrapping between the wire and `executeFn`). This
82
+ * file never invents a way to execute arbitrary chunk payloads -- no
83
+ * sandboxing, no interpretation, no `eval`, no worker pool -- that is
84
+ * entirely the node operator's problem to solve, exactly the restraint
85
+ * `mesh-verification.mjs`'s `executeFn` already shows for verification jobs,
86
+ * itself modeled on this same module's own pre-migration design ("a pure
87
+ * orchestrator that delegates real execution... entirely outside the
88
+ * file"). Per issue #86's resolved design pass: "Neither `TerminalHost`'s
89
+ * `shell` nor `FederatedCompute`'s `scheduler` has any real implementation
90
+ * anywhere in this repo today... the node operator [is] required to supply
91
+ * their own real executor. No default shell... or scheduler is built as
92
+ * part of this." A node whose operator never supplies `executeFn` can still
93
+ * SUBMIT compute jobs (the requesting role) but cleanly refuses to RUN them
94
+ * (the executing role) -- an authorized peer gets a fast, explicit
95
+ * `{error: 'compute worker not configured to execute jobs'}` rather than a
96
+ * silent hang until the requester's own retry/timeout budget is exhausted.
97
+ *
98
+ * WHY AN EXPLICIT DENIAL RESPONSE (not a silent drop, unlike e.g.
99
+ * `chunk-replication.mjs`'s checkAccess-gated inbound mutation handlers):
100
+ * those are fire-and-forget broadcasts with no waiting caller. Here, the
101
+ * REQUESTING side's `scheduler.dispatch()` Promise is already open and
102
+ * waiting -- silently dropping would just make an unauthorized/unconfigured
103
+ * peer indistinguishable from a slow or dead one, forcing every such case to
104
+ * eat the full `dispatchTimeoutMs` PLUS `FederatedCompute`'s own
105
+ * `#dispatchChunk()` retry loop (`COMPUTE_DEFAULTS.maxRetries`, reassigning
106
+ * the chunk to the next peer each time) before finally failing. An explicit
107
+ * fast rejection changes nothing about eventual correctness (a rejected
108
+ * dispatch is still just a rejected dispatch as far as `#dispatchChunk()`'s
109
+ * retry logic is concerned), only how long a caller waits to find out.
110
+ *
111
+ * ---------------------------------------------------------------------------
112
+ * DEFAULT `listAvailablePeers` -- `peerNode.listPeers({status:'connected'})`
113
+ * (the reachable candidate set -- asking a peer with no live connection to
114
+ * run a chunk cannot work), mapped to each peer's `.fingerprint`, mirroring
115
+ * `mesh-verification.mjs`'s own default `trust.listTrustedPeers()` adapter.
116
+ * Unlike verification, there is no trust filter here by default -- supply
117
+ * `opts.listAvailablePeers` (or pass `scheduler` outright) to add one (e.g.
118
+ * only dispatch compute jobs to peers above some trust threshold), since
119
+ * `FederatedCompute` itself has no notion of trust at all (that's
120
+ * `mesh-verification.mjs`'s job, one layer up, for callers who want BOTH
121
+ * distributed execution AND cross-checked correctness -- see
122
+ * `peer-verification.mjs`'s own header for how the two compose).
123
+ *
124
+ * ---------------------------------------------------------------------------
125
+ * Observability events (`ctx.emit()`, see `mesh-service.mjs`'s module doc
126
+ * comment for the full convention). `FederatedCompute`'s own pre-existing
127
+ * `on`/`off` surface is bridged through verbatim, prefixed `compute:`:
128
+ *
129
+ * - `compute:submitted` -- `FederatedJob` (job accepted, about to split).
130
+ * - `compute:split` -- `{jobId, count}`.
131
+ * - `compute:chunk-assigned` -- `{jobId, chunkId, peerId}`.
132
+ * - `compute:chunk-complete` -- `{jobId, chunkId, result}`.
133
+ * - `compute:chunk-failed` -- `{jobId, chunkId, error}`.
134
+ * - `compute:merged` -- `{jobId, result}`.
135
+ * - `compute:completed` -- `FederatedJob` (final, status 'completed').
136
+ * - `compute:failed` -- `FederatedJob` (final, status 'failed'/'cancelled').
137
+ *
138
+ * Plus this file's own, for the wire layer (mirroring
139
+ * `mesh-verification.mjs`'s `verification:verify-served` /
140
+ * `verification:verify-request-denied`):
141
+ *
142
+ * - `compute:chunk-served` `{from, requestId, ok}` -- this node, AS A
143
+ * WORKER, answered an authorized `'compute-request'` (`ok: true` if
144
+ * `executeFn` succeeded, `false` if it threw).
145
+ * - `compute:chunk-request-denied` `{from, requestId, reason}` -- an
146
+ * inbound `'compute-request'` was rejected before `executeFn` ever ran
147
+ * (`reason`: `'access_denied'` or `'no_executor'`).
148
+ *
149
+ * No browser-only imports at module level.
150
+ */
151
+
152
+ import { FederatedCompute } from './peer-compute.mjs'
153
+
154
+ /** Shared envelope `type` for both compute request/response directions (tagged by `kind`), mirroring `mesh-verification.mjs`'s `'mesh-verification'` shape. */
155
+ const DEFAULT_COMPUTE_ENVELOPE_TYPE = 'mesh-compute'
156
+
157
+ /** How long the default `scheduler.dispatch()` waits for a matching `'compute-response'` before giving up. Independent of `FederatedCompute`'s own `#dispatchChunk()` retry loop (`COMPUTE_DEFAULTS.maxRetries`) -- a per-attempt timeout, not a whole-job one; a never-answering peer's pending entry is always eventually cleaned up and the chunk retried on the next peer. */
158
+ const DEFAULT_COMPUTE_DISPATCH_TIMEOUT_MS = 30000
159
+
160
+ /** Default `resource`/`action` pair checked via `ctx.registry.checkAccess(fromPubKey, resource, action)` before honoring an inbound `'compute-request'`. */
161
+ const DEFAULT_COMPUTE_ACCESS_RESOURCE = 'compute'
162
+ const DEFAULT_COMPUTE_ACCESS_ACTION = 'execute'
163
+
164
+ /**
165
+ * Build a `MeshService` descriptor (`mesh-service.mjs`, Phase C) wrapping
166
+ * `FederatedCompute`. See this file's module doc comment for the full
167
+ * design writeup (what's local/admin-only vs. peer-initiated, why
168
+ * `executeFn` is required-but-not-provided, the default `listAvailablePeers`
169
+ * adapter).
170
+ *
171
+ * @param {object} [opts]
172
+ * @param {{dispatch: (peerId: string, job: object) => Promise<*>, listAvailablePeers: () => string[]}} [opts.scheduler]
173
+ * Defaults to a real mesh-wired scheduler (`ctx.sendTo()` a
174
+ * `'compute-request'`, await a matching `'compute-response'`; peer
175
+ * discovery via `opts.listAvailablePeers` or `peerNode.listPeers()`).
176
+ * Supply your own to bypass the network entirely (e.g. local-only
177
+ * testing) or use a different transport/discovery source.
178
+ * @param {() => string[]} [opts.listAvailablePeers] - Used by the DEFAULT
179
+ * scheduler only (ignored if `opts.scheduler` is supplied directly).
180
+ * Defaults to connected peers' fingerprints via `peerNode.listPeers()`.
181
+ * @param {Function} [opts.splitFn] - Constructor-level default `(payload) =>
182
+ * chunkPayloads[]`, used by `api.submit(jobSpec)` when `jobSpec.splitFn`
183
+ * is omitted. Neither this nor a per-call `jobSpec.splitFn` is required at
184
+ * construction time -- `FederatedCompute.submit()` itself throws (via the
185
+ * missing-function call) if neither is ultimately supplied for a given
186
+ * job, exactly like today's direct `FederatedCompute` usage.
187
+ * @param {Function} [opts.mergeFn] - Constructor-level default
188
+ * `(results[]) => mergedResult`, same override behavior as `splitFn`.
189
+ * @param {(job: {chunkId: string, jobId: string, index: number, payload: *}) => Promise<*>} [opts.executeFn]
190
+ * Called to actually run an inbound, authorized compute chunk and produce
191
+ * this node's result. REQUIRED for this node to usefully serve as a
192
+ * compute worker -- see module doc comment. Omitting it still allows this
193
+ * node to SUBMIT compute jobs (the requesting role).
194
+ * @param {number} [opts.dispatchTimeoutMs=30000] - How long the default
195
+ * `scheduler.dispatch()` waits for a `'compute-response'`.
196
+ * @param {string} [opts.envelopeType='mesh-compute']
197
+ * @param {string} [opts.accessResource='compute'] - `resource` passed to
198
+ * `ctx.registry.checkAccess()` for inbound `'compute-request'`s.
199
+ * @param {string} [opts.accessAction='execute'] - `action` passed to
200
+ * `ctx.registry.checkAccess()` for inbound `'compute-request'`s.
201
+ * @param {Function} [opts.onLog]
202
+ * @returns {import('./mesh-service.mjs').MeshService}
203
+ */
204
+ export function createComputeService({
205
+ scheduler,
206
+ listAvailablePeers,
207
+ splitFn: defaultSplitFn,
208
+ mergeFn: defaultMergeFn,
209
+ executeFn,
210
+ dispatchTimeoutMs = DEFAULT_COMPUTE_DISPATCH_TIMEOUT_MS,
211
+ envelopeType = DEFAULT_COMPUTE_ENVELOPE_TYPE,
212
+ accessResource = DEFAULT_COMPUTE_ACCESS_RESOURCE,
213
+ accessAction = DEFAULT_COMPUTE_ACCESS_ACTION,
214
+ onLog,
215
+ } = {}) {
216
+ const log = onLog || (() => {})
217
+
218
+ return {
219
+ name: 'compute',
220
+
221
+ attach(peerNode, ctx) {
222
+ // -- Default scheduler: real request/response wire protocol -----------
223
+ let reqSeq = 0
224
+ const nextRequestId = () => `${peerNode.podId}:${Date.now()}:${++reqSeq}`
225
+
226
+ /** @type {Map<string, {resolve: Function, reject: Function, timer: ReturnType<typeof setTimeout>}>} */
227
+ const pendingDispatches = new Map()
228
+
229
+ const effectiveListAvailablePeers = listAvailablePeers || (() => {
230
+ const connected = typeof peerNode.listPeers === 'function'
231
+ ? peerNode.listPeers({ status: 'connected' })
232
+ : []
233
+ return connected.map((p) => p.fingerprint).filter(Boolean)
234
+ })
235
+
236
+ const effectiveScheduler = scheduler || {
237
+ dispatch(peerId, job) {
238
+ const requestId = nextRequestId()
239
+ const promise = new Promise((resolve, reject) => {
240
+ const timer = setTimeout(() => {
241
+ pendingDispatches.delete(requestId)
242
+ reject(new Error(`mesh-compute: dispatch to ${peerId} timed out after ${dispatchTimeoutMs}ms`))
243
+ }, dispatchTimeoutMs)
244
+ pendingDispatches.set(requestId, { resolve, reject, timer })
245
+ })
246
+
247
+ ctx.sendTo(peerId, envelopeType, { kind: 'compute-request', requestId, job }).catch((err) => {
248
+ const pending = pendingDispatches.get(requestId)
249
+ if (pending) {
250
+ clearTimeout(pending.timer)
251
+ pendingDispatches.delete(requestId)
252
+ pending.reject(err)
253
+ }
254
+ })
255
+
256
+ return promise
257
+ },
258
+ listAvailablePeers: effectiveListAvailablePeers,
259
+ }
260
+
261
+ const compute = new FederatedCompute({
262
+ scheduler: effectiveScheduler,
263
+ onLog: (level, msg) => log('mesh-compute:internal', { level, msg }),
264
+ })
265
+
266
+ // Bridge FederatedCompute's own pre-existing on()/off() events through
267
+ // ctx.emit() -- see module doc comment's "Observability events" section.
268
+ const bridgedEvents = [
269
+ 'submitted', 'split', 'chunk-assigned', 'chunk-complete',
270
+ 'chunk-failed', 'merged', 'completed', 'failed',
271
+ ]
272
+ const bridgeHandlers = bridgedEvents.map((event) => {
273
+ const handler = (data) => ctx.emit(`compute:${event}`, data)
274
+ compute.on(event, handler)
275
+ return [event, handler]
276
+ })
277
+
278
+ // -- Inbound wire handling ----------------------------------------------
279
+ async function handleComputeRequest(fromPubKey, msg) {
280
+ const { requestId, job } = msg
281
+
282
+ const access = ctx.registry.checkAccess(fromPubKey, accessResource, accessAction)
283
+ if (!access.allowed) {
284
+ ctx.emit('compute:chunk-request-denied', { from: fromPubKey, requestId, reason: 'access_denied' })
285
+ await ctx.sendTo(fromPubKey, envelopeType, { kind: 'compute-response', requestId, error: 'access denied' }).catch((err) => {
286
+ log('mesh-compute:response-send-failed', { to: fromPubKey, requestId, error: err?.message || String(err) })
287
+ })
288
+ return
289
+ }
290
+
291
+ if (typeof executeFn !== 'function') {
292
+ ctx.emit('compute:chunk-request-denied', { from: fromPubKey, requestId, reason: 'no_executor' })
293
+ await ctx.sendTo(fromPubKey, envelopeType, { kind: 'compute-response', requestId, error: 'compute worker not configured to execute jobs' }).catch((err) => {
294
+ log('mesh-compute:response-send-failed', { to: fromPubKey, requestId, error: err?.message || String(err) })
295
+ })
296
+ return
297
+ }
298
+
299
+ let response
300
+ try {
301
+ const result = await executeFn(job)
302
+ response = { kind: 'compute-response', requestId, result }
303
+ } catch (err) {
304
+ response = { kind: 'compute-response', requestId, error: err?.message || String(err) }
305
+ }
306
+
307
+ try {
308
+ await ctx.sendTo(fromPubKey, envelopeType, response)
309
+ ctx.emit('compute:chunk-served', { from: fromPubKey, requestId, ok: !response.error })
310
+ } catch (err) {
311
+ log('mesh-compute:response-send-failed', { to: fromPubKey, requestId, error: err?.message || String(err) })
312
+ }
313
+ }
314
+
315
+ function handleComputeResponse(msg) {
316
+ const pending = pendingDispatches.get(msg.requestId)
317
+ if (!pending) return // already resolved (timed out or answered) -- ignore
318
+ pendingDispatches.delete(msg.requestId)
319
+ clearTimeout(pending.timer)
320
+ if (msg.error) {
321
+ pending.reject(new Error(msg.error))
322
+ } else {
323
+ pending.resolve(msg.result)
324
+ }
325
+ }
326
+
327
+ const unsubscribe = ctx.onIncomingData(envelopeType, (fromPubKey, msg) => {
328
+ if (!msg || typeof msg.kind !== 'string') return
329
+ if (msg.kind === 'compute-request') {
330
+ handleComputeRequest(fromPubKey, msg).catch((err) => {
331
+ log('mesh-compute:request-handling-failed', { from: fromPubKey, requestId: msg.requestId, error: err?.message || String(err) })
332
+ })
333
+ } else if (msg.kind === 'compute-response') {
334
+ handleComputeResponse(msg)
335
+ }
336
+ })
337
+
338
+ const api = {
339
+ /**
340
+ * @param {object} jobSpec - See `FederatedCompute.submit()`'s own
341
+ * JSDoc. `splitFn`/`mergeFn` fall back to this service's own
342
+ * constructor-level defaults when omitted from `jobSpec`.
343
+ * @returns {Promise<import('./peer-compute.mjs').FederatedJob>}
344
+ */
345
+ submit: (jobSpec) => compute.submit({
346
+ splitFn: defaultSplitFn,
347
+ mergeFn: defaultMergeFn,
348
+ ...jobSpec,
349
+ }),
350
+
351
+ /** @param {string} jobId */
352
+ cancel: (jobId) => compute.cancel(jobId),
353
+
354
+ /** @param {string} id */
355
+ getJob: (id) => compute.getJob(id),
356
+
357
+ /** @param {object} [filter] */
358
+ listJobs: (filter) => compute.listJobs(filter),
359
+
360
+ getStats: () => compute.getStats(),
361
+ }
362
+
363
+ return {
364
+ api,
365
+ teardown() {
366
+ // Stop FederatedCompute's own #dispatchChunk() retry loop FIRST
367
+ // (issue #136): compute.destroy() makes every in-flight/queued
368
+ // chunk's retry loop bail out instead of calling
369
+ // effectiveScheduler.dispatch() again, so rejecting the
370
+ // currently-pending dispatches below can't trigger a brand-new
371
+ // setTimeout()-backed entry that this teardown() has no further
372
+ // chance to clear. Order relative to the rejection loop doesn't
373
+ // matter for correctness (both run synchronously before any
374
+ // pending promise's .catch continuation gets a turn), but
375
+ // destroying first documents the causality: no more retries can
376
+ // be issued, THEN the ones already in flight are force-settled.
377
+ compute.destroy()
378
+
379
+ for (const [event, handler] of bridgeHandlers) compute.off(event, handler)
380
+ unsubscribe()
381
+ for (const pending of pendingDispatches.values()) {
382
+ clearTimeout(pending.timer)
383
+ pending.reject(new Error('mesh-compute: service torn down while a dispatch was still in flight'))
384
+ }
385
+ pendingDispatches.clear()
386
+ },
387
+ }
388
+ },
389
+ }
390
+ }
391
+
392
+ export {
393
+ DEFAULT_COMPUTE_ENVELOPE_TYPE,
394
+ DEFAULT_COMPUTE_DISPATCH_TIMEOUT_MS,
395
+ DEFAULT_COMPUTE_ACCESS_RESOURCE,
396
+ DEFAULT_COMPUTE_ACCESS_ACTION,
397
+ }
@@ -0,0 +1,182 @@
1
+ /**
2
+ * mesh-dht.mjs -- wires `@johnhenry/browsermesh-discovery`'s
3
+ * `DhtDiscoveryStrategy` (dht.mjs) into `createMeshNode()` (Phase D, issue
4
+ * #87: "Unwired: Kademlia DHT discovery").
5
+ *
6
+ * `DhtDiscoveryStrategy` is a real, tested `DiscoveryStrategy` implementation
7
+ * -- but its constructor only takes a bare `sendFn: (targetId, msg) => void`.
8
+ * It has NO transport of its own: something else has to actually deliver
9
+ * that message to `targetId`, and route the reply back into
10
+ * `strategy.dhtNode.handleMessage(fromId, msg)`. dht.mjs's own tests (see
11
+ * `packages/browsermesh-discovery/test/dht.test.mjs`) only ever pass a
12
+ * `sendFn` that pushes into a local array -- there is no in-repo precedent
13
+ * for what a *real* `sendFn` looks like, which is exactly why nothing ever
14
+ * constructed `DhtDiscoveryStrategy` outside its own test file.
15
+ *
16
+ * The cold-start problem this does NOT solve: a Kademlia DHT node needs some
17
+ * way to exchange PING/FIND_NODE/FIND_VALUE/STORE messages with other DHT
18
+ * nodes before a WebRTC connection to any of them exists (that's the whole
19
+ * point of discovery -- you don't have a connection yet). `createMeshNode()`
20
+ * already has exactly one thing that fits: `signalingTransport`, the
21
+ * caller-supplied bidirectional bus used to relay WebRTC offer/answer/ICE
22
+ * traffic between peers *before* their DataChannel exists (see
23
+ * signaling.mjs). This module multiplexes DHT wire traffic onto that same
24
+ * bus rather than inventing a second one.
25
+ *
26
+ * What this buys you: once two or more `createMeshNode({ enableDht: true })`
27
+ * nodes share a `signalingTransport` bus (a `BroadcastChannel`, a
28
+ * `SharedWorker` relay, a real signaling server, or an in-process bus like
29
+ * the test suites use) AND at least one already knows another's `podId`
30
+ * (`dhtBootstrapPeers`), they bootstrap a routing table and can discover
31
+ * each other and any peer transitively reachable through DHT `STORE`
32
+ * replication over that bus.
33
+ *
34
+ * What this does NOT buy you: a way to find that first peer with zero prior
35
+ * knowledge. `DhtDiscoveryStrategy.query()` only ever inspects the *local*
36
+ * `DhtNode`'s own store/routing table (see dht.mjs's `findValue()` /
37
+ * `findNode()`) -- it never issues a network FIND_NODE/FIND_VALUE RPC and
38
+ * waits on the answer, so there is no genuine iterative Kademlia lookup
39
+ * here, only local-store replication seeded by `bootstrap()`. Two nodes with
40
+ * no shared bootstrap peer and no other rendezvous mechanism cannot find
41
+ * each other via DHT alone, exactly like `ManualStrategy` today -- DHT's
42
+ * real advantage over `ManualStrategy` is that discovery propagates
43
+ * transitively once *some* peers share bootstrap knowledge (A+B bootstrapped
44
+ * together, C bootstraps with B alone, C can still learn of A once B
45
+ * replicates A's record to C), not that it solves rendezvous from nothing.
46
+ * A real rendezvous service (well-known bootstrap nodes, a public tracker,
47
+ * DNS seeds, etc.) is infrastructure this repo does not have and is out of
48
+ * scope here; `dhtBootstrapPeers` is the honest, explicit escape hatch for
49
+ * supplying that out-of-band knowledge yourself.
50
+ *
51
+ * No browser-only imports at module level.
52
+ */
53
+
54
+ import { DhtDiscoveryStrategy } from '@johnhenry/browsermesh-discovery'
55
+
56
+ /** Default `type` tag for DHT wire messages multiplexed onto a shared transport. */
57
+ const DEFAULT_MESSAGE_TYPE = 'dht-relay'
58
+
59
+ // ---------------------------------------------------------------------------
60
+ // shareTransport
61
+ // ---------------------------------------------------------------------------
62
+
63
+ /**
64
+ * Wrap a raw `{send(msg), onMessage(cb), open?, close?}` transport so more
65
+ * than one independent listener can subscribe to it.
66
+ *
67
+ * Most real transports in this repo are single-subscriber: e.g.
68
+ * `signaling.mjs`'s `createBroadcastChannelSignalingTransport()` implements
69
+ * `onMessage(cb) { handler = cb }`, where a second `onMessage()` call
70
+ * silently *replaces* the first rather than adding a second listener. When
71
+ * `createMeshNode({ enableDht: true })` needs to put both
72
+ * `MeshSignalingChannel` (WebRTC signaling) and DHT wire traffic on the same
73
+ * caller-supplied `signalingTransport`, both must go through one shared
74
+ * subscription to the underlying transport, or one silently stops receiving
75
+ * messages depending on construction order.
76
+ *
77
+ * @param {{send: Function, onMessage: Function, open?: Function, close?: Function}} rawTransport
78
+ * @returns {{send: Function, onMessage: Function, open?: Function, close?: Function}}
79
+ * A transport-shaped object safe for multiple independent `onMessage()`
80
+ * subscribers. `onMessage()` returns an unsubscribe function.
81
+ */
82
+ export function shareTransport(rawTransport) {
83
+ const listeners = new Set()
84
+ let subscribed = false
85
+ const ensureSubscribed = () => {
86
+ if (subscribed) return
87
+ subscribed = true
88
+ rawTransport.onMessage((msg) => {
89
+ for (const cb of [...listeners]) cb(msg)
90
+ })
91
+ }
92
+ return {
93
+ send: (msg) => rawTransport.send(msg),
94
+ onMessage: (cb) => {
95
+ ensureSubscribed()
96
+ listeners.add(cb)
97
+ return () => listeners.delete(cb)
98
+ },
99
+ ...(typeof rawTransport.open === 'function' ? { open: () => rawTransport.open() } : {}),
100
+ ...(typeof rawTransport.close === 'function' ? { close: () => rawTransport.close() } : {}),
101
+ }
102
+ }
103
+
104
+ // ---------------------------------------------------------------------------
105
+ // createMeshDht
106
+ // ---------------------------------------------------------------------------
107
+
108
+ /**
109
+ * Build a real, wire-connected `DhtDiscoveryStrategy`: constructs the
110
+ * strategy with a `sendFn` that sends over `transport`, and subscribes to
111
+ * `transport` to route matching incoming messages into
112
+ * `strategy.dhtNode.handleMessage()` -- the two halves dht.mjs itself
113
+ * deliberately leaves to the caller (see this file's header).
114
+ *
115
+ * @param {object} opts
116
+ * @param {string} opts.localPodId - This node's pod identifier.
117
+ * @param {{send: Function, onMessage: Function}} opts.transport - Injectable
118
+ * bidirectional bus reaching other DHT peers by podId -- typically
119
+ * `createMeshNode()`'s own `signalingTransport` (wrapped via
120
+ * `shareTransport()` so WebRTC signaling keeps working on the same bus),
121
+ * or a dedicated bus if you have one.
122
+ * @param {Array<string|{podId: string}>} [opts.bootstrapPeers=[]] - Already-known
123
+ * peer podIds (or `{podId}` records) to seed the DHT routing table with.
124
+ * Required for this node to discover anyone at all -- see this file's
125
+ * header for why DHT does not solve first-contact rendezvous from nothing.
126
+ * @param {number} [opts.k] - Kademlia bucket size, forwarded to
127
+ * `DhtDiscoveryStrategy` (defaults to 20 there).
128
+ * @param {string} [opts.messageType='dht-relay'] - `type` tag used to
129
+ * distinguish DHT wire messages from other traffic sharing `transport`
130
+ * (e.g. `signaling.mjs`'s `'webrtc-offer'|'webrtc-answer'|'webrtc-ice'`).
131
+ * @param {Function} [opts.onLog]
132
+ * @returns {{strategy: DhtDiscoveryStrategy, dhtNode: import('@johnhenry/browsermesh-discovery').DhtNode, teardown: () => void}}
133
+ */
134
+ export function createMeshDht({
135
+ localPodId,
136
+ transport,
137
+ bootstrapPeers = [],
138
+ k,
139
+ messageType = DEFAULT_MESSAGE_TYPE,
140
+ onLog = () => {},
141
+ }) {
142
+ if (!localPodId || typeof localPodId !== 'string') {
143
+ throw new Error('createMeshDht: options.localPodId is required and must be a non-empty string')
144
+ }
145
+ if (!transport || typeof transport.send !== 'function' || typeof transport.onMessage !== 'function') {
146
+ throw new Error('createMeshDht: options.transport is required and must implement send(msg)/onMessage(cb)')
147
+ }
148
+
149
+ const sendFn = (targetId, msg) => {
150
+ transport.send({ type: messageType, from: localPodId, to: targetId, payload: msg })
151
+ }
152
+
153
+ const strategy = new DhtDiscoveryStrategy({
154
+ localId: localPodId,
155
+ sendFn,
156
+ k,
157
+ bootstrapContacts: bootstrapPeers.map((p) => (typeof p === 'string' ? { podId: p } : p)),
158
+ })
159
+
160
+ const unsubscribe = transport.onMessage((raw) => {
161
+ if (!raw || typeof raw !== 'object') return
162
+ if (raw.type !== messageType) return
163
+ if (raw.to !== localPodId) return // not addressed to us
164
+ if (raw.from === localPodId) return // ignore our own broadcast echo
165
+ try {
166
+ strategy.dhtNode.handleMessage(raw.from, raw.payload)
167
+ } catch (err) {
168
+ onLog('mesh-dht:handle-message-failed', {
169
+ from: raw.from,
170
+ error: err?.message || String(err),
171
+ })
172
+ }
173
+ })
174
+
175
+ return {
176
+ strategy,
177
+ dhtNode: strategy.dhtNode,
178
+ teardown: () => {
179
+ if (typeof unsubscribe === 'function') unsubscribe()
180
+ },
181
+ }
182
+ }