Files
FFF_vtt_frozen/tools/serve.mjs
T
SirStone a79d809394 feat(m4): cap map images at Full HD and shrink on import (#85)
The owner fixed the map cap at 1920 px on the long side and 1080 px on the
short side (either orientation). fff-vtt import now shrinks a larger source
with ImageMagick Lanczos before tiling (alpha kept, proportions preserved,
no upscaling), prints `scaled WxH -> WxH`, and records the shrunk w/h; a
source at or below the cap is untouched, so the pixel-identity tests still
hold. A scene row already above the cap is not rewritten: the server logs
`map_above_cap` at startup and serve prints the re-import advice.

Docs: ADR-0023, DESIGN 3.3/5.3/8/11.1/13/14, TESTING 5.3/13, README,
HANDOFF-M4, client README. The M4 phone gate and the fogbench measurement
now use the Full HD maximum; the 16384 px / 262144-cell bench and test rows
stay as labelled server stress references. import-scale now proves a 16384²
input is shrunk to 1080x1080 (289 tiles at 64 px) quickly and bounded.

Part of #63, #85. #77 is blocked by this issue.
2026-11-21 22:37:34 +01:00

291 lines
13 KiB
JavaScript

#!/usr/bin/env node
// `devbox run serve` (M4 #80). tools/serve.sh builds the client dist and the server binary, then
// exec's this script: it starts nginx on the LAN address in front of the loopback server, prints
// the URL, the GM key and the certificate-trust steps, and blocks until Ctrl-C.
//
// Configuration (flags win over env, env wins over defaults):
// --host=<ip|0.0.0.0> FFF_VTT_LAN_HOST default: detected LAN IPv4
// --port=<n> FFF_VTT_LAN_PORT default: 8443 (nginx TLS listener)
// --state-dir=<path> FFF_VTT_STATE_DIR default: run/lan (persistent, never deleted)
// --dist=<path> FFF_VTT_LAN_DIST default: client/dist
// --server-bin=<path> FFF_VTT_SERVER_BIN default: run/fff-vtt
// --server-port=<n> FFF_VTT_SERVER_PORT default: a free loopback port
// --image=<file> FFF_VTT_LAN_IMAGE import this map before the server starts (#82);
// the import runs offline and refuses (exit 3) if a server holds the lock
// --tile-size=<px> FFF_VTT_LAN_TILE optional for --image (64 is the playtest fallback)
import { spawnSync } from 'node:child_process'
import fs from 'node:fs'
import path from 'node:path'
import { DatabaseSync } from 'node:sqlite'
import { DEFAULT_DIST, DEFAULT_LAN_PORT, DEFAULT_SERVER_BIN, DEFAULT_STATE_DIR,
detectLanIp, startLanServe } from './lanserve.mjs'
const USAGE = `usage: devbox run serve [-- --host=<ip>] [-- --port=<n>] [-- --state-dir=<path>]
[-- --image=<file> [-- --tile-size=<px>]] [-- --dry-run]
Starts the FFF_vtt server behind a TLS/HTTP2 nginx on the LAN. State, GM key and certificate
persist under the state dir (default ${DEFAULT_STATE_DIR}), so a session (and a trusted phone)
survives Ctrl-C and a restart. Env equivalents: FFF_VTT_LAN_HOST, FFF_VTT_LAN_PORT,
FFF_VTT_STATE_DIR.
--image imports a PNG/WebP map before starting (a fresh state dir is created and migrated first)
and then serves the imported scene; a server already holding the state-dir lock is refused (exit 3).
--dry-run parses and prints the effective options, then exits without building or starting anything.
Unknown options, a non-numeric port/tile size, and --tile-size without --image fail loudly (exit 1)
instead of being ignored: a silently dropped --image used to serve the default 4096 scene (#84).
`
const VALUE_OPTIONS = new Set(
['host', 'port', 'state-dir', 'dist', 'server-bin', 'server-port', 'image', 'tile-size'],
)
function parseArgs(argv) {
const opts = {}
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i]
if (arg === '-h' || arg === '--help') { process.stdout.write(USAGE); process.exit(0) }
const m = /^--([a-z-]+)(?:=(.*))?$/.exec(arg)
if (!m) throw new Error(`unexpected argument ${JSON.stringify(arg)} (see --help)`)
const key = m[1]
if (key === 'dry-run') {
if (m[2] !== undefined) throw new Error('--dry-run takes no value (see --help)')
opts.dryRun = true
continue
}
if (!VALUE_OPTIONS.has(key)) throw new Error(`unknown option --${key} (see --help)`)
let value = m[2]
if (value === undefined) {
if (i + 1 >= argv.length) throw new Error(`--${key}: missing value (see --help)`)
value = argv[++i]
}
if (key === 'host') opts.host = value
else if (key === 'port') opts.port = Number(value)
else if (key === 'state-dir') opts.stateDir = value
else if (key === 'dist') opts.distDir = value
else if (key === 'server-bin') opts.bin = value
else if (key === 'server-port') opts.serverPort = Number(value)
else if (key === 'image') opts.image = value
else if (key === 'tile-size') opts.tileSize = Number(value)
}
return opts
}
/** Flags that only make sense with an image, or that need numbers, fail instead of being ignored. */
function validate(opts) {
for (const [key, env] of [['port', 'FFF_VTT_LAN_PORT'], ['serverPort', 'FFF_VTT_SERVER_PORT'],
['tileSize', 'FFF_VTT_LAN_TILE']]) {
if (opts[key] === undefined) continue
if (!Number.isInteger(opts[key]) || opts[key] < 1) {
throw new Error(`${key}: expected a whole number >= 1, got ${JSON.stringify(opts[key])} ` +
`(--${key === 'serverPort' ? 'server-port' : key === 'tileSize' ? 'tile-size' : key} / ${env})`)
}
}
if (opts.tileSize !== undefined && !opts.image) {
throw new Error('--tile-size requires --image (it is the import tile size); ' +
'drop --tile-size or pass --image=<file>')
}
if (opts.image !== undefined && opts.image.trim() === '') {
throw new Error('--image: empty path (see --help)')
}
}
function envOptions() {
const env = process.env
const opts = {}
if (env.FFF_VTT_LAN_HOST) opts.host = env.FFF_VTT_LAN_HOST
if (env.FFF_VTT_LAN_PORT) opts.port = Number(env.FFF_VTT_LAN_PORT)
if (env.FFF_VTT_STATE_DIR) opts.stateDir = env.FFF_VTT_STATE_DIR
if (env.FFF_VTT_LAN_DIST) opts.distDir = env.FFF_VTT_LAN_DIST
if (env.FFF_VTT_SERVER_BIN) opts.bin = env.FFF_VTT_SERVER_BIN
if (env.FFF_VTT_SERVER_PORT) opts.serverPort = Number(env.FFF_VTT_SERVER_PORT)
if (env.FFF_VTT_LAN_IMAGE) opts.image = env.FFF_VTT_LAN_IMAGE
if (env.FFF_VTT_LAN_TILE) opts.tileSize = Number(env.FFF_VTT_LAN_TILE)
return opts
}
/**
* `--image`: run the offline import before the server exists. Import creates and migrates a fresh
* state dir through the server's startup path, and refuses (exit 3) while a server holds the lock,
* so `serve` never starts a stack on top of a half-imported scene.
*/
function importImage(opts, stateDir) {
const bin = path.resolve(opts.bin ?? DEFAULT_SERVER_BIN)
if (!fs.existsSync(bin)) {
throw new Error(`server binary missing at ${bin}: run \`devbox run serve\` (it builds the ` +
'server first), or pass --server-bin')
}
const args = ['import', `--state-dir=${stateDir}`, `--image=${path.resolve(opts.image)}`]
if (Number.isFinite(opts.tileSize)) args.push(`--tile-size=${opts.tileSize}`)
process.stdout.write(`serve: importing ${opts.image} before starting the server...\n`)
const r = spawnSync(bin, args, { stdio: 'inherit', cwd: process.cwd() })
if (r.error) throw r.error
if (r.status !== 0) {
const error = new Error(`map import failed (exit ${r.status}); the server was not started`)
error.exitCode = r.status ?? 1
throw error
}
}
// The Full HD map cap (FIXED owner decision 2026-11-21, #85); the server warns in its own log,
// this is the same warning on the console where the operator actually looks.
const CAP_LONG = 1920
const CAP_SHORT = 1080
function readSceneRow(stateDir) {
const dbFile = path.join(stateDir, 'state.db')
if (!fs.existsSync(dbFile)) return { text: 'fresh state: default 4096x4096, tile 32, art v1' }
let db
try {
db = new DatabaseSync(dbFile, { readOnly: true })
const row = db.prepare('SELECT w, h, tile_size, art_version FROM scene WHERE id = 1').get()
if (!row) return { text: `no scene row in ${dbFile}` }
return { row, text: `${row.w}x${row.h}, tile ${row.tile_size}, art v${row.art_version}` }
} catch (e) {
return { text: `unreadable ${dbFile} (${e.message})` }
} finally {
db?.close()
}
}
/** The map a no-image start will serve, read from the state db without starting anything. */
function describeScene(stateDir) {
return readSceneRow(stateDir).text
}
/** `--dry-run`: prove the `--` arguments reached this script, then exit without side effects. */
function printDryRun(opts, stateDir) {
const lines = [
'serve: dry-run (nothing built, imported or started)',
` host: ${opts.host ?? '<detected>'}${opts.host ? '' : ` (${detectLanIp() ?? 'none'})`}`,
` port: ${opts.port ?? DEFAULT_LAN_PORT}`,
` state-dir: ${stateDir}`,
` dist: ${path.resolve(opts.distDir ?? DEFAULT_DIST)}`,
` server-bin: ${path.resolve(opts.bin ?? DEFAULT_SERVER_BIN)}`,
` server-port: ${opts.serverPort ?? '<auto>'}`,
` image: ${opts.image ? path.resolve(opts.image) : '<none, keeping current map>'}`,
` tile-size: ${opts.tileSize ?? '<none>'}`,
]
if (!opts.image) {
lines.push(` current map: ${describeScene(stateDir)}`)
const { row } = readSceneRow(stateDir)
if (row && (Math.max(row.w, row.h) > CAP_LONG || Math.min(row.w, row.h) > CAP_SHORT)) {
lines.push(` WARNING: map is ${row.w}x${row.h}, above the Full HD cap ` +
`(at most ${CAP_LONG} px long side, ${CAP_SHORT} px short side); re-import to shrink.`)
}
}
process.stdout.write(lines.join('\n') + '\n')
}
function printStartup(handle) {
const { origin, gmKey, stateDir, certPath, distDir, serverPort, certRegenerated } = handle
const ip = handle.host
const lines = [
'',
'FFF_vtt playtest server (Ctrl-C stops nginx and the server)',
` URL: ${origin}`,
` GM key: ${gmKey}`,
` state: ${stateDir} (kept across restarts)`,
` cert: ${certPath}`,
` server: 127.0.0.1:${serverPort} (loopback only; nginx is the LAN face)`,
'',
`Open ${origin} on the phone (same Wi-Fi) and on the laptop.`,
'',
'Phone (Android Chrome), one-time per certificate:',
` 1. Open ${origin} -> "Advanced" -> "Proceed to ${ip} (unsafe)".`,
' 2. To drop the warning: push the certificate and install it as a user CA:',
` adb push ${certPath} /sdcard/Download/fff-vtt-lan.crt`,
' Settings > Security > Encryption & credentials > Install a certificate >',
' CA certificate > CA Certificate > fff-vtt-lan.crt > Install anyway.',
' Only the "Proceed" tap is required; installing the CA just silences the warning.',
'',
'Laptop, one-time per certificate:',
]
// The Debian steps are wrong on NixOS (no /usr/local/share/ca-certificates, no imperative
// update-ca-certificates): point at the declarative option instead. #84.
if (fs.existsSync('/etc/NIXOS')) {
lines.push(
` NixOS: security.pki.certificateFiles = [ "${certPath}" ];`,
' sudo nixos-rebuild switch (or home-manager switch)',
` Chrome: "Advanced" -> "Proceed to ${ip} (unsafe)" is enough for the playtest;`,
' the option above only silences the warning for every app.',
)
} else {
lines.push(
` Linux: sudo cp ${certPath} /usr/local/share/ca-certificates/fff-vtt-lan.crt`,
' sudo update-ca-certificates',
)
}
lines.push(
` macOS: sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${certPath}`,
' Firefox: Settings > Privacy & Security > Certificates > View Certificates >',
' Authorities > Import > select cert.pem > "Trust this CA to identify websites".',
' (Chrome/Edge on the laptop read the system store; Firefox keeps its own.)',
'',
)
if (certRegenerated) {
lines.push(`NOTE: the LAN address is new (${ip}); the certificate was regenerated. Trust it again.`, '')
}
if (!fs.existsSync(distDir)) {
lines.push(`WARNING: no client build at ${distDir}; "/" will 404 until it is built.`, '')
}
const { row } = readSceneRow(stateDir)
if (row && (Math.max(row.w, row.h) > CAP_LONG || Math.min(row.w, row.h) > CAP_SHORT)) {
lines.push(`WARNING: map is ${row.w}x${row.h}, above the Full HD cap ` +
`(at most ${CAP_LONG} px long side, ${CAP_SHORT} px short side); re-import to shrink.`, '')
}
lines.push('The certificate only names this LAN address; if the laptop\'s address changes,',
'`devbox run serve` regenerates it and prints these steps again.', '')
process.stdout.write(lines.join('\n') + '\n')
}
async function main() {
const opts = { ...envOptions(), ...parseArgs(process.argv.slice(2)) }
validate(opts)
if (!opts.host) {
const detected = detectLanIp()
if (detected) opts.host = detected
}
const stateDir = path.resolve(opts.stateDir ?? DEFAULT_STATE_DIR)
if (opts.dryRun) { printDryRun(opts, stateDir); return }
if (opts.image) importImage(opts, stateDir)
else {
process.stdout.write(`serve: no --image given, keeping current map (${describeScene(stateDir)})\n`)
}
const handle = await startLanServe({
stateDir,
host: opts.host,
port: opts.port ?? DEFAULT_LAN_PORT,
distDir: opts.distDir ?? DEFAULT_DIST,
bin: opts.bin ?? DEFAULT_SERVER_BIN,
serverPort: opts.serverPort,
})
printStartup(handle)
let stopping = false
const shutdown = async signal => {
if (stopping) return
stopping = true
process.stdout.write(`\n${signal}: stopping nginx and the server...\n`)
try {
await handle.stop()
process.stdout.write('stopped; state, GM key and certificate are on disk for the next run.\n')
process.exit(0)
} catch (e) {
process.stderr.write(`shutdown failed: ${e.stack ?? e}\n`)
process.exit(1)
}
}
process.on('SIGINT', () => { shutdown('SIGINT') })
process.on('SIGTERM', () => { shutdown('SIGTERM') })
process.on('uncaughtException', e => { process.stderr.write(`${e.stack ?? e}\n`); shutdown('error') })
process.on('unhandledRejection', e => {
process.stderr.write(`${(e && e.stack) ?? e}\n`); shutdown('error')
})
}
main().catch(e => {
process.stderr.write(`serve: ${e.stack ?? e}\n`)
process.exit(e.exitCode ?? 1)
})