diff options
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 }); +} |
