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
+41
View File
@@ -38,6 +38,47 @@ type
cx*, cy*: int cx*, cy*: int
bits*: seq[byte] bits*: seq[byte]
BitMap* = object
## The explored grid as one bit per cell, row-major from the world origin (`cy * cols + cx`).
## This is the tile gate's read-side snapshot (issue #65): the gate asks "is this cell explored?"
## for a handful of indices instead of walking a `HashSet` under the global lock. The on-disk
## chunk bits use the same least-significant-bit-first convention, but per 64x64 chunk; this is
## the whole map flattened, which is what the gate's index arithmetic wants.
cols*: int
rows*: int
bits*: seq[byte]
proc newBitMap*(cols, rows: int): BitMap =
result.cols = max(1, cols)
result.rows = max(1, rows)
result.bits = newSeq[byte]((result.cols * result.rows + 7) div 8)
proc setBit*(bm: var BitMap, idx: int) {.inline.} =
## Idempotent: explored only grows, so setting a set bit costs one load and one store.
if idx < 0 or idx >= bm.cols * bm.rows: return
let byteIdx = idx shr 3
bm.bits[byteIdx] = bm.bits[byteIdx] or byte(1 shl (idx and 7))
proc bitMapOf*(sc: SceneRec, explored: HashSet[int]): BitMap =
## The whole explored set as a bitmap, for startup restore and tests.
result = newBitMap(sc.cols, sc.rows)
for idx in explored:
result.setBit(idx)
proc bitSet*(bits: openArray[byte], idx: int): bool {.inline.} =
## The gate's hot read: no copy, no refcount (the caller passes a borrowed `seq` as openArray).
if idx < 0: return false
let byteIdx = idx shr 3
byteIdx < bits.len and (bits[byteIdx] and byte(1 shl (idx and 7))) != 0
proc bitCount*(bm: BitMap): int =
## How many explored cells the snapshot holds (tests / diagnostics).
for b in bm.bits:
var v = b
while v != 0:
inc result
v = v and (v - 1)
# --------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------
# Geometry of a chunk # Geometry of a chunk
+12
View File
@@ -19,6 +19,18 @@ proc crashNow*() =
when defined(leakfault): when defined(leakfault):
quit(70) quit(70)
when defined(leakfault):
var lockHoldFired = false
proc faultHoldLock*() =
## `-d:leakfault` only: hold the global lock for a moment at the start of `token.move`, so a test
## can prove a tile burst is answered while a mutation is still in flight (#65). Fires once per
## process; the caller already holds `dbLock`, which serializes the flag.
when defined(leakfault):
if not lockHoldFired and getEnv("LEAK_FAULT") == "lockhold":
lockHoldFired = true
sleep(1200)
when defined(dispfault): when defined(dispfault):
var txnFaultFired = false var txnFaultFired = false
var ackFaultFired = false var ackFaultFired = false
+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 ## 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/` ## 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). ## 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 ## 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 ## 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. ## 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 mummy, mummy/routers
import config, db, eventlog, crypto, auth, conns, instancelock, protocol, world, jsonbound 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 characters, geometry, markers, props, text, tiles, tokens, vision, views, explored, worldmap, faults, moverules
import sessions
const const
CookieName* = "fff_session" CookieName* = "fff_session"
@@ -57,6 +63,9 @@ type
db: DbConn db: DbConn
dbLock: Lock dbLock: Lock
## The one global lock (DESIGN 4.3): it serializes every mutation, the DB, and the world below. ## 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 conns: Conns
instanceLock: InstanceLock instanceLock: InstanceLock
scene: SceneRec 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 ## 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`. ## markers (5.8): the polygon is the gate, so it must run after `refresh`.
if pid == GmControlled: return if pid == GmControlled: return
app.visions.mgetOrPut(pid, PlayerVision()).refresh(app.scene, app.tokens, pid) # Borrow the entry: `let` would copy the whole PlayerVision (polygons, explored set, markers).
discard markers.syncMarkers(app.visions.mgetOrPut(pid, PlayerVision()), app.scene) 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() = 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).
@@ -752,7 +766,10 @@ proc join(request: Request) {.gcsafe.} =
player = findPlayerByKey(app.db, key) player = findPlayerByKey(app.db, key)
if player.isSome: if player.isSome:
token = randomSessionToken() 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: if player.isNone:
# No key, no body, no detail: a wrong key and an unknown key look the same (T9 discipline). # No key, no body, no detail: a wrong key and an unknown key look the same (T9 discipline).
app.lg.log(lvInfo, "join_refused") app.lg.log(lvInfo, "join_refused")
@@ -777,43 +794,32 @@ proc join(request: Request) {.gcsafe.} =
request.respond(303, headers) request.respond(303, headers)
proc tileGate(request: Request) {.gcsafe.} = proc tileGate(request: Request) {.gcsafe.} =
## GET /tiles/<scene>/v<art_version>/<x>_<y>.png (DESIGN 3.3, 6.6; slice 9 / #24). Order: parse ## GET /tiles/<scene>/v<art_version>/<x>_<y>.png (DESIGN 3.3, 6.6; slice 9 / #24, #65). Order:
## the URL (malformed, out of range, another scene, stale art version -> 404 whatever the session), ## parse the URL (malformed, out of range, another scene, stale art version -> 404 whatever the
## then the session (missing or unknown -> 403), then the explored grid (unexplored -> 403). ## session), then the session (missing or unknown -> 403), then the explored bitmap (unexplored ->
## The GM is always allowed. Nim never opens a tile file: a `200` carries `X-Accel-Redirect` to ## 403). The GM is always allowed. Nim never opens a tile file: a `200` carries
## the internal `/_tiles/` location and `Cache-Control: private` (Q4), and nginx serves the bytes. ## `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` ## No `dbLock` (issue #65): the whole decision is one read of the gate's published snapshot, which
## under that same lock, so this request parses the URL, checks the explored grid and builds the ## holds the scalar scene record, the session table and the explored bitmap. A mutation holding
## redirect from ONE record. A second read could see a swapped scene whose `walls`/`artVersion` ## the global lock for its write/COMMIT cannot delay a tile burst, and a tile never hashes a
## disagree with the parse (the old code read it three times, twice outside the lock). ## 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) let token = sessionCookie(request)
var parsed: tuple[outcome: TileOutcome, req: TileRequest] let hash = if token.len > 0: sha256Hex(token) else: ""
var player: Option[Player] let decision = app.gate.gateTile(hash, request.pathParams["scene"],
var allowed = false request.pathParams["version"], request.pathParams["file"])
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)
if parsed.outcome != toTileOk: if decision.outcome != toTileOk:
request.respond(404, body = "") request.respond(404, body = "")
return return
if player.isNone or not allowed: if not decision.session or not decision.allowed:
request.respond(403, body = "") request.respond(403, body = "")
return return
var headers: HttpHeaders var headers: HttpHeaders
headers["X-Accel-Redirect"] = redirect headers["X-Accel-Redirect"] = decision.redirect
headers["Cache-Control"] = "private" headers["Cache-Control"] = "private"
request.respond(200, headers) request.respond(200, headers)
@@ -827,9 +833,17 @@ proc wsUpgrade(request: Request) {.gcsafe.} =
request.respond(401, body = "") request.respond(401, body = "")
return 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] var player: Option[Player]
withLock app.dbLock: withLock app.dbLock:
player = sessionPlayer(app.db, sha256Hex(token)) player = playerById(app.db, cached.get.playerId)
if player.isNone: if player.isNone:
request.respond(401, body = "") request.respond(401, body = "")
return return
@@ -874,8 +888,9 @@ proc wsUpgrade(request: Request) {.gcsafe.} =
withLock app.dbLock: withLock app.dbLock:
activated = app.conns.activate(pid, role, ws, named) activated = app.conns.activate(pid, role, ws, named)
# Close the replacement race: a key.replace between the lookup and the activation must not # Close the replacement race: a key.replace between the lookup and the activation must not
# leave a live connection on a revoked session. # leave a live connection on a revoked session. Both this check and the drop run under
if sessionPlayer(app.db, sha256Hex(token)).isNone: # `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: if app.conns.connById(activated.id).isSome:
closeRegistered(app.conns.connById(activated.id).get, ReasonRevoked, CloseRevoked) closeRegistered(app.conns.connById(activated.id).get, ReasonRevoked, CloseRevoked)
return 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) notAllowed = true # the GM's own key rotates only through the CLI (DESIGN 3.2)
else: else:
key = replacePlayerKey(app.db, id) 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: if notFound:
ackErr(conn, env.reqId, CodeNotFound) ackErr(conn, env.reqId, CodeNotFound)
return return
@@ -1094,6 +1112,10 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
removed = removePlayer(app.db, id) removed = removePlayer(app.db, id)
else: else:
removed = removePlayer(app.db, id) 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: if notFound:
ackErr(conn, env.reqId, CodeNotFound) ackErr(conn, env.reqId, CodeNotFound)
return return
@@ -1387,6 +1409,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
var kind = mkError var kind = mkError
var resultPos: Vec var resultPos: Vec
withLock app.dbLock: withLock app.dbLock:
faultHoldLock() # -d:leakfault only: prove the tile gate does not queue on dbLock
let idx = tokenIndex(app.tokens, id) let idx = tokenIndex(app.tokens, id)
if idx.isNone: if idx.isNone:
# T9: a player gets one code for "unknown" and "not yours" (no existence oracle); a GM's # 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 # 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. # connection, so a reconnecting player gets the full set they had.
markers.restore(conn, state.scene, state.visions) 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) 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),
@@ -2481,6 +2511,8 @@ proc runServer(cfg: Config): int =
lg.log(lvInfo, "explored_loaded", [("players", $state.visions.len), lg.log(lvInfo, "explored_loaded", [("players", $state.visions.len),
("chunks", $explored.chunkCount(conn, state.scene.id)), ("chunks", $explored.chunkCount(conn, state.scene.id)),
("markers", $markers.markerCount(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), lg.log(lvInfo, "names_loaded", [("reveals", $state.reveals.pairs.len),
("encountered_players", $state.encountered.len)]) ("encountered_players", $state.encountered.len)])
appHandle = cast[pointer](state) appHandle = cast[pointer](state)
+161
View File
@@ -0,0 +1,161 @@
## 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)
+43 -11
View File
@@ -17,17 +17,27 @@
## ##
## Access rule [FIXED, Q4/3.3]: the GM is always allowed; a player is allowed iff at least one cell ## Access rule [FIXED, Q4/3.3]: the GM is always allowed; a player is allowed iff at least one cell
## of that player's explored grid overlaps the tile rectangle (in v1 `tile_size == cell`, so one ## of that player's explored grid overlaps the tile rectangle (in v1 `tile_size == cell`, so one
## cell). Nothing here reads the world or a lock: main.nim hands in the scene and the player's ## cell). Nothing here reads the world, the DB or the global lock: these are pure functions over a
## explored set. A player with no sight state has explored nothing, so every tile is refused. ## `TileScene` and either an explored set (unit tests) or its bitmap (the published gate view,
## issue #65). A player with no sight state has explored nothing, so every tile is refused.
## ##
## Status split [FIXED (owner-delegated), #24]: a nonexistent tile is 404; an existing tile that the ## Status split [FIXED (owner-delegated), #24]: a nonexistent tile is 404; an existing tile that the
## session may not have (no session, unknown session, or unexplored) is 403. The 403 is the same for ## session may not have (no session, unknown session, or unexplored) is 403. The 403 is the same for
## "no session" and "unexplored" so the route never says whether a tile exists for an anonymous ## "no session" and "unexplored" so the route never says whether a tile exists for an anonymous
## requester beyond the non-secret scene geometry (3.1: world size and cell size are not secret). ## requester beyond the non-secret scene geometry (3.1: world size and cell size are not secret).
import std/[math, sets, strutils] import std/[math, sets, strutils]
import vision, world import explored, vision, world
type type
TileScene* = object
## The tile gate's scalar copy of the scene (issue #65). The gate reads it from the published
## snapshot without the global lock; the value holds no `seq`/`ref`, so copying it across a
## thread boundary costs no ORC reference-count traffic. `w/h/tile_size/cell/art_version` never
## change at runtime (`scene.set` cannot patch them, 6.1), so a snapshot is stable for its life.
id*: int
w*, h*: float
tileSize*, cell*, cols*, rows*, artVersion*: int
TileOutcome* = enum TileOutcome* = enum
toTileOk toTileOk
toTileMalformed ## a component that is not canonical or a suffix that is not `.png` -> 404 toTileMalformed ## a component that is not canonical or a suffix that is not `.png` -> 404
@@ -48,6 +58,12 @@ const
## 99999 tiles is far beyond any v1 scene (128 tiles per side at 4096 px); a longer component ## 99999 tiles is far beyond any v1 scene (128 tiles per side at 4096 px); a longer component
## is malformed rather than parsed. ## is malformed rather than parsed.
converter tileScene*(sc: SceneRec): TileScene =
## The one conversion point: existing callers keep passing a `SceneRec`; the gate publishes and
## consumes a `TileScene` (no refs). `cols`/`rows` come from `vision` (ceil(w / cell)).
TileScene(id: sc.id, w: sc.w, h: sc.h, tileSize: sc.tileSize, cell: sc.cell,
cols: sc.cols, rows: sc.rows, artVersion: sc.artVersion)
proc canonicalNumber*(raw: string, maxDigits: int, dest: var int): bool = proc canonicalNumber*(raw: string, maxDigits: int, dest: var int): bool =
## The URL's number grammar (this module's header): digits only, 1..maxDigits, no leading zero. ## The URL's number grammar (this module's header): digits only, 1..maxDigits, no leading zero.
## Nothing is parsed unless every rule holds, so an overflow cannot reach `parseInt`. ## Nothing is parsed unless every rule holds, so an overflow cannot reach `parseInt`.
@@ -66,18 +82,18 @@ proc parseVersion*(raw: string, dest: var int): bool =
if raw.len < 2 or raw[0] != 'v': return false if raw.len < 2 or raw[0] != 'v': return false
canonicalNumber(raw[1 .. ^1], MaxVersionDigits, dest) canonicalNumber(raw[1 .. ^1], MaxVersionDigits, dest)
proc tileCols*(sc: SceneRec): int = proc tileCols*(sc: TileScene): int =
## Tiles across the scene (DESIGN 3.3: the tile grid's origin is the world origin). ## Tiles across the scene (DESIGN 3.3: the tile grid's origin is the world origin).
max(1, int(ceil(sc.w / float(sc.tileSize)))) max(1, int(ceil(sc.w / float(sc.tileSize))))
proc tileRows*(sc: SceneRec): int = proc tileRows*(sc: TileScene): int =
max(1, int(ceil(sc.h / float(sc.tileSize)))) max(1, int(ceil(sc.h / float(sc.tileSize))))
proc tileInRange*(sc: SceneRec, x, y: int): bool = proc tileInRange*(sc: TileScene, x, y: int): bool =
x >= 0 and y >= 0 and x < tileCols(sc) and y < tileRows(sc) x >= 0 and y >= 0 and x < tileCols(sc) and y < tileRows(sc)
proc parseTileRequest*(sceneRaw, versionRaw, fileRaw: string, proc parseTileRequest*(sceneRaw, versionRaw, fileRaw: string,
sc: SceneRec): tuple[outcome: TileOutcome, req: TileRequest] = sc: TileScene): tuple[outcome: TileOutcome, req: TileRequest] =
## Strict parse of the three route components (this module's header). `req` is only meaningful ## Strict parse of the three route components (this module's header). `req` is only meaningful
## when `outcome == toTileOk`. ## when `outcome == toTileOk`.
var sceneId, artVersion: int var sceneId, artVersion: int
@@ -106,7 +122,7 @@ proc parseTileRequest*(sceneRaw, versionRaw, fileRaw: string,
(toTileOk, TileRequest(scene: sceneId, artVersion: artVersion, x: x, y: y)) (toTileOk, TileRequest(scene: sceneId, artVersion: artVersion, x: x, y: y))
proc tileCoveredByExplored*(sc: SceneRec, explored: HashSet[int], tileX, tileY: int): bool = proc tileCoveredByExplored*(sc: TileScene, explored: HashSet[int], tileX, tileY: int): bool =
## DESIGN 3.3: a tile is allowed iff at least one explored cell overlaps it. The tile rectangle is ## DESIGN 3.3: a tile is allowed iff at least one explored cell overlaps it. The tile rectangle is
## `[tileX*tile_size, (tileX+1)*tile_size) x ...`; a cell overlaps when its rectangle shares any ## `[tileX*tile_size, (tileX+1)*tile_size) x ...`; a cell overlaps when its rectangle shares any
## point with it. General over `tile_size` and `cell` (v1 pins them equal, Q4, but a 64 px ## point with it. General over `tile_size` and `cell` (v1 pins them equal, Q4, but a 64 px
@@ -120,16 +136,32 @@ proc tileCoveredByExplored*(sc: SceneRec, explored: HashSet[int], tileX, tileY:
for cy in cy0 .. cy1: for cy in cy0 .. cy1:
for cx in cx0 .. cx1: for cx in cx0 .. cx1:
if cx < 0 or cy < 0 or cx >= sc.cols or cy >= sc.rows: continue if cx < 0 or cy < 0 or cx >= sc.cols or cy >= sc.rows: continue
if sc.cellIndex(cx, cy) in explored: return true if cy * sc.cols + cx in explored: return true
false false
proc tileAllowed*(sc: SceneRec, explored: HashSet[int], tileX, tileY: int, proc tileCoveredByBits*(sc: TileScene, bits: openArray[byte], tileX, tileY: int): bool =
## The same overlap rule over the gate's explored bitmap (issue #65): cell index `cy * cols + cx`,
## bit `idx shr 3`, mask `1 shl (idx and 7)`, exactly `BitMap`/`cellIndex`. The bitmap is borrowed
## (openArray), so a gate read never copies or ref-counts the snapshot.
let x0 = tileX * sc.tileSize
let y0 = tileY * sc.tileSize
let cx0 = x0 div sc.cell
let cy0 = y0 div sc.cell
let cx1 = (x0 + sc.tileSize - 1) div sc.cell
let cy1 = (y0 + sc.tileSize - 1) div sc.cell
for cy in cy0 .. cy1:
for cx in cx0 .. cx1:
if cx < 0 or cy < 0 or cx >= sc.cols or cy >= sc.rows: continue
if bitSet(bits, cy * sc.cols + cx): return true
false
proc tileAllowed*(sc: TileScene, explored: HashSet[int], tileX, tileY: int,
isGm: bool): bool = isGm: bool): bool =
## The whole gate rule (3.3): the GM is always allowed; a player only through its explored grid. ## The whole gate rule (3.3): the GM is always allowed; a player only through its explored grid.
if isGm: return true if isGm: return true
tileCoveredByExplored(sc, explored, tileX, tileY) tileCoveredByExplored(sc, explored, tileX, tileY)
proc tilePath*(sc: SceneRec, x, y: int): string = proc tilePath*(sc: TileScene, x, y: int): string =
## The internal nginx path of a tile (3.3, 11.1): `/_tiles/<scene>/v<art_version>/<x>_<y>.png`. ## The internal nginx path of a tile (3.3, 11.1): `/_tiles/<scene>/v<art_version>/<x>_<y>.png`.
## Built only from integers, never from request text, so no request can steer it. ## Built only from integers, never from request text, so no request can steer it.
"/_tiles/" & $sc.id & "/v" & $sc.artVersion & "/" & $x & "_" & $y & ".png" "/_tiles/" & $sc.id & "/v" & $sc.artVersion & "/" & $x & "_" & $y & ".png"
+166
View File
@@ -0,0 +1,166 @@
## 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"
+2 -2
View File
@@ -118,8 +118,8 @@ suite "tile access rule":
suite "one scene record per request (#31)": suite "one scene record per request (#31)":
test "a request built from one record stays internally consistent when the scene is swapped": test "a request built from one record stays internally consistent when the scene is swapped":
# What main.tileGate does: read the scene once under the lock, then parse, gate and build the # The gate's one-record rule (#31, #65): parse, gate and build the redirect from one scalar
# redirect from that one local. A `scene.set` landing afterwards must not change the answer. # `TileScene`; a `scene.set` landing afterwards must not change the answer.
var live = testScene() var live = testScene()
let sc = live # the one read (`withLock` in main) let sc = live # the one read (`withLock` in main)
let parsed = parseOk(sc, "1", "v1", "9_9.png") let parsed = parseOk(sc, "1", "v1", "9_9.png")
+26
View File
@@ -141,6 +141,32 @@ test('key.replace: old key and old sessions die, live connections close, the new
}) })
}) })
// #65: the negative control for the in-memory session cache. `LEAK_FAULT=sessioncache` skips the
// cache drop on key.replace, so the old cookie still upgrades (101 instead of the clean build's
// 401). It proves the replacement test above is load-bearing: without cache invalidation the auth
// group fails. The fault build contains the hook; the shipped binary cannot.
test('fault sessioncache: a revoked session kept alive fails the authentication group', async () => {
const stateDir = makeStateDir()
const gmKey = gmKeyOf(stateDir)
const s = await startServer({ stateDir, defines: ['leakfault'],
env: { LEAK_FAULT: 'sessioncache' } })
try {
const gm = await openAs(s.origin, gmKey)
const player = await createPlayer(gm.ws)
const session = await openAs(s.origin, player.key)
assert.equal((await rawUpgrade(s.origin, { cookie: session.cookie })).status, 101)
assert.equal((await gm.ws.request({ t: 'key.replace', id: player.id })).ok, true)
await session.ws.closed
const status = (await rawUpgrade(s.origin, { cookie: session.cookie })).status
assert.equal(status, 101, 'the fault keeps the revoked session in the cache')
assert.notEqual(status, 401, 'a stale cache is exactly what the auth group refuses')
gm.ws.close()
} finally {
await stopServer(s)
fs.rmSync(stateDir, { recursive: true, force: true })
}
})
test('player.remove: key, sessions and connections gone; slot freed; the GM is not removable', async () => { test('player.remove: key, sessions and connections gone; slot freed; the GM is not removable', async () => {
await withGmServer(async (s, gmKey) => { await withGmServer(async (s, gmKey) => {
const gm = await openAs(s.origin, gmKey) const gm = await openAs(s.origin, gmKey)
+43 -2
View File
@@ -2,9 +2,10 @@
## No timing code lives in server/: this harness times from outside with O(1) accumulators (sum, worst), no sample arrays. ## No timing code lives in server/: this harness times from outside with O(1) accumulators (sum, worst), no sample arrays.
## Targets (DESIGN 5.3 / 13 M2, PROPOSED): polygon + cells <= 0.451 ms avg on the prototype scene; polygon < 1 ms avg on 5k walls. ## Targets (DESIGN 5.3 / 13 M2, PROPOSED): polygon + cells <= 0.451 ms avg on the prototype scene; polygon < 1 ms avg on 5k walls.
## The egress rows record the absolute averages the in-process gate (tests/tviews.nim, TESTING 5.3) deliberately does not assert. ## The egress rows record the absolute averages the in-process gate (tests/tviews.nim, TESTING 5.3) deliberately does not assert.
import std/[json, monotimes, times, strformat, os, math, sets, tables] import std/[json, monotimes, times, strformat, os, math, options, sets, tables]
import db_connector/db_sqlite
import geometry, moverules import geometry, moverules
import characters, props, tokens, views, vision, world import auth, characters, crypto, db, explored, props, sessions, tiles, tokens, views, vision, world
import scenegen import scenegen
import ../tests/[refold, testutil] import ../tests/[refold, testutil]
@@ -105,5 +106,45 @@ discard bench("GM egress pass (fresh diff base)", 200, proc(i: int) =
discard bench("player egress pass (fresh diff base)", 200, proc(i: int) = discard bench("player egress pass (fresh diff base)", 200, proc(i: int) =
var known: Known var known: Known
sink += egressFrames(Recipient(isGm: false, playerId: 2), egressLarge.borrow, known).len) sink += egressFrames(Recipient(isGm: false, playerId: 2), egressLarge.borrow, known).len)
echo "== tile gate (#65): old SQL-under-lock path vs published snapshot =="
let gateScene = SceneRec(id: 1, name: "Scene", w: 4096, h: 4096, tileSize: 32, cell: 32,
visionRadiusDefault: 400, tokenRadiusDefault: 20, artVersion: 1,
nextWallId: 1, extra: newJObject())
# The "before" side: a real (in-memory) SQLite session table and the explored HashSet the old gate
# read under dbLock. The SELECT is the same `session JOIN player` auth.sessionPlayer runs.
let mem = openDatabase(":memory:")
mem.exec(sql"CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT, role TEXT, colour TEXT)")
mem.exec(sql"""CREATE TABLE session (id INTEGER PRIMARY KEY, player_id INTEGER,
token_hash TEXT, created_at TEXT, last_seen TEXT)""")
mem.exec(sql"INSERT INTO player (id, name, role, colour) VALUES (2, 'Alice', 'player', '#222')")
let benchToken = "bench-session-token"
mem.exec(sql"INSERT INTO session (player_id, token_hash) VALUES (2, ?)", sha256Hex(benchToken))
var exploredSet = initHashSet[int]()
var gateCells: seq[(int, int)]
for cx in 8 .. 12:
for cy in 8 .. 12:
exploredSet.incl gateScene.cellIndex(cx, cy)
gateCells.add (cx, cy)
let gc = newGateCache(gateScene)
gc.putSession(sha256Hex(benchToken), 2, false)
gc.markExplored(2, gateScene, gateCells)
discard bench("tile gate old: parse + SHA-256 + session JOIN + HashSet", 2000, proc(i: int) =
let h = sha256Hex(benchToken)
let parsed = parseTileRequest("1", "v1", "9_9.png", gateScene)
if parsed.outcome == toTileOk and sessionPlayer(mem, h).isSome:
if tileCoveredByExplored(gateScene, exploredSet, parsed.req.x, parsed.req.y): inc sink)
discard bench("tile gate new: parse + SHA-256 + cache lookup + bitmap", 2000, proc(i: int) =
let h = sha256Hex(benchToken)
if gc.gateTile(h, "1", "v1", "9_9.png").allowed: inc sink)
# Explored ops: the snapshot build at the 16384 px size (512x512 cells) and the incremental mark.
let bigScene = SceneRec(id: 1, name: "Scene", w: 16384, h: 16384, tileSize: 32, cell: 32,
visionRadiusDefault: 400, tokenRadiusDefault: 20, artVersion: 1,
nextWallId: 1, extra: newJObject())
var bigSet = initHashSet[int]()
for k in 0 ..< 262144: bigSet.incl k
discard bench("explored snapshot build (262144 cells)", 20, proc(i: int) =
sink += bitMapOf(bigScene, bigSet).bitCount)
discard bench("explored incremental mark (16 fresh cells)", 5000, proc(i: int) =
gc.markExplored(2, gateScene, @[(9, 9), (10, 9), (11, 9), (12, 9)]))
echo "(sink ", sink, ")" echo "(sink ", sink, ")"
quit(if misses == 0: 0 else: 1) quit(if misses == 0: 0 else: 1)
+12
View File
@@ -36,6 +36,13 @@ export const GROUPS = {
{ file: 'tiles.test.mjs', { file: 'tiles.test.mjs',
test: 'tile gate: leak check (d) matches the independent explored oracle', test: 'tile gate: leak check (d) matches the independent explored oracle',
minAsserts: 6, requires: ['oracle'] }, minAsserts: 6, requires: ['oracle'] },
// #65: off the global lock, and revocation/restart at the gate seam.
{ file: 'tiles.test.mjs',
test: 'tile gate: a burst is answered while a mutation holds the global lock (#65)',
minAsserts: 4, requires: ['elapsed < 700'] },
{ file: 'tiles.test.mjs',
test: 'tile gate: revocation is immediate and sessions survive a restart (#65)',
minAsserts: 6, requires: ['rawUpgrade'] },
{ file: 'oneway.test.mjs', { file: 'oneway.test.mjs',
test: 'one-way sight: the blind side sees nothing across, the seeing side does (#58)', test: 'one-way sight: the blind side sees nothing across, the seeing side does (#58)',
minAsserts: 12, requires: ['withOneWayStack'] }, minAsserts: 12, requires: ['withOneWayStack'] },
@@ -63,6 +70,11 @@ export const GROUPS = {
{ file: 'auth.test.mjs', { file: 'auth.test.mjs',
test: 'key.replace: old key and old sessions die, live connections close, the new key works', test: 'key.replace: old key and old sessions die, live connections close, the new key works',
minAsserts: 6, requires: ['assert.notEqual'] }, minAsserts: 6, requires: ['assert.notEqual'] },
// #65: the session cache's negative control. A fault that keeps the revoked entry alive must
// make the revocation assertion above fail (here: 101 where the clean build answers 401).
{ file: 'auth.test.mjs',
test: 'fault sessioncache: a revoked session kept alive fails the authentication group',
minAsserts: 3, requires: ['rawUpgrade'] },
], ],
}, },
'characters and names': { 'characters and names': {
+3
View File
@@ -32,6 +32,7 @@
# slice 9 (#24): the canonical tile URL and the "any explored cell allows" gate # slice 9 (#24): the canonical tile URL and the "any explored cell allows" gate
# c1: a tile is allowed without any explored cell | c2: every overlapping cell is required # c1: a tile is allowed without any explored cell | c2: every overlapping cell is required
# c3: an out-of-grid coordinate is accepted | c4: a leading-zero coordinate is canonical # c3: an out-of-grid coordinate is accepted | c4: a leading-zero coordinate is canonical
# #65: c5 a revocation keeps the cached session
# d3: scene.set accepts a patch with no field (slice 10, #25) # d3: scene.set accepts a patch with no field (slice 10, #25)
# Parallel: MUTATION_JOBS (default nproc/4) jobs, each in its own temp copy + nimcache; output collected, printed in fixed order. # Parallel: MUTATION_JOBS (default nproc/4) jobs, each in its own temp copy + nimcache; output collected, printed in fixed order.
# Tests run with FFF_MUTATION=1 (iteration counts ~/10, see tests/testutil.nim scaled()); only test files holding an expected # Tests run with FFF_MUTATION=1 (iteration counts ~/10, see tests/testutil.nim scaled()); only test files holding an expected
@@ -208,6 +209,8 @@ run c1 "the tile gate ignores the explored set" server/tiles.nim 's/ if sc\
run c2 "the tile gate needs every overlapping cell" server/tiles.nim 's/ if sc\.cellIndex(cx, cy) in explored: return true/ if sc.cellIndex(cx, cy) notin explored: return false/' "$TILE_GATE" run c2 "the tile gate needs every overlapping cell" server/tiles.nim 's/ if sc\.cellIndex(cx, cy) in explored: return true/ if sc.cellIndex(cx, cy) notin explored: return false/' "$TILE_GATE"
run c3 "an out-of-grid tile coordinate is accepted" server/tiles.nim 's/^ x >= 0 and y >= 0 and x < tileCols(sc) and y < tileRows(sc)$/ x >= 0 and y >= 0/' "$TILE_RANGE" run c3 "an out-of-grid tile coordinate is accepted" server/tiles.nim 's/^ x >= 0 and y >= 0 and x < tileCols(sc) and y < tileRows(sc)$/ x >= 0 and y >= 0/' "$TILE_RANGE"
run c4 "a leading-zero tile coordinate is canonical" server/tiles.nim "s/ if raw\[0\] == '0' and raw.len > 1: return false/ discard/" "$TILE_ZERO" run c4 "a leading-zero tile coordinate is canonical" server/tiles.nim "s/ if raw\[0\] == '0' and raw.len > 1: return false/ discard/" "$TILE_ZERO"
# #65: the in-memory session cache must drop a player's entry on revocation (server/sessions.nim)
run c5 "a revocation keeps the cached session" server/sessions.nim 's/^ g\.view\.sessions\.del h$/ discard/' "revocation drops"
# slice 10 (#25): scene.set needs at least one patch field (server/world.nim parseScenePatch) # slice 10 (#25): scene.set needs at least one patch field (server/world.nim parseScenePatch)
run d3 "scene.set accepts a patch with no field" server/world.nim 's/^ if not any: return none(ScenePatch)$/ discard/' "a patch with none is invalid" run d3 "scene.set accepts a patch with no field" server/world.nim 's/^ if not any: return none(ScenePatch)$/ discard/' "a patch with none is invalid"
# #32: the rollback on a Defect, in both transaction helpers, and the one-ack decision # #32: the rollback on a Defect, in both transaction helpers, and the one-ack decision
+89 -7
View File
@@ -15,8 +15,8 @@ import assert from 'node:assert/strict'
import fs from 'node:fs' import fs from 'node:fs'
import path from 'node:path' import path from 'node:path'
import { spawnSync } from 'node:child_process' import { spawnSync } from 'node:child_process'
import { createPlayer, freePort, httpsBaseUrl, namePlayer, projectRoot } from './lib.mjs' import { createPlayer, freePort, httpsBaseUrl, namePlayer, projectRoot, rawUpgrade, sleep } from './lib.mjs'
import { gmKeyOf, makeStateDir, openAs, startServer, stopServer } from './withserver.mjs' import { gmKeyOf, makeStateDir, openAs, signIn, startServer, stopServer } from './withserver.mjs'
import { startTestNginx, stopTestNginx } from './nginx.mjs' import { startTestNginx, stopTestNginx } from './nginx.mjs'
import { isPng, pngBytes, tileDir, writeTileGrid, writeTiles } from './tilefixture.mjs' import { isPng, pngBytes, tileDir, writeTileGrid, writeTiles } from './tilefixture.mjs'
@@ -405,8 +405,9 @@ test('tile gate: refusals, direct /_tiles, malformed and out-of-range paths', as
// #31: `app.scene` is swapped (not mutated) by `scene.set` under the global lock. A handler that // #31: `app.scene` is swapped (not mutated) by `scene.set` under the global lock. A handler that
// reads it twice can see two different records in one request; a read outside the lock races the // reads it twice can see two different records in one request; a read outside the lock races the
// assignment itself. This pins the shape of the two HTTP handlers that touch it (the WS handlers all // assignment itself. #65 moved the tile gate onto its published snapshot (session cache + explored
// run under the lock), because a data race is otherwise only visible to a sanitiser. // bitmap + scalar scene), so the gate must not touch `app.scene` or `dbLock` at all: one
// `gateTile` call is the whole request. The remaining scene reader keeps the #31 shape.
test('every handler reads app.scene at most once, under the lock (#31)', async () => { test('every handler reads app.scene at most once, under the lock (#31)', async () => {
const source = fs.readFileSync(path.join(projectRoot, 'server', 'main.nim'), 'utf8') const source = fs.readFileSync(path.join(projectRoot, 'server', 'main.nim'), 'utf8')
// The body of a proc: from its `proc name` line to the next top-level `proc`. // The body of a proc: from its `proc name` line to the next top-level `proc`.
@@ -417,9 +418,9 @@ test('every handler reads app.scene at most once, under the lock (#31)', async (
const next = rest.indexOf('\nproc ') const next = rest.indexOf('\nproc ')
return rest.slice(0, next < 0 ? undefined : next) return rest.slice(0, next < 0 ? undefined : next)
} }
for (const handler of ['tileGate', 'checkScene']) { const codeOf = name => bodyOf(name).split('\n').filter(l => !l.trim().startsWith('#')).join('\n')
// Code only: the comments explain the rule and would count as reads. for (const handler of ['checkScene']) {
const body = bodyOf(handler).split('\n').filter(l => !l.trim().startsWith('#')).join('\n') const body = codeOf(handler)
const reads = body.split('app.scene').length - 1 const reads = body.split('app.scene').length - 1
assert.equal(reads, 1, `${handler} must read app.scene once (found ${reads})`) assert.equal(reads, 1, `${handler} must read app.scene once (found ${reads})`)
const readAt = body.indexOf('app.scene') const readAt = body.indexOf('app.scene')
@@ -427,6 +428,13 @@ test('every handler reads app.scene at most once, under the lock (#31)', async (
assert.ok(lockAt >= 0 && lockAt < readAt, assert.ok(lockAt >= 0 && lockAt < readAt,
`${handler} must take the lock before it reads app.scene`) `${handler} must take the lock before it reads app.scene`)
} }
// #65: no global lock and no second scene read in the tile path.
const gate = codeOf('tileGate')
assert.equal(gate.split('app.scene').length - 1, 0, 'tileGate must not read app.scene')
assert.equal(gate.split('withLock app.dbLock').length - 1, 0,
'tileGate must not take the global lock')
assert.equal(gate.split('app.gate.gateTile').length - 1, 1,
'tileGate is one published-snapshot decision')
}) })
test('concurrent scene edits and tile requests answer whole tiles, never a mixture (#31)', async () => { test('concurrent scene edits and tile requests answer whole tiles, never a mixture (#31)', async () => {
@@ -477,6 +485,80 @@ test('concurrent scene edits and tile requests answer whole tiles, never a mixtu
}) })
}) })
// #65: a tile burst must not queue behind a mutation that holds the global lock. The `lockhold`
// fault (-d:leakfault build only) sleeps inside `token.move` while `dbLock` is held. The gate reads
// the published session/explored snapshot under its own mutex, so the burst answers immediately;
// with the old SQL-under-dbLock gate the whole burst would wait out the sleep.
test('tile gate: a burst is answered while a mutation holds the global lock (#65)', async () => {
const stateDir = makeStateDir()
const gmKey = gmKeyOf(stateDir)
const s = await startServer({ stateDir, defines: ['leakfault'], env: { LEAK_FAULT: 'lockhold' } })
try {
const ctx = await sceneWithVision(s, gmKey, { origin: s.origin })
const scene = ctx.gm.ws.messages.find(m => m.t === 'hello' && m.scene).scene
const url = tileUrl(scene.id, ctx.artVersion, 9, 9)
assert.equal((await getTile(s.origin, url, ctx.seenCtx.cookie)).status, 200)
// The GM move holds dbLock for ~1.2 s before it does any work.
const edit = ctx.gm.ws.request({ t: 'token.move', id: ctx.token.id, pos: [310, 300] })
await sleep(250)
const t0 = Date.now()
const burst = await Promise.all(Array.from({ length: 32 }, async () =>
(await getTile(s.origin, url, ctx.seenCtx.cookie)).status))
const elapsed = Date.now() - t0
assert.ok(burst.every(status => status === 200), `unexpected statuses: ${burst}`)
assert.ok(elapsed < 700, `a tile burst waited ${elapsed} ms behind a mutation holding dbLock`)
assert.equal((await edit).ok, true, 'the mutation itself still completes')
// The same tile after the mutation: the gate is consistent with the publish.
assert.equal((await getTile(s.origin, url, ctx.seenCtx.cookie)).status, 200)
ctx.gm.ws.close(); ctx.seenCtx.ws.close()
} finally {
await stopServer(s)
fs.rmSync(stateDir, { recursive: true, force: true })
}
})
// #65: revocation is immediate at the gate, and a restart rebuilds the session cache from the DB.
// key.replace drops the player's entries before the ack; the old cookie is 403 on the next tile and
// 401 on the next upgrade, while the new key's session is allowed. A restart keeps the live session
// alive and the revoked one dead.
test('tile gate: revocation is immediate and sessions survive a restart (#65)', async () => {
const stateDir = makeStateDir()
const gmKey = gmKeyOf(stateDir)
let s = await startServer({ stateDir })
try {
const ctx = await sceneWithVision(s, gmKey, { origin: s.origin })
const scene = ctx.gm.ws.messages.find(m => m.t === 'hello' && m.scene).scene
const url = tileUrl(scene.id, ctx.artVersion, 9, 9)
const oldCookie = ctx.seenCtx.cookie
assert.equal((await getTile(s.origin, url, oldCookie)).status, 200)
const ack = await ctx.gm.ws.request({ t: 'key.replace', id: ctx.player.id })
assert.equal(ack.ok, true, JSON.stringify(ack))
assert.equal((await getTile(s.origin, url, oldCookie)).status, 403,
'the replaced key’s session is refused on the very next tile')
assert.equal((await rawUpgrade(s.origin, { cookie: oldCookie })).status, 401,
'and on the next upgrade')
const fresh = await signIn(s.origin, ack.key)
assert.equal((await getTile(s.origin, url, fresh.cookie)).status, 200,
'the new key’s session is allowed with the same explored bitmap')
// restart: the cache is loaded from the `session` rows, so the live session is still allowed
// and the revoked one is still refused.
ctx.gm.ws.close()
await stopServer(s)
s = await startServer({ stateDir })
assert.equal((await getTile(s.origin, url, fresh.cookie)).status, 200,
'a restart restores live sessions')
assert.equal((await getTile(s.origin, url, oldCookie)).status, 403,
'a restart does not resurrect a revoked session')
} finally {
await stopServer(s)
fs.rmSync(stateDir, { recursive: true, force: true })
}
})
test('fixture tiles are generated by the helper and none is committed', async () => { test('fixture tiles are generated by the helper and none is committed', async () => {
// The repo owns no PNG: tiles are generated per test into a state dir (DESIGN 13 M3). // The repo owns no PNG: tiles are generated per test into a state dir (DESIGN 13 M3).
const tracked = spawnSync('git', ['ls-files', '*.png'], { cwd: projectRoot, encoding: 'utf8' }) const tracked = spawnSync('git', ['ls-files', '*.png'], { cwd: projectRoot, encoding: 'utf8' })