193 lines
5.9 KiB
TypeScript
193 lines
5.9 KiB
TypeScript
// 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 } 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";
|
|
|
|
const MAX_MESSAGE_SIZE = 4096;
|
|
// in build/, see build.ts
|
|
export const ENGINE_TEXTURES_INDEX = "assets/textures/index.json";
|
|
const SHUTDOWN_TIMEOUT_MS = 5000;
|
|
|
|
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;
|
|
world_file: 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<Response>;
|
|
// saves the world and stops the game. resolves once it's on disk
|
|
shutdown(): Promise<void>;
|
|
}
|
|
|
|
// throws when the mods have problems, saying what they are
|
|
export async function start_host(options: HostOptions): Promise<Host> {
|
|
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<number, WebSocket>();
|
|
let next_conn = 1;
|
|
let on_final_save: (() => void) | undefined;
|
|
|
|
game.onmessage = (event: MessageEvent<GameToHost>) => {
|
|
const message = event.data;
|
|
switch (message.type) {
|
|
case "ready":
|
|
console.log(`World ${options.world_file} 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":
|
|
write_world(options.world_file, message.data);
|
|
if (message.final) {
|
|
console.log("World saved");
|
|
on_final_save?.();
|
|
}
|
|
break;
|
|
}
|
|
};
|
|
game.onerror = (event) => {
|
|
event.preventDefault();
|
|
options.on_fatal(`Game server crashed: ${event.message}`);
|
|
};
|
|
|
|
post({
|
|
type: "init",
|
|
save: read_world(options.world_file),
|
|
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,
|
|
})),
|
|
});
|
|
|
|
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",
|
|
},
|
|
});
|
|
}
|
|
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 = () => {
|
|
clearTimeout(timeout);
|
|
game.terminate();
|
|
resolve();
|
|
};
|
|
post({ type: "shutdown" });
|
|
});
|
|
},
|
|
};
|
|
}
|
|
|
|
function read_world(file: string): string | undefined {
|
|
try {
|
|
return Deno.readTextFileSync(file);
|
|
} catch (e) {
|
|
if (e instanceof Deno.errors.NotFound) {
|
|
return undefined;
|
|
}
|
|
throw e;
|
|
}
|
|
}
|
|
|
|
function write_world(file: string, data: string) {
|
|
// write then rename so a crash mid write doesnt eat the world
|
|
Deno.writeTextFileSync(`${file}.tmp`, data);
|
|
Deno.renameSync(`${file}.tmp`, file);
|
|
}
|
|
|
|
// 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;
|
|
}
|