main: read the scene once per request, under the lock (#31)

scene.set reassigns app.scene under dbLock while the HTTP handlers read it with
no lock and no stable snapshot: tileGate read it three times (twice outside the
lock) and checkScene read the id unlocked, so a swap could hand a request two
records, or race ORC freeing the old walls seq. tileGate now takes one snapshot
under the lock and uses it for the URL parse, the explored check and the
X-Accel-Redirect; checkScene and scene.set read under the lock; the wall/door
handlers capture sceneId inside their lock for the post-lock log and effect
frame.

Tests: ttiles pins that one record gives one whole answer after a swap;
tiles.test.mjs pins the handler shape (one code read, after the lock) and
interleaves 20 scene.set plus wall edits with 200 tile fetches -- only whole
tiles, no crash.
This commit is contained in:
2026-11-15 14:26:15 +01:00
parent e9d5f6815a
commit f963e8f4d6
3 changed files with 144 additions and 31 deletions
+51 -31
View File
@@ -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: