@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,846 @@
1
+ /**
2
+ // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
+ * clawser-mesh-scheduler.js -- Mesh-aware task scheduling for BrowserMesh.
4
+ *
5
+ * Distributes tasks across mesh peers using configurable scheduling policies
6
+ * (best-fit, first-fit, round-robin, load-balanced). Includes a priority queue,
7
+ * constraint matching, retry logic, and callback-based lifecycle hooks.
8
+ *
9
+ * No browser-only imports at module level.
10
+ *
11
+ * Run tests:
12
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-scheduler.test.mjs
13
+ */
14
+
15
+ // ---------------------------------------------------------------------------
16
+ // Wire constants
17
+ // ---------------------------------------------------------------------------
18
+
19
+ /** Submit a task to the mesh scheduler */
20
+ export const SCHED_SUBMIT = 0xcc;
21
+ /** Query status of a scheduled task */
22
+ export const SCHED_STATUS = 0xcd;
23
+ /** Cancel a scheduled task */
24
+ export const SCHED_CANCEL = 0xce;
25
+ /** Result of a completed scheduled task */
26
+ export const SCHED_RESULT = 0xcf;
27
+
28
+ // ---------------------------------------------------------------------------
29
+ // Valid enumerations
30
+ // ---------------------------------------------------------------------------
31
+
32
+ const VALID_STATUSES = Object.freeze([
33
+ 'pending', 'queued', 'assigned', 'running', 'completed', 'failed', 'cancelled',
34
+ ]);
35
+
36
+ const VALID_PRIORITIES = Object.freeze([
37
+ 'low', 'normal', 'high', 'critical',
38
+ ]);
39
+
40
+ const PRIORITY_WEIGHT = Object.freeze({
41
+ critical: 4,
42
+ high: 3,
43
+ normal: 2,
44
+ low: 1,
45
+ });
46
+
47
+ const VALID_POLICIES = Object.freeze([
48
+ 'best-fit', 'first-fit', 'round-robin', 'load-balanced',
49
+ ]);
50
+
51
+ // ---------------------------------------------------------------------------
52
+ // ScheduledTask
53
+ // ---------------------------------------------------------------------------
54
+
55
+ /**
56
+ * A task to be scheduled across the mesh.
57
+ */
58
+ export class ScheduledTask {
59
+ /**
60
+ * @param {object} opts
61
+ * @param {string} opts.id
62
+ * @param {string} opts.type
63
+ * @param {*} opts.payload
64
+ * @param {'low'|'normal'|'high'|'critical'} [opts.priority='normal']
65
+ * @param {object} [opts.constraints={}]
66
+ * @param {string} opts.submittedBy
67
+ * @param {number} [opts.submittedAt]
68
+ * @param {number|null} [opts.deadline]
69
+ * @param {number} [opts.retries=0]
70
+ * @param {number} [opts.maxRetries=3]
71
+ * @param {string} [opts.status='pending']
72
+ */
73
+ constructor({
74
+ id,
75
+ type,
76
+ payload,
77
+ priority = 'normal',
78
+ constraints = {},
79
+ submittedBy,
80
+ submittedAt,
81
+ deadline,
82
+ retries = 0,
83
+ maxRetries = 3,
84
+ status = 'pending',
85
+ }) {
86
+ if (!id || typeof id !== 'string') {
87
+ throw new Error('id is required and must be a non-empty string');
88
+ }
89
+ if (!type || typeof type !== 'string') {
90
+ throw new Error('type is required and must be a non-empty string');
91
+ }
92
+ if (!submittedBy || typeof submittedBy !== 'string') {
93
+ throw new Error('submittedBy is required and must be a non-empty string');
94
+ }
95
+ if (!VALID_PRIORITIES.includes(priority)) {
96
+ throw new Error(`Invalid priority: "${priority}". Must be one of: ${VALID_PRIORITIES.join(', ')}`);
97
+ }
98
+ if (!VALID_STATUSES.includes(status)) {
99
+ throw new Error(`Invalid status: "${status}". Must be one of: ${VALID_STATUSES.join(', ')}`);
100
+ }
101
+
102
+ this.id = id;
103
+ this.type = type;
104
+ this.payload = payload !== undefined ? payload : null;
105
+ this.priority = priority;
106
+ this.constraints = constraints ? { ...constraints } : {};
107
+ this.submittedBy = submittedBy;
108
+ this.submittedAt = submittedAt ?? Date.now();
109
+ this.deadline = deadline ?? null;
110
+ this.retries = retries;
111
+ this.maxRetries = maxRetries;
112
+ this.status = status;
113
+ // Internal fields set during lifecycle
114
+ this.assignedTo = null;
115
+ this.result = null;
116
+ this.error = null;
117
+ this.assignedAt = null;
118
+ this.completedAt = null;
119
+ }
120
+
121
+ /**
122
+ * Whether the task has passed its deadline.
123
+ * @param {number} [now]
124
+ * @returns {boolean}
125
+ */
126
+ isExpired(now = Date.now()) {
127
+ if (this.deadline === null || this.deadline === undefined) return false;
128
+ return now > this.deadline;
129
+ }
130
+
131
+ /**
132
+ * Whether the task may be retried.
133
+ * @returns {boolean}
134
+ */
135
+ canRetry() {
136
+ return this.retries < this.maxRetries;
137
+ }
138
+
139
+ toJSON() {
140
+ return {
141
+ id: this.id,
142
+ type: this.type,
143
+ payload: this.payload != null && typeof this.payload === 'object'
144
+ ? JSON.parse(JSON.stringify(this.payload))
145
+ : this.payload,
146
+ priority: this.priority,
147
+ constraints: { ...this.constraints },
148
+ submittedBy: this.submittedBy,
149
+ submittedAt: this.submittedAt,
150
+ deadline: this.deadline,
151
+ retries: this.retries,
152
+ maxRetries: this.maxRetries,
153
+ status: this.status,
154
+ assignedTo: this.assignedTo,
155
+ result: this.result,
156
+ error: this.error,
157
+ assignedAt: this.assignedAt,
158
+ completedAt: this.completedAt,
159
+ };
160
+ }
161
+
162
+ /**
163
+ * @param {object} data
164
+ * @returns {ScheduledTask}
165
+ */
166
+ static fromJSON(data) {
167
+ const task = new ScheduledTask({
168
+ id: data.id,
169
+ type: data.type,
170
+ payload: data.payload,
171
+ priority: data.priority,
172
+ constraints: data.constraints,
173
+ submittedBy: data.submittedBy,
174
+ submittedAt: data.submittedAt,
175
+ deadline: data.deadline,
176
+ retries: data.retries,
177
+ maxRetries: data.maxRetries,
178
+ status: data.status,
179
+ });
180
+ task.assignedTo = data.assignedTo ?? null;
181
+ task.result = data.result ?? null;
182
+ task.error = data.error ?? null;
183
+ task.assignedAt = data.assignedAt ?? null;
184
+ task.completedAt = data.completedAt ?? null;
185
+ return task;
186
+ }
187
+ }
188
+
189
+ // ---------------------------------------------------------------------------
190
+ // TaskConstraints
191
+ // ---------------------------------------------------------------------------
192
+
193
+ /**
194
+ * Scheduling constraints for a task.
195
+ */
196
+ export class TaskConstraints {
197
+ /**
198
+ * @param {object} [opts]
199
+ * @param {string[]} [opts.requiredCaps=[]]
200
+ * @param {number} [opts.minMemoryMb=0]
201
+ * @param {number} [opts.minCpuCores=0]
202
+ * @param {boolean} [opts.preferLocal=false]
203
+ * @param {number|null} [opts.maxLatencyMs=null]
204
+ * @param {string[]} [opts.affinityPodIds=[]]
205
+ * @param {string[]} [opts.antiAffinityPodIds=[]]
206
+ */
207
+ constructor(opts = {}) {
208
+ this.requiredCaps = opts.requiredCaps ? [...opts.requiredCaps] : [];
209
+ this.minMemoryMb = opts.minMemoryMb ?? 0;
210
+ this.minCpuCores = opts.minCpuCores ?? 0;
211
+ this.preferLocal = opts.preferLocal ?? false;
212
+ this.maxLatencyMs = opts.maxLatencyMs ?? null;
213
+ this.affinityPodIds = opts.affinityPodIds ? [...opts.affinityPodIds] : [];
214
+ this.antiAffinityPodIds = opts.antiAffinityPodIds ? [...opts.antiAffinityPodIds] : [];
215
+ }
216
+
217
+ /**
218
+ * Check whether a resource descriptor satisfies these constraints.
219
+ *
220
+ * @param {object} resourceDescriptor
221
+ * @param {string[]} [resourceDescriptor.capabilities]
222
+ * @param {object} [resourceDescriptor.resources]
223
+ * @param {number} [resourceDescriptor.resources.memory]
224
+ * @param {number} [resourceDescriptor.resources.cpu]
225
+ * @param {string} [resourceDescriptor.podId]
226
+ * @returns {boolean}
227
+ */
228
+ matches(resourceDescriptor) {
229
+ if (!resourceDescriptor) return false;
230
+
231
+ // Required capabilities
232
+ if (this.requiredCaps.length > 0) {
233
+ const caps = resourceDescriptor.capabilities || [];
234
+ for (const cap of this.requiredCaps) {
235
+ if (!caps.includes(cap)) return false;
236
+ }
237
+ }
238
+
239
+ // Minimum memory
240
+ const mem = resourceDescriptor.resources?.memory ?? 0;
241
+ if (this.minMemoryMb > 0 && mem < this.minMemoryMb) return false;
242
+
243
+ // Minimum CPU cores
244
+ const cpu = resourceDescriptor.resources?.cpu ?? 0;
245
+ if (this.minCpuCores > 0 && cpu < this.minCpuCores) return false;
246
+
247
+ // Affinity: must be one of the listed pods (if any listed)
248
+ if (this.affinityPodIds.length > 0) {
249
+ if (!resourceDescriptor.podId || !this.affinityPodIds.includes(resourceDescriptor.podId)) {
250
+ return false;
251
+ }
252
+ }
253
+
254
+ // Anti-affinity: must NOT be any of the listed pods
255
+ if (this.antiAffinityPodIds.length > 0) {
256
+ if (resourceDescriptor.podId && this.antiAffinityPodIds.includes(resourceDescriptor.podId)) {
257
+ return false;
258
+ }
259
+ }
260
+
261
+ return true;
262
+ }
263
+
264
+ toJSON() {
265
+ return {
266
+ requiredCaps: [...this.requiredCaps],
267
+ minMemoryMb: this.minMemoryMb,
268
+ minCpuCores: this.minCpuCores,
269
+ preferLocal: this.preferLocal,
270
+ maxLatencyMs: this.maxLatencyMs,
271
+ affinityPodIds: [...this.affinityPodIds],
272
+ antiAffinityPodIds: [...this.antiAffinityPodIds],
273
+ };
274
+ }
275
+
276
+ /**
277
+ * @param {object} data
278
+ * @returns {TaskConstraints}
279
+ */
280
+ static fromJSON(data) {
281
+ return new TaskConstraints({
282
+ requiredCaps: data.requiredCaps,
283
+ minMemoryMb: data.minMemoryMb,
284
+ minCpuCores: data.minCpuCores,
285
+ preferLocal: data.preferLocal,
286
+ maxLatencyMs: data.maxLatencyMs,
287
+ affinityPodIds: data.affinityPodIds,
288
+ antiAffinityPodIds: data.antiAffinityPodIds,
289
+ });
290
+ }
291
+ }
292
+
293
+ // ---------------------------------------------------------------------------
294
+ // TaskQueue
295
+ // ---------------------------------------------------------------------------
296
+
297
+ /**
298
+ * Priority queue for scheduled tasks.
299
+ *
300
+ * Default ordering: higher priority first, then earlier deadline,
301
+ * then earlier submittedAt.
302
+ */
303
+ export class TaskQueue {
304
+ /** @type {ScheduledTask[]} */
305
+ #items = [];
306
+ #comparator;
307
+
308
+ /**
309
+ * @param {object} [opts]
310
+ * @param {function} [opts.comparator] - (a, b) => number. Negative = a first.
311
+ */
312
+ constructor(opts = {}) {
313
+ this.#comparator = opts.comparator ?? _defaultComparator;
314
+ }
315
+
316
+ /**
317
+ * Add a task to the queue.
318
+ * @param {ScheduledTask} task
319
+ */
320
+ enqueue(task) {
321
+ this.#items.push(task);
322
+ this.#items.sort(this.#comparator);
323
+ }
324
+
325
+ /**
326
+ * Remove and return the highest-priority task.
327
+ * @returns {ScheduledTask|null}
328
+ */
329
+ dequeue() {
330
+ if (this.#items.length === 0) return null;
331
+ return this.#items.shift();
332
+ }
333
+
334
+ /**
335
+ * View the highest-priority task without removing.
336
+ * @returns {ScheduledTask|null}
337
+ */
338
+ peek() {
339
+ if (this.#items.length === 0) return null;
340
+ return this.#items[0];
341
+ }
342
+
343
+ /**
344
+ * Remove a task by ID.
345
+ * @param {string} taskId
346
+ * @returns {boolean}
347
+ */
348
+ remove(taskId) {
349
+ const idx = this.#items.findIndex(t => t.id === taskId);
350
+ if (idx === -1) return false;
351
+ this.#items.splice(idx, 1);
352
+ return true;
353
+ }
354
+
355
+ /** @returns {number} */
356
+ get size() {
357
+ return this.#items.length;
358
+ }
359
+
360
+ /** @returns {boolean} */
361
+ get isEmpty() {
362
+ return this.#items.length === 0;
363
+ }
364
+
365
+ /**
366
+ * Return a sorted copy of the queue contents.
367
+ * @returns {ScheduledTask[]}
368
+ */
369
+ toArray() {
370
+ return [...this.#items];
371
+ }
372
+ }
373
+
374
+ /**
375
+ * Default comparator: higher priority weight first, then earlier deadline,
376
+ * then earlier submittedAt.
377
+ */
378
+ function _defaultComparator(a, b) {
379
+ const wa = PRIORITY_WEIGHT[a.priority] ?? 0;
380
+ const wb = PRIORITY_WEIGHT[b.priority] ?? 0;
381
+ if (wa !== wb) return wb - wa;
382
+
383
+ // Earlier deadline first; null deadlines sort to the end
384
+ const da = a.deadline ?? Infinity;
385
+ const db = b.deadline ?? Infinity;
386
+ if (da !== db) return da - db;
387
+
388
+ return (a.submittedAt ?? 0) - (b.submittedAt ?? 0);
389
+ }
390
+
391
+ // ---------------------------------------------------------------------------
392
+ // MeshScheduler
393
+ // ---------------------------------------------------------------------------
394
+
395
+ /**
396
+ * Distributes tasks across mesh peers with configurable scheduling policies.
397
+ */
398
+ export class MeshScheduler {
399
+ /** @type {string} */
400
+ #localPodId;
401
+ /** @type {Map<string, ScheduledTask>} */
402
+ #tasks = new Map();
403
+ /** @type {TaskQueue} */
404
+ #queue = new TaskQueue();
405
+ /** @type {Map<string, object>} podId -> resource descriptor */
406
+ #nodes = new Map();
407
+ /** @type {number} */
408
+ #maxConcurrent;
409
+ /** @type {string} */
410
+ #schedulingPolicy;
411
+ /** @type {number} round-robin index */
412
+ #rrIndex = 0;
413
+
414
+ // Stats
415
+ #totalSubmitted = 0;
416
+ #completed = 0;
417
+ #failed = 0;
418
+ #totalWaitMs = 0;
419
+ #totalRunMs = 0;
420
+
421
+ // Callbacks
422
+ #onAssigned = [];
423
+ #onCompleted = [];
424
+ #onFailed = [];
425
+
426
+ /**
427
+ * @param {object} opts
428
+ * @param {string} opts.localPodId
429
+ * @param {number} [opts.maxConcurrent=10]
430
+ * @param {'best-fit'|'first-fit'|'round-robin'|'load-balanced'} [opts.schedulingPolicy='best-fit']
431
+ */
432
+ constructor({ localPodId, maxConcurrent = 10, schedulingPolicy = 'best-fit' } = {}) {
433
+ if (!localPodId || typeof localPodId !== 'string') {
434
+ throw new Error('localPodId is required and must be a non-empty string');
435
+ }
436
+ if (!VALID_POLICIES.includes(schedulingPolicy)) {
437
+ throw new Error(`Invalid scheduling policy: "${schedulingPolicy}". Must be one of: ${VALID_POLICIES.join(', ')}`);
438
+ }
439
+
440
+ this.#localPodId = localPodId;
441
+ this.#maxConcurrent = maxConcurrent;
442
+ this.#schedulingPolicy = schedulingPolicy;
443
+ }
444
+
445
+ /** @returns {number} */
446
+ get maxConcurrent() {
447
+ return this.#maxConcurrent;
448
+ }
449
+
450
+ /** @returns {string} */
451
+ get schedulingPolicy() {
452
+ return this.#schedulingPolicy;
453
+ }
454
+
455
+ // -- Task lifecycle -------------------------------------------------------
456
+
457
+ /**
458
+ * Submit a task to the scheduler.
459
+ * @param {ScheduledTask} task
460
+ * @returns {Promise<string>} task ID
461
+ */
462
+ async submit(task) {
463
+ if (this.#tasks.has(task.id)) {
464
+ throw new Error(`Task "${task.id}" already exists`);
465
+ }
466
+ task.status = 'queued';
467
+ this.#tasks.set(task.id, task);
468
+ this.#queue.enqueue(task);
469
+ this.#totalSubmitted++;
470
+ return task.id;
471
+ }
472
+
473
+ /**
474
+ * Cancel a pending/queued/assigned/running task.
475
+ * @param {string} taskId
476
+ * @returns {Promise<boolean>}
477
+ */
478
+ async cancel(taskId) {
479
+ const task = this.#tasks.get(taskId);
480
+ if (!task) return false;
481
+ if (task.status === 'completed' || task.status === 'failed' || task.status === 'cancelled') {
482
+ return false;
483
+ }
484
+ task.status = 'cancelled';
485
+ task.completedAt = Date.now();
486
+ this.#queue.remove(taskId);
487
+ return true;
488
+ }
489
+
490
+ /**
491
+ * Assign a task to a specific pod.
492
+ * @param {string} taskId
493
+ * @param {string} podId
494
+ */
495
+ assign(taskId, podId) {
496
+ const task = this.#tasks.get(taskId);
497
+ if (!task) throw new Error(`Task "${taskId}" not found`);
498
+ task.status = 'assigned';
499
+ task.assignedTo = podId;
500
+ task.assignedAt = Date.now();
501
+ this.#queue.remove(taskId);
502
+ for (const cb of this.#onAssigned) cb(taskId, podId);
503
+ }
504
+
505
+ /**
506
+ * Mark a task as completed with a result.
507
+ * @param {string} taskId
508
+ * @param {*} result
509
+ */
510
+ complete(taskId, result) {
511
+ const task = this.#tasks.get(taskId);
512
+ if (!task) throw new Error(`Task "${taskId}" not found`);
513
+ task.status = 'completed';
514
+ task.result = result;
515
+ task.completedAt = Date.now();
516
+ this.#completed++;
517
+
518
+ // Track timing
519
+ if (task.assignedAt) {
520
+ this.#totalRunMs += task.completedAt - task.assignedAt;
521
+ }
522
+ if (task.submittedAt && task.assignedAt) {
523
+ this.#totalWaitMs += task.assignedAt - task.submittedAt;
524
+ }
525
+
526
+ this.#queue.remove(taskId);
527
+ for (const cb of this.#onCompleted) cb(taskId, result);
528
+ }
529
+
530
+ /**
531
+ * Mark a task as failed, possibly requeue for retry.
532
+ * @param {string} taskId
533
+ * @param {string} error
534
+ */
535
+ fail(taskId, error) {
536
+ const task = this.#tasks.get(taskId);
537
+ if (!task) throw new Error(`Task "${taskId}" not found`);
538
+
539
+ task.retries++;
540
+
541
+ if (task.canRetry()) {
542
+ // Requeue for retry
543
+ task.status = 'queued';
544
+ task.assignedTo = null;
545
+ task.assignedAt = null;
546
+ task.error = null;
547
+ this.#queue.enqueue(task);
548
+ } else {
549
+ // Permanent failure
550
+ task.status = 'failed';
551
+ task.error = error;
552
+ task.completedAt = Date.now();
553
+ this.#failed++;
554
+ for (const cb of this.#onFailed) cb(taskId, error);
555
+ }
556
+ }
557
+
558
+ /**
559
+ * Look up a task by ID.
560
+ * @param {string} taskId
561
+ * @returns {ScheduledTask|null}
562
+ */
563
+ getTask(taskId) {
564
+ return this.#tasks.get(taskId) ?? null;
565
+ }
566
+
567
+ /**
568
+ * List tasks, optionally filtered.
569
+ * @param {object} [filter]
570
+ * @param {string} [filter.status]
571
+ * @param {string} [filter.type]
572
+ * @param {string} [filter.submittedBy]
573
+ * @returns {ScheduledTask[]}
574
+ */
575
+ listTasks(filter) {
576
+ const results = [];
577
+ for (const task of this.#tasks.values()) {
578
+ if (filter) {
579
+ if (filter.status && task.status !== filter.status) continue;
580
+ if (filter.type && task.type !== filter.type) continue;
581
+ if (filter.submittedBy && task.submittedBy !== filter.submittedBy) continue;
582
+ }
583
+ results.push(task);
584
+ }
585
+ return results;
586
+ }
587
+
588
+ /**
589
+ * Count of tasks in queued status.
590
+ * @returns {number}
591
+ */
592
+ getQueueDepth() {
593
+ let count = 0;
594
+ for (const task of this.#tasks.values()) {
595
+ if (task.status === 'queued') count++;
596
+ }
597
+ return count;
598
+ }
599
+
600
+ /**
601
+ * Count of tasks in assigned or running status.
602
+ * @returns {number}
603
+ */
604
+ getRunningCount() {
605
+ let count = 0;
606
+ for (const task of this.#tasks.values()) {
607
+ if (task.status === 'assigned' || task.status === 'running') count++;
608
+ }
609
+ return count;
610
+ }
611
+
612
+ // -- Node management ------------------------------------------------------
613
+
614
+ /**
615
+ * Register a node with its resource descriptor.
616
+ * @param {string} podId
617
+ * @param {object} resources
618
+ */
619
+ registerNode(podId, resources) {
620
+ this.#nodes.set(podId, resources);
621
+ }
622
+
623
+ /**
624
+ * Remove a registered node.
625
+ * @param {string} podId
626
+ * @returns {boolean}
627
+ */
628
+ unregisterNode(podId) {
629
+ return this.#nodes.delete(podId);
630
+ }
631
+
632
+ // -- Scheduling cycle -----------------------------------------------------
633
+
634
+ /**
635
+ * Run one scheduling cycle: match queued tasks to available nodes.
636
+ * @returns {Promise<number>} number of tasks assigned
637
+ */
638
+ async schedule() {
639
+ if (this.#nodes.size === 0) return 0;
640
+
641
+ let assigned = 0;
642
+ const nodeIds = [...this.#nodes.keys()];
643
+
644
+ // Collect queued tasks from the queue
645
+ const queuedTasks = [];
646
+ const queueSnapshot = this.#queue.toArray();
647
+ for (const task of queueSnapshot) {
648
+ if (task.status === 'queued') {
649
+ queuedTasks.push(task);
650
+ }
651
+ }
652
+
653
+ for (const task of queuedTasks) {
654
+ // Check concurrent limit
655
+ if (this.getRunningCount() >= this.#maxConcurrent) break;
656
+
657
+ // Resolve constraints
658
+ const constraints = task.constraints && task.constraints.requiredCaps
659
+ ? TaskConstraints.fromJSON(task.constraints)
660
+ : new TaskConstraints(task.constraints || {});
661
+
662
+ // Find matching nodes
663
+ const matchingNodes = [];
664
+ for (const nodeId of nodeIds) {
665
+ const nodeRes = this.#nodes.get(nodeId);
666
+ if (constraints.matches(nodeRes)) {
667
+ matchingNodes.push({ podId: nodeId, ...nodeRes });
668
+ }
669
+ }
670
+
671
+ if (matchingNodes.length === 0) continue;
672
+
673
+ let selectedPodId;
674
+
675
+ switch (this.#schedulingPolicy) {
676
+ case 'first-fit':
677
+ selectedPodId = matchingNodes[0].podId;
678
+ break;
679
+
680
+ case 'round-robin':
681
+ selectedPodId = matchingNodes[this.#rrIndex % matchingNodes.length].podId;
682
+ this.#rrIndex++;
683
+ break;
684
+
685
+ case 'load-balanced': {
686
+ let minLoad = Infinity;
687
+ let minPod = matchingNodes[0].podId;
688
+ for (const node of matchingNodes) {
689
+ const load = node.load ?? 0;
690
+ if (load < minLoad) {
691
+ minLoad = load;
692
+ minPod = node.podId;
693
+ }
694
+ }
695
+ selectedPodId = minPod;
696
+ break;
697
+ }
698
+
699
+ case 'best-fit':
700
+ default: {
701
+ // Score by how well resources match constraints
702
+ let bestScore = -1;
703
+ let bestPod = matchingNodes[0].podId;
704
+ for (const node of matchingNodes) {
705
+ let score = 0;
706
+ const mem = node.resources?.memory ?? 0;
707
+ const cpu = node.resources?.cpu ?? 0;
708
+ if (constraints.minMemoryMb > 0 && mem > 0) {
709
+ // Tighter fit = higher score (inverse of excess)
710
+ score += Math.max(0, 100 - Math.abs(mem - constraints.minMemoryMb) / 10);
711
+ } else {
712
+ score += mem / 100;
713
+ }
714
+ if (constraints.minCpuCores > 0 && cpu > 0) {
715
+ score += Math.max(0, 50 - Math.abs(cpu - constraints.minCpuCores) * 5);
716
+ } else {
717
+ score += cpu * 5;
718
+ }
719
+ if (score > bestScore) {
720
+ bestScore = score;
721
+ bestPod = node.podId;
722
+ }
723
+ }
724
+ selectedPodId = bestPod;
725
+ break;
726
+ }
727
+ }
728
+
729
+ this.assign(task.id, selectedPodId);
730
+ assigned++;
731
+ }
732
+
733
+ return assigned;
734
+ }
735
+
736
+ // -- Callbacks ------------------------------------------------------------
737
+
738
+ /**
739
+ * Register a callback for task assignment.
740
+ * @param {function(string, string)} cb - (taskId, podId)
741
+ */
742
+ onTaskAssigned(cb) {
743
+ this.#onAssigned.push(cb);
744
+ }
745
+
746
+ /**
747
+ * Register a callback for task completion.
748
+ * @param {function(string, *)} cb - (taskId, result)
749
+ */
750
+ onTaskCompleted(cb) {
751
+ this.#onCompleted.push(cb);
752
+ }
753
+
754
+ /**
755
+ * Register a callback for permanent task failure.
756
+ * @param {function(string, string)} cb - (taskId, error)
757
+ */
758
+ onTaskFailed(cb) {
759
+ this.#onFailed.push(cb);
760
+ }
761
+
762
+ // -- Stats ----------------------------------------------------------------
763
+
764
+ /**
765
+ * @returns {{ totalSubmitted: number, completed: number, failed: number, avgWaitMs: number, avgRunMs: number }}
766
+ */
767
+ getStats() {
768
+ const completedAndFailed = this.#completed + this.#failed;
769
+ return {
770
+ totalSubmitted: this.#totalSubmitted,
771
+ completed: this.#completed,
772
+ failed: this.#failed,
773
+ avgWaitMs: completedAndFailed > 0 ? Math.round(this.#totalWaitMs / completedAndFailed) : 0,
774
+ avgRunMs: this.#completed > 0 ? Math.round(this.#totalRunMs / this.#completed) : 0,
775
+ };
776
+ }
777
+
778
+ // -- Serialization --------------------------------------------------------
779
+
780
+ toJSON() {
781
+ const tasks = [];
782
+ for (const task of this.#tasks.values()) {
783
+ tasks.push(task.toJSON());
784
+ }
785
+ const nodes = [];
786
+ for (const [podId, res] of this.#nodes) {
787
+ nodes.push({ podId, ...res });
788
+ }
789
+ return {
790
+ localPodId: this.#localPodId,
791
+ maxConcurrent: this.#maxConcurrent,
792
+ schedulingPolicy: this.#schedulingPolicy,
793
+ tasks,
794
+ nodes,
795
+ stats: {
796
+ totalSubmitted: this.#totalSubmitted,
797
+ completed: this.#completed,
798
+ failed: this.#failed,
799
+ totalWaitMs: this.#totalWaitMs,
800
+ totalRunMs: this.#totalRunMs,
801
+ },
802
+ };
803
+ }
804
+
805
+ /**
806
+ * @param {object} data
807
+ * @returns {MeshScheduler}
808
+ */
809
+ static fromJSON(data) {
810
+ const sched = new MeshScheduler({
811
+ localPodId: data.localPodId,
812
+ maxConcurrent: data.maxConcurrent,
813
+ schedulingPolicy: data.schedulingPolicy,
814
+ });
815
+
816
+ // Restore stats
817
+ if (data.stats) {
818
+ sched.#totalSubmitted = data.stats.totalSubmitted ?? 0;
819
+ sched.#completed = data.stats.completed ?? 0;
820
+ sched.#failed = data.stats.failed ?? 0;
821
+ sched.#totalWaitMs = data.stats.totalWaitMs ?? 0;
822
+ sched.#totalRunMs = data.stats.totalRunMs ?? 0;
823
+ }
824
+
825
+ // Restore nodes
826
+ if (data.nodes) {
827
+ for (const node of data.nodes) {
828
+ const { podId, ...rest } = node;
829
+ sched.#nodes.set(podId, rest);
830
+ }
831
+ }
832
+
833
+ // Restore tasks
834
+ if (data.tasks) {
835
+ for (const taskData of data.tasks) {
836
+ const task = ScheduledTask.fromJSON(taskData);
837
+ sched.#tasks.set(task.id, task);
838
+ if (task.status === 'queued' || task.status === 'pending') {
839
+ sched.#queue.enqueue(task);
840
+ }
841
+ }
842
+ }
843
+
844
+ return sched;
845
+ }
846
+ }