diff --git a/server/main.nim b/server/main.nim index 30c779e..423dea1 100644 --- a/server/main.nim +++ b/server/main.nim @@ -27,6 +27,9 @@ ## server/tiles.nim: a strict canonical URL, the player's explored rule (the GM always), `404` for a ## tile that does not exist and a bodyless `200` with `X-Accel-Redirect` to the internal `/_tiles/` ## location, which nginx alone can serve (DESIGN 3.3, 6.6, 11.1). +## M3 slice 10 (#25): the finish line - `scene.set` (the 29th catalogue intent: the settable scene +## fields, the token-radius-default resize through 5.6, and a hello + full resync of every +## connection), plus the restart and logs acceptance groups and the group checklist. ## Close reasons (FIXED, owner decision #18): mummy 0.4.8 cannot put a code in the close frame, so ## every server-initiated close is preceded by a `closing {reason, code}` message and the client ## reads 1005 + that message (DESIGN 6.5). @@ -285,6 +288,9 @@ proc sendHello(connId: int, player: Player) = ## The `hello` frame (6.1): the first frame on a connection, and again after `player.setname` ## (which is why it lives in a proc both paths call). Keyed by the app connId so a caller holding ## only the id (the upgrade handler) and one holding the record (the fan-out) share it. + ## A `hello` tells the client to reset everything (6.1), so the server's diff base for that + ## connection resets with it: without this, a `scene.set` resync would skip every unchanged token + ## and the client would hold an empty world. `resync` runs right after every `hello`. let named = player.name.isSome let me = if named: %player.name.get else: newJNull() var sceneJson: JsonNode @@ -294,6 +300,7 @@ proc sendHello(connId: int, player: Player) = let helloN = app.conns.nextFrameNo(connId) let found = app.conns.connById(connId) if helloN <= 0 or found.isNone: return + app.known.del connId found.get.ws.send($helloFrame(ProtoVersion, helloN, $player.role, player.id, me, sceneJson, extraJson)) @@ -332,6 +339,16 @@ proc resync(connId: int, named: bool, player: Player) = let n = nextN(conn) if n > 0: conn.ws.send($withN(f, n)) +proc resyncEveryone() = + ## `scene.set` (6.1): `hello` plus a full resync to every connection, unnamed players included + ## (they get `hello` and nothing else, 6.3). The scene block in `hello` may have changed, so even + ## a connection that has no state yet is told. Caller holds the global lock. + for c in app.conns.snapshot(): + let p = playerById(app.db, c.playerId) + if p.isSome: + sendHello(c.id, p.get) + resync(c.id, c.named, p.get) + proc settle(conn: Conn, reqId: int, extra: JsonNode = nil, roster = false) = ## 4.2 step 7 for a mutation: the ack and then every recipient's diff are enqueued under the global ## lock, so no two threads touch a connection's `known` table at once and the ack always precedes @@ -554,6 +571,12 @@ proc join(request: Request) {.gcsafe.} = app.lg.log(lvInfo, "join_refused") request.respond(401, body = "") return + if faultActive("keylog"): + # Test-only negative control for the "logs" acceptance group (#25): write the raw secret to + # stdout, bypassing `eventlog` on purpose, so the group's grep must find it in a fault build. + # Compiled out of the shipped binary (faults.nim). + stdout.write("FAULT keylog key=" & key & "\n") + stdout.flushFile() # The token is deliberately never registered for redaction: sessions never expire, so a value # registry would grow without bound. It is only ever written to the Set-Cookie header; if a future @@ -1731,6 +1754,58 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = settle(conn, env.reqId) return + of "scene.set": + # DESIGN 6.1, slice 10 / #25: a hello-equivalent reset of every connection (the client resets on + # `hello`, 6.1) after a GM edit of the settable scene fields. `w`, `h`, `tile_size`, `cell` and + # `art_version` are not patch fields (import is the M6 CLI) and are ignored as unknown fields + # (6.2); a patch carrying only those has no field and is `invalid`. + if not sceneOk(conn, env): return + let patch = parseScenePatch(env.node) + if patch.isNone: + ackErr(conn, env.reqId, CodeInvalid) + return + var candidate = app.scene.patched(patch.get) + var changed: seq[string] + if patch.get.name.isSome: changed.add "name" + if patch.get.gridSize.isSome: changed.add "grid_size" + if patch.get.visionRadiusDefault.isSome: changed.add "vision_radius_default" + if patch.get.tokenRadiusDefault.isSome: changed.add "token_radius_default" + if patch.get.extra.isSome: changed.add "extra" + var tokenChanges: seq[(int, TokenRec)] + withLock app.dbLock: + # 5.6 `token_radius_default`: every token that uses the default changes effective size; a grow + # pushes (or squeezes), a shrink clears the `walls` entries only when the overlap ends. The + # rules run on a snapshot with the OLD radii (the candidate default is not in `app.scene` yet), + # then one FULL transaction writes the scene row and every token it resized. + if candidate.tokenRadiusDefault != app.scene.tokenRadiusDefault: + var mr = moveScene(app.scene, app.tokens) + for i, t in app.tokens: + if t.radius.isSome: continue # an own radius is not the default (#4) + discard moverules.resizeToken(mr, i, candidate.tokenRadiusDefault) + var rec = app.tokens[i] + let outcome = rec.applyOutcome(mr.tokens[i]) + if outcome.moved or outcome.statuses: tokenChanges.add (i, rec) + app.db.exec(sql"PRAGMA synchronous=FULL") + try: + app.db.withTransaction: + writeSceneRow(app.db, candidate) + for (_, rec) in tokenChanges: + discard writePosition(app.db, rec) + writeStatuses(app.db, rec) + finally: + app.db.exec(sql"PRAGMA synchronous=NORMAL") + app.scene = candidate + for (i, rec) in tokenChanges: app.tokens[i] = rec + refreshAll() + persistAllExplored() + recordEncounters() + ackOk(conn, env.reqId) + resyncEveryone() + app.lg.log(lvInfo, "scene_set", [("scene", $candidate.id), + ("fields", changed.join(",")), + ("tokens_resized", $tokenChanges.len)]) + return + of "wall.add": if not sceneOk(conn, env): return let a = parseVec(fieldOrNull(env.node, "a")) diff --git a/server/protocol.nim b/server/protocol.nim index 15deb31..82a1fc6 100644 --- a/server/protocol.nim +++ b/server/protocol.nim @@ -82,7 +82,7 @@ const ImplementedIntents* = ["conn.ping", "act.do", "key.create", "key.replace", "key.show", "player.setname", "player.rename", "player.remove", - "wall.add", "wall.update", "wall.remove", "door.set", + "scene.set", "wall.add", "wall.update", "wall.remove", "door.set", "token.create", "token.update", "token.move", "token.resize", "token.remove", "status.set", "status.clear", "prop.set", "prop.unset", "character.create", "character.update", "character.remove", @@ -90,8 +90,8 @@ const "encountered.remove"] ## What the built slices actually handle (slice 3 #18: the shell and the auth intents; slice 4 ## #19: walls and doors; slice 5 #20: tokens and sight; slice 7 #22: sizes, statuses and props; - ## slice 8 #23: characters, names, encountered, and the players/keys rows). Only `scene.set` - ## still answers `unknown-type` (DESIGN 6.1 note). + ## slice 8 #23: characters, names, encountered, and the players/keys rows; slice 10 #25: + ## `scene.set`). With slice 10 the whole 29-intent catalogue of 6.1 has a handler. type Envelope* = object diff --git a/server/world.nim b/server/world.nim index c11f5c0..c4369b9 100644 --- a/server/world.nim +++ b/server/world.nim @@ -12,6 +12,9 @@ ## owner-delegated, #19, in DESIGN 6.1/14): ## - `scene` is an integer id; in v1 it is always the one seeded scene (id 1), and any other value ## is `not-found` (no existence oracle either way: only the GM can send these intents). +## - `scene.set` (slice 10, #25): the patch rules of 6.1 ("Scene payload rules"); `w`, `h`, +## `tile_size`, `cell` and `art_version` are not patch fields. `patched`/`writeSceneRow` are pure +## and transaction-free so main.nim can commit the scene row with the tokens it resized. ## - `wall.add`: `open` omitted = false; `open` on a `kind: "wall"` is `invalid` (a wall is never ## open), and the stored row normalizes it to false regardless. ## - `wall.update` patches `a`, `b`, `kind`, `flags` only (`open` belongs to `door.set`; an `open` @@ -26,7 +29,7 @@ ## no locking: the caller holds the global lock (4.3). import std/[json, math, options, strutils] import db_connector/db_sqlite -import geometry +import geometry, text type WallKind* = enum @@ -66,6 +69,17 @@ type kind*: Option[WallKind] flags*: Option[JsonNode] + ScenePatch* = object + ## `scene.set` (DESIGN 6.1): every field is optional; an absent field keeps its value. + ## `w`, `h`, `tile_size`, `cell` and `art_version` are not patch fields (import is the M6 CLI): + ## they are unknown fields and ignored (6.2), so a patch with only one of them has no field at + ## all and is `invalid`. + name*: Option[string] + gridSize*: Option[float] + visionRadiusDefault*: Option[float] + tokenRadiusDefault*: Option[float] + extra*: Option[JsonNode] + SceneError* = object of CatchableError ## The DB and this build disagree about the scene (missing seed, unreadable row). @@ -73,6 +87,8 @@ const DefaultSceneId* = 1 ## The seeded v1 scene (migration step 3). Exactly one scene exists in v1 (Q3). WallKinds* = [wkWall, wkDoor] + SceneNameMaxLen* = 64 + ## `scene.set.name`: the 6.5 text rule, same 64-code-point bound as character names (#25). # --------------------------------------------------------------------------------------------------- # Field parsing (DESIGN 6.1 field notes: px floats, missing or wrongly typed -> `invalid`) @@ -113,6 +129,66 @@ proc fieldOrNull*(env: JsonNode, key: string): JsonNode = result = env{key} if not result.isNil and result.kind == JNull: result = nil +proc parseFinite(node: JsonNode): Option[float] = + ## One finite JSON number (integers accepted; strings, booleans and null are not numbers). + if node.isNil: return none(float) + case node.kind + of JInt: result = some(float(node.getInt)) + of JFloat: + let f = node.getFloat + if classify(f) in {fcNan, fcInf, fcNegInf}: return none(float) + result = some(f) + else: discard + +proc parseScenePatch*(node: JsonNode): Option[ScenePatch] = + ## `scene.set` payload (DESIGN 6.1, slice 10 / #25). At least one patch field is required and a + ## present field must have its own shape: a `null` is a wrong type, not "absent", because the + ## field was declared (the same reading `token.resize` gives a required `radius`). + ## name: the 6.5 text rule (1..64 code points, no control characters) + ## grid_size: a finite number >= 0 (0 = no grid) + ## vision_radius_default, token_radius_default: a finite number > 0; no upper cap (#4, #25) + ## extra: a JSON object, stored verbatim and never interpreted + if node.isNil or node.kind != JObject: return none(ScenePatch) + var p: ScenePatch + var any = false + if node.hasKey("name"): + let v = node["name"] + if v.kind != JString or not validText(v.getStr, SceneNameMaxLen): return none(ScenePatch) + p.name = some(v.getStr) + any = true + if node.hasKey("grid_size"): + let v = parseFinite(node["grid_size"]) + if v.isNone or v.get < 0: return none(ScenePatch) + p.gridSize = v + any = true + if node.hasKey("vision_radius_default"): + let v = parseFinite(node["vision_radius_default"]) + if v.isNone or v.get <= 0: return none(ScenePatch) + p.visionRadiusDefault = v + any = true + if node.hasKey("token_radius_default"): + let v = parseFinite(node["token_radius_default"]) + if v.isNone or v.get <= 0: return none(ScenePatch) + p.tokenRadiusDefault = v + any = true + if node.hasKey("extra"): + let v = node["extra"] + if v.kind != JObject: return none(ScenePatch) + p.extra = some(v) + any = true + if not any: return none(ScenePatch) + some(p) + +proc patched*(sc: SceneRec, patch: ScenePatch): SceneRec = + ## The scene as `scene.set` would store it. The caller validates the result by construction: every + ## patch field was already type- and range-checked by `parseScenePatch`. + result = sc + if patch.name.isSome: result.name = patch.name.get + if patch.gridSize.isSome: result.gridSize = patch.gridSize.get + if patch.visionRadiusDefault.isSome: result.visionRadiusDefault = patch.visionRadiusDefault.get + if patch.tokenRadiusDefault.isSome: result.tokenRadiusDefault = patch.tokenRadiusDefault.get + if patch.extra.isSome: result.extra = patch.extra.get + # --------------------------------------------------------------------------------------------------- # In-memory rules (pure): validation, lookup and the id allocator @@ -170,6 +246,19 @@ template authoringTransaction*(db: DbConn, body: untyped) = finally: db.exec(sql"PRAGMA synchronous=NORMAL") +proc writeSceneRow*(db: DbConn, sc: SceneRec) = + ## The `scene.set` columns, no transaction control: the caller owns the transaction (the scene row + ## and the tokens its default radius resized commit together, #25). + db.exec(sql"""UPDATE scene SET name = ?, grid_size = ?, vision_radius_default = ?, + token_radius_default = ?, extra = ? WHERE id = ?""", + sc.name, $sc.gridSize, $sc.visionRadiusDefault, $sc.tokenRadiusDefault, + flagsText(sc.extra), sc.id) + +proc storeScene*(db: DbConn, sc: SceneRec) = + ## `scene.set` alone in memory (tests): one FULL authoring transaction (Q12). + authoringTransaction(db): + writeSceneRow(db, sc) + proc insertRow(db: DbConn, sceneId: int, w: WallRec) = db.exec(sql"""INSERT INTO wall (scene_id, id, ax, ay, bx, by, kind, open, flags) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""", diff --git a/tests/tprotocol.nim b/tests/tprotocol.nim index 5927ad5..6dcaa29 100644 --- a/tests/tprotocol.nim +++ b/tests/tprotocol.nim @@ -40,7 +40,7 @@ suite "envelope (6.5 step 2)": test "the catalogue is the 29 intents of 6.1 and the built set is a subset": check IntentCatalogue.len == 29 - check ImplementedIntents.len == 28 # 29 - `scene.set`, which is slice 10 + check ImplementedIntents.len == 29 # slice 10 (#25): `scene.set` closed the last gap for t in ImplementedIntents: check t in IntentCatalogue check isCatalogueIntent(t) @@ -66,9 +66,12 @@ suite "envelope (6.5 step 2)": for t in ["player.setname", "player.rename", "key.show", "token.resize", "status.set", "status.clear", "prop.set", "prop.unset", "character.create", "character.update", "character.remove", "character.reassign", "name.reveal", "name.reveal_all", - "encountered.remove"]: + "encountered.remove", "scene.set"]: + check isImplementedIntent(t) + check isGmOnlyIntent("scene.set") # scene edits are GM-only (6.1) + # Every catalogue intent has a handler now (#25): no `unknown-type` gap is left. + for t in IntentCatalogue: check isImplementedIntent(t) - check not isImplementedIntent("scene.set") # the only catalogue intent left for slice 10 suite "intent rate limit (6.4: 30/s, burst 100)": test "a fresh bucket allows exactly the burst, then refuses": diff --git a/tests/tworld.nim b/tests/tworld.nim index 5225845..efd72d4 100644 --- a/tests/tworld.nim +++ b/tests/tworld.nim @@ -1,7 +1,7 @@ ## Scene and wall state (#19, DESIGN 3.1, 4.1, 4.4, 6.1, 8): wall validation, the per-scene ## never-reused wall ids, the write-through persistence (synchronous=FULL for authoring) and the ## reload that a restart performs. The wire behaviour over a real socket lives in tools/walls.test.mjs. -import std/[json, options, os, sequtils, unittest] +import std/[json, options, os, sequtils, strutils, unittest] import db_connector/db_sqlite import db, world @@ -300,3 +300,67 @@ suite "lookup outcomes (main.nim's 6.5 mapping)": let id = addWall(conn, sc, wall(1, 1, 2, 2)).get check id == 1 check wallById(sc, 0).isNone + +suite "scene.set (6.1, slice 10 / #25)": + test "a patch changes only the fields it names and the row round-trips": + let (conn, d) = freshScene() + defer: + close(conn) + removeDir(d) + let before = loadScene(conn).get + let p = parseScenePatch(%*{"name": "Cave", "grid_size": 64, + "vision_radius_default": 500, "token_radius_default": 30, + "extra": {"mood": "dark"}}) + check p.isSome + let after = patched(before, p.get) + check after.name == "Cave" + check after.gridSize == 64 + check after.visionRadiusDefault == 500 + check after.tokenRadiusDefault == 30 + check after.extra["mood"].getStr == "dark" + # the non-settable columns and the wall counter are untouched (import is the M6 CLI) + check (after.w, after.h) == (before.w, before.h) + check after.tileSize == before.tileSize and after.cell == before.cell + check after.artVersion == before.artVersion + check after.nextWallId == before.nextWallId + storeScene(conn, after) + let back = loadScene(conn).get + check back.name == "Cave" + check back.gridSize == 64 + check back.visionRadiusDefault == 500 + check back.tokenRadiusDefault == 30 + check back.extra["mood"].getStr == "dark" + + test "one field is enough; a patch with none is invalid": + check parseScenePatch(%*{"name": "Cave"}).isSome + check parseScenePatch(%*{"grid_size": 0}).isSome + check parseScenePatch(%*{}).isNone + check parseScenePatch(newJNull()).isNone + check parseScenePatch(nil).isNone + check parseScenePatch(%*[1]).isNone + + test "the non-settable columns are unknown fields: alone they leave no patch field": + for key in ["w", "h", "tile_size", "cell", "art_version"]: + check parseScenePatch(%*{key: 1}).isNone + # and they are ignored next to a real field (6.2) + let p = parseScenePatch(%*{key: 1, "name": "Cave"}) + check p.isSome + check p.get.name.get == "Cave" + + test "field shapes: text by the 6.5 rule, numbers finite, extra an object": + check parseScenePatch(%*{"name": ""}).isNone + check parseScenePatch(%*{"name": " padded"}).isNone # trimmed rule, like other names + check parseScenePatch(%*{"name": repeat("x", SceneNameMaxLen + 1)}).isNone + check parseScenePatch(%*{"name": repeat("x", SceneNameMaxLen)}).isSome + check parseScenePatch(%*{"name": 5}).isNone + check parseScenePatch(%*{"name": newJNull()}).isNone # declared, wrong type + check parseScenePatch(%*{"grid_size": -1}).isNone + check parseScenePatch(%*{"grid_size": "60"}).isNone + check parseScenePatch(%*{"grid_size": 0}).isSome + check parseScenePatch(%*{"vision_radius_default": 0}).isNone + check parseScenePatch(%*{"vision_radius_default": -5}).isNone + check parseScenePatch(%*{"token_radius_default": 0}).isNone + check parseScenePatch(%*{"token_radius_default": 20.5}).isSome + check parseScenePatch(%*{"extra": []}).isNone + check parseScenePatch(%*{"extra": newJNull()}).isNone + check parseScenePatch(%*{"extra": {}}).isSome diff --git a/tools/protocol.test.mjs b/tools/protocol.test.mjs index 5948aef..185ba48 100644 --- a/tools/protocol.test.mjs +++ b/tools/protocol.test.mjs @@ -99,13 +99,13 @@ test('an unknown type is refused, unknown fields are ignored, and every intent g assert.equal((await gm.ws.request({ t: 'token.teleport', id: 'x' })).code, 'unknown-type') assert.equal((await gm.ws.request({ t: '' })).code, 'unknown-type') assert.equal((await gm.ws.request({ t: 'TOKEN.MOVE', id: 'x' })).code, 'unknown-type') - // the only catalogue intent whose slice has not landed still answers exactly once - assert.equal((await gm.ws.request({ t: 'scene.set', scene: 1 })).code, 'unknown-type') + // `scene.set` (slice 10) is built: it answers on its own fields, no `unknown-type` gap is left + assert.equal((await gm.ws.request({ t: 'scene.set', scene: 1 })).code, 'invalid') // no field // a built intent answers on its own fields instead assert.equal((await gm.ws.request({ t: 'name.reveal', subject: 'token', id: 'x', player: 2 })).code, 'not-found') assert.equal((await gm.ws.request({ t: 'character.create' })).code, 'invalid') - assert.equal((await gm.ws.request({ t: 'scene.set' })).code, 'unknown-type') + assert.equal((await gm.ws.request({ t: 'scene.set' })).code, 'invalid') // no scene // an intent whose slice HAS landed answers on its fields (empty token.create = invalid) assert.equal((await gm.ws.request({ t: 'token.create', scene: 1 })).code, 'invalid') // the reserved FFF hook is refused for everyone and is never ok diff --git a/tools/scene.test.mjs b/tools/scene.test.mjs new file mode 100644 index 0000000..a32e4c8 --- /dev/null +++ b/tools/scene.test.mjs @@ -0,0 +1,211 @@ +// M3 slice 10 (#25): `scene.set`, the last catalogue intent (DESIGN 6.1). One GM edit of the +// settable scene fields is a hello-equivalent reset of every connection: `hello` (new scene block) +// then the full 6.3 resync, including the unchanged tokens the client just reset. A +// `token_radius_default` change resizes the tokens that use the default through the 5.6 rules +// (grow pushes or squeezes; a token with its own radius does not move). +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 } +} + +async function namedPlayer(origin, gm, name) { + const player = await createPlayer(gm.ws) + await namePlayer(origin, player.key, name) + return player +} + +// A frame that arrives after `mark` (the message index captured before the mutation). +function after(client, mark, t) { + return client.waitFor((m, i) => i >= mark && m.t === t) +} + +test('scene.set edits the scene and resets every connection with hello plus a full resync', async () => { + const stateDir = makeStateDir() + const gmKey = gmKeyOf(stateDir) + const s = await startServer({ stateDir }) + try { + const gm = await gmConnect(s.origin, gmKey) + const alice = await namedPlayer(s.origin, gm, 'Alice') + const tok = 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 } }) + assert.equal(tok.ok, true, JSON.stringify(tok)) + const a = await openAs(s.origin, alice.key) + await a.ws.waitText('hello') + await a.ws.waitFor(m => m.t === 'token' && m.id === tok.id) + + const gmMark = gm.ws.messages.length + const aMark = a.ws.messages.length + const ack = await gm.ws.request({ t: 'scene.set', scene: gm.sceneId, name: 'Cave', + grid_size: 64, vision_radius_default: 500, + token_radius_default: 25, extra: { mood: 'dark' } }) + assert.equal(ack.ok, true, JSON.stringify(ack)) + + // The GM: a new hello with the edited scene block (and the GM-only `extra`), then walls and the + // unchanged token again (the hello reset the server's diff base too). + const gmHello = await after(gm.ws, gmMark, 'hello') + assert.equal(gmHello.scene.name, 'Cave') + assert.equal(gmHello.scene.grid_size, 64) + assert.equal(gmHello.scene.vision_radius_default, 500) + assert.equal(gmHello.scene.token_radius_default, 25) + assert.equal(gmHello.scene.tile_size, 32, 'tile_size is not settable on the wire') + assert.deepEqual(gmHello.extra, { mood: 'dark' }) + await after(gm.ws, gmMark, 'walls') + await after(gm.ws, gmMark, 'roster') + const gmTok = await after(gm.ws, gmMark, 'token') + assert.equal(gmTok.id, tok.id) + + // The player: the same hello (no `extra` for a player) and the token resent after the reset. + const aHello = await after(a.ws, aMark, 'hello') + assert.equal(aHello.scene.name, 'Cave') + assert.equal(aHello.scene.token_radius_default, 25) + assert.equal('extra' in aHello, false, '`extra` is GM-only (6.1 hello)') + const aTok = await after(a.ws, aMark, 'token') + assert.equal(aTok.id, tok.id) + assert.equal(aTok.radius, 25, 'a default-radius token follows the scene default') + + // A patch that changes no token at all still re-sends it: `hello` is a client reset, so the + // server's diff base resets with it (a resync that skipped unchanged tokens would empty the + // client). + const mark2 = gm.ws.messages.length + assert.equal((await gm.ws.request({ t: 'scene.set', scene: gm.sceneId, + name: 'Cave II' })).ok, true) + await after(gm.ws, mark2, 'hello') + assert.equal((await after(gm.ws, mark2, 'token')).id, tok.id) + a.ws.close(); gm.ws.close() + } finally { + await stopServer(s) + fs.rmSync(stateDir, { recursive: true, force: true }) + } +}) + +test('scene.set validation: not-found, invalid shapes, one field required, unknown fields ignored', + async () => { + const stateDir = makeStateDir() + const gmKey = gmKeyOf(stateDir) + const s = await startServer({ stateDir }) + try { + const gm = await gmConnect(s.origin, gmKey) + const bad = [ + [{ scene: 99, name: 'x' }, 'not-found'], + [{ scene: '1', name: 'x' }, 'invalid'], + [{ scene: 1 }, 'invalid'], // no patch field + [{ scene: 1, w: 8000 }, 'invalid'], // not settable, so no field at all + [{ scene: 1, tile_size: 256 }, 'invalid'], + [{ scene: 1, art_version: 9 }, 'invalid'], + [{ scene: 1, name: '' }, 'invalid'], + [{ scene: 1, name: ' padded' }, 'invalid'], + [{ scene: 1, name: 'x'.repeat(65) }, 'invalid'], + [{ scene: 1, name: null }, 'invalid'], + [{ scene: 1, grid_size: -1 }, 'invalid'], + [{ scene: 1, grid_size: '60' }, 'invalid'], + [{ scene: 1, vision_radius_default: 0 }, 'invalid'], + [{ scene: 1, token_radius_default: 0 }, 'invalid'], + [{ scene: 1, token_radius_default: -10 }, 'invalid'], + [{ scene: 1, extra: [] }, 'invalid'], + [{ scene: 1, extra: null }, 'invalid'], + ] + for (const [payload, code] of bad) { + const reply = await gm.ws.request({ t: 'scene.set', ...payload }) + assert.equal(reply.ok, false, `${JSON.stringify(payload)} must be refused`) + assert.equal(reply.code, code, JSON.stringify(payload)) + } + + // An unknown field next to a real one is ignored (6.2), not a second error. + const mark = gm.ws.messages.length + const ok = await gm.ws.request({ t: 'scene.set', scene: 1, name: 'Cave', w: 9999, + tile_size: 256, art_version: 7 }) + assert.equal(ok.ok, true, JSON.stringify(ok)) + const hello = await after(gm.ws, mark, 'hello') + assert.equal(hello.scene.name, 'Cave') + assert.equal(hello.scene.w, 4096) + assert.equal(hello.scene.tile_size, 32) + assert.equal(hello.scene.art_version, 1) + + // A plain player may not edit the scene (6.1, 6.5 step 6). + const alice = await namedPlayer(s.origin, gm, 'Alice') + const a = await openAs(s.origin, alice.key) + await a.ws.waitText('hello') + assert.equal((await a.ws.request({ t: 'scene.set', scene: 1, name: 'nope' })).code, + 'not-allowed') + a.ws.close(); gm.ws.close() + } finally { + await stopServer(s) + fs.rmSync(stateDir, { recursive: true, force: true }) + } + }) + +test('token_radius_default: a grow pushes default-radius tokens, an own radius never moves', + async () => { + const stateDir = makeStateDir() + const gmKey = gmKeyOf(stateDir) + const s = await startServer({ stateDir }) + try { + const gm = await gmConnect(s.origin, gmKey) + // A wall 40 px above the token: clear at radius 20, overlapping at 50. + assert.equal((await gm.ws.request({ t: 'wall.add', scene: gm.sceneId, a: [0, 440], + b: [1000, 440], kind: 'wall' })).ok, true) + const def = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'npc', + pos: [400, 400], descriptive_name: 'a goblin', + actual_name: 'Grib' }) + assert.equal(def.ok, true, JSON.stringify(def)) + const own = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'npc', + pos: [2000, 2000], descriptive_name: 'a big troll', + actual_name: 'Grum', radius: 30 }) + assert.equal(own.ok, true, JSON.stringify(own)) + const ownBefore = await gm.ws.waitFor(m => m.t === 'token' && m.id === own.id) + + assert.equal((await gm.ws.request({ t: 'scene.set', scene: gm.sceneId, + token_radius_default: 50 })).ok, true) + const pushed = await gm.ws.waitFor(m => m.t === 'token' && m.id === def.id && m.radius === 50) + // 5.6 grow push: away from the wall by exactly the distance that ends at r + eps. + assert.ok(pushed.pos[1] < 400, `expected a push up, got ${JSON.stringify(pushed.pos)}`) + assert.ok(Math.abs(440 - pushed.pos[1] - 50) < 1, + `the circle ends clear of the wall: ${JSON.stringify(pushed.pos)}`) + assert.deepEqual(pushed.statuses, [], 'a successful push leaves no status') + await sleep(50) + const ownAfter = gm.ws.messages.filter(m => m.t === 'token' && m.id === own.id).pop() + assert.equal(ownAfter.radius, 30, 'a token with its own radius is untouched') + assert.deepEqual(ownAfter.pos, ownBefore.pos) + gm.ws.close() + } finally { + await stopServer(s) + fs.rmSync(stateDir, { recursive: true, force: true }) + } + }) + +test('token_radius_default: a grow with no room on either side squeezes', async () => { + const stateDir = makeStateDir() + const gmKey = gmKeyOf(stateDir) + const s = await startServer({ stateDir }) + try { + const gm = await gmConnect(s.origin, gmKey) + // A corridor 60 px wide: a radius-20 token fits centred, a radius-40 token cannot fit at all. + assert.equal((await gm.ws.request({ t: 'wall.add', scene: gm.sceneId, a: [1000, 900], + b: [1000, 1100], kind: 'wall' })).ok, true) + assert.equal((await gm.ws.request({ t: 'wall.add', scene: gm.sceneId, a: [1060, 900], + b: [1060, 1100], kind: 'wall' })).ok, true) + const tok = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'npc', + pos: [1030, 1000], descriptive_name: 'a rat', + actual_name: 'Squeak' }) + assert.equal(tok.ok, true, JSON.stringify(tok)) + assert.equal((await gm.ws.request({ t: 'scene.set', scene: gm.sceneId, + token_radius_default: 40 })).ok, true) + const frame = await gm.ws.waitFor(m => m.t === 'token' && m.id === tok.id && m.radius === 40) + assert.deepEqual(frame.pos, [1030, 1000], 'no valid side: the token stays where it was') + assert.deepEqual(frame.statuses, [{ status: 'squeezed', source: 'walls' }]) + gm.ws.close() + } finally { + await stopServer(s) + fs.rmSync(stateDir, { recursive: true, force: true }) + } +})