@johnhenry/browsermesh-apps 0.11.0 → 0.13.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,732 @@
1
+ /**
2
+ * pod-host-service.mjs -- the gated, audited mesh service that speaks the
3
+ * pod host protocol (issue #185's "hosted pods control surface", item 2).
4
+ *
5
+ * `@johnhenry/browsermesh-pod`'s `host-protocol.mjs` defines the eight
6
+ * lane-agnostic verbs (`spawn`, `status`, `send`, `exec`, `snapshot`,
7
+ * `restore`, `drain`, `list`), the podspec, the lifecycle state machine and
8
+ * the wire envelopes -- as PLAIN DATA, so a Worker or a microVM host agent
9
+ * can import it without pulling in this package. THIS file is the other
10
+ * half: the place where those verbs meet `PeerRegistry.checkAccess()`, the
11
+ * `AuditChain` and the orchestrator's `PLACEMENT_AUDIT` vocabulary, none of
12
+ * which exist outside `browsermesh-apps`.
13
+ *
14
+ * Every later surface is a projection of this one service -- `mesh://`
15
+ * routes, `meshctl` LLM tools, an external CLI, a supervisor. None of them
16
+ * should re-implement access control, validation or audit; they should call
17
+ * `createPodHostClient()` (or, in-process, the service's own `api`).
18
+ *
19
+ * ---------------------------------------------------------------------------
20
+ * Three pieces:
21
+ *
22
+ * - `createPodHostService({driver, ...})` -- a `MeshService` descriptor
23
+ * (`mesh-service.mjs`'s convention, same as `createMeshKvService()` /
24
+ * `createGrantLogService()`). Attach it with `attachService(peerNode,
25
+ * undefined, descriptor)`. It owns the HOST side: gate, validate,
26
+ * dispatch to the driver, respond, fan events out.
27
+ * - `createPodHostClient({peerNode})` -- the REQUESTER side: one method
28
+ * per verb, `requestId` correlation, a timeout, and remote
29
+ * `{code, message}` errors rethrown as `PodHostDriverError`.
30
+ * - `podHostRuntimePeer()` -- projects a host's `describe()` into the
31
+ * runtime-registry peer shape `orchestrator.mjs`'s
32
+ * `runtimePeerToComputeDescriptor()` already reads, so a host pod can
33
+ * be scored for placement without that function learning anything new.
34
+ *
35
+ * ---------------------------------------------------------------------------
36
+ * ACCESS CONTROL. Every verb is checked as
37
+ * `ctx.registry.checkAccess(pubKey, resource, verb)` -- i.e. the scope
38
+ * grammar is `pod-host:spawn`, `pod-host:exec`, ... under the default
39
+ * `resource` of `'pod-host'`. A host serving several tenants gives each its
40
+ * own resource (`createPodHostService({resource: 'pod-host:tenant-a'})`)
41
+ * rather than trying to express tenancy inside one scope.
42
+ *
43
+ * `describe` is DELIBERATELY NOT GATED, and travels on its own
44
+ * `pod-host:describe` envelope rather than as a ninth verb. It returns only
45
+ * what the host would publish in its announce metadata anyway (its lane,
46
+ * its verb set, whether it can deploy); gating it would be security theatre
47
+ * that also breaks discovery -- a peer has to be able to find out a host
48
+ * exists before it can ask to be granted anything on it.
49
+ *
50
+ * ---------------------------------------------------------------------------
51
+ * AUDIT. When an `auditChain` is supplied, the host writes the
52
+ * `PLACEMENT_AUDIT` record types WP4 introduced (`orchestrator.mjs`):
53
+ *
54
+ * placement_requested a spawn request arrived (before the access check)
55
+ * placement_denied checkAccess() said no, for any verb
56
+ * placement_started spawn passed the gate and reached the driver
57
+ * placement_ready the driver returned a live pod
58
+ * placement_evicted a pod was drained (or snapshotted away)
59
+ *
60
+ * The REQUESTER side records its own `placement_requested`/`placement_ready`
61
+ * /`placement_denied` through `MeshOrchestrator#recordPlacement()`; the two
62
+ * sides are independent chains with independent authors, by design -- a
63
+ * host's audit log is not evidence to the requester and vice versa.
64
+ *
65
+ * ---------------------------------------------------------------------------
66
+ * Observability events (`ctx.emit()`, see `mesh-service.mjs`'s own module
67
+ * doc comment for the convention):
68
+ *
69
+ * - `pod-host:request` `{from, verb, requestId}` -- a gated request was accepted.
70
+ * - `pod-host:denied` `{from, verb, requestId, reason}` -- `checkAccess()` refused.
71
+ * - `pod-host:completed` `{from, verb, requestId, ok, code}` -- a response was sent.
72
+ * - `pod-host:event` `{kind, data}` -- a driver lifecycle/log/exit event.
73
+ *
74
+ * No browser-only imports at module level.
75
+ */
76
+
77
+ import {
78
+ POD_HOST_REQUEST,
79
+ POD_HOST_RESPONSE,
80
+ POD_HOST_EVENT,
81
+ POD_HOST_EVENT_KIND,
82
+ POD_HOST_VERB,
83
+ POD_HOST_VERBS,
84
+ POD_HOST_ERROR,
85
+ POD_LANE,
86
+ PodHostDriverError,
87
+ createHostRequest,
88
+ createHostResponse,
89
+ laneSupports,
90
+ validateVerbRequest,
91
+ } from '@johnhenry/browsermesh-pod'
92
+ import { PLACEMENT_AUDIT } from './orchestrator.mjs'
93
+ import { decodeWireData } from './internal/wire-envelope.mjs'
94
+
95
+ /** Envelope type of a host-metadata request. Not one of the eight verbs -- see the module doc comment. */
96
+ export const POD_HOST_DESCRIBE = 'pod-host:describe'
97
+
98
+ /** Default ACL resource every verb is checked against. */
99
+ export const DEFAULT_POD_HOST_RESOURCE = 'pod-host'
100
+
101
+ /** Default `createPodHostClient()` request timeout, in ms. */
102
+ export const DEFAULT_POD_HOST_TIMEOUT_MS = 10_000
103
+
104
+ /**
105
+ * The `shellBackend` each lane advertises, using the exact strings
106
+ * `orchestrator.mjs`'s `runtimePeerToComputeDescriptor()` already maps
107
+ * (`'vm-console'` -> the `vm_console` capability, `'pty'` -> `host_pty`).
108
+ * Lanes with no shell advertise none, which is also why they answer `exec`
109
+ * with `ELANE`.
110
+ */
111
+ const LANE_SHELL_BACKEND = Object.freeze({
112
+ [POD_LANE.MICROVM]: 'vm-console',
113
+ [POD_LANE.NODE]: 'pty',
114
+ [POD_LANE.ISOLATE]: null,
115
+ [POD_LANE.BROWSER]: null,
116
+ })
117
+
118
+ /**
119
+ * @typedef {object} PodHostDescription
120
+ * @property {string|null} podId - The host pod's own mesh identity.
121
+ * @property {string} lane - A `POD_LANE` value.
122
+ * @property {string[]} verbs - Verbs this host actually serves.
123
+ * @property {string[]} runtimeClasses - `[lane]` -- the `runtime:<class>`
124
+ * capability strings `ResourceScorer` matches on.
125
+ * @property {string|null} shellBackend
126
+ * @property {{canDeploy: boolean}} deploymentSupport
127
+ * @property {string[]} capabilities
128
+ * @property {string} resource - The ACL resource verbs are checked against.
129
+ * @property {string|null} hostLabel
130
+ */
131
+
132
+ /**
133
+ * Project a `describe()` result into the runtime-registry peer shape
134
+ * `orchestrator.mjs`'s `runtimePeerToComputeDescriptor()` reads, so a host
135
+ * pod can be registered for placement scoring without that function
136
+ * learning anything about pod hosts.
137
+ *
138
+ * KNOWN LIMITATION, worth stating plainly rather than papering over:
139
+ * `runtimePeerToComputeDescriptor()` returns `null` for any peer whose
140
+ * capabilities do not include `shell`/`exec`/`tools` (that is what it turns
141
+ * into the `compute` capability every scored descriptor needs). An
142
+ * ISOLATE-lane pod host has no `exec` by definition, so it produces no
143
+ * compute descriptor today and can only be reached through this service
144
+ * directly, not through `dispatchCompute()`. Fixing that means teaching the
145
+ * orchestrator that "can spawn" is a kind of compute even without a shell
146
+ * -- a change to WP4's scoring surface, deliberately out of scope here.
147
+ *
148
+ * @param {PodHostDescription} description
149
+ * @param {object} [extra]
150
+ * @param {object} [extra.resources] - Advertised resources, if any.
151
+ * @param {string} [extra.hostedBy] - Set when this host is itself hosted.
152
+ * @returns {object} A runtime-registry peer record.
153
+ */
154
+ export function podHostRuntimePeer(description, extra = {}) {
155
+ return {
156
+ identity: { podId: description.podId },
157
+ capabilities: [...description.capabilities],
158
+ shellBackend: description.shellBackend ?? undefined,
159
+ metadata: {
160
+ runtimeClasses: [...description.runtimeClasses],
161
+ deploymentSupport: { ...description.deploymentSupport },
162
+ podHost: { verbs: [...description.verbs], resource: description.resource },
163
+ ...(extra.resources ? { resources: extra.resources } : {}),
164
+ ...(extra.hostedBy ? { hostedBy: extra.hostedBy } : {}),
165
+ },
166
+ }
167
+ }
168
+
169
+ // ---------------------------------------------------------------------------
170
+ // Host side
171
+ // ---------------------------------------------------------------------------
172
+
173
+ /**
174
+ * Build the `MeshService` descriptor that serves the pod host protocol for
175
+ * one driver.
176
+ *
177
+ * @param {object} opts
178
+ * @param {import('@johnhenry/browsermesh-pod').PodHostDriver} opts.driver
179
+ * The lane adapter. Must at minimum expose `lane` and `capabilities()`;
180
+ * any verb it omits is answered `ENOTSUP` without the driver being called.
181
+ * @param {string} [opts.resource='pod-host'] - ACL resource every verb is
182
+ * checked against (`checkAccess(pubKey, resource, verb)`).
183
+ * @param {object} [opts.auditChain] - Duck-typed `AuditChain`
184
+ * (`{append(authorPodId, operation, data, signFn)}`). When supplied, the
185
+ * host writes `PLACEMENT_AUDIT` records -- see the module doc comment.
186
+ * @param {string} [opts.shellBackend] - Override the lane's default
187
+ * `shellBackend` in `describe()`.
188
+ * @param {string} [opts.hostLabel] - Human-readable host name, echoed in
189
+ * `describe()` and in audit records.
190
+ * @param {Function} [opts.onLog] - `(event, data) => void` debug logging.
191
+ * @returns {import('./mesh-service.mjs').MeshService}
192
+ */
193
+ export function createPodHostService({
194
+ driver,
195
+ resource = DEFAULT_POD_HOST_RESOURCE,
196
+ auditChain,
197
+ onLog,
198
+ hostLabel,
199
+ shellBackend,
200
+ } = {}) {
201
+ if (!driver || typeof driver !== 'object') {
202
+ throw new Error('createPodHostService: driver is required')
203
+ }
204
+ if (typeof driver.lane !== 'string' || !driver.lane) {
205
+ throw new Error('createPodHostService: driver.lane is required')
206
+ }
207
+ if (typeof driver.capabilities !== 'function') {
208
+ throw new Error('createPodHostService: driver.capabilities() is required')
209
+ }
210
+
211
+ const log = onLog || (() => {})
212
+ const lane = driver.lane
213
+ // `undefined` means "use the lane default"; an explicit `null` means
214
+ // "this host advertises no shell backend", which is a different claim.
215
+ const advertisedShellBackend = shellBackend === undefined
216
+ ? (LANE_SHELL_BACKEND[lane] ?? null)
217
+ : shellBackend
218
+
219
+ return {
220
+ name: 'pod-host',
221
+
222
+ attach(peerNode, ctx) {
223
+ /** @type {string[]} The verbs this host answers; everything else is ELANE/ENOTSUP. */
224
+ const verbs = (driver.capabilities().verbs || []).filter((verb) => POD_HOST_VERBS.includes(verb))
225
+
226
+ /**
227
+ * Which requesters are interested in which pod, for event fan-out.
228
+ * A peer becomes interested by successfully addressing a pod by name
229
+ * (spawning it, or driving any other named verb against it).
230
+ * @type {Map<string, Set<string>>} pod name -> pubKeys
231
+ */
232
+ const interested = new Map()
233
+
234
+ /**
235
+ * @param {string} operation - A `PLACEMENT_AUDIT` value.
236
+ * @param {object} data
237
+ * @returns {Promise<void>}
238
+ */
239
+ async function recordAudit(operation, data) {
240
+ if (!auditChain || typeof auditChain.append !== 'function') return
241
+ const podId = peerNode.podId
242
+ if (!podId) return
243
+ try {
244
+ await auditChain.append(
245
+ podId,
246
+ operation,
247
+ { lane, resource, host: hostLabel ?? podId, ...data },
248
+ (payload) => peerNode.wallet.sign(podId, payload),
249
+ )
250
+ } catch (err) {
251
+ // Audit failures never break a verb -- same rule `PeerNode#audit()`
252
+ // already applies to its own chain writes.
253
+ log('pod-host:audit-failed', { operation, error: err?.message || String(err) })
254
+ }
255
+ }
256
+
257
+ /** @returns {PodHostDescription} */
258
+ function describe() {
259
+ return {
260
+ podId: peerNode.podId ?? null,
261
+ lane,
262
+ verbs: [...verbs],
263
+ runtimeClasses: [lane],
264
+ shellBackend: advertisedShellBackend,
265
+ deploymentSupport: { canDeploy: verbs.includes(POD_HOST_VERB.SPAWN) },
266
+ // `compute` is what `runtimePeerToComputeDescriptor()` derives
267
+ // from `exec`; a host without exec deliberately does not claim it.
268
+ capabilities: [
269
+ 'pod-host',
270
+ ...(verbs.includes(POD_HOST_VERB.EXEC) ? ['exec'] : []),
271
+ ],
272
+ resource,
273
+ hostLabel: hostLabel ?? null,
274
+ }
275
+ }
276
+
277
+ /**
278
+ * Refuse a verb before the driver is ever called: `ELANE` when the
279
+ * lane structurally cannot, `ENOTSUP` when this driver simply does
280
+ * not serve it.
281
+ * @param {string} verb
282
+ * @returns {PodHostDriverError|null}
283
+ */
284
+ function verbRefusal(verb) {
285
+ // Lane first, driver second: a driver may not widen its lane by
286
+ // declaring a verb the lane excludes (found by the browser-lane
287
+ // extension driver, whose chrome.tabs.discard would otherwise have
288
+ // slipped through as 'snapshot').
289
+ if (!laneSupports(lane, verb)) {
290
+ return new PodHostDriverError(POD_HOST_ERROR.ELANE, `lane '${lane}' cannot '${verb}'`, { verb, lane })
291
+ }
292
+ if (verbs.includes(verb) && typeof driver[verb] === 'function') return null
293
+ return new PodHostDriverError(
294
+ POD_HOST_ERROR.ENOTSUP,
295
+ `host does not implement '${verb}'`,
296
+ { verb, lane },
297
+ )
298
+ }
299
+
300
+ /**
301
+ * @param {string} verb
302
+ * @param {object} value - The NORMALIZED payload from `validateVerbRequest()`.
303
+ * @returns {Promise<*>}
304
+ */
305
+ async function dispatch(verb, value) {
306
+ switch (verb) {
307
+ case POD_HOST_VERB.SPAWN:
308
+ return driver.spawn(value)
309
+ case POD_HOST_VERB.STATUS:
310
+ return driver.status(value.name)
311
+ case POD_HOST_VERB.SEND:
312
+ return driver.send(value.name, { to: value.to, payload: value.payload })
313
+ case POD_HOST_VERB.EXEC:
314
+ return driver.exec(value.name, value.command, { timeoutMs: value.timeoutMs })
315
+ case POD_HOST_VERB.SNAPSHOT:
316
+ return driver.snapshot(value.name)
317
+ case POD_HOST_VERB.RESTORE:
318
+ return driver.restore(value.name)
319
+ case POD_HOST_VERB.DRAIN:
320
+ return driver.drain(value.name, { cascade: value.cascade })
321
+ case POD_HOST_VERB.LIST:
322
+ default:
323
+ return driver.list()
324
+ }
325
+ }
326
+
327
+ /**
328
+ * @param {string} pubKey
329
+ * @param {string} requestId
330
+ * @param {{ok: boolean, result?: *, error?: {code: string, message: string}}} body
331
+ */
332
+ async function respond(pubKey, requestId, body) {
333
+ try {
334
+ const response = createHostResponse(requestId, body)
335
+ await ctx.sendTo(pubKey, POD_HOST_RESPONSE, {
336
+ requestId: response.requestId,
337
+ ok: response.ok,
338
+ result: response.result,
339
+ error: response.error,
340
+ ts: response.ts,
341
+ })
342
+ } catch (err) {
343
+ log('pod-host:respond-failed', { to: pubKey, requestId, error: err?.message || String(err) })
344
+ }
345
+ }
346
+
347
+ /** @param {string} name @param {string} pubKey */
348
+ function noteInterest(name, pubKey) {
349
+ if (!name) return
350
+ let set = interested.get(name)
351
+ if (!set) {
352
+ set = new Set()
353
+ interested.set(name, set)
354
+ }
355
+ set.add(pubKey)
356
+ }
357
+
358
+ /**
359
+ * The one untrusted-input path into this service.
360
+ * @param {string} pubKey
361
+ * @param {object} envelope
362
+ */
363
+ async function handleRequest(pubKey, envelope) {
364
+ const requestId = envelope.requestId
365
+ if (typeof requestId !== 'string' || !requestId) {
366
+ log('pod-host:bad-envelope', { from: pubKey, reason: 'missing requestId' })
367
+ return
368
+ }
369
+
370
+ if (envelope.type === POD_HOST_DESCRIBE) {
371
+ // Ungated on purpose -- see the module doc comment.
372
+ await respond(pubKey, requestId, { ok: true, result: describe() })
373
+ return
374
+ }
375
+
376
+ const verb = envelope.verb
377
+ if (!POD_HOST_VERBS.includes(verb)) {
378
+ await respond(pubKey, requestId, {
379
+ ok: false,
380
+ error: { code: POD_HOST_ERROR.EINVAL, message: `unknown verb '${verb}'` },
381
+ })
382
+ return
383
+ }
384
+
385
+ try {
386
+ const result = await gatedDispatch(pubKey, verb, envelope.payload ?? {}, { requestId })
387
+ await respond(pubKey, requestId, { ok: true, result })
388
+ } catch (err) {
389
+ const driverError = PodHostDriverError.from(err)
390
+ await respond(pubKey, requestId, { ok: false, error: driverError.toJSON() })
391
+ }
392
+ }
393
+
394
+ /**
395
+ * The ONE gated path from "a peer wants `verb`" to the driver: gate,
396
+ * validate, lane/driver refusal, dispatch, with every audit record and
397
+ * `ctx.emit()` this service makes. `handleRequest()` (the envelope
398
+ * path) and `api.dispatch()` (what `pod-host-routes.mjs`'s `mesh://`
399
+ * router and the HTTP gateway call) both go through here, so there is
400
+ * exactly one copy of the gate.
401
+ *
402
+ * Resolves with the driver's result; rejects with a
403
+ * `PodHostDriverError` (`EACCES`, `EINVAL`, `ELANE`, `ENOTSUP`, or
404
+ * whatever the driver threw).
405
+ *
406
+ * @param {string} pubKey - The requesting peer.
407
+ * @param {string} verb
408
+ * @param {object} rawPayload - Un-normalized payload.
409
+ * @param {{requestId?: string}} [opts]
410
+ * @returns {Promise<*>}
411
+ */
412
+ async function gatedDispatch(pubKey, verb, rawPayload, { requestId = `local:${Date.now().toString(36)}:${Math.random().toString(36).slice(2, 8)}` } = {}) {
413
+ if (verb === POD_HOST_VERB.SPAWN) {
414
+ await recordAudit(PLACEMENT_AUDIT.REQUESTED, {
415
+ requester: pubKey, requestId, name: rawPayload?.name ?? null,
416
+ })
417
+ }
418
+
419
+ // 1. Gate.
420
+ const check = ctx.registry.checkAccess(pubKey, resource, verb)
421
+ if (!check.allowed) {
422
+ const reason = check.reason || 'denied'
423
+ log('pod-host:denied', { from: pubKey, verb, reason })
424
+ ctx.emit('pod-host:denied', { from: pubKey, verb, requestId, reason })
425
+ await recordAudit(PLACEMENT_AUDIT.DENIED, { requester: pubKey, requestId, verb, reason })
426
+ throw new PodHostDriverError(POD_HOST_ERROR.EACCES, `not authorized for '${resource}:${verb}'`, { verb, lane })
427
+ }
428
+
429
+ // 2. Validate (and normalize) before anything reaches the driver.
430
+ const validated = validateVerbRequest(verb, rawPayload ?? {})
431
+ if (!validated.ok) {
432
+ ctx.emit('pod-host:completed', { from: pubKey, verb, requestId, ok: false, code: POD_HOST_ERROR.EINVAL })
433
+ throw new PodHostDriverError(POD_HOST_ERROR.EINVAL, validated.errors.join('; '), { verb, lane })
434
+ }
435
+
436
+ // 3. Lane / driver capability.
437
+ const refusal = verbRefusal(verb)
438
+ if (refusal) {
439
+ ctx.emit('pod-host:completed', { from: pubKey, verb, requestId, ok: false, code: refusal.code })
440
+ throw refusal
441
+ }
442
+
443
+ ctx.emit('pod-host:request', { from: pubKey, verb, requestId })
444
+ // Registered BEFORE the driver runs, not after: `spawn` emits its
445
+ // own `cold -> booting -> registered` transitions from inside
446
+ // `dispatch()`, and a requester that only became "interested" once
447
+ // the call returned would miss every event about the pod it just
448
+ // created.
449
+ if (validated.value.name) noteInterest(validated.value.name, pubKey)
450
+ if (verb === POD_HOST_VERB.SPAWN) {
451
+ await recordAudit(PLACEMENT_AUDIT.STARTED, {
452
+ requester: pubKey, requestId, name: validated.value.name,
453
+ })
454
+ }
455
+
456
+ // 4. Dispatch.
457
+ try {
458
+ const result = await dispatch(verb, validated.value)
459
+ if (verb === POD_HOST_VERB.SPAWN) {
460
+ await recordAudit(PLACEMENT_AUDIT.READY, {
461
+ requester: pubKey, requestId, name: validated.value.name, state: result?.state ?? null,
462
+ })
463
+ } else if (verb === POD_HOST_VERB.DRAIN || verb === POD_HOST_VERB.SNAPSHOT) {
464
+ await recordAudit(PLACEMENT_AUDIT.EVICTED, {
465
+ requester: pubKey, requestId, name: validated.value.name, verb, state: result?.state ?? null,
466
+ })
467
+ }
468
+ ctx.emit('pod-host:completed', { from: pubKey, verb, requestId, ok: true, code: null })
469
+ return result
470
+ } catch (err) {
471
+ const driverError = PodHostDriverError.from(err)
472
+ log('pod-host:verb-failed', { from: pubKey, verb, code: driverError.code, error: driverError.message })
473
+ ctx.emit('pod-host:completed', {
474
+ from: pubKey, verb, requestId, ok: false, code: driverError.code,
475
+ })
476
+ throw driverError
477
+ }
478
+ }
479
+
480
+ const unsubscribeIncoming = ctx.onIncomingData([POD_HOST_REQUEST, POD_HOST_DESCRIBE], (pubKey, envelope) => {
481
+ handleRequest(pubKey, envelope).catch((err) => {
482
+ log('pod-host:handler-failed', { from: pubKey, error: err?.message || String(err) })
483
+ })
484
+ })
485
+
486
+ /**
487
+ * Forward one driver event to every peer with an interest in the pod
488
+ * it names, and publish it locally on the service's own event bus.
489
+ * @param {object} event - A `createHostEvent()` envelope.
490
+ */
491
+ function forwardDriverEvent(event) {
492
+ if (!event || typeof event !== 'object') return
493
+ ctx.emit('pod-host:event', { kind: event.kind, data: event.data })
494
+ const name = event.data?.name
495
+ if (!name) return
496
+ const targets = interested.get(name)
497
+ if (!targets) return
498
+ for (const pubKey of [...targets]) {
499
+ ctx.sendTo(pubKey, POD_HOST_EVENT, { kind: event.kind, data: event.data, ts: event.ts })
500
+ .catch((err) => {
501
+ log('pod-host:event-forward-failed', { to: pubKey, error: err?.message || String(err) })
502
+ })
503
+ }
504
+ // A pod that has exited has no further events; stop tracking it so
505
+ // long-lived hosts don't accumulate an entry per pod ever spawned.
506
+ if (event.kind === POD_HOST_EVENT_KIND.EXIT) interested.delete(name)
507
+ }
508
+
509
+ const unsubscribeDriver = typeof driver.onEvent === 'function'
510
+ ? driver.onEvent(forwardDriverEvent)
511
+ : null
512
+
513
+ const api = {
514
+ resource,
515
+ lane,
516
+ get verbs() { return [...verbs] },
517
+ driver,
518
+ describe,
519
+ /** @param {object} [extra] @returns {object} */
520
+ runtimePeer(extra) { return podHostRuntimePeer(describe(), extra) },
521
+ /**
522
+ * Gated dispatch on behalf of `pubKey` -- the same gate, validation,
523
+ * lane check, audit and events the envelope path uses. This is what
524
+ * other projections (`pod-host-routes.mjs`) must call instead of
525
+ * `api.driver`, which stays raw and UNGATED.
526
+ * @param {string} pubKey
527
+ * @param {string} verb
528
+ * @param {object} [payload]
529
+ * @returns {Promise<*>}
530
+ */
531
+ dispatch(pubKey, verb, payload = {}) {
532
+ if (!POD_HOST_VERBS.includes(verb)) {
533
+ return Promise.reject(new PodHostDriverError(POD_HOST_ERROR.EINVAL, `unknown verb '${verb}'`, { verb, lane }))
534
+ }
535
+ return gatedDispatch(pubKey, verb, payload)
536
+ },
537
+ }
538
+
539
+ return {
540
+ api,
541
+ teardown() {
542
+ unsubscribeIncoming()
543
+ if (typeof unsubscribeDriver === 'function') unsubscribeDriver()
544
+ interested.clear()
545
+ },
546
+ }
547
+ },
548
+ }
549
+ }
550
+
551
+ // ---------------------------------------------------------------------------
552
+ // Requester side
553
+ // ---------------------------------------------------------------------------
554
+
555
+ /**
556
+ * @typedef {object} PodHostClient
557
+ * @property {(hostPubKey: string, spec: object) => Promise<object>} spawn
558
+ * @property {(hostPubKey: string, name: string) => Promise<object>} status
559
+ * @property {(hostPubKey: string, name: string, payload: *, opts?: {to?: string}) => Promise<object>} send
560
+ * @property {(hostPubKey: string, name: string, command: string[]|string, opts?: {timeoutMs?: number}) => Promise<{stdout: string, stderr: string, code: number}>} exec
561
+ * @property {(hostPubKey: string, name: string) => Promise<object>} snapshot
562
+ * @property {(hostPubKey: string, name: string) => Promise<object>} restore
563
+ * @property {(hostPubKey: string, name: string, opts?: {cascade?: boolean}) => Promise<object>} drain
564
+ * @property {(hostPubKey: string) => Promise<object[]>} list
565
+ * @property {(hostPubKey: string) => Promise<PodHostDescription>} describe
566
+ * @property {(fn: (hostPubKey: string, event: object) => void) => (() => void)} onEvent
567
+ * @property {() => void} close
568
+ */
569
+
570
+ /**
571
+ * Build a client for talking to remote pod hosts over a `PeerNode`.
572
+ *
573
+ * One client talks to any number of hosts: every method takes the host's
574
+ * pubKey as its first argument. Responses are correlated by the
575
+ * `requestId` `createHostRequest()` generates, so several verbs can be in
576
+ * flight against several hosts at once.
577
+ *
578
+ * A request that gets no response within `timeoutMs` rejects with
579
+ * `PodHostDriverError` / `ETIMEDOUT`; a response carrying
580
+ * `{ok: false, error}` rejects with that error's `{code, message}` rebuilt
581
+ * as a `PodHostDriverError`, so `err.code === 'EACCES'` works the same
582
+ * whether the refusal came from the local driver or six hops away.
583
+ *
584
+ * @param {object} opts
585
+ * @param {object} [opts.peerNode] - The local `PeerNode`.
586
+ * @param {import('./mesh-service.mjs').MeshServiceContext} [opts.ctx] -
587
+ * Alternative to `peerNode`, for a client built inside another service.
588
+ * @param {number} [opts.timeoutMs=10000]
589
+ * @param {Function} [opts.onLog]
590
+ * @returns {PodHostClient}
591
+ */
592
+ export function createPodHostClient({ peerNode, ctx, timeoutMs = DEFAULT_POD_HOST_TIMEOUT_MS, onLog } = {}) {
593
+ const node = peerNode || ctx?.peerNode
594
+ if (!node) throw new Error('createPodHostClient: peerNode (or ctx) is required')
595
+ const log = onLog || (() => {})
596
+
597
+ /** @type {Map<string, {resolve: Function, reject: Function, timer: *}>} */
598
+ const pending = new Map()
599
+ /** @type {Set<(hostPubKey: string, event: object) => void>} */
600
+ const eventListeners = new Set()
601
+ let closed = false
602
+
603
+ const unsubscribe = node.onIncomingData((pubKey, rawData) => {
604
+ // A real transport hands over the JSON text the host's ctx.sendTo() put
605
+ // on the wire (browsermesh#208); `ctx.onIncomingData()` decodes that for
606
+ // services, but this is a raw PeerNode subscriber, so it must too.
607
+ const data = decodeWireData(rawData)
608
+ if (!data || typeof data !== 'object') return
609
+
610
+ if (data.type === POD_HOST_EVENT) {
611
+ for (const fn of [...eventListeners]) {
612
+ try {
613
+ fn(pubKey, { type: POD_HOST_EVENT, kind: data.kind, data: data.data, ts: data.ts })
614
+ } catch {
615
+ // A throwing subscriber never breaks delivery to the others --
616
+ // the same rule `mesh-service.mjs`'s event bus applies.
617
+ }
618
+ }
619
+ return
620
+ }
621
+
622
+ if (data.type !== POD_HOST_RESPONSE) return
623
+ const entry = pending.get(data.requestId)
624
+ if (!entry) {
625
+ // A late response to a request that already timed out. Dropping it
626
+ // is correct: the caller has long since seen ETIMEDOUT.
627
+ log('pod-host-client:unmatched-response', { from: pubKey, requestId: data.requestId })
628
+ return
629
+ }
630
+ pending.delete(data.requestId)
631
+ clearTimeout(entry.timer)
632
+ if (data.ok) entry.resolve(data.result)
633
+ else entry.reject(PodHostDriverError.from(data.error || { code: POD_HOST_ERROR.EINVAL, message: 'unknown error' }))
634
+ })
635
+
636
+ /**
637
+ * @param {string} hostPubKey
638
+ * @param {object} envelope - A request envelope with a `requestId`.
639
+ * @returns {Promise<*>}
640
+ */
641
+ function roundTrip(hostPubKey, envelope) {
642
+ if (closed) {
643
+ return Promise.reject(new PodHostDriverError(POD_HOST_ERROR.EINVAL, 'pod host client is closed'))
644
+ }
645
+ if (!hostPubKey || typeof hostPubKey !== 'string') {
646
+ return Promise.reject(new PodHostDriverError(POD_HOST_ERROR.EINVAL, 'hostPubKey is required'))
647
+ }
648
+ return new Promise((resolve, reject) => {
649
+ const timer = setTimeout(() => {
650
+ pending.delete(envelope.requestId)
651
+ reject(new PodHostDriverError(
652
+ POD_HOST_ERROR.ETIMEDOUT,
653
+ `pod host '${hostPubKey}' did not answer '${envelope.verb || envelope.type}' within ${timeoutMs}ms`,
654
+ { host: hostPubKey, requestId: envelope.requestId },
655
+ ))
656
+ }, timeoutMs)
657
+ // Never hold a Node process open for an in-flight request.
658
+ if (typeof timer === 'object' && typeof timer.unref === 'function') timer.unref()
659
+
660
+ pending.set(envelope.requestId, { resolve, reject, timer })
661
+ Promise.resolve(node.sendTo(hostPubKey, envelope)).catch((err) => {
662
+ pending.delete(envelope.requestId)
663
+ clearTimeout(timer)
664
+ reject(PodHostDriverError.from(err))
665
+ })
666
+ })
667
+ }
668
+
669
+ /**
670
+ * @param {string} hostPubKey
671
+ * @param {string} verb
672
+ * @param {object} [payload]
673
+ * @returns {Promise<*>}
674
+ */
675
+ function call(hostPubKey, verb, payload = {}) {
676
+ return roundTrip(hostPubKey, createHostRequest(verb, payload))
677
+ }
678
+
679
+ return {
680
+ spawn(hostPubKey, spec) {
681
+ return call(hostPubKey, POD_HOST_VERB.SPAWN, spec)
682
+ },
683
+ status(hostPubKey, name) {
684
+ return call(hostPubKey, POD_HOST_VERB.STATUS, { name })
685
+ },
686
+ send(hostPubKey, name, payload, { to } = {}) {
687
+ return call(hostPubKey, POD_HOST_VERB.SEND, to === undefined ? { name, payload } : { name, to, payload })
688
+ },
689
+ exec(hostPubKey, name, command, { timeoutMs: execTimeoutMs } = {}) {
690
+ return call(
691
+ hostPubKey,
692
+ POD_HOST_VERB.EXEC,
693
+ execTimeoutMs === undefined ? { name, command } : { name, command, timeoutMs: execTimeoutMs },
694
+ )
695
+ },
696
+ snapshot(hostPubKey, name) {
697
+ return call(hostPubKey, POD_HOST_VERB.SNAPSHOT, { name })
698
+ },
699
+ restore(hostPubKey, name) {
700
+ return call(hostPubKey, POD_HOST_VERB.RESTORE, { name })
701
+ },
702
+ drain(hostPubKey, name, { cascade } = {}) {
703
+ return call(hostPubKey, POD_HOST_VERB.DRAIN, cascade === undefined ? { name } : { name, cascade })
704
+ },
705
+ list(hostPubKey) {
706
+ return call(hostPubKey, POD_HOST_VERB.LIST, {})
707
+ },
708
+ describe(hostPubKey) {
709
+ // `describe` is not one of the eight verbs (see `POD_HOST_DESCRIBE`
710
+ // and the module doc comment); it borrows `createHostRequest()` only
711
+ // for its id generator, so both envelope families share one id space.
712
+ const { requestId, ts } = createHostRequest(POD_HOST_VERB.LIST)
713
+ return roundTrip(hostPubKey, { type: POD_HOST_DESCRIBE, requestId, ts })
714
+ },
715
+ onEvent(fn) {
716
+ if (typeof fn !== 'function') return () => {}
717
+ eventListeners.add(fn)
718
+ return () => { eventListeners.delete(fn) }
719
+ },
720
+ close() {
721
+ if (closed) return
722
+ closed = true
723
+ unsubscribe()
724
+ eventListeners.clear()
725
+ for (const [, entry] of pending) {
726
+ clearTimeout(entry.timer)
727
+ entry.reject(new PodHostDriverError(POD_HOST_ERROR.EINVAL, 'pod host client closed before the response arrived'))
728
+ }
729
+ pending.clear()
730
+ },
731
+ }
732
+ }