BlueGit

timfa questward

Files

questward / server / src / index.js

index.js

index.js 3.5 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";
11import { DeployScheduler } from "./deploy/scheduler.js";
12import { writeRestartManifest, restartManifestPath } from "./deploy/manifest.js";
13import { hookConsoleCapture } from "./logging/consoleCapture.js";
14
15hookConsoleCapture();
16
17const rootDir = repoRootFrom(import.meta.url);
18const dataDir = join(rootDir, "server", "data");
19const port = Number(process.env.PORT ?? 8080);
20
21const worldDb = new WorldDatabase(join(dataDir, "world.sqlite"));
22const stateDb = new StateDatabase(join(dataDir, "state.sqlite"));
23const editor = new EditorService(worldDb);
24const characters = new CharacterService(stateDb, console);
25const friends = new FriendService(stateDb);
26const simulation = new Simulation(worldDb, stateDb);
27const auth = new StubAuth();
28const httpServer = createHttpServer(rootDir);
29
30const deployBridge = {
31 getStatus ()
32 {
33 return deployScheduler?.status() ?? { scheduled: false };
34 },
35 isDraining ()
36 {
37 return shuttingDown;
38 }
39};
40
41const gateway = attachGateway({
42 httpServer,
43 auth,
44 stateDb,
45 characters,
46 friends,
47 editor,
48 simulation,
49 deploy: deployBridge
50});
51
52let tickTimer = null;
53let shuttingDown = false;
54let deployScheduler = null;
55
56function scheduleTick ()
57{
58 if (shuttingDown)
59 { return; }
60 const tickMs = Math.max(16, Math.round(1000 / (simulation.settings.simulationTickHz || 20)));
61 tickTimer = setTimeout(() =>
62 {
63 characters.processDueDeletions(Date.now(), (characterId) => simulation.despawnCharacter(characterId));
64 const result = simulation.step();
65 gateway.onTickResult(result);
66 scheduleTick();
67 }, tickMs);
68}
69scheduleTick();
70
71deployScheduler = new DeployScheduler({
72 repoRoot: rootDir,
73 onStatusChange ()
74 {
75 gateway.broadcastRestartStatus?.();
76 },
77 onRestartDue (status)
78 {
79 void plannedRestart(status);
80 }
81});
82deployScheduler.start();
83
84httpServer.listen(port, () =>
85{
86 console.log(`Tile MMO listening on http://localhost:${port}`);
87 console.log(`World editor: http://localhost:${port}/editor`);
88});
89
90async function plannedRestart (status)
91{
92 if (shuttingDown)
93 { return; }
94 console.log("[deploy] Planned restart due:", status?.reasons?.join(", ") ?? "unknown");
95 try
96 {
97 writeRestartManifest(restartManifestPath(dataDir), {
98 reasons: status?.reasons ?? ["code-update"],
99 deployCode: true,
100 targetCommit: status?.remoteCommit ?? null,
101 pendingWorldRevision: worldDb.getPendingRevisionId?.() ?? null,
102 writtenAt: Date.now()
103 });
104 }
105 catch (error)
106 {
107 console.error("[deploy] Failed to write restart manifest:", error);
108 }
109 await shutdown("planned-restart");
110}
111
112async function shutdown (signal)
113{
114 if (shuttingDown)
115 { return; }
116 shuttingDown = true;
117 console.log(`Shutting down (${signal})…`);
118 clearTimeout(tickTimer);
119 deployScheduler?.stop();
120 gateway.setDraining?.(true);
121 try
122 { await gateway.shutdown(); }
123 catch (error)
124 { console.error("Graceful shutdown error:", error); }
125 worldDb.close();
126 stateDb.close();
127 await new Promise((resolve) => httpServer.close(resolve));
128 process.exit(0);
129}
130
131process.on("SIGINT", () => { void shutdown("SIGINT"); });
132process.on("SIGTERM", () => { void shutdown("SIGTERM"); });