diff options
| author | Joel Klinghed <the_jk@spawned.biz> | 2026-11-23 00:51:32 +0100 |
|---|---|---|
| committer | Joel Klinghed <the_jk@spawned.biz> | 2026-11-23 00:51:32 +0100 |
| commit | 93970f361b831f17d48ff2a345fc78488ac71fba (patch) | |
| tree | f3844cc343c95dcc19a1444bdb6666e807bc59ef /e2e/helpers/server.ts | |
| parent | b884441ba0d10bdd3559748507a0991888f66194 (diff) | |
Phase 7: hardening and shipping (M7)
E2E (Playwright, e2e/):
- table fixture: one real compiled server per test (temp saves dir, free
port, workers: 1); a Tab helper drives the real UI (menus, rows,
initiative, draw, seats) over one WS per fresh browser context
- full round: onboarding, secret initiative masked to ?? per connection,
draw revealing on every screen, turns, next round, round-2 secrecy
- seats: claim/re-claim on owner-leave, reload keeps the session and
re-claims, two sessions can't own one character
- resilience: a dropped tab resyncs on reconnect (no drift); a SIGKILL'd
server restarts with state + seats surviving (incl. the owner's secret
initiative and the enabled draw); a throttled tab converges on the same
state as the fast tabs; a double-tapped draw runs once, error sent to
the sender only
- figure edit: set a character level + rename from the status menu
Cross-check vs the reference (feature parity):
- status menu: level pills (setCharacterLevel) + a name field
(changeName), mirroring SetCharacterLevelMenu
- ability-card removal: draw-pile-only "send to bottom"
(reorderAbilityList -> index 0) + "shuffle undrawn cards"
(shuffleDrawnAbilityCard), mirroring RemoveCardMenu
- Add Character: already-added classes disabled (Objective/Escort may be
added repeatedly), matching _characterAlreadyAdded
- every remaining registry command verified reachable from the UI
Session persistence (found by the restart test):
- the client never learned its session id before the first welcome, so a
reconnect minted a new id and orphaned the restored seat; fixed with
establishSessionCookie() (a GET /session before the WS upgrade, plus a
vite /session proxy) so the x-haven-session cookie survives restarts
- the initiative input now prefills from re-synced state (CharacterRow
effect, guarded against clobbering a live edit) so a reload/reconnect
doesn't blank an entry
Performance + deployment:
- immutable asset caching (Cache-Control: 1yr, immutable) for the game
data / images / in-game translations; no-cache for the SPA index.html
so rebuilt apps reach open tabs
- server tool/perf_measure.dart: the performance probe (state payload
size at full-table scale, WS fan-out bytes per action, traffic per
connection)
- Dockerfile (server + built web); docs/DEPLOYMENT.md (Docker,
persistence, reverse proxy, measured performance, smoke-test list)
- README quickstart + production/Docker/testing sections
Server:
- --saves-dir and --data-dir CLI options (Docker / multi-game hosts),
threaded through the stores and data loading
Misc:
- app.css: height 100% on .row so the turn-done tap zone resolves to a
clickable height; fake-socket.ts readyState constants corrected to the
real WebSocket values (0 CONNECTING, 1 OPEN)
- scripts/ci.sh: the Playwright E2E gate (runs when PLAYWRIGHT is set)
- PLAN.md: Phase 7 boxes checked, M7 progress-log entry
Verification: svelte-check 0 errors; web 196/196 tests; vite build OK;
dart analyze 0 errors / 0 warnings; dart test 604/604; Playwright 9/9;
scripts/ci.sh green end-to-end.
Diffstat (limited to 'e2e/helpers/server.ts')
| -rw-r--r-- | e2e/helpers/server.ts | 167 |
1 files changed, 167 insertions, 0 deletions
diff --git a/e2e/helpers/server.ts b/e2e/helpers/server.ts new file mode 100644 index 0000000..8357421 --- /dev/null +++ b/e2e/helpers/server.ts @@ -0,0 +1,167 @@ +/** + * Boots the real Dart game server for the E2E specs (PLAN.md Phase 7). + * + * `bin/main.dart` is compiled to a native executable once (cached under + * `e2e/.cache/`, recompiled when `bin/main.dart` is newer) so the + * resilience specs can kill and restart the server quickly. Each test gets + * a fresh temp saves dir and a free port, so the specs never share state. + */ +import { + execFileSync, + spawn, + type ChildProcess +} from 'node:child_process'; +import { + existsSync, + mkdirSync, + mkdtempSync, + rmSync, + statSync +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +// This file lives in `e2e/helpers/`; the E2E root is one level up. +const E2E_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const REPO_ROOT = path.resolve(E2E_DIR, '..'); +const SERVER_DIR = path.join(REPO_ROOT, 'server'); +const WEB_DIST = path.join(REPO_ROOT, 'web', 'dist'); +const CACHE_DIR = path.join(E2E_DIR, '.cache'); +const BINARY = path.join(CACHE_DIR, 'xhaven-server'); +const MAIN_DART = path.join(SERVER_DIR, 'bin', 'main.dart'); + +let compilePromise: Promise<void> | null = null; + +/** Compiles the server to a native binary (cached; recompile when stale). */ +export function ensureServerBinary(): Promise<void> { + const needsCompile = + !existsSync(BINARY) || + statSync(MAIN_DART).mtimeMs > statSync(BINARY).mtimeMs; + if (!needsCompile) return Promise.resolve(); + compilePromise ??= (async () => { + mkdirSync(CACHE_DIR, { recursive: true }); + execFileSync('dart', ['compile', 'exe', 'bin/main.dart', '-o', BINARY], { + cwd: SERVER_DIR, + stdio: 'inherit', + timeout: 300_000 + }); + })(); + return compilePromise; +} + +/** A free TCP port on localhost. */ +export async function freePort(): Promise<number> { + const net = await import('node:net'); + return new Promise((resolve, reject) => { + const srv = net.createServer(); + srv.unref(); + srv.listen(0, '127.0.0.1', () => { + const addr = srv.address(); + const port = typeof addr === 'object' && addr ? addr.port : 0; + srv.close(() => (port ? resolve(port) : reject(new Error('no port')))); + }); + }); +} + +export interface RunningServer { + /** `http://127.0.0.1:<port>` — open a tab here. */ + url: string; + port: number; + /** The temp dir holding game.json / settings.json / seats.json. */ + savesDir: string; + child: ChildProcess; + /** SIGKILL the server (crash simulation). */ + kill(): Promise<void>; + /** SIGKILL, then report the exit code. */ + killAndWait(): Promise<number>; +} + +export interface StartServerOptions { + /** Reuse an existing saves dir (restart mid-game). */ + savesDir?: string; + /** Bind a specific port (restart must keep the old port). */ + port?: number; +} + +/** + * Starts the server on a free port (or [opts.port]) with a fresh saves dir + * (or [opts.savesDir]) and resolves once `/healthz` answers. + */ +export async function startServer( + opts: StartServerOptions = {} +): Promise<RunningServer> { + await ensureServerBinary(); + if (!existsSync(WEB_DIST)) { + throw new Error( + `web/dist missing — run \`npm run build\` in ${WEB_DIST} first` + ); + } + const port = opts.port ?? (await freePort()); + const savesDir = + opts.savesDir ?? mkdtempSync(path.join(tmpdir(), 'xhaven-e2e-')); + + const child = spawn( + BINARY, + [`--port=${port}`, `--static-dir=${WEB_DIST}`, `--saves-dir=${savesDir}`], + { cwd: SERVER_DIR } + ); + let logs = ''; + child.stdout?.on('data', (d) => (logs += String(d))); + child.stderr?.on('data', (d) => (logs += String(d))); + + try { + await waitForHttp(`http://127.0.0.1:${port}/healthz`, 90_000); + } catch (err) { + child.kill('SIGKILL'); + rmSync(savesDir, { recursive: true, force: true }); + throw new Error(`server failed to start on port ${port}:\n${logs}\n${String(err)}`); + } + + return { + url: `http://127.0.0.1:${port}`, + port, + savesDir, + child, + kill: () => new Promise((resolve) => { + // Already dead (e.g. the spec killed it): nothing to wait for. + if (child.exitCode !== null || child.signalCode !== null) { + resolve(); + return; + } + child.once('exit', () => resolve()); + child.kill('SIGKILL'); + }), + killAndWait: () => + new Promise<number>((resolve) => { + if (child.exitCode !== null || child.signalCode !== null) { + resolve(child.exitCode ?? -1); + return; + } + child.once('exit', (code) => resolve(code ?? -1)); + child.kill('SIGKILL'); + }) + }; +} + +/** Polls [url] until it answers 2xx (or the timeout elapses). */ +export async function waitForHttp(url: string, timeoutMs: number): Promise<void> { + const deadline = Date.now() + timeoutMs; + for (;;) { + try { + const res = await fetch(url); + if (res.ok) return; + } catch { + // not up yet + } + if (Date.now() > deadline) { + throw new Error(`timed out waiting for ${url}`); + } + await new Promise((r) => setTimeout(r, 200)); + } +} + +/** Removes a stale cached binary (used by `npm run e2e:clean`). */ +export function cleanCache(): void { + rmSync(CACHE_DIR, { recursive: true, force: true }); +} |
