@johnhenry/browsermesh-apps 0.11.0 → 0.12.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,784 @@
1
+ /**
2
+ * pod-supervisor.mjs -- issue #185 item 6: links, monitors, and restart
3
+ * policy over the hosted-pods control surface ("docs/hosted-pods.md" §8a's
4
+ * last control-surface row -- "`restart` policy + `status`/`spawn`/`drain`
5
+ * in a loop").
6
+ *
7
+ * PRECEDENT: OTP. Three ideas, each already present elsewhere in this
8
+ * surface and composed here rather than reinvented:
9
+ *
10
+ * - **links** -- parent/child pod relationships that cascade on drain
11
+ * (`docs/hosted-pods.md` §7: "Hosted pods are `child`-role pods of the
12
+ * host pod ... `drainPod()` on the host must cascade." This file is
13
+ * the general form of that rule, for ANY parent pod, not just a host.)
14
+ * - **monitors** -- be told when a pod you care about dies, without
15
+ * taking responsibility for it.
16
+ * - **supervisors** -- `podspec.restart` (`host-protocol.mjs`) finally
17
+ * gets an implementation: watch a pod's `exit` events and re-spawn it
18
+ * per its declared policy.
19
+ *
20
+ * THE ONE RULE THAT MATTERS: **a restart is a NEW `spawn` request the host
21
+ * may refuse.** This file never calls a driver directly and never bypasses
22
+ * `pod-host-service.mjs`'s gate -- every (re)spawn goes through
23
+ * `orchestrator.spawnPod()` (which itself goes through the gated
24
+ * `PodHostClient`) or, when no orchestrator was supplied, straight through
25
+ * an injected `PodHostClient`. A host that returns `EACCES`/`EBUSY` for a
26
+ * restart is answered the same way `MeshctlSpawnTool` answers it for a
27
+ * fresh spawn: "the orchestrator proposes, the host accepts" -- this file
28
+ * proposes a DIFFERENT host next (`pickHost`) rather than hammering the one
29
+ * that refused.
30
+ *
31
+ * NO POLLING BY DEFAULT. Everything here is event-driven: the
32
+ * `PodHostClient`'s own `onEvent()` (lifecycle/log/exit, forwarded by
33
+ * `pod-host-service.mjs` to every requester with "interest" in a pod -- see
34
+ * that module's `noteInterest()`) and, for host loss, `PeerNode`'s own
35
+ * `'peer:disconnect'` signal (`peer-node.mjs`). `reconcileIntervalMs` is
36
+ * an OPT-IN, slow safety-net sweep for the case an event genuinely never
37
+ * arrives (a dropped message, a host that vanished without a disconnect
38
+ * signal ever firing) -- not the primary mechanism.
39
+ *
40
+ * COMPOSES WITH `AutoMigrator` (`peer-health.mjs`), DOES NOT DUPLICATE IT.
41
+ * `AutoMigrator` already does "move work when a peer degrades" for the
42
+ * MESH-PEER population (`#knownPeers`, skills redeployed via
43
+ * `deploySkill()`). This file does the analogous thing for the HOSTED-POD
44
+ * population (pods a `PodHostDriver` tracks, redeployed via `spawnPod()`).
45
+ * They watch different health signals (`HealthMonitor`'s heartbeat
46
+ * liveness vs. this file's `pod-host:event` stream) and move different
47
+ * things (skills on a bare peer vs. a podspec on a pod host); a mesh using
48
+ * both gets whole-peer failover from one and single-pod supervision from
49
+ * the other, with no overlap to reconcile.
50
+ *
51
+ * No browser-only imports at module level.
52
+ */
53
+
54
+ import { validatePodSpec, PodHostDriverError } from '@johnhenry/browsermesh-pod'
55
+ import { createPodHostClient } from './pod-host-service.mjs'
56
+ import { pickAutoHost } from './orchestrator.mjs'
57
+
58
+ /**
59
+ * Audit record kinds this file writes that are NOT already covered by
60
+ * `orchestrator.mjs`'s `PLACEMENT_AUDIT` (`placement_requested` /
61
+ * `placement_ready` / `placement_denied` are written automatically by
62
+ * `orchestrator.spawnPod()` for every (re)spawn this file issues -- see the
63
+ * module doc comment's "a restart is a new spawn" rule. This file never
64
+ * records those itself, to avoid double-recording the same placement).
65
+ */
66
+ export const SUPERVISOR_AUDIT = Object.freeze({
67
+ RESTART_SCHEDULED: 'supervisor_restart_scheduled',
68
+ RESTARTED: 'supervisor_restarted',
69
+ GAVE_UP: 'supervisor_gave_up',
70
+ CASCADE: 'supervisor_cascade',
71
+ HOST_LOST: 'supervisor_host_lost',
72
+ })
73
+
74
+ /** Default `restart.maxRestarts` when a podspec did not say (matches `host-protocol.mjs`'s own silence on a default -- 3 is this file's choice, not the protocol's). */
75
+ const DEFAULT_MAX_RESTARTS = 3
76
+ /** Default `restart.backoffMs` base. */
77
+ const DEFAULT_BACKOFF_MS = 1000
78
+ /** Backoff never waits longer than this, regardless of restart count. */
79
+ const MAX_BACKOFF_MS = 60_000
80
+
81
+ /** @param {{host: string, name: string}} ref @returns {string} */
82
+ function refKey(ref) {
83
+ return `${ref.host}::${ref.name}`
84
+ }
85
+
86
+ /**
87
+ * Whether `policy` says to restart a pod that exited with `{code, reason}`.
88
+ * `reason === 'drained'` is handled by the CALLER, before this is ever
89
+ * consulted -- an intentional drain is never a restart candidate under any
90
+ * policy (see `#onExit()`).
91
+ *
92
+ * @param {'never'|'on-failure'|'always'} policy
93
+ * @param {{code?: number, reason?: string}} exit
94
+ * @returns {boolean}
95
+ */
96
+ function policyWantsRestart(policy, { code, reason }) {
97
+ switch (policy) {
98
+ case 'always':
99
+ return true
100
+ case 'on-failure':
101
+ return code !== 0 || reason === 'crashed' || reason === 'host-lost'
102
+ case 'never':
103
+ default:
104
+ return false
105
+ }
106
+ }
107
+
108
+ /**
109
+ * Build the `PodSupervisor` (issue #185 item 6).
110
+ *
111
+ * @param {object} opts
112
+ * @param {object} [opts.orchestrator] - A `MeshOrchestrator`
113
+ * (`orchestrator.mjs`). Supplies `spawnPod()` (the gated restart path,
114
+ * which also records the requester-side `PLACEMENT_AUDIT` trail for
115
+ * free), the default `pickHost` (`pickAutoHost()` against this
116
+ * orchestrator), and -- via `.peerNode` -- the `'peer:disconnect'` signal
117
+ * `monitor()`'s synthesized `host-lost` events come from. Either this or
118
+ * `client` is required.
119
+ * @param {object} [opts.client] - A `PodHostClient`
120
+ * (`pod-host-service.mjs`), used directly when no `orchestrator` was
121
+ * given. No requester-side placement audit trail exists on this path
122
+ * (`PLACEMENT_AUDIT` is `MeshOrchestrator#recordPlacement()`'s to write,
123
+ * not a raw client's); `auditChain` records (`SUPERVISOR_AUDIT`) still
124
+ * work as long as `opts.auditChain`/`opts.peerNode` are supplied.
125
+ * @param {() => string[]} [opts.hosts] - Extra hosts the reconcile sweep
126
+ * and the fallback `pickHost` should consider, beyond the hosts already
127
+ * tracked because a pod is supervised on them.
128
+ * @param {(spec: object, opts?: {excludeHost?: string}) => Promise<string|null>} [opts.pickHost]
129
+ * Choose a re-placement host for a restart that cannot stay on its
130
+ * current host (refused with `EACCES`/`EBUSY`, or the host itself is
131
+ * gone -- `reason: 'host-lost'`). Defaults to `pickAutoHost()` against
132
+ * `orchestrator` for `spec.lane`, the same selection
133
+ * `MeshctlSpawnTool`/`meshctl spawn auto` use -- see `orchestrator.mjs`.
134
+ * Returns `null`/throws when no orchestrator and no override were given.
135
+ * @param {number} [opts.reconcileIntervalMs=0] - `0` disables the sweep
136
+ * (the default -- see module doc comment on why polling is not the
137
+ * primary mechanism).
138
+ * @param {number} [opts.maxConcurrentRestarts=1] - How many `spawn` calls
139
+ * this supervisor will have in flight for restarts at once; further
140
+ * restarts whose backoff has elapsed wait their turn.
141
+ * @param {() => number} [opts.now=Date.now]
142
+ * @param {Function} [opts.setTimeout] - Injectable, for fake-timer tests.
143
+ * @param {Function} [opts.clearTimeout] - Injectable, for fake-timer tests.
144
+ * @param {Function} [opts.onLog] - `(event, data) => void` debug logging.
145
+ * @param {object} [opts.auditChain] - Duck-typed `AuditChain`
146
+ * (`{append(authorPodId, operation, data, signFn)}`, matching
147
+ * `pod-host-service.mjs`'s own convention). Requires a `peerNode` to sign
148
+ * with -- taken from `orchestrator.peerNode` when present, or
149
+ * `opts.peerNode` directly.
150
+ * @param {object} [opts.peerNode] - Used for `'peer:disconnect'` ->
151
+ * synthesized `host-lost`, and for audit signing, when no `orchestrator`
152
+ * was supplied.
153
+ * @returns {object} A `PodSupervisor`.
154
+ */
155
+ export function createPodSupervisor({
156
+ orchestrator,
157
+ client,
158
+ hosts,
159
+ pickHost,
160
+ reconcileIntervalMs = 0,
161
+ maxConcurrentRestarts = 1,
162
+ now = Date.now,
163
+ setTimeout: injectedSetTimeout,
164
+ clearTimeout: injectedClearTimeout,
165
+ onLog,
166
+ auditChain,
167
+ peerNode,
168
+ } = {}) {
169
+ if (!orchestrator && !client) {
170
+ throw new Error('createPodSupervisor: orchestrator or client is required')
171
+ }
172
+
173
+ const log = onLog || (() => {})
174
+ const doSetTimeout = injectedSetTimeout || globalThis.setTimeout.bind(globalThis)
175
+ const doClearTimeout = injectedClearTimeout || globalThis.clearTimeout.bind(globalThis)
176
+ const effectivePeerNode = peerNode || orchestrator?.peerNode || null
177
+ const maxConcurrent = Math.max(1, maxConcurrentRestarts)
178
+
179
+ /** The `PodHostClient` every verb this file issues (other than restarts, which prefer `orchestrator.spawnPod()`) goes through. Built once, lazily. */
180
+ let hostClient = client || null
181
+ function getHostClient() {
182
+ if (hostClient) return hostClient
183
+ if (!effectivePeerNode) {
184
+ throw new Error('createPodSupervisor: no client and no peerNode to build one from')
185
+ }
186
+ hostClient = createPodHostClient({ peerNode: effectivePeerNode })
187
+ return hostClient
188
+ }
189
+
190
+ // -- state ------------------------------------------------------------
191
+ /** @type {Map<string, object>} refKey -> supervised-pod record */
192
+ const pods = new Map()
193
+ /** @type {Map<string, Set<string>>} parent refKey -> Set<child refKey> */
194
+ const childrenOf = new Map()
195
+ /** @type {Map<string, string>} child refKey -> parent refKey */
196
+ const parentOf = new Map()
197
+ /** @type {Map<string, Set<Function>>} refKey -> monitor callbacks */
198
+ const monitors = new Map()
199
+ /** @type {Map<string, Set<Function>>} event name -> listeners */
200
+ const listeners = new Map()
201
+
202
+ let activeRestarts = 0
203
+ /** @type {Function[]} queued restart attempts, FIFO, when `maxConcurrent` is saturated */
204
+ const restartQueue = []
205
+ let stopped = false
206
+ let reconcileTimer = null
207
+ let unsubscribeHostEvents = null
208
+ let unsubscribePeerDisconnect = null
209
+
210
+ /** @param {string} event @param {object} data */
211
+ function emit(event, data) {
212
+ const set = listeners.get(event)
213
+ if (!set) return
214
+ for (const fn of [...set]) {
215
+ try {
216
+ fn(data)
217
+ } catch {
218
+ // A throwing subscriber never breaks delivery to the others or to
219
+ // this file's own control flow -- the same rule `mesh-service.mjs`'s
220
+ // event bus applies everywhere else in this package.
221
+ }
222
+ }
223
+ }
224
+
225
+ /**
226
+ * @param {string} operation - A `SUPERVISOR_AUDIT` value.
227
+ * @param {object} data
228
+ */
229
+ async function audit(operation, data) {
230
+ if (!auditChain || typeof auditChain.append !== 'function') return
231
+ const podId = effectivePeerNode?.podId
232
+ if (!podId || typeof effectivePeerNode?.wallet?.sign !== 'function') return
233
+ try {
234
+ await auditChain.append(podId, operation, data, (payload) => effectivePeerNode.wallet.sign(podId, payload))
235
+ } catch (err) {
236
+ log('supervisor:audit-failed', { operation, error: err?.message || String(err) })
237
+ }
238
+ }
239
+
240
+ /** @param {string} key @param {{ref: object, event: object}} payload */
241
+ function fireMonitors(key, payload) {
242
+ const set = monitors.get(key)
243
+ if (!set) return
244
+ for (const fn of [...set]) {
245
+ try {
246
+ fn(payload)
247
+ } catch {
248
+ // Same isolation rule as `emit()`.
249
+ }
250
+ }
251
+ }
252
+
253
+ /**
254
+ * Re-key every map entry for `entry` after its host changes (a
255
+ * re-placed restart). `entry.ref` is the SAME object across the move --
256
+ * callers holding a `supervise()` handle's `.ref` see the new host
257
+ * without having to re-fetch anything.
258
+ * @param {object} entry
259
+ * @param {string} newHost
260
+ */
261
+ function rekey(entry, newHost) {
262
+ const oldKey = refKey(entry.ref)
263
+ entry.ref.host = newHost
264
+ entry.host = newHost
265
+ const newKey = refKey(entry.ref)
266
+ if (newKey === oldKey) return
267
+
268
+ pods.delete(oldKey)
269
+ pods.set(newKey, entry)
270
+
271
+ const mons = monitors.get(oldKey)
272
+ if (mons) { monitors.delete(oldKey); monitors.set(newKey, mons) }
273
+
274
+ const kids = childrenOf.get(oldKey)
275
+ if (kids) { childrenOf.delete(oldKey); childrenOf.set(newKey, kids) }
276
+
277
+ const parentKey = parentOf.get(oldKey)
278
+ if (parentKey) {
279
+ parentOf.delete(oldKey)
280
+ parentOf.set(newKey, parentKey)
281
+ const siblings = childrenOf.get(parentKey)
282
+ if (siblings) { siblings.delete(oldKey); siblings.add(newKey) }
283
+ }
284
+ }
285
+
286
+ /**
287
+ * Issue a (re)spawn -- ALWAYS through the gate. Prefers
288
+ * `orchestrator.spawnPod()` (gated `PodHostClient` round trip, plus the
289
+ * requester-side `PLACEMENT_AUDIT` trail for free); falls back to the
290
+ * raw `client.spawn()` when no orchestrator was supplied.
291
+ * @param {string} host
292
+ * @param {object} spec
293
+ * @returns {Promise<object>}
294
+ */
295
+ async function doSpawn(host, spec) {
296
+ if (orchestrator) return orchestrator.spawnPod(host, spec)
297
+ return getHostClient().spawn(host, spec)
298
+ }
299
+
300
+ /**
301
+ * @param {object} spec - normalized podspec
302
+ * @param {{excludeHost?: string}} [opts]
303
+ * @returns {Promise<string|null>}
304
+ */
305
+ async function choosePlacement(spec, opts = {}) {
306
+ if (pickHost) return pickHost(spec, opts)
307
+ if (orchestrator) {
308
+ const picked = await pickAutoHost(orchestrator, spec.lane)
309
+ if (!picked) return null
310
+ if (opts.excludeHost && picked.podId === opts.excludeHost) return null
311
+ return picked.podId
312
+ }
313
+ if (typeof hosts === 'function') {
314
+ const candidates = hosts().filter((h) => h !== opts.excludeHost)
315
+ return candidates[0] ?? null
316
+ }
317
+ return null
318
+ }
319
+
320
+ // -- public API: supervise / link / monitor / unsupervise -----------------
321
+
322
+ /**
323
+ * Spawn a pod (via `doSpawn()`, the gated path) and start supervising it
324
+ * per `spec.restart`. `spec.links.parent` implies `link()` against
325
+ * `{host, name: spec.links.parent}` -- the parent is assumed to live on
326
+ * the SAME host as the child (podspec's `links.parent` is a bare name,
327
+ * not a full ref; a cross-host parent needs an explicit `link()` call
328
+ * after the fact instead).
329
+ *
330
+ * @param {string} hostPodId - Target host, or `'auto'` to pick one via
331
+ * `choosePlacement()` the same way `MeshctlSpawnTool`/`meshctl spawn
332
+ * auto` do.
333
+ * @param {object} spec - A podspec (`validatePodSpec()`).
334
+ * @returns {Promise<{ref: {host: string, name: string}, spec: object, host: string, status: object}>}
335
+ */
336
+ async function supervise(hostPodId, spec) {
337
+ if (stopped) throw new Error('supervisor is stopped')
338
+ const validated = validatePodSpec(spec)
339
+ if (!validated.ok) {
340
+ throw new PodHostDriverError('EINVAL', validated.errors.join('; '), { errors: validated.errors })
341
+ }
342
+ const normalized = validated.value
343
+
344
+ let host = hostPodId
345
+ if (!host || host === 'auto') {
346
+ host = await choosePlacement(normalized)
347
+ if (!host) throw new Error(`supervise: no host available for lane '${normalized.lane}'`)
348
+ }
349
+
350
+ const status = await doSpawn(host, normalized)
351
+
352
+ /** @type {{host: string, name: string}} */
353
+ const ref = { host, name: normalized.name }
354
+ const entry = {
355
+ ref,
356
+ spec: normalized,
357
+ host,
358
+ restarts: 0,
359
+ state: 'running',
360
+ backoffTimer: null,
361
+ createdAt: now(),
362
+ }
363
+ pods.set(refKey(ref), entry)
364
+
365
+ if (normalized.links?.parent) {
366
+ link({ host, name: normalized.links.parent }, ref)
367
+ }
368
+
369
+ return { ref, spec: normalized, host, status }
370
+ }
371
+
372
+ /**
373
+ * Register `childRef` as a child of `parentRef`: when the parent drains
374
+ * (`drain()`) or unexpectedly exits, the child is cascade-drained too
375
+ * (unless `childRef`'s own podspec set `links.detachOnParentExit: true`
376
+ * together with `restart.policy: 'always'`).
377
+ * @param {{host: string, name: string}} parentRef
378
+ * @param {{host: string, name: string}} childRef
379
+ */
380
+ function link(parentRef, childRef) {
381
+ const parentKey = refKey(parentRef)
382
+ const childKey = refKey(childRef)
383
+ let set = childrenOf.get(parentKey)
384
+ if (!set) { set = new Set(); childrenOf.set(parentKey, set) }
385
+ set.add(childKey)
386
+ parentOf.set(childKey, parentKey)
387
+ }
388
+
389
+ /**
390
+ * @param {{host: string, name: string}} parentRef
391
+ * @param {{host: string, name: string}} childRef
392
+ */
393
+ function unlink(parentRef, childRef) {
394
+ const parentKey = refKey(parentRef)
395
+ const childKey = refKey(childRef)
396
+ childrenOf.get(parentKey)?.delete(childKey)
397
+ if (parentOf.get(childKey) === parentKey) parentOf.delete(childKey)
398
+ }
399
+
400
+ /**
401
+ * Fire `fn({ref, event})` for every lifecycle/exit event of the pod named
402
+ * by `ref`, including a synthesized `{kind: 'exit', data: {reason:
403
+ * 'host-lost', restartable: true, ...}}` when its host disconnects.
404
+ * @param {{host: string, name: string}} ref
405
+ * @param {(payload: {ref: object, event: object}) => void} fn
406
+ * @returns {() => void} Unsubscribe.
407
+ */
408
+ function monitor(ref, fn) {
409
+ const key = refKey(ref)
410
+ let set = monitors.get(key)
411
+ if (!set) { set = new Set(); monitors.set(key, set) }
412
+ set.add(fn)
413
+ return () => { monitors.get(key)?.delete(fn) }
414
+ }
415
+
416
+ /**
417
+ * Stop supervising `ref` -- clears any pending restart timer and forgets
418
+ * it. Does NOT drain the pod; use `drain()` for that.
419
+ * @param {{host: string, name: string}} ref
420
+ */
421
+ function unsupervise(ref) {
422
+ const key = refKey(ref)
423
+ const entry = pods.get(key)
424
+ if (entry?.backoffTimer) doClearTimeout(entry.backoffTimer)
425
+ pods.delete(key)
426
+ }
427
+
428
+ /** @returns {object[]} Every supervised pod this instance is tracking. */
429
+ function list() {
430
+ return [...pods.values()].map((entry) => ({
431
+ ref: entry.ref, spec: entry.spec, host: entry.host, restarts: entry.restarts, state: entry.state,
432
+ }))
433
+ }
434
+
435
+ // -- cascade ----------------------------------------------------------
436
+
437
+ /**
438
+ * Depth-first drain of every child of `parentRef` (grandchildren before
439
+ * children), skipping a child that opted out via `links.detachOnParentExit
440
+ * && restart.policy === 'always'`. Returns the flat drain order
441
+ * (deepest descendants first), NOT including `parentRef` itself.
442
+ * @param {{host: string, name: string}} parentRef
443
+ * @returns {Promise<object[]>}
444
+ */
445
+ async function drainChildren(parentRef) {
446
+ const parentKey = refKey(parentRef)
447
+ const childKeys = childrenOf.get(parentKey)
448
+ if (!childKeys || childKeys.size === 0) return []
449
+
450
+ /** @type {object[]} */
451
+ const order = []
452
+ for (const childKey of [...childKeys]) {
453
+ const childEntry = pods.get(childKey)
454
+ const childRef = childEntry ? childEntry.ref : parseKey(childKey)
455
+
456
+ if (childEntry?.spec?.links?.detachOnParentExit && childEntry?.spec?.restart?.policy === 'always') {
457
+ // Detached: left running (and left supervised -- it restarts on its
458
+ // own per its own policy if it independently fails later).
459
+ continue
460
+ }
461
+
462
+ // Grandchildren before children (depth-first).
463
+ order.push(...await drainChildren(childRef))
464
+
465
+ if (childEntry?.backoffTimer) {
466
+ doClearTimeout(childEntry.backoffTimer)
467
+ childEntry.backoffTimer = null
468
+ }
469
+ try {
470
+ await getHostClient().drain(childRef.host, childRef.name, { cascade: false })
471
+ } catch (err) {
472
+ log('supervisor:cascade-drain-failed', { ref: childRef, error: err?.message || String(err) })
473
+ }
474
+ if (childEntry) childEntry.state = 'dead'
475
+ order.push(childRef)
476
+
477
+ // Sever the relationship now that it has been handled: the
478
+ // driver-level `drain()` just issued above will, asynchronously,
479
+ // deliver its OWN 'drained' exit event back to this supervisor
480
+ // (`onExit()`), which would otherwise re-discover this same
481
+ // parent/child edge and cascade-drain an already-drained subtree a
482
+ // second time.
483
+ childrenOf.delete(childKey)
484
+ parentOf.delete(childKey)
485
+ childKeys.delete(childKey)
486
+ }
487
+ return order
488
+ }
489
+
490
+ /** @param {string} key @returns {{host: string, name: string}} */
491
+ function parseKey(key) {
492
+ const idx = key.indexOf('::')
493
+ return { host: key.slice(0, idx), name: key.slice(idx + 2) }
494
+ }
495
+
496
+ /**
497
+ * Drain `ref`: cascade-drain its children first (depth-first), then
498
+ * drain `ref` itself, emitting `supervisor:cascade` with the full order
499
+ * (children, then `ref` last).
500
+ * @param {{host: string, name: string}} ref
501
+ * @param {{cascade?: boolean}} [opts]
502
+ * @returns {Promise<{ref: object, order: object[]}>}
503
+ */
504
+ async function drain(ref, { cascade = true } = {}) {
505
+ const order = cascade ? await drainChildren(ref) : []
506
+
507
+ const key = refKey(ref)
508
+ const entry = pods.get(key)
509
+ if (entry?.backoffTimer) {
510
+ doClearTimeout(entry.backoffTimer)
511
+ entry.backoffTimer = null
512
+ }
513
+ try {
514
+ await getHostClient().drain(ref.host, ref.name, { cascade: false })
515
+ } catch (err) {
516
+ log('supervisor:drain-failed', { ref, error: err?.message || String(err) })
517
+ }
518
+ if (entry) entry.state = 'dead'
519
+ order.push(ref)
520
+
521
+ // Same reasoning as `drainChildren()`'s own cleanup: sever `ref`'s
522
+ // relationship to ITS parent (if linked) now, before the driver's own
523
+ // asynchronous 'drained' echo for `ref` can re-discover it.
524
+ childrenOf.delete(key)
525
+ const parentKey = parentOf.get(key)
526
+ if (parentKey) { childrenOf.get(parentKey)?.delete(key); parentOf.delete(key) }
527
+
528
+ emit('supervisor:cascade', { parent: ref, order })
529
+ await audit(SUPERVISOR_AUDIT.CASCADE, { parent: ref, order })
530
+ return { ref, order }
531
+ }
532
+
533
+ // -- restart scheduling -------------------------------------------------
534
+
535
+ /**
536
+ * @param {object} entry
537
+ * @param {string} [reason]
538
+ */
539
+ async function scheduleRestart(entry, reason) {
540
+ const maxRestarts = entry.spec.restart?.maxRestarts ?? DEFAULT_MAX_RESTARTS
541
+ if (entry.restarts >= maxRestarts) {
542
+ entry.state = 'dead'
543
+ emit('supervisor:gave-up', { ref: entry.ref, restarts: entry.restarts, reason })
544
+ await audit(SUPERVISOR_AUDIT.GAVE_UP, { ref: entry.ref, restarts: entry.restarts, reason })
545
+ return
546
+ }
547
+
548
+ const base = entry.spec.restart?.backoffMs ?? DEFAULT_BACKOFF_MS
549
+ const delayMs = Math.min(base * (2 ** entry.restarts), MAX_BACKOFF_MS)
550
+ entry.restarts += 1
551
+ const attempt = entry.restarts
552
+
553
+ emit('supervisor:restart-scheduled', { ref: entry.ref, attempt, delayMs, reason })
554
+ await audit(SUPERVISOR_AUDIT.RESTART_SCHEDULED, { ref: entry.ref, attempt, delayMs, reason })
555
+
556
+ entry.backoffTimer = doSetTimeout(() => {
557
+ entry.backoffTimer = null
558
+ runRestart(entry, reason).catch((err) => {
559
+ log('supervisor:restart-failed', { ref: entry.ref, error: err?.message || String(err) })
560
+ })
561
+ }, delayMs)
562
+ if (typeof entry.backoffTimer === 'object' && typeof entry.backoffTimer.unref === 'function') {
563
+ entry.backoffTimer.unref()
564
+ }
565
+ }
566
+
567
+ /**
568
+ * @param {object} entry
569
+ * @param {string} [reason]
570
+ */
571
+ async function runRestart(entry, reason) {
572
+ if (activeRestarts >= maxConcurrent) {
573
+ await new Promise((resolve) => { restartQueue.push(resolve) })
574
+ }
575
+ activeRestarts += 1
576
+ try {
577
+ let targetHost = entry.host
578
+ let placed = false
579
+
580
+ if (reason !== 'host-lost') {
581
+ try {
582
+ const status = await doSpawn(targetHost, entry.spec)
583
+ entry.state = 'running'
584
+ placed = true
585
+ emit('supervisor:restarted', { ref: entry.ref, attempt: entry.restarts, host: targetHost, status })
586
+ await audit(SUPERVISOR_AUDIT.RESTARTED, { ref: entry.ref, attempt: entry.restarts, host: targetHost })
587
+ } catch (err) {
588
+ const code = err?.code
589
+ if (code !== 'EACCES' && code !== 'EBUSY') throw err
590
+ log('supervisor:restart-refused', { ref: entry.ref, host: targetHost, code })
591
+ }
592
+ }
593
+
594
+ if (!placed) {
595
+ const newHost = await choosePlacement(entry.spec, { excludeHost: targetHost })
596
+ if (!newHost) throw new Error(`no host available to re-place '${entry.ref.name}'`)
597
+ const status = await doSpawn(newHost, entry.spec)
598
+ rekey(entry, newHost)
599
+ entry.state = 'running'
600
+ emit('supervisor:restarted', { ref: entry.ref, attempt: entry.restarts, host: newHost, status })
601
+ await audit(SUPERVISOR_AUDIT.RESTARTED, { ref: entry.ref, attempt: entry.restarts, host: newHost })
602
+ }
603
+ } catch (err) {
604
+ // This restart ATTEMPT failed (no host would take it, or spawn threw
605
+ // something other than a refusal). Schedule another attempt -- still
606
+ // bounded by `maxRestarts`, which `scheduleRestart()` enforces.
607
+ await scheduleRestart(entry, 'restart-failed')
608
+ } finally {
609
+ activeRestarts -= 1
610
+ const next = restartQueue.shift()
611
+ if (next) next()
612
+ }
613
+ }
614
+
615
+ // -- exit handling --------------------------------------------------------
616
+
617
+ /**
618
+ * @param {string} host - The host pubKey the event came from.
619
+ * @param {object} data - A `PodHostExitEventData` shape.
620
+ */
621
+ async function onExit(host, data) {
622
+ const ref = { host, name: data.name }
623
+ const key = refKey(ref)
624
+
625
+ fireMonitors(key, { ref, event: { kind: 'exit', data } })
626
+
627
+ // Cascade to children regardless of whether `ref` itself is supervised
628
+ // -- a parent that is merely LINKED (not itself under this supervisor's
629
+ // restart policy) still cascades.
630
+ const cascaded = await drainChildren(ref)
631
+ if (cascaded.length > 0) {
632
+ emit('supervisor:cascade', { parent: ref, order: cascaded })
633
+ await audit(SUPERVISOR_AUDIT.CASCADE, { parent: ref, order: cascaded })
634
+ }
635
+
636
+ const entry = pods.get(key)
637
+ if (!entry || entry.state === 'dead') return
638
+
639
+ if (data.reason === 'drained') {
640
+ entry.state = 'dead'
641
+ return
642
+ }
643
+
644
+ const policy = entry.spec.restart?.policy || 'never'
645
+ if (!policyWantsRestart(policy, data)) {
646
+ entry.state = 'dead'
647
+ return
648
+ }
649
+
650
+ entry.state = 'restarting'
651
+ await scheduleRestart(entry, data.reason)
652
+ }
653
+
654
+ // -- host loss --------------------------------------------------------
655
+
656
+ /** @param {string} hostPubKey */
657
+ async function onHostLost(hostPubKey) {
658
+ const affected = [...pods.values()]
659
+ .filter((entry) => entry.host === hostPubKey && entry.state === 'running')
660
+ .map((entry) => entry.ref)
661
+ if (affected.length === 0) return
662
+
663
+ emit('supervisor:host-lost', { host: hostPubKey, affected })
664
+ await audit(SUPERVISOR_AUDIT.HOST_LOST, { host: hostPubKey, affected })
665
+
666
+ for (const ref of affected) {
667
+ await onExit(hostPubKey, { name: ref.name, reason: 'host-lost', restartable: true })
668
+ }
669
+ }
670
+
671
+ // -- wiring -------------------------------------------------------------
672
+
673
+ function wireHostEvents() {
674
+ if (!hostClient && !effectivePeerNode) return // no client to build one from; onExit only reachable via reconcile/manual crash
675
+ const c = getHostClient()
676
+ unsubscribeHostEvents = c.onEvent((hostPubKey, event) => {
677
+ if (event.kind !== 'exit') return
678
+ onExit(hostPubKey, event.data).catch((err) => {
679
+ log('supervisor:on-exit-failed', { error: err?.message || String(err) })
680
+ })
681
+ })
682
+ }
683
+
684
+ function wirePeerDisconnect() {
685
+ const node = effectivePeerNode
686
+ if (!node || typeof node.on !== 'function') return
687
+ const handler = (peer) => {
688
+ const hostPubKey = typeof peer === 'string'
689
+ ? peer
690
+ : (peer?.fingerprint || peer?.pubKey || peer?.podId || null)
691
+ if (!hostPubKey) return
692
+ onHostLost(hostPubKey).catch((err) => {
693
+ log('supervisor:on-host-lost-failed', { error: err?.message || String(err) })
694
+ })
695
+ }
696
+ node.on('peer:disconnect', handler)
697
+ unsubscribePeerDisconnect = () => { if (typeof node.off === 'function') node.off('peer:disconnect', handler) }
698
+ }
699
+
700
+ wireHostEvents()
701
+ wirePeerDisconnect()
702
+
703
+ if (reconcileIntervalMs > 0) {
704
+ reconcileTimer = doSetTimeout(function tick() {
705
+ reconcile().catch((err) => log('supervisor:reconcile-failed', { error: err?.message || String(err) }))
706
+ if (!stopped) {
707
+ reconcileTimer = doSetTimeout(tick, reconcileIntervalMs)
708
+ if (typeof reconcileTimer === 'object' && typeof reconcileTimer.unref === 'function') reconcileTimer.unref()
709
+ }
710
+ }, reconcileIntervalMs)
711
+ if (typeof reconcileTimer === 'object' && typeof reconcileTimer.unref === 'function') reconcileTimer.unref()
712
+ }
713
+
714
+ /**
715
+ * Slow safety-net sweep (opt-in via `reconcileIntervalMs`): for every
716
+ * distinct host with a `state: 'running'` supervised pod, `list()` that
717
+ * host and treat any pod this supervisor still thinks is `running` but
718
+ * the host reports `gone` as a MISSED exit event -- synthesizing one with
719
+ * `reason: 'crashed'` (the conservative assumption; an intentional drain
720
+ * that genuinely got lost in transit is rare enough that over-restarting
721
+ * it is the safer failure mode than under-restarting a real crash).
722
+ * @returns {Promise<void>}
723
+ */
724
+ async function reconcile() {
725
+ const byHost = new Map()
726
+ for (const entry of pods.values()) {
727
+ if (entry.state !== 'running') continue
728
+ if (!byHost.has(entry.host)) byHost.set(entry.host, [])
729
+ byHost.get(entry.host).push(entry)
730
+ }
731
+ for (const [host, entries] of byHost) {
732
+ let statuses
733
+ try {
734
+ statuses = await getHostClient().list(host)
735
+ } catch (err) {
736
+ log('supervisor:reconcile-list-failed', { host, error: err?.message || String(err) })
737
+ continue
738
+ }
739
+ const stateByName = new Map(statuses.map((s) => [s.name, s.state]))
740
+ for (const entry of entries) {
741
+ if (stateByName.get(entry.ref.name) === 'gone') {
742
+ await onExit(host, { name: entry.ref.name, reason: 'crashed', restartable: true })
743
+ }
744
+ }
745
+ }
746
+ }
747
+
748
+ // -- bus / lifecycle ------------------------------------------------------
749
+
750
+ /** @param {string} event @param {Function} fn */
751
+ function on(event, fn) {
752
+ let set = listeners.get(event)
753
+ if (!set) { set = new Set(); listeners.set(event, set) }
754
+ set.add(fn)
755
+ return () => { listeners.get(event)?.delete(fn) }
756
+ }
757
+
758
+ function stop() {
759
+ if (stopped) return
760
+ stopped = true
761
+ for (const entry of pods.values()) {
762
+ if (entry.backoffTimer) doClearTimeout(entry.backoffTimer)
763
+ entry.backoffTimer = null
764
+ }
765
+ if (reconcileTimer) doClearTimeout(reconcileTimer)
766
+ reconcileTimer = null
767
+ if (unsubscribeHostEvents) unsubscribeHostEvents()
768
+ if (unsubscribePeerDisconnect) unsubscribePeerDisconnect()
769
+ listeners.clear()
770
+ monitors.clear()
771
+ }
772
+
773
+ return {
774
+ supervise,
775
+ link,
776
+ unlink,
777
+ monitor,
778
+ unsupervise,
779
+ drain,
780
+ list,
781
+ stop,
782
+ on,
783
+ }
784
+ }