v0.5.1 — multiplayer Phase 4: lobby, sessions, reconnection
A real server existed since v0.5.0 but nobody could reach it without a hand-built ?seat=&secret= URL. This is what makes it a game you can actually create or join. The server now hosts more than one game: src/server/lobby.ts (new) is pure logic — creating, joining, bot seats, host transfer, starting — same split session.ts already draws for a running game. persistence.ts gained one directory per gameId plus a top-level index so index.ts resumes every saved game on boot. /api/stream and /api/intent now authenticate by session token instead of ?seat=&secret= — the token alone proves identity (lobby-and-sessions.md §1), so the join secret's job ends at the lobby door. Bots fill empty seats at Lobby.Start only, never take over a disconnected human (D8): session.ts gained driveBots(), playing developerBot forward through consecutive bot seats after every accepted intent. Disconnect keeps the seat and says so — Push gained an optional presence field, built entirely by http.ts and never routed through the engine, since a disconnect is transport news, not a GameEvent. Host rights pass to the earliest-joined remaining player if the host drops before start. Client: src/web/lobby.ts adds create/join forms and a live seating screen; localStorage replaces ?seat= for reconnecting straight back into a game already joined. A Multiplayer button sits beside New game; the New Game dialog itself is untouched. Found only by the live smoke test, not by typechecking: /api/intent read its token from the JSON body while the client sends it in the query string (matching /api/stream) — every intent failed "no such game" until caught by curl-level verification. Doc fix: multiplayer.md's D18 said the player cap was 6; lobby-and-sessions.md §2 says 2-4 with the reasoning and the test coverage to back it. The two had drifted apart. D18 now reads 2-4. Not verified: an actual browser walking through the lobby screens — none available in this environment, same limitation Phase 2's RemoteSession shipped under. 656 tests, 0 failures. tools/jitsi-harness/ deliberately left untracked — unrelated side-project work, not part of this release.
This commit is contained in:
+97
-10
@@ -1,22 +1,26 @@
|
||||
/**
|
||||
* Persistence — Phase 3 of `docs/architecture/multiplayer.md` (§12 steps 14-15;
|
||||
* `lobby-and-sessions.md` §6 specifies the exact shape and reasoning).
|
||||
* Persistence — Phase 3 of `docs/architecture/multiplayer.md` (§12 steps 14-15), extended for
|
||||
* Phase 4 (§12 steps 17-20) to more than one game (`lobby-and-sessions.md` §6 specifies both
|
||||
* shapes and the reasoning behind them).
|
||||
*
|
||||
* One game per process (Phase 2's scope, unchanged) — two files in `DATA_DIR`, no index and no
|
||||
* `gameId`, both deferred to Phase 4's multi-game generalization same as the server core deferred
|
||||
* them. Every write is a full-file atomic rewrite (write to `.tmp`, `rename` over the real path)
|
||||
* rather than true on-disk appending: §6 says the storage mechanism is genuinely open as long as the
|
||||
* LOGICAL history is never rewritten or reordered, which a full rewrite of an always-growing array
|
||||
* satisfies — and at the measured scale (~350 intents, a few hundred bytes per game) there is nothing
|
||||
* to optimize yet.
|
||||
* ONE DIRECTORY PER GAME (`games/<gameId>/`), plus one top-level `index.json` naming every game so
|
||||
* `index.ts` can find and resume them all on boot without scanning the filesystem. Every write is
|
||||
* still a full-file atomic rewrite (write to `.tmp`, `rename` over the real path) rather than true
|
||||
* on-disk appending — §6 says the storage mechanism is genuinely open as long as the LOGICAL history
|
||||
* is never rewritten or reordered, which a full rewrite of an always-growing array satisfies, and at
|
||||
* the measured scale (~350 intents, a few hundred bytes per game) there is nothing to optimize yet.
|
||||
*/
|
||||
|
||||
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
||||
import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import type { SavedGame, TurnTiming } from './session.ts';
|
||||
import type { Lobby, PlayerSession } from './lobby.ts';
|
||||
|
||||
const GAME_FILE = 'game.json';
|
||||
const TIMINGS_FILE = 'turn-timings.json';
|
||||
const LOBBY_FILE = 'lobby.json';
|
||||
const SESSIONS_FILE = 'sessions.json';
|
||||
const INDEX_FILE = 'index.json';
|
||||
|
||||
type PersistedGame = SavedGame & { engineVersion: string };
|
||||
|
||||
@@ -67,3 +71,86 @@ export async function appendTiming(dataDir: string, timing: TurnTiming): Promise
|
||||
existing.push(timing);
|
||||
await atomicWrite(path, JSON.stringify(existing, null, 1));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Phase 4 — more than one game
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export type GameIndexEntry = { gameId: string; gameCode: string; status: 'lobby' | 'active' | 'finished' };
|
||||
|
||||
/** Where one game's own files live. Every function below takes a `gameId` and joins it under here
|
||||
* itself; `writeGame`/`loadGame`/`appendTiming` above do not, and take a directory directly, so a
|
||||
* caller wanting one specific game's `game.json` passes `gameDir(dataDir, gameId)` to those. */
|
||||
export function gameDir(dataDir: string, gameId: string): string {
|
||||
return join(dataDir, 'games', gameId);
|
||||
}
|
||||
|
||||
export async function readIndex(dataDir: string): Promise<GameIndexEntry[]> {
|
||||
try {
|
||||
return JSON.parse(await readFile(join(dataDir, INDEX_FILE), 'utf8')) as GameIndexEntry[];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async function writeIndex(dataDir: string, entries: GameIndexEntry[]): Promise<void> {
|
||||
await mkdir(dataDir, { recursive: true });
|
||||
await atomicWrite(join(dataDir, INDEX_FILE), JSON.stringify(entries, null, 1));
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds or updates exactly one game's row, by `gameId` — every caller that changes one game's status
|
||||
* (created, started, finished) wants precisely this, not "replace the whole index", which would
|
||||
* silently drop every other game's row the moment two writes happened close together.
|
||||
*/
|
||||
export async function upsertIndexEntry(dataDir: string, entry: GameIndexEntry): Promise<void> {
|
||||
const entries = await readIndex(dataDir);
|
||||
const i = entries.findIndex((e) => e.gameId === entry.gameId);
|
||||
if (i >= 0) entries[i] = entry;
|
||||
else entries.push(entry);
|
||||
await writeIndex(dataDir, entries);
|
||||
}
|
||||
|
||||
export async function writeLobby(dataDir: string, lobby: Lobby): Promise<void> {
|
||||
const dir = gameDir(dataDir, lobby.gameId);
|
||||
await mkdir(dir, { recursive: true });
|
||||
await atomicWrite(join(dir, LOBBY_FILE), JSON.stringify(lobby, null, 1));
|
||||
}
|
||||
|
||||
export async function readLobby(dataDir: string, gameId: string): Promise<Lobby | null> {
|
||||
try {
|
||||
return JSON.parse(await readFile(join(gameDir(dataDir, gameId), LOBBY_FILE), 'utf8')) as Lobby;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removed once a game starts — a `Lobby` and a running `SavedGame` are mutually exclusive for one
|
||||
* `gameId`, and leaving the file behind would let a restart resurrect a lobby for a game already
|
||||
* under way. Missing already is not an error; `Lobby.Start` calls this exactly once, in the same
|
||||
* request that writes `game.json`.
|
||||
*/
|
||||
export async function deleteLobby(dataDir: string, gameId: string): Promise<void> {
|
||||
try {
|
||||
await unlink(join(gameDir(dataDir, gameId), LOBBY_FILE));
|
||||
} catch {
|
||||
// Already gone — nothing to do.
|
||||
}
|
||||
}
|
||||
|
||||
/** Session tokens for one game — `lobby-and-sessions.md` §6: persisted so a token still works after
|
||||
* a server restart, the same reason `game.json` itself is persisted. */
|
||||
export async function writeSessions(dataDir: string, gameId: string, sessions: PlayerSession[]): Promise<void> {
|
||||
const dir = gameDir(dataDir, gameId);
|
||||
await mkdir(dir, { recursive: true });
|
||||
await atomicWrite(join(dir, SESSIONS_FILE), JSON.stringify(sessions, null, 1));
|
||||
}
|
||||
|
||||
export async function readSessions(dataDir: string, gameId: string): Promise<PlayerSession[]> {
|
||||
try {
|
||||
return JSON.parse(await readFile(join(gameDir(dataDir, gameId), SESSIONS_FILE), 'utf8')) as PlayerSession[];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user