mirror of
https://github.com/openfrontio/OpenFrontIO.git
synced 2026-06-23 06:09:37 +00:00
275fd0dccc
## Description: This is a refactor to simplify config handling. Replaces the per-environment DevConfig/PreprodConfig/ProdConfig class hierarchy with two static classes: ClientEnv (browser main thread, reads from window.BOOTSTRAP_CONFIG) and ServerEnv (Node server, reads from process.env). The four config classes are deleted, the abstract DefaultServerConfig is gone, and DefaultConfig is renamed to Config. The values that flow server → client (gameEnv, numWorkers, turnstileSiteKey, jwtAudience, instanceId) used to be baked into the hardcoded per-env classes. They're now real env vars on the server, embedded into a single window.BOOTSTRAP_CONFIG object in index.html at request time (alongside the existing gitCommit/assetManifest/cdnBase globals, which moved into the same object), and read back by ClientEnv on the client. The dev defaults previously hidden inside DevServerConfig are now explicit in start:server-dev (NUM_WORKERS=2, TURNSTILE_SITE_KEY=1x..., JWT_AUDIENCE=localhost, etc.) and in vite.config.ts's html plugin inject.data. Production deploys plumb NUM_WORKERS and TURNSTILE_SITE_KEY through deploy.yml (GitHub vars) into the remote env file; JWT_AUDIENCE is derived from DOMAIN in deploy.sh. The dynamic /api/instance endpoint is gone — INSTANCE_ID rides along in BOOTSTRAP_CONFIG now. ServerEnv is the only thing server code touches; ClientEnv is browser-only. The two classes have intentional overlap (env, numWorkers, jwtIssuer, gameCreationRate, workerIndex, etc.) since they derive identical logic from different sources — there's a TODO in each to consolidate via a shared helper later. The game-logic Config no longer stores a ServerConfig/ClientEnv reference and its serverConfig() getter is gone; the one caller (MultiTabModal) now reads ClientEnv.env() directly. Worker init no longer carries server-config values since nothing in the worker actually reads them. ## Please complete the following: - [x] I have added screenshots for all UI updates - [x] I process any text displayed to the user through translateText() and I've added it to the en.json file - [x] I have added relevant tests to the test directory - [x] I confirm I have thoroughly tested these changes and take full responsibility for any bugs introduced ## Please put your Discord username so you can be contacted if a bug or regression is found: evan
163 lines
4.2 KiB
TypeScript
163 lines
4.2 KiB
TypeScript
import cluster from "cluster";
|
|
import crypto from "crypto";
|
|
import express from "express";
|
|
import rateLimit from "express-rate-limit";
|
|
import http from "http";
|
|
import path from "path";
|
|
import { fileURLToPath } from "url";
|
|
import { GameEnv } from "../core/configuration/Config";
|
|
import { logger } from "./Logger";
|
|
import { MapPlaylist } from "./MapPlaylist";
|
|
import { MasterLobbyService } from "./MasterLobbyService";
|
|
import { setNoStoreHeaders } from "./NoStoreHeaders";
|
|
import { renderAppShell } from "./RenderHtml";
|
|
import { ServerEnv } from "./ServerEnv";
|
|
import { applyStaticAssetCacheControl } from "./StaticAssetCache";
|
|
|
|
const playlist = new MapPlaylist();
|
|
let lobbyService: MasterLobbyService;
|
|
|
|
const app = express();
|
|
const server = http.createServer(app);
|
|
|
|
const log = logger.child({ comp: "m" });
|
|
|
|
const __filename = fileURLToPath(import.meta.url);
|
|
const __dirname = path.dirname(__filename);
|
|
|
|
app.use(express.json());
|
|
|
|
// Serve the shared app shell for the root document.
|
|
app.use(async (req, res, next) => {
|
|
if (req.path === "/") {
|
|
try {
|
|
await renderAppShell(
|
|
res,
|
|
path.join(__dirname, "../../static/index.html"),
|
|
);
|
|
} catch (error) {
|
|
log.error("Error rendering index.html:", error);
|
|
res.status(500).send("Internal Server Error");
|
|
}
|
|
} else {
|
|
next();
|
|
}
|
|
});
|
|
|
|
app.use(
|
|
express.static(path.join(__dirname, "../../static"), {
|
|
maxAge: "1y", // Set max-age to 1 year for all static assets
|
|
setHeaders: (res) => {
|
|
applyStaticAssetCacheControl(
|
|
res.setHeader.bind(res),
|
|
res.req.originalUrl,
|
|
);
|
|
},
|
|
}),
|
|
);
|
|
|
|
app.set("trust proxy", 3);
|
|
app.use(
|
|
rateLimit({
|
|
windowMs: 1000, // 1 second
|
|
max: 20, // 20 requests per IP per second
|
|
}),
|
|
);
|
|
|
|
app.use("/api", (_req, res, next) => {
|
|
setNoStoreHeaders(res);
|
|
next();
|
|
});
|
|
|
|
// Start the master process
|
|
export async function startMaster() {
|
|
if (!cluster.isPrimary) {
|
|
throw new Error(
|
|
"startMaster() should only be called in the primary process",
|
|
);
|
|
}
|
|
|
|
log.info(`Primary ${process.pid} is running`);
|
|
log.info(`Setting up ${ServerEnv.numWorkers()} workers...`);
|
|
|
|
lobbyService = new MasterLobbyService(playlist, log);
|
|
|
|
// Generate admin token for worker authentication
|
|
const ADMIN_TOKEN = crypto.randomBytes(16).toString("hex");
|
|
process.env.ADMIN_TOKEN = ADMIN_TOKEN;
|
|
|
|
const INSTANCE_ID =
|
|
ServerEnv.env() === GameEnv.Dev
|
|
? "DEV_ID"
|
|
: crypto.randomBytes(4).toString("hex");
|
|
process.env.INSTANCE_ID = INSTANCE_ID;
|
|
|
|
log.info(`Instance ID: ${INSTANCE_ID}`);
|
|
|
|
// Fork workers
|
|
for (let i = 0; i < ServerEnv.numWorkers(); i++) {
|
|
const worker = cluster.fork({
|
|
WORKER_ID: i,
|
|
ADMIN_TOKEN,
|
|
INSTANCE_ID,
|
|
});
|
|
|
|
lobbyService.registerWorker(i, worker);
|
|
log.info(`Started worker ${i} (PID: ${worker.process.pid})`);
|
|
}
|
|
|
|
// Handle worker crashes
|
|
cluster.on("exit", (worker, code, signal) => {
|
|
const workerId = (worker as any).process?.env?.WORKER_ID;
|
|
if (workerId === undefined) {
|
|
log.error(`worker crashed could not find id`);
|
|
return;
|
|
}
|
|
|
|
const workerIdNum = parseInt(workerId);
|
|
lobbyService.removeWorker(workerIdNum);
|
|
|
|
log.warn(
|
|
`Worker ${workerId} (PID: ${worker.process.pid}) died with code: ${code} and signal: ${signal}`,
|
|
);
|
|
log.info(`Restarting worker ${workerId}...`);
|
|
|
|
// Restart the worker with the same ID
|
|
const newWorker = cluster.fork({
|
|
WORKER_ID: workerId,
|
|
ADMIN_TOKEN,
|
|
INSTANCE_ID,
|
|
});
|
|
|
|
lobbyService.registerWorker(workerIdNum, newWorker);
|
|
log.info(
|
|
`Restarted worker ${workerId} (New PID: ${newWorker.process.pid})`,
|
|
);
|
|
});
|
|
|
|
const PORT = 3000;
|
|
server.listen(PORT, () => {
|
|
log.info(`Master HTTP server listening on port ${PORT}`);
|
|
});
|
|
}
|
|
|
|
app.get("/api/health", (_req, res) => {
|
|
const ready = lobbyService?.isHealthy() ?? false;
|
|
if (ready) {
|
|
res.json({ status: "ok" });
|
|
} else {
|
|
res.status(503).json({ status: "unavailable" });
|
|
}
|
|
});
|
|
|
|
// SPA fallback route
|
|
app.get("/{*splat}", async function (_req, res) {
|
|
try {
|
|
const htmlPath = path.join(__dirname, "../../static/index.html");
|
|
await renderAppShell(res, htmlPath);
|
|
} catch (error) {
|
|
log.error("Error rendering SPA fallback:", error);
|
|
res.status(500).send("Internal Server Error");
|
|
}
|
|
});
|