@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,679 @@
1
+ /**
2
+ * clawser-mesh-resources.js -- Resource advertisement, discovery, and job
3
+ * scheduling for BrowserMesh.
4
+ *
5
+ * Peers advertise hardware/software resources, discover matching nodes, score
6
+ * candidates, and submit compute jobs through a lightweight queue.
7
+ *
8
+ * No browser-only imports at module level.
9
+ *
10
+ * Run tests:
11
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-resources.test.mjs
12
+ */
13
+
14
+ import { MESH_TYPE } from '@johnhenry/browsermesh-primitives';
15
+
16
+ // ---------------------------------------------------------------------------
17
+ // Wire constants — imported from canonical registry
18
+ // ---------------------------------------------------------------------------
19
+
20
+ /** Advertise local resources to the mesh */
21
+ export const RESOURCE_ADVERTISE = MESH_TYPE.RESOURCE_ADVERTISE;
22
+ /** Discover peers matching resource constraints */
23
+ export const RESOURCE_DISCOVER = MESH_TYPE.RESOURCE_DISCOVER;
24
+ /** Response to a discovery query */
25
+ export const RESOURCE_DISCOVER_RESPONSE = MESH_TYPE.RESOURCE_DISCOVER_RESPONSE;
26
+ /** Submit a compute request */
27
+ export const COMPUTE_REQUEST = MESH_TYPE.COMPUTE_REQUEST;
28
+ /** Return a compute result */
29
+ export const COMPUTE_RESULT = MESH_TYPE.COMPUTE_RESULT;
30
+ /** Incremental progress update for a running job */
31
+ export const COMPUTE_PROGRESS = MESH_TYPE.COMPUTE_PROGRESS;
32
+
33
+ // ---------------------------------------------------------------------------
34
+ // ResourceDescriptor
35
+ // ---------------------------------------------------------------------------
36
+
37
+ /**
38
+ * Describes the resources a mesh pod makes available.
39
+ */
40
+ export class ResourceDescriptor {
41
+ /**
42
+ * @param {object} opts
43
+ * @param {string} opts.podId
44
+ * @param {object} [opts.resources]
45
+ * @param {number} [opts.resources.cpu] - Logical cores (0 = unknown)
46
+ * @param {number} [opts.resources.gpu] - GPU count (0 = none)
47
+ * @param {number} [opts.resources.memory] - Available MB
48
+ * @param {number} [opts.resources.storage] - Available MB
49
+ * @param {number} [opts.resources.bandwidth] - Mbps estimate
50
+ * @param {string[]} [opts.capabilities]
51
+ * @param {'online'|'busy'|'offline'} [opts.availability]
52
+ * @param {number} [opts.updatedAt]
53
+ * @param {number} [opts.ttl] - Time-to-live in ms (default 60 000)
54
+ */
55
+ constructor({
56
+ podId,
57
+ resources = {},
58
+ capabilities = [],
59
+ availability = 'online',
60
+ updatedAt,
61
+ ttl,
62
+ }) {
63
+ if (!podId || typeof podId !== 'string') {
64
+ throw new Error('podId is required and must be a non-empty string');
65
+ }
66
+ this.podId = podId;
67
+ this.resources = {
68
+ cpu: resources.cpu ?? 0,
69
+ gpu: resources.gpu ?? 0,
70
+ memory: resources.memory ?? 0,
71
+ storage: resources.storage ?? 0,
72
+ bandwidth: resources.bandwidth ?? 0,
73
+ };
74
+ this.capabilities = [...capabilities];
75
+ this.availability = availability;
76
+ this.updatedAt = updatedAt ?? Date.now();
77
+ this.ttl = ttl ?? 60_000;
78
+ }
79
+
80
+ /**
81
+ * Check whether this descriptor satisfies the given constraints.
82
+ *
83
+ * Constraints may include any subset of resource fields (minimum values),
84
+ * a required `capabilities` array, and an `availability` value.
85
+ *
86
+ * @param {object} [constraints]
87
+ * @returns {boolean}
88
+ */
89
+ matches(constraints) {
90
+ if (!constraints) return true;
91
+
92
+ // Availability check
93
+ if (constraints.availability && this.availability !== constraints.availability) {
94
+ return false;
95
+ }
96
+
97
+ // Resource minimums
98
+ for (const key of ['cpu', 'gpu', 'memory', 'storage', 'bandwidth']) {
99
+ if (constraints[key] !== undefined && this.resources[key] < constraints[key]) {
100
+ return false;
101
+ }
102
+ }
103
+
104
+ // Required capabilities
105
+ if (constraints.capabilities) {
106
+ for (const cap of constraints.capabilities) {
107
+ if (!this.capabilities.includes(cap)) return false;
108
+ }
109
+ }
110
+
111
+ return true;
112
+ }
113
+
114
+ /**
115
+ * @param {number} [now]
116
+ * @returns {boolean}
117
+ */
118
+ isExpired(now = Date.now()) {
119
+ return now > this.updatedAt + this.ttl;
120
+ }
121
+
122
+ toJSON() {
123
+ return {
124
+ podId: this.podId,
125
+ resources: { ...this.resources },
126
+ capabilities: [...this.capabilities],
127
+ availability: this.availability,
128
+ updatedAt: this.updatedAt,
129
+ ttl: this.ttl,
130
+ };
131
+ }
132
+
133
+ /**
134
+ * @param {object} data
135
+ * @returns {ResourceDescriptor}
136
+ */
137
+ static fromJSON(data) {
138
+ return new ResourceDescriptor({
139
+ podId: data.podId,
140
+ resources: data.resources,
141
+ capabilities: data.capabilities,
142
+ availability: data.availability,
143
+ updatedAt: data.updatedAt,
144
+ ttl: data.ttl,
145
+ });
146
+ }
147
+ }
148
+
149
+ // ---------------------------------------------------------------------------
150
+ // ResourceRegistry
151
+ // ---------------------------------------------------------------------------
152
+
153
+ /**
154
+ * Local registry of known resource descriptors, keyed by podId.
155
+ */
156
+ export class ResourceRegistry {
157
+ /** @type {Map<string, ResourceDescriptor>} */
158
+ #entries = new Map();
159
+ #maxEntries;
160
+ #ttlMs;
161
+
162
+ /**
163
+ * @param {object} [opts]
164
+ * @param {number} [opts.maxEntries=1024]
165
+ * @param {number} [opts.ttlMs=60000] - Default TTL applied when advertising
166
+ */
167
+ constructor(opts = {}) {
168
+ this.#maxEntries = opts.maxEntries ?? 1024;
169
+ this.#ttlMs = opts.ttlMs ?? 60_000;
170
+ }
171
+
172
+ /**
173
+ * Advertise (upsert) a descriptor. Applies the registry-level TTL if the
174
+ * descriptor does not already have one.
175
+ *
176
+ * @param {ResourceDescriptor} descriptor
177
+ */
178
+ advertise(descriptor) {
179
+ if (this.#entries.size >= this.#maxEntries && !this.#entries.has(descriptor.podId)) {
180
+ throw new Error('ResourceRegistry is full');
181
+ }
182
+ descriptor.updatedAt = Date.now();
183
+ if (!descriptor.ttl) descriptor.ttl = this.#ttlMs;
184
+ this.#entries.set(descriptor.podId, descriptor);
185
+ }
186
+
187
+ /**
188
+ * Withdraw a pod's advertisement.
189
+ *
190
+ * @param {string} podId
191
+ * @returns {boolean}
192
+ */
193
+ withdraw(podId) {
194
+ return this.#entries.delete(podId);
195
+ }
196
+
197
+ /**
198
+ * @param {string} podId
199
+ * @returns {ResourceDescriptor|null}
200
+ */
201
+ get(podId) {
202
+ return this.#entries.get(podId) ?? null;
203
+ }
204
+
205
+ /**
206
+ * Discover descriptors matching optional constraints. Only returns
207
+ * non-expired entries.
208
+ *
209
+ * @param {object} [constraints]
210
+ * @returns {ResourceDescriptor[]}
211
+ */
212
+ discover(constraints) {
213
+ const now = Date.now();
214
+ const results = [];
215
+ for (const desc of this.#entries.values()) {
216
+ if (desc.isExpired(now)) continue;
217
+ if (desc.matches(constraints)) results.push(desc);
218
+ }
219
+ return results;
220
+ }
221
+
222
+ /**
223
+ * Remove all expired entries.
224
+ * @returns {number} count of entries removed
225
+ */
226
+ pruneExpired() {
227
+ const now = Date.now();
228
+ let count = 0;
229
+ for (const [podId, desc] of this.#entries) {
230
+ if (desc.isExpired(now)) {
231
+ this.#entries.delete(podId);
232
+ count++;
233
+ }
234
+ }
235
+ return count;
236
+ }
237
+
238
+ /** @returns {number} */
239
+ get size() {
240
+ return this.#entries.size;
241
+ }
242
+
243
+ /**
244
+ * List all entries (including expired).
245
+ * @returns {ResourceDescriptor[]}
246
+ */
247
+ listAll() {
248
+ return [...this.#entries.values()];
249
+ }
250
+
251
+ toJSON() {
252
+ return [...this.#entries.values()].map(d => d.toJSON());
253
+ }
254
+
255
+ /**
256
+ * @param {object[]} data
257
+ * @returns {ResourceRegistry}
258
+ */
259
+ static fromJSON(data) {
260
+ const reg = new ResourceRegistry();
261
+ for (const item of data) {
262
+ const desc = ResourceDescriptor.fromJSON(item);
263
+ reg.#entries.set(desc.podId, desc);
264
+ }
265
+ return reg;
266
+ }
267
+ }
268
+
269
+ // ---------------------------------------------------------------------------
270
+ // ComputeRequest
271
+ // ---------------------------------------------------------------------------
272
+
273
+ /**
274
+ * A request to execute a compute job on a remote mesh node.
275
+ */
276
+ export class ComputeRequest {
277
+ /**
278
+ * @param {object} opts
279
+ * @param {string} [opts.jobId]
280
+ * @param {'wasm'|'js'} opts.moduleType
281
+ * @param {string} opts.moduleCid - Content-addressed ID of the module
282
+ * @param {string} opts.entry - Entry function name
283
+ * @param {*} [opts.input] - Serializable input payload
284
+ * @param {object} [opts.constraints]
285
+ * @param {string} [opts.constraints.prefer] - 'gpu'|'cpu'|'any'
286
+ * @param {string} [opts.constraints.preferRuntimeClass]
287
+ * @param {string[]} [opts.constraints.capabilities]
288
+ * @param {number} [opts.constraints.timeoutMs]
289
+ * @param {number} [opts.constraints.maxMemoryMb]
290
+ * @param {number} [opts.constraints.priority] - 0 = low, higher = more urgent
291
+ * @param {string} opts.requesterId
292
+ * @param {number} [opts.timestamp]
293
+ */
294
+ constructor({
295
+ jobId,
296
+ moduleType,
297
+ moduleCid,
298
+ entry,
299
+ input,
300
+ constraints = {},
301
+ requesterId,
302
+ timestamp,
303
+ }) {
304
+ this.jobId = jobId ?? _genId();
305
+ this.moduleType = moduleType;
306
+ this.moduleCid = moduleCid;
307
+ this.entry = entry;
308
+ this.input = input ?? null;
309
+ this.constraints = {
310
+ ...constraints,
311
+ prefer: constraints.prefer ?? 'any',
312
+ preferRuntimeClass: constraints.preferRuntimeClass ?? null,
313
+ capabilities: [...(constraints.capabilities || [])],
314
+ timeoutMs: constraints.timeoutMs ?? 30_000,
315
+ maxMemoryMb: constraints.maxMemoryMb ?? null,
316
+ priority: constraints.priority ?? 0,
317
+ };
318
+ this.requesterId = requesterId;
319
+ this.timestamp = timestamp ?? Date.now();
320
+ }
321
+
322
+ toJSON() {
323
+ return {
324
+ jobId: this.jobId,
325
+ moduleType: this.moduleType,
326
+ moduleCid: this.moduleCid,
327
+ entry: this.entry,
328
+ input: this.input,
329
+ constraints: { ...this.constraints },
330
+ requesterId: this.requesterId,
331
+ timestamp: this.timestamp,
332
+ };
333
+ }
334
+
335
+ /**
336
+ * @param {object} data
337
+ * @returns {ComputeRequest}
338
+ */
339
+ static fromJSON(data) {
340
+ return new ComputeRequest({
341
+ jobId: data.jobId,
342
+ moduleType: data.moduleType,
343
+ moduleCid: data.moduleCid,
344
+ entry: data.entry,
345
+ input: data.input,
346
+ constraints: data.constraints,
347
+ requesterId: data.requesterId,
348
+ timestamp: data.timestamp,
349
+ });
350
+ }
351
+ }
352
+
353
+ // ---------------------------------------------------------------------------
354
+ // ComputeResult
355
+ // ---------------------------------------------------------------------------
356
+
357
+ /**
358
+ * The result of a completed (or failed) compute job.
359
+ */
360
+ export class ComputeResult {
361
+ /**
362
+ * @param {object} opts
363
+ * @param {string} opts.jobId
364
+ * @param {'success'|'error'|'cancelled'|'timeout'} opts.status
365
+ * @param {*} [opts.result]
366
+ * @param {string} [opts.error]
367
+ * @param {object} [opts.metrics]
368
+ * @param {string} [opts.metrics.executorId]
369
+ * @param {number} [opts.metrics.startTime]
370
+ * @param {number} [opts.metrics.endTime]
371
+ * @param {number} [opts.metrics.cpuTimeMs]
372
+ * @param {number} [opts.metrics.memoryPeakMb]
373
+ */
374
+ constructor({ jobId, status, result, error, metrics = {} }) {
375
+ this.jobId = jobId;
376
+ this.status = status;
377
+ this.result = result ?? null;
378
+ this.error = error ?? null;
379
+ this.metrics = {
380
+ executorId: metrics.executorId ?? null,
381
+ startTime: metrics.startTime ?? null,
382
+ endTime: metrics.endTime ?? null,
383
+ cpuTimeMs: metrics.cpuTimeMs ?? 0,
384
+ memoryPeakMb: metrics.memoryPeakMb ?? 0,
385
+ };
386
+ }
387
+
388
+ /**
389
+ * Wall-clock duration from start to end. Returns 0 when timestamps are
390
+ * missing.
391
+ * @returns {number}
392
+ */
393
+ get durationMs() {
394
+ if (this.metrics.startTime == null || this.metrics.endTime == null) return 0;
395
+ return this.metrics.endTime - this.metrics.startTime;
396
+ }
397
+
398
+ toJSON() {
399
+ return {
400
+ jobId: this.jobId,
401
+ status: this.status,
402
+ result: this.result,
403
+ error: this.error,
404
+ metrics: { ...this.metrics },
405
+ };
406
+ }
407
+
408
+ /**
409
+ * @param {object} data
410
+ * @returns {ComputeResult}
411
+ */
412
+ static fromJSON(data) {
413
+ return new ComputeResult({
414
+ jobId: data.jobId,
415
+ status: data.status,
416
+ result: data.result,
417
+ error: data.error,
418
+ metrics: data.metrics,
419
+ });
420
+ }
421
+ }
422
+
423
+ // ---------------------------------------------------------------------------
424
+ // ResourceScorer
425
+ // ---------------------------------------------------------------------------
426
+
427
+ /**
428
+ * Scores a ResourceDescriptor against a ComputeRequest to determine fitness.
429
+ *
430
+ * Scoring heuristic (0-100+ scale):
431
+ * - Base: 50 points for being online
432
+ * - Preference match (gpu/cpu): +20
433
+ * - Memory headroom: up to +15
434
+ * - CPU count: up to +10
435
+ * - Bandwidth: up to +5
436
+ * - Busy penalty: -20
437
+ */
438
+ export class ResourceScorer {
439
+ /**
440
+ * @param {ComputeRequest} request
441
+ * @param {ResourceDescriptor} descriptor
442
+ * @returns {number}
443
+ */
444
+ static score(request, descriptor) {
445
+ let s = 0;
446
+
447
+ // Availability base score
448
+ if (descriptor.availability === 'online') s += 50;
449
+ else if (descriptor.availability === 'busy') s += 30;
450
+ else return 0; // offline nodes score zero
451
+
452
+ // Preference match
453
+ const prefer = request.constraints?.prefer ?? 'any';
454
+ if (prefer === 'gpu' && descriptor.resources.gpu > 0) s += 20;
455
+ else if (prefer === 'cpu' && descriptor.resources.cpu > 0) s += 20;
456
+ else if (prefer === 'any') s += 10;
457
+
458
+ const preferRuntimeClass = request.constraints?.preferRuntimeClass;
459
+ if (preferRuntimeClass && descriptor.capabilities.includes(`runtime:${preferRuntimeClass}`)) {
460
+ s += 60;
461
+ } else if (preferRuntimeClass) {
462
+ s -= 15;
463
+ }
464
+
465
+ // Memory headroom: up to +15
466
+ const reqMem = request.constraints?.maxMemoryMb ?? 0;
467
+ if (reqMem > 0 && descriptor.resources.memory > 0) {
468
+ const ratio = Math.min(descriptor.resources.memory / reqMem, 4);
469
+ s += Math.round((ratio / 4) * 15);
470
+ } else if (descriptor.resources.memory > 0) {
471
+ s += 8;
472
+ }
473
+
474
+ // CPU count: up to +10
475
+ if (descriptor.resources.cpu > 0) {
476
+ s += Math.min(descriptor.resources.cpu, 10);
477
+ }
478
+
479
+ // Bandwidth: up to +5
480
+ if (descriptor.resources.bandwidth > 0) {
481
+ s += Math.min(Math.round(descriptor.resources.bandwidth / 20), 5);
482
+ }
483
+
484
+ return s;
485
+ }
486
+
487
+ /**
488
+ * Select the best-scoring descriptor for a request.
489
+ *
490
+ * @param {ComputeRequest} request
491
+ * @param {ResourceDescriptor[]} descriptors
492
+ * @returns {ResourceDescriptor|null}
493
+ */
494
+ static selectBest(request, descriptors) {
495
+ if (!descriptors || descriptors.length === 0) return null;
496
+ let best = null;
497
+ let bestScore = -1;
498
+ for (const desc of descriptors) {
499
+ const s = ResourceScorer.score(request, desc);
500
+ if (s > bestScore) {
501
+ bestScore = s;
502
+ best = desc;
503
+ }
504
+ }
505
+ return best;
506
+ }
507
+ }
508
+
509
+ // ---------------------------------------------------------------------------
510
+ // JobQueue
511
+ // ---------------------------------------------------------------------------
512
+
513
+ /** @typedef {'pending'|'assigned'|'running'|'completed'|'cancelled'|'timeout'|'error'} JobStatus */
514
+
515
+ /**
516
+ * In-memory job queue for compute requests.
517
+ */
518
+ export class JobQueue {
519
+ /** @type {Map<string, object>} jobId -> job record */
520
+ #jobs = new Map();
521
+ #maxJobs;
522
+
523
+ /**
524
+ * @param {object} [opts]
525
+ * @param {number} [opts.maxJobs=256]
526
+ */
527
+ constructor(opts = {}) {
528
+ this.#maxJobs = opts.maxJobs ?? 256;
529
+ }
530
+
531
+ /**
532
+ * Submit a compute request to the queue.
533
+ *
534
+ * @param {ComputeRequest} request
535
+ * @returns {string} jobId
536
+ */
537
+ submit(request) {
538
+ if (this.#jobs.size >= this.#maxJobs) {
539
+ throw new Error('JobQueue is full');
540
+ }
541
+ this.#jobs.set(request.jobId, {
542
+ request,
543
+ status: 'pending',
544
+ assignedTo: null,
545
+ result: null,
546
+ submittedAt: Date.now(),
547
+ startedAt: null,
548
+ completedAt: null,
549
+ });
550
+ return request.jobId;
551
+ }
552
+
553
+ /**
554
+ * Get a job record by ID.
555
+ *
556
+ * @param {string} jobId
557
+ * @returns {object|null}
558
+ */
559
+ get(jobId) {
560
+ const job = this.#jobs.get(jobId);
561
+ if (!job) return null;
562
+ return { ...job };
563
+ }
564
+
565
+ /**
566
+ * Assign a pending job to an executor pod.
567
+ *
568
+ * @param {string} jobId
569
+ * @param {string} executorPodId
570
+ * @returns {boolean}
571
+ */
572
+ assign(jobId, executorPodId) {
573
+ const job = this.#jobs.get(jobId);
574
+ if (!job || job.status !== 'pending') return false;
575
+ job.status = 'assigned';
576
+ job.assignedTo = executorPodId;
577
+ job.startedAt = Date.now();
578
+ return true;
579
+ }
580
+
581
+ /**
582
+ * Mark a job as completed with a ComputeResult.
583
+ *
584
+ * @param {string} jobId
585
+ * @param {ComputeResult} result
586
+ * @returns {boolean}
587
+ */
588
+ complete(jobId, result) {
589
+ const job = this.#jobs.get(jobId);
590
+ if (!job) return false;
591
+ if (job.status !== 'pending' && job.status !== 'assigned') return false;
592
+ job.status = result.status === 'success' ? 'completed' : result.status;
593
+ job.result = result;
594
+ job.completedAt = Date.now();
595
+ return true;
596
+ }
597
+
598
+ /**
599
+ * Cancel a pending or assigned job.
600
+ *
601
+ * @param {string} jobId
602
+ * @param {string} [reason]
603
+ * @returns {boolean}
604
+ */
605
+ cancel(jobId, reason) {
606
+ const job = this.#jobs.get(jobId);
607
+ if (!job) return false;
608
+ if (job.status !== 'pending' && job.status !== 'assigned') return false;
609
+ job.status = 'cancelled';
610
+ job.result = new ComputeResult({
611
+ jobId,
612
+ status: 'cancelled',
613
+ error: reason ?? 'Cancelled by requester',
614
+ });
615
+ job.completedAt = Date.now();
616
+ return true;
617
+ }
618
+
619
+ /**
620
+ * List all pending requests.
621
+ * @returns {ComputeRequest[]}
622
+ */
623
+ listPending() {
624
+ const results = [];
625
+ for (const job of this.#jobs.values()) {
626
+ if (job.status === 'pending') results.push(job.request);
627
+ }
628
+ return results;
629
+ }
630
+
631
+ /**
632
+ * List jobs filtered by status.
633
+ *
634
+ * @param {string} status
635
+ * @returns {object[]}
636
+ */
637
+ listByStatus(status) {
638
+ const results = [];
639
+ for (const job of this.#jobs.values()) {
640
+ if (job.status === status) results.push({ ...job });
641
+ }
642
+ return results;
643
+ }
644
+
645
+ /** @returns {number} */
646
+ get size() {
647
+ return this.#jobs.size;
648
+ }
649
+
650
+ /**
651
+ * Remove completed/cancelled/error/timeout jobs older than maxAgeMs.
652
+ *
653
+ * @param {number} [maxAgeMs=300000] - Default 5 minutes
654
+ * @returns {number} count of jobs pruned
655
+ */
656
+ pruneCompleted(maxAgeMs = 300_000) {
657
+ const cutoff = Date.now() - maxAgeMs;
658
+ const terminal = new Set(['completed', 'cancelled', 'error', 'timeout']);
659
+ let count = 0;
660
+ for (const [jobId, job] of this.#jobs) {
661
+ if (terminal.has(job.status) && job.completedAt && job.completedAt <= cutoff) {
662
+ this.#jobs.delete(jobId);
663
+ count++;
664
+ }
665
+ }
666
+ return count;
667
+ }
668
+ }
669
+
670
+ // ---------------------------------------------------------------------------
671
+ // Internal helpers
672
+ // ---------------------------------------------------------------------------
673
+
674
+ let _idCounter = 0;
675
+
676
+ /** Generate a unique-ish job ID. */
677
+ function _genId() {
678
+ return `job_${Date.now().toString(36)}_${(++_idCounter).toString(36)}`;
679
+ }