summaryrefslogtreecommitdiff
path: root/e2e/helpers/server.ts
blob: 8357421a56eb44ffce2802ee8b15b30ba4044902 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
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 });
}