@johnhenry/browsermesh-pod 0.0.3 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +382 -1
- package/package.json +2 -2
- package/src/browser-host-child.mjs +109 -0
- package/src/browser-host-driver.mjs +445 -0
- package/src/detect-kind.mjs +9 -0
- package/src/host-protocol.mjs +1221 -0
- package/src/index.d.ts +274 -1
- package/src/index.mjs +15 -0
- package/src/transport.mjs +3 -1
- package/src/ws-transport.mjs +380 -0
package/README.md
CHANGED
|
@@ -27,6 +27,10 @@ Pods automatically generate an Ed25519 cryptographic identity, detect their exec
|
|
|
27
27
|
- [Pod Kinds](#pod-kinds)
|
|
28
28
|
- [Capabilities](#capabilities)
|
|
29
29
|
- [Wire Protocol](#wire-protocol)
|
|
30
|
+
- [WebSocketTransport (relay-backed)](#websockettransport-relay-backed)
|
|
31
|
+
- [Running a Pod outside the browser](#running-a-pod-outside-the-browser)
|
|
32
|
+
- [Pod host protocol](#pod-host-protocol)
|
|
33
|
+
- [Browser lane drivers](#browser-lane-drivers)
|
|
30
34
|
- [InjectedPod](#injectedpod)
|
|
31
35
|
- [Peer Dependency](#peer-dependency)
|
|
32
36
|
- [License](#license)
|
|
@@ -175,7 +179,7 @@ const server = await createServer({ discoveryTimeout: 5000 })
|
|
|
175
179
|
| `shared-worker` | `instanceof SharedWorkerGlobalScope` |
|
|
176
180
|
| `worker` | `instanceof WorkerGlobalScope` |
|
|
177
181
|
| `worklet` | `instanceof AudioWorkletGlobalScope` |
|
|
178
|
-
| `server` | No `window` or `
|
|
182
|
+
| `server` | No `window`, `document`, or worker global scope — plain Node.js, including a Firecracker microVM guest. Note: inside workerd/Cloudflare Workers the global is an instance of `ServiceWorkerGlobalScope`, so an isolate-hosted pod reports `service-worker`, not `server`. See [Running a Pod outside the browser](#running-a-pod-outside-the-browser). |
|
|
179
183
|
| `iframe` | `window !== window.parent` |
|
|
180
184
|
| `spawned` | `window.opener` is set |
|
|
181
185
|
| `window` | Default (top-level window) |
|
|
@@ -206,6 +210,383 @@ const server = await createServer({ discoveryTimeout: 5000 })
|
|
|
206
210
|
|
|
207
211
|
Message factories: `createHello()`, `createHelloAck()`, `createGoodbye()`, `createMessage()`, `createRpcRequest()`, `createRpcResponse()`.
|
|
208
212
|
|
|
213
|
+
## WebSocketTransport (relay-backed)
|
|
214
|
+
|
|
215
|
+
`BroadcastChannelTransport` only reaches same-origin tabs. `WebSocketTransport` is the adapter that lets a `Pod` run anywhere a WebSocket client exists — a Node process, a browser, or a V8 isolate (workerd / Cloudflare Workers) — and still join the mesh, by speaking the `browsermesh-servers` relay/signaling wire protocol (`register`/`registered`, `relay`/`relayed`, `peers`/`peer-joined`/`peer-left`, `ping`/`pong`, `error`). This is what unlocks "hosted pods" (see [issue #185](https://github.com/johnhenry/browsermesh/issues/185)): a pod running on a machine someone else operates, reachable over the same relay a browser tab would use.
|
|
216
|
+
|
|
217
|
+
```js
|
|
218
|
+
import { Pod, WebSocketTransport } from '@johnhenry/browsermesh-pod'
|
|
219
|
+
import { PodIdentity } from '@johnhenry/browsermesh-primitives'
|
|
220
|
+
|
|
221
|
+
// Pod generates its own identity during boot() unless one is supplied; the
|
|
222
|
+
// transport needs the same podId up front to register with the relay, so
|
|
223
|
+
// generate (or load) the identity first.
|
|
224
|
+
const identity = await PodIdentity.generate()
|
|
225
|
+
|
|
226
|
+
const transport = new WebSocketTransport({
|
|
227
|
+
url: 'wss://relay.example.com',
|
|
228
|
+
podId: identity.podId,
|
|
229
|
+
// WebSocket: globalThis.WebSocket is used by default; inject your own
|
|
230
|
+
// (e.g. the `ws` package, or a fake) for testing or non-browser runtimes
|
|
231
|
+
// that don't expose a global WebSocket.
|
|
232
|
+
peersFromSignaling: true,
|
|
233
|
+
signalingUrl: 'wss://signaling.example.com',
|
|
234
|
+
})
|
|
235
|
+
|
|
236
|
+
const pod = new Pod()
|
|
237
|
+
await pod.boot({ identity, transport })
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
Key properties, driven directly by the relay server's shape:
|
|
241
|
+
|
|
242
|
+
- **Point-to-point only.** The relay server forwards `{type:'relay', target, envelope}` to exactly one registered peer — it has no broadcast primitive. `send(msg)` relays point-to-point when `msg.to` names a specific peer, and fans a `to`-less (or `to: '*'`) message like discovery's `hello`/`goodbye` out point-to-point to every peer id the transport currently knows about (`get knownPeers`).
|
|
243
|
+
- **`knownPeers` has two sources**: every podId seen as the sender of a `relayed` envelope, and — when `peersFromSignaling: true` and `signalingUrl` is set — a second WebSocket connection to the signaling server that consumes its `peers` snapshot plus `peer-joined`/`peer-left` events. Seeding from signaling matters for discovery specifically: without it, two freshly-registered pods' first `hello` broadcasts have nobody to fan out to.
|
|
244
|
+
- **Reconnects with exponential backoff** (`reconnect: { baseMs: 250, maxMs: 10000, maxAttempts: Infinity }` by default) and re-registers on reconnect; `ready` is `false` while disconnected, and `close()` clears all pending timers.
|
|
245
|
+
- **Wire encoding** follows the same rule as `@johnhenry/browsermesh-transport`'s `encodeWireData()`: each relay/signaling frame is sent as exactly one JSON text, with the pod message nested inside as an object (never as a pre-encoded string, so nothing is double-encoded). Inbound frames may be text or binary (`ArrayBuffer`/typed array, read as UTF-8); a `Blob` frame cannot be read synchronously and is ignored.
|
|
246
|
+
- **Protocol note**: the relay/signaling servers' wire protocol uses `target`/`source` field names for forwarding, not `to`/`from` — `WebSocketTransport` speaks the servers' real field names and only remaps to `from` on the Pod message shape when delivering to `onMessage()`.
|
|
247
|
+
|
|
248
|
+
See `examples/12-hosted-pod-over-websocket.mjs` in the monorepo root for a full runnable example (two pods discovering each other and exchanging a message over a simulated relay, no network required).
|
|
249
|
+
|
|
250
|
+
## Running a Pod outside the browser
|
|
251
|
+
|
|
252
|
+
`Pod` (`src/pod.mjs`) is runtime-agnostic: it imports only `PodIdentity` from
|
|
253
|
+
`@johnhenry/browsermesh-primitives` plus its own sibling modules. Everything
|
|
254
|
+
browser-specific lives in the pluggable `transport`/`discovery` adapters and
|
|
255
|
+
in feature-detected capability flags, not in the core class. This section
|
|
256
|
+
spells out exactly what a non-browser host needs to provide, verified
|
|
257
|
+
against this package's source (see
|
|
258
|
+
[`docs/hosted-pods.md`](../../docs/hosted-pods.md) at the monorepo root for
|
|
259
|
+
the full design and how this fits into hosted-pod lanes).
|
|
260
|
+
|
|
261
|
+
### Exact runtime requirements
|
|
262
|
+
|
|
263
|
+
A default `pod.boot()` call (no `window`/`document` present, so
|
|
264
|
+
`detectPodKind()` returns `'server'`) needs:
|
|
265
|
+
|
|
266
|
+
| Requirement | Why | Always runs, or conditional? |
|
|
267
|
+
| --- | --- | --- |
|
|
268
|
+
| `crypto.subtle` — Ed25519 `generateKey` | `PodIdentity.generate()` | Always, unless `opts.identity` is passed in |
|
|
269
|
+
| `crypto.subtle` — `exportKey('raw')` + SHA-256 `digest` | `derivePodId()` | Always, as part of `PodIdentity.generate()` |
|
|
270
|
+
| `btoa` / `atob` | `encodeBase64url()`/`decodeBase64url()` | Always — every `podId` derivation calls these |
|
|
271
|
+
| `setTimeout` | `TransportDiscovery.start()`'s discovery-timeout wait | Whenever a real (non-`Null`) transport/discovery pair is used |
|
|
272
|
+
| `TextEncoder`/`TextDecoder`, `structuredClone` | *(not actually used by this package)* | N/A — see note below |
|
|
273
|
+
|
|
274
|
+
`crypto.subtle.sign`/`verify` are also available on `PodIdentity` but are
|
|
275
|
+
**not** called during `boot()` itself — only when application code
|
|
276
|
+
explicitly signs or verifies data.
|
|
277
|
+
|
|
278
|
+
**Note on `TextEncoder`/`TextDecoder` and `structuredClone`:** despite
|
|
279
|
+
sometimes being cited as `Pod` runtime requirements, neither is used
|
|
280
|
+
anywhere in this package's source. `TextEncoder`/`TextDecoder` appear only
|
|
281
|
+
in `browsermesh-primitives`' wire-format module, which `Pod` does not
|
|
282
|
+
import; `structuredClone` appears only in a primitives test helper. If your
|
|
283
|
+
host environment is missing them, `Pod` itself still works — you'd only hit
|
|
284
|
+
a problem if you separately use the primitives wire format or that test
|
|
285
|
+
helper. All three (plus `btoa`/`atob`) are present in Node ≥18, browsers,
|
|
286
|
+
and `workerd`, so this is unlikely to matter in practice — it's called out
|
|
287
|
+
here so the requirement list stays exactly as narrow as the code.
|
|
288
|
+
|
|
289
|
+
None of this requires `window`, `document`, `navigator`, `indexedDB`,
|
|
290
|
+
`fetch`, `WebAssembly`, `RTCPeerConnection`, or `SharedArrayBuffer` — those
|
|
291
|
+
are only probed, never required, by `detectCapabilities()`.
|
|
292
|
+
|
|
293
|
+
### The `TransportAdapter` and `DiscoveryAdapter` contracts
|
|
294
|
+
|
|
295
|
+
Pass `opts.transport` and `opts.discovery` to `boot()` to run `Pod` anywhere
|
|
296
|
+
these two interfaces can be implemented:
|
|
297
|
+
|
|
298
|
+
```ts
|
|
299
|
+
interface TransportAdapter {
|
|
300
|
+
readonly ready: boolean
|
|
301
|
+
open(): Promise<void>
|
|
302
|
+
close(): Promise<void>
|
|
303
|
+
send(msg: object): void // no-op before open(), never throws
|
|
304
|
+
onMessage(handler: (msg: object) => void): void
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
interface DiscoveryAdapter {
|
|
308
|
+
start(): Promise<void>
|
|
309
|
+
stop(opts?: { silent?: boolean }): Promise<void>
|
|
310
|
+
onPeerDiscovered(handler: (peer: { podId: string, kind?: string }) => void): void
|
|
311
|
+
onPeerLost(handler: (peer: { podId: string }) => void): void
|
|
312
|
+
onMessage(handler: (msg: object) => void): void // non-discovery messages pass through
|
|
313
|
+
}
|
|
314
|
+
```
|
|
315
|
+
|
|
316
|
+
Every `TransportAdapter` implementation in this package (and any you write)
|
|
317
|
+
is expected to satisfy the shared conformance suite in
|
|
318
|
+
`test/helpers/transport-conformance.mjs` — see
|
|
319
|
+
`test/transport-conformance.test.mjs` for how the three built-in adapters
|
|
320
|
+
are wired into it.
|
|
321
|
+
|
|
322
|
+
### Worked example: `EventEmitterTransport` + `NullDiscovery` in Node
|
|
323
|
+
|
|
324
|
+
This mirrors the composition a server-side `Pod` subclass would use to run
|
|
325
|
+
a pod in plain Node with no browser APIs at all — an in-process
|
|
326
|
+
`EventEmitterTransport` shared bus stands in for a real network transport,
|
|
327
|
+
and `NullDiscovery` skips the hello/ack handshake since there's nothing to
|
|
328
|
+
discover on a bus you fully control yourself:
|
|
329
|
+
|
|
330
|
+
```js
|
|
331
|
+
import { Pod } from '@johnhenry/browsermesh-pod'
|
|
332
|
+
import { EventEmitterTransport, NullTransport } from '@johnhenry/browsermesh-pod'
|
|
333
|
+
import { NullDiscovery } from '@johnhenry/browsermesh-pod'
|
|
334
|
+
|
|
335
|
+
// A shared in-process bus standing in for a real network (relay, WebSocket, …)
|
|
336
|
+
const bus = EventEmitterTransport.createBus()
|
|
337
|
+
|
|
338
|
+
class NodePod extends Pod {
|
|
339
|
+
_onMessage(msg) {
|
|
340
|
+
console.log(`[${this.podId}] received`, msg.payload)
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
const alpha = new NodePod()
|
|
345
|
+
const beta = new NodePod()
|
|
346
|
+
|
|
347
|
+
await alpha.boot({
|
|
348
|
+
transport: new EventEmitterTransport(bus),
|
|
349
|
+
discovery: new NullDiscovery(),
|
|
350
|
+
})
|
|
351
|
+
await beta.boot({
|
|
352
|
+
transport: new EventEmitterTransport(bus),
|
|
353
|
+
discovery: new NullDiscovery(),
|
|
354
|
+
})
|
|
355
|
+
|
|
356
|
+
// NullDiscovery doesn't run the hello/ack protocol, so peers aren't
|
|
357
|
+
// auto-discovered — address pods directly once you know their podId:
|
|
358
|
+
alpha.send(beta.podId, { text: 'hello from alpha' })
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
Swap `NullDiscovery` for a `TransportDiscovery` wired to the same
|
|
362
|
+
`EventEmitterTransport` if you want real hello/ack peer discovery over the
|
|
363
|
+
bus instead of addressing pods by a `podId` you already have out of band.
|
|
364
|
+
To actually leave the process — reaching a pod hosted in a separate Node
|
|
365
|
+
process, a V8 isolate, or a Firecracker microVM guest — swap the transport
|
|
366
|
+
for one that crosses a real network boundary (a `WebSocketTransport`
|
|
367
|
+
speaking to a relay/signaling server; see `docs/hosted-pods.md` at the
|
|
368
|
+
monorepo root for that design). Until such a transport lands, `Pod` running
|
|
369
|
+
server-side is confined to one process, same as `EventEmitterTransport`
|
|
370
|
+
always has been.
|
|
371
|
+
|
|
372
|
+
> [!WARNING]
|
|
373
|
+
> **`node:vm` and `worker_threads` are NOT security boundaries.** Node's own
|
|
374
|
+
> `node:vm` docs say so explicitly, and `worker_threads` share the host
|
|
375
|
+
> process's memory space and OS permissions. Use them to pack multiple
|
|
376
|
+
> *trusted* pods into one process to save memory — never to run a
|
|
377
|
+
> stranger's code. If you need to run code from an untrusted party, that
|
|
378
|
+
> belongs in a real isolation boundary: a V8 isolate (`workerd`/Cloudflare
|
|
379
|
+
> Workers + Durable Objects) or a Firecracker microVM. See
|
|
380
|
+
> `docs/hosted-pods.md`'s "isolate pod" and "microVM pod" lanes for the two
|
|
381
|
+
> supported designs.
|
|
382
|
+
|
|
383
|
+
## Pod host protocol
|
|
384
|
+
|
|
385
|
+
`src/host-protocol.mjs` is the plain-data half of the **hosted-pods control
|
|
386
|
+
surface** ([issue #185](https://github.com/johnhenry/browsermesh/issues/185)):
|
|
387
|
+
one lane-agnostic verb set that every way of driving a hosted pod — the
|
|
388
|
+
mesh service in `@johnhenry/browsermesh-apps`, `mesh://` routes, `meshctl`
|
|
389
|
+
tools, an external CLI, a supervisor — projects.
|
|
390
|
+
|
|
391
|
+
It lives *here*, not in `browsermesh-apps`, so the two places a hosted pod
|
|
392
|
+
actually runs (a Worker / Durable Object, a microVM host agent) can import
|
|
393
|
+
the verbs, the podspec validator and the wire shapes without pulling in the
|
|
394
|
+
app runtime. Zero dependencies, no browser-only globals, no `node:` imports.
|
|
395
|
+
|
|
396
|
+
### The verbs
|
|
397
|
+
|
|
398
|
+
| Verb | Payload | Returns | Notes |
|
|
399
|
+
| --- | --- | --- | --- |
|
|
400
|
+
| `spawn` | a **podspec** (below) | pod status | `EEXIST` if the name is live |
|
|
401
|
+
| `status` | `{name}` | pod status | `ENOENT` if unknown |
|
|
402
|
+
| `send` | `{name, to?, payload}` | driver-defined | delivers a message to the pod |
|
|
403
|
+
| `exec` | `{name, command, timeoutMs?}` | `{stdout, stderr, code}` | `ELANE` on isolate; on browser it means "evaluate script in the page", not a shell — see [Browser lane drivers](#browser-lane-drivers) |
|
|
404
|
+
| `snapshot` | `{name}` | pod status | `ELANE` on isolate/browser |
|
|
405
|
+
| `restore` | `{name}` | pod status | `ELANE` on isolate/browser |
|
|
406
|
+
| `drain` | `{name, cascade?}` | pod status | ends at `gone` |
|
|
407
|
+
| `list` | `{}` | pod status[] | every pod the host tracks |
|
|
408
|
+
|
|
409
|
+
`validateVerbRequest(verb, payload)` returns `{ok: true, value}` with the
|
|
410
|
+
payload normalized (`exec`'s `command` is always a `string[]`; `drain`'s
|
|
411
|
+
`cascade` is always a boolean) or `{ok: false, errors: string[]}`. A string
|
|
412
|
+
`command` becomes a *single-element* argv — it is deliberately not
|
|
413
|
+
shell-split; pass `['sh', '-c', '…']` when a shell is really wanted.
|
|
414
|
+
|
|
415
|
+
Which lane can do what is static, not a runtime surprise — `POD_LANE_VERBS`
|
|
416
|
+
and `laneSupports(lane, verb)` say so up front:
|
|
417
|
+
|
|
418
|
+
| Lane | `spawn` | `status` | `send` | `exec` | `snapshot` | `restore` | `drain` | `list` |
|
|
419
|
+
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
|
420
|
+
| `isolate` | ✓ | ✓ | ✓ | `ELANE` | `ELANE` | `ELANE` | ✓ | ✓ |
|
|
421
|
+
| `microvm` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
|
|
422
|
+
| `node` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
|
|
423
|
+
| `browser` | ✓ | ✓ | ✓ | ✓* | `ELANE` | `ELANE` | ✓ | ✓ |
|
|
424
|
+
|
|
425
|
+
\* lane-capable (a tab has a JS realm to evaluate in, even with no shell);
|
|
426
|
+
whether a given browser-lane *driver* implements it is separate — see
|
|
427
|
+
[Browser lane drivers](#browser-lane-drivers).
|
|
428
|
+
|
|
429
|
+
`POD_LANE`'s strings are identical to `RUNTIME_CLASS` in
|
|
430
|
+
`@johnhenry/browsermesh-apps`' `resources.mjs`, so a host's lane is also the
|
|
431
|
+
`runtime:<class>` capability the `ResourceScorer` matches on. They are
|
|
432
|
+
duplicated rather than imported on purpose (this package must stay
|
|
433
|
+
importable from a Worker); if one gains a lane, add it to both.
|
|
434
|
+
|
|
435
|
+
### The podspec
|
|
436
|
+
|
|
437
|
+
```js
|
|
438
|
+
import { validatePodSpec } from '@johnhenry/browsermesh-pod'
|
|
439
|
+
|
|
440
|
+
const { ok, value, errors } = validatePodSpec({
|
|
441
|
+
name: 'greeter', // [A-Za-z0-9][A-Za-z0-9._-]{0,63}
|
|
442
|
+
lane: 'isolate', // optional — defaulted from run.kind
|
|
443
|
+
run: { kind: 'skill', ref: 'greeter', entry: 'main.mjs', input: { seed: 1 } },
|
|
444
|
+
limits: { vcpus: 1, memMib: 128, timeoutMs: 30_000 },
|
|
445
|
+
caps: ['net', 'mesh'], // KERNEL_CAP strings
|
|
446
|
+
env: { LOG_LEVEL: 'info' },
|
|
447
|
+
budget: { credits: 10, currency: 'bmc' },
|
|
448
|
+
restart: { policy: 'on-failure', maxRestarts: 3, backoffMs: 500 },
|
|
449
|
+
labels: { team: 'core' },
|
|
450
|
+
links: { parent: 'greeter-supervisor', detachOnParentExit: false },
|
|
451
|
+
})
|
|
452
|
+
```
|
|
453
|
+
|
|
454
|
+
Only two defaults are ever applied: `lane` (`isolate` for a `skill`/`module`
|
|
455
|
+
run, `microvm` for `command`/`rootfs`) and `restart.policy` (`'never'`).
|
|
456
|
+
Optional sections that were absent stay absent, so a driver can tell "no
|
|
457
|
+
limits asked for" from "limits asked for, all defaults". **Unknown keys are
|
|
458
|
+
an error**, at every level — a mistyped `limits.memMB` that silently did
|
|
459
|
+
nothing would be a quota bug nobody notices until the bill.
|
|
460
|
+
|
|
461
|
+
`links` (issue #185 item 6, the supervisor) declares this pod's place in a
|
|
462
|
+
parent/child tree: `links.parent` names the pod that should drain this one
|
|
463
|
+
when *it* drains (cascade), `links.hostedBy` optionally records the pod
|
|
464
|
+
host for the same bookkeeping a `ResourceDescriptor.hostedBy` already does
|
|
465
|
+
at the resource layer, and `links.detachOnParentExit` (default `false`)
|
|
466
|
+
opts a child with `restart.policy: 'always'` out of being drained when its
|
|
467
|
+
parent exits — it keeps running and restarting on its own instead. None of
|
|
468
|
+
this is enforced by `validatePodSpec()` beyond shape (strings, booleans);
|
|
469
|
+
the cascade/restart behavior itself lives in `@johnhenry/browsermesh-apps`'
|
|
470
|
+
`pod-supervisor.mjs`.
|
|
471
|
+
|
|
472
|
+
### Lifecycle
|
|
473
|
+
|
|
474
|
+
`POD_LIFECYCLE` matches `docs/hosted-pods.md` §5.3 and adds a terminal
|
|
475
|
+
`gone`; `POD_LIFECYCLE_TRANSITIONS` is the frozen `from -> to[]` map and
|
|
476
|
+
`canTransition(from, to)` the predicate drivers enforce with:
|
|
477
|
+
|
|
478
|
+
```
|
|
479
|
+
cold → booting → registered ⇄ serving
|
|
480
|
+
registered → paused → snapshotted → restoring → registered
|
|
481
|
+
registered → draining → cold | gone
|
|
482
|
+
```
|
|
483
|
+
|
|
484
|
+
Every non-terminal state may also jump straight to `gone` — a host losing
|
|
485
|
+
its VMM or isolate is not a graceful drain but still has to be reportable.
|
|
486
|
+
|
|
487
|
+
### Wire messages
|
|
488
|
+
|
|
489
|
+
`createHostRequest(verb, payload, {requestId?})`,
|
|
490
|
+
`createHostResponse(requestId, {ok, result?, error?})` and
|
|
491
|
+
`createHostEvent(kind, data)` build the three JSON-safe envelopes
|
|
492
|
+
(`pod-host:request` / `pod-host:response` / `pod-host:event`). Event kinds
|
|
493
|
+
are `lifecycle`, `log` and `exit`. Errors travel as `{code, message}` with
|
|
494
|
+
`code` one of `POD_HOST_ERROR`: `EACCES`, `ENOENT`, `EEXIST`, `EINVAL`,
|
|
495
|
+
`ENOTSUP`, `ELANE`, `ETIMEDOUT`, `EBUSY`. `ELANE` means "this lane
|
|
496
|
+
structurally cannot"; `ENOTSUP` means "this driver did not implement an
|
|
497
|
+
otherwise lane-compatible verb".
|
|
498
|
+
|
|
499
|
+
### The `PodHostDriver` interface
|
|
500
|
+
|
|
501
|
+
A driver is **any object** with these members — a typedef, not a base class,
|
|
502
|
+
so a Worker, a Firecracker host agent and an in-memory fake can all be one
|
|
503
|
+
without inheriting anything:
|
|
504
|
+
|
|
505
|
+
```js
|
|
506
|
+
{
|
|
507
|
+
lane, // a POD_LANE value
|
|
508
|
+
capabilities(), // -> { verbs: string[] }
|
|
509
|
+
spawn(spec), status(name), send(name, msg),
|
|
510
|
+
exec(name, argv, opts), snapshot(name), restore(name),
|
|
511
|
+
drain(name, opts), list(), // all Promise-returning
|
|
512
|
+
onEvent(fn), // optional; returns unsubscribe
|
|
513
|
+
}
|
|
514
|
+
```
|
|
515
|
+
|
|
516
|
+
A verb the driver cannot serve must reject with a `PodHostDriverError`
|
|
517
|
+
carrying `ELANE` or `ENOTSUP`; `createUnsupportedDriverMethod(verb, lane)`
|
|
518
|
+
builds exactly such a method so a partial driver still has all eight.
|
|
519
|
+
|
|
520
|
+
`InMemoryPodHostDriver` is the complete reference driver: a `Map` of fake
|
|
521
|
+
pods running the real state machine, every verb implemented, an injectable
|
|
522
|
+
`exec` (default: echo the argv), and `onEvent()` fan-out. Tests, examples
|
|
523
|
+
and every later control surface use it when they need a host that behaves
|
|
524
|
+
correctly without a workerd process or a KVM box behind it.
|
|
525
|
+
|
|
526
|
+
```js
|
|
527
|
+
import { InMemoryPodHostDriver } from '@johnhenry/browsermesh-pod'
|
|
528
|
+
|
|
529
|
+
const driver = new InMemoryPodHostDriver({ lane: 'node' })
|
|
530
|
+
driver.onEvent((event) => console.log(event.kind, event.data))
|
|
531
|
+
|
|
532
|
+
await driver.spawn({ name: 'alpha', lane: 'node', run: { kind: 'command', ref: '/bin/echo' } })
|
|
533
|
+
await driver.exec('alpha', ['echo', 'hi']) // { stdout: 'echo hi', stderr: '', code: 0 }
|
|
534
|
+
await driver.snapshot('alpha') // -> paused -> snapshotted
|
|
535
|
+
await driver.restore('alpha') // -> restoring -> registered
|
|
536
|
+
await driver.drain('alpha') // -> draining -> gone, exit {reason: 'drained', restartable: false}
|
|
537
|
+
await driver.crash('alpha', { code: 1 }) // TEST-ONLY -> gone, exit {reason: 'crashed', restartable: true}
|
|
538
|
+
```
|
|
539
|
+
|
|
540
|
+
Every `EXIT` event's `data` matches `PodHostExitEventData`: `{ name, code?,
|
|
541
|
+
reason?: 'drained'|'crashed'|'host-lost'|'evicted', restartable }` — see
|
|
542
|
+
`host-protocol.mjs`'s own doc comment on `POD_HOST_EVENT_KIND`. A
|
|
543
|
+
supervisor (`@johnhenry/browsermesh-apps`' `pod-supervisor.mjs`) is the
|
|
544
|
+
first consumer that actually branches on `reason`/`restartable` rather than
|
|
545
|
+
just logging the event.
|
|
546
|
+
|
|
547
|
+
The gated, audited mesh service that speaks this protocol over a `PeerNode`
|
|
548
|
+
is `createPodHostService()` in `@johnhenry/browsermesh-apps` — see that
|
|
549
|
+
package's "Pod host service" README section.
|
|
550
|
+
|
|
551
|
+
### Browser lane drivers
|
|
552
|
+
|
|
553
|
+
The browser lane (`POD_LANE.BROWSER`) has three drivers, documented in full
|
|
554
|
+
with a diagram in `docs/hosted-pods.md` §8b. The one THIS package ships —
|
|
555
|
+
`createInPageDriver()` — needs nothing beyond what a page already has:
|
|
556
|
+
|
|
557
|
+
```js
|
|
558
|
+
import { createInPageDriver, bootHostedPod } from '@johnhenry/browsermesh-pod'
|
|
559
|
+
|
|
560
|
+
// On the pod page itself (podUrl), the whole bootstrap is:
|
|
561
|
+
await bootHostedPod() // reads its name from window.name / #name=…, boots a Pod,
|
|
562
|
+
// announces readiness over BroadcastChannel
|
|
563
|
+
|
|
564
|
+
// On the host tab:
|
|
565
|
+
const driver = createInPageDriver({
|
|
566
|
+
podUrl: 'https://example.com/pod.html',
|
|
567
|
+
spawnKind: 'iframe', // or 'window' | 'worker'
|
|
568
|
+
})
|
|
569
|
+
await driver.spawn({ name: 'worker-1', lane: 'browser', run: { kind: 'module', ref: 'pod' } })
|
|
570
|
+
await driver.send('worker-1', { payload: { hi: true } })
|
|
571
|
+
await driver.drain('worker-1')
|
|
572
|
+
```
|
|
573
|
+
|
|
574
|
+
It answers `spawn`/`status`/`send`/`drain`/`list`; `exec`/`snapshot`/
|
|
575
|
+
`restore` are `ENOTSUP` — a parent tab has no safe way to evaluate code in
|
|
576
|
+
a child it spawned, and no durable freeze/thaw of a page's JS heap exists
|
|
577
|
+
yet. The other two drivers trade that safety story for more setup:
|
|
578
|
+
|
|
579
|
+
| Driver | Where | `exec` |
|
|
580
|
+
| --- | --- | --- |
|
|
581
|
+
| In-page (above) | here | `ENOTSUP` |
|
|
582
|
+
| CDP (remote debugging protocol) | `spikes/browser-pod-host` | real `Runtime.evaluate`, gated like any exec |
|
|
583
|
+
| Extension (Manifest V3) | `spikes/browser-extension-host` | real `chrome.scripting.executeScript`, gated |
|
|
584
|
+
|
|
585
|
+
**Trust caveat:** a tab is not a privilege boundary against the page it
|
|
586
|
+
hosts. For a hosted pod whose code you do not trust, use the CDP driver
|
|
587
|
+
inside a Lane B microVM, not the in-page driver — see §8b's "Trust
|
|
588
|
+
caveat".
|
|
589
|
+
|
|
209
590
|
## InjectedPod
|
|
210
591
|
|
|
211
592
|
Lightweight subclass for Chrome extension injection or bookmarklet use. Adds page text extraction, structured data extraction, and a visual overlay indicator.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@johnhenry/browsermesh-pod",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"description": "Pod base class for browser execution contexts with Ed25519 identity, BroadcastChannel discovery, and peer messaging",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.mjs",
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
"@johnhenry/browsermesh-primitives": ">=0.2.0 <1.0.0"
|
|
39
39
|
},
|
|
40
40
|
"devDependencies": {
|
|
41
|
-
"@johnhenry/browsermesh-primitives": "^0.
|
|
41
|
+
"@johnhenry/browsermesh-primitives": "^0.3.0"
|
|
42
42
|
},
|
|
43
43
|
"engines": {
|
|
44
44
|
"node": ">=26.0.0"
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* browser-host-child.mjs — the pod-page side of the browser lane (issue
|
|
3
|
+
* #185 item 7, deliverable A).
|
|
4
|
+
*
|
|
5
|
+
* `browser-host-driver.mjs`'s `createInPageDriver()` spawns a child page or
|
|
6
|
+
* worker (an iframe, a `window.open()`ed window, or a dedicated `Worker`);
|
|
7
|
+
* this is the ~20-line bootstrap THAT CHILD runs. It is deliberately tiny
|
|
8
|
+
* and has no dependency on the driver module (a real pod page only needs
|
|
9
|
+
* this file, `pod.mjs`'s `Pod`, and its own bundler): boot a `Pod` with a
|
|
10
|
+
* `BroadcastChannelTransport` on the agreed discovery channel, then
|
|
11
|
+
* broadcast a `browser-host:ready` announcement so a driver listening on
|
|
12
|
+
* that channel can mark the pod `registered`.
|
|
13
|
+
*
|
|
14
|
+
* Carrying the pod's logical NAME (the one the orchestrator's podspec
|
|
15
|
+
* named it, as opposed to its generated `podId`) is the one piece of
|
|
16
|
+
* plumbing a plain `Pod` boot does not already do — `createHello()` has no
|
|
17
|
+
* `name` field (see `messages.mjs`), and threading one through there would
|
|
18
|
+
* touch the lane-agnostic wire protocol for a browser-lane-only concern.
|
|
19
|
+
* The LEAST invasive option, used here: read `name` the same way a real
|
|
20
|
+
* browsing context already carries it for free —
|
|
21
|
+
*
|
|
22
|
+
* - iframe: `iframe.name = spec.name` (an HTML attribute every iframe
|
|
23
|
+
* already has) → inside the frame, `window.name === spec.name`.
|
|
24
|
+
* - window: `window.open(url, spec.name)` — the second argument IS the
|
|
25
|
+
* new window's `name` → `window.name === spec.name` there too.
|
|
26
|
+
* - worker: `new Worker(url, { name: spec.name })` — a dedicated
|
|
27
|
+
* worker's global scope exposes that same option back as `self.name`.
|
|
28
|
+
*
|
|
29
|
+
* So `g.name` is the primary source in all three spawn kinds, with the
|
|
30
|
+
* `#name=…` URL-hash convention the driver also writes into `podUrl` kept
|
|
31
|
+
* as a fallback (useful for a page opened by hand, or a kind this module
|
|
32
|
+
* does not special-case). Once booted, readiness is announced over the
|
|
33
|
+
* pod's own public `broadcast()` — a plain `pod:message` to `'*'` with a
|
|
34
|
+
* `{kind: 'browser-host:ready', name, podId}` payload — rather than a new
|
|
35
|
+
* wire message type, so neither `messages.mjs` nor `pod.mjs` needed to
|
|
36
|
+
* change for this lane to exist.
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
import { Pod } from './pod.mjs'
|
|
40
|
+
|
|
41
|
+
/** The discovery-channel name `pod.mjs` itself defaults to, duplicated here
|
|
42
|
+
* (it is not exported) so a child booted with no explicit `channel` still
|
|
43
|
+
* lands on the same BroadcastChannel a same-origin driver listens on. */
|
|
44
|
+
export const DEFAULT_DISCOVERY_CHANNEL = 'pod-discovery'
|
|
45
|
+
|
|
46
|
+
/** The `payload.kind` a driver watches for on the discovery channel. */
|
|
47
|
+
export const BROWSER_HOST_READY = 'browser-host:ready'
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Read the pod's logical name off the global this code is running in.
|
|
51
|
+
* @param {object} g
|
|
52
|
+
* @returns {string|null}
|
|
53
|
+
*/
|
|
54
|
+
export function readPodName(g) {
|
|
55
|
+
if (g && typeof g.name === 'string' && g.name) return g.name
|
|
56
|
+
const href = (g?.location && (g.location.href || g.location.hash)) || ''
|
|
57
|
+
const match = /[#?&]name=([^&]*)/.exec(href)
|
|
58
|
+
return match ? decodeURIComponent(match[1]) : null
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Boot a `Pod` inside a page or worker a browser-lane `PodHostDriver`
|
|
63
|
+
* spawned, and announce readiness on the discovery channel.
|
|
64
|
+
*
|
|
65
|
+
* @param {object} [opts]
|
|
66
|
+
* @param {object} [opts.globalThis=globalThis] - Override for testing (a
|
|
67
|
+
* fake iframe/window/worker global); the real call site never passes
|
|
68
|
+
* this.
|
|
69
|
+
* @param {string} [opts.channel] - BroadcastChannel name; must match the
|
|
70
|
+
* driver's `channel` option. Defaults to `DEFAULT_DISCOVERY_CHANNEL`,
|
|
71
|
+
* the same default `Pod#boot()` itself uses.
|
|
72
|
+
* @param {string} [opts.name] - Override the name `readPodName()` would
|
|
73
|
+
* otherwise infer. Mostly for tests; real pages should let it be read
|
|
74
|
+
* from `g.name`/the URL.
|
|
75
|
+
* @param {number} [opts.handshakeTimeout] - Forwarded to `Pod#boot()`.
|
|
76
|
+
* @param {number} [opts.discoveryTimeout] - Forwarded to `Pod#boot()`.
|
|
77
|
+
* @param {typeof Pod} [opts.PodClass=Pod] - Swap in a `Pod` subclass (e.g.
|
|
78
|
+
* `InjectedPod`) that boots the same way.
|
|
79
|
+
* @returns {Promise<{pod: Pod, name: string|null}>}
|
|
80
|
+
*/
|
|
81
|
+
export async function bootHostedPod({
|
|
82
|
+
globalThis: g = globalThis,
|
|
83
|
+
channel = DEFAULT_DISCOVERY_CHANNEL,
|
|
84
|
+
name,
|
|
85
|
+
handshakeTimeout,
|
|
86
|
+
discoveryTimeout,
|
|
87
|
+
PodClass = Pod,
|
|
88
|
+
} = {}) {
|
|
89
|
+
const resolvedName = name !== undefined ? name : readPodName(g)
|
|
90
|
+
const pod = new PodClass()
|
|
91
|
+
await pod.boot({
|
|
92
|
+
globalThis: g,
|
|
93
|
+
discoveryChannel: channel,
|
|
94
|
+
...(handshakeTimeout === undefined ? {} : { handshakeTimeout }),
|
|
95
|
+
...(discoveryTimeout === undefined ? {} : { discoveryTimeout }),
|
|
96
|
+
})
|
|
97
|
+
// A plain broadcast through the Pod's own public API -- no new wire
|
|
98
|
+
// message type. A driver that is not listening (or is listening on a
|
|
99
|
+
// different channel) simply never sees this; it is not a request that
|
|
100
|
+
// needs an answer.
|
|
101
|
+
try {
|
|
102
|
+
pod.broadcast({ kind: BROWSER_HOST_READY, name: resolvedName, podId: pod.podId })
|
|
103
|
+
} catch {
|
|
104
|
+
// broadcast() throws if the transport never came up (e.g. no
|
|
105
|
+
// BroadcastChannel in this global at all) -- the pod is still booted
|
|
106
|
+
// and usable locally, it is just undiscoverable by a driver.
|
|
107
|
+
}
|
|
108
|
+
return { pod, name: resolvedName }
|
|
109
|
+
}
|