// Isolated server for the Node harnesses (ported from prototype-server-vision/tools/withserver.sh). // Own state dir, own port, never a live session: the server is the real binary, built from the // working tree, and its stdout/stderr land in /server.log so a check can grep them. import { spawn, spawnSync } from 'node:child_process' import fs from 'node:fs' import os from 'node:os' import path from 'node:path' import { baseUrl, freePort, join, openWs, projectRoot, refuseLivePort, sleep } from './lib.mjs' const SERVER_BIN = path.join(projectRoot, 'run', 'test', 'server') function nimblePkgs() { const nimbleDir = process.env.NIMBLE_DIR ?? path.join(projectRoot, '.devbox', 'nimble') return path.join(nimbleDir, 'pkgs2') } let builtAt = null export function buildServer() { if (builtAt) return builtAt fs.mkdirSync(path.dirname(SERVER_BIN), { recursive: true }) const args = ['c', '--hints:off', '--mm:orc', `--nimblePath:${nimblePkgs()}`, `-o:${SERVER_BIN}`, path.join('server', 'main.nim')] const r = spawnSync('nim', args, { cwd: projectRoot, encoding: 'utf8' }) if (r.status !== 0) throw new Error(`nim c server/main.nim failed:\n${r.stdout}\n${r.stderr}`) builtAt = SERVER_BIN return builtAt } export function makeStateDir(prefix = 'fffvtt-') { return fs.mkdtempSync(path.join(process.env.TMPDIR ?? os.tmpdir(), prefix)) } const hasExited = child => child.exitCode !== null || child.signalCode !== null // Ready means *this* process answers /healthz, not merely that something listens on the port. async function waitForHealth(handle) { const deadline = Date.now() + 30000 let last = 'no response' while (Date.now() < deadline) { if (hasExited(handle.child)) { throw new Error(`server exited (code=${handle.child.exitCode}, signal=${handle.child.signalCode})`) } try { const r = await fetch(`${handle.origin}/healthz`) if (r.status === 200 && (await r.text()) === '{"status":"ok"}') return last = `status ${r.status}` } catch (e) { last = e.message } await sleep(50) } throw new Error(`timed out waiting for /healthz: ${last}`) } // Starts the server and waits for /healthz. Resolves to a handle; stopServer() tears it down. export async function startServer(opts = {}) { const ownStateDir = opts.stateDir === undefined const stateDir = opts.stateDir ?? makeStateDir() const args = opts.args ?? [] const bin = buildServer() const port = opts.port ?? await freePort() refuseLivePort(port) fs.mkdirSync(stateDir, { recursive: true }) const logPath = path.join(stateDir, 'server.log') const logFd = fs.openSync(logPath, 'a') const child = spawn(bin, [`--port=${port}`, `--state-dir=${stateDir}`, `--public-origin=${baseUrl(port)}`, ...args], { cwd: projectRoot, stdio: ['ignore', logFd, logFd] }) const handle = { port, origin: baseUrl(port), stateDir, dbPath: path.join(stateDir, 'state.db'), logPath, child, log: () => fs.readFileSync(logPath, 'utf8'), } try { await waitForHealth(handle) } catch (e) { await stopServer(handle, logFd) const tail = `server did not come up: ${e.message}\n--- ${logPath} ---\n${handle.log()}` if (ownStateDir) fs.rmSync(stateDir, { recursive: true, force: true }) throw new Error(tail) } handle.logFd = logFd return handle } export async function stopServer(handle, logFd = handle.logFd) { // A process killed by a signal keeps exitCode null and sets signalCode, so test both. if (!hasExited(handle.child)) { handle.child.kill('SIGTERM') const deadline = Date.now() + 5000 while (!hasExited(handle.child) && Date.now() < deadline) await sleep(25) if (!hasExited(handle.child)) handle.child.kill('SIGKILL') } if (logFd !== undefined && logFd !== null) { try { fs.closeSync(logFd) } catch {} } } export async function withServer(fn, opts = {}) { const handle = await startServer(opts) try { return await fn(handle) } finally { await stopServer(handle) if (opts.keepState !== true && opts.stateDir === undefined) { fs.rmSync(handle.stateDir, { recursive: true, force: true }) } } } // --------------------------------------------------------------------------------------------- // A server with the GM key already made (#17/#18 harnesses). Kept here, next to the lifecycle, // so the black-box test files share one copy. const KEY_LINE = /GM key(?: \(new\))?: ([A-Z0-9-]+)/ // Runs `fff-vtt gm-key` against a state dir (the CLI is part of the product, so it is the source // of the GM key in every harness). export function runGmKey(stateDir, extra = []) { const r = spawnSync(buildServer(), ['gm-key', `--state-dir=${stateDir}`, ...extra], { encoding: 'utf8' }) return { status: r.status, stdout: r.stdout, stderr: r.stderr } } // The key line of a `gm-key` run: "GM key: XXXX-..." or "GM key (new): XXXX-...". export function parseGmKey(stdout) { const m = KEY_LINE.exec(stdout) if (!m) throw new Error(`no GM key in output: ${stdout}`) return m[1] } // The GM key of a state dir, created on first call and stable afterwards. export function gmKeyOf(stateDir) { const r = runGmKey(stateDir) if (r.status !== 0) throw new Error(`gm-key failed: ${r.stderr}`) return parseGmKey(r.stdout) } // A fresh state dir, its GM key and a running server; the dir is removed afterwards. export async function withGmServer(fn) { const stateDir = makeStateDir() const gmKey = gmKeyOf(stateDir) const s = await startServer({ stateDir }) try { return await fn(s, gmKey, stateDir) } finally { await stopServer(s) fs.rmSync(stateDir, { recursive: true, force: true }) } } // POST /join with a key that must work, returning the cookie. export async function signIn(origin, key) { const r = await join(origin, key) if (r.status !== 303) throw new Error(`join with a valid key: ${r.status}`) if (!r.cookie) throw new Error('no session cookie') return r } // {cookie, ws}: a signed-in WebSocket client of that key. export async function openAs(origin, key) { const { cookie } = await signIn(origin, key) const ws = await openWs(origin, cookie) return { cookie, ws } }