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:
@@ -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 () => {
|
||||
await withGmServer(async (s, gmKey) => {
|
||||
const gm = await openAs(s.origin, gmKey)
|
||||
|
||||
+43
-2
@@ -2,9 +2,10 @@
|
||||
## 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.
|
||||
## 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 characters, props, tokens, views, vision, world
|
||||
import auth, characters, crypto, db, explored, props, sessions, tiles, tokens, views, vision, world
|
||||
import scenegen
|
||||
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) =
|
||||
var known: Known
|
||||
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, ")"
|
||||
quit(if misses == 0: 0 else: 1)
|
||||
|
||||
@@ -36,6 +36,13 @@ export const GROUPS = {
|
||||
{ file: 'tiles.test.mjs',
|
||||
test: 'tile gate: leak check (d) matches the independent explored 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',
|
||||
test: 'one-way sight: the blind side sees nothing across, the seeing side does (#58)',
|
||||
minAsserts: 12, requires: ['withOneWayStack'] },
|
||||
@@ -63,6 +70,11 @@ export const GROUPS = {
|
||||
{ file: 'auth.test.mjs',
|
||||
test: 'key.replace: old key and old sessions die, live connections close, the new key works',
|
||||
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': {
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
# 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
|
||||
# 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)
|
||||
# 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
|
||||
@@ -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 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"
|
||||
# #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)
|
||||
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
|
||||
|
||||
+89
-7
@@ -15,8 +15,8 @@ import assert from 'node:assert/strict'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { createPlayer, freePort, httpsBaseUrl, namePlayer, projectRoot } from './lib.mjs'
|
||||
import { gmKeyOf, makeStateDir, openAs, startServer, stopServer } from './withserver.mjs'
|
||||
import { createPlayer, freePort, httpsBaseUrl, namePlayer, projectRoot, rawUpgrade, sleep } from './lib.mjs'
|
||||
import { gmKeyOf, makeStateDir, openAs, signIn, startServer, stopServer } from './withserver.mjs'
|
||||
import { startTestNginx, stopTestNginx } from './nginx.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
|
||||
// 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
|
||||
// run under the lock), because a data race is otherwise only visible to a sanitiser.
|
||||
// assignment itself. #65 moved the tile gate onto its published snapshot (session cache + explored
|
||||
// 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 () => {
|
||||
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`.
|
||||
@@ -417,9 +418,9 @@ test('every handler reads app.scene at most once, under the lock (#31)', async (
|
||||
const next = rest.indexOf('\nproc ')
|
||||
return rest.slice(0, next < 0 ? undefined : next)
|
||||
}
|
||||
for (const handler of ['tileGate', 'checkScene']) {
|
||||
// Code only: the comments explain the rule and would count as reads.
|
||||
const body = bodyOf(handler).split('\n').filter(l => !l.trim().startsWith('#')).join('\n')
|
||||
const codeOf = name => bodyOf(name).split('\n').filter(l => !l.trim().startsWith('#')).join('\n')
|
||||
for (const handler of ['checkScene']) {
|
||||
const body = codeOf(handler)
|
||||
const reads = body.split('app.scene').length - 1
|
||||
assert.equal(reads, 1, `${handler} must read app.scene once (found ${reads})`)
|
||||
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,
|
||||
`${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 () => {
|
||||
@@ -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 () => {
|
||||
// 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' })
|
||||
|
||||
Reference in New Issue
Block a user