Files
bworld/server/game/worker.ts
T
2026-11-15 18:41:22 -03:00

178 lines
6.0 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
/// <reference lib="deno.worker" />
// runs the game in a worker without any permissions, the host does files and networking
import type { GameServer } from "./game_server.ts";
import { GameLoop } from "./game_loop.ts";
import { GameToHost, HostToGame, READ_DONE, READ_HEADER, READ_TOO_SMALL, READ_WAITING } from "./host_protocol.ts";
import { start_game } from "./load_mods.ts";
import { data_url } from "@/common/mod.ts";
import { type WorkerPort, WorldgenPool } from "./worldgen_pool.ts";
const SAVE_INTERVAL_MS = 30_000;
// how long the worldgen workers get to load the mods before the game starts without them
const WORLDGEN_START_TIMEOUT_MS = 60_000;
// a host that takes longer to read a chunk is stuck, and the game can't go on without it
const CHUNK_READ_TIMEOUT_MS = 30_000;
let game: GameServer | undefined;
let starting: Promise<void> | undefined;
// what the game asked the host for and waits on, downloads and schematic files, by id
const requests = new Map<number, { resolve: (value: never) => void; reject: (error: Error) => void }>();
let next_request = 1;
// where the host puts saved chunks, grown when one doesn't fit
let chunk_buffer = new SharedArrayBuffer(READ_HEADER + 256 * 1024);
function post(message: GameToHost) {
// the chunks and other bytes are moved to the host, not copied
const transfer = message.type === "save"
? message.save.chunks.map((chunk) => chunk.data.buffer)
: message.type === "send" && typeof message.data !== "string"
? [message.data.buffer]
: message.type === "write_schematic"
? [message.bytes.buffer]
: [];
self.postMessage(message, transfer);
}
function request<T>(message: (id: number) => GameToHost): Promise<T> {
return new Promise((resolve, reject) => {
const id = next_request++;
requests.set(id, { resolve: resolve as (value: never) => void, reject });
post(message(id));
});
}
// the host's answer to a request, with what was asked for, or undefined and why not
function answer(id: number, value: unknown, error: string) {
const pending = requests.get(id);
requests.delete(id);
if (value !== undefined) {
pending?.resolve(value as never);
} else {
pending?.reject(new Error(error));
}
}
// a saved chunk from the host. the game waits for it, like minecraft's server waits for a chunk it needs right away,
// which takes much less than generating it
function read_chunk(x: number, z: number): Uint8Array | undefined {
for (;;) {
const header = new Int32Array(chunk_buffer, 0, 2);
Atomics.store(header, 0, READ_WAITING);
post({ type: "read_chunk", x, z, buffer: chunk_buffer });
if (Atomics.wait(header, 0, READ_WAITING, CHUNK_READ_TIMEOUT_MS) === "timed-out") {
throw new Error(`The host didn't read chunk ${x}, ${z}`);
}
const length = header[1];
if (Atomics.load(header, 0) === READ_TOO_SMALL) {
chunk_buffer = new SharedArrayBuffer(READ_HEADER + length);
continue;
}
if (Atomics.load(header, 0) !== READ_DONE) throw new Error(`Bad answer reading chunk ${x}, ${z}`);
return length < 0 ? undefined : new Uint8Array(chunk_buffer, READ_HEADER, length).slice();
}
}
self.onmessage = async (event: MessageEvent<HostToGame>) => {
const message = event.data;
if (message.type === "init") {
starting = init(message);
return;
}
if (message.type === "worldgen_port") {
// the worker it replaces crashed. the pool resends what it was working on
await starting;
game?.worldgen_pool?.replace(message.index, message.port as unknown as WorkerPort);
return;
}
if (message.type === "downloaded") {
answer(message.id, message.bytes, message.error ?? "Couldn't download it");
return;
}
if (message.type === "wrote_schematic") {
answer(message.id, message.path, message.error ?? "Couldn't write it");
return;
}
// players can connect while mods are still loading
await starting;
if (!game) {
return;
}
switch (message.type) {
case "connect":
game.on_connect(message.conn);
break;
case "message":
game.on_message(message.conn, message.data);
break;
case "disconnect":
game.on_disconnect(message.conn);
break;
case "shutdown":
post({ type: "save", save: game.save(), final: true });
break;
}
};
async function init(message: Extract<HostToGame, { type: "init" }>) {
try {
game = await start_game(
{
send: (conn, data) => post({ type: "send", conn, data }),
close: (conn) => post({ type: "close", conn }),
download: (url, max_bytes) => request((id) => ({ type: "download", id, url, max_bytes })),
write_schematic: (bytes) => request((id) => ({ type: "write_schematic", id, bytes })),
},
{ level: message.save.level, chunks: { list: message.save.chunks, read: read_chunk } },
message.default_seed,
message.mods.map((mod) => ({
listing: mod.listing,
data: mod.data,
// the worker has no file access, so the host sends the code and it's imported from memory
url: mod.code ? data_url(mod.code) : undefined,
})),
);
} catch (e) {
post({ type: "failed", error: e instanceof Error ? e.message : String(e) });
return;
}
// chunks are generated in the worldgen workers, except what can't wait for them
if (message.worldgen_ports.length > 0) {
const pool = new WorldgenPool(message.worldgen_ports as unknown as WorkerPort[], game.worldgen_bundle!);
game.use_worldgen_pool(pool);
try {
let timer: ReturnType<typeof setTimeout> | undefined;
await Promise.race([
pool.ready(),
new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error("they took too long")), WORLDGEN_START_TIMEOUT_MS);
}),
]).finally(() => clearTimeout(timer));
await game.warm_up();
} catch (e) {
console.error(`The worldgen workers didn't start, generating on the game thread: ${(e as Error).message}`);
game.use_worldgen_pool(undefined);
pool.close();
}
}
const loop = new GameLoop(() => game!.tick());
game.loop = loop;
loop.start();
setInterval(() => {
if (game!.world.dirty) {
post({ type: "save", save: game!.save(), final: false });
}
}, SAVE_INTERVAL_MS);
post({ type: "ready", seed: game.world.seed });
}