Files
SirStone 2727617db9 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).
2026-11-21 00:10:39 +01:00

162 lines
7.4 KiB
Nim

## In-memory session cache and explored bitmap snapshot for the tile gate (DESIGN 3.3, 4.3, 6.6;
## issue #65, ANALYSIS-review build item 6).
##
## Why: the gate used to take the global `dbLock` and, inside it, hash the cookie and run a SQL
## `session JOIN player` per tile. A tile burst therefore queued behind every GM wall edit and its
## COMMIT. The gate now reads a published, in-memory view instead:
## * `sessions`: token hash -> (player id, role), loaded from `session`/`player` at startup,
## added by `POST /join`, dropped by key replacement and player removal;
## * `explored`: player id -> one bit per explored cell (`explored.BitMap`), set for the cells a
## refresh added, restored from the chunk rows at startup.
##
## Locking: one mutex guards this view. It is **not** `dbLock`. A mutation holds `dbLock` for its
## write and COMMIT, then publishes here for a handful of microseconds before the ack; a tile
## request holds only this mutex for a hash lookup and a bit test. The published data is deliberately
## refcount-free on the read path: `SessionEntry` is two ints and the bitmap is passed as a borrowed
## `openArray[byte]`, because ORC reference counts are not atomic and two readers must not touch the
## same `seq` header. `TileScene` (tiles.nim) is likewise all scalars.
##
## Revocation is explicit, never a TTL: `dropSessions` on key replacement, `dropPlayer` on removal
## (sessions and explored), `POST /join` adds. The database stays the source of truth across a
## restart (`loadSessions`). The lifecycle is proven by tests/tsessions.nim and the black-box
## auth/tiles groups; `LEAK_FAULT=sessioncache` keeps a revoked entry alive as the negative control.
import std/[locks, options, sequtils, strutils, tables]
import db_connector/db_sqlite
import explored, faults, tiles, vision, world
type
SessionEntry* = object
## The whole session fact the gate needs. No name, no colour: a tile decision never uses them,
## and keeping the entry ref-free makes the read path safe across worker threads.
playerId*: int
isGm*: bool
GateDecision* = object
## One tile request's answer, computed from one snapshot (URL parse included, 3.3/6.6).
outcome*: TileOutcome
session*: bool ## a live session was found for the cookie
gm*: bool
allowed*: bool
redirect*: string
GateView = object
scene: TileScene
sessions: Table[string, SessionEntry]
explored: Table[int, explored.BitMap]
GateCache* = ref object
lock: Lock
view: GateView
proc newGateCache*(sc: SceneRec): GateCache =
## Empty sessions and explored; the caller loads both before serving.
result = GateCache()
initLock(result.lock)
result.view.scene = tileScene(sc)
result.view.sessions = initTable[string, SessionEntry]()
result.view.explored = initTable[int, explored.BitMap]()
# ---------------------------------------------------------------------------------------------------
# Sessions
proc putSession*(g: GateCache, tokenHash: string, playerId: int, isGm: bool) =
## `POST /join` and the startup loader. A fresh sign-in always gets a fresh token hash, so an
## overwrite is either the same session or a harmless no-op.
if tokenHash.len == 0 or playerId <= 0: return
withLock g.lock:
g.view.sessions[tokenHash] = SessionEntry(playerId: playerId, isGm: isGm)
proc sessionOf*(g: GateCache, tokenHash: string): Option[SessionEntry] =
## The `/ws` upgrade lookup. Returns only scalars, so a caller never holds shared refcounted state.
if tokenHash.len == 0: return none(SessionEntry)
withLock g.lock:
let e = g.view.sessions.getOrDefault(tokenHash)
if e.playerId > 0: result = some(e)
proc dropSessions*(g: GateCache, playerId: int) =
## `key.replace`: every session of that player dies before the next real or tile request reads.
if playerId <= 0: return
if faultActive("sessioncache"): return # test-only negative control (#65)
withLock g.lock:
for h in g.view.sessions.keys.toSeq:
if g.view.sessions[h].playerId == playerId:
g.view.sessions.del h
proc dropPlayer*(g: GateCache, playerId: int) =
## `player.remove`: the key's sessions and the explored snapshot go with the player.
if playerId <= 0: return
if faultActive("sessioncache"): return # test-only negative control (#65)
withLock g.lock:
for h in g.view.sessions.keys.toSeq:
if g.view.sessions[h].playerId == playerId:
g.view.sessions.del h
g.view.explored.del playerId
proc loadSessions*(g: GateCache, db: DbConn) =
## Startup (4.4): the `session` rows are the source of truth, the cache their mirror. Every live
## session (sessions never expire, Q10) is available before the first request is served.
var rows: seq[(string, SessionEntry)]
for row in db.getAllRows(sql"""
SELECT s.token_hash, p.id, p.role
FROM session s JOIN player p ON p.id = s.player_id"""):
rows.add (row[0], SessionEntry(playerId: parseInt(row[1]), isGm: row[2] == "gm"))
withLock g.lock:
g.view.sessions.clear()
for (h, e) in rows: g.view.sessions[h] = e
proc sessionCount*(g: GateCache): int =
withLock g.lock:
result = g.view.sessions.len
# ---------------------------------------------------------------------------------------------------
# Explored bitmap
proc setExplored*(g: GateCache, playerId: int, bm: explored.BitMap) =
## Startup restore: the whole grid the player had before the restart.
withLock g.lock:
g.view.explored[playerId] = bm
proc markExplored*(g: GateCache, playerId: int, sc: SceneRec,
cells: openArray[(int, int)]) =
## One refresh's new cells (4.2 step 5). Explored only grows, so setting the bits in place under
## the mutex *is* the publish: a reader sees a cell before or after, never a torn byte.
if playerId <= 0 or cells.len == 0: return
withLock g.lock:
var bm = g.view.explored.mgetOrPut(playerId, newBitMap(sc.cols, sc.rows))
for (cx, cy) in cells:
bm.setBit(cy * bm.cols + cx)
g.view.explored[playerId] = bm
proc exploredPlayers*(g: GateCache): int =
withLock g.lock:
result = g.view.explored.len
# ---------------------------------------------------------------------------------------------------
# Scene and the gate itself
proc setScene*(g: GateCache, sc: SceneRec) =
## `scene.set` republishes the (unchanging) tile geometry. Kept for the one-record rule: a gate
## request parses, checks and builds its redirect from the same published record.
withLock g.lock:
g.view.scene = tileScene(sc)
proc gateTile*(g: GateCache, tokenHash, sceneRaw, versionRaw, fileRaw: string): GateDecision =
## DESIGN 3.3/6.6 in one snapshot read: parse the canonical URL first (malformed, out of range,
## another scene, stale art version -> 404 whatever the session), then the session, then the
## player's explored bit. The GM is always allowed. No `dbLock`, no SQL, no per-tile hash beyond
## the cookie's one SHA-256 (done by the caller).
withLock g.lock:
let sc = g.view.scene
let parsed = parseTileRequest(sceneRaw, versionRaw, fileRaw, sc)
result.outcome = parsed.outcome
if parsed.outcome != toTileOk: return
let e = if tokenHash.len > 0: g.view.sessions.getOrDefault(tokenHash) else: SessionEntry()
if e.playerId <= 0: return
result.session = true
result.gm = e.isGm
result.allowed = e.isGm or
(g.view.explored.hasKey(e.playerId) and
tileCoveredByBits(sc, g.view.explored[e.playerId].bits, parsed.req.x, parsed.req.y))
if result.allowed:
result.redirect = tilePath(sc, parsed.req.x, parsed.req.y)