server: resize, status and prop intents in the mutation pipeline (#22)

`token.resize`, `status.set`, `status.clear`, `prop.set` and `prop.unset`
answer the 6.1 acks and codes; `token.create` now accepts `radius` and
`props` and computes the placement status before writing the row, so a token
dropped on a wall is born `stuck`. `token.update` keeps refusing the
character link and ignores `radius`/`props` (their intents own them).

Wall add/update/remove and door.set now run the pure rules on a snapshot
taken before the write and apply the outcome after it committed
(`applyRuleOutcome`: positions and walls-sourced statuses in one NORMAL
transaction, memory after COMMIT), which replaces the door-push-only helpers
and adds the 5.5 SET/KEEP/CLEAR rules and the squeeze of a failed push. A
value over the bucket cap is refused without touching the token (the clone
makes the cap check side-effect free). Prop keys are never logged.
This commit is contained in:
2026-11-15 11:02:35 +01:00
parent dcc813225f
commit 81898ab69c
+282 -54
View File
@@ -14,6 +14,10 @@
## M3 slice 6 (#21): explored persistence - the per-player explored grid is stored as 64x64-cell
## bitmaps (server/explored.nim, migration step 5), loaded at startup and upserted per mutation with
## only the chunks that mutation dirtied (DESIGN 4.2 step 6, 4.4).
## M3 slice 7 (#22): token details - `token.resize` (5.6, grow push or squeeze), `status.set` /
## `status.clear` with the `walls`|`GM` sources of 5.5 (`source` is GM-only on the wire), `prop.set` /
## `prop.unset` under the bucket caps of server/props.nim, and the per-token radius, props and status
## effects on `token.create`, `token.move`, `wall.*` and `door.set`.
## 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).
@@ -23,7 +27,7 @@ import std/typedthreads
import db_connector/db_sqlite
import mummy, mummy/routers
import config, db, eventlog, crypto, auth, conns, instancelock, protocol, world
import geometry, tokens, vision, views, explored, worldmap, faults, moverules
import geometry, props, tokens, vision, views, explored, worldmap, faults, moverules
const
CookieName* = "fff_session"
@@ -52,6 +56,9 @@ type
## every egress pass, so a closed connection leaves nothing behind.
gmPlayerId: int
## The GM's player id. A `controller` naming it means "the GM", i.e. `GmControlled`.
registry: props.Registry
## The property-schema registry (DESIGN 8/9): empty in v1, permissive fallback. One copy for
## the whole process, so the wire layer and the egress cannot disagree about it.
var appHandle: pointer
## The one App for the process. A plain pointer keeps worker-thread handlers `{.gcsafe.}`
@@ -242,41 +249,28 @@ proc settleWorld(conn: Conn, reqId: int, wallEffect: JsonNode, extra: JsonNode =
egressAll()
# ---------------------------------------------------------------------------------------------------
# Door push (DESIGN 5.5 FIXED Q14): closing a door on a token moves the token aside instead of
# locking it. The move rules compute the new positions (server-originated, no step cap); this pair
# persists them and wakes the owners' vision. A token with no valid side stays where it is: the
# `squeezed` status that records it is part of slice 7's status model (#22), which does not exist yet.
# Applying a move-rules outcome (DESIGN 5.5, 5.6). Every wall/door edit and every resize runs the
# pure rules on a snapshot of the tokens (`worldmap.moveScene`), then the DB write, then this: the
# new positions (door push, grow push) and the walls-sourced statuses that the event changed are
# persisted and copied into memory. Nothing is applied when the write failed, so memory and DB stay
# identical. Positions and derived statuses use one NORMAL transaction (Q12): neither is authored.
proc planDoorClose(wallId: int, open: bool): seq[moverules.Push] =
## The pushes a `door.set` would cause, computed against the state *before* the write (the move
## rules apply the transition themselves). Pure: nothing is changed here, so a refused or failing
## write cannot leave a token moved in memory but not in the DB. Caller holds the lock.
if open: return
let idx = wallIndex(app.scene, wallId)
if idx.isNone: return
var mr = moveScene(app.scene, app.tokens)
discard moverules.setDoor(mr, idx.get, open, result)
proc applyPushes(pushes: seq[moverules.Push]) =
## Runs after the door write committed: one transaction for the new positions (a move is NORMAL
## durability, Q12), then memory follows it and the owners' vision is recomputed. A pushed token
## records the position it came from (5.5 decides a later push's side with it). The explored
## chunks a push reveals are written by the caller's `persistAllExplored` after `refreshAll`.
if pushes.len == 0: return
var moved: seq[(int, TokenRec)]
for p in pushes:
if p.ti < 0 or p.ti >= app.tokens.len: continue
var stored = app.tokens[p.ti]
stored.prev = stored.pos
stored.hasPrev = true
stored.pos = p.pos
moved.add (p.ti, stored)
if moved.len == 0: return
proc applyRuleOutcome(mr: moverules.Scene): int =
## Persists every token the rules changed and then copies it into memory. Caller holds the lock and
## has already committed the wall/door/resize row, so a failing write here leaves the DB without the
## new positions and memory untouched (4.2 step 6). `refreshAll` runs afterwards by the caller.
var changes: seq[(int, TokenRec)]
for i in 0 ..< min(mr.tokens.len, app.tokens.len):
var rec = app.tokens[i] # object copy; the JsonNode refs are shared and never mutated
let outcome = rec.applyOutcome(mr.tokens[i])
if outcome.moved or outcome.statuses: changes.add (i, rec)
if changes.len == 0: return 0
app.db.withTransaction:
for (_, stored) in moved: discard writePosition(app.db, stored)
for (ti, stored) in moved:
app.tokens[ti] = stored
refreshPlayer(stored.owner)
for (_, rec) in changes:
discard writePosition(app.db, rec)
writeStatuses(app.db, rec)
for (i, rec) in changes: app.tokens[i] = rec
changes.len
# ---------------------------------------------------------------------------------------------------
# Intent field helpers (DESIGN 6.1, 6.5 steps 7-8): shape first, then lookup.
@@ -667,12 +661,11 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
if pos.isNone:
ackErr(conn, env.reqId, CodeInvalid)
return
for unsupported in ["character_id", "props", "radius"]:
# Slice 7 (#22) owns props and the per-token size (#4), slice 8 (#23) the character link. A
# known-but-unbuilt field is refused `invalid`: silently dropping a GM's field would lose data.
if present(env, unsupported):
ackErr(conn, env.reqId, CodeInvalid)
return
if present(env, "character_id"):
# The character link is slice 8 (#23). A known-but-unbuilt field is refused `invalid`:
# silently dropping a GM's field would lose data (6.1 token payload rules).
ackErr(conn, env.reqId, CodeInvalid)
return
var gmOnly = false
if present(env, "gm_only") and not boolField(env, "gm_only", gmOnly):
ackErr(conn, env.reqId, CodeInvalid)
@@ -685,14 +678,29 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
if vr.isNone:
ackErr(conn, env.reqId, CodeInvalid)
return
let radius = parseRadius(fieldOrNull(env.node, "radius")) # 5.6, #4 (slice 7)
if radius.isNone:
ackErr(conn, env.reqId, CodeInvalid)
return
let tokenProps = props.parseProps(app.registry, fieldOrNull(env.node, "props"))
if tokenProps.isNone:
ackErr(conn, env.reqId, CodeInvalid)
return
var created: tuple[outcome: TokenOutcome, token: TokenRec]
var controllerCheck = ccOk
withLock app.dbLock:
var candidate = TokenRec(kind: kind, descriptiveName: dname, actualName: aname,
pos: pos.get, gmOnly: gmOnly, flags: flags.get,
visionRadius: vr.get)
visionRadius: vr.get, radius: radius.get,
props: tokenProps.get)
controllerCheck = resolveController(env.node{"controller"}, candidate.owner)
if controllerCheck == ccOk:
# 5.5 SET: a GM placement ignores walls, but a position overlapping a blocking wall gives the
# new token `stuck(walls)` right away. The rules compute it on a snapshot that already holds
# the candidate as its last token, so the row is written once with its statuses.
var mr = moveScene(app.scene, app.tokens & @[candidate])
moverules.placeToken(mr, app.tokens.len)
candidate.statuses = wallsStatuses(candidate.statuses, mr.tokens[app.tokens.len])
created = addToken(app.db, app.scene, candidate, app.tokens.mapIt(it.id))
if created.outcome == toOk:
app.tokens.add created.token
@@ -837,14 +845,17 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
kind = moved.kind
resultPos = moved.pos
if kind == mkAck:
app.tokens[idx.get].pos = moved.pos
app.tokens[idx.get].prev = mr.tokens[idx.get].prev
app.tokens[idx.get].hasPrev = mr.tokens[idx.get].hasPrev
# The rules already decided the walls-sourced statuses (`mkAck` may also clear them, for
# a GM move to a free spot). Copy position + history + statuses, then persist them with
# the explored chunks the move added (4.2 step 6): a position, a derived lock and a grid
# are all NORMAL-durability data (Q12).
var rec = app.tokens[idx.get]
discard rec.applyOutcome(mr.tokens[idx.get])
app.tokens[idx.get] = rec
refreshPlayer(app.tokens[idx.get].owner)
# One transaction for the move and the explored chunks it added (4.2 step 6): a position
# and a grid are both NORMAL-durability data (Q12), so they commit or roll back together.
app.db.withTransaction:
discard writePosition(app.db, app.tokens[idx.get])
writeStatuses(app.db, app.tokens[idx.get])
persistExplored(@[app.tokens[idx.get].owner])
case kind
of mkError:
@@ -883,6 +894,199 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
settle(conn, env.reqId)
return
of "token.resize":
# 5.6: `radius` is a positive number or null (= back to the scene default); the field itself is
# required, so an absent `radius` is `invalid` (6.5 step 7). GM only (5.6: only the GM sets a size).
var id: string
if not stringField(env, "id", id):
ackErr(conn, env.reqId, CodeInvalid)
return
if not env.node.hasKey("radius"):
ackErr(conn, env.reqId, CodeInvalid)
return
let radius = parseRadius(env.node{"radius"})
if radius.isNone:
ackErr(conn, env.reqId, CodeInvalid)
return
var outcome = toNotFound
withLock app.dbLock:
let idx = tokenIndex(app.tokens, id)
if idx.isSome:
var candidate = app.tokens[idx.get]
candidate.radius = radius.get
# The rules decide the position effect first (5.6: shrink never pushes, grow pushes or
# squeezes), then one FULL transaction writes the size and the position together, so a
# crash cannot leave a grown token sitting inside a wall with no status.
var mr = moveScene(app.scene, app.tokens)
let effect = moverules.resizeToken(mr, idx.get, effectiveRadius(app.scene, candidate))
var rec = candidate
# The rules own the `walls` source: a grow push clears it, a failed grow sets `squeezed`, a
# shrink clears it only when the overlap ended, and an overlap that stays keeps it as it was.
rec.statuses = wallsStatuses(rec.statuses, mr.tokens[idx.get])
if effect == rkPushed:
rec.pos = mr.tokens[idx.get].pos
rec.prev = mr.tokens[idx.get].prev
rec.hasPrev = mr.tokens[idx.get].hasPrev
outcome = storeToken(app.db, app.scene, rec)
if outcome == toOk:
app.tokens[idx.get] = rec
refreshPlayer(rec.owner)
app.db.withTransaction:
persistExplored(@[rec.owner])
if outcome == toNotFound:
ackErr(conn, env.reqId, CodeNotFound)
return
if outcome != toOk:
ackErr(conn, env.reqId, CodeInvalid)
return
app.lg.log(lvInfo, "token_resize",
[("token", id), ("radius", if radius.get.isSome: $radius.get.get else: "default")])
settle(conn, env.reqId)
return
of "status.set":
# 5.5: the GM sets `stuck` or `squeezed` by hand, source `GM`; adding an entry twice is a no-op.
var id: string
if not stringField(env, "id", id):
ackErr(conn, env.reqId, CodeInvalid)
return
var rawStatus: string
if not stringField(env, "status", rawStatus):
ackErr(conn, env.reqId, CodeInvalid)
return
let kind = parseStatusKind(rawStatus)
if kind.isNone:
ackErr(conn, env.reqId, CodeInvalid)
return
var outcome = toNotFound
withLock app.dbLock:
let idx = tokenIndex(app.tokens, id)
if idx.isSome:
var rec = app.tokens[idx.get]
rec.addStatus(kind.get, ssGM)
outcome = storeToken(app.db, app.scene, rec)
if outcome == toOk: app.tokens[idx.get] = rec
if outcome == toNotFound:
ackErr(conn, env.reqId, CodeNotFound)
return
if outcome != toOk:
ackErr(conn, env.reqId, CodeInvalid)
return
app.lg.log(lvInfo, "status_set", [("token", id), ("status", $kind.get), ("source", $ssGM)])
settle(conn, env.reqId)
return
of "status.clear":
# 5.5: removes exactly one (status, source) entry. `not-found` covers "no such token" and "no
# such entry" alike (6.1). After clearing the `walls` source the player escape rule of 5.5 step 3
# applies unchanged: the token may step out without crossing, destination >= r from every wall.
var id: string
if not stringField(env, "id", id):
ackErr(conn, env.reqId, CodeInvalid)
return
var rawStatus, rawSource: string
if not stringField(env, "status", rawStatus):
ackErr(conn, env.reqId, CodeInvalid)
return
if not stringField(env, "source", rawSource):
ackErr(conn, env.reqId, CodeInvalid)
return
let kind = parseStatusKind(rawStatus)
let source = parseStatusSource(rawSource)
if kind.isNone or source.isNone:
ackErr(conn, env.reqId, CodeInvalid)
return
var outcome = toNotFound
withLock app.dbLock:
let idx = tokenIndex(app.tokens, id)
if idx.isSome and app.tokens[idx.get].hasStatus(kind.get, source.get):
var rec = app.tokens[idx.get]
discard rec.removeStatus(kind.get, source.get)
outcome = storeToken(app.db, app.scene, rec)
if outcome == toOk: app.tokens[idx.get] = rec
if outcome == toNotFound:
ackErr(conn, env.reqId, CodeNotFound)
return
if outcome != toOk:
ackErr(conn, env.reqId, CodeInvalid)
return
app.lg.log(lvInfo, "status_clear", [("token", id), ("status", $kind.get),
("source", $source.get)])
settle(conn, env.reqId)
return
of "prop.set", "prop.unset":
# 6.1 prop payload rules + server/props.nim caps. Slice 7 is GM-only (v1: owner-bucket writes by
# players come with FFF actions, 9, which is already the role check of 6.5 step 6). `target` is
# `token` or `character`; characters do not exist before slice 8 (#23), so a character target is
# `not-found` - the honest answer for an id that names nothing.
let setting = env.t == "prop.set"
var target, id, bucketRaw, key: string
if not stringField(env, "target", target):
ackErr(conn, env.reqId, CodeInvalid)
return
if target notin ["token", "character"]:
ackErr(conn, env.reqId, CodeInvalid)
return
if not stringField(env, "id", id):
ackErr(conn, env.reqId, CodeInvalid)
return
if not stringField(env, "bucket", bucketRaw):
ackErr(conn, env.reqId, CodeInvalid)
return
let bucket = props.parseBucket(bucketRaw)
if bucket.isNone:
ackErr(conn, env.reqId, CodeInvalid)
return
if not stringField(env, "key", key) or not props.validPropKey(key):
ackErr(conn, env.reqId, CodeInvalid)
return
var value: JsonNode
if setting:
value = env.node{"value"}
if value.isNil:
ackErr(conn, env.reqId, CodeInvalid)
return
if value.kind == JNull or props.valueBytes(value) > props.MaxPropValueBytes:
ackErr(conn, env.reqId, CodeInvalid)
return
if not app.registry.checkWrite(bucket.get, key, value):
ackErr(conn, env.reqId, CodeInvalid) # the registry refuses this key, kind or bucket
return
if target == "character":
ackErr(conn, env.reqId, CodeNotFound)
return
var outcome = toNotFound
var capped = false
withLock app.dbLock:
let idx = tokenIndex(app.tokens, id)
if idx.isSome:
var rec = app.tokens[idx.get]
var p = props.clone(rec.props)
if setting:
if not p.setProp(bucket.get, key, value): capped = true
else: rec.props = p
else:
discard p.unsetProp(bucket.get, key) # unsetting an absent key is ok (6.1)
rec.props = p
if not capped:
outcome = storeToken(app.db, app.scene, rec)
if outcome == toOk: app.tokens[idx.get] = rec
if capped:
ackErr(conn, env.reqId, CodeInvalid) # 64 keys per bucket (6.1, #22)
return
if outcome == toNotFound:
ackErr(conn, env.reqId, CodeNotFound)
return
if outcome != toOk:
ackErr(conn, env.reqId, CodeInvalid)
return
# The key is not logged: it is GM-authored text and the log stays free of player content.
app.lg.log(lvInfo, if setting: "prop_set" else: "prop_unset",
[("token", id), ("bucket", $bucket.get)])
settle(conn, env.reqId)
return
of "wall.add":
if not sceneOk(conn, env): return
let a = parseVec(fieldOrNull(env.node, "a"))
@@ -913,9 +1117,15 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
let candidate = WallRec(a: a.get, b: b.get, kind: kind.get, open: open.get, flags: flags.get)
var added: Option[WallRec]
withLock app.dbLock:
# 5.5 SET: the new wall sticks every token its circle overlaps. The rules run on a snapshot
# taken before the write (the id is assigned by the write), and their outcome is applied only
# after it committed, so a failed write leaves every token untouched.
var mr = moveScene(app.scene, app.tokens)
let id = addWall(app.db, app.scene, candidate)
if id.isSome:
added = wallById(app.scene, id.get)
discard moverules.addWall(mr, ruleWall(added.get))
discard applyRuleOutcome(mr)
refreshAll() # 4.2 step 5: a wall change moves every player's sight
persistAllExplored() # step 6: the chunks the new wall revealed, before the ack
if added.isNone:
@@ -976,9 +1186,15 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
withLock app.dbLock:
let current = wallById(app.scene, id)
if current.isSome:
# `wall.update` = remove then add for the status rules (5.5): the rules run on the snapshot
# with the patched wall at the same index, so a move away clears and a move onto a token sticks.
let idx = wallIndex(app.scene, id).get
var mr = moveScene(app.scene, app.tokens)
outcome = updateWall(app.db, app.scene, patched(current.get, patch))
if outcome == waOk:
updated = wallById(app.scene, id)
discard moverules.updateWall(mr, idx, ruleWall(updated.get))
discard applyRuleOutcome(mr)
refreshAll()
persistAllExplored()
if outcome == waNotFound:
@@ -1000,10 +1216,16 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
return
var outcome = waNotFound
withLock app.dbLock:
outcome = removeWall(app.db, app.scene, id)
if outcome == waOk:
refreshAll()
persistAllExplored()
let idx = wallIndex(app.scene, id)
if idx.isSome:
# 5.5 KEEP/CLEAR: a removal frees only the tokens that no longer overlap any blocking wall.
var mr = moveScene(app.scene, app.tokens)
outcome = removeWall(app.db, app.scene, id)
if outcome == waOk:
discard moverules.removeWall(mr, idx.get)
discard applyRuleOutcome(mr)
refreshAll()
persistAllExplored()
if outcome == waNotFound:
ackErr(conn, env.reqId, CodeNotFound)
return
@@ -1024,13 +1246,18 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
let open = openNode.getBool
var outcome = waNotFound
var updated: Option[WallRec]
var pushes: seq[moverules.Push]
withLock app.dbLock:
pushes = planDoorClose(id, open) # 5.5: plan against the pre-write state
# 5.5: closing pushes overlapped tokens aside and squeezes the ones with no valid side;
# opening re-evaluates the walls-sourced entries (KEEP while another wall still overlaps).
# The rules run on a snapshot taken before the write; their positions and statuses are applied
# only after it committed.
let idx = wallIndex(app.scene, id)
var mr = moveScene(app.scene, app.tokens)
outcome = setDoor(app.db, app.scene, id, open)
if outcome == waOk:
updated = wallById(app.scene, id)
applyPushes(pushes)
if idx.isSome: discard moverules.setDoor(mr, idx.get, open)
discard applyRuleOutcome(mr)
refreshAll()
persistAllExplored()
if outcome == waNotFound:
@@ -1236,7 +1463,8 @@ proc runServer(cfg: Config): int =
lg.log(lvInfo, "db_ready", [("path", cfg.dbPath), ("schema_version", $schemaVersion(conn)),
("applied", $applied)])
let state = App(cfg: cfg, lg: lg, db: conn, conns: newConns(), instanceLock: instanceLock)
let state = App(cfg: cfg, lg: lg, db: conn, conns: newConns(), instanceLock: instanceLock,
registry: props.defaultRegistry())
initLock(state.dbLock)
readRedactionSecrets(conn, lg)
# DESIGN 4.1/4.4: load everything into memory once; migration 3 seeds the single v1 scene.