BlueGit

timfa questward

Files

questward / server / src / index.js

index.js

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