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:
+45
-18
@@ -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
@@ -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
@@ -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
|
||||
|
||||
+140
-2
@@ -32,6 +32,11 @@ 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)
|
||||
@@ -150,6 +155,30 @@ suite "names and validation (6.5: 1..64 code points, trimmed, no control charact
|
||||
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
|
||||
@@ -267,6 +296,103 @@ suite "persistence (write-through, restart-identical)":
|
||||
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:
|
||||
@@ -280,13 +406,25 @@ suite "persistence (write-through, restart-identical)":
|
||||
writeEncountered(conn, p2.id, EncounteredEntry(entityId: "t1", characterId: some("char1"),
|
||||
descriptiveName: "a grumpy man",
|
||||
actualName: some("Lord Vex")))
|
||||
renameEncountered(conn, "char1", "a tall stranger", "Lady 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"
|
||||
revealEncountered(conn, "char1", "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()
|
||||
|
||||
@@ -396,6 +396,74 @@ test('character.update and character.remove: rename, in-use, and a token link th
|
||||
})
|
||||
})
|
||||
|
||||
test('token.update links a plain token to a character: the names are handed over (#29)', async () => {
|
||||
await withGmServer(async (s, gmKey) => {
|
||||
const gm = await gmConnect(s.origin, gmKey)
|
||||
const alice = await createPlayer(gm.ws)
|
||||
const a = await connectNamed(s.origin, alice.key, 'Alice')
|
||||
// Alice has sight on the wolf's square, so she meets it before it is linked.
|
||||
const eye = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'pc',
|
||||
pos: [350, 350], descriptive_name: 'Alice',
|
||||
actual_name: 'Alice', controller: alice.id,
|
||||
flags: { vision: true } })
|
||||
assert.equal(eye.ok, true, JSON.stringify(eye))
|
||||
const char = await gm.ws.request({ t: 'character.create',
|
||||
descriptive_name: 'a cloaked figure',
|
||||
actual_name: 'Lady Vex', owner: alice.id })
|
||||
assert.equal(char.ok, true, JSON.stringify(char))
|
||||
const wolf = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'npc',
|
||||
pos: [450, 450], descriptive_name: 'a wolf',
|
||||
actual_name: 'Fang' })
|
||||
assert.equal(wolf.ok, true, JSON.stringify(wolf))
|
||||
const met = await a.ws.waitFor(m => m.t === 'encountered' &&
|
||||
m.set.some(e => e.id === wolf.id))
|
||||
assert.equal(met.set.find(e => e.id === wolf.id).name, 'a wolf')
|
||||
|
||||
// Linking *and* supplying names is still the 6.1 `invalid`.
|
||||
const withNames = await gm.ws.request({ t: 'token.update', id: wolf.id,
|
||||
character_id: char.id,
|
||||
descriptive_name: 'a wolf',
|
||||
actual_name: 'Fang' })
|
||||
assert.equal(withNames.code, 'invalid')
|
||||
|
||||
// A bare link is `ok` and drops the token's own names: the character's names reach clients.
|
||||
const aFrom = a.ws.messages.length
|
||||
const link = await mutate(gm.ws, { t: 'token.update', id: wolf.id, character_id: char.id })
|
||||
assert.equal(link.ack.ok, true, JSON.stringify(link.ack))
|
||||
const gmTok = await link.wait(m => m.t === 'token' && m.id === wolf.id &&
|
||||
m.character_id === char.id)
|
||||
assert.equal(gmTok.name, 'a cloaked figure')
|
||||
assert.equal(gmTok.descriptive_name, undefined,
|
||||
'a linked token carries no names of its own (6.1)')
|
||||
assert.equal(gmTok.actual_name, undefined)
|
||||
// Alice owns the character, so its actual name is the one she sees.
|
||||
const aTok = await a.ws.waitFor((m, i) => i >= aFrom && m.t === 'token' && m.id === wolf.id)
|
||||
assert.equal(aTok.name, 'Lady Vex')
|
||||
assert.equal(aTok.character_id, char.id)
|
||||
// The snapshot follows the link too: her encountered entry is the character's name now.
|
||||
const relinked = await a.ws.waitFor((m, i) => i >= aFrom && m.t === 'encountered' &&
|
||||
m.set.some(e => e.id === wolf.id))
|
||||
assert.equal(relinked.set.find(e => e.id === wolf.id).name, 'Lady Vex')
|
||||
|
||||
// Unlinking without both names stays `invalid`; with both it restores the token's own names.
|
||||
assert.equal((await gm.ws.request({ t: 'token.update', id: wolf.id,
|
||||
character_id: null })).code, 'invalid')
|
||||
const unlink = await mutate(gm.ws, { t: 'token.update', id: wolf.id, character_id: null,
|
||||
descriptive_name: 'a wolf', actual_name: 'Fang' })
|
||||
assert.equal(unlink.ack.ok, true, JSON.stringify(unlink.ack))
|
||||
const plain = await unlink.wait(m => m.t === 'token' && m.id === wolf.id &&
|
||||
m.character_id === null)
|
||||
assert.equal(plain.name, 'a wolf')
|
||||
assert.equal(plain.descriptive_name, 'a wolf')
|
||||
assert.equal(plain.actual_name, 'Fang')
|
||||
// A linked token still cannot receive names of its own afterwards.
|
||||
assert.equal((await gm.ws.request({ t: 'token.update', id: wolf.id,
|
||||
character_id: char.id,
|
||||
actual_name: 'X' })).code, 'invalid')
|
||||
a.ws.close(); gm.ws.close()
|
||||
})
|
||||
})
|
||||
|
||||
test('encountered: a sighting is kept under the name the player knows, and survives everything',
|
||||
async () => {
|
||||
await withGmServer(async (s, gmKey) => {
|
||||
|
||||
@@ -298,6 +298,13 @@ export async function runLeak({ origin, gmKey, stateDir, transcript, keepOpen =
|
||||
if (ack.ok !== true) throw new Error(`token.create refused: ${JSON.stringify(ack)}`)
|
||||
ids.C1 = ack.id
|
||||
})
|
||||
// #27/#30: a second player meets the same token of the same character, so the transcript carries
|
||||
// two encountered lists whose names can be compared independently (leakcheck runs once per
|
||||
// subject). The later rename and reveals must reach this player's snapshot too, and a reveal to
|
||||
// the *other* player must not.
|
||||
await group('GM walks the other player into the room again', async () => {
|
||||
expectAck(await move(gm, ids.B, [650, 700]), true)
|
||||
})
|
||||
// One mutation per group (the driver's contract): the checker evaluates a group as one state, so
|
||||
// two prop writes in one group would compare an intermediate frame against the final truth.
|
||||
for (const [bucket, value] of [['public', 'noble'], ['owner', 4], ['gm', 'the duke']]) {
|
||||
@@ -338,6 +345,9 @@ export async function runLeak({ origin, gmKey, stateDir, transcript, keepOpen =
|
||||
const ack = await gm.request({ t: 'name.reveal_all', subject: 'token', id: ids.N2 })
|
||||
if (ack.ok !== true) throw new Error(`name.reveal_all refused: ${JSON.stringify(ack)}`)
|
||||
})
|
||||
await group('GM walks the other player out again', async () => {
|
||||
expectAck(await move(gm, ids.B, [420, 1500]), true)
|
||||
})
|
||||
await group('GM hides the character token (the encountered entry stays, greyed)', async () => {
|
||||
const ack = await gm.request({ t: 'token.update', id: ids.C1, gm_only: true })
|
||||
if (ack.ok !== true) throw new Error(`token.update refused: ${JSON.stringify(ack)}`)
|
||||
|
||||
+13
-5
@@ -20,6 +20,8 @@
|
||||
## GM_PROP the `gm` property bucket reached a player at all
|
||||
## STATUS_SOURCE a player frame carried the `source` of a status (5.5, 6.1 note 6)
|
||||
## ACTUAL_NAME an actual name the subject was never told reached it (8)
|
||||
## STALE_NAME an encountered entry names a subject something other than the name that player
|
||||
## knows (8): a stale snapshot the old "not the unrevealed actual" check let pass
|
||||
## CHAR_LIST another player's character record or encountered entry reached the subject
|
||||
## CONTROLLER_CHANGE a token changed controller in a group that asked for no such thing (8)
|
||||
## CHAR_OWNER_PROP a character's owner bucket reached a player who does not own it (8)
|
||||
@@ -487,11 +489,17 @@ proc main() =
|
||||
fail "CHAR_LIST", "encountered entry the subject never saw: " & id
|
||||
elif truth.tokens.hasKey(id):
|
||||
let (dname, aname) = subjectNames(truth, truth.tokens[id])
|
||||
# Only a *different* name leaks: a subject whose two names are the same string has no
|
||||
# secret to keep.
|
||||
if aname != dname and e["name"].getStr == aname and
|
||||
not subjectKnewActual(truth, truth.tokens[id], me):
|
||||
fail "ACTUAL_NAME", "encountered " & id & " carries an unrevealed actual name"
|
||||
let knows = subjectKnewActual(truth, truth.tokens[id], me)
|
||||
# The expected name, not merely "not the unrevealed actual": a stale snapshot that still
|
||||
# carries an old descriptive name is a bug the old check could not see (#30).
|
||||
let want = if knows: aname else: dname
|
||||
let got = e["name"].getStr
|
||||
if got != want:
|
||||
if aname != dname and got == aname:
|
||||
fail "ACTUAL_NAME", "encountered " & id & " carries an unrevealed actual name"
|
||||
else:
|
||||
fail "STALE_NAME", "encountered " & id & " has name " & got & " not " & want &
|
||||
" (group " & g.label & ")"
|
||||
if m.hasKey("del"):
|
||||
for d in m["del"]:
|
||||
if d.getStr notin encounterable:
|
||||
|
||||
+10
-3
@@ -22,6 +22,10 @@
|
||||
# az: in-use not enforced | b1: player.remove forgets the characters | b2: an encountered rename
|
||||
# overwrites a name the player never knew | b3: cprops carries the character owner bucket |
|
||||
# b4: a player is sent every character
|
||||
# #27/#29/#30: the per-player reveal scope, the link patch's name handover and the live
|
||||
# snapshot update. e1: a reveal rewrites every player's snapshot (the old subject-only
|
||||
# SQL) | e2: the encountered rewrite updates the DB but not memory (live list stale) |
|
||||
# e3: a link patch keeps the plain token's own names (every link attempt is invalid)
|
||||
# slice 9 (#24): the canonical tile URL and the "any explored cell allows" gate
|
||||
# c1: a tile is allowed without any explored cell | c2: every overlapping cell is required
|
||||
# c3: an out-of-grid coordinate is accepted | c4: a leading-zero coordinate is canonical
|
||||
@@ -139,7 +143,7 @@ run y "wall endpoints unchecked against the world bounds" server/world.nim 's/p\
|
||||
run z "door.set accepted on a plain wall" server/world.nim '/if sc.walls\[idx.get\].kind != wkDoor: return waNotDoor/d' "wrong kinds are their own"
|
||||
run z2 "persisted open state loaded inverted" server/world.nim 's/open: row\[6\] == "1",/open: row[6] == "0",/' "round-trip through a reload"
|
||||
# slice 5 (#20): the view rule, the egress diff and the explored set
|
||||
run aa "the egress ignores LOS, gm_only and ownership" server/views.nim 's/^ if not pv\.visibleTo(t, playerId): continue$/ if false: continue/' "$AA"
|
||||
run aa "the egress ignores LOS, gm_only and ownership" server/views.nim 's/^ if not pv\[\]\.visibleTo(t, playerId): continue$/ if false: continue/' "$AA"
|
||||
run ab "gm_only ignored by the view rule" server/vision.nim '/^ if t\.gmOnly: return false$/d' "$AB"
|
||||
run ac "a controlled token is not always visible" server/vision.nim '/^ if t\.owner == playerId: return true$/d' "$AC"
|
||||
run ad "no token_gone when a token leaves the view" server/views.nim 's/^ result\.add tokenGoneFrame(id)$/ discard/' "$AD"
|
||||
@@ -170,9 +174,12 @@ run ax "a rename tells a player an actual name it never knew" server/characters.
|
||||
run ay "a linked token may keep its own names" server/tokens.nim 's/ if t\.characterId\.isSome: t\.descriptiveName\.len == 0/ if false: t.descriptiveName.len == 0/' "a linked token carries no names"
|
||||
run az "in-use is not enforced" server/characters.nim 's/^ if t\.characterId\.isSome and t\.characterId\.get == characterId: inc result$/ discard/' "a character still figured by a token is in use"
|
||||
run b1 "player.remove forgets the characters" server/characters.nim 's/WHERE owner_player_id = ?", gmId, playerId)/WHERE owner_player_id = ? AND 0", gmId, playerId)/' "hands the player"
|
||||
run b2 "an encountered rename overwrites a secret" server/characters.nim 's/AND actual_name <> .."""/AND 1 = 1"""/' "a character rename follows the snapshots"
|
||||
run b2 "an encountered rename overwrites a secret" server/characters.nim 's/actualName: (if knows: some(n\.actual) else: none(string))/actualName: some(n.actual)/' "a character rename"
|
||||
run b3 "cprops carries the character owner bucket" server/views.nim 's/cpropsPublic: objectOf(if ch\.isSome and not ownsCharacter: ch\.get\.props\[pbPublic\]/cpropsPublic: objectOf(if ch.isSome and not ownsCharacter: ch.get.props[pbOwner]/' "cprops carries the character"
|
||||
run b4 "a player is sent every character" server/views.nim 's/ if c\.owner != playerId: continue/ if false: continue/' "a player gets only its own characters"
|
||||
run e1 "an encountered rewrite ignores what the player knows" server/characters.nim 's/let updated = e\.refreshed(n, knowsActual(/let updated = e.refreshed(n, true or knowsActual(/' "a link change moves the snapshot"
|
||||
run e2 "an encountered rewrite updates the DB only" server/characters.nim 's/^ enc\[pid\]\[e\.entityId\] = e$/ discard/' "a character rename rewrites the live snapshots"
|
||||
run e3 "a link patch keeps the token's own names" server/tokens.nim 's/^ if result\.characterId\.isSome:$/ if false:/' "linking through a patch hands the names over"
|
||||
# slice 9 (#24): the tile URL grammar and the access rule (server/tiles.nim)
|
||||
TILE_GATE="an unexplored tile is refused|a tile is allowed when any overlapping cell"
|
||||
TILE_ZERO="leading zero tile coordinates"
|
||||
@@ -186,7 +193,7 @@ run d3 "scene.set accepts a patch with no field" server/world.nim 's/^ if not a
|
||||
wait
|
||||
|
||||
rc=0; : > "$LOG"
|
||||
for id in control a b c d1 d2 d3 e f g h i j k l m n o p q r s t u v w x y z z2 aa ab ac ad ae af ag ah ai aj ak al am an ao ap aq ar as at au av aw ax ay az b1 b2 b3 b4 c1 c2 c3 c4; do
|
||||
for id in control a b c d1 d2 d3 e e1 e2 e3 f g h i j k l m n o p q r s t u v w x y z z2 aa ab ac ad ae af ag ah ai aj ak al am an ao ap aq ar as at au av aw ax ay az b1 b2 b3 b4 c1 c2 c3 c4; do
|
||||
[ -f "$T/$id/res" ] && cat "$T/$id/res" >> "$LOG"
|
||||
if [ -f "$T/$id/verdict" ]; then tee -a "$LOG" < "$T/$id/verdict"; [ "$(cat "$T/$id/rc")" = 0 ] || rc=1
|
||||
else echo "$id: NO RESULT (job killed?)" | tee -a "$LOG"; rc=1; fi
|
||||
|
||||
+194
-25
@@ -6,9 +6,17 @@
|
||||
// sighting in the encountered list, explored cells, players and their names), then compares what a
|
||||
// fresh GM connection and a fresh player connection receive as their full 6.3 resync before and
|
||||
// after the restart. SIGTERM and SIGKILL are both checked: every acked commit is durable (4.2).
|
||||
//
|
||||
// #27: three named players meet the same subjects, and the reveals are per player, so the restart
|
||||
// group also pins that the persisted `encountered` snapshot is the name *that* player knows. Before
|
||||
// the fix the reveal SQL had no player predicate: the non-revealed players saw the actual name only
|
||||
// after the restart. Each player's encountered list is compared before/after AND against the name
|
||||
// that player may know (from the GM truth), so a leak cannot hide behind two equally wrong snapshots.
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { createPlayer, namePlayer, sleep } from './lib.mjs'
|
||||
import { gmKeyOf, makeStateDir, openAs, startServer, stopServer } from './withserver.mjs'
|
||||
|
||||
@@ -25,11 +33,20 @@ async function buildWorld(origin, gmKey) {
|
||||
const gm = await gmConnect(origin, gmKey)
|
||||
const saved = {}
|
||||
try {
|
||||
// Players: a GM plus one named player with a key (its own CRUD path is key.* + player.setname).
|
||||
// Players: a GM plus three named players with keys (their CRUD path is key.* + player.setname).
|
||||
// Three, because the per-player reveal bug (#27) needs a second and a third encountered list to
|
||||
// be wrong: one player is revealed to, the others must keep the descriptive name across a
|
||||
// restart. Their tokens all stand west of the x=700 wall and see the same two subjects.
|
||||
const alice = await createPlayer(gm.ws)
|
||||
await namePlayer(origin, alice.key, 'Alice')
|
||||
saved.alice = alice
|
||||
// A second, still unnamed player: the GM roster carries it (`name:null`), players never see it.
|
||||
const bob = await createPlayer(gm.ws)
|
||||
await namePlayer(origin, bob.key, 'Bob')
|
||||
saved.bob = bob
|
||||
const carol = await createPlayer(gm.ws)
|
||||
await namePlayer(origin, carol.key, 'Carol')
|
||||
saved.carol = carol
|
||||
// A fourth, still unnamed player: the GM roster carries it (`name:null`), players never see it.
|
||||
await createPlayer(gm.ws)
|
||||
// A wall and a door; the door is opened (door.set is its own write path).
|
||||
const wall = await gm.ws.request({ t: 'wall.add', scene: gm.sceneId, a: [700, 0],
|
||||
@@ -49,6 +66,17 @@ async function buildWorld(origin, gmKey) {
|
||||
props: { public: { aura: 'cold' }, owner: { hp: 5 },
|
||||
gm: { secret: 1 } } })
|
||||
assert.equal(pc.ok, true, JSON.stringify(pc))
|
||||
// Bob and Carol: sight of their own, at the same subjects. They never own a character, so only a
|
||||
// reveal can tell them an actual name.
|
||||
for (const [p, pos] of [[bob, [250, 500]], [carol, [300, 650]]]) {
|
||||
const sight = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'pc',
|
||||
pos, descriptive_name: 'sight', actual_name: 'Sight',
|
||||
controller: p.id, flags: { vision: true },
|
||||
radius: 35 })
|
||||
assert.equal(sight.ok, true, JSON.stringify(sight))
|
||||
if (p === bob) saved.ids = { ...(saved.ids ?? {}), bobTok: sight.id }
|
||||
else saved.ids = { ...(saved.ids ?? {}), carolTok: sight.id }
|
||||
}
|
||||
// A monster right next to it: Alice meets it (one encountered entry, grey after it moves away).
|
||||
const monster = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'npc',
|
||||
pos: [500, 400], descriptive_name: 'a goblin',
|
||||
@@ -77,13 +105,17 @@ async function buildWorld(origin, gmKey) {
|
||||
assert.equal((await gm.ws.request({ t: 'status.set', id: monster.id,
|
||||
status: 'stuck' })).ok, true)
|
||||
assert.equal((await gm.ws.request({ t: 'token.resize', id: monster.id, radius: 28 })).ok, true)
|
||||
// A reveal for one player, reveal-all for a plain token, one encountered entry removed later.
|
||||
// Per-player reveals: the character's actual name to Alice only, the monster's to Bob only.
|
||||
// Alice must then keep "a goblin" and Bob "a cloaked figure" - before the fix both flipped to
|
||||
// the actual name after a restart (#27). reveal-all for a plain token stays all-players.
|
||||
assert.equal((await gm.ws.request({ t: 'name.reveal', subject: 'character',
|
||||
id: character.id, player: alice.id })).ok, true)
|
||||
assert.equal((await gm.ws.request({ t: 'name.reveal', subject: 'token',
|
||||
id: monster.id, player: bob.id })).ok, true)
|
||||
assert.equal((await gm.ws.request({ t: 'name.reveal_all', subject: 'token',
|
||||
id: pc.id })).ok, true)
|
||||
saved.ids = { pc: pc.id, monster: monster.id, character: character.id, linked: linked.id,
|
||||
wall: wall.id, door: door.id }
|
||||
saved.ids = { ...saved.ids, pc: pc.id, monster: monster.id, character: character.id,
|
||||
linked: linked.id, wall: wall.id, door: door.id }
|
||||
gm.ws.close()
|
||||
} finally {
|
||||
try { gm.ws.close() } catch {}
|
||||
@@ -150,29 +182,50 @@ async function snapshot(origin, key, expected, isGm) {
|
||||
}
|
||||
}
|
||||
|
||||
// The full before/after comparison: one fresh GM connection and one fresh Alice connection.
|
||||
async function compareAcross(origin, gmKey, aliceKey, ids, expected) {
|
||||
// The name each player may know for a subject, from the fixture's own truth: the character reveal
|
||||
// went to Alice only, the monster's to Bob only, and the pc's reveal_all covers everyone.
|
||||
function expectedEncounteredName(who, ids) {
|
||||
if (who === 'alice') return { [ids.monster]: 'a goblin', [ids.linked]: 'Lady Vex',
|
||||
[ids.pc]: 'Wanderer' }
|
||||
return { [ids.monster]: who === 'bob' ? 'Grib' : 'a goblin',
|
||||
[ids.linked]: 'a cloaked figure', [ids.pc]: 'Wanderer' }
|
||||
}
|
||||
|
||||
// The full before/after comparison: one fresh GM connection and one fresh connection per player.
|
||||
async function compareAcross(origin, gmKey, players, ids, expected) {
|
||||
const beforeGm = await snapshot(origin, gmKey, expected, true)
|
||||
const beforeAlice = await snapshot(origin, aliceKey, expected, false)
|
||||
const before = { gm: beforeGm }
|
||||
for (const [who, p] of Object.entries(players)) {
|
||||
// Only the character's owner is sent a `character` record (6.1).
|
||||
before[who] = await snapshot(origin, p.key,
|
||||
{ ...expected, characters: who === 'alice' ? 1 : 0 }, false)
|
||||
}
|
||||
// The CRUD inventory is not empty: a restart test over an empty world would prove nothing.
|
||||
assert.ok(beforeGm.walls.walls.length >= 2, 'the wall and the door are there')
|
||||
assert.equal(beforeGm.walls.walls.find(w => w.id === ids.door).open, true, 'the door is open')
|
||||
assert.ok(beforeGm.tokens.length >= 3, 'plain, monster, player and linked tokens are there')
|
||||
assert.ok(beforeGm.tokens.length >= 5, 'plain, monster, player, linked and sight tokens are there')
|
||||
assert.ok(beforeGm.characters.length >= 1, 'the character is there')
|
||||
assert.equal(beforeGm.characters.find(c => c.id === ids.character).props.public.banner, 'red')
|
||||
assert.equal(beforeGm.tokens.find(t => t.id === ids.monster).radius, 28,
|
||||
'the resize survived')
|
||||
assert.ok(beforeGm.tokens.find(t => t.id === ids.monster).statuses
|
||||
.some(s => s.status === 'stuck' && s.source === 'GM'), 'the GM status survived')
|
||||
assert.equal(beforeAlice.encountered.set.find(e => e.id === ids.monster)?.name, 'a goblin')
|
||||
assert.ok(beforeAlice.vision.polys.length >= 1, 'the player has sight')
|
||||
assert.ok(beforeAlice.explored.rle.length >= 1, 'the player explored something')
|
||||
return { beforeGm, beforeAlice }
|
||||
// #27: each player's encountered list holds the name *that* player knows, live.
|
||||
for (const [who, snap] of Object.entries(before)) {
|
||||
if (who === 'gm') continue
|
||||
for (const [id, name] of Object.entries(expectedEncounteredName(who, ids))) {
|
||||
assert.equal(snap.encountered.set.find(e => e.id === id)?.name, name,
|
||||
`${who}'s encountered entry for ${id} live`)
|
||||
}
|
||||
assert.ok(snap.vision.polys.length >= 1, `${who} has sight`)
|
||||
assert.ok(snap.explored.rle.length >= 1, `${who} explored something`)
|
||||
}
|
||||
return before
|
||||
}
|
||||
|
||||
async function restartAndCompare(stateDir, gmKey, aliceKey, ids, expected, hard) {
|
||||
async function restartAndCompare(stateDir, gmKey, players, ids, expected, hard) {
|
||||
let s = await startServer({ stateDir })
|
||||
const before = await compareAcross(s.origin, gmKey, aliceKey, ids, expected)
|
||||
const before = await compareAcross(s.origin, gmKey, players, ids, expected)
|
||||
if (hard) {
|
||||
// Every ack is sent after COMMIT (4.2), so a hard kill cannot lose an acked mutation.
|
||||
s.child.kill('SIGKILL')
|
||||
@@ -186,47 +239,163 @@ async function restartAndCompare(stateDir, gmKey, aliceKey, ids, expected, hard)
|
||||
s = await startServer({ stateDir })
|
||||
try {
|
||||
const afterGm = await snapshot(s.origin, gmKey, expected, true)
|
||||
const afterAlice = await snapshot(s.origin, aliceKey, expected, false)
|
||||
assert.deepEqual(afterGm, before.beforeGm, 'the GM resync after the restart is identical')
|
||||
assert.deepEqual(afterAlice, before.beforeAlice,
|
||||
'the player resync after the restart is identical')
|
||||
assert.deepEqual(afterGm, before.gm, 'the GM resync after the restart is identical')
|
||||
for (const [who, p] of Object.entries(players)) {
|
||||
const after = await snapshot(s.origin, p.key,
|
||||
{ ...expected, characters: who === 'alice' ? 1 : 0 }, false)
|
||||
assert.deepEqual(after, before[who],
|
||||
`${who}'s resync after the restart is identical`)
|
||||
// ... and the absolute truth, so two equally wrong snapshots cannot pass (#27).
|
||||
for (const [id, name] of Object.entries(expectedEncounteredName(who, ids))) {
|
||||
assert.equal(after.encountered.set.find(e => e.id === id)?.name, name,
|
||||
`${who}'s encountered entry for ${id} after the restart`)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await stopServer(s)
|
||||
}
|
||||
}
|
||||
|
||||
const EXPECTED = { tokens: 3, characters: 1 }
|
||||
// The persisted snapshot is where #27 lived: assert directly that the reveal changed exactly one
|
||||
// player's row for the revealed subject, and nobody else's.
|
||||
function dbEncounteredNames(stateDir, entityId) {
|
||||
const r = spawnSync('sqlite3', [path.join(stateDir, 'state.db'),
|
||||
`SELECT player_id || '=' || IFNULL(actual_name, '') FROM encountered ` +
|
||||
`WHERE entity_id = '${entityId}' ORDER BY player_id`], { encoding: 'utf8' })
|
||||
assert.equal(r.status, 0, r.stderr)
|
||||
return Object.fromEntries(r.stdout.trim().split('\n').filter(Boolean)
|
||||
.map(line => { const [id, name] = line.split('='); return [id, name] }))
|
||||
}
|
||||
|
||||
test('restart: full state, all CRUD, before and after SIGTERM', async () => {
|
||||
const EXPECTED = { tokens: 5, characters: 1 }
|
||||
|
||||
async function restartGroup(hard) {
|
||||
const stateDir = makeStateDir()
|
||||
const gmKey = gmKeyOf(stateDir)
|
||||
const players = {}
|
||||
let s = await startServer({ stateDir })
|
||||
let saved
|
||||
try {
|
||||
saved = await buildWorld(s.origin, gmKey)
|
||||
players.alice = saved.alice
|
||||
players.bob = saved.bob
|
||||
players.carol = saved.carol
|
||||
// #27, asserted against the rows while the server is still up: the monster's actual name was
|
||||
// revealed to Bob only, so exactly one of the three rows carries it.
|
||||
const monsterRows = dbEncounteredNames(stateDir, saved.ids.monster)
|
||||
assert.equal(monsterRows[String(saved.bob.id)], 'Grib')
|
||||
assert.equal(monsterRows[String(saved.alice.id)], '')
|
||||
assert.equal(monsterRows[String(saved.carol.id)], '',
|
||||
'the reveal to Bob did not write Alice\'s or Carol\'s row (#27)')
|
||||
const linkedRows = dbEncounteredNames(stateDir, saved.ids.linked)
|
||||
assert.equal(linkedRows[String(saved.alice.id)], 'Lady Vex')
|
||||
assert.equal(linkedRows[String(saved.bob.id)], '')
|
||||
assert.equal(linkedRows[String(saved.carol.id)], '',
|
||||
'the reveal to Alice did not write Bob\'s or Carol\'s row (#27)')
|
||||
} finally {
|
||||
await stopServer(s)
|
||||
}
|
||||
try {
|
||||
await restartAndCompare(stateDir, gmKey, saved.alice.key, saved.ids, EXPECTED, false)
|
||||
await restartAndCompare(stateDir, gmKey, players, saved.ids, EXPECTED, hard)
|
||||
} finally {
|
||||
fs.rmSync(stateDir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
test('restart: full state, all CRUD, before and after SIGTERM', async () => {
|
||||
await restartGroup(false)
|
||||
})
|
||||
|
||||
test('restart: full state, all CRUD, before and after SIGKILL', async () => {
|
||||
await restartGroup(true)
|
||||
})
|
||||
|
||||
// #30: a rename must reach the live encountered list, not just the row a restart loads. The wire
|
||||
// and the DB are asserted to agree before and after a restart, for a plain token and a character,
|
||||
// and for a player who was never told the actual name.
|
||||
test('restart: a mid-session rename reaches the live encountered list (#30)', async () => {
|
||||
const stateDir = makeStateDir()
|
||||
const gmKey = gmKeyOf(stateDir)
|
||||
let s = await startServer({ stateDir })
|
||||
let saved
|
||||
let ids = {}
|
||||
let alice, bob
|
||||
try {
|
||||
saved = await buildWorld(s.origin, gmKey)
|
||||
const gm = await gmConnect(s.origin, gmKey)
|
||||
alice = await createPlayer(gm.ws)
|
||||
await namePlayer(s.origin, alice.key, 'Alice')
|
||||
bob = await createPlayer(gm.ws)
|
||||
await namePlayer(s.origin, bob.key, 'Bob')
|
||||
for (const [p, pos] of [[alice, [350, 350]], [bob, [300, 650]]]) {
|
||||
const t = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'pc', pos,
|
||||
descriptive_name: 'sight', actual_name: 'Sight',
|
||||
controller: p.id, flags: { vision: true } })
|
||||
assert.equal(t.ok, true, JSON.stringify(t))
|
||||
}
|
||||
const wolf = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'npc',
|
||||
pos: [450, 450], descriptive_name: 'a wolf',
|
||||
actual_name: 'Fang' })
|
||||
const char = await gm.ws.request({ t: 'character.create',
|
||||
descriptive_name: 'a cloaked figure',
|
||||
actual_name: 'Lady Vex', owner: alice.id })
|
||||
const linked = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'npc',
|
||||
pos: [500, 400], character_id: char.id })
|
||||
assert.ok(wolf.ok && char.ok && linked.ok)
|
||||
ids = { wolf: wolf.id, char: char.id, linked: linked.id }
|
||||
|
||||
// Both players are connected while the rename happens, so the live frame is what is checked.
|
||||
const a = await openAs(s.origin, alice.key)
|
||||
await a.ws.waitText('hello')
|
||||
const b = await openAs(s.origin, bob.key)
|
||||
await b.ws.waitText('hello')
|
||||
await a.ws.waitFor(m => m.t === 'encountered' &&
|
||||
m.set.some(e => e.id === wolf.id && e.name === 'a wolf'))
|
||||
await b.ws.waitFor(m => m.t === 'encountered' &&
|
||||
m.set.some(e => e.id === wolf.id && e.name === 'a wolf'))
|
||||
|
||||
let from = a.ws.messages.length
|
||||
const w = await gm.ws.request({ t: 'token.update', id: wolf.id,
|
||||
descriptive_name: 'a huge wolf' })
|
||||
assert.equal(w.ok, true, JSON.stringify(w))
|
||||
const renamed = await a.ws.waitFor((m, i) => i >= from && m.t === 'encountered' &&
|
||||
m.set.some(e => e.id === wolf.id))
|
||||
assert.equal(renamed.set.find(e => e.id === wolf.id).name, 'a huge wolf',
|
||||
'the live list follows a plain-token rename (#30)')
|
||||
await b.ws.waitFor(m => m.t === 'encountered' &&
|
||||
m.set.some(e => e.id === wolf.id && e.name === 'a huge wolf'))
|
||||
|
||||
const bFrom = b.ws.messages.length
|
||||
const c = await gm.ws.request({ t: 'character.update', id: char.id,
|
||||
descriptive_name: 'a tall stranger' })
|
||||
assert.equal(c.ok, true, JSON.stringify(c))
|
||||
// Alice owns the character, so she sees the actual name and the descriptive rename is invisible
|
||||
// to her; Bob (never told) must see the new descriptive name on the wire, with no restart.
|
||||
const moved = await b.ws.waitFor((m, i) => i >= bFrom && m.t === 'encountered' &&
|
||||
m.set.some(e => e.id === linked.id))
|
||||
assert.equal(moved.set.find(e => e.id === linked.id).name, 'a tall stranger',
|
||||
'the live list follows a character rename for a player who was not told (#30)')
|
||||
assert.equal(renamed.set.find(e => e.id === wolf.id).name, 'a huge wolf')
|
||||
a.ws.close(); b.ws.close(); gm.ws.close()
|
||||
} finally {
|
||||
await stopServer(s)
|
||||
}
|
||||
try {
|
||||
await restartAndCompare(stateDir, gmKey, saved.alice.key, saved.ids, EXPECTED, true)
|
||||
s = await startServer({ stateDir })
|
||||
for (const [key, who] of [[alice.key, 'alice'], [bob.key, 'bob']]) {
|
||||
const c = await openAs(s.origin, key)
|
||||
try {
|
||||
await c.ws.waitFor(m => m.t === 'encountered' && m.full === true)
|
||||
const e = c.ws.messages.filter(m => m.t === 'encountered').pop()
|
||||
assert.equal(e.set.find(x => x.id === ids.wolf)?.name, 'a huge wolf',
|
||||
`${who}: the plain-token rename survives the restart`)
|
||||
assert.equal(e.set.find(x => x.id === ids.linked)?.name,
|
||||
who === 'alice' ? 'Lady Vex' : 'a tall stranger',
|
||||
`${who}: the character rename survives the restart, per player`)
|
||||
} finally {
|
||||
c.ws.close()
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await stopServer(s)
|
||||
fs.rmSync(stateDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user