@johnhenry/browsermesh-pod 0.0.3 → 0.1.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,1221 @@
1
+ /**
2
+ * host-protocol.mjs — the lane-agnostic pod-host control surface (issue
3
+ * #185, the "hosted pods control surface" follow-up to WP1–WP5).
4
+ *
5
+ * This file is **plain data plus one reference driver**. It deliberately
6
+ * lives in `@johnhenry/browsermesh-pod`, not in
7
+ * `@johnhenry/browsermesh-apps`, so that the two places a hosted pod
8
+ * actually runs — a V8 isolate (a Worker / Durable Object) and a microVM
9
+ * host agent — can `import` the verb set, the podspec validator and the
10
+ * wire shapes without pulling in the whole app/agent runtime (marketplace,
11
+ * payments, quotas, GPU...). The gated, audited *service* that speaks this
12
+ * protocol over the mesh is `createPodHostService()` in
13
+ * `browsermesh-apps/src/pod-host-service.mjs`; everything later (mesh://
14
+ * routes, meshctl tools, an external CLI, a supervisor) is a projection of
15
+ * the same eight verbs defined here.
16
+ *
17
+ * The eight verbs (`POD_HOST_VERB`) are the whole control surface:
18
+ *
19
+ * spawn create a pod from a podspec
20
+ * status one pod's lifecycle state
21
+ * send deliver a message to a pod
22
+ * exec run argv inside a pod (lane-dependent — see POD_LANE_VERBS)
23
+ * snapshot freeze a pod to durable storage (lane-dependent)
24
+ * restore thaw a snapshotted pod (lane-dependent)
25
+ * drain stop a pod, notifying peers
26
+ * list every pod this host tracks
27
+ *
28
+ * Not every lane can honour every verb, and that is a first-class part of
29
+ * the contract rather than a runtime surprise: `POD_LANE_VERBS` /
30
+ * `laneSupports()` describe it statically, and a driver refusing a verb its
31
+ * lane structurally cannot do throws `POD_HOST_ERROR.ELANE` (as opposed to
32
+ * `ENOTSUP`, which means "this particular driver did not implement an
33
+ * otherwise lane-compatible verb").
34
+ *
35
+ * Zero dependencies, no browser-only globals, no `node:` imports — this
36
+ * module must load unchanged in Node, a browser, `workerd` and a microVM
37
+ * guest.
38
+ */
39
+
40
+ // ---------------------------------------------------------------------------
41
+ // Verbs, lanes, lifecycle
42
+ // ---------------------------------------------------------------------------
43
+
44
+ /** The complete pod-host verb set. Every later surface projects these eight. */
45
+ export const POD_HOST_VERB = Object.freeze({
46
+ SPAWN: 'spawn',
47
+ STATUS: 'status',
48
+ SEND: 'send',
49
+ EXEC: 'exec',
50
+ SNAPSHOT: 'snapshot',
51
+ RESTORE: 'restore',
52
+ DRAIN: 'drain',
53
+ LIST: 'list',
54
+ })
55
+
56
+ /** Every verb string, in declaration order. @type {readonly string[]} */
57
+ export const POD_HOST_VERBS = Object.freeze(Object.values(POD_HOST_VERB))
58
+
59
+ /**
60
+ * Isolation lanes a pod host can offer.
61
+ *
62
+ * These strings are intentionally IDENTICAL to `RUNTIME_CLASS` in
63
+ * `packages/browsermesh-apps/src/resources.mjs` (issue #185 WP4), which is
64
+ * what `ResourceScorer` matches on as `runtime:<class>` capabilities. They
65
+ * are duplicated rather than imported ON PURPOSE: `browsermesh-pod` must
66
+ * stay importable from a Worker or a microVM guest without dragging in
67
+ * `browsermesh-apps`. If one side ever gains a lane, add it to both.
68
+ */
69
+ export const POD_LANE = Object.freeze({
70
+ ISOLATE: 'isolate',
71
+ MICROVM: 'microvm',
72
+ NODE: 'node',
73
+ BROWSER: 'browser',
74
+ })
75
+
76
+ /** Every lane string. @type {readonly string[]} */
77
+ export const POD_LANES = Object.freeze(Object.values(POD_LANE))
78
+
79
+ /**
80
+ * Hosted-pod lifecycle states, matching `docs/hosted-pods.md` §5.3's state
81
+ * diagram, plus a terminal `gone`.
82
+ *
83
+ * The diagram's `Draining --> Cold` + `Cold --> [*]: destroy` pair is
84
+ * represented here as two allowed edges out of `draining`: back to `cold`
85
+ * (the rootfs/DO survives and the pod can boot again — what
86
+ * `spikes/vm-pod-host`'s `VmPod` actually does) and straight to `gone` (the
87
+ * pod is forgotten). `gone` is terminal and is what a drained pod reports
88
+ * from `status` when the host keeps a tombstone.
89
+ */
90
+ export const POD_LIFECYCLE = Object.freeze({
91
+ COLD: 'cold',
92
+ BOOTING: 'booting',
93
+ REGISTERED: 'registered',
94
+ SERVING: 'serving',
95
+ PAUSED: 'paused',
96
+ SNAPSHOTTED: 'snapshotted',
97
+ RESTORING: 'restoring',
98
+ DRAINING: 'draining',
99
+ GONE: 'gone',
100
+ })
101
+
102
+ /** Every lifecycle state string. @type {readonly string[]} */
103
+ export const POD_LIFECYCLE_STATES = Object.freeze(Object.values(POD_LIFECYCLE))
104
+
105
+ /**
106
+ * Allowed lifecycle transitions, `from -> readonly to[]`. A state missing
107
+ * from this map, or a `to` missing from its array, is not a legal
108
+ * transition — see `canTransition()`.
109
+ *
110
+ * `gone` is terminal (empty array). Every non-terminal state may jump
111
+ * straight to `gone`, because a host losing its VMM/isolate is not a
112
+ * graceful drain and still has to be reportable.
113
+ */
114
+ export const POD_LIFECYCLE_TRANSITIONS = Object.freeze({
115
+ [POD_LIFECYCLE.COLD]: Object.freeze([POD_LIFECYCLE.BOOTING, POD_LIFECYCLE.GONE]),
116
+ [POD_LIFECYCLE.BOOTING]: Object.freeze([POD_LIFECYCLE.REGISTERED, POD_LIFECYCLE.GONE]),
117
+ [POD_LIFECYCLE.REGISTERED]: Object.freeze([
118
+ POD_LIFECYCLE.SERVING, POD_LIFECYCLE.PAUSED, POD_LIFECYCLE.DRAINING, POD_LIFECYCLE.GONE,
119
+ ]),
120
+ [POD_LIFECYCLE.SERVING]: Object.freeze([
121
+ POD_LIFECYCLE.REGISTERED, POD_LIFECYCLE.DRAINING, POD_LIFECYCLE.GONE,
122
+ ]),
123
+ [POD_LIFECYCLE.PAUSED]: Object.freeze([
124
+ POD_LIFECYCLE.SNAPSHOTTED, POD_LIFECYCLE.REGISTERED, POD_LIFECYCLE.DRAINING, POD_LIFECYCLE.GONE,
125
+ ]),
126
+ [POD_LIFECYCLE.SNAPSHOTTED]: Object.freeze([POD_LIFECYCLE.RESTORING, POD_LIFECYCLE.GONE]),
127
+ [POD_LIFECYCLE.RESTORING]: Object.freeze([POD_LIFECYCLE.REGISTERED, POD_LIFECYCLE.GONE]),
128
+ [POD_LIFECYCLE.DRAINING]: Object.freeze([POD_LIFECYCLE.COLD, POD_LIFECYCLE.GONE]),
129
+ [POD_LIFECYCLE.GONE]: Object.freeze([]),
130
+ })
131
+
132
+ /**
133
+ * Is `from -> to` a legal lifecycle transition?
134
+ *
135
+ * @param {string} from - A `POD_LIFECYCLE` value.
136
+ * @param {string} to - A `POD_LIFECYCLE` value.
137
+ * @returns {boolean} `false` for any unknown state on either side.
138
+ */
139
+ export function canTransition(from, to) {
140
+ const allowed = POD_LIFECYCLE_TRANSITIONS[from]
141
+ if (!allowed) return false
142
+ return allowed.includes(to)
143
+ }
144
+
145
+ /**
146
+ * Which verbs each lane can structurally honour (issue #185 §2's two-lane
147
+ * comparison table, reduced to the control surface).
148
+ *
149
+ * - An **isolate** has no shell and no process to freeze to disk, so
150
+ * `exec`, `snapshot` and `restore` are `ELANE` there *today* — Durable
151
+ * Object hibernation is automatic, not a verb a caller drives.
152
+ * - A **browser** pod host is a tab, not a shell — but unlike an isolate it
153
+ * DOES have a JS realm a sufficiently privileged driver can evaluate code
154
+ * in (`Runtime.evaluate` over CDP; `chrome.scripting.executeScript` from
155
+ * an extension's isolated world). Issue #185 item 7 (the browser lane)
156
+ * settled this explicitly: `exec` on the browser lane means **"evaluate
157
+ * an expression in the page's JS context," not a shell command** — the
158
+ * `command` argv's first element is treated as a JS expression string by
159
+ * a driver that implements it. That is a real, structurally possible
160
+ * capability of the lane, so it is `true` here, NOT `ELANE`. Whether a
161
+ * *particular* driver actually does it is a separate, per-driver
162
+ * question: the in-page driver (`browser-host-driver.mjs`) answers
163
+ * `ENOTSUP` for it on purpose — a parent tab evaluating code in a
164
+ * cross-origin child has no trust boundary to speak of, so that driver
165
+ * never implements it, while the CDP and extension drivers
166
+ * (`spikes/browser-pod-host`, `spikes/browser-extension-host`) do, because
167
+ * their drivers run with an external operator's full control over the
168
+ * browser (remote debugging port / extension privileges) rather than
169
+ * borrowing the hosted page's own non-boundary. `ENOTSUP` is the correct
170
+ * code for that gap (a driver choice, not a lane law) — see
171
+ * `POD_HOST_ERROR`'s doc comment for the `ELANE`/`ENOTSUP` distinction.
172
+ * - `snapshot`/`restore` stay `ELANE` on the browser lane: no driver in
173
+ * this wave durably freezes a page's JS heap to storage and thaws it
174
+ * byte-for-byte the way a microVM snapshot does. (The extension driver's
175
+ * `chrome.tabs.discard`/reload pair is a real, useful pause/resume
176
+ * primitive, but it is a *different, weaker* promise — see that spike's
177
+ * README — so it is kept out of the standard gated verb set rather than
178
+ * stretching `snapshot` to mean two different things across drivers.)
179
+ * - **microvm** and **node** hosts can do all eight.
180
+ */
181
+ export const POD_LANE_VERBS = Object.freeze({
182
+ [POD_LANE.ISOLATE]: Object.freeze([
183
+ POD_HOST_VERB.SPAWN, POD_HOST_VERB.STATUS, POD_HOST_VERB.SEND,
184
+ POD_HOST_VERB.DRAIN, POD_HOST_VERB.LIST,
185
+ ]),
186
+ [POD_LANE.MICROVM]: Object.freeze([...POD_HOST_VERBS]),
187
+ [POD_LANE.NODE]: Object.freeze([...POD_HOST_VERBS]),
188
+ [POD_LANE.BROWSER]: Object.freeze([
189
+ POD_HOST_VERB.SPAWN, POD_HOST_VERB.STATUS, POD_HOST_VERB.SEND, POD_HOST_VERB.EXEC,
190
+ POD_HOST_VERB.DRAIN, POD_HOST_VERB.LIST,
191
+ ]),
192
+ })
193
+
194
+ /**
195
+ * Can `lane` honour `verb` at all? An unknown lane is treated as capable of
196
+ * nothing (`false`), so a typo'd lane fails loudly rather than silently
197
+ * advertising the full verb set.
198
+ *
199
+ * @param {string} lane - A `POD_LANE` value.
200
+ * @param {string} verb - A `POD_HOST_VERB` value.
201
+ * @returns {boolean}
202
+ */
203
+ export function laneSupports(lane, verb) {
204
+ const verbs = POD_LANE_VERBS[lane]
205
+ if (!verbs) return false
206
+ return verbs.includes(verb)
207
+ }
208
+
209
+ // ---------------------------------------------------------------------------
210
+ // Errors
211
+ // ---------------------------------------------------------------------------
212
+
213
+ /**
214
+ * Machine-readable pod-host error codes. Deliberately errno-shaped, like
215
+ * `browsermesh-kernel`'s own `KERNEL_ERROR`.
216
+ *
217
+ * `ELANE` is the one code with no errno ancestor: it means "this lane
218
+ * structurally cannot do this verb" (exec on an isolate; snapshot/restore
219
+ * on an isolate today). `ENOTSUP` means "this particular driver does not
220
+ * implement an otherwise lane-compatible verb" — a gap, not a law.
221
+ */
222
+ export const POD_HOST_ERROR = Object.freeze({
223
+ EACCES: 'EACCES',
224
+ ENOENT: 'ENOENT',
225
+ EEXIST: 'EEXIST',
226
+ EINVAL: 'EINVAL',
227
+ ENOTSUP: 'ENOTSUP',
228
+ ELANE: 'ELANE',
229
+ ETIMEDOUT: 'ETIMEDOUT',
230
+ EBUSY: 'EBUSY',
231
+ })
232
+
233
+ /**
234
+ * The error every `PodHostDriver` method rejects with. Carries a
235
+ * `POD_HOST_ERROR` code so the wire layer can round-trip it as
236
+ * `{ code, message }` without losing the distinction between "denied",
237
+ * "no such pod" and "wrong lane".
238
+ */
239
+ export class PodHostDriverError extends Error {
240
+ /** @type {string} A `POD_HOST_ERROR` value. */
241
+ code
242
+
243
+ /** @type {object|null} Optional structured context (pod name, lane, ...). */
244
+ details
245
+
246
+ /**
247
+ * @param {string} code - A `POD_HOST_ERROR` value.
248
+ * @param {string} message
249
+ * @param {object} [details]
250
+ */
251
+ constructor(code, message, details = null) {
252
+ super(message)
253
+ this.name = 'PodHostDriverError'
254
+ this.code = code
255
+ this.details = details
256
+ }
257
+
258
+ /** @returns {{code: string, message: string}} The wire shape. */
259
+ toJSON() {
260
+ return { code: this.code, message: this.message }
261
+ }
262
+
263
+ /**
264
+ * Rebuild a `PodHostDriverError` from a wire `{ code, message }` (or from
265
+ * anything else, defaulting to `EINVAL`). Used by the client side of the
266
+ * mesh service to re-throw a remote failure locally.
267
+ *
268
+ * @param {*} err
269
+ * @returns {PodHostDriverError}
270
+ */
271
+ static from(err) {
272
+ if (err instanceof PodHostDriverError) return err
273
+ const code = (err && typeof err.code === 'string' && err.code) || POD_HOST_ERROR.EINVAL
274
+ const message = (err && typeof err.message === 'string' && err.message) || String(err)
275
+ return new PodHostDriverError(code, message, err && err.details ? err.details : null)
276
+ }
277
+ }
278
+
279
+ /**
280
+ * Build a `PodHostDriver` method that always refuses, for a verb a driver
281
+ * cannot serve. Use it to fill in the gaps of a partial driver so every
282
+ * driver still has all eight methods and callers never hit
283
+ * `driver.exec is not a function`.
284
+ *
285
+ * Defaults to `ELANE` when `lane` says the verb is structurally impossible
286
+ * there, and to `ENOTSUP` otherwise (a driver gap on a lane that could, in
287
+ * principle, do it).
288
+ *
289
+ * @param {string} verb - A `POD_HOST_VERB` value.
290
+ * @param {string} [lane] - A `POD_LANE` value.
291
+ * @param {object} [opts]
292
+ * @param {string} [opts.code] - Force a specific `POD_HOST_ERROR` code.
293
+ * @param {string} [opts.message] - Override the generated message.
294
+ * @returns {() => Promise<never>} An async function that always rejects.
295
+ */
296
+ export function createUnsupportedDriverMethod(verb, lane, opts = {}) {
297
+ const error = unsupportedVerbError(verb, lane, opts)
298
+ return async function unsupportedDriverMethod() {
299
+ throw error
300
+ }
301
+ }
302
+
303
+ /**
304
+ * The `ELANE`/`ENOTSUP` decision in one place, shared by
305
+ * `createUnsupportedDriverMethod()` and `InMemoryPodHostDriver`'s own
306
+ * per-call verb gate.
307
+ *
308
+ * @param {string} verb
309
+ * @param {string} [lane]
310
+ * @param {{code?: string, message?: string}} [opts]
311
+ * @returns {PodHostDriverError}
312
+ */
313
+ function unsupportedVerbError(verb, lane, opts = {}) {
314
+ const laneKnown = Boolean(POD_LANE_VERBS[lane])
315
+ const code = opts.code
316
+ || (laneKnown && !laneSupports(lane, verb) ? POD_HOST_ERROR.ELANE : POD_HOST_ERROR.ENOTSUP)
317
+ const message = opts.message || (code === POD_HOST_ERROR.ELANE
318
+ ? `lane '${lane}' cannot '${verb}'`
319
+ : `driver${lane ? ` (lane '${lane}')` : ''} does not implement '${verb}'`)
320
+ return new PodHostDriverError(code, message, { verb, lane: lane ?? null })
321
+ }
322
+
323
+ // ---------------------------------------------------------------------------
324
+ // Podspec validation
325
+ // ---------------------------------------------------------------------------
326
+
327
+ /** What a podspec's `run.kind` may be. */
328
+ const RUN_KINDS = Object.freeze(['skill', 'module', 'rootfs', 'command'])
329
+
330
+ /** `run.kind`s that default to the isolate lane; the rest default to microvm. */
331
+ const ISOLATE_RUN_KINDS = Object.freeze(['skill', 'module'])
332
+
333
+ /** Restart policies a podspec may ask for. */
334
+ const RESTART_POLICIES = Object.freeze(['never', 'on-failure', 'always'])
335
+
336
+ /** Pod names are path/URL/CLI-safe: this is the whole grammar. */
337
+ const NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/
338
+
339
+ const SPEC_KEYS = Object.freeze(['name', 'lane', 'run', 'limits', 'caps', 'env', 'budget', 'restart', 'labels', 'links'])
340
+ const RUN_KEYS = Object.freeze(['kind', 'ref', 'entry', 'input'])
341
+ const LIMIT_KEYS = Object.freeze(['vcpus', 'memMib', 'timeoutMs', 'netRateLimiter', 'blockRateLimiter'])
342
+ const BUDGET_KEYS = Object.freeze(['credits', 'currency'])
343
+ const RESTART_KEYS = Object.freeze(['policy', 'maxRestarts', 'backoffMs'])
344
+ const LINKS_KEYS = Object.freeze(['parent', 'hostedBy', 'detachOnParentExit'])
345
+
346
+ /** @param {*} value @returns {boolean} */
347
+ function isPlainObject(value) {
348
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
349
+ }
350
+
351
+ /**
352
+ * @param {object} obj
353
+ * @param {readonly string[]} allowed
354
+ * @param {string} where - Dotted path used in the error message.
355
+ * @param {string[]} errors - Accumulator, appended to in place.
356
+ */
357
+ function rejectUnknownKeys(obj, allowed, where, errors) {
358
+ for (const key of Object.keys(obj)) {
359
+ if (!allowed.includes(key)) errors.push(`${where}: unknown key '${key}'`)
360
+ }
361
+ }
362
+
363
+ /**
364
+ * @param {*} value
365
+ * @param {string} where
366
+ * @param {string[]} errors
367
+ * @returns {Record<string, string>|undefined}
368
+ */
369
+ function validateStringMap(value, where, errors) {
370
+ if (value === undefined) return undefined
371
+ if (!isPlainObject(value)) {
372
+ errors.push(`${where} must be an object`)
373
+ return undefined
374
+ }
375
+ /** @type {Record<string, string>} */
376
+ const out = {}
377
+ for (const [key, entry] of Object.entries(value)) {
378
+ if (typeof entry !== 'string') {
379
+ errors.push(`${where}.${key} must be a string`)
380
+ continue
381
+ }
382
+ out[key] = entry
383
+ }
384
+ return out
385
+ }
386
+
387
+ /**
388
+ * @param {*} value
389
+ * @param {string} where
390
+ * @param {string[]} errors
391
+ * @param {object} [opts]
392
+ * @param {boolean} [opts.integer=false]
393
+ * @returns {number|undefined}
394
+ */
395
+ function validatePositiveNumber(value, where, errors, { integer = false } = {}) {
396
+ if (value === undefined) return undefined
397
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
398
+ errors.push(`${where} must be a positive finite number`)
399
+ return undefined
400
+ }
401
+ if (integer && !Number.isInteger(value)) {
402
+ errors.push(`${where} must be an integer`)
403
+ return undefined
404
+ }
405
+ return value
406
+ }
407
+
408
+ /**
409
+ * Validate and normalize a **podspec** — the payload of the `spawn` verb.
410
+ *
411
+ * Normalization is deliberately minimal and total: the only defaults
412
+ * applied are `lane` (derived from `run.kind`: `isolate` for
413
+ * `skill`/`module`, `microvm` for `command`/`rootfs`) and
414
+ * `restart.policy` (`'never'`). Optional sections that were absent stay
415
+ * absent in the normalized value, so a driver can tell "no limits asked
416
+ * for" apart from "limits asked for, all defaults".
417
+ *
418
+ * Unknown keys are an error, not ignored: a mistyped `limits.memMB` that
419
+ * silently did nothing would be a quota bug nobody notices until the bill.
420
+ *
421
+ * @param {object} spec
422
+ * @returns {{ok: true, value: object}|{ok: false, errors: string[]}}
423
+ */
424
+ export function validatePodSpec(spec) {
425
+ /** @type {string[]} */
426
+ const errors = []
427
+
428
+ if (!isPlainObject(spec)) {
429
+ return { ok: false, errors: ['podspec must be an object'] }
430
+ }
431
+ rejectUnknownKeys(spec, SPEC_KEYS, 'podspec', errors)
432
+
433
+ // -- name ---------------------------------------------------------------
434
+ if (typeof spec.name !== 'string' || !spec.name) {
435
+ errors.push('name is required and must be a non-empty string')
436
+ } else if (!NAME_PATTERN.test(spec.name)) {
437
+ errors.push(`name '${spec.name}' must match ${NAME_PATTERN}`)
438
+ }
439
+
440
+ // -- run ----------------------------------------------------------------
441
+ /** @type {object|null} */
442
+ let run = null
443
+ if (!isPlainObject(spec.run)) {
444
+ errors.push('run is required and must be an object')
445
+ } else {
446
+ rejectUnknownKeys(spec.run, RUN_KEYS, 'run', errors)
447
+ if (!RUN_KINDS.includes(spec.run.kind)) {
448
+ errors.push(`run.kind must be one of ${RUN_KINDS.join('|')}`)
449
+ }
450
+ if (typeof spec.run.ref !== 'string' || !spec.run.ref) {
451
+ errors.push('run.ref is required and must be a non-empty string')
452
+ }
453
+ if (spec.run.entry !== undefined && typeof spec.run.entry !== 'string') {
454
+ errors.push('run.entry must be a string')
455
+ }
456
+ run = { kind: spec.run.kind, ref: spec.run.ref }
457
+ if (spec.run.entry !== undefined) run.entry = spec.run.entry
458
+ if (spec.run.input !== undefined) run.input = spec.run.input
459
+ }
460
+
461
+ // -- lane (defaulted from run.kind) --------------------------------------
462
+ let lane
463
+ if (spec.lane === undefined) {
464
+ lane = run && ISOLATE_RUN_KINDS.includes(run.kind) ? POD_LANE.ISOLATE : POD_LANE.MICROVM
465
+ } else if (!POD_LANES.includes(spec.lane)) {
466
+ errors.push(`lane must be one of ${POD_LANES.join('|')}`)
467
+ } else {
468
+ lane = spec.lane
469
+ }
470
+
471
+ // -- limits --------------------------------------------------------------
472
+ /** @type {object|undefined} */
473
+ let limits
474
+ if (spec.limits !== undefined) {
475
+ if (!isPlainObject(spec.limits)) {
476
+ errors.push('limits must be an object')
477
+ } else {
478
+ rejectUnknownKeys(spec.limits, LIMIT_KEYS, 'limits', errors)
479
+ limits = {}
480
+ const vcpus = validatePositiveNumber(spec.limits.vcpus, 'limits.vcpus', errors, { integer: true })
481
+ if (vcpus !== undefined) limits.vcpus = vcpus
482
+ const memMib = validatePositiveNumber(spec.limits.memMib, 'limits.memMib', errors, { integer: true })
483
+ if (memMib !== undefined) limits.memMib = memMib
484
+ const timeoutMs = validatePositiveNumber(spec.limits.timeoutMs, 'limits.timeoutMs', errors)
485
+ if (timeoutMs !== undefined) limits.timeoutMs = timeoutMs
486
+ for (const key of ['netRateLimiter', 'blockRateLimiter']) {
487
+ if (spec.limits[key] === undefined) continue
488
+ if (!isPlainObject(spec.limits[key])) {
489
+ errors.push(`limits.${key} must be an object`)
490
+ continue
491
+ }
492
+ // Passed through verbatim: the shape is Firecracker's own rate
493
+ // limiter document and only lane B knows how to read it.
494
+ limits[key] = { ...spec.limits[key] }
495
+ }
496
+ }
497
+ }
498
+
499
+ // -- caps ----------------------------------------------------------------
500
+ /** @type {string[]|undefined} */
501
+ let caps
502
+ if (spec.caps !== undefined) {
503
+ if (!Array.isArray(spec.caps)) {
504
+ errors.push('caps must be an array of strings')
505
+ } else {
506
+ // Validated as strings only, NOT against a copy of `KERNEL_CAP` —
507
+ // that enum lives in `@johnhenry/browsermesh-kernel` and this package
508
+ // must not depend on it (see the module doc comment). The host, which
509
+ // does know the kernel, is the enforcement point.
510
+ caps = []
511
+ for (const [i, cap] of spec.caps.entries()) {
512
+ if (typeof cap !== 'string' || !cap) {
513
+ errors.push(`caps[${i}] must be a non-empty string`)
514
+ continue
515
+ }
516
+ caps.push(cap)
517
+ }
518
+ }
519
+ }
520
+
521
+ // -- env / labels ---------------------------------------------------------
522
+ const env = validateStringMap(spec.env, 'env', errors)
523
+ const labels = validateStringMap(spec.labels, 'labels', errors)
524
+
525
+ // -- budget ---------------------------------------------------------------
526
+ /** @type {object|undefined} */
527
+ let budget
528
+ if (spec.budget !== undefined) {
529
+ if (!isPlainObject(spec.budget)) {
530
+ errors.push('budget must be an object')
531
+ } else {
532
+ rejectUnknownKeys(spec.budget, BUDGET_KEYS, 'budget', errors)
533
+ if (typeof spec.budget.credits !== 'number'
534
+ || !Number.isFinite(spec.budget.credits)
535
+ || spec.budget.credits < 0) {
536
+ errors.push('budget.credits is required and must be a non-negative finite number')
537
+ }
538
+ if (spec.budget.currency !== undefined && typeof spec.budget.currency !== 'string') {
539
+ errors.push('budget.currency must be a string')
540
+ }
541
+ budget = { credits: spec.budget.credits }
542
+ if (spec.budget.currency !== undefined) budget.currency = spec.budget.currency
543
+ }
544
+ }
545
+
546
+ // -- restart (policy defaulted to 'never') ---------------------------------
547
+ let restart = { policy: 'never' }
548
+ if (spec.restart !== undefined) {
549
+ if (!isPlainObject(spec.restart)) {
550
+ errors.push('restart must be an object')
551
+ } else {
552
+ rejectUnknownKeys(spec.restart, RESTART_KEYS, 'restart', errors)
553
+ const policy = spec.restart.policy === undefined ? 'never' : spec.restart.policy
554
+ if (!RESTART_POLICIES.includes(policy)) {
555
+ errors.push(`restart.policy must be one of ${RESTART_POLICIES.join('|')}`)
556
+ }
557
+ restart = { policy }
558
+ if (spec.restart.maxRestarts !== undefined) {
559
+ if (!Number.isInteger(spec.restart.maxRestarts) || spec.restart.maxRestarts < 0) {
560
+ errors.push('restart.maxRestarts must be a non-negative integer')
561
+ } else {
562
+ restart.maxRestarts = spec.restart.maxRestarts
563
+ }
564
+ }
565
+ if (spec.restart.backoffMs !== undefined) {
566
+ if (typeof spec.restart.backoffMs !== 'number'
567
+ || !Number.isFinite(spec.restart.backoffMs)
568
+ || spec.restart.backoffMs < 0) {
569
+ errors.push('restart.backoffMs must be a non-negative finite number')
570
+ } else {
571
+ restart.backoffMs = spec.restart.backoffMs
572
+ }
573
+ }
574
+ }
575
+ }
576
+
577
+ // -- links (issue #185 item 6: parent/supervision linkage) ----------------
578
+ /** @type {object|undefined} */
579
+ let links
580
+ if (spec.links !== undefined) {
581
+ if (!isPlainObject(spec.links)) {
582
+ errors.push('links must be an object')
583
+ } else {
584
+ rejectUnknownKeys(spec.links, LINKS_KEYS, 'links', errors)
585
+ links = {}
586
+ if (spec.links.parent !== undefined) {
587
+ if (typeof spec.links.parent !== 'string' || !spec.links.parent) {
588
+ errors.push('links.parent must be a non-empty string')
589
+ } else {
590
+ links.parent = spec.links.parent
591
+ }
592
+ }
593
+ if (spec.links.hostedBy !== undefined) {
594
+ if (typeof spec.links.hostedBy !== 'string' || !spec.links.hostedBy) {
595
+ errors.push('links.hostedBy must be a non-empty string')
596
+ } else {
597
+ links.hostedBy = spec.links.hostedBy
598
+ }
599
+ }
600
+ if (spec.links.detachOnParentExit !== undefined) {
601
+ if (typeof spec.links.detachOnParentExit !== 'boolean') {
602
+ errors.push('links.detachOnParentExit must be a boolean')
603
+ } else {
604
+ links.detachOnParentExit = spec.links.detachOnParentExit
605
+ }
606
+ }
607
+ }
608
+ }
609
+
610
+ if (errors.length > 0) return { ok: false, errors }
611
+
612
+ /** @type {Record<string, *>} */
613
+ const value = { name: spec.name, lane, run, restart }
614
+ if (limits !== undefined) value.limits = limits
615
+ if (caps !== undefined) value.caps = caps
616
+ if (env !== undefined) value.env = env
617
+ if (budget !== undefined) value.budget = budget
618
+ if (labels !== undefined) value.labels = labels
619
+ if (links !== undefined) value.links = links
620
+ return { ok: true, value }
621
+ }
622
+
623
+ // ---------------------------------------------------------------------------
624
+ // Verb-request validation
625
+ // ---------------------------------------------------------------------------
626
+
627
+ /**
628
+ * @param {object} payload
629
+ * @param {string[]} errors
630
+ * @returns {string|undefined}
631
+ */
632
+ function validateName(payload, errors) {
633
+ if (typeof payload.name !== 'string' || !payload.name) {
634
+ errors.push('name is required and must be a non-empty string')
635
+ return undefined
636
+ }
637
+ if (!NAME_PATTERN.test(payload.name)) {
638
+ errors.push(`name '${payload.name}' must match ${NAME_PATTERN}`)
639
+ return undefined
640
+ }
641
+ return payload.name
642
+ }
643
+
644
+ /**
645
+ * Validate and normalize the payload of ANY pod-host verb, `spawn`
646
+ * included (which delegates to `validatePodSpec()`).
647
+ *
648
+ * The normalized `value` is what a driver should be handed — notably,
649
+ * `exec`'s `command` is always a `string[]` on the way out, and `drain`'s
650
+ * `cascade` is always a boolean.
651
+ *
652
+ * @param {string} verb - A `POD_HOST_VERB` value.
653
+ * @param {object} [payload]
654
+ * @returns {{ok: true, value: object}|{ok: false, errors: string[]}}
655
+ */
656
+ export function validateVerbRequest(verb, payload = {}) {
657
+ if (!POD_HOST_VERBS.includes(verb)) {
658
+ return { ok: false, errors: [`unknown verb '${verb}'`] }
659
+ }
660
+ if (verb === POD_HOST_VERB.SPAWN) return validatePodSpec(payload)
661
+
662
+ if (!isPlainObject(payload)) {
663
+ return { ok: false, errors: [`${verb} payload must be an object`] }
664
+ }
665
+
666
+ /** @type {string[]} */
667
+ const errors = []
668
+
669
+ switch (verb) {
670
+ case POD_HOST_VERB.STATUS:
671
+ case POD_HOST_VERB.SNAPSHOT:
672
+ case POD_HOST_VERB.RESTORE: {
673
+ rejectUnknownKeys(payload, ['name'], verb, errors)
674
+ const name = validateName(payload, errors)
675
+ if (errors.length > 0) return { ok: false, errors }
676
+ return { ok: true, value: { name } }
677
+ }
678
+
679
+ case POD_HOST_VERB.SEND: {
680
+ rejectUnknownKeys(payload, ['name', 'to', 'payload'], verb, errors)
681
+ const name = validateName(payload, errors)
682
+ if (payload.to !== undefined && (typeof payload.to !== 'string' || !payload.to)) {
683
+ errors.push('to must be a non-empty string when present')
684
+ }
685
+ if (!('payload' in payload) || payload.payload === undefined) {
686
+ errors.push('payload is required')
687
+ }
688
+ if (errors.length > 0) return { ok: false, errors }
689
+ /** @type {Record<string, *>} */
690
+ const value = { name, payload: payload.payload }
691
+ if (payload.to !== undefined) value.to = payload.to
692
+ return { ok: true, value }
693
+ }
694
+
695
+ case POD_HOST_VERB.EXEC: {
696
+ rejectUnknownKeys(payload, ['name', 'command', 'timeoutMs'], verb, errors)
697
+ const name = validateName(payload, errors)
698
+ /** @type {string[]} */
699
+ let command = []
700
+ if (typeof payload.command === 'string') {
701
+ if (!payload.command) {
702
+ errors.push('command must be a non-empty string or a non-empty string[]')
703
+ }
704
+ // A string command becomes a SINGLE-ELEMENT argv. It is deliberately
705
+ // NOT shell-split: quoting rules differ per lane and guessing them
706
+ // is how injection bugs happen. Pass an explicit argv array, or
707
+ // `['sh', '-c', '<string>']` when a shell really is wanted.
708
+ command = [payload.command]
709
+ } else if (Array.isArray(payload.command)) {
710
+ if (payload.command.length === 0) {
711
+ errors.push('command must be a non-empty string or a non-empty string[]')
712
+ }
713
+ for (const [i, part] of payload.command.entries()) {
714
+ if (typeof part !== 'string' || !part) errors.push(`command[${i}] must be a non-empty string`)
715
+ }
716
+ command = [...payload.command]
717
+ } else {
718
+ errors.push('command is required and must be a string or string[]')
719
+ }
720
+ const timeoutMs = validatePositiveNumber(payload.timeoutMs, 'timeoutMs', errors)
721
+ if (errors.length > 0) return { ok: false, errors }
722
+ /** @type {Record<string, *>} */
723
+ const value = { name, command }
724
+ if (timeoutMs !== undefined) value.timeoutMs = timeoutMs
725
+ return { ok: true, value }
726
+ }
727
+
728
+ case POD_HOST_VERB.DRAIN: {
729
+ rejectUnknownKeys(payload, ['name', 'cascade'], verb, errors)
730
+ const name = validateName(payload, errors)
731
+ if (payload.cascade !== undefined && typeof payload.cascade !== 'boolean') {
732
+ errors.push('cascade must be a boolean')
733
+ }
734
+ if (errors.length > 0) return { ok: false, errors }
735
+ return { ok: true, value: { name, cascade: payload.cascade === true } }
736
+ }
737
+
738
+ case POD_HOST_VERB.LIST:
739
+ default: {
740
+ rejectUnknownKeys(payload, [], verb, errors)
741
+ if (errors.length > 0) return { ok: false, errors }
742
+ return { ok: true, value: {} }
743
+ }
744
+ }
745
+ }
746
+
747
+ // ---------------------------------------------------------------------------
748
+ // Wire messages
749
+ // ---------------------------------------------------------------------------
750
+
751
+ /** Envelope type of a verb request. */
752
+ export const POD_HOST_REQUEST = 'pod-host:request'
753
+ /** Envelope type of a verb response. */
754
+ export const POD_HOST_RESPONSE = 'pod-host:response'
755
+ /** Envelope type of an unsolicited host event. */
756
+ export const POD_HOST_EVENT = 'pod-host:event'
757
+
758
+ /** Kinds of `POD_HOST_EVENT` a host pushes to interested requesters. */
759
+ export const POD_HOST_EVENT_KIND = Object.freeze({
760
+ LIFECYCLE: 'lifecycle',
761
+ LOG: 'log',
762
+ EXIT: 'exit',
763
+ })
764
+
765
+ /**
766
+ * The `data` shape of an `EXIT` event (issue #185 item 6, the supervisor).
767
+ * Every driver that can tell a pod has left the host's live set -- drained,
768
+ * crashed, or lost along with its host -- emits one of these so a listener
769
+ * (a supervisor's `monitor()`, `pod-host-service.mjs`'s event forwarding)
770
+ * can decide, without guessing, whether a restart is worth attempting:
771
+ *
772
+ * ```js
773
+ * {
774
+ * name: string, // the pod's name
775
+ * code?: number, // exit code, when one exists (e.g. a crashed exec)
776
+ * reason?: 'drained' | 'crashed' | 'host-lost' | 'evicted',
777
+ * restartable: boolean, // false for an intentional drain; true otherwise
778
+ * }
779
+ * ```
780
+ *
781
+ * `reason` is intentionally optional on the TYPE (a driver that predates
782
+ * this field, or a lane with no finer-grained signal, may omit it), but
783
+ * `InMemoryPodHostDriver` always sets it: `'drained'` from `drain()`,
784
+ * `'crashed'` from the test-only `crash()`. `'host-lost'` is synthesized by
785
+ * a SUPERVISOR (`pod-supervisor.mjs`, `browsermesh-apps`), not by a driver
786
+ * -- no driver can know its own host died. `'evicted'` matches
787
+ * `PLACEMENT_AUDIT.EVICTED` (`orchestrator.mjs`) for a pod removed by
788
+ * something other than its own drain/crash (e.g. a snapshot). `restartable`
789
+ * is the one field every EXIT event should set: a drained pod intentionally
790
+ * left (`restartable: false`), anything else is a candidate for a
791
+ * supervisor's restart policy to evaluate (`restartable: true`).
792
+ *
793
+ * @typedef {object} PodHostExitEventData
794
+ * @property {string} name
795
+ * @property {number} [code]
796
+ * @property {'drained'|'crashed'|'host-lost'|'evicted'} [reason]
797
+ * @property {boolean} restartable
798
+ */
799
+
800
+ /** @type {number} Monotonic suffix making generated request ids unique within a process. */
801
+ let requestCounter = 0
802
+
803
+ /**
804
+ * A request id that is unique per process without needing `crypto`
805
+ * (`randomUUID` is used when available, which is everywhere this package
806
+ * targets, but the counter fallback keeps the module total).
807
+ *
808
+ * @returns {string}
809
+ */
810
+ function nextRequestId() {
811
+ requestCounter += 1
812
+ const rand = globalThis.crypto?.randomUUID?.()
813
+ if (rand) return rand
814
+ return `pod-host-${Date.now().toString(36)}-${requestCounter.toString(36)}`
815
+ }
816
+
817
+ /**
818
+ * Build a `pod-host:request` envelope.
819
+ *
820
+ * @param {string} verb - A `POD_HOST_VERB` value.
821
+ * @param {object} [payload]
822
+ * @param {object} [opts]
823
+ * @param {string} [opts.requestId] - Supply your own correlation id.
824
+ * @returns {{type: string, requestId: string, verb: string, payload: object, ts: number}}
825
+ */
826
+ export function createHostRequest(verb, payload = {}, { requestId } = {}) {
827
+ return {
828
+ type: POD_HOST_REQUEST,
829
+ requestId: requestId || nextRequestId(),
830
+ verb,
831
+ payload,
832
+ ts: Date.now(),
833
+ }
834
+ }
835
+
836
+ /**
837
+ * Build a `pod-host:response` envelope. `result` and `error` are always
838
+ * present (as `null` when unused), matching `createRpcResponse()` in
839
+ * `messages.mjs`.
840
+ *
841
+ * @param {string} requestId - The `createHostRequest()` id being answered.
842
+ * @param {object} opts
843
+ * @param {boolean} opts.ok
844
+ * @param {*} [opts.result]
845
+ * @param {{code: string, message: string}} [opts.error]
846
+ * @returns {{type: string, requestId: string, ok: boolean, result: *, error: object|null, ts: number}}
847
+ */
848
+ export function createHostResponse(requestId, { ok, result, error } = {}) {
849
+ return {
850
+ type: POD_HOST_RESPONSE,
851
+ requestId,
852
+ ok: Boolean(ok),
853
+ result: result ?? null,
854
+ error: error ? { code: error.code, message: error.message } : null,
855
+ ts: Date.now(),
856
+ }
857
+ }
858
+
859
+ /**
860
+ * Build a `pod-host:event` envelope.
861
+ *
862
+ * @param {string} kind - A `POD_HOST_EVENT_KIND` value.
863
+ * @param {object} [data]
864
+ * @returns {{type: string, kind: string, data: object, ts: number}}
865
+ */
866
+ export function createHostEvent(kind, data = {}) {
867
+ return { type: POD_HOST_EVENT, kind, data, ts: Date.now() }
868
+ }
869
+
870
+ // ---------------------------------------------------------------------------
871
+ // The driver interface (documentation only — a typedef, not a class)
872
+ // ---------------------------------------------------------------------------
873
+
874
+ /**
875
+ * @typedef {object} PodHostDriverCapabilities
876
+ * @property {string[]} verbs - The `POD_HOST_VERB` values this driver
877
+ * actually serves. Always a subset of `POD_LANE_VERBS[driver.lane]`.
878
+ */
879
+
880
+ /**
881
+ * @typedef {object} PodHostStatus
882
+ * @property {string} name
883
+ * @property {string} lane
884
+ * @property {string} state - A `POD_LIFECYCLE` value.
885
+ * @property {number} createdAt
886
+ * @property {number} updatedAt
887
+ * @property {object} [spec] - The normalized podspec, when the driver keeps it.
888
+ * @property {string|null} [podId] - The hosted pod's own mesh identity, once known.
889
+ */
890
+
891
+ /**
892
+ * `PodHostDriver` — the lane adapter the pod-host service dispatches to.
893
+ *
894
+ * It is a **typedef, not a class**: a driver is any object with these
895
+ * members, so a Worker, a Firecracker host agent and an in-memory fake can
896
+ * all be one without inheriting anything. Every method returns a Promise.
897
+ * A verb the driver cannot serve must REJECT with a `PodHostDriverError`
898
+ * carrying `ELANE` (the lane structurally cannot) or `ENOTSUP` (this driver
899
+ * did not implement it) — see `createUnsupportedDriverMethod()`, which
900
+ * builds exactly such a method.
901
+ *
902
+ * `onEvent` is optional. A driver that has it pushes `createHostEvent()`
903
+ * envelopes; the service forwards them to interested requesters.
904
+ *
905
+ * @typedef {object} PodHostDriver
906
+ * @property {string} lane - A `POD_LANE` value.
907
+ * @property {() => PodHostDriverCapabilities} capabilities
908
+ * @property {(spec: object) => Promise<PodHostStatus>} spawn
909
+ * @property {(name: string) => Promise<PodHostStatus>} status
910
+ * @property {(name: string, msg: {to?: string, payload: *}) => Promise<object>} send
911
+ * @property {(name: string, argv: string[], opts?: {timeoutMs?: number}) => Promise<{stdout: string, stderr: string, code: number}>} exec
912
+ * @property {(name: string) => Promise<PodHostStatus>} snapshot
913
+ * @property {(name: string) => Promise<PodHostStatus>} restore
914
+ * @property {(name: string, opts?: {cascade?: boolean}) => Promise<PodHostStatus>} drain
915
+ * @property {() => Promise<PodHostStatus[]>} list
916
+ * @property {(fn: (event: object) => void) => (() => void)} [onEvent] - Subscribe
917
+ * to this driver's `createHostEvent()` output. Returns an unsubscribe function.
918
+ */
919
+
920
+ // ---------------------------------------------------------------------------
921
+ // InMemoryPodHostDriver — the reference driver
922
+ // ---------------------------------------------------------------------------
923
+
924
+ /**
925
+ * A complete, dependency-free `PodHostDriver` backed by a `Map` of fake
926
+ * pods, running the real `POD_LIFECYCLE` state machine via
927
+ * `canTransition()`. This is the driver tests, examples and every later
928
+ * control surface (mesh:// routes, meshctl tools, the external CLI) use
929
+ * when they need a host that behaves correctly without a workerd process or
930
+ * a KVM box behind it.
931
+ *
932
+ * Lane is configurable (default `'node'`, which supports all eight verbs);
933
+ * set `lane: 'isolate'` to get a driver that rejects `exec`/`snapshot`/
934
+ * `restore` with `ELANE`, exactly as a real Worker host does.
935
+ *
936
+ * Drained pods are kept as tombstones in state `gone` so `status()` still
937
+ * answers after a drain (and `list()` still shows them); `spawn()` reuses a
938
+ * tombstoned name rather than reporting `EEXIST`.
939
+ */
940
+ export class InMemoryPodHostDriver {
941
+ /** @type {string} */
942
+ #lane
943
+
944
+ /** @type {Set<string>} */
945
+ #verbs
946
+
947
+ /** @type {Map<string, {name: string, lane: string, spec: object, state: string, createdAt: number, updatedAt: number, inbox: object[], execs: number}>} */
948
+ #pods = new Map()
949
+
950
+ /** @type {(argv: string[], ctx: {name: string, timeoutMs?: number}) => Promise<{stdout: string, stderr: string, code: number}>} */
951
+ #exec
952
+
953
+ /** @type {Set<(event: object) => void>} */
954
+ #listeners = new Set()
955
+
956
+ /**
957
+ * @param {object} [opts]
958
+ * @param {string} [opts.lane='node'] - A `POD_LANE` value.
959
+ * @param {string[]} [opts.verbs] - Narrow the served verb set further than
960
+ * the lane already does (useful for testing `ENOTSUP` paths). Never
961
+ * widens it: a verb the lane cannot do stays `ELANE`.
962
+ * @param {(argv: string[], ctx: {name: string, timeoutMs?: number}) => Promise<{stdout: string, stderr: string, code: number}>} [opts.exec]
963
+ * Injectable exec implementation. Defaults to echoing the argv back as
964
+ * `stdout` with `code: 0`.
965
+ */
966
+ constructor({ lane = POD_LANE.NODE, verbs, exec } = {}) {
967
+ if (!POD_LANES.includes(lane)) {
968
+ throw new Error(`InMemoryPodHostDriver: unknown lane '${lane}'`)
969
+ }
970
+ this.#lane = lane
971
+ const laneVerbs = POD_LANE_VERBS[lane]
972
+ this.#verbs = new Set(verbs ? laneVerbs.filter((verb) => verbs.includes(verb)) : laneVerbs)
973
+ this.#exec = exec || (async (argv) => ({ stdout: argv.join(' '), stderr: '', code: 0 }))
974
+ }
975
+
976
+ /** @returns {string} A `POD_LANE` value. */
977
+ get lane() {
978
+ return this.#lane
979
+ }
980
+
981
+ /** @returns {PodHostDriverCapabilities} */
982
+ capabilities() {
983
+ return { verbs: [...this.#verbs] }
984
+ }
985
+
986
+ /**
987
+ * Subscribe to this driver's lifecycle/log/exit events.
988
+ * @param {(event: object) => void} fn
989
+ * @returns {() => void} Unsubscribe.
990
+ */
991
+ onEvent(fn) {
992
+ if (typeof fn !== 'function') return () => {}
993
+ this.#listeners.add(fn)
994
+ return () => { this.#listeners.delete(fn) }
995
+ }
996
+
997
+ // -- verbs ---------------------------------------------------------------
998
+
999
+ /**
1000
+ * @param {object} spec - A podspec; validated with `validatePodSpec()`.
1001
+ * @returns {Promise<PodHostStatus>}
1002
+ */
1003
+ async spawn(spec) {
1004
+ this.#requireVerb(POD_HOST_VERB.SPAWN)
1005
+ const validated = validatePodSpec(spec)
1006
+ if (!validated.ok) {
1007
+ throw new PodHostDriverError(POD_HOST_ERROR.EINVAL, validated.errors.join('; '), { errors: validated.errors })
1008
+ }
1009
+ const value = validated.value
1010
+ const existing = this.#pods.get(value.name)
1011
+ if (existing && existing.state !== POD_LIFECYCLE.GONE) {
1012
+ throw new PodHostDriverError(POD_HOST_ERROR.EEXIST, `pod '${value.name}' already exists`, { name: value.name })
1013
+ }
1014
+
1015
+ const now = Date.now()
1016
+ const record = {
1017
+ name: value.name,
1018
+ lane: this.#lane,
1019
+ spec: value,
1020
+ state: POD_LIFECYCLE.COLD,
1021
+ createdAt: now,
1022
+ updatedAt: now,
1023
+ inbox: [],
1024
+ execs: 0,
1025
+ }
1026
+ this.#pods.set(value.name, record)
1027
+ this.#transition(record, POD_LIFECYCLE.BOOTING, 'spawn')
1028
+ this.#transition(record, POD_LIFECYCLE.REGISTERED, 'spawn')
1029
+ return this.#snapshotOf(record)
1030
+ }
1031
+
1032
+ /**
1033
+ * @param {string} name
1034
+ * @returns {Promise<PodHostStatus>}
1035
+ */
1036
+ async status(name) {
1037
+ this.#requireVerb(POD_HOST_VERB.STATUS)
1038
+ return this.#snapshotOf(this.#require(name))
1039
+ }
1040
+
1041
+ /**
1042
+ * @param {string} name
1043
+ * @param {{to?: string, payload: *}} msg
1044
+ * @returns {Promise<{delivered: boolean, inbox: number}>}
1045
+ */
1046
+ async send(name, msg) {
1047
+ this.#requireVerb(POD_HOST_VERB.SEND)
1048
+ const record = this.#requireLive(name)
1049
+ record.inbox.push({ to: msg?.to ?? null, payload: msg?.payload ?? null, ts: Date.now() })
1050
+ record.updatedAt = Date.now()
1051
+ return { delivered: true, inbox: record.inbox.length }
1052
+ }
1053
+
1054
+ /**
1055
+ * @param {string} name
1056
+ * @param {string[]} argv
1057
+ * @param {{timeoutMs?: number}} [opts]
1058
+ * @returns {Promise<{stdout: string, stderr: string, code: number}>}
1059
+ */
1060
+ async exec(name, argv, opts = {}) {
1061
+ this.#requireVerb(POD_HOST_VERB.EXEC)
1062
+ const record = this.#requireLive(name)
1063
+ this.#transition(record, POD_LIFECYCLE.SERVING, 'exec')
1064
+ try {
1065
+ const result = await this.#exec(argv, { name, timeoutMs: opts.timeoutMs })
1066
+ record.execs += 1
1067
+ this.#emit(createHostEvent(POD_HOST_EVENT_KIND.LOG, {
1068
+ name, lane: this.#lane, stream: 'stdout', chunk: result.stdout,
1069
+ }))
1070
+ return result
1071
+ } finally {
1072
+ this.#transition(record, POD_LIFECYCLE.REGISTERED, 'exec-done')
1073
+ }
1074
+ }
1075
+
1076
+ /**
1077
+ * `registered -> paused -> snapshotted` (both edges, so a subscriber sees
1078
+ * the same two transitions a real microVM host emits).
1079
+ * @param {string} name
1080
+ * @returns {Promise<PodHostStatus>}
1081
+ */
1082
+ async snapshot(name) {
1083
+ this.#requireVerb(POD_HOST_VERB.SNAPSHOT)
1084
+ const record = this.#require(name)
1085
+ if (record.state === POD_LIFECYCLE.REGISTERED) this.#transition(record, POD_LIFECYCLE.PAUSED, 'snapshot')
1086
+ this.#transition(record, POD_LIFECYCLE.SNAPSHOTTED, 'snapshot')
1087
+ return this.#snapshotOf(record)
1088
+ }
1089
+
1090
+ /**
1091
+ * `snapshotted -> restoring -> registered`.
1092
+ * @param {string} name
1093
+ * @returns {Promise<PodHostStatus>}
1094
+ */
1095
+ async restore(name) {
1096
+ this.#requireVerb(POD_HOST_VERB.RESTORE)
1097
+ const record = this.#require(name)
1098
+ this.#transition(record, POD_LIFECYCLE.RESTORING, 'restore')
1099
+ this.#transition(record, POD_LIFECYCLE.REGISTERED, 'restore')
1100
+ return this.#snapshotOf(record)
1101
+ }
1102
+
1103
+ /**
1104
+ * `* -> draining -> gone`, plus an `exit` event. `cascade` is recorded on
1105
+ * the exit event; this driver has no child pods of its own to cascade to.
1106
+ * @param {string} name
1107
+ * @param {{cascade?: boolean}} [opts]
1108
+ * @returns {Promise<PodHostStatus>}
1109
+ */
1110
+ async drain(name, opts = {}) {
1111
+ this.#requireVerb(POD_HOST_VERB.DRAIN)
1112
+ const record = this.#require(name)
1113
+ if (record.state !== POD_LIFECYCLE.GONE) {
1114
+ this.#transition(record, POD_LIFECYCLE.DRAINING, 'drain')
1115
+ this.#transition(record, POD_LIFECYCLE.GONE, 'drain')
1116
+ }
1117
+ this.#emit(createHostEvent(POD_HOST_EVENT_KIND.EXIT, {
1118
+ name, lane: this.#lane, code: 0, cascade: opts.cascade === true,
1119
+ reason: 'drained', restartable: false,
1120
+ }))
1121
+ return this.#snapshotOf(record)
1122
+ }
1123
+
1124
+ /**
1125
+ * TEST-ONLY: force a live pod straight to `gone` with `reason: 'crashed'`,
1126
+ * for exercising a supervisor's restart policy without a real failure.
1127
+ * Unlike `drain()`, `restartable` is `true` -- a crash is exactly the
1128
+ * case a supervisor's `on-failure`/`always` restart policy exists for.
1129
+ *
1130
+ * @param {string} name
1131
+ * @param {{code?: number}} [opts]
1132
+ * @returns {Promise<PodHostStatus>}
1133
+ */
1134
+ async crash(name, { code = 1 } = {}) {
1135
+ const record = this.#requireLive(name)
1136
+ this.#transition(record, POD_LIFECYCLE.GONE, 'crash')
1137
+ this.#emit(createHostEvent(POD_HOST_EVENT_KIND.EXIT, {
1138
+ name, lane: this.#lane, code, reason: 'crashed', restartable: true,
1139
+ }))
1140
+ return this.#snapshotOf(record)
1141
+ }
1142
+
1143
+ /** @returns {Promise<PodHostStatus[]>} Every tracked pod, tombstones included. */
1144
+ async list() {
1145
+ this.#requireVerb(POD_HOST_VERB.LIST)
1146
+ return [...this.#pods.values()].map((record) => this.#snapshotOf(record))
1147
+ }
1148
+
1149
+ // -- internals -------------------------------------------------------------
1150
+
1151
+ /**
1152
+ * Refuse a verb this driver does not serve, with `ELANE` when the lane
1153
+ * structurally cannot and `ENOTSUP` when only this driver's narrowed
1154
+ * `verbs` option excluded it.
1155
+ * @param {string} verb
1156
+ */
1157
+ #requireVerb(verb) {
1158
+ if (this.#verbs.has(verb)) return
1159
+ throw unsupportedVerbError(verb, this.#lane)
1160
+ }
1161
+
1162
+ /** @param {string} name @returns {object} */
1163
+ #require(name) {
1164
+ const record = this.#pods.get(name)
1165
+ if (!record) throw new PodHostDriverError(POD_HOST_ERROR.ENOENT, `no pod named '${name}'`, { name })
1166
+ return record
1167
+ }
1168
+
1169
+ /** @param {string} name @returns {object} A pod that is not a tombstone. */
1170
+ #requireLive(name) {
1171
+ const record = this.#require(name)
1172
+ if (record.state === POD_LIFECYCLE.GONE) {
1173
+ throw new PodHostDriverError(POD_HOST_ERROR.ENOENT, `pod '${name}' is gone`, { name })
1174
+ }
1175
+ return record
1176
+ }
1177
+
1178
+ /** @param {object} record @param {string} to @param {string} reason */
1179
+ #transition(record, to, reason) {
1180
+ if (!canTransition(record.state, to)) {
1181
+ throw new PodHostDriverError(
1182
+ POD_HOST_ERROR.EBUSY,
1183
+ `pod '${record.name}' cannot go ${record.state} -> ${to}`,
1184
+ { name: record.name, from: record.state, to },
1185
+ )
1186
+ }
1187
+ const from = record.state
1188
+ record.state = to
1189
+ record.updatedAt = Date.now()
1190
+ this.#emit(createHostEvent(POD_HOST_EVENT_KIND.LIFECYCLE, {
1191
+ name: record.name, lane: this.#lane, from, to, reason,
1192
+ }))
1193
+ }
1194
+
1195
+ /** @param {object} event */
1196
+ #emit(event) {
1197
+ for (const fn of [...this.#listeners]) {
1198
+ try {
1199
+ fn(event)
1200
+ } catch {
1201
+ // A throwing subscriber never breaks the driver or other
1202
+ // subscribers — same rule `mesh-service.mjs`'s event bus applies.
1203
+ }
1204
+ }
1205
+ }
1206
+
1207
+ /** @param {object} record @returns {PodHostStatus} */
1208
+ #snapshotOf(record) {
1209
+ return {
1210
+ name: record.name,
1211
+ lane: record.lane,
1212
+ state: record.state,
1213
+ spec: record.spec,
1214
+ createdAt: record.createdAt,
1215
+ updatedAt: record.updatedAt,
1216
+ inbox: record.inbox.length,
1217
+ execs: record.execs,
1218
+ podId: null,
1219
+ }
1220
+ }
1221
+ }