server: token intents, the resync and the door push (#20)

token.create/update/remove (GM) and token.move (controller, or GM) through
moverules: the uniform nack for locked/over-cap/collision and for an out-of-bounds
GM move, one not-allowed code for a player's unknown and not-yours targets, not-found
for the GM; accepted moves are persisted with NORMAL durability and the mover's
vision recomputed. token.update honours kind, both names, controller, gm_only,
flags and vision_radius, and refuses character_id until slice 8.

connect now sends hello, the GM walls snapshot and the 6.3 token half (vision,
explored full, tokens) under the global lock, so hello is always the first frame and
the resync is the diff base. Egress runs under the same lock, per mutation, so no two
threads touch a connection's known table and an unnamed player is never fed state.

door.set applies the 5.5 push: the move rules compute the new positions against the
pre-write state, the positions are persisted in one transaction, then memory and
vision follow (stuck/squeezed are slice 7). player.remove hands the controlled
tokens to the GM in memory as the FK already does in the DB.
This commit is contained in:
2026-11-15 09:35:19 +01:00
parent 5f5bf3293b
commit 6fcf7f8271
+479 -49
View File
@@ -7,15 +7,20 @@
## M3 slice 4 (#19): walls and doors - the one scene loaded at startup, `wall.add`, `wall.update`,
## `wall.remove` and `door.set` (GM only), the GM `walls` snapshot on connect, `wall`/`wall_gone`
## to every GM connection, and nothing about walls ever reaching a player (DESIGN 3.1, 6.1, 8).
## M3 slice 5 (#20): tokens and sight - `token.create`/`token.update`/`token.remove`/`token.move`
## through server/moverules.nim, one vision polygon per controlled token with the `vision` flag, the
## per-player explored set, and per-recipient egress: every state frame a socket receives is built by
## server/views.nim from a typed `GmView`/`PlayerView`, so raw world state has no other path out.
## 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).
## The listen address is the constant config.BindAddress (127.0.0.1): nginx is the only public face.
import std/[atomics, json, locks, options, os, strutils]
import std/[atomics, json, locks, options, os, sequtils, sets, strutils, tables]
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, worldmap, faults, moverules
const
CookieName* = "fff_session"
@@ -29,11 +34,21 @@ type
lg: Logger
db: DbConn
dbLock: Lock
## The one global lock (DESIGN 4.3): it serializes every mutation, the DB and `scene`.
## The one global lock (DESIGN 4.3): it serializes every mutation, the DB, and the world below.
conns: Conns
instanceLock: InstanceLock
scene: SceneRec
## The single v1 scene with its walls, loaded at startup and never re-read (4.1).
tokens: seq[TokenRec]
## Every token of the scene, in creation order, loaded at startup (4.1).
visions: Table[int, PlayerVision]
## Per-player sight state (4.1 PlayerState): polygons, explored cells, fresh cells. Created on
## a player's first connection; the GM has no entry (the GM sees everything, 6.1).
known: Table[int, views.Known]
## Per-connection egress diff state (4.1 `known`), keyed by the app connId (H19). Pruned on
## 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`.
var appHandle: pointer
## The one App for the process. A plain pointer keeps worker-thread handlers `{.gcsafe.}`
@@ -87,6 +102,8 @@ proc closeGone(conn: Conn, reason: string, code: int) =
# ---------------------------------------------------------------------------------------------------
# Wall fan-out (DESIGN 3.1: walls are GM-only data; a player never receives one, in any message).
# Walls are not part of the egress view: they are GM-only by construction, so they bypass
# views.egressFrames and never enter a PlayerView at all.
proc wallObjectOf(w: WallRec): JsonNode =
wallObject(w.id, w.a, w.b, $w.kind, w.open, w.flags)
@@ -99,11 +116,140 @@ proc wallsSnapshot(sc: SceneRec): JsonNode =
proc sendToGms(frame: JsonNode) =
## Every GM connection, each with its own `n` (DESIGN 6.1 `wall`/`wall_gone`, 6). The loop is
## sequential on this thread, so reusing one frame object while stamping `n` is safe.
## `LEAK_FAULT=walls` (a -d:leakfault build only) also sends it to players: the negative control
## for the WALLDATA class (DESIGN 10.3).
let leakToPlayers = faultActive("walls")
for c in app.conns.snapshot():
if c.role != prGm: continue
if c.role != prGm and not leakToPlayers: continue
let n = nextN(c)
if n > 0: c.ws.send($withN(frame, n))
# ---------------------------------------------------------------------------------------------------
# Egress (DESIGN 2 single egress rule, 4.2 step 7). Everything a recipient learns about tokens,
# vision and explored goes through views.egressFrames; this section only moves the bytes.
proc egressContext(): views.Context =
## A read-only borrow of the world and every player's sight state. The seqs and tables are shared
## by reference and only read before egressFrames returns, so no copy is needed.
views.Context(scene: app.scene, tokens: app.tokens, visions: app.visions)
proc pruneKnown() =
## A closed connection's `known` table must not outlive it.
var live = initHashSet[int]()
for c in app.conns.snapshot(): live.incl c.id
for id in app.known.keys.toSeq:
if id notin live: app.known.del id
proc refreshPlayer(pid: int) =
## Recompute one player's polygons and explored cells (4.2 step 5). Caller holds the lock. The
## sight state is created on first use, so a player who never connected still gets one the moment
## they do (nothing is stale from startup, 4.1). The table entry is passed by reference: reading it
## into a `var` would copy it and the update would be lost.
if pid == GmControlled: return
app.visions.mgetOrPut(pid, PlayerVision()).refresh(app.scene, app.tokens, pid)
proc refreshAll() =
## A wall or door changed: every player's sight changes (4.2 step 5).
for pid in app.visions.keys.toSeq: refreshPlayer(pid)
proc egressAll() =
## One pass over every live connection: build that recipient's view, diff it against what the
## connection already knows, send the difference. 4.2 step 8: the fresh cells are cleared here,
## after every connection of every player has been offered them.
let ctx = egressContext()
for c in app.conns.snapshot():
if c.role != prGm and not c.named:
continue # 6.3: an unnamed player gets `hello` and nothing else until it is named
let recipient = views.Recipient(isGm: c.role == prGm, playerId: c.playerId)
let frames = egressFrames(recipient, ctx, app.known.mgetOrPut(c.id, views.Known()))
for f in frames:
let n = nextN(c)
if n > 0: c.ws.send($withN(f, n))
for pid in app.visions.keys.toSeq: app.visions[pid].clearFresh()
pruneKnown()
proc resync(connId: int, named: bool, player: Player) =
## The 6.3 sequence after `hello`, for the parts this slice has: GM gets `walls` then every token;
## a named player gets `vision`, `explored` (full) then every token it may see. An unnamed player
## gets nothing beyond `hello`.
let isGm = player.role == prGm
let found = app.conns.connById(connId)
if found.isNone: return
let conn = found.get
if isGm or faultActive("walls"):
let snap = wallsSnapshot(app.scene)
let n = nextN(conn)
if n > 0: conn.ws.send($withN(snap, n))
if not isGm and not named: return
let recipient = views.Recipient(isGm: isGm, playerId: player.id)
# The diff state is passed by reference straight out of the table: `var known = ...mgetOrPut(...)`
# would COPY the entry and the connection would forget everything it learnt on connect.
for f in egressFrames(recipient, egressContext(),
app.known.mgetOrPut(conn.id, views.Known()), resync = true):
let n = nextN(conn)
if n > 0: conn.ws.send($withN(f, n))
proc settle(conn: Conn, reqId: int, extra: JsonNode = nil) =
## 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
## the effects that mutation caused. Every frame is built from the state at enqueue time, so a
## mutation that runs between another mutation's transaction and its settle cannot send stale
## state; the exact per-connection ordering of two concurrent mutations, and the coalescing that
## makes it cheap, are the M5 outbox (4.3).
withLock app.dbLock:
ackOk(conn, reqId, extra)
egressAll()
proc settleWorld(conn: Conn, reqId: int, wallEffect: JsonNode, extra: JsonNode = nil) =
## The same for a wall/door write: ack, the GM-only wall effect, then the per-recipient egress
## (a wall change can reveal or hide tokens and always changes vision).
withLock app.dbLock:
ackOk(conn, reqId, extra)
sendToGms(wallEffect)
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.
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).
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
app.db.exec(sql"BEGIN")
try:
for (_, stored) in moved: discard writePosition(app.db, stored)
app.db.exec(sql"COMMIT")
except CatchableError:
try: app.db.exec(sql"ROLLBACK")
except CatchableError: discard
raise
for (ti, stored) in moved:
app.tokens[ti] = stored
refreshPlayer(stored.owner)
# ---------------------------------------------------------------------------------------------------
# Intent field helpers (DESIGN 6.1, 6.5 steps 7-8): shape first, then lookup.
@@ -134,6 +280,50 @@ proc sceneOk(conn: Conn, env: Envelope): bool =
of scNotFound: ackErr(conn, env.reqId, CodeNotFound)
of scOk: return true
proc stringField(env: Envelope, key: string, dest: var string): bool =
let node = env.node{key}
if node.isNil or node.kind != JString: return false
dest = node.getStr
true
proc boolField(env: Envelope, key: string, dest: var bool): bool =
let node = env.node{key}
if node.isNil or node.kind != JBool: return false
dest = node.getBool
true
proc present(env: Envelope, key: string): bool =
## The field exists and is not JSON null (DESIGN 6.1: absent and null are the same for these
## payloads, except where a null has its own meaning, e.g. `controller` and `vision_radius`).
not fieldOrNull(env.node, key).isNil
proc declared(env: Envelope, key: string): bool =
## The field is there, JSON null included: `controller: null` means "the GM" and
## `vision_radius: null` means "the scene default" (6.1), so both are real patch fields.
not env.node.isNil and env.node.hasKey(key)
type
ControllerCheck = enum
ccOk
ccInvalid
ccNotFound
proc resolveController(raw: JsonNode, dest: var int): ControllerCheck =
## `controller`: a player id, or null = the GM (DESIGN 6.1). The GM's own player id is stored as
## GM-controlled, so "the GM controls it" has one representation in memory and on the wire.
## Reads the DB (6.5 step 8): the caller holds the lock.
if raw.isNil or raw.kind == JNull:
dest = GmControlled
return ccOk
if raw.kind != JInt: return ccInvalid
let id = raw.getInt
if id == app.gmPlayerId:
dest = GmControlled
return ccOk
if playerById(app.db, id).isNone: return ccNotFound
dest = id
ccOk
# ---------------------------------------------------------------------------------------------------
# HTTP helpers
@@ -277,42 +467,44 @@ proc wsUpgrade(request: Request) {.gcsafe.} =
let pid = player.get.id
let role = player.get.role
let named = player.get.name.isSome
let activated = app.conns.activate(pid, role, ws, named)
# Close the replacement race: a key.replace between the lookup and the activation must not leave
# a live connection on a revoked session.
var stillValid = false
let playerRec = player.get
var activated: Activation
# The activation, `hello` and the 6.3 resync run under the global lock: a mutation must not slip
# in between the registry entry and `hello` (which would put a state frame before the first frame,
# 6.1) nor between `hello` and the resync (the resync's `known` table is the diff base).
withLock app.dbLock:
stillValid = sessionPlayer(app.db, sha256Hex(token)).isSome
if not stillValid:
if app.conns.connById(activated.id).isSome:
let live = app.conns.connById(activated.id).get
closeRegistered(live, ReasonRevoked, CloseRevoked)
return
if activated.evicted.isSome:
let doomed = activated.evicted.get
closeGone(doomed, ReasonEvicted, CloseEvicted)
app.lg.log(lvInfo, "conn_evicted", [("player", $pid), ("evicted_conn", $doomed.id)])
app.lg.log(lvInfo, "conn_open", [("player", $pid), ("role", $role),
("conn", $activated.id), ("total", $app.conns.activeCount)])
activated = app.conns.activate(pid, role, ws, named)
# Close the replacement race: a key.replace between the lookup and the activation must not
# leave a live connection on a revoked session.
if sessionPlayer(app.db, sha256Hex(token)).isNone:
if app.conns.connById(activated.id).isSome:
closeRegistered(app.conns.connById(activated.id).get, ReasonRevoked, CloseRevoked)
return
if activated.evicted.isSome:
let doomed = activated.evicted.get
closeGone(doomed, ReasonEvicted, CloseEvicted)
app.lg.log(lvInfo, "conn_evicted", [("player", $pid), ("evicted_conn", $doomed.id)])
app.lg.log(lvInfo, "conn_open", [("player", $pid), ("role", $role),
("conn", $activated.id), ("total", $app.conns.activeCount)])
# `hello` is the first frame on the connection (n = 1). The scene block and the resync sequence
# arrive with slice 5; this slice sends proto, role and me (DESIGN 6.1, 6.3). It is queued here,
# before the handler returns, and a browser cannot send anything before it has seen the 101, so
# in practice nothing can overtake it.
let me = if player.get.name.isSome: %player.get.name.get else: newJNull()
let helloN = app.conns.nextFrameNo(activated.id)
ws.send($helloFrame(ProtoVersion, helloN, $role, pid, me))
# One Ping right away, then one every PingIntervalMs: the browser answers without JS (4.3).
ws.send($nextPingSeq(), Ping)
if player.get.role == prGm:
# The wall part of the GM snapshot (6.1 `walls`: on connect and resync). The rest of the 6.3
# sequence (roster, characters, encountered, tokens) arrives with slices 5-8; players never
# receive wall data at all (3.1, T2).
var snapshot: JsonNode
withLock app.dbLock:
snapshot = wallsSnapshot(app.scene)
let snapN = app.conns.nextFrameNo(activated.id)
if snapN > 0: ws.send($withN(snapshot, snapN))
# `hello` is the first frame on the connection (n = 1). An unnamed player gets `proto, role, me`
# and nothing else; a named player and the GM get the scene block (6.1: no counts, no wall data,
# no owned ids; `mine` travels on `token`).
let me = if playerRec.name.isSome: %playerRec.name.get else: newJNull()
var sceneJson: JsonNode
if role == prGm or named:
sceneJson = sceneBlock(app.scene)
var extraJson: JsonNode
if role == prGm: extraJson = app.scene.extra
let helloN = app.conns.nextFrameNo(activated.id)
if helloN > 0: ws.send($helloFrame(ProtoVersion, helloN, $role, pid, me, sceneJson, extraJson))
# One Ping right away, then one every PingIntervalMs: the browser answers without JS (4.3).
ws.send($nextPingSeq(), Ping)
# The 6.3 order for the parts this slice has: GM: `walls` then every token; player: `vision`,
# `explored` (full) then every token it may see. Players never receive wall data (3.1, T2).
if role != prGm and named:
refreshPlayer(pid)
resync(activated.id, named, playerRec)
# ---------------------------------------------------------------------------------------------------
# Intent pipeline (DESIGN 6.5). Order: parse, rate limit, unknown type, unnamed player, role,
@@ -422,8 +614,235 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
return
let closed = app.conns.revokePlayer(id)
for doomed in closed: closeGone(doomed, ReasonRevoked, CloseRevoked)
# DESIGN 3.2: that player's controlled tokens pass to the GM. The FK's ON DELETE SET NULL did
# the row; memory (and the `controller: null` the GM sees) follows here.
for t in app.tokens.mitems:
if t.owner == id: t.owner = GmControlled
app.visions.del id
app.lg.log(lvInfo, "player_removed", [("player", $id), ("conns_closed", $closed.len)])
ackOk(conn, env.reqId)
settle(conn, env.reqId)
return
of "token.create":
if not sceneOk(conn, env): return
var kind, dname, aname: string
if not stringField(env, "kind", kind) or not validKind(kind):
ackErr(conn, env.reqId, CodeInvalid)
return
if not stringField(env, "descriptive_name", dname) or not validName(dname):
ackErr(conn, env.reqId, CodeInvalid)
return
if not stringField(env, "actual_name", aname) or not validName(aname):
ackErr(conn, env.reqId, CodeInvalid)
return
let pos = parseVec(fieldOrNull(env.node, "pos"))
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
var gmOnly = false
if present(env, "gm_only") and not boolField(env, "gm_only", gmOnly):
ackErr(conn, env.reqId, CodeInvalid)
return
let flags = parseFlags(fieldOrNull(env.node, "flags"))
if flags.isNone:
ackErr(conn, env.reqId, CodeInvalid)
return
let vr = parseVisionRadius(fieldOrNull(env.node, "vision_radius"))
if vr.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)
controllerCheck = resolveController(env.node{"controller"}, candidate.owner)
if controllerCheck == ccOk:
created = addToken(app.db, app.scene, candidate, app.tokens.mapIt(it.id))
if created.outcome == toOk:
app.tokens.add created.token
refreshPlayer(created.token.owner)
if controllerCheck == ccInvalid:
ackErr(conn, env.reqId, CodeInvalid)
return
if controllerCheck == ccNotFound:
ackErr(conn, env.reqId, CodeNotFound) # no such controller player
return
if created.outcome != toOk:
ackErr(conn, env.reqId, CodeInvalid)
return
app.lg.log(lvInfo, "token_create", [("token", created.token.id),
("scene", $created.token.scene)])
settle(conn, env.reqId, %*{"id": created.token.id})
return
of "token.update":
var id: string
if not stringField(env, "id", id):
ackErr(conn, env.reqId, CodeInvalid)
return
if present(env, "character_id"):
ackErr(conn, env.reqId, CodeInvalid) # the character link is slice 8 (#23)
return
var patch: TokenPatch
var anyField = false
if present(env, "kind"):
var kind: string
if not stringField(env, "kind", kind) or not validKind(kind):
ackErr(conn, env.reqId, CodeInvalid)
return
patch.kind = some(kind)
anyField = true
for field in ["descriptive_name", "actual_name"]:
if not present(env, field): continue
var name: string
if not stringField(env, field, name) or not validName(name):
ackErr(conn, env.reqId, CodeInvalid)
return
if field == "descriptive_name": patch.descriptiveName = some(name)
else: patch.actualName = some(name)
anyField = true
if present(env, "gm_only"):
var gmOnly: bool
if not boolField(env, "gm_only", gmOnly):
ackErr(conn, env.reqId, CodeInvalid)
return
patch.gmOnly = some(gmOnly)
anyField = true
if present(env, "flags"):
let flags = parseFlags(env.node{"flags"})
if flags.isNone:
ackErr(conn, env.reqId, CodeInvalid)
return
patch.flags = flags
anyField = true
if declared(env, "vision_radius"):
let vr = parseVisionRadius(env.node{"vision_radius"})
if vr.isNone:
ackErr(conn, env.reqId, CodeInvalid)
return
patch.visionRadius = vr
anyField = true
let controllerSeen = declared(env, "controller")
if controllerSeen:
# null (the GM) or an integer; anything else is a mistyped field (6.5 step 7)
let raw = env.node{"controller"}
if raw.kind notin {JInt, JNull}:
ackErr(conn, env.reqId, CodeInvalid)
return
anyField = true
if not anyField:
# `token.update` changes at least one field (6.1); a fieldless update is invalid (6.5 step 7).
ackErr(conn, env.reqId, CodeInvalid)
return
var outcome = toNotFound
var updated: TokenRec
var controllerCheck = ccOk
var controller = GmControlled
withLock app.dbLock:
let current = tokenById(app.tokens, id)
if current.isSome:
if controllerSeen:
controllerCheck = resolveController(env.node{"controller"}, controller)
if controllerCheck == ccOk: patch.controller = some(controller)
if controllerCheck == ccOk:
let candidate = patched(current.get, patch)
outcome = storeToken(app.db, app.scene, candidate)
if outcome == toOk:
let oldOwner = current.get.owner
updated = candidate
app.tokens[tokenIndex(app.tokens, id).get] = updated
refreshPlayer(oldOwner)
refreshPlayer(updated.owner)
if controllerCheck == ccInvalid:
ackErr(conn, env.reqId, CodeInvalid)
return
if controllerCheck == ccNotFound:
ackErr(conn, env.reqId, CodeNotFound)
return
if outcome == toNotFound:
ackErr(conn, env.reqId, CodeNotFound)
return
if outcome != toOk:
ackErr(conn, env.reqId, CodeInvalid)
return
app.lg.log(lvInfo, "token_update", [("token", id)])
settle(conn, env.reqId)
return
of "token.move":
var id: string
if not stringField(env, "id", id):
ackErr(conn, env.reqId, CodeInvalid)
return
let dest = parseVec(fieldOrNull(env.node, "pos"))
if dest.isNone:
ackErr(conn, env.reqId, CodeInvalid)
return
var kind = mkError
var resultPos: Vec
withLock app.dbLock:
let idx = tokenIndex(app.tokens, id)
if idx.isNone:
# T9: a player gets one code for "unknown" and "not yours" (no existence oracle); a GM's
# missing target is not-found (6.5 step 8). Nothing is applied either way.
kind = mkError
elif conn.role != prGm and app.tokens[idx.get].owner != conn.playerId:
kind = mkError
else:
var mr = moveScene(app.scene, app.tokens)
let actor = if conn.role == prGm: Actor(role: roleGM, player: conn.playerId)
else: Actor(role: rolePlayer, player: conn.playerId)
let moved = moveToken(mr, actor, idx.get, dest.get)
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
discard writePosition(app.db, app.tokens[idx.get])
refreshPlayer(app.tokens[idx.get].owner)
case kind
of mkError:
ackErr(conn, env.reqId, if conn.role == prGm: CodeNotFound else: CodeNotAllowed)
return
of mkNack:
# The uniform move refusal (5.5, T9): the old position and no code, one shape for locked,
# over-cap and collision alike.
let n = nextN(conn)
if n > 0: conn.ws.send($nackMoveFrame(env.reqId, n, resultPos.x, resultPos.y))
return
of mkAck:
settle(conn, env.reqId, %*{"pos": [resultPos.x, resultPos.y]})
return
of "token.remove":
var id: string
if not stringField(env, "id", id):
ackErr(conn, env.reqId, CodeInvalid)
return
var removed = false
withLock app.dbLock:
let idx = tokenIndex(app.tokens, id)
if idx.isSome:
removed = removeToken(app.db, id)
if removed:
let owner = app.tokens[idx.get].owner
app.tokens.delete idx.get
refreshPlayer(owner)
if not removed:
ackErr(conn, env.reqId, CodeNotFound)
return
app.lg.log(lvInfo, "token_remove", [("token", id)])
settle(conn, env.reqId)
return
of "wall.add":
@@ -457,14 +876,16 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
var added: Option[WallRec]
withLock app.dbLock:
let id = addWall(app.db, app.scene, candidate)
if id.isSome: added = wallById(app.scene, id.get)
if id.isSome:
added = wallById(app.scene, id.get)
refreshAll() # 4.2 step 5: a wall change moves every player's sight
if added.isNone:
ackErr(conn, env.reqId, CodeInvalid) # degenerate or out-of-bounds geometry
return
app.lg.log(lvInfo, "wall_add", [("scene", $app.scene.id), ("wall", $added.get.id),
("kind", $added.get.kind)])
ackOk(conn, env.reqId, %*{"id": added.get.id})
sendToGms(wallFrame(app.scene.id, wallObjectOf(added.get)))
settleWorld(conn, env.reqId, wallFrame(app.scene.id, wallObjectOf(added.get)),
%*{"id": added.get.id})
return
of "wall.update":
@@ -517,7 +938,9 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
let current = wallById(app.scene, id)
if current.isSome:
outcome = updateWall(app.db, app.scene, patched(current.get, patch))
if outcome == waOk: updated = wallById(app.scene, id)
if outcome == waOk:
updated = wallById(app.scene, id)
refreshAll()
if outcome == waNotFound:
ackErr(conn, env.reqId, CodeNotFound)
return
@@ -526,8 +949,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
return
app.lg.log(lvInfo, "wall_update", [("scene", $app.scene.id), ("wall", $id),
("kind", $updated.get.kind)])
ackOk(conn, env.reqId)
sendToGms(wallFrame(app.scene.id, wallObjectOf(updated.get)))
settleWorld(conn, env.reqId, wallFrame(app.scene.id, wallObjectOf(updated.get)))
return
of "wall.remove":
@@ -539,12 +961,12 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
var outcome = waNotFound
withLock app.dbLock:
outcome = removeWall(app.db, app.scene, id)
if outcome == waOk: refreshAll()
if outcome == waNotFound:
ackErr(conn, env.reqId, CodeNotFound)
return
app.lg.log(lvInfo, "wall_remove", [("scene", $app.scene.id), ("wall", $id)])
ackOk(conn, env.reqId)
sendToGms(wallGoneFrame(app.scene.id, id))
settleWorld(conn, env.reqId, wallGoneFrame(app.scene.id, id))
return
of "door.set":
@@ -560,9 +982,14 @@ 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
outcome = setDoor(app.db, app.scene, id, open)
if outcome == waOk: updated = wallById(app.scene, id)
if outcome == waOk:
updated = wallById(app.scene, id)
applyPushes(pushes)
refreshAll()
if outcome == waNotFound:
ackErr(conn, env.reqId, CodeNotFound)
return
@@ -571,8 +998,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
return
app.lg.log(lvInfo, "door_set", [("scene", $app.scene.id), ("wall", $id),
("open", $open)])
ackOk(conn, env.reqId)
sendToGms(wallFrame(app.scene.id, wallObjectOf(updated.get)))
settleWorld(conn, env.reqId, wallFrame(app.scene.id, wallObjectOf(updated.get)))
return
else:
@@ -776,7 +1202,11 @@ proc runServer(cfg: Config): int =
lg.log(lvError, "scene_missing", [("path", cfg.dbPath), ("scene", $DefaultSceneId)])
return 1
state.scene = loaded.get
state.tokens = loadTokens(conn, state.scene.id)
let gm = gmPlayer(conn)
if gm.isSome: state.gmPlayerId = gm.get.id
lg.log(lvInfo, "scene_loaded", [("scene", $state.scene.id), ("walls", $state.scene.walls.len),
("tokens", $state.tokens.len),
("next_wall_id", $state.scene.nextWallId)])
appHandle = cast[pointer](state)