server: load and persist explored with every mutation (#21)

Startup restores each player's grid from its chunk rows (explored_loaded log) and every
mutation writes only the chunks its refresh dirtied, in the mutation's transaction: a move
keeps position and chunks in one NORMAL commit, a GM authoring write adds one NORMAL chunk
transaction under the same lock, before the ack. db.withTransaction is the shared seam.
This commit is contained in:
2026-11-15 09:58:19 +01:00
parent 22014a36dc
commit df4634d12a
2 changed files with 61 additions and 12 deletions
+59 -11
View File
@@ -11,6 +11,9 @@
## through server/moverules.nim, one vision polygon per controlled token with the `vision` flag, the ## 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 ## 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. ## server/views.nim from a typed `GmView`/`PlayerView`, so raw world state has no other path out.
## 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).
## Close reasons (FIXED, owner decision #18): mummy 0.4.8 cannot put a code in the close frame, so ## 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 ## every server-initiated close is preceded by a `closing {reason, code}` message and the client
## reads 1005 + that message (DESIGN 6.5). ## reads 1005 + that message (DESIGN 6.5).
@@ -20,7 +23,7 @@ import std/typedthreads
import db_connector/db_sqlite import db_connector/db_sqlite
import mummy, mummy/routers import mummy, mummy/routers
import config, db, eventlog, crypto, auth, conns, instancelock, protocol, world import config, db, eventlog, crypto, auth, conns, instancelock, protocol, world
import geometry, tokens, vision, views, worldmap, faults, moverules import geometry, tokens, vision, views, explored, worldmap, faults, moverules
const const
CookieName* = "fff_session" CookieName* = "fff_session"
@@ -152,6 +155,36 @@ proc refreshAll() =
## A wall or door changed: every player's sight changes (4.2 step 5). ## A wall or door changed: every player's sight changes (4.2 step 5).
for pid in app.visions.keys.toSeq: refreshPlayer(pid) for pid in app.visions.keys.toSeq: refreshPlayer(pid)
# ---------------------------------------------------------------------------------------------------
# Explored persistence (DESIGN 4.2 step 6, 4.4; M3 slice 6 / #21). The grid lives in memory; this is
# the only place it reaches the DB. One rule: a mutation writes exactly the chunks its refresh
# dirtied, never the whole grid, and the write rides in the mutation's transaction so an ack cannot
# precede the cells it reports. NORMAL durability (Q12): explored is derived and monotone, not
# GM-authored content.
proc dirtyExplored(pids: openArray[int]): seq[explored.Chunk] =
## The chunks the last refresh dirtied, for the named players. Caller holds the lock and has
## already refreshed those players, so `fresh` is current. A player with nothing fresh costs one
## table lookup and is skipped.
for pid in pids:
if pid == GmControlled: continue
let fresh = app.visions.mgetOrPut(pid, PlayerVision()).fresh
if fresh.len == 0: continue
for c in explored.dirtyChunks(app.scene, pid,
app.visions.mgetOrPut(pid, PlayerVision()).explored, fresh):
result.add c
proc persistExplored(pids: openArray[int]) =
## Writes the dirtied chunks. No transaction of its own: the caller wraps it together with the
## mutation's own row writes (db.withTransaction).
let chunks = dirtyExplored(pids)
if chunks.len > 0: discard explored.writeChunks(app.db, app.scene.id, chunks)
proc persistAllExplored() =
## After `refreshAll` (a wall or door changed): every player whose grid grew, in one transaction.
app.db.withTransaction:
persistExplored(app.visions.keys.toSeq)
proc egressAll() = proc egressAll() =
## One pass over every live connection: build that recipient's view, diff it against what the ## 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, ## connection already knows, send the difference. 4.2 step 8: the fresh cells are cleared here,
@@ -227,7 +260,8 @@ proc planDoorClose(wallId: int, open: bool): seq[moverules.Push] =
proc applyPushes(pushes: seq[moverules.Push]) = proc applyPushes(pushes: seq[moverules.Push]) =
## Runs after the door write committed: one transaction for the new positions (a move is NORMAL ## 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 ## 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). ## 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 if pushes.len == 0: return
var moved: seq[(int, TokenRec)] var moved: seq[(int, TokenRec)]
for p in pushes: for p in pushes:
@@ -238,14 +272,8 @@ proc applyPushes(pushes: seq[moverules.Push]) =
stored.pos = p.pos stored.pos = p.pos
moved.add (p.ti, stored) moved.add (p.ti, stored)
if moved.len == 0: return if moved.len == 0: return
app.db.exec(sql"BEGIN") app.db.withTransaction:
try:
for (_, stored) in moved: discard writePosition(app.db, stored) 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: for (ti, stored) in moved:
app.tokens[ti] = stored app.tokens[ti] = stored
refreshPlayer(stored.owner) refreshPlayer(stored.owner)
@@ -669,6 +697,8 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
if created.outcome == toOk: if created.outcome == toOk:
app.tokens.add created.token app.tokens.add created.token
refreshPlayer(created.token.owner) refreshPlayer(created.token.owner)
app.db.withTransaction:
persistExplored(@[created.token.owner])
if controllerCheck == ccInvalid: if controllerCheck == ccInvalid:
ackErr(conn, env.reqId, CodeInvalid) ackErr(conn, env.reqId, CodeInvalid)
return return
@@ -762,6 +792,8 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
app.tokens[tokenIndex(app.tokens, id).get] = updated app.tokens[tokenIndex(app.tokens, id).get] = updated
refreshPlayer(oldOwner) refreshPlayer(oldOwner)
refreshPlayer(updated.owner) refreshPlayer(updated.owner)
app.db.withTransaction:
persistExplored(@[oldOwner, updated.owner])
if controllerCheck == ccInvalid: if controllerCheck == ccInvalid:
ackErr(conn, env.reqId, CodeInvalid) ackErr(conn, env.reqId, CodeInvalid)
return return
@@ -808,8 +840,12 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
app.tokens[idx.get].pos = moved.pos app.tokens[idx.get].pos = moved.pos
app.tokens[idx.get].prev = mr.tokens[idx.get].prev app.tokens[idx.get].prev = mr.tokens[idx.get].prev
app.tokens[idx.get].hasPrev = mr.tokens[idx.get].hasPrev app.tokens[idx.get].hasPrev = mr.tokens[idx.get].hasPrev
discard writePosition(app.db, app.tokens[idx.get])
refreshPlayer(app.tokens[idx.get].owner) 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])
persistExplored(@[app.tokens[idx.get].owner])
case kind case kind
of mkError: of mkError:
ackErr(conn, env.reqId, if conn.role == prGm: CodeNotFound else: CodeNotAllowed) ackErr(conn, env.reqId, if conn.role == prGm: CodeNotFound else: CodeNotAllowed)
@@ -838,6 +874,8 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
let owner = app.tokens[idx.get].owner let owner = app.tokens[idx.get].owner
app.tokens.delete idx.get app.tokens.delete idx.get
refreshPlayer(owner) refreshPlayer(owner)
app.db.withTransaction:
persistExplored(@[owner])
if not removed: if not removed:
ackErr(conn, env.reqId, CodeNotFound) ackErr(conn, env.reqId, CodeNotFound)
return return
@@ -879,6 +917,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
if id.isSome: if id.isSome:
added = wallById(app.scene, id.get) added = wallById(app.scene, id.get)
refreshAll() # 4.2 step 5: a wall change moves every player's sight 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: if added.isNone:
ackErr(conn, env.reqId, CodeInvalid) # degenerate or out-of-bounds geometry ackErr(conn, env.reqId, CodeInvalid) # degenerate or out-of-bounds geometry
return return
@@ -941,6 +980,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
if outcome == waOk: if outcome == waOk:
updated = wallById(app.scene, id) updated = wallById(app.scene, id)
refreshAll() refreshAll()
persistAllExplored()
if outcome == waNotFound: if outcome == waNotFound:
ackErr(conn, env.reqId, CodeNotFound) ackErr(conn, env.reqId, CodeNotFound)
return return
@@ -961,7 +1001,9 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
var outcome = waNotFound var outcome = waNotFound
withLock app.dbLock: withLock app.dbLock:
outcome = removeWall(app.db, app.scene, id) outcome = removeWall(app.db, app.scene, id)
if outcome == waOk: refreshAll() if outcome == waOk:
refreshAll()
persistAllExplored()
if outcome == waNotFound: if outcome == waNotFound:
ackErr(conn, env.reqId, CodeNotFound) ackErr(conn, env.reqId, CodeNotFound)
return return
@@ -990,6 +1032,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
updated = wallById(app.scene, id) updated = wallById(app.scene, id)
applyPushes(pushes) applyPushes(pushes)
refreshAll() refreshAll()
persistAllExplored()
if outcome == waNotFound: if outcome == waNotFound:
ackErr(conn, env.reqId, CodeNotFound) ackErr(conn, env.reqId, CodeNotFound)
return return
@@ -1203,11 +1246,16 @@ proc runServer(cfg: Config): int =
return 1 return 1
state.scene = loaded.get state.scene = loaded.get
state.tokens = loadTokens(conn, state.scene.id) state.tokens = loadTokens(conn, state.scene.id)
# 4.4 startup / slice 6: the players' explored grids come back from their chunk rows. Polygons are
# never stored; the sight state is rebuilt from the loaded walls on the player's first refresh.
state.visions = explored.restore(conn, state.scene)
let gm = gmPlayer(conn) let gm = gmPlayer(conn)
if gm.isSome: state.gmPlayerId = gm.get.id if gm.isSome: state.gmPlayerId = gm.get.id
lg.log(lvInfo, "scene_loaded", [("scene", $state.scene.id), ("walls", $state.scene.walls.len), lg.log(lvInfo, "scene_loaded", [("scene", $state.scene.id), ("walls", $state.scene.walls.len),
("tokens", $state.tokens.len), ("tokens", $state.tokens.len),
("next_wall_id", $state.scene.nextWallId)]) ("next_wall_id", $state.scene.nextWallId)])
lg.log(lvInfo, "explored_loaded", [("players", $state.visions.len),
("chunks", $explored.chunkCount(conn, state.scene.id))])
appHandle = cast[pointer](state) appHandle = cast[pointer](state)
createThread(heartbeatThread, heartbeat) createThread(heartbeatThread, heartbeat)
+2 -1
View File
@@ -10,7 +10,8 @@
## Explored (5.1, 8): the union of the cells every polygon ever overlapped, per player, strictly ## Explored (5.1, 8): the union of the cells every polygon ever overlapped, per player, strictly
## per player (Q9 FIXED). It only grows: a wall edit or a door closing never un-explores. `cells` ## per player (Q9 FIXED). It only grows: a wall edit or a door closing never un-explores. `cells`
## are `(cx, cy)` from the world origin, cell size = the scene's `cell` (= `tile_size` in v1, Q4). ## are `(cx, cy)` from the world origin, cell size = the scene's `cell` (= `tile_size` in v1, Q4).
## Persistence (chunked bitmaps, #21) is slice 6; this module owns the in-memory set only. ## Persistence (chunked bitmaps, #21) lives in server/explored.nim, which stores this module's
## `explored` set and restores it at startup; this module owns the in-memory set only.
## ##
## Token visibility to a player (3.1): a token this player controls is always visible; any other ## Token visibility to a player (3.1): a token this player controls is always visible; any other
## token only while its centre is inside one of the player's polygons and it is not `gm_only`. ## token only while its centre is inside one of the player's polygons and it is not `gm_only`.