server: token records and the entity migration step (#20)
Migration step 4 ("tokens") creates the entity table: the token id, scene, kind,
both names, position, nullable radius/owner/vision_radius, gm_only and flags. A
NULL owner is GM-controlled, so player.remove hands that player's tokens to the GM
through the FK; radius, props and character_id stay out until slices 7-8.
server/tokens.nim holds the record, the 6.1 field rules (12 CSPRNG characters from
a 64-symbol alphabet, trimmed names, kind, positive vision_radius), the write-through
persistence (FULL for GM authoring, NORMAL for a move) and the loader. db_connector
quotes every argument, so the three nullable columns are emitted as numeric literals
while text still goes through ? arguments.
This commit is contained in:
@@ -10,6 +10,9 @@
|
||||
## Step 3 ("world", M3 slice 4 / #19) creates `scene` and `wall` and seeds the single v1 scene
|
||||
## (DESIGN 4.4, 8; Q3 FIXED: exactly one scene). Wall ids are per scene and come from
|
||||
## `scene.next_wall_id`, which never decreases (#3 FIXED).
|
||||
## Step 4 ("tokens", M3 slice 5 / #20) creates `entity` for the map figures (DESIGN 4.4, 8). The
|
||||
## character link, the name-reveal flags and the three property buckets are slices 7-8 (#22, #23) and
|
||||
## are not columns yet; `entity_status` and `explored_chunk` arrive with slice 7 and slice 6.
|
||||
## One connection, used under the server's global lock (4.3); this module does no locking itself.
|
||||
import std/[strutils, times]
|
||||
import db_connector/db_sqlite
|
||||
@@ -90,6 +93,22 @@ CREATE TABLE wall (
|
||||
INSERT INTO scene (id, name, w, h, tile_size, cell, grid_size, vision_radius_default,
|
||||
token_radius_default, art_version, active, next_wall_id, extra)
|
||||
VALUES (1, 'Scene', 4096, 4096, 32, 32, 0, 400, 20, 1, 1, 1, '{}')"""]),
|
||||
Migration(version: 4, name: "tokens", stmts: @["""
|
||||
CREATE TABLE entity (
|
||||
id TEXT PRIMARY KEY, -- 12 random chars from [A-Za-z0-9_-] (#3, DESIGN 8)
|
||||
scene_id INTEGER NOT NULL REFERENCES scene(id) ON DELETE CASCADE,
|
||||
kind TEXT NOT NULL, -- free string (pc, npc, item...); GM-only on the wire
|
||||
descriptive_name TEXT NOT NULL, -- the name players see until the GM reveals (8)
|
||||
actual_name TEXT NOT NULL,
|
||||
x REAL NOT NULL,
|
||||
y REAL NOT NULL,
|
||||
radius REAL, -- NULL = scene token_radius_default (#4, slice 7)
|
||||
owner_player_id INTEGER REFERENCES player(id) ON DELETE SET NULL, -- NULL = GM-controlled
|
||||
gm_only INTEGER NOT NULL DEFAULT 0 CHECK (gm_only IN (0, 1)),
|
||||
vision_radius REAL, -- NULL = scene vision_radius_default (Q7)
|
||||
flags TEXT NOT NULL DEFAULT '{}', -- JSON object; the `vision` flag lives here (8)
|
||||
created_at TEXT NOT NULL
|
||||
)"""]),
|
||||
]
|
||||
LatestVersion* = migrations[^1].version
|
||||
## Derived, so adding a step cannot leave it stale.
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
## Tokens: the map figures (DESIGN 3.1, 4.1, 4.4, 6.1, 8; M3 slice 5, issue #20). The wire and the
|
||||
## client say "token"; the DB table is `entity` (4.4's schema sketch), because the model is the FFF
|
||||
## seam of section 9. In-memory authoritative state, SQLite write-through: rows are read once at
|
||||
## startup (`loadTokens`) and never queried at runtime for reads.
|
||||
##
|
||||
## Ids (DESIGN 8, FIXED #3): random opaque 12 characters from `[A-Za-z0-9_-]`, from the OS CSPRNG,
|
||||
## unique game-wide (not per scene) and collision-checked on create. Counted ids would leak hidden
|
||||
## tokens through the gaps of the numbers a player does see.
|
||||
##
|
||||
## Scope of this slice (issue #20): plain tokens only. The character link, the name-reveal machinery
|
||||
## and the three property buckets are slices 7-8 (#22, #23), and the per-token size is #4's
|
||||
## `token.resize` (slice 7): a token's effective radius is always the scene's `token_radius_default`
|
||||
## here, so a `radius` field on the wire intents is refused `invalid` rather than silently dropped.
|
||||
##
|
||||
## Owner (`entity.owner_player_id`) is the token *controller* (DESIGN 8: independent of any character
|
||||
## owner). `GmControlled` (0) is SQL NULL; player ids start at 1. A controller that is the GM's own
|
||||
## player id is stored as GM-controlled, so "the GM controls it" has one representation in memory and
|
||||
## on the wire (`controller: null`).
|
||||
##
|
||||
## Persistence order (4.2 step 6): the row is written first and memory is updated only after the
|
||||
## transaction, so a failed write leaves memory and DB identical. GM authoring (create/update/remove)
|
||||
## runs with `synchronous=FULL` (Q12); a move - player or GM drag - runs with `NORMAL`, like explored
|
||||
## cells: a position is not authored content. This module does no locking: the caller holds the
|
||||
## server's global lock (4.3).
|
||||
import std/[json, options, strutils, times, unicode]
|
||||
import db_connector/db_sqlite
|
||||
import crypto, geometry, world
|
||||
import std/math except round
|
||||
|
||||
type
|
||||
TokenRec* = object
|
||||
id*: string
|
||||
scene*: int
|
||||
kind*: string ## free string (pc, npc, item...); GM-only on the wire (6.1 leak note 1)
|
||||
descriptiveName*: string
|
||||
actualName*: string
|
||||
pos*: Vec
|
||||
radius*: Option[float] ## px; none = the scene default. Slice 7 (#4) fills this.
|
||||
owner*: int ## controller: player id, GmControlled = the GM
|
||||
gmOnly*: bool
|
||||
visionRadius*: Option[float] ## px; none = the scene default (Q7, the 5.5 step cap)
|
||||
flags*: JsonNode ## JObject, never nil; the `vision` flag lives here (DESIGN 8)
|
||||
prev*: Vec ## position before the most recent move/push (door-push side, 5.5)
|
||||
hasPrev*: bool
|
||||
|
||||
TokenOutcome* = enum
|
||||
toOk
|
||||
toInvalid ## field/geometry semantics: `invalid`
|
||||
toNotFound ## no such token (or controller player): `not-found`
|
||||
|
||||
TokenPatch* = object
|
||||
## The `token.update` fields this slice can honour (6.1); none = keep the stored value.
|
||||
kind*: Option[string]
|
||||
descriptiveName*: Option[string]
|
||||
actualName*: Option[string]
|
||||
controller*: Option[int] ## GmControlled = GM
|
||||
gmOnly*: Option[bool]
|
||||
flags*: Option[JsonNode]
|
||||
visionRadius*: Option[Option[float]]
|
||||
|
||||
const
|
||||
TokenIdLength* = 12
|
||||
TokenIdAlphabet* = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-"
|
||||
## 64 symbols = 6 bits per character, 72 bits per id (DESIGN 8).
|
||||
MaxNameLen* = 64
|
||||
## DESIGN 6.5: character and plain-token names are 1 to 64 code points.
|
||||
MaxKindLen* = 32
|
||||
GmControlled* = 0
|
||||
## TokenRec.owner value for "no controller" (SQL NULL). Player ids are >= 1 (auth.nim).
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------
|
||||
# Field parsing and validation (DESIGN 6.1 field notes, 6.5)
|
||||
|
||||
proc hasControlChar(s: string): bool =
|
||||
for r in s.runes:
|
||||
if r.int < 0x20 or r.int == 0x7f: return true
|
||||
|
||||
proc validText*(s: string, maxLen: int): bool =
|
||||
## Trimmed, 1..maxLen code points, no control characters (DESIGN 6.5). NFC normalisation and the
|
||||
## per-player uniqueness rules arrive with the name machinery of slice 8 (#23).
|
||||
s.len > 0 and s == s.strip and s.runeLen in 1 .. maxLen and not hasControlChar(s)
|
||||
|
||||
proc validName*(s: string): bool = validText(s, MaxNameLen)
|
||||
|
||||
proc validKind*(s: string): bool = validText(s, MaxKindLen)
|
||||
|
||||
proc parseVisionRadius*(node: JsonNode): Option[Option[float]] =
|
||||
## `vision_radius`: a positive finite number, or null/absent (= the scene default).
|
||||
## `some(none(float))` = explicitly cleared; `some(some(r))` = set; none = present but invalid.
|
||||
if node.isNil or node.kind == JNull: return some(none(float))
|
||||
var f: float
|
||||
case node.kind
|
||||
of JInt: f = float(node.getInt)
|
||||
of JFloat: f = node.getFloat
|
||||
else: return none(Option[float])
|
||||
if classify(f) in {fcNan, fcInf, fcNegInf} or f <= 0: return none(Option[float])
|
||||
some(some(f))
|
||||
|
||||
proc newTokenId*(): string =
|
||||
## 12 CSPRNG characters from a 64-symbol alphabet (uniform: 256 = 4 x 64, no rejection needed).
|
||||
result = newStringOfCap(TokenIdLength)
|
||||
while result.len < TokenIdLength:
|
||||
for b in randomBytes(TokenIdLength * 2):
|
||||
if result.len == TokenIdLength: break
|
||||
result.add TokenIdAlphabet[int(b) and 0x3f]
|
||||
|
||||
proc freshId*(taken: openArray[string]): string =
|
||||
## An id that collides with no token in `taken` (DESIGN 8: the server checks on create).
|
||||
while true:
|
||||
result = newTokenId()
|
||||
var clash = false
|
||||
for id in taken:
|
||||
if id == result:
|
||||
clash = true
|
||||
break
|
||||
if not clash: return
|
||||
|
||||
proc normalize*(t: TokenRec): TokenRec =
|
||||
## Stored-token invariants: `flags` is an object, and a controller never becomes a negative id.
|
||||
result = t
|
||||
if result.flags.isNil or result.flags.kind != JObject: result.flags = newJObject()
|
||||
if result.owner < 0: result.owner = GmControlled
|
||||
|
||||
proc effectiveRadius*(sc: SceneRec, t: TokenRec): float =
|
||||
## DESIGN 5.6/#4: the entity radius if set, else the scene's `token_radius_default`.
|
||||
if t.radius.isSome: t.radius.get else: sc.tokenRadiusDefault
|
||||
|
||||
proc hasVision*(t: TokenRec): bool =
|
||||
## Q7: the `vision` flag (DESIGN 8), carried in `flags`. Only these tokens get a polygon (4.1).
|
||||
t.flags.kind == JObject and t.flags.hasKey("vision") and t.flags["vision"].kind == JBool and
|
||||
t.flags["vision"].getBool
|
||||
|
||||
proc visionRange*(sc: SceneRec, t: TokenRec): float =
|
||||
## The vision range and the player step cap (5.5): the token's own radius when it has vision and
|
||||
## sets one, else the scene default.
|
||||
if t.hasVision and t.visionRadius.isSome and t.visionRadius.get > 0: t.visionRadius.get
|
||||
else: sc.visionRadiusDefault
|
||||
|
||||
proc inBounds(sc: SceneRec, p: Vec): bool =
|
||||
p.x >= 0 and p.y >= 0 and p.x <= sc.w and p.y <= sc.h # written so NaN fails
|
||||
|
||||
proc validPlacement*(sc: SceneRec, pos: Vec): bool = inBounds(sc, pos)
|
||||
|
||||
proc validToken*(sc: SceneRec, t: TokenRec): bool =
|
||||
validName(t.descriptiveName) and validName(t.actualName) and validKind(t.kind) and
|
||||
validPlacement(sc, t.pos)
|
||||
|
||||
proc patched*(t: TokenRec, patch: TokenPatch): TokenRec =
|
||||
result = t
|
||||
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.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
|
||||
if patch.visionRadius.isSome: result.visionRadius = patch.visionRadius.get
|
||||
result = normalize(result)
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------
|
||||
# Persistence (write-through). db_connector quotes every argument as text, so a SQL NULL cannot ride
|
||||
# an argument: the three nullable columns are emitted as literals built from numbers only (never from
|
||||
# user text), and every string value still goes through a `?` argument.
|
||||
|
||||
proc sqlLit(v: Option[float]): string =
|
||||
if v.isSome: $v.get else: "NULL"
|
||||
|
||||
proc sqlLitOwner(owner: int): string =
|
||||
if owner == GmControlled: "NULL" else: $owner
|
||||
|
||||
proc insertRow(db: DbConn, t: TokenRec) =
|
||||
db.exec(sql("INSERT INTO entity (id, scene_id, kind, descriptive_name, actual_name, x, y, radius," &
|
||||
" owner_player_id, gm_only, vision_radius, flags, created_at) VALUES (" &
|
||||
"?, ?, ?, ?, ?, ?, ?, " & sqlLit(t.radius) & ", " & sqlLitOwner(t.owner) & ", ?, " &
|
||||
sqlLit(t.visionRadius) & ", ?, ?)"),
|
||||
t.id, t.scene, t.kind, t.descriptiveName, t.actualName, $t.pos.x, $t.pos.y,
|
||||
(if t.gmOnly: 1 else: 0), $t.flags,
|
||||
now().utc.format("yyyy-MM-dd'T'HH:mm:ss'Z'"))
|
||||
|
||||
proc replaceRow(db: DbConn, t: TokenRec) =
|
||||
db.exec(sql("UPDATE entity SET kind = ?, descriptive_name = ?, actual_name = ?, x = ?, y = ?," &
|
||||
" radius = " & sqlLit(t.radius) & ", owner_player_id = " & sqlLitOwner(t.owner) &
|
||||
", gm_only = ?, vision_radius = " & sqlLit(t.visionRadius) & ", flags = ?" &
|
||||
" WHERE id = ?"),
|
||||
t.kind, t.descriptiveName, t.actualName, $t.pos.x, $t.pos.y,
|
||||
(if t.gmOnly: 1 else: 0), $t.flags, t.id)
|
||||
|
||||
proc addToken*(db: DbConn, sc: SceneRec, candidate: TokenRec, takenIds: openArray[string]):
|
||||
tuple[outcome: TokenOutcome, token: TokenRec] =
|
||||
## `token.create`: validates, assigns a fresh id, persists. The caller appends the returned record
|
||||
## to the in-memory list after the transaction (4.2).
|
||||
var stored = normalize(candidate)
|
||||
stored.scene = sc.id
|
||||
if not validToken(sc, stored): return (toInvalid, stored)
|
||||
stored.id = freshId(takenIds)
|
||||
authoringTransaction(db):
|
||||
insertRow(db, stored)
|
||||
(toOk, stored)
|
||||
|
||||
proc storeToken*(db: DbConn, sc: SceneRec, candidate: TokenRec): TokenOutcome =
|
||||
## `token.update`: full replacement of the patched row (GM authoring, FULL).
|
||||
if not validToken(sc, candidate): return toInvalid
|
||||
var stored = normalize(candidate)
|
||||
authoringTransaction(db):
|
||||
replaceRow(db, stored)
|
||||
toOk
|
||||
|
||||
proc writePosition*(db: DbConn, t: TokenRec): bool =
|
||||
## One UPSERT of x,y (DESIGN 4.4). NORMAL durability: a position is not authored content (Q12).
|
||||
db.execAffectedRows(sql"UPDATE entity SET x = ?, y = ? WHERE id = ?",
|
||||
$t.pos.x, $t.pos.y, t.id) > 0
|
||||
|
||||
proc removeToken*(db: DbConn, id: string): bool =
|
||||
var removed = false
|
||||
authoringTransaction(db):
|
||||
removed = db.execAffectedRows(sql"DELETE FROM entity WHERE id = ?", id) > 0
|
||||
removed
|
||||
|
||||
proc clearOwnership*(db: DbConn, playerId: int) =
|
||||
## player.remove (DESIGN 3.2): that player's controlled tokens pass to the GM. The FK's ON DELETE
|
||||
## SET NULL does the same on the DELETE; this keeps an in-memory transfer explicit.
|
||||
db.exec(sql"UPDATE entity SET owner_player_id = NULL WHERE owner_player_id = ?", playerId)
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------
|
||||
# Loading (4.4 startup: load everything into memory once)
|
||||
|
||||
proc optFloat(s: string): Option[float] =
|
||||
if s.len == 0: none(float) else: some(parseFloat(s))
|
||||
|
||||
proc rowToToken(row: Row): TokenRec =
|
||||
var flags: JsonNode
|
||||
try:
|
||||
flags = parseJson(row[11])
|
||||
except CatchableError:
|
||||
flags = newJObject()
|
||||
TokenRec(id: row[0], scene: parseInt(row[1]), kind: row[2],
|
||||
descriptiveName: row[3], actualName: row[4],
|
||||
pos: (parseFloat(row[5]), parseFloat(row[6])),
|
||||
radius: optFloat(row[7]),
|
||||
owner: (if row[8].len == 0: GmControlled else: parseInt(row[8])),
|
||||
gmOnly: row[9] == "1",
|
||||
visionRadius: optFloat(row[10]), flags: flags)
|
||||
|
||||
proc loadTokens*(db: DbConn, sceneId = DefaultSceneId): seq[TokenRec] =
|
||||
## Every token of the scene, in creation order (rowid), which is the order egress walks.
|
||||
for row in db.getAllRows(sql"""
|
||||
SELECT id, scene_id, kind, descriptive_name, actual_name, x, y, radius, owner_player_id,
|
||||
gm_only, vision_radius, flags
|
||||
FROM entity WHERE scene_id = ? ORDER BY rowid""", sceneId):
|
||||
result.add rowToToken(row)
|
||||
|
||||
proc tokenIndex*(tokens: openArray[TokenRec], id: string): Option[int] =
|
||||
for i, t in tokens:
|
||||
if t.id == id: return some(i)
|
||||
|
||||
proc tokenById*(tokens: openArray[TokenRec], id: string): Option[TokenRec] =
|
||||
let i = tokenIndex(tokens, id)
|
||||
if i.isSome: return some(tokens[i.get])
|
||||
+1
-1
@@ -153,7 +153,7 @@ proc patched*(w: WallRec, patch: WallPatch): WallRec =
|
||||
proc flagsText(node: JsonNode): string =
|
||||
if node.isNil: "{}" else: $node
|
||||
|
||||
template authoringTransaction(db: DbConn, body: untyped) =
|
||||
template authoringTransaction*(db: DbConn, body: untyped) =
|
||||
## GM authoring durability (Q12): `synchronous=FULL` for this transaction, `NORMAL` again
|
||||
## afterwards, whether the body succeeded or raised. `PRAGMA synchronous` cannot change inside a
|
||||
## transaction, so it brackets BEGIN/COMMIT; a failing body rolls back completely.
|
||||
|
||||
+12
-7
@@ -38,15 +38,17 @@ suite "migrate":
|
||||
check migrate(db) == LatestVersion
|
||||
check LatestVersion == migrations[^1].version
|
||||
check schemaVersion(db) == LatestVersion
|
||||
check LatestVersion == 3
|
||||
check LatestVersion == 4
|
||||
let rows = appliedMigrations(db)
|
||||
check rows.len == 3
|
||||
check rows.len == 4
|
||||
check rows[0][0] == 1
|
||||
check rows[0][1] == "meta"
|
||||
check rows[1][0] == 2
|
||||
check rows[1][1] == "auth"
|
||||
check rows[2][0] == 3
|
||||
check rows[2][1] == "world"
|
||||
check rows[3][0] == 4
|
||||
check rows[3][1] == "tokens"
|
||||
# the steps' own DDL ran: meta and the auth tables exist and are empty
|
||||
check db.getValue(sql"SELECT count(*) FROM meta") == "0"
|
||||
check db.getValue(sql"SELECT count(*) FROM player") == "0"
|
||||
@@ -55,12 +57,14 @@ suite "migrate":
|
||||
# step 3 seeds the single v1 scene (Q3) and no walls
|
||||
check db.getValue(sql"SELECT count(*) FROM scene") == "1"
|
||||
check db.getValue(sql"SELECT count(*) FROM wall") == "0"
|
||||
# step 4 creates the token table (DESIGN 4.4 `entity`), empty
|
||||
check db.getValue(sql"SELECT count(*) FROM entity") == "0"
|
||||
|
||||
test "re-open is a no-op: no step applied, history and timestamps untouched":
|
||||
let d = tmpDir()
|
||||
block:
|
||||
let db = openFresh(d)
|
||||
check migrate(db) == 3
|
||||
check migrate(db) == 4
|
||||
close(db)
|
||||
let db = openFresh(d)
|
||||
defer:
|
||||
@@ -69,7 +73,7 @@ suite "migrate":
|
||||
let before = appliedMigrations(db)
|
||||
check migrate(db) == 0
|
||||
check migrate(db) == 0
|
||||
check schemaVersion(db) == 3
|
||||
check schemaVersion(db) == 4
|
||||
check appliedMigrations(db) == before
|
||||
|
||||
test "history and user_version must agree":
|
||||
@@ -124,7 +128,7 @@ suite "migrate":
|
||||
# the runner's own bookkeeping table may exist, but the failed step left nothing else
|
||||
check db.getValue(sql"SELECT count(*) FROM sqlite_master WHERE name = 'meta'") == "1"
|
||||
|
||||
test "a slice-2 DB migrates to slice 3: the scene is seeded, players and keys survive":
|
||||
test "a slice-2 DB migrates on: the scene is seeded, players and keys survive":
|
||||
let d = tmpDir()
|
||||
let db = openFresh(d)
|
||||
defer:
|
||||
@@ -143,8 +147,9 @@ suite "migrate":
|
||||
check schemaVersion(db) == 2
|
||||
check db.getValue(sql"SELECT count(*) FROM sqlite_master WHERE name = 'scene'") == "0"
|
||||
|
||||
check migrate(db) == 1 # only step 3 runs
|
||||
check schemaVersion(db) == 3
|
||||
check migrate(db) == 2 # steps 3 and 4 run
|
||||
check schemaVersion(db) == 4
|
||||
check db.getValue(sql"SELECT count(*) FROM scene") == "1"
|
||||
check db.getValue(sql"SELECT next_wall_id FROM scene WHERE id = 1") == "1"
|
||||
check db.getValue(sql"SELECT count(*) FROM player WHERE role = 'gm'") == "1"
|
||||
check db.getValue(sql"SELECT count(*) FROM entity") == "0"
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
## Tokens (#20, DESIGN 4.1, 4.4, 6.1, 8): ids, name/kind validation, the `vision` flag, the
|
||||
## write-through persistence and the reload a restart performs, including the nullable columns and
|
||||
## the FK that hands a removed player's tokens to the GM. The wire behaviour over a socket lives in
|
||||
## tools/tokens.test.mjs and the leak harness.
|
||||
import std/[json, options, os, sequtils, sets, strutils, unittest]
|
||||
import db_connector/db_sqlite
|
||||
import auth, db, tokens, world
|
||||
|
||||
var tmpCount = 0
|
||||
proc tmpDir(): string =
|
||||
inc tmpCount
|
||||
result = getTempDir() / "ffftokens-" & $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 plain(id = "", x = 100.0, y = 100.0, owner = GmControlled): TokenRec =
|
||||
TokenRec(id: id, kind: "npc", descriptiveName: "a grumpy man", actualName: "Lord Vex",
|
||||
pos: (x, y), owner: owner, flags: %*{"vision": true})
|
||||
|
||||
suite "ids (DESIGN 8, FIXED #3: random, opaque, 12 chars)":
|
||||
test "12 characters from the documented alphabet":
|
||||
let allowed = TokenIdAlphabet.toHashSet
|
||||
var seen = initHashSet[string]()
|
||||
for i in 0 ..< 200:
|
||||
let id = newTokenId()
|
||||
check id.len == TokenIdLength
|
||||
for c in id: check c in allowed
|
||||
check id notin seen
|
||||
seen.incl id
|
||||
|
||||
test "freshId never returns an id that is taken":
|
||||
let a = newTokenId()
|
||||
var taken = newSeq[string]()
|
||||
# a taken list that is exhaustive in the only way a test can be: same length, one element
|
||||
for i in 0 ..< 1000: taken.add newTokenId()
|
||||
let id = freshId(taken & @[a])
|
||||
check id notin taken
|
||||
check id != a
|
||||
|
||||
suite "names and kinds (DESIGN 6.5: 1..64 code points, trimmed, no control characters)":
|
||||
test "a name is trimmed, non-empty and free of control characters":
|
||||
check validName("a grumpy man")
|
||||
check validName("Lord Vex")
|
||||
check validName(repeat("x", MaxNameLen))
|
||||
check not validName("")
|
||||
check not validName(" ")
|
||||
check not validName(" padded")
|
||||
check not validName("padded ")
|
||||
check not validName("tab\there")
|
||||
check not validName("nul\0here")
|
||||
check not validName(repeat("x", MaxNameLen + 1))
|
||||
check validName("café") # code points, not bytes
|
||||
|
||||
test "kind is a short free string":
|
||||
check validKind("pc")
|
||||
check validKind("npc")
|
||||
check validKind("item")
|
||||
check not validKind("")
|
||||
check not validKind("two words but a very long kind that overflows")
|
||||
|
||||
test "vision_radius is a positive finite number or null":
|
||||
check parseVisionRadius(nil).get.isNone # absent = the scene default
|
||||
check parseVisionRadius(newJNull()).get.isNone
|
||||
check parseVisionRadius(%300).get.get == 300.0
|
||||
check parseVisionRadius(%150.5).get.get == 150.5
|
||||
check parseVisionRadius(%0).isNone
|
||||
check parseVisionRadius(%(-5)).isNone
|
||||
check parseVisionRadius(%"300").isNone
|
||||
check parseVisionRadius(%*[300]).isNone
|
||||
|
||||
suite "the `vision` flag (Q7, DESIGN 8)":
|
||||
test "only a true boolean flag counts":
|
||||
check plain().hasVision
|
||||
var t = plain()
|
||||
t.flags = %*{}
|
||||
check not t.hasVision
|
||||
t.flags = %*{"vision": false}
|
||||
check not t.hasVision
|
||||
t.flags = %*{"vision": "yes"}
|
||||
check not t.hasVision
|
||||
t.flags = newJNull()
|
||||
check not t.hasVision
|
||||
|
||||
test "the range is the token's own radius when it has vision, else the scene default":
|
||||
var sc = loadScene(freshDb()[0]).get
|
||||
var t = plain()
|
||||
check visionRange(sc, t) == 400.0
|
||||
t.visionRadius = some(250.0)
|
||||
check visionRange(sc, t) == 250.0
|
||||
t.flags = %*{} # no vision flag: the scene default, whatever the radius
|
||||
check visionRange(sc, t) == 400.0
|
||||
|
||||
test "the effective radius is the scene default in this slice":
|
||||
let (conn, d) = freshDb()
|
||||
defer:
|
||||
close(conn)
|
||||
removeDir(d)
|
||||
let sc = loadScene(conn).get
|
||||
check effectiveRadius(sc, plain()) == 20.0 # #4 default; token.resize is slice 7
|
||||
|
||||
suite "persistence (write-through, restart-identical)":
|
||||
test "create assigns the id, stores every column and reloads identically":
|
||||
let (conn, d) = freshDb()
|
||||
defer:
|
||||
close(conn)
|
||||
removeDir(d)
|
||||
let sc = loadScene(conn).get
|
||||
var t = plain(owner = 0)
|
||||
t.visionRadius = some(250.0)
|
||||
let (outcome, stored) = addToken(conn, sc, t, @[])
|
||||
check outcome == toOk
|
||||
check stored.id.len == TokenIdLength
|
||||
check stored.scene == 1
|
||||
let reloaded = loadTokens(conn)
|
||||
check reloaded.len == 1
|
||||
let r = reloaded[0]
|
||||
check r.id == stored.id
|
||||
check r.kind == "npc"
|
||||
check r.descriptiveName == "a grumpy man"
|
||||
check r.actualName == "Lord Vex"
|
||||
check r.pos == (100.0, 100.0)
|
||||
check r.radius.isNone # NULL -> the scene default
|
||||
check r.owner == GmControlled # NULL -> the GM
|
||||
check not r.gmOnly
|
||||
check r.visionRadius.get == 250.0
|
||||
check r.flags["vision"].getBool
|
||||
check r.hasVision
|
||||
|
||||
test "a controller round-trips, and a move rewrites only the position":
|
||||
let (conn, d) = freshDb()
|
||||
defer:
|
||||
close(conn)
|
||||
removeDir(d)
|
||||
let sc = loadScene(conn).get
|
||||
discard createPlayerWithKey(conn)
|
||||
let pid = parseInt(conn.getValue(sql"SELECT id FROM player WHERE role = 'player'"))
|
||||
let (_, stored) = addToken(conn, sc, plain(owner = pid), @[])
|
||||
var t = loadTokens(conn)[0]
|
||||
check t.owner == pid
|
||||
t.pos = (1200.5, 3400.25)
|
||||
check writePosition(conn, t)
|
||||
let after = loadTokens(conn)[0]
|
||||
check after.pos == (1200.5, 3400.25)
|
||||
check after.owner == pid
|
||||
check after.descriptiveName == "a grumpy man"
|
||||
|
||||
test "update replaces the whole row and keeps the id":
|
||||
let (conn, d) = freshDb()
|
||||
defer:
|
||||
close(conn)
|
||||
removeDir(d)
|
||||
let sc = loadScene(conn).get
|
||||
let (_, stored) = addToken(conn, sc, plain(), @[])
|
||||
var changed = stored
|
||||
changed.descriptiveName = "a tall stranger"
|
||||
changed.actualName = "Lady Vex"
|
||||
changed.gmOnly = true
|
||||
changed.visionRadius = some(90.0)
|
||||
changed.flags = %*{"vision": false}
|
||||
check storeToken(conn, sc, changed) == toOk
|
||||
let r = loadTokens(conn)[0]
|
||||
check r.id == stored.id
|
||||
check r.descriptiveName == "a tall stranger"
|
||||
check r.gmOnly
|
||||
check r.visionRadius.get == 90.0
|
||||
check not r.hasVision
|
||||
var invalid = changed
|
||||
invalid.descriptiveName = ""
|
||||
check storeToken(conn, sc, invalid) == toInvalid
|
||||
check loadTokens(conn)[0].descriptiveName == "a tall stranger"
|
||||
|
||||
test "remove deletes the row; a second remove reports nothing":
|
||||
let (conn, d) = freshDb()
|
||||
defer:
|
||||
close(conn)
|
||||
removeDir(d)
|
||||
let sc = loadScene(conn).get
|
||||
let (_, stored) = addToken(conn, sc, plain(), @[])
|
||||
check removeToken(conn, stored.id)
|
||||
check loadTokens(conn).len == 0
|
||||
check not removeToken(conn, stored.id)
|
||||
|
||||
test "player.remove hands the player's tokens to the GM (DESIGN 3.2)":
|
||||
let (conn, d) = freshDb()
|
||||
defer:
|
||||
close(conn)
|
||||
removeDir(d)
|
||||
let sc = loadScene(conn).get
|
||||
let created = createPlayerWithKey(conn)
|
||||
discard addToken(conn, sc, plain(owner = created.id), @[])
|
||||
check loadTokens(conn)[0].owner == created.id
|
||||
check removePlayer(conn, created.id)
|
||||
let r = loadTokens(conn)[0]
|
||||
check r.owner == GmControlled
|
||||
check r.id.len == TokenIdLength
|
||||
|
||||
test "tokens load in creation order":
|
||||
let (conn, d) = freshDb()
|
||||
defer:
|
||||
close(conn)
|
||||
removeDir(d)
|
||||
let sc = loadScene(conn).get
|
||||
var ids: seq[string]
|
||||
for i in 0 ..< 5:
|
||||
let (_, t) = addToken(conn, sc, plain(x = float(i) * 10), @[])
|
||||
ids.add t.id
|
||||
check loadTokens(conn).mapIt(it.id) == ids
|
||||
|
||||
suite "validation (DESIGN 6.1)":
|
||||
test "an out-of-bounds position writes nothing":
|
||||
let (conn, d) = freshDb()
|
||||
defer:
|
||||
close(conn)
|
||||
removeDir(d)
|
||||
let sc = loadScene(conn).get
|
||||
check addToken(conn, sc, plain(x = -1), @[]).outcome == toInvalid
|
||||
check addToken(conn, sc, plain(y = 4097), @[]).outcome == toInvalid
|
||||
check loadTokens(conn).len == 0
|
||||
|
||||
test "an empty name writes nothing":
|
||||
let (conn, d) = freshDb()
|
||||
defer:
|
||||
close(conn)
|
||||
removeDir(d)
|
||||
let sc = loadScene(conn).get
|
||||
var t = plain()
|
||||
t.actualName = ""
|
||||
check addToken(conn, sc, t, @[]).outcome == toInvalid
|
||||
check loadTokens(conn).len == 0
|
||||
|
||||
test "the same id is never handed out twice by the caller-supplied taken list":
|
||||
let (conn, d) = freshDb()
|
||||
defer:
|
||||
close(conn)
|
||||
removeDir(d)
|
||||
let sc = loadScene(conn).get
|
||||
var ids: seq[string]
|
||||
for i in 0 ..< 20:
|
||||
let (outcome, t) = addToken(conn, sc, plain(x = float(i)), ids)
|
||||
check outcome == toOk
|
||||
ids.add t.id
|
||||
check ids.toHashSet.len == 20
|
||||
|
||||
test "a lookup by id is exact":
|
||||
let (conn, d) = freshDb()
|
||||
defer:
|
||||
close(conn)
|
||||
removeDir(d)
|
||||
let sc = loadScene(conn).get
|
||||
let (_, t) = addToken(conn, sc, plain(), @[])
|
||||
check tokenById(@[t], t.id).isSome
|
||||
check tokenById(@[t], "").isNone
|
||||
check tokenById(@[t], t.id & "x").isNone
|
||||
@@ -49,21 +49,23 @@ test('a fresh DB is created and migrated; re-opening applies nothing', async ()
|
||||
const first = await startServer({ stateDir })
|
||||
const firstLog = first.log()
|
||||
await stopServer(first)
|
||||
assert.match(firstLog, /db_ready .*schema_version=3 applied=3/, firstLog)
|
||||
assert.match(firstLog, /db_ready .*schema_version=4 applied=4/, firstLog)
|
||||
assert.ok(fs.existsSync(first.dbPath), 'state.db was not created')
|
||||
|
||||
const db = new DatabaseSync(first.dbPath)
|
||||
try {
|
||||
assert.equal(Number(db.prepare('PRAGMA user_version').get().user_version), 3)
|
||||
assert.equal(Number(db.prepare('PRAGMA user_version').get().user_version), 4)
|
||||
const rows = db.prepare('SELECT version, name FROM schema_migration ORDER BY version').all()
|
||||
assert.deepEqual(rows.map(r => [Number(r.version), r.name]),
|
||||
[[1, 'meta'], [2, 'auth'], [3, 'world']])
|
||||
[[1, 'meta'], [2, 'auth'], [3, 'world'], [4, 'tokens']])
|
||||
assert.equal(Number(db.prepare('SELECT count(*) AS n FROM meta').get().n), 0)
|
||||
assert.equal(Number(db.prepare('SELECT count(*) AS n FROM player').get().n), 0)
|
||||
// step 3 seeds the single v1 scene (Q3) with no walls and a counter at 1
|
||||
assert.deepEqual(db.prepare('SELECT id, next_wall_id FROM scene').all()
|
||||
.map(r => [Number(r.id), Number(r.next_wall_id)]), [[1, 1]])
|
||||
assert.equal(Number(db.prepare('SELECT count(*) AS n FROM wall').get().n), 0)
|
||||
// step 4 creates the token table (DESIGN 4.4 `entity`), empty
|
||||
assert.equal(Number(db.prepare('SELECT count(*) AS n FROM entity').get().n), 0)
|
||||
assert.equal(db.prepare('PRAGMA journal_mode').get().journal_mode, 'wal')
|
||||
} finally {
|
||||
db.close()
|
||||
@@ -72,7 +74,7 @@ test('a fresh DB is created and migrated; re-opening applies nothing', async ()
|
||||
const second = await startServer({ stateDir })
|
||||
const secondLog = second.log().slice(firstLog.length)
|
||||
await stopServer(second)
|
||||
assert.match(secondLog, /db_ready .*schema_version=3 applied=0/, secondLog)
|
||||
assert.match(secondLog, /db_ready .*schema_version=4 applied=0/, secondLog)
|
||||
assert.doesNotMatch(secondLog, /applied=[1-9]/)
|
||||
} finally {
|
||||
fs.rmSync(stateDir, { recursive: true, force: true })
|
||||
|
||||
Reference in New Issue
Block a user