server: scene.set closes the 29-intent catalogue, plus a log-leak fault hook (#25)

This commit is contained in:
2026-11-15 12:52:17 +01:00
parent df2b186267
commit 70a984c55a
7 changed files with 453 additions and 11 deletions
+75
View File
@@ -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"))
+3 -3
View File
@@ -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
+90 -1
View File
@@ -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 (?, ?, ?, ?, ?, ?, ?, ?, ?)""",