BlueGit

timfa questward

Files

questward / server / src / index.js

index.js

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