import { join } from "node:path"; import { WorldDatabase } from "./persistence/worldDb.js"; import { StateDatabase } from "./persistence/stateDb.js"; import { EditorService } from "./editor/service.js"; import { CharacterService } from "./characters/service.js"; import { FriendService } from "./friends/service.js"; import { createAuth } from "./auth/index.js"; import { Simulation } from "./simulation/simulation.js"; import { createHttpServer, repoRootFrom } from "./gateway/http.js"; import { attachGateway } from "./gateway/websocket.js"; import { DeployScheduler } from "./deploy/scheduler.js"; import { writeRestartManifest, restartManifestPath } from "./deploy/manifest.js"; import { hookConsoleCapture } from "./logging/consoleCapture.js"; hookConsoleCapture(); const rootDir = repoRootFrom(import.meta.url); const dataDir = join(rootDir, "server", "data"); const port = Number(process.env.PORT ?? 8080); const worldDb = new WorldDatabase(join(dataDir, "world.sqlite")); const stateDb = new StateDatabase(join(dataDir, "state.sqlite")); const editor = new EditorService(worldDb); const characters = new CharacterService(stateDb, console); const friends = new FriendService(stateDb); const simulation = new Simulation(worldDb, stateDb); const auth = createAuth(stateDb); const httpServer = createHttpServer(rootDir, { auth, stateDb }); const deployBridge = { getStatus () { return deployScheduler?.status() ?? { scheduled: false }; }, isDraining () { return shuttingDown; }, requestRestartNow (reason = "admin-editor") { void plannedRestart({ reasons: [reason], remoteCommit: null, scheduledAt: Date.now() }); } }; const gateway = attachGateway({ httpServer, auth, stateDb, characters, friends, editor, simulation, deploy: deployBridge }); let tickTimer = null; let shuttingDown = false; let deployScheduler = null; function scheduleTick () { if (shuttingDown) { return; } const tickMs = Math.max(16, Math.round(1000 / (simulation.settings.simulationTickHz || 20))); tickTimer = setTimeout(() => { characters.processDueDeletions(Date.now(), (characterId) => simulation.despawnCharacter(characterId)); const result = simulation.step(); gateway.onTickResult(result); scheduleTick(); }, tickMs); } scheduleTick(); deployScheduler = new DeployScheduler({ repoRoot: rootDir, onStatusChange () { gateway.broadcastRestartStatus?.(); }, onRestartDue (status) { void plannedRestart(status); } }); deployScheduler.start(); httpServer.listen(port, () => { console.log(`Questward listening on http://localhost:${port}`); console.log(`World editor: http://localhost:${port}/editor`); }); async function plannedRestart (status) { if (shuttingDown) { return; } console.log("[deploy] Planned restart due:", status?.reasons?.join(", ") ?? "unknown"); try { writeRestartManifest(restartManifestPath(dataDir), { reasons: status?.reasons ?? ["code-update"], deployCode: true, targetCommit: status?.remoteCommit ?? null, pendingWorldRevision: worldDb.getPendingRevisionId?.() ?? null, writtenAt: Date.now() }); } catch (error) { console.error("[deploy] Failed to write restart manifest:", error); } await shutdown("planned-restart"); } async function shutdown (signal) { if (shuttingDown) { return; } shuttingDown = true; console.log(`Shutting down (${signal})…`); clearTimeout(tickTimer); deployScheduler?.stop(); gateway.setDraining?.(true); try { await gateway.shutdown(); } catch (error) { console.error("Graceful shutdown error:", error); } worldDb.close(); stateDb.close(); await new Promise((resolve) => httpServer.close(resolve)); process.exit(0); } process.on("SIGINT", () => { void shutdown("SIGINT"); }); process.on("SIGTERM", () => { void shutdown("SIGTERM"); });