diff --git a/server/main.nim b/server/main.nim index 382db60..d830009 100644 --- a/server/main.nim +++ b/server/main.nim @@ -428,10 +428,14 @@ type proc checkScene(env: Envelope): SceneCheck = ## `scene` is the id of the single v1 scene (DESIGN 6.1, 6.5 step 8: a GM's missing target is - ## `not-found`; a wrongly typed field is `invalid`). + ## `not-found`; a wrongly typed field is `invalid`). The id is read under the global lock: the + ## scene record is swapped there, never mutated in place (#31), and this handler thread must not + ## read the field while `scene.set` assigns it. let node = env.node{"scene"} if node.isNil or node.kind != JInt: return scInvalid - if node.getInt != app.scene.id: return scNotFound + var sceneId = 0 + withLock app.dbLock: sceneId = app.scene.id + if node.getInt != sceneId: return scNotFound scOk proc intField(env: Envelope, key: string, dest: var int): bool = @@ -597,33 +601,38 @@ proc tileGate(request: Request) {.gcsafe.} = ## then the session (missing or unknown -> 403), then the explored grid (unexplored -> 403). ## The GM is always allowed. Nim never opens a tile file: a `200` carries `X-Accel-Redirect` to ## the internal `/_tiles/` location and `Cache-Control: private` (Q4), and nginx serves the bytes. - let parsed = parseTileRequest(request.pathParams["scene"], request.pathParams["version"], - request.pathParams["file"], app.scene) + ## + ## The scene is read exactly once, under the global lock (#31): `scene.set` reassigns `app.scene` + ## under that same lock, so this request parses the URL, checks the explored grid and builds the + ## redirect from ONE record. A second read could see a swapped scene whose `walls`/`artVersion` + ## disagree with the parse (the old code read it three times, twice outside the lock). + let token = sessionCookie(request) + var parsed: tuple[outcome: TileOutcome, req: TileRequest] + var player: Option[Player] + var allowed = false + 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: request.respond(404, body = "") return - - let token = sessionCookie(request) - var player: Option[Player] - if token.len > 0: - withLock app.dbLock: - player = sessionPlayer(app.db, sha256Hex(token)) - if player.isNone: - request.respond(403, body = "") - return - - var allowed = player.get.role == prGm - if not allowed: - withLock app.dbLock: - if app.visions.hasKey(player.get.id): - allowed = tileCoveredByExplored(app.scene, app.visions[player.get.id].explored, - parsed.req.x, parsed.req.y) - if not allowed: + if player.isNone or not allowed: request.respond(403, body = "") return var headers: HttpHeaders - headers["X-Accel-Redirect"] = tilePath(app.scene, parsed.req.x, parsed.req.y) + headers["X-Accel-Redirect"] = redirect headers["Cache-Control"] = "private" request.respond(200, headers) @@ -1766,7 +1775,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = if patch.isNone: ackErr(conn, env.reqId, CodeInvalid) return - var candidate = app.scene.patched(patch.get) + var candidate: SceneRec var changed: seq[string] if patch.get.name.isSome: changed.add "name" if patch.get.gridSize.isSome: changed.add "grid_size" @@ -1775,6 +1784,9 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = if patch.get.extra.isSome: changed.add "extra" var tokenChanges: seq[(int, TokenRec)] withLock app.dbLock: + # The base record is read under the lock (#31): `scene.set` must not patch a record that a + # concurrent `scene.set` is replacing, and every comparison below is against this same base. + candidate = app.scene.patched(patch.get) # 5.6 `token_radius_default`: every token that uses the default changes effective size; a grow # pushes (or squeezes), a shrink clears the `walls` entries only when the overlap ends. The # rules run on a snapshot with the OLD radii (the candidate default is not in `app.scene` yet), @@ -1837,7 +1849,9 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = return let candidate = WallRec(a: a.get, b: b.get, kind: kind.get, open: open.get, flags: flags.get) var added: Option[WallRec] + var sceneId = 0 withLock app.dbLock: + sceneId = app.scene.id # the request's one read (#31) # 5.5 SET: the new wall sticks every token its circle overlaps. The rules run on a snapshot # taken before the write (the id is assigned by the write), and their outcome is applied only # after it committed, so a failed write leaves every token untouched. @@ -1852,9 +1866,9 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = if added.isNone: ackErr(conn, env.reqId, CodeInvalid) # degenerate or out-of-bounds geometry return - app.lg.log(lvInfo, "wall_add", [("scene", $app.scene.id), ("wall", $added.get.id), + app.lg.log(lvInfo, "wall_add", [("scene", $sceneId), ("wall", $added.get.id), ("kind", $added.get.kind)]) - settleWorld(conn, env.reqId, wallFrame(app.scene.id, wallObjectOf(added.get)), + settleWorld(conn, env.reqId, wallFrame(sceneId, wallObjectOf(added.get)), %*{"id": added.get.id}) return @@ -1904,7 +1918,9 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = return var outcome = waNotFound var updated: Option[WallRec] + var sceneId = 0 withLock app.dbLock: + sceneId = app.scene.id # the request's one read (#31) let current = wallById(app.scene, id) if current.isSome: # `wall.update` = remove then add for the status rules (5.5): the rules run on the snapshot @@ -1924,9 +1940,9 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = if outcome != waOk or updated.isNone: ackErr(conn, env.reqId, CodeInvalid) return - app.lg.log(lvInfo, "wall_update", [("scene", $app.scene.id), ("wall", $id), + app.lg.log(lvInfo, "wall_update", [("scene", $sceneId), ("wall", $id), ("kind", $updated.get.kind)]) - settleWorld(conn, env.reqId, wallFrame(app.scene.id, wallObjectOf(updated.get))) + settleWorld(conn, env.reqId, wallFrame(sceneId, wallObjectOf(updated.get))) return of "wall.remove": @@ -1936,7 +1952,9 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = ackErr(conn, env.reqId, CodeInvalid) return var outcome = waNotFound + var sceneId = 0 withLock app.dbLock: + sceneId = app.scene.id # the request's one read (#31) let idx = wallIndex(app.scene, id) if idx.isSome: # 5.5 KEEP/CLEAR: a removal frees only the tokens that no longer overlap any blocking wall. @@ -1950,8 +1968,8 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = if outcome == waNotFound: ackErr(conn, env.reqId, CodeNotFound) return - app.lg.log(lvInfo, "wall_remove", [("scene", $app.scene.id), ("wall", $id)]) - settleWorld(conn, env.reqId, wallGoneFrame(app.scene.id, id)) + app.lg.log(lvInfo, "wall_remove", [("scene", $sceneId), ("wall", $id)]) + settleWorld(conn, env.reqId, wallGoneFrame(sceneId, id)) return of "door.set": @@ -1967,7 +1985,9 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = let open = openNode.getBool var outcome = waNotFound var updated: Option[WallRec] + var sceneId = 0 withLock app.dbLock: + sceneId = app.scene.id # the request's one read (#31) # 5.5: closing pushes overlapped tokens aside and squeezes the ones with no valid side; # opening re-evaluates the walls-sourced entries (KEEP while another wall still overlaps). # The rules run on a snapshot taken before the write; their positions and statuses are applied @@ -1987,9 +2007,9 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = if outcome != waOk or updated.isNone: ackErr(conn, env.reqId, CodeInvalid) # waNotDoor: a plain wall has no open state return - app.lg.log(lvInfo, "door_set", [("scene", $app.scene.id), ("wall", $id), + app.lg.log(lvInfo, "door_set", [("scene", $sceneId), ("wall", $id), ("open", $open)]) - settleWorld(conn, env.reqId, wallFrame(app.scene.id, wallObjectOf(updated.get))) + settleWorld(conn, env.reqId, wallFrame(sceneId, wallObjectOf(updated.get))) return else: diff --git a/tests/ttiles.nim b/tests/ttiles.nim index 181662a..70c3ba5 100644 --- a/tests/ttiles.nim +++ b/tests/ttiles.nim @@ -115,3 +115,22 @@ suite "tile access rule": check tileAllowed(sc, cells(sc, [(128, 0)]), 128, 0, false) # a cell beyond the scene is never consulted even if a stray index says so check not tileAllowed(sc, cells(sc, [(129, 0)]), 128, 0, false) + +suite "one scene record per request (#31)": + 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 + # redirect from that one local. A `scene.set` landing afterwards must not change the answer. + var live = testScene() + let sc = live # the one read (`withLock` in main) + let parsed = parseOk(sc, "1", "v1", "9_9.png") + var explored = initHashSet[int]() + explored.incl sc.cellIndex(9, 9) + let allowed = tileCoveredByExplored(sc, explored, parsed.x, parsed.y) + # the writer swaps the scene between the read and the last use of the local + live.artVersion = 2 + live.w = 8192.0 + check allowed + check tilePath(sc, parsed.x, parsed.y) == "/_tiles/1/v1/9_9.png" + # the same URL is stale for the new record, never a mixture of the two + check parseTileRequest("1", "v1", "9_9.png", live).outcome == toTileWrongVersion + check tilePath(live, parsed.x, parsed.y) == "/_tiles/1/v2/9_9.png" diff --git a/tools/tiles.test.mjs b/tools/tiles.test.mjs index 064fd84..1496f93 100644 --- a/tools/tiles.test.mjs +++ b/tools/tiles.test.mjs @@ -358,6 +358,80 @@ 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. +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`. + const bodyOf = name => { + const start = source.indexOf(`proc ${name}(`) + assert.ok(start > 0, `proc ${name} not found`) + const rest = source.slice(start + 1) + 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 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') + const lockAt = body.indexOf('withLock app.dbLock') + assert.ok(lockAt >= 0 && lockAt < readAt, + `${handler} must take the lock before it reads app.scene`) + } +}) + +test('concurrent scene edits and tile requests answer whole tiles, never a mixture (#31)', async () => { + await withTileStack(async ({ s, gmKey, ngx, stateDir }) => { + const ctx = await sceneWithVision(s, gmKey, ngx) + const scene = ctx.gm.ws.messages.find(m => m.t === 'hello' && m.scene).scene + const url = tileUrl(scene.id, ctx.artVersion, 9, 9) + const want = writeTiles(stateDir, { scene: scene.id, artVersion: ctx.artVersion, + tiles: [[9, 9]] }) + const expected = fs.readFileSync(want[0]) + // The explored tile Alice may fetch; the gate may refuse it while a wall edit hides the cell, + // so both 200 and 403 are whole answers, and a 200 must be exactly the fixture bytes. + let allowed = 0 + let refused = 0 + const fetchTile = async () => { + const r = await getTile(ngx.origin, url, ctx.seenCtx.cookie) + assert.ok([200, 403].includes(r.status), `unexpected status ${r.status}`) + if (r.status === 200) { + allowed++ + assert.ok(Buffer.from(await r.arrayBuffer()).equals(expected), + 'a 200 must be one whole tile, not a mix of two scene records') + } else { + refused++ + } + } + // Editors: `scene.set` (a full resync) and wall edits that change the explored grid, while the + // fetches run. Every edit is acked before the next one: they are serialised by the global lock. + const edits = (async () => { + for (let i = 0; i < 20; i++) { + assert.equal((await ctx.gm.ws.request({ t: 'scene.set', scene: scene.id, + name: `Cave ${i}` })).ok, true) + const w = await ctx.gm.ws.request({ t: 'wall.add', scene: scene.id, + a: [380, 200], b: [380, 420], kind: 'wall' }) + assert.equal(w.ok, true, JSON.stringify(w)) + assert.equal((await ctx.gm.ws.request({ t: 'wall.remove', scene: scene.id, + id: w.id })).ok, true) + } + })() + const fetches = (async () => { + for (let i = 0; i < 200; i++) await fetchTile() + })() + await Promise.all([edits, fetches]) + assert.ok(allowed + refused === 200, `every request answered (${allowed} + ${refused})`) + assert.ok(allowed > 0, 'the request shape was fetchable at least once') + // The server is alive and still answers its own health after the interleaving. + assert.equal((await fetch(`${s.origin}/healthz`)).status, 200) + ctx.gm.ws.close(); ctx.seenCtx.ws.close() + }) +}) + 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' })