BlueGit

timfa questward

Files

questward / server / src / index.js

index.js

index.js 2.3 KiB Download Raw
1import { join } from "node:path";
2import { WorldDatabase } from "./persistence/worldDb.js";
3import { StateDatabase } from "./persistence/stateDb.js";
4import { EditorService } from "./editor/service.js";
5import { CharacterService } from "./characters/service.js";
6import { FriendService } from "./friends/service.js";
7import { StubAuth } from "./auth/stub.js";
8import { Simulation } from "./simulation/simulation.js";
9import { createHttpServer, repoRootFrom } from "./gateway/http.js";
10import { attachGateway } from "./gateway/websocket.js";
11
12const rootDir = repoRootFrom(import.meta.url);
13const dataDir = join(rootDir, "server", "data");
14const port = Number(process.env.PORT ?? 8080);
15
16const worldDb = new WorldDatabase(join(dataDir, "world.sqlite"));
17const stateDb = new StateDatabase(join(dataDir, "state.sqlite"));
18const editor = new EditorService(worldDb);
19const characters = new CharacterService(stateDb, console);
20const friends = new FriendService(stateDb);
21const simulation = new Simulation(worldDb, stateDb);
22const auth = new StubAuth();
23const httpServer = createHttpServer(rootDir);
24const gateway = attachGateway({ httpServer, auth, stateDb, characters, friends, editor, simulation });
25
26let tickTimer = null;
27let shuttingDown = false;
28
29function scheduleTick ()
30{
31 if (shuttingDown)
32 { return; }
33 const tickMs = Math.max(16, Math.round(1000 / (simulation.settings.simulationTickHz || 20)));
34 tickTimer = setTimeout(() =>
35 {
36 characters.processDueDeletions(Date.now(), (characterId) => simulation.despawnCharacter(characterId));
37 const result = simulation.step();
38 gateway.onTickResult(result);
39 scheduleTick();
40 }, tickMs);
41}
42scheduleTick();
43
44httpServer.listen(port, () =>
45{
46 console.log(`Tile MMO listening on http://localhost:${port}`);
47 console.log(`World editor: http://localhost:${port}/editor`);
48});
49
50async function shutdown (signal)
51{
52 if (shuttingDown)
53 { return; }
54 shuttingDown = true;
55 console.log(`Shutting down (${signal})…`);
56 clearTimeout(tickTimer);
57 try
58 { await gateway.shutdown(); }
59 catch (error)
60 { console.error("Graceful shutdown error:", error); }
61 worldDb.close();
62 stateDb.close();
63 await new Promise((resolve) => httpServer.close(resolve));
64 process.exit(0);
65}
66
67process.on("SIGINT", () => { void shutdown("SIGINT"); });
68process.on("SIGTERM", () => { void shutdown("SIGTERM"); });