Files
SirStone 8e045b0ac8 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.
2026-11-15 14:26:07 +01:00

361 lines
18 KiB
Nim

## Characters, name reveals and the per-player encountered list (DESIGN 3.1, 4.1, 6.1, 8; M3
## slice 8, issue #23).
##
## A character is its own record, separate from the tokens that figure it (FIXED #14): one owner - a
## real player id, and the GM owns through its own player id - two names, `reveal_all` and the three
## property buckets. `TokenRec.characterId` is the link; a token linked to a character carries no
## names of its own, because the character's names are the ones a client sees. A token's *controller*
## is set on the token and is independent of the character's owner: `character.reassign` never
## touches it (6.1, DESIGN 8).
##
## Names [FIXED #14, DESIGN 8]: every character and every plain token has a `descriptive_name` (what
## a player sees) and an `actual_name` (what the GM knows). A player sees the actual name only when
## the subject is a character they own, or the GM revealed it to them, or `reveal_all` is set. That
## one rule lives in `knowsActual`/`visibleName` and nothing else in the server re-derives it: the
## token frame, the character frame and the encountered entry all call it.
##
## Reveals are stored per `(player, subject)` in `name_reveal`, where the subject is a character id or
## a plain token id. Token and character ids share one alphabet *and one uniqueness namespace*
## (`freshId` is called with both lists), so a subject id is never ambiguous. A reveal is never
## revoked and is not dropped when the character changes owner (8); `reveal_all` is a flag on the
## subject, so a player who joins later is covered without a row per player.
##
## Encountered [FIXED #14, DESIGN 8]: per player, one entry per token that player ever saw, holding
## the *snapshot* of the name that player knows (`actual_name` NULL = not known). Entries are never
## removed automatically - not on token removal, not on a `gm_only` flip, not on a scene change -
## only by `encountered.remove`. The entry is added the moment the token enters that player's view
## (main.recordEncounters); a rename updates the snapshot; a reveal fills in the actual name.
##
## 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, sequtils, sets, strutils, tables, times]
import db_connector/db_sqlite
import db
import props, text, tokens, world
type
CharacterRec* = object
id*: string
owner*: int ## a real player id, the GM's included; never GmControlled
descriptiveName*: string
actualName*: string
revealAll*: bool
props*: Props ## three buckets, never nil
CharacterOutcome* = enum
coOk
coInvalid ## a name or a prop value is off: `invalid`
coNotFound ## no such character (or owner player): `not-found`
coInUse ## a token still figures it: `in-use` (6.5)
NameSubject* = enum
nsCharacter = "character"
nsToken = "token"
Reveals* = object
## `(playerId, subjectId)` pairs, i.e. one row of `name_reveal` each. A set because every
## question asked of it is a membership test; the per-subject player list is a bounded scan.
pairs*: HashSet[(int, string)]
EncounteredEntry* = object
entityId*: string
characterId*: Option[string] ## none = the entry belongs to a plain token
descriptiveName*: string
actualName*: Option[string] ## none = this player was never told the actual name
Encountered* = Table[int, Table[string, EncounteredEntry]]
## playerId -> entityId -> the entry. Per player by construction, so no egress path can hand one
## player another player's list by accident.
SubjectNames* = object
## What the name rule needs about one subject (a character, or a plain token).
id*: string ## the reveal subject id: the character id when linked, else the token id
descriptive*: string
actual*: string
revealAll*: bool
owner*: int ## the player who always knows the actual name; 0 = nobody
characterId*: Option[string] ## set when the subject is character-backed
const
MaxOwnerlessName* = 64
## Characters follow the token name rule of 6.5: 1..64 code points (text.validText).
# ---------------------------------------------------------------------------------------------------
# The name rule (DESIGN 8). One copy, used by every frame builder.
proc knowsActual*(isOwner, revealAll, revealed: bool): bool =
## A player is told the actual name of a subject when they own it, when the GM revealed it to
## everyone, or when the GM revealed it to them (8; reveals are never revoked).
isOwner or revealAll or revealed
proc visibleName*(descriptive, actual: string, knowsActual: bool): string =
## The one name a recipient sees for a subject (6.1 `token.name`).
if knowsActual: actual else: descriptive
proc isRevealed*(r: Reveals, player: int, subject: string): bool =
(player, subject) in r.pairs
proc revealedPlayers*(r: Reveals, subject: string): seq[int] =
## The `revealed:[player ids]` list of a GM frame, ascending so the frame is deterministic.
for (player, subj) in r.pairs:
if subj == subject: result.add player
result.sort()
proc withReveal*(r: var Reveals, player: int, subject: string) =
r.pairs.incl (player, subject)
proc withoutRevealsOf*(r: var Reveals, player: int) =
## `player.remove`: that player's reveal rows go with it (6.1).
var doomed: seq[(int, string)]
for pair in r.pairs:
if pair[0] == player: doomed.add pair
for pair in doomed: r.pairs.excl pair
# ---------------------------------------------------------------------------------------------------
# Lookups and the subject view
proc characterIndex*(chars: openArray[CharacterRec], id: string): Option[int] =
for i, c in chars:
if c.id == id: return some(i)
proc characterById*(chars: openArray[CharacterRec], id: string): Option[CharacterRec] =
let i = characterIndex(chars, id)
if i.isSome: return some(chars[i.get])
proc validCharacterName*(s: string): bool = validText(s, MaxOwnerlessName)
proc parseSubject*(raw: string): Option[NameSubject] =
for s in NameSubject:
if $s == raw: return some(s)
proc normalize*(c: CharacterRec): CharacterRec =
result = c
result.props = props.normalize(result.props)
proc validCharacter*(c: CharacterRec): bool =
validCharacterName(c.descriptiveName) and validCharacterName(c.actualName) and
c.owner > 0 and props.valid(c.props)
proc subjectNamesOf*(c: CharacterRec): SubjectNames =
## A character as the name rule sees it: its owner always knows the actual name.
SubjectNames(id: c.id, descriptive: c.descriptiveName, actual: c.actualName,
revealAll: c.revealAll, owner: c.owner, characterId: some(c.id))
proc subjectNamesOf*(t: TokenRec, chars: openArray[CharacterRec]): SubjectNames =
## A token as the name rule sees it: a linked token borrows the character's names (so one reveal
## covers every token of that character), a plain token uses its own and owns nobody's trust.
if t.characterId.isSome:
let c = characterById(chars, t.characterId.get)
if c.isSome: return subjectNamesOf(c.get)
# A dangling link cannot exist (the FK and `in-use` forbid it); fall back to "no name" rather
# than crash a live connection.
return SubjectNames(id: t.characterId.get, descriptive: "", actual: "",
owner: 0, characterId: t.characterId)
SubjectNames(id: t.id, descriptive: t.descriptiveName, actual: t.actualName,
revealAll: t.revealAll, owner: 0, characterId: none(string))
proc nameFor*(n: SubjectNames, player: int, reveals: Reveals): string =
## The name `player` sees for this subject (6.1 `token.name`, `encountered.name`).
visibleName(n.descriptive, n.actual, knowsActual(n.owner == player and n.owner > 0,
n.revealAll, reveals.isRevealed(player, n.id)))
# ---------------------------------------------------------------------------------------------------
# Encountered entries (DESIGN 8)
proc entryName*(e: EncounteredEntry): string =
## The name this player knows: the actual one once it was revealed, else the descriptive one.
if e.actualName.isSome: e.actualName.get else: e.descriptiveName
proc newEntry*(entityId: string, n: SubjectNames, knowsActual: bool): EncounteredEntry =
## The snapshot a first sighting records: the names as they are now, and whether the player was
## already allowed to know the actual one (a later reveal fills it in).
EncounteredEntry(entityId: entityId, characterId: n.characterId,
descriptiveName: n.descriptive,
actualName: (if knowsActual: some(n.actual) else: none(string)))
proc renamed*(e: EncounteredEntry, descriptive, actual: string): EncounteredEntry =
## After `character.update` or a plain-token rename: the snapshot follows the subject. A player who
## was never told the actual name stays not-told.
result = e
result.descriptiveName = descriptive
if e.actualName.isSome: result.actualName = some(actual)
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)
proc insertRow(db: DbConn, c: CharacterRec) =
db.exec(sql"""INSERT INTO character (id, owner_player_id, descriptive_name, actual_name,
reveal_all, props_public, props_owner, props_gm, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",
c.id, c.owner, c.descriptiveName, c.actualName, (if c.revealAll: 1 else: 0),
$c.props[pbPublic], $c.props[pbOwner], $c.props[pbGm],
now().utc.format("yyyy-MM-dd'T'HH:mm:ss'Z'"))
proc replaceRow(db: DbConn, c: CharacterRec) =
db.exec(sql"""UPDATE character SET owner_player_id = ?, descriptive_name = ?, actual_name = ?,
reveal_all = ?, props_public = ?, props_owner = ?,
props_gm = ? WHERE id = ?""",
c.owner, c.descriptiveName, c.actualName, (if c.revealAll: 1 else: 0),
$c.props[pbPublic], $c.props[pbOwner], $c.props[pbGm], c.id)
proc addCharacter*(db: DbConn, candidate: CharacterRec, takenIds: openArray[string]):
tuple[outcome: CharacterOutcome, character: CharacterRec] =
## `character.create`: validates, assigns a fresh id from the shared token/character namespace and
## persists. The caller appends the record to memory after the transaction (4.2 step 6).
var stored = normalize(candidate)
if not validCharacter(stored): return (coInvalid, stored)
stored.id = freshId(takenIds)
authoringTransaction(db):
insertRow(db, stored)
(coOk, stored)
proc storeCharacter*(db: DbConn, candidate: CharacterRec): CharacterOutcome =
## `character.update`, `character.reassign`, `name.reveal_all`, `prop.*` on a character: one full
## replacement of the row (GM authoring, FULL), so one change is one transaction.
let stored = normalize(candidate)
if not validCharacter(stored): return coInvalid
authoringTransaction(db):
replaceRow(db, stored)
coOk
proc removeCharacter*(db: DbConn, id: string): bool =
var removed = false
authoringTransaction(db):
removed = db.execAffectedRows(sql"DELETE FROM character WHERE id = ?", id) > 0
removed
proc tokensLinkedTo*(tokens: openArray[TokenRec], characterId: string): int =
## `character.remove` is refused with `in-use` while any token still figures the character (6.5).
for t in tokens:
if t.characterId.isSome and t.characterId.get == characterId: inc result
proc transferToGm*(db: DbConn, playerId, gmId: int) =
## `player.remove` (DESIGN 3.2): that player's characters pass to the GM. Runs before the player
## DELETE, because `character.owner_player_id` refuses to dangle (no cascade on purpose).
db.exec(sql"UPDATE character SET owner_player_id = ? WHERE owner_player_id = ?", gmId, playerId)
proc addReveal*(db: DbConn, player: int, subject: string) =
## One `name_reveal` row; a repeated reveal is a no-op (`ok`, and nothing changes).
db.exec(sql"""INSERT OR IGNORE INTO name_reveal (player_id, subject_id, created_at)
VALUES (?, ?, ?)""",
player, subject, now().utc.format("yyyy-MM-dd'T'HH:mm:ss'Z'"))
proc deleteRevealsOf*(db: DbConn, player: int) =
db.exec(sql"DELETE FROM name_reveal WHERE player_id = ?", player)
proc deleteRevealsFor*(db: DbConn, subject: string) =
## `character.remove`: the reveal rows of a subject that no longer exists. (Rows of a *token* that
## was removed are left alone: the token id is never reused, so they can never be read again, and
## keeping them costs one row.)
db.exec(sql"DELETE FROM name_reveal WHERE subject_id = ?", subject)
proc writeEncountered*(db: DbConn, player: int, e: EncounteredEntry) =
## One `encountered` row per (player, token), upserted: the snapshot is a small value, not a log.
db.exec(sql"""INSERT INTO encountered (player_id, entity_id, character_id, descriptive_name,
actual_name, created_at)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT (player_id, entity_id) DO UPDATE SET
character_id = excluded.character_id,
descriptive_name = excluded.descriptive_name,
actual_name = excluded.actual_name""",
player, e.entityId,
(if e.characterId.isSome: e.characterId.get else: ""),
e.descriptiveName,
(if e.actualName.isSome: e.actualName.get else: ""),
now().utc.format("yyyy-MM-dd'T'HH:mm:ss'Z'"))
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 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)
# ---------------------------------------------------------------------------------------------------
# Loading (4.4 startup: load everything into memory once)
proc parseObject(s: string): JsonNode =
try:
result = parseJson(s)
except CatchableError:
result = newJObject()
if result.isNil or result.kind != JObject: result = newJObject()
proc rowToCharacter(row: Row): CharacterRec =
var p = newProps()
p[pbPublic] = parseObject(row[5])
p[pbOwner] = parseObject(row[6])
p[pbGm] = parseObject(row[7])
CharacterRec(id: row[0], owner: parseInt(row[1]), descriptiveName: row[2], actualName: row[3],
revealAll: row[4] == "1", props: p)
proc loadCharacters*(db: DbConn): seq[CharacterRec] =
## Every character, in creation order (rowid), which is the order egress walks them.
for row in db.getAllRows(sql"""
SELECT id, owner_player_id, descriptive_name, actual_name, reveal_all,
props_public, props_owner, props_gm
FROM character ORDER BY rowid"""):
result.add rowToCharacter(row)
proc loadReveals*(db: DbConn): Reveals =
for row in db.getAllRows(sql"SELECT player_id, subject_id FROM name_reveal"):
result.pairs.incl (parseInt(row[0]), row[1])
proc loadEncountered*(db: DbConn): Encountered =
## Every entry, in creation order: the order a player's `encountered full` list arrives in.
for row in db.getAllRows(sql"""
SELECT player_id, entity_id, character_id, descriptive_name, actual_name
FROM encountered ORDER BY rowid"""):
let player = parseInt(row[0])
result.mgetOrPut(player, initTable[string, EncounteredEntry]())[row[1]] =
EncounteredEntry(entityId: row[1],
characterId: (if row[2].len == 0: none(string) else: some(row[2])),
descriptiveName: row[3],
actualName: (if row[4].len == 0: none(string) else: some(row[4])))