diff --git a/tests/fixtures/scene.json b/tests/fixtures/scene.json index 4fc3501..4151e08 100644 --- a/tests/fixtures/scene.json +++ b/tests/fixtures/scene.json @@ -3,9 +3,7 @@ "w": 4096, "h": 4096 }, - "tileSize": 256, "visionRadius": 400, - "tokenRadius": 20, "exploredCell": 32, "walls": [ { @@ -871,7 +869,6 @@ ], "tokens": [ { - "id": "A", "kind": "player", "name": "Player A", "pos": [ @@ -881,7 +878,6 @@ "gmOnly": false }, { - "id": "B", "kind": "player", "name": "Player B", "pos": [ @@ -891,7 +887,6 @@ "gmOnly": false }, { - "id": "M1", "kind": "monster", "name": "Monster 1", "pos": [ @@ -901,7 +896,6 @@ "gmOnly": true }, { - "id": "M2", "kind": "monster", "name": "Monster 2", "pos": [ @@ -911,7 +905,6 @@ "gmOnly": true }, { - "id": "M3", "kind": "monster", "name": "Monster 3", "pos": [ @@ -921,7 +914,6 @@ "gmOnly": true }, { - "id": "M4", "kind": "monster", "name": "Monster 4", "pos": [ @@ -931,7 +923,6 @@ "gmOnly": true }, { - "id": "M5", "kind": "monster", "name": "Monster 5", "pos": [ @@ -941,7 +932,6 @@ "gmOnly": true }, { - "id": "M6", "kind": "monster", "name": "Monster 6", "pos": [ @@ -951,4 +941,4 @@ "gmOnly": true } ] -} \ No newline at end of file +} diff --git a/tests/tgeometry.nim b/tests/tgeometry.nim index ca17a26..7b187ee 100644 --- a/tests/tgeometry.nim +++ b/tests/tgeometry.nim @@ -199,6 +199,11 @@ type Scene = object tokens: seq[Vec] radius, cell, tokenRadius: float +const PrototypeTokenRadius = 20.0 + ## The prototype scene's scene-wide token radius. It is a *fixture* value since slice 10 (#25): + ## M3 has a per-token radius (5.6, #4) and no scene-wide fixture field, so the JSON no longer + ## carries one (nor its stale `tileSize`, nor index token ids). Only this seed test uses it. + proc loadScene(): Scene = # fixtures are copies of prototype-server-vision/data/scene.json; a missing file fails, never skips let j = parseFile(currentSourcePath().parentDir / "fixtures" / "scene.json") @@ -208,7 +213,7 @@ proc loadScene(): Scene = for t in j["tokens"]: result.tokens.add (t["pos"][0].getFloat, t["pos"][1].getFloat) result.radius = j["visionRadius"].getFloat result.cell = j["exploredCell"].getFloat - result.tokenRadius = j["tokenRadius"].getFloat + result.tokenRadius = PrototypeTokenRadius suite "seed": test "every token in seed sees itself and is not walled in": diff --git a/tools/groups.mjs b/tools/groups.mjs new file mode 100644 index 0000000..74d4f2d --- /dev/null +++ b/tools/groups.mjs @@ -0,0 +1,50 @@ +// The nine M3 acceptance groups of DESIGN 13 (FIXED by owner decision #12) and the test that proves +// each one. `devbox run test` runs every `tools/*.test.mjs`; this map is the checklist the finish +// line (#25) records in DESIGN 14, and tools/groups.test.mjs fails if a group's file or its named +// evidence test disappears. Slice-level test files that are not an accept group (smoke, walls, +// tokens, details, scene, wsheaders) still run; they are not listed here. +export const GROUPS = { + 'leak+fault': { + files: ['leak.test.mjs', 'fault.test.mjs'], + evidence: [ + ['leak.test.mjs', 'leak test ${subject}: the subject\'s whole view matches the GM\'s truth'], + ['fault.test.mjs', 'caught as exactly'], + ], + }, + tiles: { + files: ['tiles.test.mjs'], + evidence: [['tiles.test.mjs', 'tile gate: leak check (d) matches the independent explored oracle']], + }, + probing: { + files: ['probing.test.mjs'], + evidence: [['probing.test.mjs', 'probing over WS: walls beyond cap + radius change no reply']], + }, + protocol: { + files: ['protocol.test.mjs'], + evidence: [['protocol.test.mjs', 'an unknown type is refused, unknown fields are ignored']], + }, + auth: { + files: ['auth.test.mjs'], + evidence: [['auth.test.mjs', 'key.replace: old key and old sessions die']], + }, + 'characters and names': { + files: ['characters.test.mjs'], + evidence: [['characters.test.mjs', 'encountered: a sighting is kept under the name the player knows']], + }, + restart: { + files: ['restart.test.mjs'], + evidence: [['restart.test.mjs', 'restart: full state, all CRUD, before and after SIGTERM'], + ['restart.test.mjs', 'restart: full state, all CRUD, before and after SIGKILL']], + }, + persistence: { + files: ['persistence.test.mjs'], + evidence: [['persistence.test.mjs', 'explored round trip: a fresh connection gets the whole grid'], + ['persistence.test.mjs', 'migration: a schema-4 DB (fixture) migrates under the real binary']], + }, + logs: { + files: ['logs.test.mjs'], + evidence: [['logs.test.mjs', 'logs: no key, session cookie or session hash reaches the log']], + }, +} + +export const GROUP_COUNT = 9 diff --git a/tools/groups.test.mjs b/tools/groups.test.mjs new file mode 100644 index 0000000..8a2915b --- /dev/null +++ b/tools/groups.test.mjs @@ -0,0 +1,37 @@ +// The M3 acceptance checklist as a test: the nine groups of DESIGN 13 exist, each points at a real +// harness in tools/, and each carries the named test that proves it (DESIGN 14, #12 / #25). This +// fails if someone renames a group test or deletes a group file, so `devbox run test` cannot go +// green with a group silently unproven. +import test from 'node:test' +import assert from 'node:assert/strict' +import fs from 'node:fs' +import path from 'node:path' +import { GROUP_COUNT, GROUPS } from './groups.mjs' +import { projectRoot } from './lib.mjs' + +const tools = path.join(projectRoot, 'tools') + +test('M3 accept: the nine groups of DESIGN 13 are mapped to named harness tests', () => { + assert.deepEqual(Object.keys(GROUPS), [ + 'leak+fault', 'tiles', 'probing', 'protocol', 'auth', 'characters and names', 'restart', + 'persistence', 'logs', + ], 'the group names are the ones of DESIGN 13 (FIXED #12)') + assert.equal(Object.keys(GROUPS).length, GROUP_COUNT) + for (const [group, spec] of Object.entries(GROUPS)) { + for (const file of spec.files) { + const full = path.join(tools, file) + assert.ok(fs.existsSync(full), `${group}: ${file} exists`) + assert.ok(fs.statSync(full).size > 0, `${group}: ${file} is not empty`) + } + assert.ok(spec.evidence.length >= 1, `${group}: names its proving test`) + for (const [file, needle] of spec.evidence) { + const text = fs.readFileSync(path.join(tools, file), 'utf8') + assert.ok(text.includes(needle), `${group}: ${file} contains the test "${needle}"`) + } + } + // Every *group* harness is run by `tools/test.sh` (one glob over tools/*.test.mjs). + const globbed = fs.readdirSync(tools).filter(f => f.endsWith('.test.mjs')) + for (const spec of Object.values(GROUPS)) { + for (const file of spec.files) assert.ok(globbed.includes(file), `${file} is run by devbox run test`) + } +}) diff --git a/tools/logs.test.mjs b/tools/logs.test.mjs new file mode 100644 index 0000000..92f4123 --- /dev/null +++ b/tools/logs.test.mjs @@ -0,0 +1,144 @@ +// M3 slice 10 (#25): the "logs" acceptance group (DESIGN 11.3, 13 M3 group 9). +// +// Every key and every session value the test creates is grepped for in the server's whole log +// afterwards. The log is the real one the binary wrote to stdout (tools/withserver.mjs appends +// `/server.log`), across both runs, including the `gm-key --new` rotation: a secret from +// the first run must not resurface in the second. Session *hashes* are checked too (they are in the +// DB, they must never be in a log line either). +// +// The second test is the negative control: a `-d:leakfault` build with `LEAK_FAULT=keylog` writes a +// raw key to stdout, bypassing eventlog, and the same grep must find it. Without that, a log that +// was never captured, or a grep that matches nothing, would pass silently. +import test from 'node:test' +import assert from 'node:assert/strict' +import crypto from 'node:crypto' +import fs from 'node:fs' +import { createPlayer, join, openWs, rawWs, sleep } from './lib.mjs' +import { gmKeyOf, makeStateDir, openAs, parseGmKey, runGmKey, startServer, + stopServer } from './withserver.mjs' + +const sha256 = s => crypto.createHash('sha256').update(s).digest('hex') + +function assertClean(log, secrets, label) { + for (const { what, value } of secrets) { + assert.ok(value && value.length >= 8, `${label}: ${what} is a real secret`) + assert.equal(log.includes(value), false, + `${label}: the ${what} (${value}) appears in the log`) + } +} + +test('logs: no key, session cookie or session hash reaches the log', async () => { + const stateDir = makeStateDir() + const secrets = [] + const note = (what, value) => secrets.push({ what, value }) + + const gmKey1 = gmKeyOf(stateDir) + note('first GM key', gmKey1) + let s = await startServer({ stateDir }) + try { + // The GM signs in, creates two players (one named on two devices), reads a key, rotates a key, + // and removes the other player: every path that handles a secret. + const g = await openAs(s.origin, gmKey1) + note('GM session', g.cookie) + const alice = await createPlayer(g.ws) + note('Alice key', alice.key) + const bob = await createPlayer(g.ws) + note('Bob key', bob.key) + assert.equal((await g.ws.request({ t: 'key.show', id: alice.id })).key, alice.key) + const shown = await g.ws.request({ t: 'key.show', id: alice.id }) + note('shown key', shown.key) + + const aCookie = await join(s.origin, alice.key) + assert.equal(aCookie.status, 303) + note('Alice session 1', aCookie.cookie) + const aDevice = await join(s.origin, alice.key) + assert.equal(aDevice.status, 303, 'one key, several devices') + note('Alice session 2', aDevice.cookie) + // Named through the product path; its own sign-in is another session. + const named = await openWs(s.origin, aCookie.cookie) + await named.waitText('hello') + assert.equal((await named.request({ t: 'player.setname', name: 'Alice' })).ok, true) + await named.waitText('roster') + named.close() + + const replaced = await g.ws.request({ t: 'key.replace', id: alice.id }) + assert.equal(replaced.ok, true, JSON.stringify(replaced)) + note('replacement key', replaced.key) + assert.notEqual(replaced.key, alice.key) + assert.equal((await join(s.origin, alice.key)).status, 401, 'the old key is dead') + const a2 = await join(s.origin, replaced.key) + assert.equal(a2.status, 303) + note('Alice session 3 (new key)', a2.cookie) + + const bobConn = await openAs(s.origin, bob.key) + await bobConn.ws.waitText('hello') + note('Bob session', bobConn.cookie) + assert.equal((await g.ws.request({ t: 'player.remove', id: bob.id })).ok, true) + await bobConn.ws.closed + + // Requests that refuse a secret still must not log it. + const wrongKey = 'WRONG-WRONG-WRONG-WRONG-0000' + note('wrong key', wrongKey) + assert.equal((await join(s.origin, wrongKey)).status, 401) + const tile = await fetch(`${s.origin}/tiles/1/v1/0_0.png`) + assert.equal(tile.status, 403) + const mismatch = await rawWs(s.origin, { cookie: a2.cookie, proto: 2 }) + await mismatch.closed + const g2 = await openAs(s.origin, gmKey1) + g2.ws.sendText('this is not json') + await g2.ws.waitText('error') + assert.equal(g2.ws.messages.find(m => m.t === 'error').code, 'malformed') + g2.ws.close(); g.ws.close() + } finally { + await stopServer(s) + } + + // Rotate the GM key with the CLI (the server must be stopped: the instance lock), then serve + // again with the new key: the first key is dead but both must stay out of the log. + const rotated = runGmKey(stateDir, ['--new']) + assert.equal(rotated.status, 0, rotated.stderr) + const gmKey2 = parseGmKey(rotated.stdout) + note('rotated GM key', gmKey2) + assert.notEqual(gmKey2, gmKey1) + s = await startServer({ stateDir }) + try { + const g = await openAs(s.origin, gmKey2) + note('GM session after rotation', g.cookie) + assert.equal((await join(s.origin, gmKey1)).status, 401, 'the old GM key is dead') + assert.equal((await join(s.origin, gmKey2)).status, 303) + g.ws.close() + } finally { + await stopServer(s) + } + + const log = fs.readFileSync(`${stateDir}/server.log`, 'utf8') + assert.ok(log.length > 0, 'the product wrote a log') + for (const event of ['server_start', 'join_ok', 'key_created', 'key_replaced', 'player_removed']) { + assert.ok(log.includes(event), `the log holds the ${event} path (so the grep is over real lines)`) + } + assertClean(log, secrets, 'clean run') + // The session token itself is never stored, but its hash is: neither may be logged. + for (const { what, value } of secrets.filter(x => x.what.includes('session'))) { + const token = value.split('=')[1] + assert.equal(log.includes(sha256(token)), false, `${what}: the session hash is not logged`) + } + fs.rmSync(stateDir, { recursive: true, force: true }) +}) + +test('logs: the negative control finds a raw key when the server leaks one', async () => { + // Same grep, same capture: a fault build prints the key to stdout without eventlog. If this test + // passes, the clean run above is meaningful; if the grep breaks, this one fails. + const stateDir = makeStateDir() + const gmKey = gmKeyOf(stateDir) + const s = await startServer({ stateDir, defines: ['leakfault'], + env: { LEAK_FAULT: 'keylog' } }) + try { + assert.equal((await join(s.origin, gmKey)).status, 303) + await sleep(100) + const log = s.log() + assert.ok(log.includes(gmKey), `the leaked key must be visible to the grep; log:\n${log}`) + } finally { + await stopServer(s) + fs.rmSync(stateDir, { recursive: true, force: true }) + } +}) diff --git a/tools/mutation.sh b/tools/mutation.sh index 92e6413..c2faece 100755 --- a/tools/mutation.sh +++ b/tools/mutation.sh @@ -25,6 +25,9 @@ # slice 9 (#24): the canonical tile URL and the "any explored cell allows" gate # c1: a tile is allowed without any explored cell | c2: every overlapping cell is required # c3: an out-of-grid coordinate is accepted | c4: a leading-zero coordinate is canonical +# d3: scene.set accepts a patch with no field (slice 10, #25) +# slice 10 (#25): scene.set accepts a patch with no field at all +run d3 "scene.set accepts a patch with no field" server/world.nim 's/^ if not any: return none(ScenePatch)$/ discard/' "a patch with none is invalid" # Parallel: MUTATION_JOBS (default nproc/4) jobs, each in its own temp copy + nimcache; output collected, printed in fixed order. # Tests run with FFF_MUTATION=1 (iteration counts ~/10, see tests/testutil.nim scaled()); only test files holding an expected # test are run per mutation (control runs all). Debug build. Wrapped in systemd-inhibit (sleep:idle) when that works. @@ -183,7 +186,7 @@ run c4 "a leading-zero tile coordinate is canonical" server/tiles.nim "s/ if ra wait rc=0; : > "$LOG" -for id in control a b c d1 d2 e f g h i j k l m n o p q r s t u v w x y z z2 aa ab ac ad ae af ag ah ai aj ak al am an ao ap aq ar as at au av aw ax ay az b1 b2 b3 b4 c1 c2 c3 c4; do +for id in control a b c d1 d2 d3 e f g h i j k l m n o p q r s t u v w x y z z2 aa ab ac ad ae af ag ah ai aj ak al am an ao ap aq ar as at au av aw ax ay az b1 b2 b3 b4 c1 c2 c3 c4; do [ -f "$T/$id/res" ] && cat "$T/$id/res" >> "$LOG" if [ -f "$T/$id/verdict" ]; then tee -a "$LOG" < "$T/$id/verdict"; [ "$(cat "$T/$id/rc")" = 0 ] || rc=1 else echo "$id: NO RESULT (job killed?)" | tee -a "$LOG"; rc=1; fi diff --git a/tools/restart.test.mjs b/tools/restart.test.mjs new file mode 100644 index 0000000..df07446 --- /dev/null +++ b/tools/restart.test.mjs @@ -0,0 +1,232 @@ +// M3 slice 10 (#25): the "restart" acceptance group (DESIGN 10.1, 13 M3 group 7). +// +// A restart must bring back *identical state*, not just the single feature of one slice. This builds +// a world that exercises every CRUD path M3 has (walls and an open door, tokens with sizes, props in +// all three buckets and statuses, characters with props, a character reveal, a token reveal-all, a +// sighting in the encountered list, explored cells, players and their names), then compares what a +// fresh GM connection and a fresh player connection receive as their full 6.3 resync before and +// after the restart. SIGTERM and SIGKILL are both checked: every acked commit is durable (4.2). +import test from 'node:test' +import assert from 'node:assert/strict' +import fs from 'node:fs' +import { createPlayer, namePlayer, sleep } from './lib.mjs' +import { gmKeyOf, makeStateDir, openAs, startServer, stopServer } from './withserver.mjs' + +async function gmConnect(origin, gmKey) { + const conn = await openAs(origin, gmKey) + await conn.ws.waitText('hello') + const walls = await conn.ws.waitText('walls') + return { ...conn, sceneId: walls.scene } +} + +// Build the world on a running server. Every mutation is acked before the next one, so a kill after +// this returns cannot lose an acked commit. +async function buildWorld(origin, gmKey) { + const gm = await gmConnect(origin, gmKey) + const saved = {} + try { + // Players: a GM plus one named player with a key (its own CRUD path is key.* + player.setname). + const alice = await createPlayer(gm.ws) + await namePlayer(origin, alice.key, 'Alice') + saved.alice = alice + // A second, still unnamed player: the GM roster carries it (`name:null`), players never see it. + await createPlayer(gm.ws) + // A wall and a door; the door is opened (door.set is its own write path). + const wall = await gm.ws.request({ t: 'wall.add', scene: gm.sceneId, a: [700, 0], + b: [700, 900], kind: 'wall' }) + const door = await gm.ws.request({ t: 'wall.add', scene: gm.sceneId, a: [700, 1000], + b: [700, 1400], kind: 'door' }) + assert.equal(wall.ok, true, JSON.stringify(wall)) + assert.equal(door.ok, true, JSON.stringify(door)) + assert.equal((await gm.ws.request({ t: 'door.set', scene: gm.sceneId, id: door.id, + open: true })).ok, true) + + // The player's own token: vision, explored cells and the encountered list come from it. + const pc = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'pc', + pos: [400, 400], descriptive_name: 'a wanderer', + actual_name: 'Wanderer', controller: alice.id, + flags: { vision: true }, radius: 35, + props: { public: { aura: 'cold' }, owner: { hp: 5 }, + gm: { secret: 1 } } }) + assert.equal(pc.ok, true, JSON.stringify(pc)) + // A monster right next to it: Alice meets it (one encountered entry, grey after it moves away). + const monster = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'npc', + pos: [500, 400], descriptive_name: 'a goblin', + actual_name: 'Grib' }) + assert.equal(monster.ok, true, JSON.stringify(monster)) + // A character with props, and a token that figures it (linked tokens carry no names). + const character = await gm.ws.request({ t: 'character.create', + descriptive_name: 'a cloaked figure', + actual_name: 'Lady Vex', owner: alice.id, + props: { public: { rank: 'noble' }, + owner: { hp: 9 }, gm: { plot: 'ally' } } }) + assert.equal(character.ok, true, JSON.stringify(character)) + const linked = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'pc', + pos: [560, 400], character_id: character.id, + controller: alice.id }) + assert.equal(linked.ok, true, JSON.stringify(linked)) + + // Props: a set and an unset on the plain token, a set on the character. + assert.equal((await gm.ws.request({ t: 'prop.set', target: 'token', id: pc.id, + bucket: 'public', key: 'light', value: 30 })).ok, true) + assert.equal((await gm.ws.request({ t: 'prop.unset', target: 'token', id: pc.id, + bucket: 'owner', key: 'hp' })).ok, true) + assert.equal((await gm.ws.request({ t: 'prop.set', target: 'character', id: character.id, + bucket: 'public', key: 'banner', value: 'red' })).ok, true) + // Status (GM source) and a resize: two more persisted tables/columns. + assert.equal((await gm.ws.request({ t: 'status.set', id: monster.id, + status: 'stuck' })).ok, true) + assert.equal((await gm.ws.request({ t: 'token.resize', id: monster.id, radius: 28 })).ok, true) + // A reveal for one player, reveal-all for a plain token, one encountered entry removed later. + assert.equal((await gm.ws.request({ t: 'name.reveal', subject: 'character', + id: character.id, player: alice.id })).ok, true) + assert.equal((await gm.ws.request({ t: 'name.reveal_all', subject: 'token', + id: pc.id })).ok, true) + saved.ids = { pc: pc.id, monster: monster.id, character: character.id, linked: linked.id, + wall: wall.id, door: door.id } + gm.ws.close() + } finally { + try { gm.ws.close() } catch {} + } + return saved +} + +function count(client, t) { + return client.messages.filter(m => m && m.t === t).length +} + +async function waitResync(client, expected) { + // The 6.3 sequence is ordered but arrives asynchronously; wait until every expected part is there. + const deadline = Date.now() + 5000 + for (;;) { + const ok = count(client, 'hello') >= 1 && count(client, 'roster') >= 1 && + count(client, 'token') >= expected.tokens && + count(client, 'character') >= expected.characters && + (expected.gm ? count(client, 'walls') >= 1 + : count(client, 'encountered') >= 1 && count(client, 'vision') >= 1 && + count(client, 'explored') >= 1) + if (ok) return + if (Date.now() > deadline) { + throw new Error(`resync incomplete: ${JSON.stringify(client.messages.map(m => m.t))}`) + } + await sleep(5) + } +} + +const strip = m => { const { n, ...rest } = m; return rest } +const by = key => (a, b) => String(a[key]).localeCompare(String(b[key])) + +// One connection's whole resync, normalized: `n` is per-connection and therefore not state. +async function snapshot(origin, key, expected, isGm) { + const c = await openAs(origin, key) + try { + await waitResync(c.ws, { ...expected, gm: isGm }) + const pick = t => c.ws.messages.filter(m => m && m.t === t).map(strip) + const snap = { hello: pick('hello')[0], roster: pick('roster').pop(), tokens: pick('token') } + snap.tokens.sort(by('id')) + snap.roster.players.sort(by('id')) + if (isGm) { + const walls = pick('walls').pop() + snap.walls = walls + snap.walls.walls.sort(by('id')) + snap.characters = pick('character').sort(by('id')) + snap.encountered = pick('encountered').map(e => { + e.set.sort(by('id')) + return e + }).sort(by('player')) + } else { + snap.characters = pick('character').sort(by('id')) + snap.encountered = pick('encountered').pop() + snap.encountered.set.sort(by('id')) + snap.vision = pick('vision').pop() + snap.vision.polys.sort(by('id')) + // explored RLE rows are already ordered by cy; keep the payload as the view, not a set. + snap.explored = pick('explored').pop() + } + return snap + } finally { + c.ws.close() + await c.ws.closed + } +} + +// The full before/after comparison: one fresh GM connection and one fresh Alice connection. +async function compareAcross(origin, gmKey, aliceKey, ids, expected) { + const beforeGm = await snapshot(origin, gmKey, expected, true) + const beforeAlice = await snapshot(origin, aliceKey, expected, false) + // The CRUD inventory is not empty: a restart test over an empty world would prove nothing. + assert.ok(beforeGm.walls.walls.length >= 2, 'the wall and the door are there') + assert.equal(beforeGm.walls.walls.find(w => w.id === ids.door).open, true, 'the door is open') + assert.ok(beforeGm.tokens.length >= 3, 'plain, monster, player and linked tokens are there') + assert.ok(beforeGm.characters.length >= 1, 'the character is there') + assert.equal(beforeGm.characters.find(c => c.id === ids.character).props.public.banner, 'red') + assert.equal(beforeGm.tokens.find(t => t.id === ids.monster).radius, 28, + 'the resize survived') + assert.ok(beforeGm.tokens.find(t => t.id === ids.monster).statuses + .some(s => s.status === 'stuck' && s.source === 'GM'), 'the GM status survived') + assert.equal(beforeAlice.encountered.set.find(e => e.id === ids.monster)?.name, 'a goblin') + assert.ok(beforeAlice.vision.polys.length >= 1, 'the player has sight') + assert.ok(beforeAlice.explored.rle.length >= 1, 'the player explored something') + return { beforeGm, beforeAlice } +} + +async function restartAndCompare(stateDir, gmKey, aliceKey, ids, expected, hard) { + let s = await startServer({ stateDir }) + const before = await compareAcross(s.origin, gmKey, aliceKey, ids, expected) + if (hard) { + // Every ack is sent after COMMIT (4.2), so a hard kill cannot lose an acked mutation. + s.child.kill('SIGKILL') + const deadline = Date.now() + 5000 + while (s.child.signalCode === null && s.child.exitCode === null && Date.now() < deadline) { + await sleep(20) + } + } + await stopServer(s) + + s = await startServer({ stateDir }) + try { + const afterGm = await snapshot(s.origin, gmKey, expected, true) + const afterAlice = await snapshot(s.origin, aliceKey, expected, false) + assert.deepEqual(afterGm, before.beforeGm, 'the GM resync after the restart is identical') + assert.deepEqual(afterAlice, before.beforeAlice, + 'the player resync after the restart is identical') + } finally { + await stopServer(s) + } +} + +const EXPECTED = { tokens: 3, characters: 1 } + +test('restart: full state, all CRUD, before and after SIGTERM', async () => { + const stateDir = makeStateDir() + const gmKey = gmKeyOf(stateDir) + let s = await startServer({ stateDir }) + let saved + try { + saved = await buildWorld(s.origin, gmKey) + } finally { + await stopServer(s) + } + try { + await restartAndCompare(stateDir, gmKey, saved.alice.key, saved.ids, EXPECTED, false) + } finally { + fs.rmSync(stateDir, { recursive: true, force: true }) + } +}) + +test('restart: full state, all CRUD, before and after SIGKILL', async () => { + const stateDir = makeStateDir() + const gmKey = gmKeyOf(stateDir) + let s = await startServer({ stateDir }) + let saved + try { + saved = await buildWorld(s.origin, gmKey) + } finally { + await stopServer(s) + } + try { + await restartAndCompare(stateDir, gmKey, saved.alice.key, saved.ids, EXPECTED, true) + } finally { + fs.rmSync(stateDir, { recursive: true, force: true }) + } +})