import "dotenv/config"; import { isHfStorageEnabled, getDatasetId, getBucketId, flushAll } from "./hf-storage.js"; import { flushLocalSaves } from "./persistence.js"; import { isOAuthEnabled } from "./auth.js"; import { createApp } from "./create-app.js"; import { startStorageAlerts } from "./alerts.js"; const PORT = parseInt(process.env.PORT || "8080", 10); if (isHfStorageEnabled()) { console.log("[server] HF Dataset persistence enabled"); } else if (getDatasetId()) { console.log("[server] HF Dataset ID ready, waiting for first user login to activate persistence"); } else { console.log("[server] HF Dataset persistence disabled (no SPACE_ID or HF_DATASET_ID)"); console.log("[server] falling back to local file persistence"); } const oauthEnabled = isOAuthEnabled(); if (oauthEnabled) { console.log("[server] HF OAuth enabled (SPACE_ID set)"); } else { console.log("[server] HF OAuth disabled (no SPACE_ID), all users can edit"); } const { httpServer, stopAcceptingEdits } = createApp(); startStorageAlerts(); const server = httpServer.listen(PORT, async () => { console.log(`[server] running on http://localhost:${PORT}`); console.log(`[server] collab websocket at ws://localhost:${PORT}/collab`); console.log(`[server] SPACE_ID=${process.env.SPACE_ID || "(not set)"} HF_DATASET_ID=${getDatasetId() || "(empty)"} HF_BUCKET_ID=${getBucketId() || "(off)"} HF_TOKEN=${process.env.HF_TOKEN ? "set" : "not set"}`); }); let shuttingDown = false; async function gracefulShutdown(signal: string) { if (shuttingDown) return; shuttingDown = true; console.log(`[server] ${signal} received, flushing pending saves...`); // No new collaborative update may arrive after the final local snapshot. stopAcceptingEdits(); const httpClosed = new Promise((resolve) => { const timer = setTimeout(() => { console.warn("[server] force-closing remaining HTTP connections"); server.closeAllConnections(); resolve(); }, 5000); timer.unref(); server.close(() => { clearTimeout(timer); resolve(); }); }); // A hung cloud request must not turn a deployment into an indefinite wait. // Disk snapshots are already durable; report incomplete cloud persistence // with a non-zero exit rather than claiming a successful shutdown. const deadline = setTimeout(() => { console.error("[server] shutdown deadline exceeded; cloud saves may be incomplete"); process.exit(1); }, 30_000); deadline.unref(); // Order matters: flushLocalSaves() runs the debounced disk writes // that haven't fired yet (last <2s of edits) and schedules their // HF push; flushAll() then pushes everything, including those. let exitCode = 0; try { flushLocalSaves(); await flushAll(); } catch (error) { exitCode = 1; console.error("[server] shutdown persistence failed:", (error as Error).message); } await httpClosed; clearTimeout(deadline); process.exit(exitCode); } process.on("SIGTERM", () => gracefulShutdown("SIGTERM")); process.on("SIGINT", () => gracefulShutdown("SIGINT"));