Every Nim test file and every Node test file is already isolated (own temp state dir, free ports, own server/nginx), so run them FFF_TEST_JOBS at a time (default half the cores, capped at 8) instead of one at a time. The real server (clean, leakfault, dispfault) and the leak checker are built once per source+flags and shared across the parallel files; nimcaches are worktree-local so two checkouts cannot race on them. The 22 independent fault cases are sharded across processes. The wall-clock gate files (persistence, tiles; e2e map/fog/fogbench/ perf) still run alone first so their budgets are not measured under the suite's own load. No test or assertion changes.
178 lines
7.2 KiB
JavaScript
178 lines
7.2 KiB
JavaScript
// Isolated server for the Node harnesses (ported from docs/archive/prototypes/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 <stateDir>/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, cachedNimBuild, 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')
|
|
}
|
|
|
|
const builtCache = new Map()
|
|
|
|
// Build the real binary from the working tree. `defines` adds `-d:` flags (a leak-fault build,
|
|
// DESIGN 10.3); each variant lands in its own file so the clean build is never overwritten.
|
|
// The build is cached by source+flags and shared across the concurrently-running test files
|
|
// (lib.mjs cachedNimBuild); a serial run pays each variant once, a parallel run pays nothing extra.
|
|
export function buildServer(opts = {}) {
|
|
const defines = opts.defines ?? []
|
|
const key = defines.join(',')
|
|
const out = opts.out ?? (defines.length === 0
|
|
? SERVER_BIN
|
|
: path.join(projectRoot, 'run', 'test', `server-${defines.join('-').replace(/[^A-Za-z0-9-]/g, '')}`))
|
|
if (builtCache.has(key)) return builtCache.get(key)
|
|
const cache = path.join(projectRoot, 'run', 'nimcache', path.basename(out))
|
|
const built = cachedNimBuild({
|
|
out,
|
|
roots: ['server'],
|
|
extra: `${defines.join(',')}\n${nimblePkgs()}\n`,
|
|
nimArgs: tmp => ['c', '--hints:off', '--mm:orc', `--nimblePath:${nimblePkgs()}`,
|
|
`--nimcache:${cache}`, ...defines.map(d => `-d:${d}`), `-o:${tmp}`,
|
|
path.join('server', 'main.nim')],
|
|
})
|
|
builtCache.set(key, built)
|
|
return built
|
|
}
|
|
|
|
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.
|
|
// `defines` selects a build variant (e.g. a -d:leakfault build), `env` extra environment for it,
|
|
// `publicOrigin` overrides the configured origin (a test nginx in front of the server).
|
|
export async function startServer(opts = {}) {
|
|
const ownStateDir = opts.stateDir === undefined
|
|
const stateDir = opts.stateDir ?? makeStateDir()
|
|
const args = opts.args ?? []
|
|
const bin = opts.bin ?? buildServer({ defines: opts.defines })
|
|
const port = opts.port ?? await freePort()
|
|
const publicOrigin = opts.publicOrigin ?? baseUrl(port)
|
|
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=${publicOrigin}`, ...args],
|
|
{ cwd: projectRoot, stdio: ['ignore', logFd, logFd],
|
|
env: { ...process.env, ...(opts.env ?? {}) } })
|
|
const handle = {
|
|
port, origin: baseUrl(port), publicOrigin, 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 = [], bin = buildServer()) {
|
|
const r = spawnSync(bin, ['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, bin = buildServer()) {
|
|
const r = runGmKey(stateDir, [], bin)
|
|
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 }
|
|
}
|