Files
unkernel/js/web/web-worker-entry.ts
Pooya Parsa 82c7d36d92 SDK: start an SMP kernel's CPUs as Web Workers in browsers
js/web/cpu.ts is the browser Platform.spawnCpu: each CPU is a module
Web Worker running runCpu(), nested in worker mode's kernel worker.
webCpuBlocker() (Platform.whyNoCpus) gives the kernel one CPU where a
thread cannot run CPUs: no cross-origin isolation, no Worker, no
Atomics.waitAsync, or a page's main thread, where CPU 0's
memory.atomic.wait32 would trap. stats().cpus says how many CPUs the
kernel got. The dist inlines the CPU worker as a Blob URL, in the web
entry and inside the web kernel worker.
2026-11-17 11:26:41 +00:00

26 lines
1.3 KiB
TypeScript

// SPDX-License-Identifier: MIT
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// The kernel worker's entry in browsers (started by worker.ts): serve the
// kernel (core/worker-serve.ts) over the worker's own message port, with
// the browser device kinds (devices.ts: the IndexedDB data disk, HTTP
// disks, Wisp), starting an SMP kernel's other CPUs as nested workers
// (cpu.ts). Every
// URL it gets is absolute (in the package it runs from a Blob URL, whose
// base means nothing), and it finds nothing through import.meta.url. The
// build bundles it into a module that imports nothing.
import { serveKernel } from "../core/worker-serve.ts";
import type { ToWorker } from "../core/worker-protocol.ts";
import { spawnWebCpu, webCpuBlocker } from "./cpu.ts";
import { webDevices } from "./devices.ts";
/** The dedicated worker's global (the page's tsconfig has no webworker lib). */
const scope = globalThis as unknown as {
postMessage(msg: unknown, transfer: Transferable[]): void;
addEventListener(type: "message", fn: (e: MessageEvent<ToWorker>) => void): void;
};
serveKernel({
post: (msg, transfer) => scope.postMessage(msg, transfer ?? []),
listen: (handler) => scope.addEventListener("message", (e) => handler(e.data)),
}, { devices: webDevices, spawnCpu: spawnWebCpu, whyNoCpus: webCpuBlocker });