mirror of
https://github.com/openfrontio/OpenFrontIO.git
synced 2026-06-21 06:00:41 +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
181 lines
5.3 KiB
TypeScript
181 lines
5.3 KiB
TypeScript
import { Worker } from "cluster";
|
|
import winston from "winston";
|
|
import { PublicGameInfo, PublicGameType } from "../core/Schemas";
|
|
import { generateID } from "../core/Util";
|
|
import {
|
|
MasterCreateGame,
|
|
MasterLobbiesBroadcast,
|
|
MasterUpdateGame,
|
|
WorkerMessageSchema,
|
|
} from "./IPCBridgeSchema";
|
|
import { logger } from "./Logger";
|
|
import { MapPlaylist } from "./MapPlaylist";
|
|
import { startPolling } from "./PollingLoop";
|
|
import { ServerEnv } from "./ServerEnv";
|
|
|
|
export interface MasterLobbyServiceOptions {
|
|
playlist: MapPlaylist;
|
|
log: typeof logger;
|
|
}
|
|
|
|
export class MasterLobbyService {
|
|
private readonly workers = new Map<number, Worker>();
|
|
// Worker id => the lobbies it owns.
|
|
private readonly workerLobbies = new Map<number, PublicGameInfo[]>();
|
|
private readonly readyWorkers = new Set<number>();
|
|
private started = false;
|
|
|
|
constructor(
|
|
private playlist: MapPlaylist,
|
|
private log: winston.Logger,
|
|
) {}
|
|
|
|
registerWorker(workerId: number, worker: Worker) {
|
|
this.workers.set(workerId, worker);
|
|
|
|
worker.on("message", (raw: unknown) => {
|
|
const result = WorkerMessageSchema.safeParse(raw);
|
|
if (!result.success) {
|
|
this.log.error("Invalid IPC message from worker:", raw);
|
|
return;
|
|
}
|
|
|
|
const msg = result.data;
|
|
switch (msg.type) {
|
|
case "workerReady":
|
|
this.handleWorkerReady(msg.workerId);
|
|
break;
|
|
case "lobbyList":
|
|
this.workerLobbies.set(workerId, msg.lobbies);
|
|
break;
|
|
}
|
|
});
|
|
}
|
|
|
|
removeWorker(workerId: number) {
|
|
this.workers.delete(workerId);
|
|
this.workerLobbies.delete(workerId);
|
|
this.readyWorkers.delete(workerId);
|
|
}
|
|
|
|
isHealthy(): boolean {
|
|
// We consider the lobby service healthy if at least half of the workers are ready.
|
|
// This allows for some leeway if a worker crashes.
|
|
const minWorkers = Math.max(ServerEnv.numWorkers() / 2, 1);
|
|
return this.started && this.readyWorkers.size >= minWorkers;
|
|
}
|
|
|
|
private handleWorkerReady(workerId: number) {
|
|
this.readyWorkers.add(workerId);
|
|
this.log.info(
|
|
`Worker ${workerId} is ready. (${this.readyWorkers.size}/${ServerEnv.numWorkers()} ready)`,
|
|
);
|
|
if (this.readyWorkers.size === ServerEnv.numWorkers() && !this.started) {
|
|
this.started = true;
|
|
this.log.info("All workers ready, starting game scheduling");
|
|
startPolling(async () => this.broadcastLobbies(), 500);
|
|
startPolling(async () => await this.maybeScheduleLobby(), 1000);
|
|
}
|
|
}
|
|
|
|
private getAllLobbies(): Record<PublicGameType, PublicGameInfo[]> {
|
|
const lobbies = Array.from(this.workerLobbies.values()).flat();
|
|
|
|
const result: Record<PublicGameType, PublicGameInfo[]> = {
|
|
ffa: [],
|
|
team: [],
|
|
special: [],
|
|
};
|
|
|
|
for (const lobby of lobbies) {
|
|
result[lobby.publicGameType].push(lobby);
|
|
}
|
|
|
|
for (const type of Object.keys(result) as PublicGameType[]) {
|
|
result[type].sort((a, b) => {
|
|
if (a.startsAt === undefined && b.startsAt === undefined) {
|
|
// Sort by game id for stability.
|
|
return a.gameID > b.gameID ? 1 : -1;
|
|
}
|
|
// If a lobby has startsAt set, we assume it's the active one.
|
|
if (a.startsAt === undefined) return 1;
|
|
if (b.startsAt === undefined) return -1;
|
|
return a.startsAt - b.startsAt;
|
|
});
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
private broadcastLobbies() {
|
|
const msg = {
|
|
type: "lobbiesBroadcast",
|
|
publicGames: {
|
|
serverTime: Date.now(),
|
|
games: this.getAllLobbies(),
|
|
},
|
|
} satisfies MasterLobbiesBroadcast;
|
|
for (const [workerId, worker] of this.workers.entries()) {
|
|
worker.send(msg, (e) => {
|
|
if (e) {
|
|
this.log.error(
|
|
`Failed to send lobbies broadcast to worker ${workerId}, killing worker:`,
|
|
e,
|
|
);
|
|
worker.kill();
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
private async maybeScheduleLobby() {
|
|
const lobbiesByType = this.getAllLobbies();
|
|
|
|
for (const type of Object.keys(lobbiesByType) as PublicGameType[]) {
|
|
const lobbies = lobbiesByType[type];
|
|
|
|
// Always ensure the next lobby has a timer, even if we already have 2+
|
|
// lobbies. This prevents a race where two lobbies are created before
|
|
// either receives a startsAt (IPC round-trip delay), leaving both stuck
|
|
// without a countdown.
|
|
const nextLobby = lobbies[0];
|
|
if (nextLobby && nextLobby.startsAt === undefined) {
|
|
this.sendMessageToWorker({
|
|
type: "updateLobby",
|
|
gameID: nextLobby.gameID,
|
|
startsAt: Date.now() + ServerEnv.gameCreationRate(),
|
|
});
|
|
}
|
|
|
|
if (lobbies.length >= 2) {
|
|
continue;
|
|
}
|
|
|
|
this.sendMessageToWorker({
|
|
type: "createGame",
|
|
gameID: generateID(),
|
|
gameConfig: await this.playlist.gameConfig(type),
|
|
publicGameType: type,
|
|
} satisfies MasterCreateGame);
|
|
}
|
|
}
|
|
|
|
private sendMessageToWorker(msg: MasterCreateGame | MasterUpdateGame): void {
|
|
const workerId = ServerEnv.workerIndex(msg.gameID);
|
|
const worker = this.workers.get(workerId);
|
|
if (!worker) {
|
|
this.log.error(`Worker ${workerId} not found`);
|
|
return;
|
|
}
|
|
worker.send(msg, (e) => {
|
|
if (e) {
|
|
this.log.error(
|
|
`Failed to send message to worker ${workerId}, killing worker:`,
|
|
e,
|
|
);
|
|
worker.kill();
|
|
}
|
|
});
|
|
}
|
|
}
|