Files
unkernel/js/node/wasi.ts
2026-12-02 15:09:59 +01:00

40 lines
1.9 KiB
TypeScript

// SPDX-License-Identifier: MIT
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// The guest's WASI programs on Node (core/wasi-exec.ts): each in a
// worker_threads Worker running wasi-entry.ts, started by the owner of
// vm.vsock. serveWasiPrograms() is core's with this spawner, which also
// gives each worker's CPU time (worker.cpuUsage(), for threaded programs'
// process clock).
//
// 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 a data: URL of the bundled entry.
import { Worker } from "node:worker_threads";
import type { Vsock } from "../core/vsock.ts";
import { serveWasiProgramsWith, type WasiExecOptions, type WasiExecServer } from "../core/wasi-exec.ts";
import type { WasiFromProgram, WasiProgramEndpoint } from "../core/wasi-program.ts";
export function spawnNodeWasi(): WasiProgramEndpoint {
const w = new Worker(new URL("./wasi-entry.ts", import.meta.url), { name: "unkernel-wasi" });
return {
post: (msg, transfer) => w.postMessage(msg, transfer),
listen(h) {
w.on("message", (m: WasiFromProgram) => h.message(m));
w.on("error", h.error);
w.on("exit", () => h.exit());
// A program never keeps the process alive: it belongs to the machine, whose end ends it.
// After the "message" listener, which refs the worker again (Node 24, Bun).
w.unref();
},
terminate: () => void w.terminate(),
// Read on the worker's thread (an interrupt, also while it computes or waits); Node 24.6 and later.
...(typeof w.cpuUsage === "function" && { cpuUsage: () => w.cpuUsage().then((u) => u.user + u.system) }),
};
}
/** Run the guest's WASI programs (kwwasi, vsock port 1021) on this host, each in a worker thread. */
export function serveWasiPrograms(vsock: Vsock, opts: WasiExecOptions = {}): WasiExecServer {
return serveWasiProgramsWith(vsock, { ...opts, spawn: spawnNodeWasi });
}