Files
FFF_vtt_frozen/tests/tsessions.nim
T
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

167 lines
7.1 KiB
Nim

## The tile gate's read-side view (#65, DESIGN 3.3, 4.3, 6.6): in-memory sessions and the explored
## bitmap snapshot. Pins the lifecycle the gate depends on - a live session is found by its token
## hash; key replacement drops every entry of that player; player removal drops the entries and the
## explored bits; a restart restores the table from `session` rows - and the gate rule itself over
## the bitmap (GM always, player only through an explored bit, malformed URL before any session).
## The black-box proof through the real binary and nginx is tools/tiles.test.mjs and
## tools/auth.test.mjs.
import std/[options, os, sets, unittest]
import db_connector/db_sqlite
import db, auth, crypto, explored, sessions, tiles, vision, world
proc testScene(w = 4096.0, h = 4096.0, cell = 32): SceneRec =
## The v1 scene shape (migration step 3): 128x128 cells, 128x128 tiles.
SceneRec(id: 1, name: "Scene", w: w, h: h, tileSize: int(cell), cell: int(cell), gridSize: 0,
visionRadiusDefault: 400, tokenRadiusDefault: 20, artVersion: 1, nextWallId: 1)
proc idxSet(sc: SceneRec, cells: openArray[(int, int)]): HashSet[int] =
for (cx, cy) in cells: result.incl sc.cellIndex(cx, cy)
var tmpCount = 0
proc tmpDir(): string =
inc tmpCount
result = getTempDir() / "fffsessions-" & $getCurrentProcessId() & "-" & $tmpCount
removeDir(result)
createDir(result)
proc fresh(): tuple[db: DbConn, dir: string] =
let d = tmpDir()
let db = openDatabase(d / "state.db")
doAssert migrate(db) == LatestVersion
(db, d)
suite "gate cache: sessions":
test "a revocation drops every cached session of that player and no other":
let g = newGateCache(testScene())
g.putSession("hash-a", 2, false)
g.putSession("hash-b", 2, false)
g.putSession("hash-c", 3, false)
check g.sessionCount == 3
check g.sessionOf("hash-a").get.playerId == 2
g.dropSessions(2)
check g.sessionOf("hash-a").isNone
check g.sessionOf("hash-b").isNone
check g.sessionOf("hash-c").get.playerId == 3
check g.sessionCount == 1
# an empty cookie or an unknown hash is no session, never a lookup of player 0
check g.sessionOf("").isNone
check g.sessionOf("not-a-session").isNone
test "player removal drops the sessions and the explored bitmap":
let sc = testScene()
let g = newGateCache(sc)
g.putSession("hash-a", 2, false)
g.setExplored(2, bitMapOf(sc, idxSet(sc, [(9, 9), (10, 9)])))
check g.exploredPlayers == 1
g.dropPlayer(2)
check g.sessionOf("hash-a").isNone
check g.exploredPlayers == 0
# the GM's own entry is not touched by another player's removal
g.putSession("gm", 1, true)
g.dropPlayer(2)
check g.sessionOf("gm").get.isGm
test "sessions survive a restart through the database, replaced ones do not":
let (db, dir) = fresh()
defer:
close(db)
removeDir(dir)
let first = ensureGm(db)
let gmId = gmPlayer(db).get.id
let player = createPlayerWithKey(db)
let gmToken = randomSessionToken()
let playerToken = randomSessionToken()
createSession(db, gmId, sha256Hex(gmToken))
createSession(db, player.id, sha256Hex(playerToken))
# "restart": a fresh cache loaded from the same rows
let g = newGateCache(testScene())
loadSessions(g, db)
check g.sessionCount == 2
check g.sessionOf(sha256Hex(gmToken)).get.playerId == gmId
check g.sessionOf(sha256Hex(gmToken)).get.isGm
check g.sessionOf(sha256Hex(playerToken)).get.playerId == player.id
check not g.sessionOf(sha256Hex(playerToken)).get.isGm
# key.replace (the CLI path is DB + cache, here the two halves) and reload: the row is gone
check replacePlayerKey(db, player.id).isSome
g.dropSessions(player.id)
check g.sessionOf(sha256Hex(playerToken)).isNone
let again = newGateCache(testScene())
loadSessions(again, db)
check again.sessionOf(sha256Hex(playerToken)).isNone
check again.sessionOf(sha256Hex(gmToken)).get.playerId == gmId
check first.key.len == 24
suite "gate cache: explored bitmap":
test "the bitmap holds the same cells as the set, with the cell-index layout":
let sc = testScene()
let cells = idxSet(sc, [(0, 0), (1, 0), (63, 0), (0, 1), (127, 127)])
let bm = bitMapOf(sc, cells)
check bm.cols == 128 and bm.rows == 128
check bm.bits.len == (128 * 128 + 7) div 8
check bm.bitCount == cells.len
for idx in cells:
check bm.bits.bitSet(idx)
check not bm.bits.bitSet(sc.cellIndex(64, 64))
# out-of-range indices are ignored, not a crash (a hand-edited DB cannot reach this, but the
# gate must not walk off the array if a future caller passes one)
var b = bm
b.setBit(-1)
b.setBit(b.cols * b.rows)
check b.bitCount == cells.len
test "a refresh marks only its fresh cells, and the snapshot only grows":
let sc = testScene()
let g = newGateCache(sc)
g.markExplored(2, sc, @[(9, 9)])
g.markExplored(2, sc, @[(9, 9), (10, 9)]) # idempotent: the first cell is already set
let d = g.gateTile("s", "1", "v1", "9_9.png")
check not d.session and not d.allowed # still no session, but the bits exist
g.putSession("s", 2, false)
check g.gateTile("s", "1", "v1", "9_9.png").allowed
check g.gateTile("s", "1", "v1", "10_9.png").allowed
check not g.gateTile("s", "1", "v1", "11_9.png").allowed
suite "gate cache: the tile rule":
test "the GM is always allowed; a player only through an explored bit":
let sc = testScene()
let g = newGateCache(sc)
g.putSession("gm", 1, true)
g.putSession("player", 2, false)
g.markExplored(2, sc, @[(9, 9)])
let gm = g.gateTile("gm", "1", "v1", "110_110.png")
check gm.outcome == toTileOk
check gm.session and gm.gm and gm.allowed
check gm.redirect == "/_tiles/1/v1/110_110.png"
let seen = g.gateTile("player", "1", "v1", "9_9.png")
check seen.session and not seen.gm and seen.allowed
check seen.redirect == "/_tiles/1/v1/9_9.png"
let unseen = g.gateTile("player", "1", "v1", "110_110.png")
check unseen.outcome == toTileOk and unseen.session and not unseen.allowed
check unseen.redirect.len == 0
test "the URL is decided before any session is looked at":
let g = newGateCache(testScene())
# a malformed, out-of-range, wrong-scene and stale-version URL are all 404 classes even for a
# live GM session, exactly tileGate's order (3.3)
g.putSession("gm", 1, true)
for (scene, version, file, outcome) in [
("1", "v1", "00_0.png", toTileMalformed),
("1", "v1", "128_0.png", toTileOutOfRange),
("2", "v1", "0_0.png", toTileWrongScene),
("1", "v2", "0_0.png", toTileWrongVersion)]:
let d = g.gateTile("gm", scene, version, file)
check d.outcome == outcome
check not d.session and not d.allowed and d.redirect.len == 0
test "a scene republish changes the parse result, never a mixture":
let g = newGateCache(testScene())
g.putSession("gm", 1, true)
var live = testScene()
check g.gateTile("gm", "1", "v1", "9_9.png").outcome == toTileOk
live.artVersion = 2
g.setScene(live)
check g.gateTile("gm", "1", "v1", "9_9.png").outcome == toTileWrongVersion
check g.gateTile("gm", "1", "v2", "9_9.png").redirect == "/_tiles/1/v2/9_9.png"