## 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 (issues #20, #22): plain tokens only. The character link and the name-reveal ## machinery are slice 8 (#23); the per-token size (#4) and the three property buckets are slice 7 ## here. A token's effective radius is its own `radius` when set, else the scene's ## `token_radius_default` (5.6). ## ## Statuses (DESIGN 5.5 FIXED #4; slice 7): a token holds a set of `(status, source)` entries - ## status `stuck`|`squeezed`, source `walls`|`GM`. Any entry locks the token for its player; the GM ## always moves it. The same status may come from both sources at once and both statuses may show ## together. `walls`-sourced entries are maintained by server/moverules.nim (Set/Keep/Clear and the ## two push rules); `GM`-sourced entries only by `status.set`/`status.clear`. The egress shows the ## status to everyone who sees the token and the source to the GM only (6.1 leak note 6). ## ## 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, ## `token.resize`, `status.*`, `prop.*`) runs with `synchronous=FULL` (Q12); a move - player or GM ## drag - and a wall-derived status change run with `NORMAL`, like explored cells: neither a position ## nor a derived lock is authored content. Status rows are rewritten with the row they belong to, so ## a status change and its `token` frame can never disagree after a crash (entity_status cascades on ## the entity FK). This module does no locking: the caller holds the server's global lock (4.3). import std/[algorithm, json, options, strutils, tables, times] import db_connector/db_sqlite import crypto, db, geometry, props, text, world import std/math except round export text # `validText` stays reachable for the modules and tests that imported it via tokens type StatusKind* = enum stStuck = "stuck" ## held in place: wall through it, ropes, magic grasp (5.5) stSqueezed = "squeezed" ## pressed, no room: walls around it, a closing hand (5.5) StatusSource* = enum ssWalls = "walls" ## set by the move rules (5.5 Set/Keep/Clear, 5.6 grow push) ssGM = "GM" ## set and cleared by the GM only (6.1 status.set/status.clear) StatusEntry* = tuple[kind: StatusKind, source: StatusSource] 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 ## "" when `characterId` is set: the character carries the names (8) actualName*: string ## "" when `characterId` is set characterId*: Option[string] ## the character this token figures (8); none = a plain token revealAll*: bool ## plain tokens only: the actual name is revealed to everyone (8) pos*: Vec radius*: Option[float] ## px; none = the scene default (5.6, #4) 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) props*: Props ## three visibility buckets, never nil (6.1, 8) statuses*: seq[StatusEntry] ## sorted by (kind, source); empty = not locked 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] characterId*: Option[Option[string]] ## some(none) = unlink, some(some(id)) = link 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 validName*(s: string): bool = validText(s, MaxNameLen) proc validKind*(s: string): bool = validText(s, MaxKindLen) proc parseRadius*(node: JsonNode): Option[Option[float]] = ## `radius` / `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 parseVisionRadius*(node: JsonNode): Option[Option[float]] = parseRadius(node) proc parseStatusKind*(raw: string): Option[StatusKind] = for k in StatusKind: if $k == raw: return some(k) proc parseStatusSource*(raw: string): Option[StatusSource] = for s in StatusSource: if $s == raw: return some(s) # --------------------------------------------------------------------------------------------------- # Statuses: a sorted set of `(status, source)` entries (5.5) proc sortStatuses*(entries: seq[StatusEntry]): seq[StatusEntry] = ## Stored order: by status (stuck, squeezed) then by source (walls, GM). Deterministic, so a ## rebuilt entry list cannot produce a spurious `token` frame. Always a fresh buffer: a caller ## copies a record and re-sorts without ever touching the original's sequence. var sorted = newSeqOfCap[StatusEntry](entries.len) for e in entries: sorted.add e sorted.sort(proc (a, b: StatusEntry): int = result = cmp(ord(a.kind), ord(b.kind)) if result == 0: result = cmp(ord(a.source), ord(b.source))) var unique: seq[StatusEntry] for e in sorted: if unique.len == 0 or unique[^1] != e: unique.add e result = unique proc hasStatus*(t: TokenRec, kind: StatusKind, source: StatusSource): bool = for e in t.statuses: if e.kind == kind and e.source == source: return true proc isLocked*(t: TokenRec): bool = ## Any entry locks the token for its player, whatever the source (5.5). t.statuses.len > 0 proc withStatus*(entries: seq[StatusEntry], kind: StatusKind, source: StatusSource): seq[StatusEntry] = ## A fresh sequence with one entry added (or the same set when it was already there). Never ## mutates the caller's buffer: main.nim copies a record before it changes it. for e in entries: if e.kind == kind and e.source == source: return sortStatuses(entries) var next = newSeqOfCap[StatusEntry](entries.len + 1) for e in entries: next.add e next.add (kind: kind, source: source) sortStatuses(next) proc withoutStatus*(entries: seq[StatusEntry], kind: StatusKind, source: StatusSource): seq[StatusEntry] = ## A fresh sequence with exactly that `(status, source)` entry removed. for e in entries: if e.kind == kind and e.source == source: continue result.add e proc addStatus*(t: var TokenRec, kind: StatusKind, source: StatusSource) = t.statuses = withStatus(t.statuses, kind, source) proc removeStatus*(t: var TokenRec, kind: StatusKind, source: StatusSource): bool = ## Removes exactly one `(status, source)` entry; false = it was not there. result = t.hasStatus(kind, source) if result: t.statuses = withoutStatus(t.statuses, kind, source) 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, the props are three objects, the status set is ## sorted, 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 result.props = props.normalize(result.props) result.statuses = sortStatuses(result.statuses) 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 = ## 6.1 validation. The props are checked for structure and caps; the per-key schema is the wire ## layer's job (props.checkWrite), because only the intent knows the registry. ## Names (8): a plain token carries both of its own and they follow the name rule; a token linked ## to a character carries neither, because the character's names are the ones that reach a client. let namesOk = if t.characterId.isSome: t.descriptiveName.len == 0 and t.actualName.len == 0 else: validName(t.descriptiveName) and validName(t.actualName) namesOk and validKind(t.kind) and validPlacement(sc, t.pos) and props.valid(t.props) and (t.radius.isNone or t.radius.get > 0) 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.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 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 sqlLitId(id: Option[string]): string = ## `character_id` is NULL for a plain token, and db_connector cannot bind a NULL argument ## (it quotes every parameter as text), so the value rides as a literal. Only ids from the token ## alphabet (8) ever reach here - a value is checked on the way in - so a quote cannot appear. if id.isNone: return "NULL" let v = id.get for c in v: if c notin {'A'..'Z', 'a'..'z', '0'..'9', '_', '-'}: raise newException(ValueError, "character id outside the id alphabet") sqlLitText(v) proc writeStatuses*(db: DbConn, t: TokenRec) = ## Rewrites the token's `entity_status` rows to exactly `t.statuses`. No transaction control: the ## caller is inside the row's transaction (a status change and its row commit together). db.exec(sql"DELETE FROM entity_status WHERE entity_id = ?", t.id) for e in t.statuses: db.exec(sql"INSERT INTO entity_status (entity_id, status, source) VALUES (?, ?, ?)", t.id, $e.kind, $e.source) proc writeStatuses*(db: DbConn, id: string, statuses: openArray[StatusEntry]) = ## The same for a caller holding only the new entry list (a wall-derived change with no row write). var rec = TokenRec(id: id, statuses: @statuses) db.writeStatuses(rec) 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, props_public, props_owner," & " props_gm, created_at, character_id, reveal_all) VALUES (" & "?, ?, ?, ?, ?, ?, ?, " & sqlLit(t.radius) & ", " & sqlLitOwner(t.owner) & ", ?, " & sqlLit(t.visionRadius) & ", ?, ?, ?, ?, ?, " & sqlLitId(t.characterId) & ", ?)"), t.id, t.scene, t.kind, t.descriptiveName, t.actualName, $t.pos.x, $t.pos.y, (if t.gmOnly: 1 else: 0), $t.flags, $t.props[pbPublic], $t.props[pbOwner], $t.props[pbGm], now().utc.format("yyyy-MM-dd'T'HH:mm:ss'Z'"), (if t.revealAll: 1 else: 0)) writeStatuses(db, t) 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 = ?," & " props_public = ?, props_owner = ?, props_gm = ?, reveal_all = ?," & " character_id = " & sqlLitId(t.characterId) & " WHERE id = ?"), t.kind, t.descriptiveName, t.actualName, $t.pos.x, $t.pos.y, (if t.gmOnly: 1 else: 0), $t.flags, $t.props[pbPublic], $t.props[pbOwner], $t.props[pbGm], (if t.revealAll: 1 else: 0), t.id) writeStatuses(db, t) 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` / `token.resize` / `status.*` / `prop.*`: full replacement of the row, its ## status rows and its props (GM authoring, FULL), so one change is one transaction. let stored = normalize(candidate) if not validToken(sc, stored): return toInvalid 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 parseObject(s: string): JsonNode = ## A stored JSON object; a hand-edited or truncated value must not crash the server. try: result = parseJson(s) except CatchableError: result = newJObject() if result.isNil or result.kind != JObject: result = newJObject() proc rowToToken(row: Row): TokenRec = var p = newProps() p[pbPublic] = parseObject(row[12]) p[pbOwner] = parseObject(row[13]) p[pbGm] = parseObject(row[14]) 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: parseObject(row[11]), props: p, characterId: (if row[15].len == 0: none(string) else: some(row[15])), revealAll: row[16] == "1") proc loadStatuses(db: DbConn, sceneId: int): Table[string, seq[StatusEntry]] = ## The `(status, source)` entries of every token of the scene, keyed by token id (5.5). for row in db.getAllRows(sql""" SELECT s.entity_id, s.status, s.source FROM entity_status s JOIN entity e ON e.id = s.entity_id WHERE e.scene_id = ? ORDER BY s.status, s.source""", sceneId): result.mgetOrPut(row[0], @[]).add (kind: parseEnum[StatusKind](row[1]), source: parseEnum[StatusSource](row[2])) 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, props_public, props_owner, props_gm, character_id, reveal_all FROM entity WHERE scene_id = ? ORDER BY rowid""", sceneId): result.add rowToToken(row) let statuses = loadStatuses(db, sceneId) for t in result.mitems: if statuses.hasKey(t.id): t.statuses = sortStatuses(statuses[t.id]) 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])