feat: session cache, explored bitmap and lock-free tile gate (#65)

The tile gate no longer takes dbLock or runs a SQL session JOIN per tile: a published
in-memory view (server/sessions.nim) holds token hashes -> player/role and one explored
bitmap per player. Sessions load from the DB at startup and are updated by join, key
replacement and player removal in the same lock as the write; refreshed cells publish
before the ack. The gate is one snapshot read (parse + session + bit test + redirect)
over scalar data only, so a tile burst is answered while a mutation holds dbLock.

Evidence: tests/tsessions.nim pins the cache/bitmap lifecycle and gate rule; tiles.test
adds the lock-held burst and the revocation/restart seam; auth.test adds the
LEAK_FAULT=sessioncache negative control (a stale entry makes the auth group fail);
mutation c5 keeps the cache drop load-bearing. Explored wire and persistence untouched.

Bench (devbox run bench, in-process): tile gate old 0.006 ms -> new 0.001 ms per
request; incremental explored mark 0.001 ms; snapshot build 2.0 ms at 262144 cells
(startup only).
This commit is contained in:
2026-11-21 00:10:39 +01:00
parent 3c0258ea31
commit 2727617db9
12 changed files with 664 additions and 56 deletions
+66 -34
View File
@@ -27,6 +27,11 @@
## 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).
## #65 (build item 6): the tile gate no longer takes `dbLock` or runs SQL per tile. `app.gate`
## (server/sessions.nim) is the published read-side view - token hash -> session entry, loaded from
## the DB at startup and kept current by join/replace/remove, plus one explored bitmap per player,
## updated by each refresh. `tileGate` is one snapshot read; `wall`/`token` mutations pay only a
## few-microsecond publish before the ack.
## 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.
@@ -40,6 +45,7 @@ import db_connector/db_sqlite
import mummy, mummy/routers
import config, db, eventlog, crypto, auth, conns, instancelock, protocol, world, jsonbound
import characters, geometry, markers, props, text, tiles, tokens, vision, views, explored, worldmap, faults, moverules
import sessions
const
CookieName* = "fff_session"
@@ -57,6 +63,9 @@ type
db: DbConn
dbLock: Lock
## The one global lock (DESIGN 4.3): it serializes every mutation, the DB, and the world below.
gate: GateCache
## The tile gate's read-side view (#65): session entries and the explored bitmap, published
## under `dbLock` and read under the cache's own mutex. No tile request takes `dbLock`.
conns: Conns
instanceLock: InstanceLock
scene: SceneRec
@@ -201,8 +210,13 @@ proc refreshPlayer(pid: int) =
## into a `var` would copy it and the update would be lost. The same refresh mints the player's
## markers (5.8): the polygon is the gate, so it must run after `refresh`.
if pid == GmControlled: return
app.visions.mgetOrPut(pid, PlayerVision()).refresh(app.scene, app.tokens, pid)
discard markers.syncMarkers(app.visions.mgetOrPut(pid, PlayerVision()), app.scene)
# Borrow the entry: `let` would copy the whole PlayerVision (polygons, explored set, markers).
let pv = addr app.visions.mgetOrPut(pid, PlayerVision())
pv[].refresh(app.scene, app.tokens, pid)
discard markers.syncMarkers(pv[], app.scene)
# Publish the cells this refresh added to the tile gate's bitmap (#65). `fresh` is idempotent
# until the egress clears it, so a second refresh before the ack re-sets the same bits.
app.gate.markExplored(pid, app.scene, pv[].fresh)
proc refreshAll() =
## A wall or door changed: every player's sight changes (4.2 step 5).
@@ -752,7 +766,10 @@ proc join(request: Request) {.gcsafe.} =
player = findPlayerByKey(app.db, key)
if player.isSome:
token = randomSessionToken()
createSession(app.db, player.get.id, sha256Hex(token))
let hash = sha256Hex(token)
createSession(app.db, player.get.id, hash)
# #65: publish the new session before any tile or upgrade can ask for it.
app.gate.putSession(hash, player.get.id, player.get.role == prGm)
if player.isNone:
# No key, no body, no detail: a wrong key and an unknown key look the same (T9 discipline).
app.lg.log(lvInfo, "join_refused")
@@ -777,43 +794,32 @@ proc join(request: Request) {.gcsafe.} =
request.respond(303, headers)
proc tileGate(request: Request) {.gcsafe.} =
## GET /tiles/<scene>/v<art_version>/<x>_<y>.png (DESIGN 3.3, 6.6; slice 9 / #24). Order: parse
## the URL (malformed, out of range, another scene, stale art version -> 404 whatever the session),
## then the session (missing or unknown -> 403), then the explored grid (unexplored -> 403).
## The GM is always allowed. Nim never opens a tile file: a `200` carries `X-Accel-Redirect` to
## the internal `/_tiles/` location and `Cache-Control: private` (Q4), and nginx serves the bytes.
## GET /tiles/<scene>/v<art_version>/<x>_<y>.png (DESIGN 3.3, 6.6; slice 9 / #24, #65). Order:
## parse the URL (malformed, out of range, another scene, stale art version -> 404 whatever the
## session), then the session (missing or unknown -> 403), then the explored bitmap (unexplored ->
## 403). The GM is always allowed. Nim never opens a tile file: a `200` carries
## `X-Accel-Redirect` to the internal `/_tiles/` location and `Cache-Control: private` (Q4), and
## nginx serves the bytes.
##
## The scene is read exactly once, under the global lock (#31): `scene.set` reassigns `app.scene`
## under that same lock, so this request parses the URL, checks the explored grid and builds the
## redirect from ONE record. A second read could see a swapped scene whose `walls`/`artVersion`
## disagree with the parse (the old code read it three times, twice outside the lock).
## No `dbLock` (issue #65): the whole decision is one read of the gate's published snapshot, which
## holds the scalar scene record, the session table and the explored bitmap. A mutation holding
## the global lock for its write/COMMIT cannot delay a tile burst, and a tile never hashes a
## session or runs SQL. `gateTile` is the one record of the request (#31): parse, decision and
## redirect all come from the same snapshot.
let token = sessionCookie(request)
var parsed: tuple[outcome: TileOutcome, req: TileRequest]
var player: Option[Player]
var allowed = false
var redirect = ""
withLock app.dbLock:
let sc = app.scene # the one read of the request
parsed = parseTileRequest(request.pathParams["scene"], request.pathParams["version"],
request.pathParams["file"], sc)
if parsed.outcome == toTileOk:
if token.len > 0: player = sessionPlayer(app.db, sha256Hex(token))
if player.isSome:
allowed = player.get.role == prGm
if not allowed and app.visions.hasKey(player.get.id):
allowed = tileCoveredByExplored(sc, app.visions[player.get.id].explored,
parsed.req.x, parsed.req.y)
if allowed: redirect = tilePath(sc, parsed.req.x, parsed.req.y)
let hash = if token.len > 0: sha256Hex(token) else: ""
let decision = app.gate.gateTile(hash, request.pathParams["scene"],
request.pathParams["version"], request.pathParams["file"])
if parsed.outcome != toTileOk:
if decision.outcome != toTileOk:
request.respond(404, body = "")
return
if player.isNone or not allowed:
if not decision.session or not decision.allowed:
request.respond(403, body = "")
return
var headers: HttpHeaders
headers["X-Accel-Redirect"] = redirect
headers["X-Accel-Redirect"] = decision.redirect
headers["Cache-Control"] = "private"
request.respond(200, headers)
@@ -827,9 +833,17 @@ proc wsUpgrade(request: Request) {.gcsafe.} =
request.respond(401, body = "")
return
# #65: the session comes from the in-memory cache, so a key replacement or removal is visible
# here the moment it commits. The player record (name, role, colour) is still read from the DB
# under the lock, because a name change does not rewrite every session entry.
let hash = sha256Hex(token)
let cached = app.gate.sessionOf(hash)
if cached.isNone:
request.respond(401, body = "")
return
var player: Option[Player]
withLock app.dbLock:
player = sessionPlayer(app.db, sha256Hex(token))
player = playerById(app.db, cached.get.playerId)
if player.isNone:
request.respond(401, body = "")
return
@@ -874,8 +888,9 @@ proc wsUpgrade(request: Request) {.gcsafe.} =
withLock app.dbLock:
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:
# leave a live connection on a revoked session. Both this check and the drop run under
# `dbLock`, and the drop also publishes the cache change, so the answer is current.
if app.gate.sessionOf(hash).isNone:
if app.conns.connById(activated.id).isSome:
closeRegistered(app.conns.connById(activated.id).get, ReasonRevoked, CloseRevoked)
return
@@ -1050,6 +1065,9 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
notAllowed = true # the GM's own key rotates only through the CLI (DESIGN 3.2)
else:
key = replacePlayerKey(app.db, id)
if key.isSome:
# #65: the revoked sessions must be gone from the tile/upgrade cache before the ack.
app.gate.dropSessions(id)
if notFound:
ackErr(conn, env.reqId, CodeNotFound)
return
@@ -1094,6 +1112,10 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
removed = removePlayer(app.db, id)
else:
removed = removePlayer(app.db, id)
if removed:
# #65: revoke in the same lock as the DELETE, so no tile or upgrade can use the row
# between the commit and the cache drop.
app.gate.dropPlayer(id)
if notFound:
ackErr(conn, env.reqId, CodeNotFound)
return
@@ -1387,6 +1409,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
var kind = mkError
var resultPos: Vec
withLock app.dbLock:
faultHoldLock() # -d:leakfault only: prove the tile gate does not queue on 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
@@ -2472,6 +2495,13 @@ proc runServer(cfg: Config): int =
# 5.8 (#59): the per-player marker memory comes back with the explored state, before the first
# connection, so a reconnecting player gets the full set they had.
markers.restore(conn, state.scene, state.visions)
# #65: the tile gate's read-side view. Sessions come from the DB once (they never expire, Q10);
# explored bitmaps are the rows just restored. After this point a tile request touches neither the
# DB nor `dbLock`.
state.gate = newGateCache(state.scene)
sessions.loadSessions(state.gate, conn)
for pid in state.visions.keys.toSeq:
state.gate.setExplored(pid, explored.bitMapOf(state.scene, state.visions[pid].explored))
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),
@@ -2481,6 +2511,8 @@ proc runServer(cfg: Config): int =
lg.log(lvInfo, "explored_loaded", [("players", $state.visions.len),
("chunks", $explored.chunkCount(conn, state.scene.id)),
("markers", $markers.markerCount(conn, state.scene.id))])
lg.log(lvInfo, "gate_cache_loaded", [("sessions", $state.gate.sessionCount),
("explored_players", $state.gate.exploredPlayers)])
lg.log(lvInfo, "names_loaded", [("reveals", $state.reveals.pairs.len),
("encountered_players", $state.encountered.len)])
appHandle = cast[pointer](state)