@johnhenry/browsermesh-apps 0.0.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.
@@ -0,0 +1,687 @@
1
+ /**
2
+ // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
+ * clawser-peer-compute.js — Federated compute orchestration.
4
+ *
5
+ * Split large compute jobs across multiple peers (map/reduce pattern).
6
+ * Combines scheduling, verification, escrow, and result merging.
7
+ * Enables "nomadic supercomputer" and "compute marketplace" scenarios.
8
+ *
9
+ * Run tests:
10
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-compute.test.mjs
11
+ */
12
+
13
+ // ---------------------------------------------------------------------------
14
+ // Polyfill
15
+ // ---------------------------------------------------------------------------
16
+
17
+ if (!globalThis.crypto) globalThis.crypto = {}
18
+ if (!crypto.randomUUID) crypto.randomUUID = () => 'fc-' + Math.random().toString(36).slice(2)
19
+
20
+ // ---------------------------------------------------------------------------
21
+ // Constants
22
+ // ---------------------------------------------------------------------------
23
+
24
+ /**
25
+ * Supported compute orchestration types.
26
+ * @type {Readonly<Record<string, string>>}
27
+ */
28
+ export const COMPUTE_TYPES = Object.freeze({
29
+ MAP_REDUCE: 'map_reduce',
30
+ PIPELINE: 'pipeline',
31
+ BROADCAST: 'broadcast',
32
+ SCATTER_GATHER: 'scatter_gather',
33
+ })
34
+
35
+ /**
36
+ * Default configuration for federated compute jobs.
37
+ * @type {Readonly<Record<string, any>>}
38
+ */
39
+ export const COMPUTE_DEFAULTS = Object.freeze({
40
+ type: 'scatter_gather',
41
+ maxChunks: 100,
42
+ chunkTimeoutMs: 30_000,
43
+ maxRetries: 2,
44
+ verifyLevel: 0,
45
+ })
46
+
47
+ // ---------------------------------------------------------------------------
48
+ // ComputeChunk
49
+ // ---------------------------------------------------------------------------
50
+
51
+ /**
52
+ * Represents a single unit of work within a federated job.
53
+ */
54
+ export class ComputeChunk {
55
+ /** @type {string} */
56
+ id
57
+
58
+ /** @type {string} */
59
+ jobId
60
+
61
+ /** @type {number} */
62
+ index
63
+
64
+ /** @type {any} */
65
+ payload
66
+
67
+ /** @type {string|null} */
68
+ assignee
69
+
70
+ /** @type {string} */
71
+ status
72
+
73
+ /** @type {any} */
74
+ result
75
+
76
+ /** @type {string|null} */
77
+ error
78
+
79
+ /** @type {number} */
80
+ attempts
81
+
82
+ /** @type {number} */
83
+ cost
84
+
85
+ /**
86
+ * @param {object} opts
87
+ * @param {string} opts.id
88
+ * @param {string} opts.jobId
89
+ * @param {number} opts.index
90
+ * @param {any} opts.payload
91
+ * @param {string} [opts.assignee]
92
+ * @param {string} [opts.status]
93
+ * @param {any} [opts.result]
94
+ * @param {string|null} [opts.error]
95
+ * @param {number} [opts.attempts]
96
+ * @param {number} [opts.cost]
97
+ */
98
+ constructor(opts) {
99
+ this.id = opts.id
100
+ this.jobId = opts.jobId
101
+ this.index = opts.index
102
+ this.payload = opts.payload
103
+ this.assignee = opts.assignee ?? null
104
+ this.status = opts.status ?? 'pending'
105
+ this.result = opts.result ?? null
106
+ this.error = opts.error ?? null
107
+ this.attempts = opts.attempts ?? 0
108
+ this.cost = opts.cost ?? 0
109
+ }
110
+
111
+ /**
112
+ * Serialize to a JSON-safe plain object.
113
+ * @returns {object}
114
+ */
115
+ toJSON() {
116
+ return {
117
+ id: this.id,
118
+ jobId: this.jobId,
119
+ index: this.index,
120
+ payload: this.payload,
121
+ assignee: this.assignee,
122
+ status: this.status,
123
+ result: this.result,
124
+ error: this.error,
125
+ attempts: this.attempts,
126
+ cost: this.cost,
127
+ }
128
+ }
129
+
130
+ /**
131
+ * Restore a ComputeChunk from serialized data.
132
+ * @param {object} json
133
+ * @returns {ComputeChunk}
134
+ */
135
+ static fromJSON(json) {
136
+ return new ComputeChunk({
137
+ id: json.id,
138
+ jobId: json.jobId,
139
+ index: json.index,
140
+ payload: json.payload,
141
+ assignee: json.assignee,
142
+ status: json.status,
143
+ result: json.result,
144
+ error: json.error,
145
+ attempts: json.attempts,
146
+ cost: json.cost,
147
+ })
148
+ }
149
+ }
150
+
151
+ // ---------------------------------------------------------------------------
152
+ // FederatedJob
153
+ // ---------------------------------------------------------------------------
154
+
155
+ /**
156
+ * Represents a full federated compute job spanning multiple peers.
157
+ */
158
+ export class FederatedJob {
159
+ /** @type {string} */
160
+ id
161
+
162
+ /** @type {string} */
163
+ type
164
+
165
+ /** @type {any} */
166
+ payload
167
+
168
+ /** @type {string} */
169
+ status
170
+
171
+ /** @type {ComputeChunk[]} */
172
+ chunks
173
+
174
+ /** @type {any} */
175
+ result
176
+
177
+ /** @type {number} */
178
+ cost
179
+
180
+ /** @type {number} */
181
+ createdAt
182
+
183
+ /**
184
+ * @param {object} opts
185
+ * @param {string} opts.id
186
+ * @param {string} opts.type
187
+ * @param {any} opts.payload
188
+ * @param {string} [opts.status]
189
+ * @param {ComputeChunk[]} [opts.chunks]
190
+ * @param {any} [opts.result]
191
+ * @param {number} [opts.cost]
192
+ * @param {number} [opts.createdAt]
193
+ */
194
+ constructor(opts) {
195
+ this.id = opts.id
196
+ this.type = opts.type
197
+ this.payload = opts.payload
198
+ this.status = opts.status ?? 'pending'
199
+ this.chunks = opts.chunks ?? []
200
+ this.result = opts.result ?? null
201
+ this.cost = opts.cost ?? 0
202
+ this.createdAt = opts.createdAt ?? Date.now()
203
+ }
204
+
205
+ /**
206
+ * Get progress info for this job.
207
+ * @returns {{ total: number, completed: number, failed: number, running: number, pct: number }}
208
+ */
209
+ getProgress() {
210
+ const total = this.chunks.length
211
+ let completed = 0
212
+ let failed = 0
213
+ let running = 0
214
+
215
+ for (const chunk of this.chunks) {
216
+ if (chunk.status === 'completed') completed++
217
+ else if (chunk.status === 'failed') failed++
218
+ else if (chunk.status === 'running') running++
219
+ }
220
+
221
+ const pct = total === 0 ? 0 : Math.round((completed / total) * 100)
222
+
223
+ return { total, completed, failed, running, pct }
224
+ }
225
+
226
+ /**
227
+ * Add a chunk to this job.
228
+ * @param {ComputeChunk} chunk
229
+ */
230
+ addChunk(chunk) {
231
+ this.chunks.push(chunk)
232
+ }
233
+
234
+ /**
235
+ * Get a chunk by ID.
236
+ * @param {string} id
237
+ * @returns {ComputeChunk|null}
238
+ */
239
+ getChunk(id) {
240
+ return this.chunks.find(c => c.id === id) ?? null
241
+ }
242
+
243
+ /**
244
+ * Update a chunk by ID with partial updates.
245
+ * @param {string} id
246
+ * @param {object} updates
247
+ */
248
+ updateChunk(id, updates) {
249
+ const chunk = this.chunks.find(c => c.id === id)
250
+ if (!chunk) return
251
+ for (const [key, value] of Object.entries(updates)) {
252
+ if (key in chunk) chunk[key] = value
253
+ }
254
+ }
255
+
256
+ /**
257
+ * Serialize to a JSON-safe plain object.
258
+ * @returns {object}
259
+ */
260
+ toJSON() {
261
+ return {
262
+ id: this.id,
263
+ type: this.type,
264
+ payload: this.payload,
265
+ status: this.status,
266
+ chunks: this.chunks.map(c => c.toJSON()),
267
+ result: this.result,
268
+ cost: this.cost,
269
+ createdAt: this.createdAt,
270
+ }
271
+ }
272
+
273
+ /**
274
+ * Restore a FederatedJob from serialized data.
275
+ * @param {object} json
276
+ * @returns {FederatedJob}
277
+ */
278
+ static fromJSON(json) {
279
+ return new FederatedJob({
280
+ id: json.id,
281
+ type: json.type,
282
+ payload: json.payload,
283
+ status: json.status,
284
+ chunks: (json.chunks || []).map(c => ComputeChunk.fromJSON(c)),
285
+ result: json.result,
286
+ cost: json.cost,
287
+ createdAt: json.createdAt,
288
+ })
289
+ }
290
+ }
291
+
292
+ // ---------------------------------------------------------------------------
293
+ // FederatedCompute
294
+ // ---------------------------------------------------------------------------
295
+
296
+ /**
297
+ * Orchestrates federated compute across mesh peers.
298
+ *
299
+ * Splits work via user-provided splitFn, dispatches chunks to peers via
300
+ * the injected scheduler, handles retries on failure, and merges results
301
+ * via user-provided mergeFn.
302
+ */
303
+ export class FederatedCompute {
304
+ /** @type {object} */
305
+ #scheduler
306
+
307
+ /** @type {Function} */
308
+ #onLog
309
+
310
+ /** @type {Map<string, FederatedJob>} */
311
+ #jobs = new Map()
312
+
313
+ /** @type {Map<string, Function[]>} */
314
+ #listeners = new Map()
315
+
316
+ /**
317
+ * @param {object} opts
318
+ * @param {object} opts.scheduler - Must have dispatch(peerId, job) and listAvailablePeers()
319
+ * @param {Function} [opts.onLog] - Logging callback (level, msg)
320
+ */
321
+ constructor(opts) {
322
+ if (!opts?.scheduler) {
323
+ throw new Error('FederatedCompute requires a scheduler')
324
+ }
325
+ if (typeof opts.scheduler.dispatch !== 'function') {
326
+ throw new Error('scheduler must have a dispatch() method')
327
+ }
328
+ if (typeof opts.scheduler.listAvailablePeers !== 'function') {
329
+ throw new Error('scheduler must have a listAvailablePeers() method')
330
+ }
331
+ this.#scheduler = opts.scheduler
332
+ this.#onLog = opts.onLog ?? (() => {})
333
+ }
334
+
335
+ // ── Submit ──────────────────────────────────────────────────────
336
+
337
+ /**
338
+ * Submit a federated compute job.
339
+ *
340
+ * @param {object} jobSpec
341
+ * @param {string} [jobSpec.type] - One of COMPUTE_TYPES (default: scatter_gather)
342
+ * @param {any} jobSpec.payload - The full payload to split
343
+ * @param {Function} jobSpec.splitFn - (payload) => chunkPayloads[]
344
+ * @param {Function} jobSpec.mergeFn - (results[]) => mergedResult
345
+ * @param {string[]} [jobSpec.peers] - Specific peer list (overrides scheduler discovery)
346
+ * @param {number} [jobSpec.budget] - Cost budget (informational)
347
+ * @param {number} [jobSpec.verifyLevel] - 0=none, 1=spot-check, 2=full-quorum
348
+ * @returns {Promise<FederatedJob>}
349
+ */
350
+ async submit(jobSpec) {
351
+ const type = jobSpec.type ?? COMPUTE_DEFAULTS.type
352
+ const jobId = crypto.randomUUID()
353
+
354
+ const job = new FederatedJob({
355
+ id: jobId,
356
+ type,
357
+ payload: jobSpec.payload,
358
+ status: 'splitting',
359
+ })
360
+
361
+ this.#jobs.set(jobId, job)
362
+ this.#emit('submitted', job)
363
+ this.#onLog('info', `Job ${jobId} submitted (type: ${type})`)
364
+
365
+ // Step 1: Split payload into chunk payloads
366
+ const chunkPayloads = await jobSpec.splitFn(jobSpec.payload)
367
+ this.#emit('split', { jobId, count: chunkPayloads.length })
368
+ this.#onLog('info', `Job ${jobId} split into ${chunkPayloads.length} chunks`)
369
+
370
+ // Step 2: Resolve peer list
371
+ const peers = jobSpec.peers ?? this.#scheduler.listAvailablePeers()
372
+ if (peers.length === 0) {
373
+ job.status = 'failed'
374
+ this.#emit('failed', job)
375
+ return job
376
+ }
377
+
378
+ // Step 3: Create chunks and assign to peers
379
+ const computeType = type
380
+
381
+ if (computeType === COMPUTE_TYPES.BROADCAST) {
382
+ // Broadcast: same payload sent to all peers
383
+ for (let i = 0; i < peers.length; i++) {
384
+ const chunk = new ComputeChunk({
385
+ id: crypto.randomUUID(),
386
+ jobId,
387
+ index: i,
388
+ payload: chunkPayloads[0] ?? jobSpec.payload,
389
+ assignee: peers[i],
390
+ status: 'assigned',
391
+ })
392
+ job.addChunk(chunk)
393
+ this.#emit('chunk-assigned', { jobId, chunkId: chunk.id, peerId: peers[i] })
394
+ }
395
+ } else if (computeType === COMPUTE_TYPES.PIPELINE) {
396
+ // Pipeline: sequential stages, each assigned to a peer
397
+ for (let i = 0; i < chunkPayloads.length; i++) {
398
+ const peerId = peers[i % peers.length]
399
+ const chunk = new ComputeChunk({
400
+ id: crypto.randomUUID(),
401
+ jobId,
402
+ index: i,
403
+ payload: chunkPayloads[i],
404
+ assignee: peerId,
405
+ status: 'assigned',
406
+ })
407
+ job.addChunk(chunk)
408
+ this.#emit('chunk-assigned', { jobId, chunkId: chunk.id, peerId })
409
+ }
410
+ } else {
411
+ // MAP_REDUCE and SCATTER_GATHER: round-robin assignment
412
+ for (let i = 0; i < chunkPayloads.length; i++) {
413
+ const peerId = peers[i % peers.length]
414
+ const chunk = new ComputeChunk({
415
+ id: crypto.randomUUID(),
416
+ jobId,
417
+ index: i,
418
+ payload: chunkPayloads[i],
419
+ assignee: peerId,
420
+ status: 'assigned',
421
+ })
422
+ job.addChunk(chunk)
423
+ this.#emit('chunk-assigned', { jobId, chunkId: chunk.id, peerId })
424
+ }
425
+ }
426
+
427
+ job.status = 'running'
428
+
429
+ // Step 4: Dispatch chunks
430
+ if (computeType === COMPUTE_TYPES.PIPELINE) {
431
+ // Pipeline: sequential execution — each stage feeds into the next
432
+ await this.#dispatchPipeline(job, jobSpec, peers)
433
+ } else {
434
+ // All other types: parallel dispatch
435
+ await this.#dispatchParallel(job, jobSpec, peers)
436
+ }
437
+
438
+ // Step 5: Check if job succeeded
439
+ const progress = job.getProgress()
440
+ if (progress.failed > 0 && progress.completed === 0) {
441
+ job.status = 'failed'
442
+ this.#emit('failed', job)
443
+ return job
444
+ }
445
+
446
+ // Step 6: Merge results
447
+ job.status = 'merging'
448
+ const completedResults = job.chunks
449
+ .filter(c => c.status === 'completed')
450
+ .sort((a, b) => a.index - b.index)
451
+ .map(c => c.result)
452
+
453
+ try {
454
+ job.result = await jobSpec.mergeFn(completedResults)
455
+ job.status = 'completed'
456
+ job.cost = job.chunks.reduce((sum, c) => sum + c.cost, 0)
457
+ this.#emit('merged', { jobId, result: job.result })
458
+ this.#emit('completed', job)
459
+ this.#onLog('info', `Job ${jobId} completed`)
460
+ } catch (err) {
461
+ job.status = 'failed'
462
+ this.#emit('failed', job)
463
+ this.#onLog('error', `Job ${jobId} merge failed: ${err.message}`)
464
+ }
465
+
466
+ return job
467
+ }
468
+
469
+ // ── Cancel ─────────────────────────────────────────────────────
470
+
471
+ /**
472
+ * Cancel a running job. Sets all pending/running/assigned chunks to cancelled.
473
+ *
474
+ * @param {string} jobId
475
+ * @returns {boolean} true if job was found and cancelled
476
+ */
477
+ async cancel(jobId) {
478
+ const job = this.#jobs.get(jobId)
479
+ if (!job) return false
480
+
481
+ for (const chunk of job.chunks) {
482
+ if (chunk.status === 'pending' || chunk.status === 'running' || chunk.status === 'assigned') {
483
+ chunk.status = 'cancelled'
484
+ }
485
+ }
486
+
487
+ job.status = 'cancelled'
488
+ this.#emit('failed', job)
489
+ this.#onLog('info', `Job ${jobId} cancelled`)
490
+
491
+ return true
492
+ }
493
+
494
+ // ── Queries ────────────────────────────────────────────────────
495
+
496
+ /**
497
+ * Get a job by ID.
498
+ * @param {string} id
499
+ * @returns {FederatedJob|null}
500
+ */
501
+ getJob(id) {
502
+ return this.#jobs.get(id) ?? null
503
+ }
504
+
505
+ /**
506
+ * List all jobs, optionally filtered.
507
+ * @param {object} [filter]
508
+ * @param {string} [filter.status]
509
+ * @returns {FederatedJob[]}
510
+ */
511
+ listJobs(filter) {
512
+ let results = [...this.#jobs.values()]
513
+ if (filter?.status) {
514
+ results = results.filter(j => j.status === filter.status)
515
+ }
516
+ return results
517
+ }
518
+
519
+ /**
520
+ * Get aggregate statistics across all jobs.
521
+ * @returns {{ submitted: number, running: number, completed: number, failed: number, totalCost: number }}
522
+ */
523
+ getStats() {
524
+ let submitted = 0
525
+ let running = 0
526
+ let completed = 0
527
+ let failed = 0
528
+ let totalCost = 0
529
+
530
+ for (const job of this.#jobs.values()) {
531
+ submitted++
532
+ switch (job.status) {
533
+ case 'running':
534
+ case 'splitting':
535
+ case 'assigned':
536
+ case 'merging':
537
+ running++
538
+ break
539
+ case 'completed':
540
+ completed++
541
+ totalCost += job.cost
542
+ break
543
+ case 'failed':
544
+ case 'cancelled':
545
+ failed++
546
+ break
547
+ }
548
+ }
549
+
550
+ return { submitted, running, completed, failed, totalCost }
551
+ }
552
+
553
+ // ── Events ─────────────────────────────────────────────────────
554
+
555
+ /**
556
+ * Subscribe to an event.
557
+ * @param {string} event
558
+ * @param {Function} cb
559
+ */
560
+ on(event, cb) {
561
+ if (!this.#listeners.has(event)) {
562
+ this.#listeners.set(event, [])
563
+ }
564
+ this.#listeners.get(event).push(cb)
565
+ }
566
+
567
+ /**
568
+ * Unsubscribe from an event.
569
+ * @param {string} event
570
+ * @param {Function} cb
571
+ */
572
+ off(event, cb) {
573
+ const cbs = this.#listeners.get(event)
574
+ if (!cbs) return
575
+ const idx = cbs.indexOf(cb)
576
+ if (idx !== -1) cbs.splice(idx, 1)
577
+ }
578
+
579
+ // ── Private helpers ────────────────────────────────────────────
580
+
581
+ /**
582
+ * Dispatch all chunks in parallel with retry logic.
583
+ *
584
+ * @param {FederatedJob} job
585
+ * @param {object} jobSpec
586
+ * @param {string[]} peers
587
+ */
588
+ async #dispatchParallel(job, jobSpec, peers) {
589
+ const maxRetries = COMPUTE_DEFAULTS.maxRetries
590
+
591
+ await Promise.all(job.chunks.map(async (chunk) => {
592
+ await this.#dispatchChunk(chunk, job, jobSpec, peers, maxRetries)
593
+ }))
594
+ }
595
+
596
+ /**
597
+ * Dispatch pipeline chunks sequentially. Each stage's output feeds
598
+ * into the next stage's input.
599
+ *
600
+ * @param {FederatedJob} job
601
+ * @param {object} jobSpec
602
+ * @param {string[]} peers
603
+ */
604
+ async #dispatchPipeline(job, jobSpec, peers) {
605
+ const maxRetries = COMPUTE_DEFAULTS.maxRetries
606
+ let previousResult = null
607
+
608
+ for (const chunk of job.chunks) {
609
+ // For pipeline stages after the first, feed previous result into payload
610
+ if (previousResult !== null) {
611
+ chunk.payload = { ...chunk.payload, previousResult }
612
+ }
613
+
614
+ await this.#dispatchChunk(chunk, job, jobSpec, peers, maxRetries)
615
+
616
+ if (chunk.status === 'completed') {
617
+ previousResult = chunk.result
618
+ } else {
619
+ // Pipeline breaks on failure
620
+ break
621
+ }
622
+ }
623
+ }
624
+
625
+ /**
626
+ * Dispatch a single chunk with retry logic.
627
+ *
628
+ * @param {ComputeChunk} chunk
629
+ * @param {FederatedJob} job
630
+ * @param {object} jobSpec
631
+ * @param {string[]} peers
632
+ * @param {number} maxRetries
633
+ */
634
+ async #dispatchChunk(chunk, job, jobSpec, peers, maxRetries) {
635
+ let lastError = null
636
+
637
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
638
+ chunk.attempts = attempt + 1
639
+ chunk.status = 'running'
640
+
641
+ try {
642
+ const result = await this.#scheduler.dispatch(chunk.assignee, {
643
+ chunkId: chunk.id,
644
+ jobId: job.id,
645
+ index: chunk.index,
646
+ payload: chunk.payload,
647
+ })
648
+
649
+ chunk.result = result.output ?? result
650
+ chunk.status = 'completed'
651
+ chunk.cost = result.cost ?? 0
652
+ this.#emit('chunk-complete', { jobId: job.id, chunkId: chunk.id, result: chunk.result })
653
+ return
654
+ } catch (err) {
655
+ lastError = err
656
+ this.#onLog('warn', `Chunk ${chunk.id} attempt ${attempt + 1} failed: ${err.message}`)
657
+
658
+ if (attempt < maxRetries) {
659
+ // Retry on a different peer if available
660
+ const currentIdx = peers.indexOf(chunk.assignee)
661
+ const nextPeer = peers[(currentIdx + 1) % peers.length]
662
+ chunk.assignee = nextPeer
663
+ }
664
+ }
665
+ }
666
+
667
+ // All retries exhausted
668
+ chunk.status = 'failed'
669
+ chunk.error = lastError?.message ?? 'unknown error'
670
+ this.#emit('chunk-failed', { jobId: job.id, chunkId: chunk.id, error: chunk.error })
671
+ }
672
+
673
+ /**
674
+ * Emit an event to all registered listeners.
675
+ * Uses a snapshot to avoid mutation during iteration.
676
+ *
677
+ * @param {string} event
678
+ * @param {...any} args
679
+ */
680
+ #emit(event, ...args) {
681
+ const cbs = this.#listeners.get(event)
682
+ if (!cbs) return
683
+ for (const cb of [...cbs]) {
684
+ try { cb(...args) } catch { /* listener errors do not propagate */ }
685
+ }
686
+ }
687
+ }