server: the property buckets, the registry and the status set (#22)

Migration step 6 ("token details") adds the three prop buckets to `entity`
and creates `entity_status`, the `(status, source)` set of 5.5. A token's
status rows are rewritten with its row, so a status change and the `token`
frame that reports it commit together.

server/props.nim owns the buckets, their caps (64 keys per bucket, a key of
1..64 code points, a value of at most 8 KB of serialized JSON) and the
property-schema registry: empty at start with a permissive fallback, because
DESIGN 8 says v1 never interprets props; a key the rules module registers is
enforced (kind and bucket). server/text.nim is the one copy of the 6.5 text
rule, shared by names and prop keys.

tokens.nim gains `props` and `statuses` on the record, the sorted-unique
entry helpers, `isLocked`, `parseRadius`/`parseStatusKind`/`parseStatusSource`,
the prop and status columns in insert/replace, and `loadStatuses` joined on
the scene. Every helper builds a fresh sequence: a copied record shares its
seq buffer, so an in-place edit would reach the authoritative list before
the transaction commits (4.2 step 6).
This commit is contained in:
2026-11-15 11:02:23 +01:00
parent d773a5e2de
commit 67762c1309
5 changed files with 364 additions and 38 deletions
+12
View File
@@ -42,6 +42,18 @@ _Avoid_: PC, hero
A figure on the map. It may belong to a character; a plain token (monster, item) belongs to none. Holds what is happening to the figure. Its controller is set on its own and does not follow the character's owner. A figure on the map. It may belong to a character; a plain token (monster, item) belongs to none. Holds what is happening to the figure. Its controller is set on its own and does not follow the character's owner.
_Avoid_: entity, piece, counter _Avoid_: entity, piece, counter
**Property**:
One named value a token carries, e.g. "aura" or "hp". The server stores it and never interprets it in v1; FFF does later.
_Avoid_: attribute, stat, metadata
**Property bucket**:
The visibility a property is filed under: `public` (anyone who sees the token), `owner` (the token's controller and the GM) or `gm` (the GM only). A prop key may live in all three at once with different values.
_Avoid_: layer, scope, channel
**Property schema registry**:
The rules module's table of known property keys, each with a value kind and a bucket. It ships empty in v1, so any key is accepted in any bucket; a registered key is enforced on every write.
_Avoid_: prop whitelist, schema cache
**Descriptive name**: **Descriptive name**:
The name a player sees for a character or plain token until the GM reveals the actual name, e.g. "a grumpy man". Every character and plain token has one. The name a player sees for a character or plain token until the GM reveals the actual name, e.g. "a grumpy man". Every character and plain token has one.
_Avoid_: alias, label, nickname _Avoid_: alias, label, nickname
+16
View File
@@ -17,6 +17,12 @@
## (DESIGN 4.4, 8): one row per (player, scene, 64x64-cell chunk), 512 B per row, LSB-first ## (DESIGN 4.4, 8): one row per (player, scene, 64x64-cell chunk), 512 B per row, LSB-first
## row-major bits (server/explored.nim). Both FKs cascade, so removing a player or a scene takes its ## row-major bits (server/explored.nim). Both FKs cascade, so removing a player or a scene takes its
## explored cells with it. ## explored cells with it.
## Step 6 ("token details", M3 slice 7 / #22) adds the three property buckets to `entity` (DESIGN 8:
## `props_public`, `props_owner`, `props_gm`, one JSON object each, `'{}'` by default) and creates
## `entity_status` for the `stuck`/`squeezed` model (DESIGN 4.4, 5.5): one row per
## `(token, status, source)` entry, cascading on the token. `radius` was already a column from step 4
## (`token.resize` is what makes it reachable); step 6 only makes the buckets and the statuses
## persistent.
## One connection, used under the server's global lock (4.3); this module does no locking itself. ## One connection, used under the server's global lock (4.3); this module does no locking itself.
import std/[strutils, times] import std/[strutils, times]
import db_connector/db_sqlite import db_connector/db_sqlite
@@ -121,6 +127,16 @@ CREATE TABLE explored_chunk (
cy INTEGER NOT NULL, cy INTEGER NOT NULL,
bits BLOB NOT NULL CHECK (length(bits) = 512), -- 64x64 cells, LSB-first row-major bits BLOB NOT NULL CHECK (length(bits) = 512), -- 64x64 cells, LSB-first row-major
PRIMARY KEY (player_id, scene_id, cx, cy) PRIMARY KEY (player_id, scene_id, cx, cy)
)"""]),
Migration(version: 6, name: "token details", stmts: @["""
ALTER TABLE entity ADD COLUMN props_public TEXT NOT NULL DEFAULT '{}'""", """
ALTER TABLE entity ADD COLUMN props_owner TEXT NOT NULL DEFAULT '{}'""", """
ALTER TABLE entity ADD COLUMN props_gm TEXT NOT NULL DEFAULT '{}'""", """
CREATE TABLE entity_status (
entity_id TEXT NOT NULL REFERENCES entity(id) ON DELETE CASCADE,
status TEXT NOT NULL CHECK (status IN ('stuck', 'squeezed')),
source TEXT NOT NULL CHECK (source IN ('walls', 'GM')),
PRIMARY KEY (entity_id, status, source)
)"""]), )"""]),
] ]
LatestVersion* = migrations[^1].version LatestVersion* = migrations[^1].version
+161
View File
@@ -0,0 +1,161 @@
## Property buckets, their caps and the property-schema registry (DESIGN 6.1 prop payload rules, 8,
## 9; M3 slice 7, issue #22).
##
## A token (and, from slice 8, a character) carries three JSON objects by visibility bucket:
## `public` (anyone who sees it), `owner` (the token's controller + the GM) and `gm` (the GM only).
## The egress (views.nim) decides which buckets a recipient gets; nothing here knows about sockets.
##
## Caps [FIXED (owner-delegated, 2026-11-15, #22)]: at most 64 keys per bucket, a key is a string of
## 1..64 code points with no control characters, and a value's serialized JSON is at most 8 KB.
## 6.1 delegated these numbers (#11) and slice 7 fixes them.
##
## The registry (DESIGN 8/9): `key -> PropSchema{kind, bucket}` plus a fallback rule. v1 ships it
## **empty**, and its fallback is permissive (`pkAny`, any bucket), because DESIGN 8 says the server
## never interprets props in v1: any key may be written to any bucket, under the caps above. A key
## the rules module (FFF, post-v1) registers is enforced from then on: a value of the wrong JSON
## kind, or a write to a bucket the schema does not name, is `invalid`. That is the "the registry
## validates, the server does not interpret" rule of DESIGN 9 in one place: `checkWrite` is the only
## gate, so flipping the fallback to strict is a one-line change when FFF lands.
##
## Ordering: props are `JsonNode` objects, so key order is insertion order and a reload preserves
## it. JSON object equality ignores order (std/json), so a re-serialisation can never produce a
## spurious `token` frame (views.Known compares built frames).
import std/[json, options, tables]
import text
type
PropBucket* = enum
pbPublic = "public"
pbOwner = "owner"
pbGm = "gm"
PropKind* = enum
pkAny, pkString, pkNumber, pkBool, pkObject, pkArray
## The value kinds a schema can demand; `pkAny` accepts any JSON value (the v1 fallback).
PropSchema* = object
kind*: PropKind
bucket*: Option[PropBucket] ## none = the key may live in any bucket
Registry* = object
## `schemas` is what the rules module registered; `fallback` answers every other key.
schemas*: Table[string, PropSchema]
fallback*: PropSchema
Props* = array[PropBucket, JsonNode]
## One JSON object per bucket, never nil. A record's props always have all three buckets even
## when they are empty, so egress can filter by bucket alone.
const
MaxPropKeys* = 64
## 6.1, numbers delegated (#11), fixed by slice 7.
MaxPropKeyLen* = 64
## 1..64 code points, same rule as a character name.
MaxPropValueBytes* = 8192
## 6.1: a value's serialized JSON is at most 8 KB.
proc newProps*(): Props =
for b in PropBucket: result[b] = newJObject()
proc normalize*(p: Props): Props =
## Stored-props invariants: every bucket is an object, never nil.
result = p
for b in PropBucket:
if result[b].isNil or result[b].kind != JObject: result[b] = newJObject()
proc parseBucket*(raw: string): Option[PropBucket] =
for b in PropBucket:
if $b == raw: return some(b)
proc bucketName*(b: PropBucket): string = $b
proc validPropKey*(key: string): bool = validText(key, MaxPropKeyLen)
proc valueBytes*(value: JsonNode): int =
## The cap is on the serialized size (6.1), which is the number that actually crosses the wire.
if value.isNil: 0 else: ($value).len
proc defaultRegistry*(): Registry =
## v1's registry: nothing registered, every key accepted (DESIGN 8: props are not interpreted).
Registry(fallback: PropSchema(kind: pkAny, bucket: none(PropBucket)))
proc schemaFor*(reg: Registry, key: string): PropSchema =
reg.schemas.getOrDefault(key, reg.fallback)
proc kindMatches*(kind: PropKind, value: JsonNode): bool =
if value.isNil: return false
case kind
of pkAny: true
of pkString: value.kind == JString
of pkNumber: value.kind in {JInt, JFloat}
of pkBool: value.kind == JBool
of pkObject: value.kind == JObject
of pkArray: value.kind == JArray
proc checkWrite*(reg: Registry, bucket: PropBucket, key: string, value: JsonNode): bool =
## The registry gate for one write. Structural checks live in `parseProps`/`setProp`; this is the
## per-key schema (kind, bucket). Unregistered keys use the fallback rule.
let schema = reg.schemaFor(key)
if schema.bucket.isSome and schema.bucket.get != bucket: return false
kindMatches(schema.kind, value)
proc setProp*(p: var Props, bucket: PropBucket, key: string, value: JsonNode): bool =
## Sets one value. false = the bucket is at its key cap and the key is new (nothing changed).
if p[bucket].isNil or p[bucket].kind != JObject: p[bucket] = newJObject()
if not p[bucket].hasKey(key) and p[bucket].len >= MaxPropKeys: return false
p[bucket][key] = value
true
proc unsetProp*(p: var Props, bucket: PropBucket, key: string): bool =
## Removes one value; false = it was not there (unsetting an absent key is still `ok` on the wire).
if p[bucket].isNil or p[bucket].kind != JObject: return false
result = p[bucket].hasKey(key)
if result: p[bucket].delete(key)
proc contains*(p: Props, bucket: PropBucket, key: string): bool =
p[bucket].kind == JObject and p[bucket].hasKey(key)
proc propsJson*(p: Props): JsonNode =
## All three buckets: the shape a GM frame carries (6.1).
result = newJObject()
for b in PropBucket: result[$b] = p[b]
proc clone*(p: Props): Props =
## A copy whose buckets are fresh objects: a value node is shared (never mutated), but adding or
## removing a key cannot reach the original bucket. `main.nim` copies a record before it edits it,
## and a Nim array of refs does not give that for free.
for b in PropBucket:
var bucket = newJObject()
if not p[b].isNil and p[b].kind == JObject:
for key, value in p[b]: bucket[key] = value
result[b] = bucket
proc valid*(p: Props): bool =
## The stored-record invariant: every bucket an object, every key and value within the caps.
result = true # Nim's default for `bool` is false: set it before the early returns below
for b in PropBucket:
if p[b].isNil or p[b].kind != JObject: return false
if p[b].len > MaxPropKeys: return false
for key, value in p[b]:
if not validPropKey(key): return false
if value.kind == JNull: return false # 6.1: a value is JSON, null is not a value
if valueBytes(value) > MaxPropValueBytes: return false
proc parseProps*(reg: Registry, node: JsonNode): Option[Props] =
## `props` on `token.create` (6.1): absent/null = all empty; else an object whose keys are the
## three bucket names and whose values are objects that pass the caps and the registry.
## `some(...)` = valid, `none` = refused `invalid`.
if node.isNil or node.kind == JNull: return some(newProps())
if node.kind != JObject: return none(Props)
var parsed = newProps()
for name, bucketNode in node:
let bucket = parseBucket(name)
if bucket.isNone: return none(Props)
if bucketNode.kind != JObject: return none(Props)
for key, value in bucketNode:
if not validPropKey(key): return none(Props)
if value.kind == JNull: return none(Props)
if valueBytes(value) > MaxPropValueBytes: return none(Props)
if not reg.checkWrite(bucket.get, key, value): return none(Props)
if not parsed.setProp(bucket.get, key, value): return none(Props)
some(parsed)
+13
View File
@@ -0,0 +1,13 @@
## The one copy of the text rules of DESIGN 6.5: a stored text field is trimmed, 1..maxLen code
## points and free of control characters. Shared by the token/character names (tokens.nim) and the
## property keys (props.nim), so the two cannot drift apart.
import std/unicode
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. NFC normalisation and the per-player
## uniqueness rule arrived 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)
+162 -38
View File
@@ -7,10 +7,17 @@
## unique game-wide (not per scene) and collision-checked on create. Counted ids would leak hidden ## 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. ## 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 ## Scope of this slice (issues #20, #22): plain tokens only. The character link and the name-reveal
## and the three property buckets are slices 7-8 (#22, #23), and the per-token size is #4's ## machinery are slice 8 (#23); the per-token size (#4) and the three property buckets are slice 7
## `token.resize` (slice 7): a token's effective radius is always the scene's `token_radius_default` ## here. A token's effective radius is its own `radius` when set, else the scene's
## here, so a `radius` field on the wire intents is refused `invalid` rather than silently dropped. ## `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 (`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 ## owner). `GmControlled` (0) is SQL NULL; player ids start at 1. A controller that is the GM's own
@@ -18,16 +25,30 @@
## on the wire (`controller: null`). ## on the wire (`controller: null`).
## ##
## Persistence order (4.2 step 6): the row is written first and memory is updated only after the ## 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) ## 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 ## `token.resize`, `status.*`, `prop.*`) runs with `synchronous=FULL` (Q12); a move - player or GM
## cells: a position is not authored content. This module does no locking: the caller holds the ## drag - and a wall-derived status change run with `NORMAL`, like explored cells: neither a position
## server's global lock (4.3). ## nor a derived lock is authored content. Status rows are rewritten with the row they belong to, so
import std/[json, options, strutils, times, unicode] ## 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 db_connector/db_sqlite
import crypto, geometry, world import crypto, geometry, props, text, world
import std/math except round import std/math except round
export text # `validText` stays reachable for the modules and tests that imported it via tokens
type 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 TokenRec* = object
id*: string id*: string
scene*: int scene*: int
@@ -35,14 +56,17 @@ type
descriptiveName*: string descriptiveName*: string
actualName*: string actualName*: string
pos*: Vec pos*: Vec
radius*: Option[float] ## px; none = the scene default. Slice 7 (#4) fills this. radius*: Option[float] ## px; none = the scene default (5.6, #4)
owner*: int ## controller: player id, GmControlled = the GM owner*: int ## controller: player id, GmControlled = the GM
gmOnly*: bool gmOnly*: bool
visionRadius*: Option[float] ## px; none = the scene default (Q7, the 5.5 step cap) 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) 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) prev*: Vec ## position before the most recent move/push (door-push side, 5.5)
hasPrev*: bool hasPrev*: bool
TokenOutcome* = enum TokenOutcome* = enum
toOk toOk
toInvalid ## field/geometry semantics: `invalid` toInvalid ## field/geometry semantics: `invalid`
@@ -71,21 +95,12 @@ const
# --------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------
# Field parsing and validation (DESIGN 6.1 field notes, 6.5) # 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 validName*(s: string): bool = validText(s, MaxNameLen)
proc validKind*(s: string): bool = validText(s, MaxKindLen) proc validKind*(s: string): bool = validText(s, MaxKindLen)
proc parseVisionRadius*(node: JsonNode): Option[Option[float]] = proc parseRadius*(node: JsonNode): Option[Option[float]] =
## `vision_radius`: a positive finite number, or null/absent (= the scene default). ## `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. ## `some(none(float))` = explicitly cleared; `some(some(r))` = set; none = present but invalid.
if node.isNil or node.kind == JNull: return some(none(float)) if node.isNil or node.kind == JNull: return some(none(float))
var f: float var f: float
@@ -96,6 +111,68 @@ proc parseVisionRadius*(node: JsonNode): Option[Option[float]] =
if classify(f) in {fcNan, fcInf, fcNegInf} or f <= 0: return none(Option[float]) if classify(f) in {fcNan, fcInf, fcNegInf} or f <= 0: return none(Option[float])
some(some(f)) 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 = proc newTokenId*(): string =
## 12 CSPRNG characters from a 64-symbol alphabet (uniform: 256 = 4 x 64, no rejection needed). ## 12 CSPRNG characters from a 64-symbol alphabet (uniform: 256 = 4 x 64, no rejection needed).
result = newStringOfCap(TokenIdLength) result = newStringOfCap(TokenIdLength)
@@ -116,10 +193,13 @@ proc freshId*(taken: openArray[string]): string =
if not clash: return if not clash: return
proc normalize*(t: TokenRec): TokenRec = proc normalize*(t: TokenRec): TokenRec =
## Stored-token invariants: `flags` is an object, and a controller never becomes a negative id. ## 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 result = t
if result.flags.isNil or result.flags.kind != JObject: result.flags = newJObject() if result.flags.isNil or result.flags.kind != JObject: result.flags = newJObject()
if result.owner < 0: result.owner = GmControlled 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 = proc effectiveRadius*(sc: SceneRec, t: TokenRec): float =
## DESIGN 5.6/#4: the entity radius if set, else the scene's `token_radius_default`. ## DESIGN 5.6/#4: the entity radius if set, else the scene's `token_radius_default`.
@@ -142,8 +222,12 @@ proc inBounds(sc: SceneRec, p: Vec): bool =
proc validPlacement*(sc: SceneRec, pos: Vec): bool = inBounds(sc, pos) proc validPlacement*(sc: SceneRec, pos: Vec): bool = inBounds(sc, pos)
proc validToken*(sc: SceneRec, t: TokenRec): bool = 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.
validName(t.descriptiveName) and validName(t.actualName) and validKind(t.kind) and validName(t.descriptiveName) and validName(t.actualName) and validKind(t.kind) and
validPlacement(sc, t.pos) 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 = proc patched*(t: TokenRec, patch: TokenPatch): TokenRec =
result = t result = t
@@ -167,22 +251,41 @@ proc sqlLit(v: Option[float]): string =
proc sqlLitOwner(owner: int): string = proc sqlLitOwner(owner: int): string =
if owner == GmControlled: "NULL" else: $owner if owner == GmControlled: "NULL" else: $owner
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) = proc insertRow(db: DbConn, t: TokenRec) =
db.exec(sql("INSERT INTO entity (id, scene_id, kind, descriptive_name, actual_name, x, y, radius," & 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 (" & " owner_player_id, gm_only, vision_radius, flags, props_public, props_owner," &
" props_gm, created_at) VALUES (" &
"?, ?, ?, ?, ?, ?, ?, " & sqlLit(t.radius) & ", " & sqlLitOwner(t.owner) & ", ?, " & "?, ?, ?, ?, ?, ?, ?, " & sqlLit(t.radius) & ", " & sqlLitOwner(t.owner) & ", ?, " &
sqlLit(t.visionRadius) & ", ?, ?)"), sqlLit(t.visionRadius) & ", ?, ?, ?, ?, ?)"),
t.id, t.scene, t.kind, t.descriptiveName, t.actualName, $t.pos.x, $t.pos.y, t.id, t.scene, t.kind, t.descriptiveName, t.actualName, $t.pos.x, $t.pos.y,
(if t.gmOnly: 1 else: 0), $t.flags, (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'")) now().utc.format("yyyy-MM-dd'T'HH:mm:ss'Z'"))
writeStatuses(db, t)
proc replaceRow(db: DbConn, t: TokenRec) = proc replaceRow(db: DbConn, t: TokenRec) =
db.exec(sql("UPDATE entity SET kind = ?, descriptive_name = ?, actual_name = ?, x = ?, y = ?," & db.exec(sql("UPDATE entity SET kind = ?, descriptive_name = ?, actual_name = ?, x = ?, y = ?," &
" radius = " & sqlLit(t.radius) & ", owner_player_id = " & sqlLitOwner(t.owner) & " radius = " & sqlLit(t.radius) & ", owner_player_id = " & sqlLitOwner(t.owner) &
", gm_only = ?, vision_radius = " & sqlLit(t.visionRadius) & ", flags = ?" & ", gm_only = ?, vision_radius = " & sqlLit(t.visionRadius) & ", flags = ?," &
" WHERE id = ?"), " props_public = ?, props_owner = ?, props_gm = ? WHERE id = ?"),
t.kind, t.descriptiveName, t.actualName, $t.pos.x, $t.pos.y, t.kind, t.descriptiveName, t.actualName, $t.pos.x, $t.pos.y,
(if t.gmOnly: 1 else: 0), $t.flags, t.id) (if t.gmOnly: 1 else: 0), $t.flags,
$t.props[pbPublic], $t.props[pbOwner], $t.props[pbGm], t.id)
writeStatuses(db, t)
proc addToken*(db: DbConn, sc: SceneRec, candidate: TokenRec, takenIds: openArray[string]): proc addToken*(db: DbConn, sc: SceneRec, candidate: TokenRec, takenIds: openArray[string]):
tuple[outcome: TokenOutcome, token: TokenRec] = tuple[outcome: TokenOutcome, token: TokenRec] =
@@ -197,9 +300,10 @@ proc addToken*(db: DbConn, sc: SceneRec, candidate: TokenRec, takenIds: openArra
(toOk, stored) (toOk, stored)
proc storeToken*(db: DbConn, sc: SceneRec, candidate: TokenRec): TokenOutcome = proc storeToken*(db: DbConn, sc: SceneRec, candidate: TokenRec): TokenOutcome =
## `token.update`: full replacement of the patched row (GM authoring, FULL). ## `token.update` / `token.resize` / `status.*` / `prop.*`: full replacement of the row, its
if not validToken(sc, candidate): return toInvalid ## status rows and its props (GM authoring, FULL), so one change is one transaction.
var stored = normalize(candidate) let stored = normalize(candidate)
if not validToken(sc, stored): return toInvalid
authoringTransaction(db): authoringTransaction(db):
replaceRow(db, stored) replaceRow(db, stored)
toOk toOk
@@ -226,27 +330,47 @@ proc clearOwnership*(db: DbConn, playerId: int) =
proc optFloat(s: string): Option[float] = proc optFloat(s: string): Option[float] =
if s.len == 0: none(float) else: some(parseFloat(s)) if s.len == 0: none(float) else: some(parseFloat(s))
proc rowToToken(row: Row): TokenRec = proc parseObject(s: string): JsonNode =
var flags: JsonNode ## A stored JSON object; a hand-edited or truncated value must not crash the server.
try: try:
flags = parseJson(row[11]) result = parseJson(s)
except CatchableError: except CatchableError:
flags = newJObject() 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], TokenRec(id: row[0], scene: parseInt(row[1]), kind: row[2],
descriptiveName: row[3], actualName: row[4], descriptiveName: row[3], actualName: row[4],
pos: (parseFloat(row[5]), parseFloat(row[6])), pos: (parseFloat(row[5]), parseFloat(row[6])),
radius: optFloat(row[7]), radius: optFloat(row[7]),
owner: (if row[8].len == 0: GmControlled else: parseInt(row[8])), owner: (if row[8].len == 0: GmControlled else: parseInt(row[8])),
gmOnly: row[9] == "1", gmOnly: row[9] == "1",
visionRadius: optFloat(row[10]), flags: flags) visionRadius: optFloat(row[10]), flags: parseObject(row[11]), props: p)
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] = proc loadTokens*(db: DbConn, sceneId = DefaultSceneId): seq[TokenRec] =
## Every token of the scene, in creation order (rowid), which is the order egress walks. ## Every token of the scene, in creation order (rowid), which is the order egress walks.
for row in db.getAllRows(sql""" for row in db.getAllRows(sql"""
SELECT id, scene_id, kind, descriptive_name, actual_name, x, y, radius, owner_player_id, SELECT id, scene_id, kind, descriptive_name, actual_name, x, y, radius, owner_player_id,
gm_only, vision_radius, flags gm_only, vision_radius, flags, props_public, props_owner, props_gm
FROM entity WHERE scene_id = ? ORDER BY rowid""", sceneId): FROM entity WHERE scene_id = ? ORDER BY rowid""", sceneId):
result.add rowToToken(row) 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] = proc tokenIndex*(tokens: openArray[TokenRec], id: string): Option[int] =
for i, t in tokens: for i, t in tokens: