BlueGit

timfa questward

Files

questward / server / src / index.js

index.js

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