Files
FFF_vtt_frozen/tools/import.test.mjs
T
SirStone 9c7f9de910 feat(m4): playtest friction: perf overlay, fresh import, token seed (#82)
Opt-in ?perf=1 overlay (fps, frame p50/p95, JS p50/p95, tokens, zoom; no node or ticker work when off). fff-vtt import creates and migrates a fresh/empty state dir through the shared server startup path; devbox run serve gains --image. devbox run seed creates deterministic labelled NPC tokens over the real WS (idempotent rerun, --replace), and the GM token form defaults X/Y to the viewport centre.
2026-11-21 17:20:05 +01:00

232 lines
11 KiB
JavaScript

// #79: the map import CLI (DESIGN 11.1 "Map import", 3.3, 13 M4; pulled forward from M6). This is
// the black-box harness for the offline command, in the same style as the other tools/*.test.mjs:
// it runs the real binary's `import` subcommand against an isolated state dir, inspects the tile
// tree the gate parses, then starts the real server (+ test nginx, 11.1) and proves a player with
// explored cells is served a new tile through the gate. It also pins the re-import art_version bump
// and the "refused import changes nothing" cases (bad image/format, wrong scene, bad tile size,
// absent state dir, no schema, and the state-dir lock held by a running server).
import test from 'node:test'
import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
import { spawnSync } from 'node:child_process'
import { createPlayer, freePort, httpsBaseUrl, namePlayer } from './lib.mjs'
import { buildServer, gmKeyOf, makeStateDir, openAs, startServer, stopServer } from './withserver.mjs'
import { startTestNginx, stopTestNginx } from './nginx.mjs'
import { isPng, pngBytesWH, pngSize } from './tilefixture.mjs'
function runImport(stateDir, args) {
const r = spawnSync(buildServer(), ['import', `--state-dir=${stateDir}`, ...args],
{ encoding: 'utf8' })
return { status: r.status, stdout: r.stdout, stderr: r.stderr }
}
// A 256x192 fixture: 4x3 tiles at 64 px, every pixel's colour derived from its coordinates, so the
// source is real image data (not a blank canvas) and the slice positions are distinct files.
function writeFixtureImage(file) {
fs.writeFileSync(file, pngBytesWH(256, 192, (x, y) => [x & 0xff, y & 0xff, 128]))
return file
}
function tileNames(dir) {
return fs.readdirSync(dir).filter(n => n.endsWith('.png')).sort()
}
async function withGateStack(stateDir, fn) {
const nginxPort = await freePort()
const s = await startServer({ stateDir, publicOrigin: httpsBaseUrl(nginxPort) })
let ngx
try {
ngx = await startTestNginx({ backendPort: s.port, stateDir, port: nginxPort })
return await fn({ s, ngx })
} finally {
await stopTestNginx(ngx)
await stopServer(s)
}
}
async function tileStatus(origin, version, x, y, cookie) {
const r = await fetch(`${origin}/tiles/1/v${version}/${x}_${y}.png`, { headers: { Cookie: cookie } })
return { status: r.status, body: Buffer.from(await r.arrayBuffer()) }
}
// A GM, a named player and one vision token at (30, 30) with radius 100: tile 0_0 is explored,
// tile 3_2 is not. Returns the connections the gate assertions use.
async function sceneWithPlayer(origin, gmKey) {
const gm = await openAs(origin, gmKey)
await gm.ws.waitText('hello')
await gm.ws.waitText('walls')
const player = await createPlayer(gm.ws)
await namePlayer(origin, player.key, 'Alice')
const created = await gm.ws.request({ t: 'token.create', scene: 1, kind: 'pc', pos: [30, 30],
flags: { vision: true }, vision_radius: 100,
controller: player.id, descriptive_name: 'Alice',
actual_name: 'Alice' })
assert.equal(created.ok, true, JSON.stringify(created))
const seen = await openAs(origin, player.key)
await seen.ws.waitText('hello')
await seen.ws.waitFor(m => m.t === 'explored' && m.full === true)
return { gm, seen, player }
}
test('map import CLI: a fixture slices into v1 tiles, the scene row and a 200 through the gate', async () => {
const stateDir = makeStateDir()
const gmKey = gmKeyOf(stateDir)
const img = writeFixtureImage(path.join(stateDir, 'map.png'))
let playerKey
try {
const first = runImport(stateDir, [`--image=${img}`, '--tile-size=64'])
assert.equal(first.status, 0, first.stderr)
assert.match(first.stdout, /256x192 px, tile 64 px, 4x3 tiles/)
const dir1 = path.join(stateDir, 'tiles', '1', 'v1')
const names = tileNames(dir1)
assert.deepEqual(names, [
'0_0.png', '0_1.png', '0_2.png', '1_0.png', '1_1.png', '1_2.png',
'2_0.png', '2_1.png', '2_2.png', '3_0.png', '3_1.png', '3_2.png',
], 'the tree is the gate grammar: <x>_<y>.png, row-major origin at the world origin')
for (const n of names) assert.deepEqual(pngSize(path.join(dir1, n)), { width: 64, height: 64 })
assert.equal(fs.readdirSync(path.join(stateDir, 'tiles', '1')).some(n => n.startsWith('.import-')),
false, 'no temporary directory is left behind')
await withGateStack(stateDir, async ({ ngx }) => {
const { gm, seen, player } = await sceneWithPlayer(ngx.origin, gmKey)
playerKey = player.key
const hello = gm.ws.messages.find(m => m.t === 'hello' && m.scene)
assert.equal(hello.scene.w, 256, 'the scene row follows the image width')
assert.equal(hello.scene.h, 192, 'the scene row follows the image height')
assert.equal(hello.scene.tile_size, 64, 'tile_size is the import argument (64 px fallback)')
assert.equal(hello.scene.art_version, 1, 'a first import keeps the seeded version')
const allowed = await tileStatus(ngx.origin, 1, 0, 0, seen.cookie)
assert.equal(allowed.status, 200, 'a player with an explored overlapping cell gets the tile')
assert.ok(isPng(allowed.body), 'nginx serves the imported tile bytes through the internal alias')
assert.equal((await tileStatus(ngx.origin, 1, 3, 2, seen.cookie)).status, 403,
'an unexplored tile is still refused')
assert.equal((await tileStatus(ngx.origin, 1, 3, 2, gm.cookie)).status, 200,
'the GM is always allowed an in-range tile')
assert.equal((await tileStatus(ngx.origin, 2, 0, 0, seen.cookie)).status, 404,
'a version that is not the scene art_version does not exist')
gm.ws.close(); seen.ws.close()
})
// Re-import: the existing v1 art means the scene must advertise v2, so no client cache serves
// the old tiles. v1 stays on disk (cleanup is M6), and the restarted server serves v2.
const second = runImport(stateDir, [`--image=${img}`, '--tile-size=64'])
assert.equal(second.status, 0, second.stderr)
assert.match(second.stdout, /art_version 2/)
assert.equal(tileNames(path.join(stateDir, 'tiles', '1', 'v2')).length, 12)
assert.equal(tileNames(path.join(stateDir, 'tiles', '1', 'v1')).length, 12,
'the previous version is untouched')
await withGateStack(stateDir, async ({ ngx }) => {
const gm = await openAs(ngx.origin, gmKey)
await gm.ws.waitText('hello')
const hello = gm.ws.messages.find(m => m.t === 'hello' && m.scene)
assert.equal(hello.scene.art_version, 2, 'a restart loads the re-imported scene row')
const signed = await openAs(ngx.origin, playerKey)
await signed.ws.waitText('hello')
const allowed = await tileStatus(ngx.origin, 2, 0, 0, signed.cookie)
assert.equal(allowed.status, 200, 'the persisted explored grid still allows the new tile')
assert.ok(isPng(allowed.body))
assert.equal((await tileStatus(ngx.origin, 1, 0, 0, signed.cookie)).status, 404,
'the stale version is no longer the scene art_version')
gm.ws.close(); signed.ws.close()
})
} finally {
fs.rmSync(stateDir, { recursive: true, force: true })
}
})
test('map import CLI: a fresh/empty state dir is created, migrated and servable (#82)',
async () => {
const root = makeStateDir()
const stateDir = path.join(root, 'fresh')
const img = writeFixtureImage(path.join(root, 'map.png'))
try {
assert.equal(fs.existsSync(stateDir), false, 'the state dir starts absent')
const imported = runImport(stateDir, [`--image=${img}`, '--tile-size=64'])
assert.equal(imported.status, 0, imported.stderr)
assert.match(imported.stderr, /created\/migrated .*schema step/)
assert.match(imported.stdout, /256x192 px, tile 64 px, 4x3 tiles/)
assert.equal(fs.existsSync(path.join(stateDir, 'state.db')), true, 'the DB is created')
assert.equal(tileNames(path.join(stateDir, 'tiles', '1', 'v1')).length, 12,
'the imported tile tree exists without a prior server or gm-key run')
const gmKey = gmKeyOf(stateDir)
const s = await startServer({ stateDir })
try {
const gm = await openAs(s.origin, gmKey)
const hello = await gm.ws.waitText('hello')
assert.equal(hello.scene.w, 256, 'the server serves the imported scene')
assert.equal(hello.scene.h, 192)
assert.equal(hello.scene.tile_size, 64)
gm.ws.close()
} finally {
await stopServer(s)
}
} finally {
fs.rmSync(root, { recursive: true, force: true })
}
})
test('map import CLI: every refused import exits non-zero with a message and changes nothing',
async () => {
const stateDir = makeStateDir()
gmKeyOf(stateDir)
const img = writeFixtureImage(path.join(stateDir, 'map.png'))
const tiles = path.join(stateDir, 'tiles')
const gif = path.join(stateDir, 'tiny.gif')
fs.writeFileSync(gif, Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', 'base64'))
const corrupt = path.join(stateDir, 'corrupt.png')
fs.writeFileSync(corrupt, 'not an image')
try {
const cases = [
[[`--image=${path.join(stateDir, 'missing.png')}`], /does not exist/],
[[`--image=${gif}`], /unsupported format GIF/],
[[`--image=${corrupt}`], /cannot read image/],
[[`--image=${img}`, '--tile-size=48'], /multiple of the scene's explored cell/],
[[`--image=${img}`, '--tile-size=0'], /must be positive/],
[[`--image=${img}`, '--scene=2'], /exactly one scene, id 1/],
[[`--image=${img}`, '--tile-size=abc'], /whole number/],
[[], /--image is required/],
]
for (const [args, message] of cases) {
const r = runImport(stateDir, args)
assert.notEqual(r.status, 0, `must fail: ${args.join(' ')}`)
assert.match(r.stderr, message, `clear message for: ${args.join(' ')}`)
assert.equal(fs.existsSync(tiles), false, `nothing written for: ${args.join(' ')}`)
}
const help = runImport(stateDir, ['--help'])
assert.equal(help.status, 0, help.stderr)
assert.match(help.stdout, /--image=<path>/)
assert.match(help.stdout, /state-dir lock is refused/)
// An unreadable DB (the state-dir contents cannot be opened) is a clear runtime error, not a
// migration attempt or a partial import.
const dbFile = path.join(stateDir, 'state.db')
fs.chmodSync(dbFile, 0o000)
try {
const unreadable = runImport(stateDir, [`--image=${img}`])
assert.notEqual(unreadable.status, 0)
assert.match(unreadable.stderr, /cannot open/)
assert.equal(fs.existsSync(tiles), false)
} finally {
fs.chmodSync(dbFile, 0o600)
}
// The state-dir lock of 3.2/11.1: a live server blocks the import (like gm-key --new), so a
// running process cannot keep serving the old in-memory scene while the row changes.
const s = await startServer({ stateDir })
try {
const locked = runImport(stateDir, [`--image=${img}`, '--tile-size=64'])
assert.equal(locked.status, 3, locked.stderr)
assert.match(locked.stderr, /server is running.*state-dir lock held/)
assert.equal(fs.existsSync(tiles), false, 'a locked import writes no tile')
} finally {
await stopServer(s)
}
} finally {
fs.rmSync(stateDir, { recursive: true, force: true })
}
})