// 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, 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 }) } } }