Files
FFF_vtt_frozen/tests/tcharacters.nim
T
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

457 lines
21 KiB
Nim

## Characters, the name rule, reveals and the encountered snapshot (#23, DESIGN 3.1, 4.4, 6.1, 8).
## Pure/unit level: the records, the name rule, the reveal set and the write-through persistence
## (including the reload a restart performs). The wire behaviour lives in tools/characters.test.mjs
## and the egress filtering in tests/tviews.nim.
import std/[json, options, os, sets, strutils, tables, unittest]
import db_connector/db_sqlite
import auth, characters, db, props, tokens, world
var tmpCount = 0
proc tmpDir(): string =
inc tmpCount
result = getTempDir() / "fffchars-" & $getCurrentProcessId() & "-" & $tmpCount
removeDir(result)
createDir(result)
proc freshDb(): tuple[db: DbConn, dir: string] =
let d = tmpDir()
let conn = openDatabase(d / "state.db")
discard migrate(conn)
(conn, d)
proc ownedBy(conn: DbConn): int =
## A real owner id: the persisted characters have an FK to `player`, so a unit test needs one.
if gmPlayer(conn).isNone: discard ensureGm(conn)
parseInt(conn.getValue(sql"SELECT id FROM player ORDER BY id LIMIT 1"))
proc aChar(owner = 1, id = ""): CharacterRec =
CharacterRec(id: id, owner: owner, descriptiveName: "a grumpy man", actualName: "Lord Vex",
props: newProps())
proc plainToken(id = "tok1", owner = 0): TokenRec =
TokenRec(id: id, scene: 1, kind: "npc", descriptiveName: "a wolf", actualName: "Fang",
owner: owner, flags: %*{"vision": true}, props: newProps())
proc sceneOf(): SceneRec =
SceneRec(id: 1, name: "Scene", w: 4096, h: 4096, tileSize: 32, cell: 32, gridSize: 0,
visionRadiusDefault: 400, tokenRadiusDefault: 20, artVersion: 1, nextWallId: 1,
extra: newJObject(), walls: @[])
suite "the name rule (DESIGN 8: one copy, used by every frame)":
test "an owner, a reveal_all and a per-player reveal each expose the actual name":
check knowsActual(isOwner = true, revealAll = false, revealed = false)
check knowsActual(isOwner = false, revealAll = true, revealed = false)
check knowsActual(isOwner = false, revealAll = false, revealed = true)
check not knowsActual(isOwner = false, revealAll = false, revealed = false)
test "visibleName picks the name the recipient knows":
check visibleName("a grumpy man", "Lord Vex", false) == "a grumpy man"
check visibleName("a grumpy man", "Lord Vex", true) == "Lord Vex"
test "a character owner sees the actual name without any reveal row":
var reveals: Reveals
let c = aChar(owner = 2)
check subjectNamesOf(c).nameFor(2, reveals) == "Lord Vex"
check subjectNamesOf(c).nameFor(3, reveals) == "a grumpy man"
reveals.withReveal(3, c.id)
check subjectNamesOf(c).nameFor(3, reveals) == "Lord Vex"
test "a linked token borrows the character's names, so one reveal covers all of them":
var reveals: Reveals
let c = aChar(owner = 2, id = "char1")
var t = plainToken()
t.characterId = some("char1")
t.descriptiveName = ""
t.actualName = ""
check subjectNamesOf(t, @[c]).nameFor(3, reveals) == "a grumpy man"
check subjectNamesOf(t, @[c]).id == "char1" # the reveal key is the character, not the token
reveals.withReveal(3, "char1")
check subjectNamesOf(t, @[c]).nameFor(3, reveals) == "Lord Vex"
test "a plain token is nobody's character: only a reveal or reveal_all shows the actual name":
var reveals: Reveals
var t = plainToken(owner = 2) # its controller gets no free actual name
check subjectNamesOf(t, @[]).nameFor(2, reveals) == "a wolf"
t.revealAll = true
check subjectNamesOf(t, @[]).nameFor(3, reveals) == "Fang"
test "revealedPlayers lists the reveal rows of one subject, sorted":
var reveals: Reveals
for p in [4, 2, 3]: reveals.withReveal(p, "char1")
reveals.withReveal(2, "other")
check revealedPlayers(reveals, "char1") == @[2, 3, 4]
check revealedPlayers(reveals, "nothing") == newSeq[int]()
check reveals.isRevealed(3, "char1")
check not reveals.isRevealed(5, "char1")
test "player.remove takes that player's reveal rows with it":
var reveals: Reveals
reveals.withReveal(2, "a")
reveals.withReveal(3, "b")
reveals.withoutRevealsOf(2)
check not reveals.isRevealed(2, "a")
check reveals.isRevealed(3, "b")
test "one reveal row per (player, subject): a repeated reveal changes nothing":
var reveals: Reveals
reveals.withReveal(2, "a")
reveals.withReveal(2, "a")
check reveals.pairs.len == 1
suite "encountered snapshot (DESIGN 8: the name the player knows, frozen)":
test "a first sighting records what the player knows right now":
let c = aChar(owner = 2, id = "char1")
let names = subjectNamesOf(c)
let unknown = newEntry("t1", names, knowsActual = false)
check unknown.entryName == "a grumpy man"
check unknown.actualName.isNone
check unknown.characterId.get == "char1"
let known = newEntry("t1", names, knowsActual = true)
check known.entryName == "Lord Vex"
test "a rename follows the subject, and a player who was never told keeps not knowing":
let c = aChar(id = "char1")
var e = newEntry("t1", subjectNamesOf(c), knowsActual = false)
e = e.renamed("a tall stranger", "Lady Vex")
check e.entryName == "a tall stranger"
check e.actualName.isNone
var known = newEntry("t2", subjectNamesOf(c), knowsActual = true)
known = known.renamed("a tall stranger", "Lady Vex")
check known.entryName == "Lady Vex"
test "a reveal fills in the actual name and leaves the rest alone":
var e = newEntry("t1", subjectNamesOf(aChar(id = "char1")), knowsActual = false)
e = e.revealed("Lord Vex")
check e.entryName == "Lord Vex"
check e.descriptiveName == "a grumpy man"
suite "names and validation (6.5: 1..64 code points, trimmed, no control characters)":
test "a character needs two valid names and an owner":
let c = aChar()
check validCharacter(c)
check validCharacterName("Lord Vex")
check not validCharacterName("")
check not validCharacterName(" padded")
var bad = c
bad.actualName = ""
check not validCharacter(bad)
bad = c
bad.owner = 0
check not validCharacter(bad)
bad = c
bad.descriptiveName = repeat("x", 65)
check not validCharacter(bad)
test "a linked token carries no names of its own (they belong to the character)":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let sc = loadScene(conn).get
var t = plainToken()
t.characterId = some("char1")
check not validToken(sc, t) # still has plain-token names
t.descriptiveName = ""
t.actualName = ""
check validToken(sc, t)
test "linking through a patch hands the names over (#29)":
# `patched` is the one place a link patch is applied, so a plain token's own names go away with
# it: validation would otherwise fail every link attempt, and only unlinking would work.
let sc = sceneOf()
var t = plainToken()
check validToken(sc, t)
let linked = t.patched(TokenPatch(characterId: some(some("char1"))))
check linked.characterId == some("char1")
check linked.descriptiveName.len == 0
check linked.actualName.len == 0
check validToken(sc, linked)
# unlinking needs both names on the patch and restores them
let unlinked = linked.patched(TokenPatch(characterId: some(none(string)),
descriptiveName: some("a wolf"),
actualName: some("Fang")))
check unlinked.characterId.isNone
check unlinked.descriptiveName == "a wolf"
check unlinked.actualName == "Fang"
check validToken(sc, unlinked)
# a name patch on a plain token still applies
let renamed = t.patched(TokenPatch(descriptiveName: some("a huge wolf")))
check renamed.descriptiveName == "a huge wolf"
check renamed.actualName == "Fang"
test "parseSubject accepts exactly the two wire words":
check parseSubject("character").get == nsCharacter
check parseSubject("token").get == nsToken
check parseSubject("Character").isNone
check parseSubject("").isNone
suite "persistence (write-through, restart-identical)":
test "create assigns an id from the shared namespace, stores every column, reloads identically":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let gm = ensureGm(conn)
let gmId = parseInt(conn.getValue(sql"SELECT id FROM player WHERE role = 'gm'"))
var c = aChar(owner = gmId)
c.props[pbPublic] = %*{"class": "fighter"}
c.props[pbOwner] = %*{"hp": 12}
c.props[pbGm] = %*{"secret": true}
let (outcome, stored) = addCharacter(conn, c, @[])
check outcome == coOk
check gm.key.len > 0
check stored.id.len == TokenIdLength
let reloaded = loadCharacters(conn)
check reloaded.len == 1
check reloaded[0].id == stored.id
check reloaded[0].owner == gmId
check reloaded[0].descriptiveName == "a grumpy man"
check reloaded[0].actualName == "Lord Vex"
check not reloaded[0].revealAll
check reloaded[0].props[pbOwner]["hp"].getInt == 12
check reloaded[0].props[pbGm]["secret"].getBool
test "the id namespace is shared with tokens: taken ids are never handed out again":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
# an exhaustive "taken" list is impossible; check the call site contract instead: the ids of
# every token AND every character are passed to freshId, so the two can never collide.
let (firstOutcome, first) = addCharacter(conn, aChar(owner = ownedBy(conn)), @[])
let (secondOutcome, second) = addCharacter(conn, aChar(owner = ownedBy(conn)), @[first.id])
check firstOutcome == coOk
check secondOutcome == coOk
check second.id != first.id
test "reveal_all and the props round-trip through a full replacement":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let (_, stored) = addCharacter(conn, aChar(owner = ownedBy(conn)), @[])
var changed = stored
changed.revealAll = true
changed.actualName = "Lady Vex"
changed.props[pbPublic] = %*{"aura": "cold"}
check storeCharacter(conn, changed) == coOk
let r = loadCharacters(conn)[0]
check r.revealAll
check r.actualName == "Lady Vex"
check r.props[pbPublic]["aura"].getStr == "cold"
var invalid = changed
invalid.descriptiveName = ""
check storeCharacter(conn, invalid) == coInvalid
check loadCharacters(conn)[0].descriptiveName == "a grumpy man"
test "remove deletes the row; a second remove reports nothing":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let (_, stored) = addCharacter(conn, aChar(owner = ownedBy(conn)), @[])
check removeCharacter(conn, stored.id)
check loadCharacters(conn).len == 0
check not removeCharacter(conn, stored.id)
test "a reveal row survives a reload and a repeated reveal":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let created = createPlayerWithKey(conn)
addReveal(conn, created.id, "char1")
addReveal(conn, created.id, "char1")
let r = loadReveals(conn)
check r.pairs.len == 1
check r.isRevealed(created.id, "char1")
deleteRevealsOf(conn, created.id)
check loadReveals(conn).pairs.len == 0
test "encountered rows survive a reload, keep their NULL actual name, and replace per entry":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let created = createPlayerWithKey(conn)
writeEncountered(conn, created.id,
EncounteredEntry(entityId: "t1", characterId: some("char1"),
descriptiveName: "a grumpy man", actualName: none(string)))
writeEncountered(conn, created.id,
EncounteredEntry(entityId: "t2", characterId: none(string),
descriptiveName: "a wolf", actualName: some("Fang")))
var loaded = loadEncountered(conn)
check loaded[created.id].len == 2
check loaded[created.id]["t1"].actualName.isNone
check loaded[created.id]["t1"].characterId.get == "char1"
check loaded[created.id]["t2"].entryName == "Fang"
# an upsert replaces the snapshot of that (player, token)
writeEncountered(conn, created.id,
EncounteredEntry(entityId: "t1", characterId: some("char1"),
descriptiveName: "a tall stranger", actualName: some("Lord Vex")))
loaded = loadEncountered(conn)
check loaded[created.id].len == 2
check loaded[created.id]["t1"].entryName == "Lord Vex"
check deleteEncountered(conn, created.id, "t1")
check not deleteEncountered(conn, created.id, "t1")
check loadEncountered(conn)[created.id].len == 1
test "a character rename rewrites the live snapshots and the rows alike (#30, #27)":
# The bug: `character.update` rewrote SQLite only, so the live encountered frame kept the old
# name until a restart. One helper now rewrites both stores from the 8 name rule.
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let p1 = createPlayerWithKey(conn)
let p2 = createPlayerWithKey(conn)
let p3 = createPlayerWithKey(conn)
var enc = loadEncountered(conn)
for pid in [p1.id, p2.id, p3.id]:
enc.mgetOrPut(pid, initTable[string, EncounteredEntry]())["t1"] =
EncounteredEntry(entityId: "t1", characterId: some("char1"),
descriptiveName: "a grumpy man",
actualName: (if pid == p1.id: some("Lord Vex") else: none(string)))
writeEncountered(conn, pid, enc[pid]["t1"])
var reveals: Reveals
reveals.withReveal(p1.id, "char1") # p1 was told; p2 and p3 were not
let changed = rewriteEncountered(conn, enc, nsCharacter, "char1",
SubjectNames(id: "char1", descriptive: "a tall stranger",
actual: "Lady Vex", revealAll: false,
owner: 0, characterId: some("char1")),
reveals)
# every player's entry follows, and the memory equals a reload (no restart cliff)
check changed.len == 3
let loaded = loadEncountered(conn)
for pid in [p1.id, p2.id, p3.id]:
check enc[pid]["t1"].descriptiveName == "a tall stranger"
check loaded[pid]["t1"] == enc[pid]["t1"]
check enc[p1.id]["t1"].entryName == "Lady Vex"
check enc[p2.id]["t1"].actualName.isNone # never told, still not told
check enc[p2.id]["t1"].entryName == "a tall stranger"
test "a reveal to one player rewrites exactly that player's row (#27)":
# The leak: the reveal SQL had no `player_id` predicate, so every player who met the subject got
# the actual name persisted and saw it after a restart.
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let p1 = createPlayerWithKey(conn)
let p2 = createPlayerWithKey(conn)
let p3 = createPlayerWithKey(conn)
var enc: Encountered
for pid in [p1.id, p2.id, p3.id]:
enc.mgetOrPut(pid, initTable[string, EncounteredEntry]())["t1"] =
EncounteredEntry(entityId: "t1", characterId: none(string),
descriptiveName: "a wolf", actualName: none(string))
writeEncountered(conn, pid, enc[pid]["t1"])
var reveals: Reveals
reveals.withReveal(p2.id, "t1")
let changed = rewriteEncountered(conn, enc, nsToken, "t1",
SubjectNames(id: "t1", descriptive: "a wolf", actual: "Fang",
revealAll: false, owner: 0,
characterId: none(string)),
reveals, onlyPlayer = p2.id)
check changed == @[(p2.id, "t1")]
let loaded = loadEncountered(conn)
check loaded[p1.id]["t1"].actualName.isNone
check loaded[p3.id]["t1"].actualName.isNone
check loaded[p2.id]["t1"].entryName == "Fang"
check loadEncountered(conn)[p1.id]["t1"].entryName == "a wolf" # the other players' rows
# and memory agrees with the rows for every player
for pid in [p1.id, p2.id, p3.id]: check enc[pid]["t1"] == loaded[pid]["t1"]
test "a link change moves the snapshot to the character's names, link and knowledge (#29)":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let p1 = createPlayerWithKey(conn)
var enc: Encountered
enc.mgetOrPut(p1.id, initTable[string, EncounteredEntry]())["t1"] =
EncounteredEntry(entityId: "t1", characterId: none(string), descriptiveName: "a wolf",
actualName: some("Fang"))
writeEncountered(conn, p1.id, enc[p1.id]["t1"])
var reveals: Reveals
# the plain token is linked to a character p1 has never been told about: the token-level actual
# name must not survive the handover
check rewriteEncountered(conn, enc, nsToken, "t1",
SubjectNames(id: "char1", descriptive: "a cloaked figure",
actual: "Lady Vex", revealAll: false, owner: 0,
characterId: some("char1")), reveals) ==
@[(p1.id, "t1")]
check enc[p1.id]["t1"].characterId == some("char1")
check enc[p1.id]["t1"].entryName == "a cloaked figure"
check loadEncountered(conn)[p1.id]["t1"] == enc[p1.id]["t1"]
# unlinking moves it back and drops the character link
check rewriteEncountered(conn, enc, nsToken, "t1",
SubjectNames(id: "t1", descriptive: "a wolf", actual: "Fang",
revealAll: false, owner: 0,
characterId: none(string)),
reveals).len == 1
check enc[p1.id]["t1"].characterId.isNone
check enc[p1.id]["t1"].entryName == "a wolf"
test "a character rename follows the snapshots of everyone who met it":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let p1 = createPlayerWithKey(conn)
let p2 = createPlayerWithKey(conn)
writeEncountered(conn, p1.id, EncounteredEntry(entityId: "t1", characterId: some("char1"),
descriptiveName: "a grumpy man",
actualName: none(string)))
writeEncountered(conn, p2.id, EncounteredEntry(entityId: "t1", characterId: some("char1"),
descriptiveName: "a grumpy man",
actualName: some("Lord Vex")))
var enc = loadEncountered(conn)
var reveals: Reveals
reveals.withReveal(p2.id, "char1")
discard rewriteEncountered(conn, enc, nsCharacter, "char1",
SubjectNames(id: "char1", descriptive: "a tall stranger",
actual: "Lady Vex", revealAll: false, owner: 0,
characterId: some("char1")), reveals)
let loaded = loadEncountered(conn)
check loaded[p1.id]["t1"].entryName == "a tall stranger" # still not told the actual name
check loaded[p1.id]["t1"].actualName.isNone
check loaded[p2.id]["t1"].entryName == "Lady Vex"
# a later all-players reveal fills in exactly the ones who were not told
reveals.withReveal(p1.id, "char1")
discard rewriteEncountered(conn, enc, nsCharacter, "char1",
SubjectNames(id: "char1", descriptive: "a tall stranger",
actual: "Lady Vex", revealAll: false, owner: 0,
characterId: some("char1")), reveals)
check loadEncountered(conn)[p1.id]["t1"].entryName == "Lady Vex"
check enc[p1.id]["t1"].entryName == "Lady Vex"
test "player.remove hands the player's characters to the GM (DESIGN 3.2)":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let gmId = int(insertID(conn, sql"INSERT INTO player (name, role, colour, created_at) VALUES ('GM','gm','#000','x')"))
let created = createPlayerWithKey(conn)
let (_, stored) = addCharacter(conn, aChar(owner = created.id), @[])
transferToGm(conn, created.id, gmId)
check loadCharacters(conn)[0].owner == gmId
check loadCharacters(conn)[0].id == stored.id
test "a character still figured by a token is in use (6.5)":
let (conn, d) = freshDb()
defer:
close(conn)
removeDir(d)
let sc = loadScene(conn).get
let (_, stored) = addCharacter(conn, aChar(owner = ownedBy(conn)), @[])
var t = plainToken()
t.characterId = some(stored.id)
t.descriptiveName = ""
t.actualName = ""
let (outcome, added) = addToken(conn, sc, t, @[])
check outcome == toOk
check tokensLinkedTo(loadTokens(conn), stored.id) == 1
check tokensLinkedTo(loadTokens(conn), "other") == 0
check added.id.len == TokenIdLength