feat(server): map import CLI, pulled forward to M4 (#79)
Slice a PNG/WebP map into the gate's <x>_<y>.png tree under <state>/tiles/<scene>/v<art_version>/ and update the one scene row (w, h, tile_size, art_version); a re-import grows art_version so clients never serve stale tiles. The state-dir lock keeps a running server out (it loads the scene at startup), so stop/import/restart. Decoding is ImageMagick from the root devbox with a disk-backed pixel cache (-limit memory/map), keeping a 16384 px source memory-sane; no Nim/npm image dependency and the FIXED stack is unchanged. The black-box harness covers the tile geometry, scene row, restart pickup through the gate, re-import bump and every refused-import case. Records the M6 -> M4 move in DESIGN 3.3/11.1/13 and DESIGN-history, and documents the CLI plus the 16384 px/50-token recipe in README.
This commit is contained in:
+5
-1
@@ -31,7 +31,7 @@ export const GROUPS = {
|
||||
],
|
||||
},
|
||||
tiles: {
|
||||
files: ['tiles.test.mjs', 'oneway.test.mjs'],
|
||||
files: ['tiles.test.mjs', 'oneway.test.mjs', 'import.test.mjs'],
|
||||
evidence: [
|
||||
{ file: 'tiles.test.mjs',
|
||||
test: 'tile gate: leak check (d) matches the independent explored oracle',
|
||||
@@ -43,6 +43,10 @@ export const GROUPS = {
|
||||
{ file: 'tiles.test.mjs',
|
||||
test: 'tile gate: revocation is immediate and sessions survive a restart (#65)',
|
||||
minAsserts: 6, requires: ['rawUpgrade'] },
|
||||
// #79: the map import CLI writes the tree this gate parses, and a restarted server serves it.
|
||||
{ file: 'import.test.mjs',
|
||||
test: 'map import CLI: a fixture slices into v1 tiles, the scene row and a 200 through the gate',
|
||||
minAsserts: 12, requires: ['runImport'] },
|
||||
{ file: 'oneway.test.mjs',
|
||||
test: 'one-way sight: the blind side sees nothing across, the seeing side does (#58)',
|
||||
minAsserts: 12, requires: ['withOneWayStack'] },
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
// #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 os from 'node:os'
|
||||
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: 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/)
|
||||
|
||||
const ghost = path.join(os.tmpdir(), `fffvtt-absent-${process.pid}-${Date.now()}`)
|
||||
const absent = runImport(ghost, [`--image=${img}`])
|
||||
assert.notEqual(absent.status, 0)
|
||||
assert.match(absent.stderr, /does not exist/)
|
||||
assert.equal(fs.existsSync(ghost), false, 'an absent state dir is not created')
|
||||
|
||||
const empty = makeStateDir()
|
||||
const noDb = runImport(empty, [`--image=${img}`])
|
||||
assert.notEqual(noDb.status, 0)
|
||||
assert.match(noDb.stderr, /no state\.db/)
|
||||
assert.equal(fs.existsSync(path.join(empty, 'tiles')), false)
|
||||
fs.rmSync(empty, { recursive: true, force: true })
|
||||
|
||||
// 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 })
|
||||
}
|
||||
})
|
||||
+26
-9
@@ -36,29 +36,46 @@ function chunk(type, data) {
|
||||
|
||||
// A solid-colour 8-bit RGB PNG of `size` x `size` (filter 0 on every scanline).
|
||||
export function pngBytes(size, rgb) {
|
||||
return pngBytesWH(size, size, () => rgb)
|
||||
}
|
||||
|
||||
// A width x height 8-bit RGB PNG; `colourAt(x, y)` returns [r,g,b] (filter 0 on every scanline).
|
||||
export function pngBytesWH(width, height, colourAt) {
|
||||
const ihdr = Buffer.alloc(13)
|
||||
ihdr.writeUInt32BE(size, 0)
|
||||
ihdr.writeUInt32BE(size, 4)
|
||||
ihdr.writeUInt32BE(width, 0)
|
||||
ihdr.writeUInt32BE(height, 4)
|
||||
ihdr[8] = 8 // bit depth
|
||||
ihdr[9] = 2 // colour type: truecolour (RGB)
|
||||
ihdr[10] = 0 // compression
|
||||
ihdr[11] = 0 // filter
|
||||
ihdr[12] = 0 // interlace
|
||||
const row = Buffer.alloc(1 + size * 3)
|
||||
for (let x = 0; x < size; x++) {
|
||||
row[1 + x * 3] = rgb[0]
|
||||
row[2 + x * 3] = rgb[1]
|
||||
row[3 + x * 3] = rgb[2]
|
||||
const rows = []
|
||||
for (let y = 0; y < height; y++) {
|
||||
const row = Buffer.alloc(1 + width * 3)
|
||||
for (let x = 0; x < width; x++) {
|
||||
const rgb = colourAt(x, y)
|
||||
row[1 + x * 3] = rgb[0]
|
||||
row[2 + x * 3] = rgb[1]
|
||||
row[3 + x * 3] = rgb[2]
|
||||
}
|
||||
rows.push(row)
|
||||
}
|
||||
const raw = Buffer.concat(Array.from({ length: size }, () => row))
|
||||
return Buffer.concat([
|
||||
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
|
||||
chunk('IHDR', ihdr),
|
||||
chunk('IDAT', zlib.deflateSync(raw, { level: 6 })),
|
||||
chunk('IDAT', zlib.deflateSync(Buffer.concat(rows), { level: 6 })),
|
||||
chunk('IEND', Buffer.alloc(0)),
|
||||
])
|
||||
}
|
||||
|
||||
// The width/height of a PNG file from its IHDR (the import test checks the sliced geometry).
|
||||
export function pngSize(file) {
|
||||
const buf = fs.readFileSync(file)
|
||||
if (!isPng(buf) || buf.length < 24) throw new Error(`${file}: not a PNG`)
|
||||
return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) }
|
||||
}
|
||||
|
||||
|
||||
export function isPng(buf) {
|
||||
return Buffer.isBuffer(buf) && buf.length > 8 &&
|
||||
buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))
|
||||
|
||||
Reference in New Issue
Block a user