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:
+162
-38
@@ -7,10 +7,17 @@
|
||||
## 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.
|
||||
## 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
|
||||
@@ -18,16 +25,30 @@
|
||||
## 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]
|
||||
## 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, geometry, world
|
||||
import crypto, 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
|
||||
@@ -35,14 +56,17 @@ type
|
||||
descriptiveName*: string
|
||||
actualName*: string
|
||||
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
|
||||
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`
|
||||
@@ -71,21 +95,12 @@ const
|
||||
# ---------------------------------------------------------------------------------------------------
|
||||
# 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).
|
||||
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
|
||||
@@ -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])
|
||||
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)
|
||||
@@ -116,10 +193,13 @@ proc freshId*(taken: openArray[string]): string =
|
||||
if not clash: return
|
||||
|
||||
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
|
||||
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`.
|
||||
@@ -142,8 +222,12 @@ proc inBounds(sc: SceneRec, p: Vec): bool =
|
||||
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.
|
||||
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 =
|
||||
result = t
|
||||
@@ -167,22 +251,41 @@ proc sqlLit(v: Option[float]): string =
|
||||
proc sqlLitOwner(owner: int): string =
|
||||
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) =
|
||||
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.visionRadius) & ", ?, ?)"),
|
||||
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,
|
||||
$t.props[pbPublic], $t.props[pbOwner], $t.props[pbGm],
|
||||
now().utc.format("yyyy-MM-dd'T'HH:mm:ss'Z'"))
|
||||
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 = ?" &
|
||||
" WHERE id = ?"),
|
||||
", gm_only = ?, vision_radius = " & sqlLit(t.visionRadius) & ", flags = ?," &
|
||||
" props_public = ?, props_owner = ?, props_gm = ? WHERE id = ?"),
|
||||
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]):
|
||||
tuple[outcome: TokenOutcome, token: TokenRec] =
|
||||
@@ -197,9 +300,10 @@ proc addToken*(db: DbConn, sc: SceneRec, candidate: TokenRec, takenIds: openArra
|
||||
(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)
|
||||
## `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
|
||||
@@ -226,27 +330,47 @@ proc clearOwnership*(db: DbConn, playerId: int) =
|
||||
proc optFloat(s: string): Option[float] =
|
||||
if s.len == 0: none(float) else: some(parseFloat(s))
|
||||
|
||||
proc rowToToken(row: Row): TokenRec =
|
||||
var flags: JsonNode
|
||||
proc parseObject(s: string): JsonNode =
|
||||
## A stored JSON object; a hand-edited or truncated value must not crash the server.
|
||||
try:
|
||||
flags = parseJson(row[11])
|
||||
result = parseJson(s)
|
||||
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],
|
||||
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)
|
||||
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] =
|
||||
## 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
|
||||
gm_only, vision_radius, flags, props_public, props_owner, props_gm
|
||||
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:
|
||||
|
||||
Reference in New Issue
Block a user