Files
bworld/server/worldgen_workers.ts
T
2026-10-11 01:26:51 -03:00

67 lines
2.7 KiB
TypeScript

// the worldgen workers (game/worldgen_worker.ts), started by the host because the game worker has no permissions to
// start workers itself: Deno checks a new worker's code against its parent's permissions. each gets one end of a
// channel and the game the other, so the game talks to them directly. a worker that crashes is started again and the
// game is given its new port.
// what else was tried, in Deno 2.9: a worker without permissions can start one from a data: url, but that one can't
// import a single engine file either, so it would have to be the whole worker bundled into one script. and giving the
// game read access to the code isn't enough: imports from jsr (like @paulaboks/rng) also want permission to import
// from jsr.io, which would let engine access mods in the game import code from the internet
const WORKER_URL = new URL("./game/worldgen_worker.ts", import.meta.url);
// a worker that keeps crashing isn't started again after this many times, the game generates without it
const MAX_RESTARTS = 5;
// leaves a core for the game and one for everything else, and more than 4 doesn't help much
export function default_worldgen_workers(): number {
return Math.min(4, Math.max(1, (navigator.hardwareConcurrency ?? 2) - 2));
}
export interface WorldgenWorkers {
// the game's ends, in order
ports: MessagePort[];
terminate(): void;
}
export function start_worldgen_workers(
count: number,
options: {
// "none" like the game, for the host. tests load worldgen scripts from files, which needs "inherit"
permissions: "none" | "inherit";
// a worker crashed and was started again: the game's end of its new channel
on_restart(index: number, port: MessagePort): void;
},
): WorldgenWorkers {
const workers: Worker[] = [];
const restarts: number[] = Array(count).fill(0);
let stopped = false;
const start = (index: number): MessagePort => {
const worker = new Worker(WORKER_URL, {
type: "module",
deno: { permissions: options.permissions },
} as WorkerOptions);
const channel = new MessageChannel();
worker.postMessage({ port: channel.port1 }, [channel.port1]);
worker.onerror = (event) => {
event.preventDefault();
worker.terminate();
if (stopped) return;
if (++restarts[index] > MAX_RESTARTS) {
console.error(`Worldgen worker ${index} crashed again, leaving it: ${event.message}`);
return;
}
console.error(`Worldgen worker ${index} crashed, starting it again: ${event.message}`);
options.on_restart(index, start(index));
};
workers[index] = worker;
return channel.port2;
};
const ports = Array.from({ length: count }, (_, index) => start(index));
return {
ports,
terminate() {
stopped = true;
for (const worker of workers) worker.terminate();
for (const port of ports) port.close();
},
};
}