Files
captoys/toybox/test/vat.test.js
T
dckcandClaude Opus 5.5 88739d9495 capsite/toybox: vats with code installed at runtime, on workerd
Each vat is a Durable Object that stores code by hash and runs it as a
facet through the Worker Loader: an empty env, no fetch, storage that
carries over upgrades. Two sockets with no configured address: whoever
starts workerd hands them in (systemd socket activation), so the admin
socket is the authority to install code.

Tests run a real workerd: install, upgrade, isolation between vats, no
fetch, the public port can't install, and code and state survive a crash.
They spawn the package binary rather than the .bin shim, which forks
workerd, so killing the shim orphaned it and the test run never ended.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 21:44:29 -05:00

120 lines
4.2 KiB
JavaScript

/** @file toybox end to end: a real workerd, an admin socket, a public port. */
import { spawn } from "node:child_process";
import { mkdir, mkdtemp, readFile, rm } from "node:fs/promises";
import { request } from "node:http";
import { createServer } from "node:net";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, before, test } from "node:test";
import assert from "node:assert/strict";
const here = new URL("..", import.meta.url).pathname;
// the package binary, not the .bin shim: the shim forks it, so a kill would orphan workerd
const workerd = join(here, "node_modules/workerd/bin/workerd");
const app = (name) => readFile(join(here, "apps", name), "utf8");
const freePort = () =>
new Promise((resolve) => {
const s = createServer().listen(0, "127.0.0.1", () => {
const { port } = s.address();
s.close(() => resolve(port));
});
});
/** @param {string} socketPath the admin socket; holding it is the authority to install */
const makeAdmin = (socketPath) => ({
install: (vat, src) =>
new Promise((resolve, reject) => {
const req = request({ socketPath, path: `/${vat}`, method: "PUT", agent: false }, (res) => {
let body = "";
res.on("data", (c) => (body += c));
res.on("end", () => resolve(body.trim()));
});
req.on("error", reject);
req.end(src);
}),
});
/** @param {string} base the public origin */
const makePublic = (base) => ({
get: async (vat) => (await fetch(`${base}/${vat}`)).text(),
put: async (vat, src) => (await fetch(`${base}/${vat}`, { method: "PUT", body: src })).status,
});
/** Run workerd on `dir`'s state until `stop()`; resolves once the port answers. */
const startWorkerd = async (dir, port) => {
await rm(join(dir, "admin.sock"), { force: true }); // left behind by a crash; bind() would fail
const child = spawn(
workerd,
["serve", "--experimental", join(here, "config.capnp"),
"-s", `http=127.0.0.1:${port}`, "-s", `admin=unix:${join(dir, "admin.sock")}`,
"-d", `state=${join(dir, "state")}`],
{ stdio: ["ignore", "ignore", "pipe"] },
);
let log = "";
child.stderr.on("data", (c) => (log += c));
const exited = new Promise((resolve) => child.on("exit", resolve));
for (let i = 0; i < 100; i++) {
try {
await fetch(`http://127.0.0.1:${port}/`);
// SIGKILL: a crash is the harder durability test
return { stop: () => (child.kill("SIGKILL"), exited) };
} catch {
await new Promise((r) => setTimeout(r, 50));
}
}
child.kill("SIGKILL");
throw new Error(`workerd did not start: ${log}`);
};
let dir, port, server, admin, pub;
before(async () => {
dir = await mkdtemp(join(tmpdir(), "toybox-"));
await mkdir(join(dir, "state"));
port = await freePort();
server = await startWorkerd(dir, port);
admin = makeAdmin(join(dir, "admin.sock"));
pub = makePublic(`http://127.0.0.1:${port}`);
});
after(async () => {
await server?.stop();
await rm(dir, { recursive: true, force: true });
});
test("a vat with no code is 404", async () => {
assert.equal(await pub.get("nobody"), "no code installed\n");
});
test("install, run, upgrade: the app's state carries over", async () => {
assert.match(await admin.install("alice", await app("counter-v1.js")), /^[0-9a-f]{64}$/);
assert.equal(await pub.get("alice"), "v1 count 1\n");
assert.equal(await pub.get("alice"), "v1 count 2\n");
await admin.install("alice", await app("counter-v2.js"));
assert.equal(await pub.get("alice"), "v2 count 3\n");
});
test("vats don't share state", async () => {
await admin.install("carol", await app("counter-v1.js"));
assert.equal(await pub.get("carol"), "v1 count 1\n");
});
test("an app gets no fetch", async () => {
await admin.install("bob", await app("try-fetch.js"));
assert.match(await pub.get("bob"), /^fetch refused: This worker is not permitted to access the internet/);
});
test("the public port can't install code", async () => {
assert.equal(await pub.put("mallory", "export class App {}"), 404);
assert.equal(await pub.get("mallory"), "no code installed\n");
});
test("code and state survive a restart", async () => {
await admin.install("dave", await app("counter-v1.js"));
assert.equal(await pub.get("dave"), "v1 count 1\n");
await server.stop();
server = await startWorkerd(dir, port);
assert.equal(await pub.get("dave"), "v1 count 2\n");
});