Files
OpenFrontIO/src/client/LobbySocket.ts
T
Evan 275fd0dccc refactor: collapse per-env Configs into ClientEnv + ServerEnv (#3906)
## 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
2026-05-11 19:24:01 -07:00

150 lines
4.2 KiB
TypeScript

import { ClientEnv } from "src/client/ClientEnv";
import { PublicGames, PublicGamesSchema } from "../core/Schemas";
interface LobbySocketOptions {
reconnectDelay?: number;
maxWsAttempts?: number;
pollIntervalMs?: number;
}
function getRandomWorkerPath(numWorkers: number): string {
const workerIndex = Math.floor(Math.random() * numWorkers);
return `/w${workerIndex}`;
}
export class PublicLobbySocket {
private ws: WebSocket | null = null;
private wsReconnectTimeout: number | null = null;
private wsConnectionAttempts = 0;
private wsAttemptCounted = false;
private workerPath: string = "";
private stopped = true;
private readonly reconnectDelay: number;
private readonly maxWsAttempts: number;
constructor(
private onLobbiesUpdate: (data: PublicGames) => void,
options?: LobbySocketOptions,
) {
this.reconnectDelay = options?.reconnectDelay ?? 3000;
this.maxWsAttempts = options?.maxWsAttempts ?? 3;
}
async start() {
this.stopped = false;
this.wsConnectionAttempts = 0;
// Get config to determine number of workers, then pick a random one
this.workerPath = getRandomWorkerPath(ClientEnv.numWorkers());
this.connectWebSocket();
}
stop() {
this.stopped = true;
this.disconnectWebSocket();
}
private connectWebSocket() {
try {
// Clean up existing WebSocket before creating a new one
if (this.ws) {
this.ws.close();
this.ws = null;
}
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
const wsUrl = `${protocol}//${window.location.host}${this.workerPath}/lobbies`;
this.ws = new WebSocket(wsUrl);
this.wsAttemptCounted = false;
this.ws.addEventListener("open", () => this.handleOpen());
this.ws.addEventListener("message", (event) => this.handleMessage(event));
this.ws.addEventListener("close", () => this.handleClose());
this.ws.addEventListener("error", (error) => this.handleError(error));
} catch (error) {
this.handleConnectError(error);
}
}
private handleOpen() {
console.log("WebSocket connected: lobby updating");
this.wsConnectionAttempts = 0;
if (this.wsReconnectTimeout !== null) {
clearTimeout(this.wsReconnectTimeout);
this.wsReconnectTimeout = null;
}
}
private handleMessage(event: MessageEvent) {
try {
const publicGames = PublicGamesSchema.parse(
JSON.parse(event.data as string),
);
this.onLobbiesUpdate(publicGames);
} catch (error) {
console.error("Error parsing WebSocket message:", error);
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
try {
this.ws.close();
} catch (closeError) {
console.error(
"Error closing WebSocket after parse failure:",
closeError,
);
}
}
}
}
private handleClose() {
if (this.stopped) return;
console.log("WebSocket disconnected, attempting to reconnect...");
if (!this.wsAttemptCounted) {
this.wsAttemptCounted = true;
this.wsConnectionAttempts++;
}
if (this.wsConnectionAttempts >= this.maxWsAttempts) {
console.error("Max WebSocket attempts reached");
} else {
this.scheduleReconnect();
}
}
private handleError(error: Event) {
console.error("WebSocket error:", error);
}
private handleConnectError(error: unknown) {
console.error("Error connecting WebSocket:", error);
if (!this.wsAttemptCounted) {
this.wsAttemptCounted = true;
this.wsConnectionAttempts++;
}
if (this.wsConnectionAttempts >= this.maxWsAttempts) {
alert("error connecting to game service");
} else {
this.scheduleReconnect();
}
}
private scheduleReconnect() {
if (this.wsReconnectTimeout !== null) return;
this.wsReconnectTimeout = window.setTimeout(() => {
this.wsReconnectTimeout = null;
this.connectWebSocket();
}, this.reconnectDelay);
}
private disconnectWebSocket() {
if (this.ws) {
this.ws.close();
this.ws = null;
}
if (this.wsReconnectTimeout !== null) {
clearTimeout(this.wsReconnectTimeout);
this.wsReconnectTimeout = null;
}
}
}