// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later // the part of a game server that has permissions: files and networking. the game itself runs in a worker with none. // server/main.ts runs it as a dedicated server, and the desktop app runs it for singleplayer import { serveDir, serveFile } from "@std/http/file-server"; import { join } from "@std/path"; import { GameToHost, HostToGame, READ_DONE, READ_HEADER, READ_TOO_SMALL } from "./game/host_protocol.ts"; import { load_bmods } from "./load_bmods.ts"; import { list_chunks, read_chunk, write_chunks } from "./regions.ts"; import { default_worldgen_workers, start_worldgen_workers } from "./worldgen_workers.ts"; import type { SavedChunk } from "./game/saves.ts"; const MAX_MESSAGE_SIZE = 4096; // in build/, see build.ts export const ENGINE_TEXTURES_INDEX = "assets/textures/index.json"; const SHUTDOWN_TIMEOUT_MS = 5000; const DOWNLOAD_TIMEOUT_MS = 10_000; // the desktop app's zips that deno task desktop-all makes, for the title screen's download button export const DESKTOP_DOWNLOADS = ["windows.zip", "linux.zip"]; export interface HostOptions { // what deno task build made: the client and the engine's assets build_dir: string; // the .bmod files to load server_mods_dir: string; // .json files that change mods' settings, see docs/modding/misc/config.md. without it every mod uses its // own config.json config_dir?: string; // where DESKTOP_DOWNLOADS are, served at /dist/. without it there's nothing to download dist_dir?: string; // the world's folder: level.json, and the blocks in region/ world_dir: string; seed?: string; // how many workers generate chunks, besides the game. 0 generates on the game's thread. a few by default, see // default_worldgen_workers worldgen_workers?: number; // the game can't go on, like the worker crashing on_fatal(message: string): void; } export interface Host { handle(req: Request): Response | Promise; // saves the world and stops the game. resolves once it's on disk shutdown(): Promise; } // throws when the mods have problems, saying what they are export async function start_host(options: HostOptions): Promise { const mods = await load_bmods(options.server_mods_dir, engine_texture_ids(options.build_dir), options.config_dir); console.log(`Mods: ${mods.map((mod) => `${mod.listing.id} ${mod.listing.version}`).join(", ") || "none"}`); // what players download, by path const downloads = new Map(mods.map((mod) => [`/${mod.listing.file}`, mod.client_bytes])); const game = new Worker(new URL("./game/worker.ts", import.meta.url), { type: "module", deno: { permissions: "none" }, } as WorkerOptions); const post = (message: HostToGame, transfer: Transferable[] = []) => game.postMessage(message, transfer); // without permissions like the game, which can't start them itself const worldgen = start_worldgen_workers(options.worldgen_workers ?? default_worldgen_workers(), { permissions: "none", on_restart: (index, port) => post({ type: "worldgen_port", index, port }, [port]), }); const sockets = new Map(); let next_conn = 1; let on_final_save: ((error?: Error) => void) | undefined; // saves are written one after another, in order let saving = Promise.resolve(); // chunks from saves that aren't written yet, by "x,z": the game reads them from here. ones that couldn't be written // are tried again with the next save const unwritten = new Map(); game.onmessage = (event: MessageEvent) => { const message = event.data; switch (message.type) { case "ready": console.log(`World ${options.world_dir} ready, seed ${message.seed}`); break; case "failed": options.on_fatal(`Couldn't start the game: ${message.error}`); break; case "send": { const socket = sockets.get(message.conn); if (socket?.readyState === WebSocket.OPEN) { socket.send(message.data); } break; } case "close": sockets.get(message.conn)?.close(); break; case "save": { const { save, final } = message; for (const chunk of save.chunks) unwritten.set(`${chunk.x},${chunk.z}`, chunk); saving = saving.then(async () => { const chunks = new Map(unwritten); try { await write_world(options.world_dir, { level: save.level, chunks: [...chunks.values()] }); // unless a later save has them again for (const [key, chunk] of chunks) { if (unwritten.get(key) === chunk) unwritten.delete(key); } } catch (e) { console.error(`Couldn't save the world: ${(e as Error).message}`); if (final) on_final_save?.(e as Error); return; } if (final) { console.log("World saved"); on_final_save?.(); } }); break; } case "read_chunk": { const { x, z, buffer } = message; const unwritten_chunk = unwritten.get(`${x},${z}`); (unwritten_chunk ? Promise.resolve(unwritten_chunk.data) : read_chunk(region_dir(options.world_dir), x, z)) .catch((e) => { console.error(`Couldn't read chunk ${x}, ${z}: ${(e as Error).message}`); return undefined; }) .then((data) => answer_chunk_read(buffer, data)); break; } case "download": download(message.url, message.max_bytes).then( (bytes) => post({ type: "downloaded", id: message.id, bytes }), (e) => post({ type: "downloaded", id: message.id, error: e instanceof Error ? e.message : String(e) }), ); break; } }; game.onerror = (event) => { event.preventDefault(); options.on_fatal(`Game server crashed: ${event.message}`); }; const save = await read_world(options.world_dir); if (save.chunks.length) console.log(`${save.chunks.length} chunks saved`); game.postMessage( { type: "init", save, default_seed: options.seed ?? crypto.randomUUID(), mods: mods.map(({ listing, bmod }) => ({ listing, data: bmod.data, server_code: bmod.scripts.server, worldgen_code: bmod.scripts.worldgen, shared_code: bmod.scripts.shared, })), worldgen_ports: worldgen.ports, } satisfies HostToGame, worldgen.ports, ); function handle_socket(socket: WebSocket) { const conn = next_conn++; socket.addEventListener("open", () => { sockets.set(conn, socket); post({ type: "connect", conn }); }); socket.addEventListener("message", (event) => { if (typeof event.data !== "string" || event.data.length > MAX_MESSAGE_SIZE) { return; } post({ type: "message", conn, data: event.data }); }); socket.addEventListener("close", () => { if (sockets.delete(conn)) { post({ type: "disconnect", conn }); } }); } return { handle(req) { const url = new URL(req.url); if (url.pathname === "/ws") { if (req.headers.get("upgrade")?.toLowerCase() !== "websocket") { return new Response("Expected a websocket", { status: 426 }); } const { socket, response } = Deno.upgradeWebSocket(req); handle_socket(socket); return response; } if (url.pathname === "/") { return Response.redirect(new URL("/client/", url), 302); } const download = downloads.get(url.pathname); if (download) { // named by its hash, so it never changes and pages on other origins can cache it forever return new Response(download, { headers: { "content-type": "application/zip", "access-control-allow-origin": "*", "cache-control": "public, max-age=31536000, immutable", }, }); } const desktop_download = url.pathname.match(/^\/dist\/([^/]+)$/)?.[1]; if (options.dist_dir && desktop_download && DESKTOP_DOWNLOADS.includes(desktop_download)) { return serveFile(req, join(options.dist_dir, desktop_download)); } return serve_static(options.build_dir, req, url); }, shutdown() { console.log("Saving world..."); return new Promise((resolve, reject) => { const timeout = setTimeout( () => reject(new Error("Game server didn't save in time")), SHUTDOWN_TIMEOUT_MS, ); on_final_save = (error) => { clearTimeout(timeout); game.terminate(); worldgen.terminate(); if (error) { reject(error); } else { resolve(); } }; post({ type: "shutdown" }); }); }, }; } // for the game worker, which has no network access. errors are told to players, so they say what went wrong simply async function download(url: string, max_bytes: number): Promise { let parsed: URL; try { parsed = new URL(url); } catch { throw new Error("That isn't a url"); } if (parsed.protocol !== "http:" && parsed.protocol !== "https:") { throw new Error("Only http and https urls work"); } let response: Response; try { response = await fetch(parsed, { signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS) }); } catch { throw new Error("Couldn't download it"); } if (!response.ok || !response.body) { await response.body?.cancel(); throw new Error(`Couldn't download it (${response.status})`); } // read up to the limit instead of trusting content-length const reader = response.body.getReader(); const chunks: Uint8Array[] = []; let size = 0; while (true) { let chunk: ReadableStreamReadResult; try { chunk = await reader.read(); } catch { throw new Error("Couldn't download it"); } if (chunk.done) { break; } size += chunk.value.length; if (size > max_bytes) { await reader.cancel(); throw new Error(`It's bigger than ${Math.floor(max_bytes / 1024)} KB`); } chunks.push(chunk.value); } const bytes = new Uint8Array(size); let offset = 0; for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.length; } return bytes; } const LEVEL_FILE = "level.json"; const REGION_DIR = "region"; function region_dir(world_dir: string) { return join(world_dir, REGION_DIR); } // level.json and where the saved chunks are. a folder that isn't there is a new world async function read_world(dir: string): Promise<{ level?: string; chunks: [number, number][] }> { let level: string | undefined; try { level = Deno.readTextFileSync(join(dir, LEVEL_FILE)); } catch (e) { if (!(e instanceof Deno.errors.NotFound)) throw e; } return { level, chunks: level ? await list_chunks(region_dir(dir)) : [] }; } // gives the game waiting in read_chunk the chunk, see READ_WAITING function answer_chunk_read(buffer: SharedArrayBuffer, data: Uint8Array | undefined) { const header = new Int32Array(buffer, 0, 2); if (data && READ_HEADER + data.length > buffer.byteLength) { header[1] = data.length; Atomics.store(header, 0, READ_TOO_SMALL); } else { if (data) new Uint8Array(buffer, READ_HEADER).set(data); header[1] = data ? data.length : -1; Atomics.store(header, 0, READ_DONE); } Atomics.notify(header, 0); } // the chunks first, then level.json async function write_world(dir: string, save: { level: string; chunks: SavedChunk[] }) { await write_chunks(region_dir(dir), save.chunks); Deno.mkdirSync(dir, { recursive: true }); // write then rename so a crash mid write doesnt eat the world const level = join(dir, LEVEL_FILE); Deno.writeTextFileSync(`${level}.tmp`, save.level); Deno.renameSync(`${level}.tmp`, level); } // the engine's textures, listed by the build next to the client's assets. engine:missing is drawn by code export function engine_texture_ids(build_dir: string): string[] { const names: string[] = JSON.parse(Deno.readTextFileSync(join(build_dir, ENGINE_TEXTURES_INDEX))); return ["engine:missing", ...names.map((name) => `engine:${name}`)]; } // the client and the engine's assets. pages on other origins load the engine's textures from here too export async function serve_static(build_dir: string, req: Request, url: URL) { const response = await serveDir(req, { fsRoot: build_dir, quiet: true }); if (url.pathname.startsWith("/assets/") && response.ok) { const headers = new Headers(response.headers); headers.set("Access-Control-Allow-Origin", "*"); return new Response(response.body, { status: response.status, statusText: response.statusText, headers }); } return response; }