// 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 } from "./game/host_protocol.ts"; import { load_bmods } from "./load_bmods.ts"; import { read_regions, write_chunks } from "./regions.ts"; import type { SavedChunk, WorldSave } 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; // 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; // 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)); 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) => game.postMessage(message); 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 couldn't be written, tried again with the next one let 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; saving = saving.then(async () => { const chunks = new Map(unwritten); for (const chunk of save.chunks) chunks.set(`${chunk.x},${chunk.z}`, chunk); try { await write_world(options.world_dir, { level: save.level, chunks: [...chunks.values()] }); unwritten = new Map(); } catch (e) { unwritten = chunks; 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 "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); 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, })), } satisfies HostToGame, save.chunks.map((chunk) => chunk.data.buffer), ); 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(); 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"; // a folder that isn't there is a new world async function read_world(dir: string): Promise { 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 read_regions(join(dir, REGION_DIR)) : [] }; } // the chunks first, level.json says which world generation they were saved with async function write_world(dir: string, save: Required) { await write_chunks(join(dir, REGION_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; }