js: start the inlined Node workers from data: URLs (#143)

This commit is contained in:
pi0x
2026-12-02 17:51:17 +09:00
committed by GitHub
parent 8580d4e79a
commit bdcc90c51f
6 changed files with 67 additions and 25 deletions

View File

@@ -733,9 +733,12 @@ parts that are easy to get wrong.
- Packaging: from source, `js/node/worker.ts` starts
`new URL("./worker-entry.ts", import.meta.url)`. `pnpm build` bundles
each entry with rolldown, and the `unkernel:inline-worker` plugin
replaces that expression (it must occur once) with the code as a string
(`new Worker(code, { eval: true })`), so the dist has no worker file and
needs nothing from a downstream bundler. In browsers `js/web/worker.ts`
replaces that expression (it must occur once) with a
`data:text/javascript` URL of the code, so the dist has no worker file and
needs nothing from a downstream bundler. Not `new Worker(code, { eval:
true })`: that runs the code as an ES module only when Node detects its
syntax, which `--no-experimental-detect-module` (inherited by workers)
turns off. In browsers `js/web/worker.ts`
uses `new Worker(new URL("./web-worker-entry.ts", import.meta.url), {
type: "module" })`, which Vite bundles when the page builds from source
(`worker.format: "es"`); for the dist the plugin replaces it with

View File

@@ -60,10 +60,10 @@ const VK_WASM = process.env.UNKERNEL_VK || "vendor/build/vk/kwvk-naga.wasm";
* Worker entries and the module that starts each one with
* `new URL("./<entry>", import.meta.url)`. The build bundles the entry
* into a standalone chunk and replaces that expression with `wrap` of the
* chunk's code as a string literal: on Node the string itself
* (new Worker(code, { eval: true })), in browsers a Blob URL made from it
* (js/web/worker.ts). `entries` are the dist entries that must carry it;
* every other entry must not.
* chunk's code as a string literal: on Node a data: URL made from it
* (nodeWorkerUrl), in browsers a Blob URL made from it (js/web/worker.ts).
* `entries` are the dist entries that must carry it; every other entry
* must not.
*/
interface WorkerSpec {
name: string;
@@ -75,10 +75,27 @@ interface WorkerSpec {
/** Workers this worker starts itself: inlined into its own bundle first. */
nested?: string[];
}
/**
* A Node worker's code as a `data:text/javascript` URL, which Node always
* loads as an ES module. `new Worker(code, { eval: true })` runs the code
* as an ES module only when Node detects its module syntax, which
* `--no-experimental-detect-module` (inherited by workers) turns off.
* The bundle imports only Node built-ins, which resolve from a data: URL.
*
* The URL is a literal made at build time, escaped only where the URL
* parser would change the code (it removes tabs and newlines, and `?` and
* `#` end the path) and at `%` (Node percent-decodes the body), so a spawn
* only parses it. With encodeURIComponent at run time the URL was 40%
* longer than the code instead of 3%, and the kernel worker's start took
* about 5 ms and 0.4 MiB of its heap more.
*/
const DATA_URL = "data:text/javascript,";
const nodeWorkerUrl = (s: string) =>
`new URL(${JSON.stringify(DATA_URL + (JSON.parse(s) as string).replace(/[%#?\t\n\r]/g, (c) => `%${c.charCodeAt(0).toString(16).padStart(2, "0").toUpperCase()}`))})`;
const WORKERS: WorkerSpec[] = [
{ name: "cpu", starter: "js/node/cpu.ts", entry: "js/node/cpu-entry.ts", platform: "node", wrap: (s: string) => s, entries: ["node.mjs", "cli.mjs"] },
{ name: "node", starter: "js/node/worker.ts", entry: "js/node/worker-entry.ts", platform: "node", wrap: (s: string) => s, entries: ["node.mjs", "cli.mjs"], nested: ["cpu"] },
{ name: "wasi", starter: "js/node/wasi.ts", entry: "js/node/wasi-entry.ts", platform: "node", wrap: (s: string) => s, entries: ["node.mjs", "cli.mjs"] },
{ name: "cpu", starter: "js/node/cpu.ts", entry: "js/node/cpu-entry.ts", platform: "node", wrap: nodeWorkerUrl, entries: ["node.mjs", "cli.mjs"] },
{ name: "node", starter: "js/node/worker.ts", entry: "js/node/worker-entry.ts", platform: "node", wrap: nodeWorkerUrl, entries: ["node.mjs", "cli.mjs"], nested: ["cpu"] },
{ name: "wasi", starter: "js/node/wasi.ts", entry: "js/node/wasi-entry.ts", platform: "node", wrap: nodeWorkerUrl, entries: ["node.mjs", "cli.mjs"] },
{ name: "webwasi", starter: "js/web/wasi.ts", entry: "js/web/web-wasi-entry.ts", platform: "browser", wrap: (s: string) => `inlineWasiUrl(${s})`, entries: ["web.mjs"] },
{ name: "webcpu", starter: "js/web/cpu.ts", entry: "js/web/web-cpu-entry.ts", platform: "browser", wrap: (s: string) => `inlineCpuUrl(${s})`, entries: ["web.mjs"] },
{ name: "web", starter: "js/web/worker.ts", entry: "js/web/web-worker-entry.ts", platform: "browser", wrap: (s: string) => `inlineWorkerUrl(${s})`, entries: ["web.mjs"], nested: ["webcpu"] },
@@ -105,8 +122,9 @@ async function loadRolldown(pkgDir: string): Promise<Rolldown> {
/** `code` without the string literals that hold an inlined worker. */
function withoutWorkerStrings(code: string): string {
for (let at = code.indexOf(WORKER_MARK); at >= 0; at = code.indexOf(WORKER_MARK)) {
const start = at - 1, q = code[start]!;
if (q !== '"' && q !== "'" && q !== "`") throw new Error("an inlined worker is not at the start of a string literal");
const lead = code.startsWith(DATA_URL, at - DATA_URL.length) ? DATA_URL.length : 0;
const start = at - lead - 1, q = code[start]!;
if (q !== '"' && q !== "'" && q !== "`") throw new Error("an inlined worker is not at the start of a string literal (or of a data: URL)");
let end = at;
while (end < code.length && code[end] !== q) end += code[end] === "\\" ? 2 : 1;
code = code.slice(0, start) + code.slice(end + 1);

View File

@@ -8,16 +8,15 @@
//
// From source, Node starts the worker from cpu-entry.ts itself. `pnpm
// build` (build.config.ts, WORKERS) replaces the URL below (it must appear
// exactly once in this file) with the bundled entry as a string literal,
// in the dist entries and inside the inlined kernel worker, which starts
// the CPUs in worker mode.
// exactly once in this file) with a data: URL of the bundled entry, in
// the dist entries and inside the inlined kernel worker, which starts the
// CPUs in worker mode.
import { Worker } from "node:worker_threads";
import type { CpuEndpoint, CpuInit, CpuMessage } from "../core/cpu.ts";
export function spawnNodeCpu(init: CpuInit): CpuEndpoint {
const entry: URL | string = new URL("./cpu-entry.ts", import.meta.url);
const w = typeof entry === "string" ? new Worker(entry, { eval: true }) : new Worker(entry);
const w = new Worker(new URL("./cpu-entry.ts", import.meta.url));
// The CPU never keeps the process alive: CPU 0's exit ends the session.
w.unref();
w.postMessage(init);

View File

@@ -8,7 +8,7 @@
//
// From source, Node starts the worker from wasi-entry.ts itself. `pnpm
// build` (build.config.ts, WORKERS) replaces the URL below (it must appear
// exactly once in this file) with the bundled entry as a string literal.
// exactly once in this file) with a data: URL of the bundled entry.
import { Worker } from "node:worker_threads";
import type { Vsock } from "../core/vsock.ts";
@@ -16,9 +16,7 @@ import { serveWasiProgramsWith, type WasiExecOptions, type WasiExecServer } from
import type { WasiFromProgram, WasiProgramEndpoint } from "../core/wasi-program.ts";
export function spawnNodeWasi(): WasiProgramEndpoint {
const entry: URL | string = new URL("./wasi-entry.ts", import.meta.url);
const opts = { name: "unkernel-wasi" };
const w = typeof entry === "string" ? new Worker(entry, { ...opts, eval: true }) : new Worker(entry, opts);
const w = new Worker(new URL("./wasi-entry.ts", import.meta.url), { name: "unkernel-wasi" });
// A program never keeps the process alive: it belongs to the machine, whose end ends it.
w.unref();
return {

View File

@@ -6,15 +6,15 @@
// From source, Node starts the worker from worker-entry.ts itself. `pnpm
// build` (build.config.ts) bundles worker-entry.ts into one minified ES
// module and replaces the URL of worker-entry.ts below (the expression
// must appear exactly once in this file) with that code as a string literal, so the published package has
// no worker file to find and nothing for a downstream bundler to resolve.
// must appear exactly once in this file) with a data: URL of that code,
// so the published package has no worker file to find and nothing for a
// downstream bundler to resolve.
import { Worker } from "node:worker_threads";
import type { WorkerEndpoint } from "../core/worker-protocol.ts";
export function spawnNodeWorker(): WorkerEndpoint {
const entry: URL | string = new URL("./worker-entry.ts", import.meta.url);
const w = typeof entry === "string" ? new Worker(entry, { eval: true }) : new Worker(entry);
const w = new Worker(new URL("./worker-entry.ts", import.meta.url));
return {
post: (msg, transfer) => w.postMessage(msg, transfer),
listen(h) {

View File

@@ -20,12 +20,14 @@
import test, { after, before, describe } from "node:test";
import assert from "node:assert/strict";
import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import { createServer } from "node:http";
import type { AddressInfo } from "node:net";
import { availableParallelism, tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { promisify } from "node:util";
import { setFlagsFromString } from "node:v8";
import { runInNewContext } from "node:vm";
import { Worker } from "node:worker_threads";
@@ -329,6 +331,28 @@ describe("api", { concurrency: CONCURRENCY }, () => {
}));
});
// Workers inherit the flag, so the dist's inlined workers must not depend on Node detecting
// ES module syntax (each is a data:text/javascript URL; build.config.ts). The child runs a
// script file, not -e with --input-type=module: workers inherit that flag too, which would
// hide the failure. From source the workers are .ts files of a "type": "module" package.
test("worker mode under node --no-experimental-detect-module: the kernel worker and its CPU workers start", async (t) => {
const cpus = testCpus ?? (hasSmpPatch ? 2 : 1);
const dir = mkdtempSync(path.join(tmpdir(), "unkernel-detect-"));
t.after(() => rmSync(dir, { recursive: true, force: true }));
const script = path.join(dir, "boot.mjs");
writeFileSync(script, `const { createKernel } = await import(${JSON.stringify(import.meta.resolve(spec))});
const vm = await createKernel({ worker: true, kernel: process.env.KERNEL || undefined, cpus: ${cpus}, log: () => {} });
const { stdout } = await vm.exec("nproc");
await vm.stop();
console.log(stdout.trim());
`);
// Not spawnSync: the other tests run on this event loop meanwhile. A failure rejects with the child's stderr.
const { stdout } = await promisify(execFile)(process.execPath, ["--no-experimental-detect-module", script], {
timeout: 120_000, env: { ...process.env, KERNEL: testKernel ?? "" },
});
assert.equal(stdout.trim(), String(cpus));
});
test("worker mode: the kernel from a relative path, bytes or a Module; an initrd from bytes", async (t) => {
const file = kernelFile;
const bytes = new Uint8Array(readFileSync(file));