// A minimal test nginx for the tile gate (DESIGN 3.3, 10.1 "withserver + M3 test nginx", 11.1; // M3 slice 9 / #24). nginx itself is a devbox package (devbox.json), never a global install: the // harness starts it on a free loopback port with a config generated at test time under the server's // state dir, so nothing about a run (ports, state paths) is committed. // // The vhost shape mirrors the production one of 11.1 that this slice has to prove: // /join -> the backend (`access_log off`, no-referrer header) // /tiles/ -> the backend, which decides and answers X-Accel-Redirect // /_tiles/ -> `internal` alias of /tiles/, so only an internal redirect reaches it // /ws -> the backend upgrade // The `/healthz` proxy is the readiness probe for the proxy itself. import { spawn } from 'node:child_process' import fs from 'node:fs' import net from 'node:net' import path from 'node:path' import { sleep } from './lib.mjs' function config({ prefix, port, backendPort, stateDir }) { const temp = p => path.join(prefix, p) // `alias` needs the tiles root with its trailing slash; state dirs are harness temp dirs, so no // quoting surprises (nginx does not take a quoted path here). const tilesRoot = path.join(stateDir, 'tiles') return `# generated by tools/nginx.mjs; test only daemon off; worker_processes 1; pid ${temp('nginx.pid')}; error_log ${temp('error.log')} warn; events { worker_connections 128; } http { access_log ${temp('access.log')}; client_body_temp_path ${temp('client_body')}; proxy_temp_path ${temp('proxy')}; fastcgi_temp_path ${temp('fastcgi')}; uwsgi_temp_path ${temp('uwsgi')}; scgi_temp_path ${temp('scgi')}; server_tokens off; default_type application/octet-stream; types { text/html html; image/png png; } map $http_upgrade $conn_up { default upgrade; '' close; } server { listen 127.0.0.1:${port}; server_name localhost; location = /healthz { proxy_pass http://127.0.0.1:${backendPort}; } location = /join { proxy_pass http://127.0.0.1:${backendPort}; access_log off; add_header Referrer-Policy no-referrer; } # Nim decides and answers X-Accel-Redirect; nginx only forwards the decision. location /tiles/ { proxy_pass http://127.0.0.1:${backendPort}; } location = /ws { proxy_pass http://127.0.0.1:${backendPort}; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $conn_up; proxy_read_timeout 1h; proxy_buffering off; } # Unreachable from outside: the internal directive rejects a direct request with 404. The alias # is /tiles//v/, the tree the X-Accel-Redirect names (3.3, 11.1). # Cache-Control: private rides from the Nim gate through the internal redirect (nginx passes it). location /_tiles/ { internal; alias ${tilesRoot}/; } } } ` } async function portIsFree(port) { return await new Promise(resolve => { const srv = net.createServer() srv.once('error', () => resolve(false)) srv.listen(port, '127.0.0.1', () => srv.close(() => resolve(true))) }) } // Starts nginx in front of `backendPort`. Resolves once the proxy answers /healthz. Stop it with // stopTestNginx(); the config and logs live under /nginx/ for post-mortem greps. export async function startTestNginx({ backendPort, stateDir, port }) { if (!(await portIsFree(port))) throw new Error(`test nginx port ${port} is already in use`) const prefix = path.join(stateDir, 'nginx') fs.mkdirSync(prefix, { recursive: true }) for (const d of ['client_body', 'proxy', 'fastcgi', 'uwsgi', 'scgi']) { fs.mkdirSync(path.join(prefix, d), { recursive: true }) } const confPath = path.join(prefix, 'nginx.conf') fs.writeFileSync(confPath, config({ prefix, port, backendPort, stateDir })) const logFd = fs.openSync(path.join(prefix, 'stderr.log'), 'a') const child = spawn('nginx', ['-p', prefix, '-c', confPath, '-e', path.join(prefix, 'error.log')], { stdio: ['ignore', logFd, logFd] }) const handle = { port, origin: `http://127.0.0.1:${port}`, prefix, confPath, child, log: () => { const read = f => { try { return fs.readFileSync(path.join(prefix, f), 'utf8') } catch { return '' } } return `--- access.log ---\n${read('access.log')}\n--- error.log ---\n${read('error.log')}\n` + `--- stderr.log ---\n${read('stderr.log')}` }, } const deadline = Date.now() + 15000 for (;;) { if (child.exitCode !== null) { fs.closeSync(logFd) throw new Error(`nginx exited (code=${child.exitCode})\n${handle.log()}`) } try { const r = await fetch(`${handle.origin}/healthz`) if (r.status === 200) break } catch {} if (Date.now() > deadline) { child.kill('SIGKILL') fs.closeSync(logFd) throw new Error(`nginx did not proxy /healthz\n${handle.log()}`) } await sleep(50) } handle.logFd = logFd return handle } export async function stopTestNginx(handle) { if (!handle) return if (handle.child.exitCode === null && handle.child.signalCode === null) { handle.child.kill('SIGTERM') const deadline = Date.now() + 5000 while (handle.child.exitCode === null && handle.child.signalCode === null && Date.now() < deadline) { await sleep(25) } if (handle.child.exitCode === null && handle.child.signalCode === null) handle.child.kill('SIGKILL') } if (handle.logFd !== undefined) { try { fs.closeSync(handle.logFd) } catch {} } }