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:
+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