diff --git a/server/jsonbound.nim b/server/jsonbound.nim new file mode 100644 index 0000000..75f3524 --- /dev/null +++ b/server/jsonbound.nim @@ -0,0 +1,31 @@ +## Copies that cross the intent -> world boundary (ANALYSIS 4.1, DESIGN 4.3). +## +## Mummy runs the websocket handlers on several worker threads. The world is read and written under +## the one global lock, but the intents are parsed outside it. Nim's ORC reference counts are not +## atomic, so any `JsonNode` or `string` payload that is reachable from both an intent tree and the +## world can be ref-counted by two threads at once: once under the lock (an egress walk) and once +## outside it (the intent's `env` dying at the end of `dispatch`). That is a lost update, i.e. a +## premature free or a leak. +## +## Rule: an intent value is copied *at the boundary* into memory nothing else aliases. `copy()` is +## not enough for a `JsonNode`, because std/json rebuilds the nodes but a `JString`'s `str` field is +## still a string assignment and thus shares the intent's payload. Serialise + parse allocates a +## complete second tree, string payloads included. `detachedString` does the same for a bare string. +import std/json +import props + +proc detachedString*(s: string): string = + ## A string whose payload the caller does not share. Empty strings have no payload to share. + if s.len == 0: return "" + result = newString(s.len) + copyMem(addr result[0], unsafeAddr s[0], s.len) + +proc detachedJson*(node: JsonNode): JsonNode = + ## A deep copy of `node` that shares no node and no string payload with it. Serialise/parse is the + ## portable way to get that guarantee from std/json; props and flags are small and bounded. + if node.isNil: nil else: parseJson($node) + +proc detachedProps*(p: Props): Props = + ## The three property buckets, each detached. Keys and values both come from the intent on + ## `token.create`/`character.create`, so a shallow bucket copy would still alias them. + for b in PropBucket: result[b] = detachedJson(p[b]) diff --git a/server/main.nim b/server/main.nim index d830009..1ed0fab 100644 --- a/server/main.nim +++ b/server/main.nim @@ -38,7 +38,7 @@ import std/[atomics, json, locks, options, os, sequtils, sets, strutils, tables] import std/typedthreads import db_connector/db_sqlite import mummy, mummy/routers -import config, db, eventlog, crypto, auth, conns, instancelock, protocol, world +import config, db, eventlog, crypto, auth, conns, instancelock, protocol, world, jsonbound import characters, geometry, props, text, tiles, tokens, vision, views, explored, worldmap, faults, moverules const @@ -46,6 +46,9 @@ const ## FIXED (owner-delegated, #17); DESIGN 6.6 had it PROPOSED. MaxJoinBody* = 1024 ## DESIGN 6.6: the sign-in body is at most 1 KB. + WorkerThreads* = 4 + ## mummy defaults to 10x cores (160 on a 16-core box) for a table of at most seven people; every + ## mutation takes one global lock, so more workers only queue. Four leave room for HTTP/WS/tiles. type App = ref object @@ -351,7 +354,7 @@ proc resyncEveryone() = sendHello(c.id, p.get) resync(c.id, c.named, p.get) -proc settle(conn: Conn, reqId: int, extra: JsonNode = nil, roster = false) = +proc settleLocked(conn: Conn, reqId: int, extra: JsonNode = nil, roster = false) = ## 4.2 step 7 for a mutation: the ack and then every recipient's diff are enqueued under the global ## lock, so no two threads touch a connection's `known` table at once and the ack always precedes ## the effects that mutation caused. Every frame is built from the state at enqueue time, so a @@ -360,22 +363,30 @@ proc settle(conn: Conn, reqId: int, extra: JsonNode = nil, roster = false) = ## makes it cheap, are the M5 outbox (4.3). ## `recordEncounters` runs before the ack: a sighting is durable before the client is told about it ## (the same rule explored cells follow, 4.2 step 6). `roster` = the player list changed. - withLock app.dbLock: - recordEncounters() - ackOk(conn, reqId, extra) - if roster: sendRoster() - egressAll() + ## Caller holds `app.dbLock` (ANALYSIS 4.1: every frame that references world state is built here). + recordEncounters() + ackOk(conn, reqId, extra) + if roster: sendRoster() + egressAll() -proc settleWorld(conn: Conn, reqId: int, wallEffect: JsonNode, extra: JsonNode = nil, - roster = false) = - ## The same for a wall/door write: ack, the GM-only wall effect, then the per-recipient egress - ## (a wall change can reveal or hide tokens and always changes vision). +proc settle(conn: Conn, reqId: int, extra: JsonNode = nil, roster = false) = + ## The general form: takes the lock itself. `extra` must not reference world state (ints, floats + ## and freshly allocated strings only); a handler that has a world record in hand calls + ## `settleLocked` inside its own critical section instead. withLock app.dbLock: - recordEncounters() - ackOk(conn, reqId, extra) - sendToGms(wallEffect) - if roster: sendRoster() - egressAll() + settleLocked(conn, reqId, extra, roster) + +proc settleWorldLocked(conn: Conn, reqId: int, wallEffect: JsonNode, extra: JsonNode = nil, + roster = false) = + ## The same for a wall/door write: ack, the GM-only wall effect, then the per-recipient egress + ## (a wall change can reveal or hide tokens and always changes vision). `wallEffect` references a + ## wall record, so it is built by the caller *inside* the same critical section; the frame and the + ## last reference to the record both die here, under the lock. + recordEncounters() + ackOk(conn, reqId, extra) + sendToGms(wallEffect) + if roster: sendRoster() + egressAll() # --------------------------------------------------------------------------------------------------- # Applying a move-rules outcome (DESIGN 5.5, 5.6). Every wall/door edit and every resize runs the @@ -929,14 +940,16 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = let closed = app.conns.revokePlayer(id) for doomed in closed: closeGone(doomed, ReasonRevoked, CloseRevoked) # DESIGN 3.2: that player's controlled tokens pass to the GM. The FK's ON DELETE SET NULL did - # the row; memory (and the `controller: null` the GM sees) follows here. - for t in app.tokens.mitems: - if t.owner == id: t.owner = GmControlled - for c in app.characters.mitems: - if c.owner == id: c.owner = app.gmPlayerId - app.visions.del id - app.reveals.withoutRevealsOf(id) - app.encountered.del id + # the row; memory (and the `controller: null` the GM sees) follows here. Every in-memory table + # that holds refcounted strings is touched only under the lock (ANALYSIS 4.1). + withLock app.dbLock: + for t in app.tokens.mitems: + if t.owner == id: t.owner = GmControlled + for c in app.characters.mitems: + if c.owner == id: c.owner = app.gmPlayerId + app.visions.del id + app.reveals.withoutRevealsOf(id) + app.encountered.del id app.lg.log(lvInfo, "player_removed", [("player", $id), ("conns_closed", $closed.len)]) settle(conn, env.reqId, roster = true) return @@ -990,14 +1003,23 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = if tokenProps.isNone: ackErr(conn, env.reqId, CodeInvalid) return - var created: tuple[outcome: TokenOutcome, token: TokenRec] + var tokenOutcome = toInvalid + var createdId = "" + var createdScene = 0 var controllerCheck = ccOk var characterMissing = false withLock app.dbLock: - var candidate = TokenRec(kind: kind, descriptiveName: dname, actualName: aname, - pos: pos.get, gmOnly: gmOnly, flags: flags.get, + # Every intent value is detached here: `flags`, `props`, the two names, `kind` and the + # `character_id` string must not share a node or a string payload with `env` (ANALYSIS 4.1). + var candidate = TokenRec(kind: detachedString(kind), + descriptiveName: detachedString(dname), + actualName: detachedString(aname), + pos: pos.get, gmOnly: gmOnly, flags: detachedJson(flags.get), visionRadius: vr.get, radius: radius.get, - props: tokenProps.get, characterId: characterId) + props: detachedProps(tokenProps.get), + characterId: (if characterId.isSome: + some(detachedString(characterId.get)) + else: none(string))) if characterId.isSome: # 6.1: the default controller of a linked token is the character's owner; the GM's own id is # stored as GM-controlled like everywhere else. A missing character is `not-found`. @@ -1016,12 +1038,18 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = var mr = moveScene(app.scene, app.tokens & @[candidate]) moverules.placeToken(mr, app.tokens.len) candidate.statuses = wallsStatuses(candidate.statuses, mr.tokens[app.tokens.len]) - created = addToken(app.db, app.scene, candidate, app.tokens.mapIt(it.id)) + let created = addToken(app.db, app.scene, candidate, app.tokens.mapIt(it.id)) + tokenOutcome = created.outcome if created.outcome == toOk: app.tokens.add created.token refreshPlayer(created.token.owner) app.db.withTransaction: persistExplored(@[created.token.owner]) + # The record copy (`created`, and the world's own) must die under this lock, and so must + # the ack's `id`: settle inside the critical section, then carry only fresh scalars out. + createdId = detachedString(created.token.id) + createdScene = created.token.scene + settleLocked(conn, env.reqId, %*{"id": created.token.id}) if characterMissing: ackErr(conn, env.reqId, CodeNotFound) # no such character return @@ -1031,12 +1059,10 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = if controllerCheck == ccNotFound: ackErr(conn, env.reqId, CodeNotFound) # no such controller player return - if created.outcome != toOk: + if tokenOutcome != toOk: ackErr(conn, env.reqId, CodeInvalid) return - app.lg.log(lvInfo, "token_create", [("token", created.token.id), - ("scene", $created.token.scene)]) - settle(conn, env.reqId, %*{"id": created.token.id}) + app.lg.log(lvInfo, "token_create", [("token", createdId), ("scene", $createdScene)]) return of "token.update": @@ -1118,7 +1144,6 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = return var outcome = toNotFound - var updated: TokenRec var controllerCheck = ccOk var controller = GmControlled var characterMissing = false @@ -1132,25 +1157,39 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = controllerCheck = resolveController(env.node{"controller"}, controller) if controllerCheck == ccOk: patch.controller = some(controller) if controllerCheck == ccOk and not characterMissing: - let candidate = patched(current.get, patch) + # Detach every patch field that is about to enter the world *here*, so the copies the + # world keeps and the locals that carry them all die under this lock (ANALYSIS 4.1). + var storedPatch = patch + if patch.kind.isSome: storedPatch.kind = some(detachedString(patch.kind.get)) + if patch.descriptiveName.isSome: + storedPatch.descriptiveName = some(detachedString(patch.descriptiveName.get)) + if patch.actualName.isSome: + storedPatch.actualName = some(detachedString(patch.actualName.get)) + if patch.characterId.isSome: + storedPatch.characterId = + if patch.characterId.get.isSome: + some(some(detachedString(patch.characterId.get.get))) + else: + some(none(string)) + if patch.flags.isSome: storedPatch.flags = some(detachedJson(patch.flags.get)) + let candidate = patched(current.get, storedPatch) outcome = storeToken(app.db, app.scene, candidate) if outcome == toOk: let oldOwner = current.get.owner - updated = candidate - app.tokens[tokenIndex(app.tokens, id).get] = updated + app.tokens[tokenIndex(app.tokens, id).get] = candidate refreshPlayer(oldOwner) - refreshPlayer(updated.owner) + refreshPlayer(candidate.owner) app.db.withTransaction: - persistExplored(@[oldOwner, updated.owner]) + persistExplored(@[oldOwner, candidate.owner]) # A plain-token rename or a link change keeps every encountered snapshot of this token # in step with its subject - the descriptive name, the character link and the actual # name this player may know - in the DB and in memory at once (8; #29, #30). A linked # token's names reach the same helper through `character.update`. - if current.get.characterId != updated.characterId or - current.get.descriptiveName != updated.descriptiveName or - current.get.actualName != updated.actualName: + if current.get.characterId != candidate.characterId or + current.get.descriptiveName != candidate.descriptiveName or + current.get.actualName != candidate.actualName: discard rewriteEncountered(app.db, app.encountered, nsToken, id, - subjectNamesOf(updated, app.characters), app.reveals) + subjectNamesOf(candidate, app.characters), app.reveals) if characterMissing: ackErr(conn, env.reqId, CodeNotFound) return @@ -1393,6 +1432,9 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = if not stringField(env, "key", key) or not props.validPropKey(key): ackErr(conn, env.reqId, CodeInvalid) return + # The key and the value both enter the world (a props object key and a value node). Detach them + # *inside* each critical section: the detached copies are then reachable from the world and must + # die under the lock too (ANALYSIS 4.1). var value: JsonNode if setting: value = env.node{"value"} @@ -1411,15 +1453,17 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = var charOutcome = coNotFound var capped = false withLock app.dbLock: + let storedKey = detachedString(key) + let storedValue = if setting: detachedJson(value) else: nil let idx = characterIndex(app.characters, id) if idx.isSome: var rec = app.characters[idx.get] var p = props.clone(rec.props) if setting: - if not p.setProp(bucket.get, key, value): capped = true + if not p.setProp(bucket.get, storedKey, storedValue): capped = true else: rec.props = p else: - discard p.unsetProp(bucket.get, key) # unsetting an absent key is ok (6.1) + discard p.unsetProp(bucket.get, storedKey) # unsetting an absent key is ok (6.1) rec.props = p if not capped: charOutcome = storeCharacter(app.db, rec) @@ -1440,15 +1484,17 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = var outcome = toNotFound var capped = false withLock app.dbLock: + let storedKey = detachedString(key) + let storedValue = if setting: detachedJson(value) else: nil let idx = tokenIndex(app.tokens, id) if idx.isSome: var rec = app.tokens[idx.get] var p = props.clone(rec.props) if setting: - if not p.setProp(bucket.get, key, value): capped = true + if not p.setProp(bucket.get, storedKey, storedValue): capped = true else: rec.props = p else: - discard p.unsetProp(bucket.get, key) # unsetting an absent key is ok (6.1) + discard p.unsetProp(bucket.get, storedKey) # unsetting an absent key is ok (6.1) rec.props = p if not capped: outcome = storeToken(app.db, app.scene, rec) @@ -1488,25 +1534,33 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = if charProps.isNone: ackErr(conn, env.reqId, CodeInvalid) return - var created: tuple[outcome: CharacterOutcome, character: CharacterRec] + var charOutcome = coInvalid + var createdId = "" + var createdOwner = 0 var ownerMissing = false withLock app.dbLock: if playerById(app.db, owner).isNone: ownerMissing = true else: - let candidate = CharacterRec(owner: owner, descriptiveName: dname, actualName: aname, - props: charProps.get) - created = addCharacter(app.db, candidate, allIds()) - if created.outcome == coOk: app.characters.add created.character + let candidate = CharacterRec(owner: owner, descriptiveName: detachedString(dname), + actualName: detachedString(aname), + props: detachedProps(charProps.get)) + let created = addCharacter(app.db, candidate, allIds()) + charOutcome = created.outcome + if created.outcome == coOk: + app.characters.add created.character + # Record copy and ack value die under the lock, as for `token.create`. + createdId = detachedString(created.character.id) + createdOwner = created.character.owner + settleLocked(conn, env.reqId, %*{"id": created.character.id}) if ownerMissing: ackErr(conn, env.reqId, CodeNotFound) # 6.5 step 8: no such owner player return - if created.outcome != coOk: + if charOutcome != coOk: ackErr(conn, env.reqId, CodeInvalid) return - app.lg.log(lvInfo, "character_create", [("character", created.character.id), - ("owner", $created.character.owner)]) - settle(conn, env.reqId, %*{"id": created.character.id}) + app.lg.log(lvInfo, "character_create", [("character", createdId), + ("owner", $createdOwner)]) return of "character.update": @@ -1518,37 +1572,39 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = var patch = CharacterRec() var anyField = false if present(env, "descriptive_name"): - if not stringField(env, "descriptive_name", patch.descriptiveName) or - not validCharacterName(patch.descriptiveName): + var name: string + if not stringField(env, "descriptive_name", name) or not validCharacterName(name): ackErr(conn, env.reqId, CodeInvalid) return + patch.descriptiveName = name anyField = true if present(env, "actual_name"): - if not stringField(env, "actual_name", patch.actualName) or - not validCharacterName(patch.actualName): + var name: string + if not stringField(env, "actual_name", name) or not validCharacterName(name): ackErr(conn, env.reqId, CodeInvalid) return + patch.actualName = name anyField = true if not anyField: ackErr(conn, env.reqId, CodeInvalid) return var outcome = coNotFound - var updated: CharacterRec withLock app.dbLock: let idx = characterIndex(app.characters, id) if idx.isSome: var candidate = app.characters[idx.get] - if present(env, "descriptive_name"): candidate.descriptiveName = patch.descriptiveName - if present(env, "actual_name"): candidate.actualName = patch.actualName + if present(env, "descriptive_name"): + candidate.descriptiveName = detachedString(patch.descriptiveName) + if present(env, "actual_name"): + candidate.actualName = detachedString(patch.actualName) outcome = storeCharacter(app.db, candidate) if outcome == coOk: - updated = candidate - app.characters[idx.get] = updated + app.characters[idx.get] = candidate # 6.1: "encountered upserts for players who met it" - every snapshot of this character # follows the new names on the wire and in the DB at once (#30), with the actual name # set only for the players the name rule allows (8). discard rewriteEncountered(app.db, app.encountered, nsCharacter, id, - subjectNamesOf(updated), app.reveals) + subjectNamesOf(candidate), app.reveals) if outcome == coNotFound: ackErr(conn, env.reqId, CodeNotFound) return @@ -1600,7 +1656,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = ackErr(conn, env.reqId, CodeInvalid) return var outcome = coNotFound - var updated: CharacterRec + var updatedOwner = 0 withLock app.dbLock: let idx = characterIndex(app.characters, id) if idx.isSome and playerById(app.db, owner).isSome: @@ -1608,12 +1664,12 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = candidate.owner = owner outcome = storeCharacter(app.db, candidate) if outcome == coOk: - updated = candidate - app.characters[idx.get] = updated + app.characters[idx.get] = candidate + updatedOwner = candidate.owner # A reassignment changes who is told the actual name (8), so the snapshots of everyone # who met the character follow it on the wire and in the DB (#30). discard rewriteEncountered(app.db, app.encountered, nsCharacter, id, - subjectNamesOf(updated), app.reveals) + subjectNamesOf(candidate), app.reveals) if outcome == coNotFound: ackErr(conn, env.reqId, CodeNotFound) # no such character or owner return @@ -1629,9 +1685,9 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = for i in 0 ..< app.tokens.len: if app.tokens[i].characterId == some(id): var rec = app.tokens[i] - rec.owner = (if updated.owner == app.gmPlayerId: GmControlled else: updated.owner) + rec.owner = (if updatedOwner == app.gmPlayerId: GmControlled else: updatedOwner) if storeToken(app.db, app.scene, rec) == toOk: app.tokens[i] = rec - app.lg.log(lvInfo, "character_reassign", [("character", id), ("owner", $updated.owner)]) + app.lg.log(lvInfo, "character_reassign", [("character", id), ("owner", $updatedOwner)]) settle(conn, env.reqId) return @@ -1654,17 +1710,21 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = ackErr(conn, env.reqId, CodeInvalid) return var outcome = nrNotFound - var subjectId = id # One lock hold for the lookup, the reveal row and the snapshot rewrite (#27): a rename landing # between a lookup and the write would otherwise persist a name the subject no longer has. withLock app.dbLock: var names: SubjectNames + # The reveal set stores the id it is given, so use the *world's* id string, not the intent's + # payload: a local holding an intent string past the lock would be freed off-thread + # (ANALYSIS 4.1). It lives and dies inside this block. + var subjectId = "" if playerById(app.db, player).isNone: outcome = nrNotFound elif subject.get == nsCharacter: let ch = characterById(app.characters, id) if ch.isNone: outcome = nrNotFound else: + subjectId = ch.get.id names = subjectNamesOf(ch.get) outcome = nrOk else: @@ -1672,6 +1732,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = if tok.isNone: outcome = nrNotFound elif tok.get.characterId.isSome: outcome = nrInvalid # reveal through the character (6.1) else: + subjectId = tok.get.id names = subjectNamesOf(tok.get, app.characters) outcome = nrOk if outcome == nrOk: @@ -1706,8 +1767,8 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = ackErr(conn, env.reqId, CodeInvalid) return var outcome = coNotFound - var names: SubjectNames withLock app.dbLock: + var names: SubjectNames # world-owned strings: must die under the lock (ANALYSIS 4.1) if subject.get == nsCharacter: let idx = characterIndex(app.characters, id) if idx.isSome: @@ -1771,22 +1832,29 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = # `art_version` are not patch fields (import is the M6 CLI) and are ignored as unknown fields # (6.2); a patch carrying only those has no field and is `invalid`. if not sceneOk(conn, env): return - let patch = parseScenePatch(env.node) - if patch.isNone: + var patchOpt = parseScenePatch(env.node) + if patchOpt.isNone: ackErr(conn, env.reqId, CodeInvalid) return - var candidate: SceneRec + var patch = patchOpt.get var changed: seq[string] - if patch.get.name.isSome: changed.add "name" - if patch.get.gridSize.isSome: changed.add "grid_size" - if patch.get.visionRadiusDefault.isSome: changed.add "vision_radius_default" - if patch.get.tokenRadiusDefault.isSome: changed.add "token_radius_default" - if patch.get.extra.isSome: changed.add "extra" - var tokenChanges: seq[(int, TokenRec)] + if patch.name.isSome: changed.add "name" + if patch.gridSize.isSome: changed.add "grid_size" + if patch.visionRadiusDefault.isSome: changed.add "vision_radius_default" + if patch.tokenRadiusDefault.isSome: changed.add "token_radius_default" + if patch.extra.isSome: changed.add "extra" + var candidateId = 0 + var resizedCount = 0 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) + # `name` and `extra` are stored verbatim, so detach them here; `candidate`, `storedPatch` and + # `tokenChanges` hold world refs and all die inside this block (ANALYSIS 4.1). + var storedPatch = patch + if patch.name.isSome: storedPatch.name = some(detachedString(patch.name.get)) + if patch.extra.isSome: storedPatch.extra = some(detachedJson(patch.extra.get)) + let candidate = app.scene.patched(storedPatch) + var tokenChanges: seq[(int, TokenRec)] # 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), @@ -1815,9 +1883,11 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = recordEncounters() ackOk(conn, env.reqId) resyncEveryone() - app.lg.log(lvInfo, "scene_set", [("scene", $candidate.id), + candidateId = candidate.id + resizedCount = tokenChanges.len + app.lg.log(lvInfo, "scene_set", [("scene", $candidateId), ("fields", changed.join(",")), - ("tokens_resized", $tokenChanges.len)]) + ("tokens_resized", $resizedCount)]) return of "wall.add": @@ -1847,29 +1917,39 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = if flags.isNone: ackErr(conn, env.reqId, CodeInvalid) return - let candidate = WallRec(a: a.get, b: b.get, kind: kind.get, open: open.get, flags: flags.get) - var added: Option[WallRec] + var addedId = 0 + var addedKind = "" var sceneId = 0 + var ok = false withLock app.dbLock: sceneId = app.scene.id # the request's one read (#31) + # `candidate` is built here so its `flags` copy and its record copy both die under the lock; + # `detachedJson` keeps the stored object independent of `env` (ANALYSIS 4.1). + let candidate = WallRec(a: a.get, b: b.get, kind: kind.get, open: open.get, + flags: detachedJson(flags.get)) # 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. var mr = moveScene(app.scene, app.tokens) let id = addWall(app.db, app.scene, candidate) if id.isSome: - added = wallById(app.scene, id.get) + let added = wallById(app.scene, id.get) discard moverules.addWall(mr, ruleWall(added.get)) discard applyRuleOutcome(mr) refreshAll() # 4.2 step 5: a wall change moves every player's sight persistAllExplored() # step 6: the chunks the new wall revealed, before the ack - if added.isNone: + addedId = added.get.id + addedKind = $added.get.kind + # The wall frame references `added.flags`; build it and fan it out here, before the record + # copy leaves scope, never after the lock is released (ANALYSIS 4.1). + settleWorldLocked(conn, env.reqId, wallFrame(sceneId, wallObjectOf(added.get)), + %*{"id": added.get.id}) + ok = true + if not ok: ackErr(conn, env.reqId, CodeInvalid) # degenerate or out-of-bounds geometry return - app.lg.log(lvInfo, "wall_add", [("scene", $sceneId), ("wall", $added.get.id), - ("kind", $added.get.kind)]) - settleWorld(conn, env.reqId, wallFrame(sceneId, wallObjectOf(added.get)), - %*{"id": added.get.id}) + app.lg.log(lvInfo, "wall_add", [("scene", $sceneId), ("wall", $addedId), + ("kind", addedKind)]) return of "wall.update": @@ -1917,32 +1997,40 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = ackErr(conn, env.reqId, CodeInvalid) return var outcome = waNotFound - var updated: Option[WallRec] + var updatedKind = "" var sceneId = 0 + var ok = false withLock app.dbLock: sceneId = app.scene.id # the request's one read (#31) + # The flags object goes into the wall record verbatim: detach it here so both the record and + # this local die under the lock (ANALYSIS 4.1). + var storedPatch = patch + if patch.flags.isSome: storedPatch.flags = some(detachedJson(patch.flags.get)) 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 # with the patched wall at the same index, so a move away clears and a move onto a token sticks. let idx = wallIndex(app.scene, id).get var mr = moveScene(app.scene, app.tokens) - outcome = updateWall(app.db, app.scene, patched(current.get, patch)) + outcome = updateWall(app.db, app.scene, patched(current.get, storedPatch)) if outcome == waOk: - updated = wallById(app.scene, id) + let updated = wallById(app.scene, id) discard moverules.updateWall(mr, idx, ruleWall(updated.get)) discard applyRuleOutcome(mr) refreshAll() persistAllExplored() + updatedKind = $updated.get.kind + # Frame and record copy both live and die inside this lock (ANALYSIS 4.1). + settleWorldLocked(conn, env.reqId, wallFrame(sceneId, wallObjectOf(updated.get))) + ok = true if outcome == waNotFound: ackErr(conn, env.reqId, CodeNotFound) return - if outcome != waOk or updated.isNone: + if outcome != waOk or not ok: ackErr(conn, env.reqId, CodeInvalid) return app.lg.log(lvInfo, "wall_update", [("scene", $sceneId), ("wall", $id), - ("kind", $updated.get.kind)]) - settleWorld(conn, env.reqId, wallFrame(sceneId, wallObjectOf(updated.get))) + ("kind", updatedKind)]) return of "wall.remove": @@ -1969,7 +2057,8 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = ackErr(conn, env.reqId, CodeNotFound) return app.lg.log(lvInfo, "wall_remove", [("scene", $sceneId), ("wall", $id)]) - settleWorld(conn, env.reqId, wallGoneFrame(sceneId, id)) + withLock app.dbLock: + settleWorldLocked(conn, env.reqId, wallGoneFrame(sceneId, id)) return of "door.set": @@ -1984,8 +2073,8 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = return let open = openNode.getBool var outcome = waNotFound - var updated: Option[WallRec] var sceneId = 0 + var ok = false 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; @@ -1996,20 +2085,22 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = var mr = moveScene(app.scene, app.tokens) outcome = setDoor(app.db, app.scene, id, open) if outcome == waOk: - updated = wallById(app.scene, id) + let updated = wallById(app.scene, id) if idx.isSome: discard moverules.setDoor(mr, idx.get, open) discard applyRuleOutcome(mr) refreshAll() persistAllExplored() + # Frame and record copy both live and die inside this lock (ANALYSIS 4.1). + settleWorldLocked(conn, env.reqId, wallFrame(sceneId, wallObjectOf(updated.get))) + ok = true if outcome == waNotFound: ackErr(conn, env.reqId, CodeNotFound) return - if outcome != waOk or updated.isNone: + if outcome != waOk or not ok: ackErr(conn, env.reqId, CodeInvalid) # waNotDoor: a plain wall has no open state return app.lg.log(lvInfo, "door_set", [("scene", $sceneId), ("wall", $id), ("open", $open)]) - settleWorld(conn, env.reqId, wallFrame(sceneId, wallObjectOf(updated.get))) return else: @@ -2239,7 +2330,9 @@ proc runServer(cfg: Config): int = lg.log(lvInfo, "heartbeat", [("interval_ms", $PingIntervalMs), ("proto", $ProtoVersion)]) # maxMessageLen is DESIGN 6.4's 64 KB, stated explicitly rather than inherited from mummy. + # `WorkerThreads`: mummy's default is 10 x cores, far too many for one table (ANALYSIS 4.1). let server = newServer(buildRouter().toHandler(), websocketEvent, mummyLog, + workerThreads = WorkerThreads, maxMessageLen = MaxInboundBytes) lg.log(lvInfo, "listen", [("addr", BindAddress), ("port", $cfg.port)]) server.serve(Port(cfg.port), BindAddress) diff --git a/tests/tdetach.nim b/tests/tdetach.nim new file mode 100644 index 0000000..70af85d --- /dev/null +++ b/tests/tdetach.nim @@ -0,0 +1,68 @@ +## The intent -> world boundary copies (ANALYSIS 4.1): a regression guard for the *shape* of the +## fix, not for the race itself. A unit test can prove that the helper returns memory that aliases +## nothing the caller passed in (identity and string-payload checks); it cannot prove that every +## handler calls it, and it cannot reproduce a non-atomic refcount race. The handler audit and the +## "frames are built under the lock" rule are verified by reading, not by this file. +import std/[json, options, unittest] +import jsonbound, props, world + +proc ptrOf(n: JsonNode): pointer = cast[pointer](n) + +proc payload(s: string): pointer = + ## The address of a string's first character: two strings that share a payload answer the same. + if s.len == 0: nil else: cast[pointer](unsafeAddr s[0]) + +suite "detachedJson": + test "rebuilds nodes and string payloads": + let src = parseJson("""{"vision":true,"name":"scroll","nested":{"k":[1,2,3]}}""") + let dst = detachedJson(src) + check ptrOf(dst) != ptrOf(src) + check $dst == $src + check payload(dst["name"].getStr) != payload(src["name"].getStr) + check ptrOf(dst["nested"]) != ptrOf(src["nested"]) + check ptrOf(dst["nested"]["k"]) != ptrOf(src["nested"]["k"]) + + test "mutating the source leaves the copy alone": + let src = parseJson("""{"vision":true}""") + let dst = detachedJson(src) + src["vision"] = %false + check dst["vision"].getBool + check not src["vision"].getBool + + test "absent (nil) stays nil and null stays null": + check detachedJson(nil).isNil + check detachedJson(newJNull()).kind == JNull + +suite "detachedString": + test "does not share the payload": + let src = "vision" + let dst = detachedString(src) + check dst == src + check payload(dst) != payload(src) + + test "empty strings stay empty": + check detachedString("") == "" + check payload(detachedString("")) == nil + +suite "detachedProps": + test "three independent buckets, keys and values included": + let src = parseJson("""{"public":{"a":1},"owner":{"b":{"c":2}},"gm":{}}""") + var parsed: Props + for name, bucket in src: + parsed[parseBucket(name).get] = bucket + let dst = detachedProps(parsed) + for b in PropBucket: + check ptrOf(dst[b]) != ptrOf(parsed[b]) + check $dst[b] == $parsed[b] + var srcKey, dstKey: string + for k in parsed[pbOwner].keys: srcKey = k + for k in dst[pbOwner].keys: dstKey = k + check payload(dstKey) != payload(srcKey) + +suite "the premise this guards (world.parseFlags)": + test "parseFlags returns the caller's node by reference, not a copy": + # If this ever becomes a copy, the boundary still works; the test records why it exists. + let env = parseJson("""{"flags":{"vision":true}}""") + let flags = parseFlags(env{"flags"}) + check flags.isSome + check ptrOf(flags.get) == ptrOf(env{"flags"})