names: per-player reveal, one encountered write path, link by update (#27, #29, #30)

name.reveal wrote the subject's actual name into the encountered row of every
player who had met it: the SQL had no player predicate, so the leak was silent
live and visible only after a restart. rewriteEncountered is now the one path
that keeps a snapshot in step with its subject: it rewrites the SQLite row and
the live in-memory entry together from the name rule, takes onlyPlayer for
name.reveal (every player for reveal_all), and also runs on a rename, a link
change and an owner change, so the wire and a post-restart reload cannot
disagree (#30). The DB-only renameEncountered*/revealEncountered* helpers are
gone, which is what let the two stores drift.

token.update {character_id} now drops the token's own two names as part of the
link patch (#29): a plain token can be linked, names supplied with a link stay
invalid and unlinking still needs both names.

Tests: tcharacters covers the per-player row, the DB/memory equality, the link
handover; restart.test.mjs builds three named players, reveals to one of them
and asserts the rows directly and the whole resync over SIGTERM/SIGKILL, plus a
mid-session rename; leak.mjs/leakcheck.nim pit two players on the same subject
and pin each entry's expected name (STALE_NAME). Mutations e1-e3 and the
repointed b2 pin the three rules.
This commit is contained in:
2026-11-15 14:26:07 +01:00
parent e68c6eefbf
commit 8e045b0ac8
9 changed files with 528 additions and 93 deletions
+45 -18
View File
@@ -28,8 +28,9 @@
##
## This module does no locking (the caller holds the global lock, 4.3) and no wire shapes (that is
## server/views.nim); it owns the records and their SQLite rows.
import std/[algorithm, json, options, sets, strutils, tables, times]
import std/[algorithm, json, options, sequtils, sets, strutils, tables, times]
import db_connector/db_sqlite
import db
import props, text, tokens, world
type
@@ -183,6 +184,24 @@ proc revealed*(e: EncounteredEntry, actual: string): EncounteredEntry =
result = e
result.actualName = some(actual)
proc refreshed*(e: EncounteredEntry, n: SubjectNames, knows: bool): EncounteredEntry =
## The snapshot after any change the name rule can see: the names and the character link are the
## subject's now, and the actual name is exactly what this player may know (`knows`, from 8).
## Recomputing it instead of patching the old value is what keeps DB and memory in step (#30):
## a rename keeps a not-told player not-told, a reveal fills the one player in, a link change moves
## the snapshot to the character's names and link, and an unlink drops the link again.
EncounteredEntry(entityId: e.entityId, characterId: n.characterId,
descriptiveName: n.descriptive,
actualName: (if knows: some(n.actual) else: none(string)))
proc entryMatches*(e: EncounteredEntry, subject: NameSubject, subjectId: string): bool =
## Does this entry snapshot the subject? A character's entries are the ones that carry its link;
## a plain token's are the ones keyed by its own id (they may carry a character link after a
## later join, which is why the character test cannot be `entityId == subjectId`).
case subject
of nsCharacter: e.characterId == some(subjectId)
of nsToken: e.entityId == subjectId
# ---------------------------------------------------------------------------------------------------
# Persistence (write-through; GM authoring runs in the caller's FULL transaction, 4.4/Q12)
@@ -271,24 +290,32 @@ proc deleteEncountered*(db: DbConn, player: int, entityId: string): bool =
db.execAffectedRows(sql"DELETE FROM encountered WHERE player_id = ? AND entity_id = ?",
player, entityId) > 0
proc renameEncountered*(db: DbConn, characterId: string, descriptive, actual: string) =
## `character.update`: every snapshot of this character follows the new names. A player who was
## never told the actual name keeps not knowing it (an unknown actual name is stored as `''`).
db.exec(sql"""UPDATE encountered SET descriptive_name = ? WHERE character_id = ?""",
descriptive, characterId)
db.exec(sql"""UPDATE encountered SET actual_name = ? WHERE character_id = ?
AND actual_name <> ''""", actual, characterId)
proc rewriteEncountered*(db: DbConn, enc: var Encountered, subject: NameSubject, subjectId: string,
n: SubjectNames, reveals: Reveals, onlyPlayer = 0):
seq[(int, string)] =
## The one path that keeps `encountered` in step with its subject (#27, #29, #30). Given the
## subject's current names (`n`) it rewrites every matching snapshot - SQLite row and in-memory
## entry together - so a restart cannot disagree with the live wire, and it applies the 8 name rule
## per player (`reveals`) so the actual name is set exactly for the players allowed to know it.
## `onlyPlayer` = 0 means every player; any other value scopes the whole rewrite to that player
## (`name.reveal`), which is why the old subject-only SQL leaked the actual name to everyone.
## The persistence is NORMAL (a snapshot is derived data, Q12). The caller holds the global lock.
var changes: seq[(int, EncounteredEntry)]
for pid in enc.keys.toSeq:
if onlyPlayer != 0 and pid != onlyPlayer: continue
if not enc.hasKey(pid): continue
for entityId, e in enc[pid]:
if not e.entryMatches(subject, subjectId): continue
let updated = e.refreshed(n, knowsActual(n.owner == pid and n.owner > 0, n.revealAll,
reveals.isRevealed(pid, n.id)))
if updated != e: changes.add (pid, updated)
if changes.len == 0: return
db.withTransaction:
for (pid, e) in changes: writeEncountered(db, pid, e)
for (pid, e) in changes:
enc[pid][e.entityId] = e
result.add (pid, e.entityId)
proc revealEncountered*(db: DbConn, characterId: string, actual: string) =
db.exec(sql"UPDATE encountered SET actual_name = ? WHERE character_id = ?", actual, characterId)
proc revealEncounteredToken*(db: DbConn, entityId: string, actual: string) =
db.exec(sql"UPDATE encountered SET actual_name = ? WHERE entity_id = ?", actual, entityId)
proc renameEncounteredToken*(db: DbConn, entityId, descriptive, actual: string) =
db.exec(sql"UPDATE encountered SET descriptive_name = ? WHERE entity_id = ?", descriptive, entityId)
db.exec(sql"""UPDATE encountered SET actual_name = ? WHERE entity_id = ?
AND actual_name <> ''""", actual, entityId)
# ---------------------------------------------------------------------------------------------------
# Loading (4.4 startup: load everything into memory once)
+39 -39
View File
@@ -1131,13 +1131,15 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
refreshPlayer(updated.owner)
app.db.withTransaction:
persistExplored(@[oldOwner, updated.owner])
# A plain token renamed here keeps its encountered snapshots in step with it (8); a
# linked token's names live on the character, whose own handler does the same.
if updated.characterId.isNone and
(current.get.descriptiveName != updated.descriptiveName or
current.get.actualName != updated.actualName):
app.db.withTransaction:
renameEncounteredToken(app.db, id, updated.descriptiveName, updated.actualName)
# 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:
discard rewriteEncountered(app.db, app.encountered, nsToken, id,
subjectNamesOf(updated, app.characters), app.reveals)
if characterMissing:
ackErr(conn, env.reqId, CodeNotFound)
return
@@ -1532,9 +1534,10 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
updated = candidate
app.characters[idx.get] = updated
# 6.1: "encountered upserts for players who met it" - every snapshot of this character
# follows the new names (a player who was never told the actual one keeps not knowing it).
app.db.withTransaction:
renameEncountered(app.db, id, updated.descriptiveName, updated.actualName)
# 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)
if outcome == coNotFound:
ackErr(conn, env.reqId, CodeNotFound)
return
@@ -1596,6 +1599,10 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
if outcome == coOk:
updated = candidate
app.characters[idx.get] = updated
# 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)
if outcome == coNotFound:
ackErr(conn, env.reqId, CodeNotFound) # no such character or owner
return
@@ -1636,42 +1643,40 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
ackErr(conn, env.reqId, CodeInvalid)
return
var outcome = nrNotFound
var actual = ""
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
if playerById(app.db, player).isNone:
outcome = nrNotFound
elif subject.get == nsCharacter:
let ch = characterById(app.characters, id)
if ch.isNone: outcome = nrNotFound
else:
actual = ch.get.actualName
names = subjectNamesOf(ch.get)
outcome = nrOk
else:
let tok = tokenById(app.tokens, id)
if tok.isNone: outcome = nrNotFound
elif tok.get.characterId.isSome: outcome = nrInvalid # reveal through the character (6.1)
else:
actual = tok.get.actualName
names = subjectNamesOf(tok.get, app.characters)
outcome = nrOk
if outcome == nrOk:
addReveal(app.db, player, subjectId)
app.reveals.withReveal(player, subjectId)
# 6.1: the player's encountered list learns the actual name too (the snapshot, not a view).
# Scoped to this one player (#27): the row of every other player who met the subject is
# untouched, which is what makes the live frame and the post-restart frame agree.
discard rewriteEncountered(app.db, app.encountered, subject.get, subjectId, names,
app.reveals, onlyPlayer = player)
if outcome == nrInvalid:
ackErr(conn, env.reqId, CodeInvalid)
return
if outcome == nrNotFound:
ackErr(conn, env.reqId, CodeNotFound)
return
withLock app.dbLock:
addReveal(app.db, player, subjectId)
app.reveals.withReveal(player, subjectId)
# 6.1: the player's encountered list learns the actual name too (the snapshot, not a view).
app.db.withTransaction:
if subject.get == nsCharacter: revealEncountered(app.db, subjectId, actual)
else: revealEncounteredToken(app.db, subjectId, actual)
for eid in app.encountered.getOrDefault(player).keys.toSeq:
let e = app.encountered[player][eid]
if (subject.get == nsCharacter and e.characterId == some(subjectId)) or
(subject.get == nsToken and eid == subjectId):
app.encountered[player][eid] = e.revealed(actual)
app.lg.log(lvInfo, "name_reveal", [("subject", subjectRaw), ("id", id), ("player", $player)])
settle(conn, env.reqId)
return
@@ -1690,38 +1695,33 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
ackErr(conn, env.reqId, CodeInvalid)
return
var outcome = coNotFound
var actual = ""
var names: SubjectNames
withLock app.dbLock:
if subject.get == nsCharacter:
let idx = characterIndex(app.characters, id)
if idx.isSome:
var candidate = app.characters[idx.get]
candidate.revealAll = true
actual = candidate.actualName
outcome = storeCharacter(app.db, candidate)
if outcome == coOk: app.characters[idx.get] = candidate
if outcome == coOk:
app.characters[idx.get] = candidate
names = subjectNamesOf(candidate)
else:
let idx = tokenIndex(app.tokens, id)
if idx.isSome:
var candidate = app.tokens[idx.get]
candidate.revealAll = true
actual = candidate.actualName
# `reveal_all` on a plain token is the same flag a character carries, so it goes through
# the token's own store; the two outcome enums differ only in name here.
let stored = storeToken(app.db, app.scene, candidate)
outcome = (if stored == toOk: coOk elif stored == toNotFound: coNotFound
else: coInvalid)
if outcome == coOk: app.tokens[idx.get] = candidate
if outcome == coOk:
app.tokens[idx.get] = candidate
names = subjectNamesOf(candidate, app.characters)
if outcome == coOk:
app.db.withTransaction:
if subject.get == nsCharacter: revealEncountered(app.db, id, actual)
else: revealEncounteredToken(app.db, id, actual)
for pid in app.encountered.keys.toSeq:
for eid in app.encountered[pid].keys.toSeq:
let e = app.encountered[pid][eid]
if (subject.get == nsCharacter and e.characterId == some(id)) or
(subject.get == nsToken and eid == id):
app.encountered[pid][eid] = e.revealed(actual)
# As `name.reveal` for every player who met the subject, live and persisted (#27, #30).
discard rewriteEncountered(app.db, app.encountered, subject.get, id, names, app.reveals)
if outcome == coNotFound:
ackErr(conn, env.reqId, CodeNotFound)
return
+9 -1
View File
@@ -242,7 +242,15 @@ proc patched*(t: TokenRec, patch: TokenPatch): TokenRec =
if patch.kind.isSome: result.kind = patch.kind.get
if patch.descriptiveName.isSome: result.descriptiveName = patch.descriptiveName.get
if patch.actualName.isSome: result.actualName = patch.actualName.get
if patch.characterId.isSome: result.characterId = patch.characterId.get
if patch.characterId.isSome:
result.characterId = patch.characterId.get
# A link is a name handover (8): a linked token carries no names of its own, because the
# character's names are the ones a client sees. The handler refuses a patch that supplies names
# *with* a link, so dropping the stored pair here is what makes `token.update {character_id}`
# able to link a plain token at all (#29). An unlink must supply both names (6.1).
if result.characterId.isSome:
result.descriptiveName = ""
result.actualName = ""
if patch.controller.isSome: result.owner = patch.controller.get
if patch.gmOnly.isSome: result.gmOnly = patch.gmOnly.get
if patch.flags.isSome: result.flags = patch.flags.get