// The World's machine pool (architecture, "Other wires: … machines"): what runs a vendor's customer's image when the // vendor is one that runs images (Fly's Machines). It is a platform provider enrolled through the kernel's door // `POST /_twin/machine-pool`, recorded in the pack's own tree; a handler reaches it as `ctx.machines`. `docker` runs // each machine as a local container with its internal ports published on loopback; `none` runs nothing; `fake` // records what it was asked (capability verification). Nothing here runs at module scope, and `node:child_process` // is reached only when a compute pool is asked to act. import { refuseReadOnlyWrite } from './request-scope.ts'; import { nodeBuiltin } from './serve-http.ts'; import { refuseRequiredMachineTransport } from '../required-credential-transport.cjs'; export type MachineSpec = { name: string; image: string; env?: Record; ports?: number[]; command?: string[]; checks?: Array<{ port: number; type: 'http' | 'tcp'; path?: string }>; resetOnStop?: boolean; mounts?: Array<{ name: string; path: string }>; signal?: AbortSignal; startTimeoutMs?: number }; export type MachineRun = { ports: Array<{ internal: number; host: number; url?: string }> }; export type MachineStatus = { state: 'started' | 'paused' | 'stopped' | 'exited' | 'failed'; exitCode?: number; reason?: string }; export type MachineFileStat = { type: 'file' | 'directory'; size: number; mode: number; mtime: string }; export type MachineFiles = { read(path: string): Promise; write(path: string, bytes: Uint8Array): Promise; list(path: string): Promise>; mkdir(path: string): Promise; remove(path: string): Promise; stat(path: string): Promise; }; /** A process started in a machine: its pid, and what it writes and how it ends, as they happen. */ export type MachineProcess = { pid: number; events: AsyncIterable<{ stdout?: string } | { stderr?: string } | { exit: number }> }; export type ExecSpec = { args: string[]; env?: Record; cwd?: string }; export type MachineHttpReply = { port: number; method: string; path: string; requestText?: string; status: number; headers?: Record; body?: string }; export type MachinePool = { readonly kind: 'docker' | 'none' | 'fake'; /** Optional capability admission, before vendor resource creation; starts no process. */ admitRun?(spec: MachineSpec): Promise; /** runs the image; a failure (no container runtime, an image that will not start) rejects with the runtime's message */ run(spec: MachineSpec): Promise; /** starts a process in a running machine; a machine the pool does not run rejects */ exec(name: string, spec: ExecSpec): Promise; request(name: string, port: number, request: Request): Promise; /** Undefined means the metadata-only/fake backing has no process lifecycle to observe. */ status(name: string): Promise; ports(name: string): Promise; files(name: string): Promise; pause(name: string): Promise; resume(name: string): Promise; stop(name: string): Promise; remove(name: string): Promise; /** the fake pool's record of what it was asked */ readonly asked?: Array<{ act: 'run' | 'exec' | 'request' | 'pause' | 'resume' | 'stop' | 'remove'; name: string; spec?: MachineSpec; exec?: ExecSpec; port?: number; path?: string; requestText?: string }>; }; /** A declared compute capability gap, distinct from a failed admitted guest. */ export function isMachineCapabilityGap(error: unknown): boolean { return typeof error === 'object' && error !== null && 'code' in error && error.code === 'WORLD_MACHINE_CAPABILITY_GAP'; } export const MACHINE_POOL = '_machine_pool'; export const POOL_KINDS = ['docker', 'none', 'fake'] as const; /** A container's name for a machine: the World's prefix, the World's own mark (a machine id repeats across Worlds and * branches, which mint alike), then the vendor's machine name made safe for docker. */ const containerName = (world: string, name: string): string => `volter-world-machine-${world}-${name.replace(/[^A-Za-z0-9_.-]/g, '-')}`; // an image's pull is the slow step: a run may take two minutes before the pool gives up; anything else, thirty seconds const RUN_TIMEOUT_MS = 120_000; const STEP_TIMEOUT_MS = 30_000; function dockerPool(world: string): MachinePool { // asynchronous, so a pull never holds the World's other requests (or a socket's heartbeats) behind it const docker = (args: string[], timeout = STEP_TIMEOUT_MS): Promise => new Promise((resolve, reject) => { const { execFile } = nodeBuiltin('node:child_process'); execFile('docker', args, { encoding: 'utf8', timeout }, (error, stdout, stderr) => (error ? reject(new Error(String(stderr || error.message).trim())) : resolve(String(stdout).trim()))); }); return { kind: 'docker', async admitRun() { refuseRequiredMachineTransport(process.env, 'Docker machine application transport'); }, async status(name) { const state = JSON.parse(await docker(['inspect', '--format', '{{json .State}}', containerName(world, name)])); return state.Running ? { state: 'started' } : { state: 'exited', exitCode: state.ExitCode, ...(state.Error ? { reason: state.Error } : {}) }; }, async ports() { throw new Error('port discovery is unavailable'); }, async files() { throw new Error('file access is unavailable'); }, async run(spec) { refuseRequiredMachineTransport(process.env, 'Docker machine application transport'); const name = containerName(world, spec.name); await docker(['rm', '-f', name]).catch(() => undefined); const env = Object.entries(spec.env ?? {}).flatMap(([k, v]) => ['-e', `${k}=${v}`]); const ports = (spec.ports ?? []).flatMap((p) => ['-p', `127.0.0.1::${p}`]); await docker(['run', '-d', '--name', name, ...env, ...ports, spec.image, ...(spec.command ?? [])], RUN_TIMEOUT_MS); const published: MachineRun['ports'] = []; for (const internal of spec.ports ?? []) { const line = (await docker(['port', name, String(internal)])).split('\n')[0] ?? ''; published.push({ internal, host: Number(line.split(':').at(-1)) }); } return { ports: published }; }, async exec(name, spec) { refuseRequiredMachineTransport(process.env, 'Docker machine exec transport'); const { spawn } = nodeBuiltin('node:child_process'); const env = Object.entries(spec.env ?? {}).flatMap(([k, v]) => ['-e', `${k}=${v}`]); // the shell names its own pid first, then becomes the process: its pid is the process's const child = spawn('docker', ['exec', '-i', ...env, ...(spec.cwd ? ['-w', spec.cwd] : []), containerName(world, name), 'sh', '-c', 'echo "@pid $$"; exec "$@"', 'sh', ...spec.args], { stdio: ['ignore', 'pipe', 'pipe'] }); const queue: Array<{ stdout?: string } | { stderr?: string } | { exit: number }> = []; let wake: (() => void) | undefined; let done = false; let pid: number | undefined; let head = ''; let stderr = ''; let settle: { resolve: (n: number) => void; reject: (e: Error) => void } | undefined; const pidKnown = new Promise((resolve, reject) => { settle = { resolve, reject }; child.on('error', reject); }); const push = (e: (typeof queue)[number]): void => { queue.push(e); wake?.(); }; child.stdout!.setEncoding('utf8').on('data', (chunk: string) => { if (pid === undefined) { // the pid line may arrive split across chunks: nothing is output until its newline is read head += chunk; const nl = head.indexOf('\n'); if (nl < 0) return; const m = /^@pid (\d+)$/.exec(head.slice(0, nl)); if (!m) { push({ stdout: head }); head = ''; return; } pid = Number(m[1]); settle?.resolve(pid); chunk = head.slice(nl + 1); head = ''; } if (chunk) push({ stdout: chunk }); }); child.stderr!.setEncoding('utf8').on('data', (chunk: string) => { if (pid === undefined) stderr += chunk; push({ stderr: chunk }); }); child.on('close', (code, signal) => { // a machine the pool does not run (docker exec fails before the shell starts) rejects, with docker's words if (pid === undefined) settle?.reject(new Error(stderr.trim() || `the process did not start (exit ${code ?? signal})`)); // a process ended by a signal exits as a shell reports it: 128 and the signal's number const signals: Record = { SIGHUP: 1, SIGINT: 2, SIGQUIT: 3, SIGKILL: 9, SIGTERM: 15 }; push({ exit: code ?? (signal ? 128 + (signals[signal] ?? 0) : 0) }); done = true; wake?.(); }); const events: MachineProcess['events'] = { async *[Symbol.asyncIterator]() { for (;;) { while (queue.length) { const e = queue.shift()!; yield e; if ('exit' in e) return; } if (done) return; await new Promise((r) => { wake = r; }); } }, }; let timer: ReturnType | undefined; const timeout = new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('the process did not start')), STEP_TIMEOUT_MS); }); try { return { pid: await Promise.race([pidKnown, timeout]), events }; } finally { clearTimeout(timer); } }, async request(name, port, request) { if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('invalid machine port'); const line = (await docker(['port', containerName(world, name), String(port)])).split('\n')[0] ?? ''; const host = Number(line.split(':').at(-1)); if (!Number.isInteger(host) || host < 1 || host > 65535 || !line.startsWith('127.0.0.1:')) throw new Error('the machine port is not published on loopback'); const source = new URL(request.url); const headers = new Headers(request.headers); for (const key of ['host', 'connection', 'content-length', 'transfer-encoding']) headers.delete(key); const body = ['GET', 'HEAD'].includes(request.method) ? undefined : await request.clone().arrayBuffer(); return fetch(`http://127.0.0.1:${host}${source.pathname}${source.search}`, { method: request.method, headers, body, redirect: 'manual', signal: request.signal }); }, async pause(name) { await docker(['pause', containerName(world, name)]); }, async resume(name) { refuseRequiredMachineTransport(process.env, 'Docker machine resume transport'); await docker(['unpause', containerName(world, name)]); }, async stop(name) { await docker(['stop', containerName(world, name)]).catch(() => undefined); }, async remove(name) { await docker(['rm', '-f', containerName(world, name)]).catch(() => undefined); }, }; } /** The pool of a kind, for a World (`world`: the mark its containers carry). */ export function machinePool(kind: MachinePool['kind'], world = 'world', httpReplies: readonly MachineHttpReply[] = []): MachinePool { if (!POOL_KINDS.includes(kind)) throw new Error(`kind must be one of ${POOL_KINDS.join(', ')}`); if (kind === 'docker') return dockerPool(world); if (kind === 'fake') { const asked: NonNullable = []; const running = new Map(); return { kind, asked, async status() { return undefined; }, async ports(name) { return running.get(name)?.ports ?? []; }, async files() { throw new Error('the fake pool has no filesystem'); }, async run(spec) { running.set(spec.name, { ports: spec.ports ?? [], paused: false }); asked.push({ act: 'run', name: spec.name, spec }); return { ports: (spec.ports ?? []).map((internal) => ({ internal, host: 40_000 + internal })) }; }, async exec(name, spec) { if (!running.has(name) || running.get(name)!.paused) throw new Error('the fake machine is not running'); asked.push({ act: 'exec', name, exec: spec }); // a fake process: its pid the count of processes asked, and it ends at once const pid = asked.filter((a) => a.act === 'exec').length + 100; return { pid, events: (async function* () { yield { exit: 0 }; })() }; }, async request(name, port, request) { const machine = running.get(name); if (!machine || machine.paused || !machine.ports.includes(port)) throw new Error('the fake machine port is not running'); const url = new URL(request.url), path = url.pathname + url.search; const requestText = ['GET', 'HEAD'].includes(request.method) ? '' : await request.clone().text(); asked.push({ act: 'request', name, port, path, requestText }); const reply = httpReplies.find((r) => r.port === port && r.method === request.method && r.path === path && (r.requestText === undefined || r.requestText === requestText)); if (!reply) throw new Error('no fake HTTP reply matches'); return new Response(reply.body ?? null, { status: reply.status, headers: reply.headers }); }, async pause(name) { if (!running.has(name)) throw new Error('no fake machine'); running.get(name)!.paused = true; asked.push({ act: 'pause', name }); }, async resume(name) { if (!running.has(name)) throw new Error('no fake machine'); running.get(name)!.paused = false; asked.push({ act: 'resume', name }); }, async stop(name) { running.delete(name); asked.push({ act: 'stop', name }); }, async remove(name) { running.delete(name); asked.push({ act: 'remove', name }); }, }; } return { kind: 'none', async run() { return { ports: [] }; }, async status() { return undefined; }, async ports() { throw new Error('no guest ports'); }, async files() { throw new Error('no guest files'); }, async exec() { throw new Error('no machine runs in this World: its machine pool is none'); }, async request() { throw new Error('no machine runs in this World: its machine pool is none'); }, async pause() {}, async resume() {}, async stop() { /* nothing runs */ }, async remove() { /* nothing runs */ }, }; } /** A vendor's pool in a World, one per World and kind for the life of the process (a fake pool keeps what it was asked). */ const pools = new Map(); export function poolFor(service: string, root: string | undefined, kind: MachinePool['kind'], httpReplies: readonly MachineHttpReply[] = []): MachinePool { const key = `${service}\0${root ?? ''}\0${kind}`; let pool = pools.get(key); if (!pool) { // the World's mark: a short digest of the vendor and the World's tree, so two Worlds' machines never share a name let h = 0; for (const ch of `${service}:${root ?? ''}`) h = (Math.imul(h, 31) + ch.charCodeAt(0)) >>> 0; pool = machinePool(kind, h.toString(16).padStart(8, '0'), httpReplies); pools.set(key, pool); } return pool; } /** Re-enrolling a verification pool starts a fresh fake execution record. */ export function resetFakePool(service: string, root: string | undefined): void { pools.delete(`${service}\0${root ?? ''}\0fake`); } /** Every machine mutation shares the tree's refusal seam. HTTP/RPC reads must be explicitly * classified by the pack; a computed operation may execute arbitrary guest code. */ export function guardedMachinePool(pool: MachinePool, service: string, safeRead: boolean): MachinePool { const guard = (): void => refuseReadOnlyWrite(service); return { kind: pool.kind, asked: pool.asked, ...(pool.admitRun ? { admitRun: (spec: MachineSpec) => { guard(); return pool.admitRun!(spec); } } : {}), run: (spec) => { guard(); return pool.run(spec); }, exec: (name, spec) => { guard(); return pool.exec(name, spec); }, request: (name, port, request) => { if (!safeRead) guard(); return pool.request(name, port, request); }, status: (name) => pool.status(name), ports: (name) => pool.ports(name), files: async (name) => { const files = await pool.files(name); return { ...files, write: (path, bytes) => { guard(); return files.write(path, bytes); }, mkdir: (path) => { guard(); return files.mkdir(path); }, remove: (path) => { guard(); return files.remove(path); } }; }, pause: (name) => { guard(); return pool.pause(name); }, resume: (name) => { guard(); return pool.resume(name); }, stop: (name) => { guard(); return pool.stop(name); }, remove: (name) => { guard(); return pool.remove(name); }, }; }