BlueGit

timfa questward

Files

questward / server / src / index.js

index.js

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