@johnhenry/browsermesh-apps 0.0.1 → 0.1.1
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.
- package/package.json +17 -6
- package/src/payments.mjs +107 -15
- package/src/peer-health.mjs +124 -15
- package/src/peer-session.mjs +28 -8
- package/src/peer-timestamp.mjs +121 -29
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@johnhenry/browsermesh-apps",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"description": "Application layer: marketplace, chat, payments, compute, orchestration, and agent tools for BrowserMesh",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.mjs",
|
|
@@ -20,11 +20,22 @@
|
|
|
20
20
|
"directory": "packages/browsermesh-apps"
|
|
21
21
|
},
|
|
22
22
|
"peerDependencies": {
|
|
23
|
-
"@johnhenry/browsermesh-primitives": ">=0.0.0",
|
|
24
|
-
"@johnhenry/browsermesh-core": ">=0.0.0",
|
|
25
|
-
"@johnhenry/browsermesh-transport": ">=0.0.0",
|
|
26
|
-
"@johnhenry/browsermesh-sync": ">=0.0.0",
|
|
27
|
-
"@johnhenry/browsermesh-discovery": ">=0.0.0"
|
|
23
|
+
"@johnhenry/browsermesh-primitives": ">=0.0.1 <1.0.0",
|
|
24
|
+
"@johnhenry/browsermesh-core": ">=0.1.0 <1.0.0",
|
|
25
|
+
"@johnhenry/browsermesh-transport": ">=0.1.0 <1.0.0",
|
|
26
|
+
"@johnhenry/browsermesh-sync": ">=0.0.0 <1.0.0",
|
|
27
|
+
"@johnhenry/browsermesh-discovery": ">=0.0.1 <1.0.0"
|
|
28
|
+
},
|
|
29
|
+
"peerDependenciesMeta": {
|
|
30
|
+
"@johnhenry/browsermesh-transport": {
|
|
31
|
+
"optional": true
|
|
32
|
+
},
|
|
33
|
+
"@johnhenry/browsermesh-core": {
|
|
34
|
+
"optional": true
|
|
35
|
+
},
|
|
36
|
+
"@johnhenry/browsermesh-discovery": {
|
|
37
|
+
"optional": true
|
|
38
|
+
}
|
|
28
39
|
},
|
|
29
40
|
"scripts": {
|
|
30
41
|
"test": "node --import ./test/_setup-globals.mjs --test test/*.test.mjs"
|
package/src/payments.mjs
CHANGED
|
@@ -493,22 +493,48 @@ export class PaymentChannel {
|
|
|
493
493
|
/**
|
|
494
494
|
* Open the channel with an initial deposit.
|
|
495
495
|
*
|
|
496
|
+
* `remoteDeposit` is what the *counterparty* funded the channel with, as
|
|
497
|
+
* reported by their PAYMENT_OPEN message. It exists because a channel has
|
|
498
|
+
* two sides and only one of them runs this method with first-hand
|
|
499
|
+
* knowledge: without it, the receiving side of an open handshake starts at
|
|
500
|
+
* `remoteBalance = 0` while the initiator sits at `localBalance = deposit`,
|
|
501
|
+
* and the two views can never converge -- every subsequent update is
|
|
502
|
+
* computed from a starting point they disagree about. See
|
|
503
|
+
* `PaymentRouter.broadcastOpen()` for the wire side of this.
|
|
504
|
+
*
|
|
505
|
+
* One-sided funding stays the default: `open(100)` behaves exactly as
|
|
506
|
+
* before, including throwing on a non-positive amount. A pure counterparty
|
|
507
|
+
* mirror is `open(0, 100)` -- zero of your own credits, 100 of theirs --
|
|
508
|
+
* which is why the positivity check is on the *total*, not on the local
|
|
509
|
+
* side alone.
|
|
510
|
+
*
|
|
496
511
|
* @param {number} initialDeposit - Amount to deposit into local balance
|
|
512
|
+
* @param {number} [remoteDeposit=0] - Amount the counterparty deposited,
|
|
513
|
+
* credited to `remoteBalance`
|
|
497
514
|
*/
|
|
498
|
-
open(initialDeposit) {
|
|
515
|
+
open(initialDeposit, remoteDeposit = 0) {
|
|
499
516
|
if (this.#state !== 'idle') {
|
|
500
517
|
throw new Error(`Cannot open channel in state: ${this.#state}`);
|
|
501
518
|
}
|
|
502
|
-
if (typeof initialDeposit !== 'number' || initialDeposit
|
|
519
|
+
if (typeof initialDeposit !== 'number' || Number.isNaN(initialDeposit) || initialDeposit < 0) {
|
|
520
|
+
throw new RangeError('Initial deposit must be positive');
|
|
521
|
+
}
|
|
522
|
+
if (typeof remoteDeposit !== 'number' || Number.isNaN(remoteDeposit) || remoteDeposit < 0) {
|
|
523
|
+
throw new RangeError('Remote deposit must not be negative');
|
|
524
|
+
}
|
|
525
|
+
if (initialDeposit + remoteDeposit <= 0) {
|
|
526
|
+
// Preserves the pre-existing message for the one-argument form, which
|
|
527
|
+
// is the only way this is reachable without an explicit remoteDeposit.
|
|
503
528
|
throw new RangeError('Initial deposit must be positive');
|
|
504
529
|
}
|
|
505
|
-
if (initialDeposit > this.#capacity) {
|
|
530
|
+
if (initialDeposit + remoteDeposit > this.#capacity) {
|
|
506
531
|
throw new RangeError(
|
|
507
|
-
`Deposit ${initialDeposit} exceeds capacity ${this.#capacity}`
|
|
532
|
+
`Deposit ${initialDeposit + remoteDeposit} exceeds capacity ${this.#capacity}`
|
|
508
533
|
);
|
|
509
534
|
}
|
|
510
535
|
this.#state = 'opening';
|
|
511
536
|
this.#localBalance = initialDeposit;
|
|
537
|
+
this.#remoteBalance = remoteDeposit;
|
|
512
538
|
this.#state = 'open';
|
|
513
539
|
}
|
|
514
540
|
|
|
@@ -570,6 +596,11 @@ export class PaymentChannel {
|
|
|
570
596
|
* updates are rejected (this method returns a rejected Promise). Without
|
|
571
597
|
* a verifyFn, behavior is unchanged: synchronous, unconditional apply.
|
|
572
598
|
*
|
|
599
|
+
* `amount` is checked the same way `pay()` checks it — a finite number
|
|
600
|
+
* greater than zero. A signature proves the counterparty wrote the value,
|
|
601
|
+
* not that the value is sane, and this update arrives straight off the
|
|
602
|
+
* wire via `PaymentRouter`'s PAYMENT_UPDATE handler.
|
|
603
|
+
*
|
|
573
604
|
* @param {PaymentUpdate} update
|
|
574
605
|
* @returns {void|Promise<void>}
|
|
575
606
|
*/
|
|
@@ -585,6 +616,19 @@ export class PaymentChannel {
|
|
|
585
616
|
`Stale sequence: got ${update.sequence}, expected > ${this.#sequence}`
|
|
586
617
|
);
|
|
587
618
|
}
|
|
619
|
+
// A negative amount runs #applyReceive backwards and moves credits from
|
|
620
|
+
// the receiver to the sender; a string turns `localBalance += amount`
|
|
621
|
+
// into concatenation; NaN or Infinity poisons both balances for the life
|
|
622
|
+
// of the channel. None of these are reachable through pay(), so they can
|
|
623
|
+
// only arrive from the counterparty.
|
|
624
|
+
if (typeof update.amount !== 'number' || !Number.isFinite(update.amount) || update.amount <= 0) {
|
|
625
|
+
throw new RangeError(
|
|
626
|
+
`Rejected payment update seq ${update.sequence}: ` +
|
|
627
|
+
`amount must be a finite number greater than zero, got ${
|
|
628
|
+
typeof update.amount === 'number' ? update.amount : typeof update.amount
|
|
629
|
+
}`
|
|
630
|
+
);
|
|
631
|
+
}
|
|
588
632
|
if (!this.#verifyFn) {
|
|
589
633
|
this.#applyReceive(update);
|
|
590
634
|
return;
|
|
@@ -1146,11 +1190,14 @@ export class PaymentRouter {
|
|
|
1146
1190
|
*
|
|
1147
1191
|
* @param {string} remotePodId
|
|
1148
1192
|
* @param {number} [capacity]
|
|
1149
|
-
* @param {object} [signingOpts] - Forwarded to PaymentChannel
|
|
1150
|
-
* signed updates and mutual close
|
|
1193
|
+
* @param {object} [signingOpts] - Forwarded to PaymentChannel. Enables
|
|
1194
|
+
* signed updates and mutual close, and carries `channelId` when both
|
|
1195
|
+
* sides must agree on one (see broadcastOpen()). Omit for unchanged,
|
|
1196
|
+
* unsigned behavior with a locally-generated id.
|
|
1151
1197
|
* @param {Function} [signingOpts.signFn]
|
|
1152
1198
|
* @param {Function} [signingOpts.verifyFn]
|
|
1153
1199
|
* @param {Uint8Array} [signingOpts.remotePublicKey]
|
|
1200
|
+
* @param {string} [signingOpts.channelId]
|
|
1154
1201
|
* @returns {PaymentChannel}
|
|
1155
1202
|
*/
|
|
1156
1203
|
openChannel(remotePodId, capacity, signingOpts) {
|
|
@@ -1305,10 +1352,26 @@ export class PaymentRouter {
|
|
|
1305
1352
|
// Inbound: channel open request
|
|
1306
1353
|
subscribeFn(PAYMENT_OPEN, (payload, fromPodId) => {
|
|
1307
1354
|
try {
|
|
1308
|
-
const { remotePodId, capacity } = payload;
|
|
1309
|
-
if (remotePodId
|
|
1310
|
-
|
|
1311
|
-
|
|
1355
|
+
const { remotePodId, capacity, channelId, deposit } = payload;
|
|
1356
|
+
if (remotePodId !== this.#localPodId) return;
|
|
1357
|
+
|
|
1358
|
+
// Adopt the initiator's channelId when they sent one. Signed updates
|
|
1359
|
+
// and close claims are keyed by channelId, so a locally-generated one
|
|
1360
|
+
// would make every message from the initiator fail the
|
|
1361
|
+
// 'Channel ID mismatch' check in receive().
|
|
1362
|
+
const ch = this.openChannel(
|
|
1363
|
+
fromPodId,
|
|
1364
|
+
capacity,
|
|
1365
|
+
typeof channelId === 'string' && channelId ? { channelId } : undefined,
|
|
1366
|
+
);
|
|
1367
|
+
|
|
1368
|
+
// Adopt the initiator's deposit as our view of *their* balance, so
|
|
1369
|
+
// both sides start from the same numbers. Senders that predate this
|
|
1370
|
+
// field send no deposit; the channel is then left idle exactly as
|
|
1371
|
+
// before, which is the old (non-converging) behaviour rather than a
|
|
1372
|
+
// new failure.
|
|
1373
|
+
if (typeof deposit === 'number' && Number.isFinite(deposit) && deposit > 0) {
|
|
1374
|
+
ch.open(0, deposit);
|
|
1312
1375
|
}
|
|
1313
1376
|
} catch (e) { silentCatch('clawser-mesh-payments', 'ignore-duplicate-or-invalid-opens', e) }
|
|
1314
1377
|
});
|
|
@@ -1384,13 +1447,42 @@ export class PaymentRouter {
|
|
|
1384
1447
|
/**
|
|
1385
1448
|
* Broadcast a channel open over the transport.
|
|
1386
1449
|
*
|
|
1450
|
+
* The message carries the channel's id and this side's deposit as well as
|
|
1451
|
+
* its capacity. Both are what let the counterparty build a mirror that
|
|
1452
|
+
* agrees with ours: the id because signed updates and close claims are
|
|
1453
|
+
* keyed by it, the deposit because otherwise the receiver's `remoteBalance`
|
|
1454
|
+
* starts at 0 while ours starts at the deposit, and no later message ever
|
|
1455
|
+
* reconciles the difference.
|
|
1456
|
+
*
|
|
1457
|
+
* Defaults are read from the local channel to `remotePodId` when one
|
|
1458
|
+
* exists, so the normal sequence -- `openChannel()`, `open(deposit)`,
|
|
1459
|
+
* `broadcastOpen()` -- needs no extra arguments. Call this *after*
|
|
1460
|
+
* `open()`, or the deposit on the wire is 0.
|
|
1461
|
+
*
|
|
1462
|
+
* Wire compatibility: `channelId` and `deposit` are additional fields. A
|
|
1463
|
+
* peer running the older code ignores them and behaves as it did before;
|
|
1464
|
+
* this side ignores their absence in an incoming message the same way. Only
|
|
1465
|
+
* when both ends send them do the two views actually converge.
|
|
1466
|
+
*
|
|
1387
1467
|
* @param {string} remotePodId
|
|
1388
|
-
* @param {number} [capacity]
|
|
1468
|
+
* @param {number} [capacity] - Defaults to the local channel's capacity
|
|
1469
|
+
* @param {object} [opts]
|
|
1470
|
+
* @param {string} [opts.channelId] - Defaults to the local channel's id
|
|
1471
|
+
* @param {number} [opts.deposit] - Defaults to the local channel's current
|
|
1472
|
+
* localBalance
|
|
1389
1473
|
*/
|
|
1390
|
-
broadcastOpen(remotePodId, capacity) {
|
|
1391
|
-
if (this.#broadcastFn)
|
|
1392
|
-
|
|
1393
|
-
|
|
1474
|
+
broadcastOpen(remotePodId, capacity, opts = {}) {
|
|
1475
|
+
if (!this.#broadcastFn) return;
|
|
1476
|
+
const ch = this.#channels.get(remotePodId);
|
|
1477
|
+
const payload = {
|
|
1478
|
+
remotePodId,
|
|
1479
|
+
capacity: capacity != null ? capacity : ch?.capacity,
|
|
1480
|
+
};
|
|
1481
|
+
const channelId = opts.channelId != null ? opts.channelId : ch?.channelId;
|
|
1482
|
+
if (channelId != null) payload.channelId = channelId;
|
|
1483
|
+
const deposit = opts.deposit != null ? opts.deposit : ch?.localBalance;
|
|
1484
|
+
if (deposit != null) payload.deposit = deposit;
|
|
1485
|
+
this.#broadcastFn(PAYMENT_OPEN, payload);
|
|
1394
1486
|
}
|
|
1395
1487
|
|
|
1396
1488
|
/**
|
package/src/peer-health.mjs
CHANGED
|
@@ -108,9 +108,16 @@ export class MigrationResult {
|
|
|
108
108
|
/** @type {string} */
|
|
109
109
|
toPod
|
|
110
110
|
|
|
111
|
-
/**
|
|
111
|
+
/**
|
|
112
|
+
* What was actually redeployed to `toPod`, or null when nothing was.
|
|
113
|
+
* Never a summary word like 'all' -- see `deployed` for the itemised list.
|
|
114
|
+
* @type {string|null}
|
|
115
|
+
*/
|
|
112
116
|
workload
|
|
113
117
|
|
|
118
|
+
/** @type {string[]} names of the skills deployed to toPod (may be empty) */
|
|
119
|
+
deployed
|
|
120
|
+
|
|
114
121
|
/** @type {number} */
|
|
115
122
|
durationMs
|
|
116
123
|
|
|
@@ -123,6 +130,7 @@ export class MigrationResult {
|
|
|
123
130
|
* @param {string} opts.fromPod
|
|
124
131
|
* @param {string} opts.toPod
|
|
125
132
|
* @param {string} [opts.workload=null]
|
|
133
|
+
* @param {string[]} [opts.deployed=[]]
|
|
126
134
|
* @param {number} [opts.durationMs=0]
|
|
127
135
|
* @param {string} [opts.error=null]
|
|
128
136
|
*/
|
|
@@ -131,6 +139,7 @@ export class MigrationResult {
|
|
|
131
139
|
fromPod,
|
|
132
140
|
toPod,
|
|
133
141
|
workload = null,
|
|
142
|
+
deployed = [],
|
|
134
143
|
durationMs = 0,
|
|
135
144
|
error = null,
|
|
136
145
|
}) {
|
|
@@ -138,6 +147,7 @@ export class MigrationResult {
|
|
|
138
147
|
this.fromPod = fromPod
|
|
139
148
|
this.toPod = toPod
|
|
140
149
|
this.workload = workload
|
|
150
|
+
this.deployed = deployed
|
|
141
151
|
this.durationMs = durationMs
|
|
142
152
|
this.error = error
|
|
143
153
|
}
|
|
@@ -152,6 +162,7 @@ export class MigrationResult {
|
|
|
152
162
|
fromPod: this.fromPod,
|
|
153
163
|
toPod: this.toPod,
|
|
154
164
|
workload: this.workload,
|
|
165
|
+
deployed: [...this.deployed],
|
|
155
166
|
durationMs: this.durationMs,
|
|
156
167
|
error: this.error,
|
|
157
168
|
}
|
|
@@ -518,21 +529,38 @@ export class AutoMigrator {
|
|
|
518
529
|
/** @type {Map<string, Set<Function>>} event -> listeners */
|
|
519
530
|
#listeners = new Map()
|
|
520
531
|
|
|
532
|
+
/** @type {Function|null} resolves the workload to redeploy on the target */
|
|
533
|
+
#resolveWorkload = null
|
|
534
|
+
|
|
521
535
|
/**
|
|
522
536
|
* @param {object} opts
|
|
523
537
|
* @param {HealthMonitor} opts.healthMonitor - Health monitor to listen to
|
|
524
538
|
* @param {object} opts.orchestrator - Object with drainPod(podId), listPods(), deploySkill(podId, skill)
|
|
539
|
+
* @param {Function} [opts.resolveWorkload] - `(fromPodId, { services }) => Promise<Array<{name, content}>>`
|
|
540
|
+
* Supplies the skills to deploy on the target. A failed peer cannot be asked
|
|
541
|
+
* what it was running, so the workload has to come from the caller -- a
|
|
542
|
+
* registry, a manifest, whatever the application uses as its source of
|
|
543
|
+
* truth. Without it the migrator can drain the dead pod but cannot start
|
|
544
|
+
* anything in its place, and says so in the result rather than reporting a
|
|
545
|
+
* migration that did not happen.
|
|
525
546
|
* @param {Function} [opts.onLog] - Logging callback (level, msg)
|
|
526
547
|
*/
|
|
527
|
-
constructor({ healthMonitor, orchestrator, onLog }) {
|
|
548
|
+
constructor({ healthMonitor, orchestrator, resolveWorkload, onLog }) {
|
|
528
549
|
if (!healthMonitor) {
|
|
529
550
|
throw new Error('healthMonitor is required')
|
|
530
551
|
}
|
|
531
552
|
if (!orchestrator || typeof orchestrator.drainPod !== 'function') {
|
|
532
553
|
throw new Error('orchestrator with drainPod() method is required')
|
|
533
554
|
}
|
|
555
|
+
if (resolveWorkload !== undefined && typeof resolveWorkload !== 'function') {
|
|
556
|
+
throw new Error('resolveWorkload must be a function')
|
|
557
|
+
}
|
|
558
|
+
if (resolveWorkload && typeof orchestrator.deploySkill !== 'function') {
|
|
559
|
+
throw new Error('orchestrator with deploySkill() method is required when resolveWorkload is given')
|
|
560
|
+
}
|
|
534
561
|
this.#healthMonitor = healthMonitor
|
|
535
562
|
this.#orchestrator = orchestrator
|
|
563
|
+
this.#resolveWorkload = resolveWorkload || null
|
|
536
564
|
this.#onLog = onLog || (() => {})
|
|
537
565
|
}
|
|
538
566
|
|
|
@@ -602,29 +630,64 @@ export class AutoMigrator {
|
|
|
602
630
|
this.#onLog(2, `Migrating workload from ${fromPodId} to ${target}`)
|
|
603
631
|
|
|
604
632
|
try {
|
|
605
|
-
|
|
633
|
+
// drainPod reports failure for exactly the case this path exists to
|
|
634
|
+
// handle -- a pod that has already dropped out of the peer table -- so
|
|
635
|
+
// its verdict decides the migration. An orchestrator that returns
|
|
636
|
+
// nothing is giving no verdict, which is not the same as failing.
|
|
637
|
+
const drain = await this.#orchestrator.drainPod(fromPodId)
|
|
638
|
+
if (drain && drain.success === false) {
|
|
639
|
+
const reason = drain.error || `drainPod("${fromPodId}") reported failure`
|
|
640
|
+
return this.#fail(fromPodId, target, reason, startTime)
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
// Move the workload. Nothing below runs on a peer until deploySkill has
|
|
644
|
+
// said it succeeded, and `deployed` records what actually landed.
|
|
645
|
+
const workload = await this.#workloadFor(fromPodId)
|
|
646
|
+
const deployed = []
|
|
647
|
+
|
|
648
|
+
for (const item of workload) {
|
|
649
|
+
const name = item?.name || 'unnamed skill'
|
|
650
|
+
let outcome
|
|
651
|
+
try {
|
|
652
|
+
outcome = await this.#orchestrator.deploySkill(target, item?.content)
|
|
653
|
+
} catch (err) {
|
|
654
|
+
return this.#fail(
|
|
655
|
+
fromPodId, target,
|
|
656
|
+
`deploying "${name}" to ${target} threw: ${err.message}`,
|
|
657
|
+
startTime, deployed,
|
|
658
|
+
)
|
|
659
|
+
}
|
|
660
|
+
if (!outcome || outcome.success === false) {
|
|
661
|
+
const why = outcome?.error || 'deploySkill reported failure'
|
|
662
|
+
return this.#fail(
|
|
663
|
+
fromPodId, target,
|
|
664
|
+
`deploying "${name}" to ${target} failed: ${why}`,
|
|
665
|
+
startTime, deployed,
|
|
666
|
+
)
|
|
667
|
+
}
|
|
668
|
+
deployed.push(name)
|
|
669
|
+
}
|
|
606
670
|
|
|
607
671
|
const result = new MigrationResult({
|
|
608
672
|
success: true,
|
|
609
673
|
fromPod: fromPodId,
|
|
610
674
|
toPod: target,
|
|
611
|
-
|
|
675
|
+
// Only ever names what was really deployed. This used to read 'all'
|
|
676
|
+
// unconditionally, while nothing at all was started on the target.
|
|
677
|
+
workload: deployed.length ? deployed.join(', ') : null,
|
|
678
|
+
deployed,
|
|
612
679
|
durationMs: Date.now() - startTime,
|
|
613
680
|
})
|
|
614
681
|
this.#emit('migrated', result)
|
|
615
|
-
this.#onLog(
|
|
682
|
+
this.#onLog(
|
|
683
|
+
2,
|
|
684
|
+
deployed.length
|
|
685
|
+
? `Migration complete: ${fromPodId} -> ${target}, deployed ${deployed.length} (${result.durationMs}ms)`
|
|
686
|
+
: `Drained ${fromPodId}; NO workload was deployed to ${target} (${result.durationMs}ms)`,
|
|
687
|
+
)
|
|
616
688
|
return result
|
|
617
689
|
} catch (err) {
|
|
618
|
-
|
|
619
|
-
success: false,
|
|
620
|
-
fromPod: fromPodId,
|
|
621
|
-
toPod: target,
|
|
622
|
-
error: err.message,
|
|
623
|
-
durationMs: Date.now() - startTime,
|
|
624
|
-
})
|
|
625
|
-
this.#emit('migration-failed', result)
|
|
626
|
-
this.#onLog(0, `Migration failed: ${fromPodId} -> ${target}: ${err.message}`)
|
|
627
|
-
return result
|
|
690
|
+
return this.#fail(fromPodId, target, err.message, startTime)
|
|
628
691
|
}
|
|
629
692
|
}
|
|
630
693
|
|
|
@@ -657,6 +720,52 @@ export class AutoMigrator {
|
|
|
657
720
|
|
|
658
721
|
// -- Internal -------------------------------------------------------------
|
|
659
722
|
|
|
723
|
+
/**
|
|
724
|
+
* Build a failed MigrationResult, emit it, and log it.
|
|
725
|
+
*
|
|
726
|
+
* @param {string} fromPodId
|
|
727
|
+
* @param {string} target
|
|
728
|
+
* @param {string} error - Why the migration failed
|
|
729
|
+
* @param {number} startTime
|
|
730
|
+
* @param {string[]} [deployed=[]] - Skills that did land before the failure
|
|
731
|
+
* @returns {MigrationResult}
|
|
732
|
+
*/
|
|
733
|
+
#fail(fromPodId, target, error, startTime, deployed = []) {
|
|
734
|
+
const result = new MigrationResult({
|
|
735
|
+
success: false,
|
|
736
|
+
fromPod: fromPodId,
|
|
737
|
+
toPod: target,
|
|
738
|
+
workload: deployed.length ? deployed.join(', ') : null,
|
|
739
|
+
deployed,
|
|
740
|
+
error,
|
|
741
|
+
durationMs: Date.now() - startTime,
|
|
742
|
+
})
|
|
743
|
+
this.#emit('migration-failed', result)
|
|
744
|
+
this.#onLog(0, `Migration failed: ${fromPodId} -> ${target}: ${error}`)
|
|
745
|
+
return result
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
/**
|
|
749
|
+
* Resolve the workload to deploy on the target, normalised to a list.
|
|
750
|
+
*
|
|
751
|
+
* @param {string} fromPodId - Pod whose workload is being moved
|
|
752
|
+
* @returns {Promise<Array<{name: string, content: *}>>}
|
|
753
|
+
*/
|
|
754
|
+
async #workloadFor(fromPodId) {
|
|
755
|
+
if (!this.#resolveWorkload) {
|
|
756
|
+
// Loud, because the alternative is a self-healing component that heals
|
|
757
|
+
// nothing while reporting success.
|
|
758
|
+
this.#onLog(
|
|
759
|
+
1,
|
|
760
|
+
`No resolveWorkload configured: ${fromPodId}'s workload will NOT be redeployed`,
|
|
761
|
+
)
|
|
762
|
+
return []
|
|
763
|
+
}
|
|
764
|
+
const resolved = await this.#resolveWorkload(fromPodId, { services: this.#services })
|
|
765
|
+
if (!resolved) return []
|
|
766
|
+
return Array.isArray(resolved) ? resolved : [resolved]
|
|
767
|
+
}
|
|
768
|
+
|
|
660
769
|
/**
|
|
661
770
|
* Select the best target pod for migration.
|
|
662
771
|
* Prefers failoverPriority list, then picks the healthiest peer.
|
package/src/peer-session.mjs
CHANGED
|
@@ -443,14 +443,34 @@ export class PeerSession {
|
|
|
443
443
|
return
|
|
444
444
|
}
|
|
445
445
|
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
446
|
+
/*
|
|
447
|
+
* Arm a pong deadline, and DO NOT disturb one already outstanding.
|
|
448
|
+
*
|
|
449
|
+
* This used to `clearTimeout` unconditionally before re-arming, which
|
|
450
|
+
* made the detector incapable of firing under its own defaults: the
|
|
451
|
+
* interval is 15s and the timeout 60s, so each ping cancelled the
|
|
452
|
+
* deadline three times over before it could elapse. `#handlePong()`
|
|
453
|
+
* already clears it on a reply -- that is the only thing that should.
|
|
454
|
+
*
|
|
455
|
+
* Measured against a transport that accepts sends and never pongs, at
|
|
456
|
+
* the shipped 1:4 ratio scaled down: 21 pings, state still `active`.
|
|
457
|
+
* The only configuration in which it worked was the inverted one,
|
|
458
|
+
* interval longer than timeout.
|
|
459
|
+
*
|
|
460
|
+
* The surviving escape was `send()` throwing, which a buffering or
|
|
461
|
+
* half-open transport will not do -- so a peer whose tab closed kept a
|
|
462
|
+
* session `active` forever, `send()` kept succeeding into a dead pipe,
|
|
463
|
+
* and no 'session:suspend' ever fired.
|
|
464
|
+
*/
|
|
465
|
+
if (this.#heartbeatTimer === null) {
|
|
466
|
+
this.#heartbeatTimer = setTimeout(() => {
|
|
467
|
+
this.#heartbeatTimer = null
|
|
468
|
+
if (this.#state === 'active') {
|
|
469
|
+
this.#onLog(1, `Heartbeat timeout for session ${this.#sessionId}, suspending`)
|
|
470
|
+
this.suspend()
|
|
471
|
+
}
|
|
472
|
+
}, this.#heartbeatTimeoutMs)
|
|
473
|
+
}
|
|
454
474
|
}, intervalMs)
|
|
455
475
|
}
|
|
456
476
|
|
package/src/peer-timestamp.mjs
CHANGED
|
@@ -82,24 +82,81 @@ export class TimestampProof {
|
|
|
82
82
|
}
|
|
83
83
|
|
|
84
84
|
/**
|
|
85
|
-
* Verify
|
|
85
|
+
* Verify this proof.
|
|
86
86
|
*
|
|
87
|
-
*
|
|
88
|
-
*
|
|
87
|
+
* Without `verifyFn` this checks STRUCTURE ONLY -- that three fields have
|
|
88
|
+
* plausible types -- and says so in `checked`. A structurally valid proof is
|
|
89
|
+
* not an authentic one: `confidence` is a number the proof asserts about
|
|
90
|
+
* itself, and a forgery can assert it too.
|
|
91
|
+
*
|
|
92
|
+
* With `verifyFn` every signature in the proof is checked. Both the
|
|
93
|
+
* authority signature and the witness entries are signed by `issuedBy` --
|
|
94
|
+
* the authority attests to what each peer reported, peers do not sign for
|
|
95
|
+
* themselves -- so `issuedBy` is the pod whose key `verifyFn` must resolve,
|
|
96
|
+
* for witness entries as much as for the proof itself.
|
|
97
|
+
*
|
|
98
|
+
* @param {Function} [verifyFn] - async (signature: Uint8Array, data: string, signerPodId: string) => boolean
|
|
99
|
+
* @returns {Promise<{ valid: boolean, confidence: number, checked: 'structure'|'signatures', reason?: string }>}
|
|
89
100
|
*/
|
|
90
|
-
verify(verifyFn) {
|
|
101
|
+
async verify(verifyFn) {
|
|
91
102
|
// Basic structural checks
|
|
92
103
|
if (!this.eventHash || typeof this.eventHash !== 'string') {
|
|
93
|
-
return { valid: false, confidence: 0 }
|
|
104
|
+
return { valid: false, confidence: 0, checked: 'structure', reason: 'eventHash missing or not a string' }
|
|
94
105
|
}
|
|
95
106
|
if (typeof this.canonicalTimestamp !== 'number' || this.canonicalTimestamp <= 0) {
|
|
96
|
-
return { valid: false, confidence: 0 }
|
|
107
|
+
return { valid: false, confidence: 0, checked: 'structure', reason: 'canonicalTimestamp missing or not a positive number' }
|
|
97
108
|
}
|
|
98
109
|
if (!Array.isArray(this.witnesses) || this.witnesses.length === 0) {
|
|
99
|
-
return { valid: false, confidence: 0 }
|
|
110
|
+
return { valid: false, confidence: 0, checked: 'structure', reason: 'witnesses missing or empty' }
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (typeof verifyFn !== 'function') {
|
|
114
|
+
return { valid: true, confidence: this.confidence, checked: 'structure' }
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if (!this.signature) {
|
|
118
|
+
return { valid: false, confidence: 0, checked: 'signatures', reason: 'proof carries no authority signature' }
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const check = async (signature, data, what) => {
|
|
122
|
+
let ok
|
|
123
|
+
try {
|
|
124
|
+
ok = await verifyFn(fromBase64(signature), data, this.issuedBy)
|
|
125
|
+
} catch (err) {
|
|
126
|
+
return `verifying ${what} threw: ${err.message}`
|
|
127
|
+
}
|
|
128
|
+
return ok === true ? null : `${what} failed verification`
|
|
100
129
|
}
|
|
101
130
|
|
|
102
|
-
|
|
131
|
+
const authorityFailure = await check(
|
|
132
|
+
this.signature,
|
|
133
|
+
`${this.eventHash}:${this.canonicalTimestamp}`,
|
|
134
|
+
`authority signature from ${this.issuedBy}`,
|
|
135
|
+
)
|
|
136
|
+
if (authorityFailure) {
|
|
137
|
+
return { valid: false, confidence: 0, checked: 'signatures', reason: authorityFailure }
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
for (const witness of this.witnesses) {
|
|
141
|
+
if (!witness || !witness.signature) {
|
|
142
|
+
return {
|
|
143
|
+
valid: false,
|
|
144
|
+
confidence: 0,
|
|
145
|
+
checked: 'signatures',
|
|
146
|
+
reason: `witness ${witness?.podId ?? '(unnamed)'} carries no signature`,
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
const witnessFailure = await check(
|
|
150
|
+
witness.signature,
|
|
151
|
+
`${this.eventHash}:${witness.podId}:${witness.localTimestamp}`,
|
|
152
|
+
`witness entry for ${witness.podId}`,
|
|
153
|
+
)
|
|
154
|
+
if (witnessFailure) {
|
|
155
|
+
return { valid: false, confidence: 0, checked: 'signatures', reason: witnessFailure }
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
return { valid: true, confidence: this.confidence, checked: 'signatures' }
|
|
103
160
|
}
|
|
104
161
|
|
|
105
162
|
/**
|
|
@@ -154,6 +211,25 @@ function toBase64(bytes) {
|
|
|
154
211
|
return btoa(String.fromCharCode(...bytes))
|
|
155
212
|
}
|
|
156
213
|
|
|
214
|
+
/**
|
|
215
|
+
* Decode a base64 string back to a Uint8Array.
|
|
216
|
+
* Signatures travel through toJSON as base64; a verify callback expects the
|
|
217
|
+
* bytes it was given at signing time, so passing the string through would
|
|
218
|
+
* compare characters against byte values and never match.
|
|
219
|
+
*
|
|
220
|
+
* @param {string} b64
|
|
221
|
+
* @returns {Uint8Array}
|
|
222
|
+
*/
|
|
223
|
+
function fromBase64(b64) {
|
|
224
|
+
if (typeof Buffer !== 'undefined') {
|
|
225
|
+
return new Uint8Array(Buffer.from(b64, 'base64'))
|
|
226
|
+
}
|
|
227
|
+
const binary = atob(b64)
|
|
228
|
+
const bytes = new Uint8Array(binary.length)
|
|
229
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)
|
|
230
|
+
return bytes
|
|
231
|
+
}
|
|
232
|
+
|
|
157
233
|
// ---------------------------------------------------------------------------
|
|
158
234
|
// TimestampAuthority — distributed consensus coordinator
|
|
159
235
|
// ---------------------------------------------------------------------------
|
|
@@ -271,45 +347,61 @@ export class TimestampAuthority {
|
|
|
271
347
|
/**
|
|
272
348
|
* Verify a TimestampProof.
|
|
273
349
|
*
|
|
274
|
-
* Checks
|
|
275
|
-
*
|
|
350
|
+
* Checks every signature in the proof against the key of the pod that
|
|
351
|
+
* issued it. This requires `identity.verify(signature, data, signerPodId)`.
|
|
352
|
+
* Without it the only check available is re-signing with THIS authority's
|
|
353
|
+
* own key, which answers a different question -- "did I issue this?" -- and
|
|
354
|
+
* is reported as such rather than as authenticity.
|
|
276
355
|
*
|
|
277
356
|
* @param {TimestampProof} proof
|
|
278
|
-
* @returns {Promise<{ valid: boolean, reason?: string }>}
|
|
357
|
+
* @returns {Promise<{ valid: boolean, checked?: string, reason?: string }>}
|
|
279
358
|
*/
|
|
280
359
|
async verify(proof) {
|
|
281
360
|
if (!(proof instanceof TimestampProof)) {
|
|
282
361
|
return { valid: false, reason: 'Not a TimestampProof instance' }
|
|
283
362
|
}
|
|
284
363
|
|
|
285
|
-
|
|
286
|
-
|
|
364
|
+
if (this.#identity.verify) {
|
|
365
|
+
const result = await proof.verify(
|
|
366
|
+
(signature, data, signerPodId) => this.#identity.verify(signature, data, signerPodId),
|
|
367
|
+
)
|
|
368
|
+
if (!result.valid) {
|
|
369
|
+
return { valid: false, checked: result.checked, reason: result.reason }
|
|
370
|
+
}
|
|
371
|
+
return { valid: true, checked: 'signatures' }
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// No verify() on the identity: we can only re-sign and compare, which
|
|
375
|
+
// works solely for proofs this authority issued itself. Saying anything
|
|
376
|
+
// about a foreign proof here would be a guess.
|
|
377
|
+
if (proof.issuedBy !== this.#identity.podId) {
|
|
378
|
+
return {
|
|
379
|
+
valid: false,
|
|
380
|
+
checked: 'none',
|
|
381
|
+
reason: `Cannot verify a proof issued by ${proof.issuedBy}: identity has no verify() to check another pod's key`,
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
const structural = await proof.verify()
|
|
287
386
|
if (!structural.valid) {
|
|
288
|
-
return { valid: false, reason: 'Structural validation failed' }
|
|
387
|
+
return { valid: false, checked: 'structure', reason: structural.reason || 'Structural validation failed' }
|
|
289
388
|
}
|
|
290
389
|
|
|
291
|
-
// Verify authority signature matches eventHash + canonicalTimestamp
|
|
292
390
|
const expectedData = `${proof.eventHash}:${proof.canonicalTimestamp}`
|
|
293
|
-
const
|
|
294
|
-
const expectedB64 = toBase64(expectedSig)
|
|
295
|
-
|
|
391
|
+
const expectedB64 = toBase64(await this.#identity.sign(expectedData))
|
|
296
392
|
if (proof.signature !== expectedB64) {
|
|
297
|
-
return { valid: false, reason: 'Authority signature mismatch — eventHash or timestamp was tampered' }
|
|
393
|
+
return { valid: false, checked: 'self', reason: 'Authority signature mismatch — eventHash or timestamp was tampered' }
|
|
298
394
|
}
|
|
299
395
|
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
const witnessSigB64 = toBase64(witnessSig)
|
|
306
|
-
if (witness.signature !== witnessSigB64) {
|
|
307
|
-
return { valid: false, reason: `Witness signature mismatch for ${witness.podId}` }
|
|
308
|
-
}
|
|
396
|
+
for (const witness of proof.witnesses) {
|
|
397
|
+
const witnessData = `${proof.eventHash}:${witness.podId}:${witness.localTimestamp}`
|
|
398
|
+
const witnessSigB64 = toBase64(await this.#identity.sign(witnessData))
|
|
399
|
+
if (witness.signature !== witnessSigB64) {
|
|
400
|
+
return { valid: false, checked: 'self', reason: `Witness signature mismatch for ${witness.podId}` }
|
|
309
401
|
}
|
|
310
402
|
}
|
|
311
403
|
|
|
312
|
-
return { valid: true }
|
|
404
|
+
return { valid: true, checked: 'self' }
|
|
313
405
|
}
|
|
314
406
|
|
|
315
407
|
/**
|