server: scene and wall state, slice-4 migration (#19)
Migration step 3 ("world") creates scene and wall and seeds the single v1 scene
(id 1, 4096x4096, tile = cell 32, vision 400, token radius 20, art_version 1,
next_wall_id 1). server/world.nim holds the in-memory scene with SQLite as
write-through persistence: per-scene wall ids from next_wall_id (monotonic,
never reused, #3), 6.1 validation (a != b, in bounds, a wall is never open),
flags as an opaque JSON object, and one transaction with synchronous=FULL
around every GM authoring write (Q12); memory follows COMMIT, so a failed
write leaves both sides unchanged.
Tests: tests/tworld.nim (ids, reload, doors, validation, pragma, failed write),
tests/tdb.nim (version 3, history, a slice-2 DB migrating to slice 3).
This commit is contained in:
@@ -7,6 +7,9 @@
|
||||
## - One transaction per step: DDL + history row + user_version together. A failing step leaves
|
||||
## nothing behind; a fully migrated DB is not written to at all (re-open is a no-op).
|
||||
## - Engine settings: WAL, synchronous=NORMAL (Q12), busy_timeout=5000, foreign_keys=ON.
|
||||
## 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).
|
||||
## 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
|
||||
@@ -58,6 +61,35 @@ CREATE TABLE session (
|
||||
last_seen TEXT NOT NULL
|
||||
)""", """
|
||||
CREATE INDEX session_player ON session(player_id)"""]),
|
||||
Migration(version: 3, name: "world", stmts: @["""
|
||||
CREATE TABLE scene (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
w REAL NOT NULL,
|
||||
h REAL NOT NULL,
|
||||
tile_size INTEGER NOT NULL, -- px; == cell in v1 (Q4)
|
||||
cell INTEGER NOT NULL, -- explored cell px; tile_size % cell == 0
|
||||
grid_size REAL NOT NULL, -- px; 0 = no grid
|
||||
vision_radius_default REAL NOT NULL, -- px; also the player step cap (5.5)
|
||||
token_radius_default REAL NOT NULL, -- px; token size when the token sets none (#4)
|
||||
art_version INTEGER NOT NULL, -- tiles URL version; 1 in M3 (3.3)
|
||||
active INTEGER NOT NULL DEFAULT 1,
|
||||
next_wall_id INTEGER NOT NULL DEFAULT 1, -- monotonic, never reused (#3, 8)
|
||||
extra TEXT NOT NULL DEFAULT '{}'
|
||||
)""", """
|
||||
CREATE TABLE wall (
|
||||
scene_id INTEGER NOT NULL REFERENCES scene(id) ON DELETE CASCADE,
|
||||
id INTEGER NOT NULL, -- per scene, from next_wall_id (#3, 8)
|
||||
ax REAL NOT NULL, ay REAL NOT NULL,
|
||||
bx REAL NOT NULL, by REAL NOT NULL,
|
||||
kind TEXT NOT NULL CHECK (kind IN ('wall', 'door')),
|
||||
open INTEGER NOT NULL DEFAULT 0 CHECK (open IN (0, 1)),
|
||||
flags TEXT NOT NULL DEFAULT '{}', -- JSON object, GM-defined, never interpreted
|
||||
PRIMARY KEY (scene_id, id)
|
||||
)""", """
|
||||
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, '{}')"""]),
|
||||
]
|
||||
LatestVersion* = migrations[^1].version
|
||||
## Derived, so adding a step cannot leave it stale.
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
## Scene and wall state: the authoring half of the world (DESIGN 3.1, 4.1, 4.2, 4.4, 6.1, 8;
|
||||
## M3 slice 4, issue #19). In-memory authoritative state, SQLite as write-through persistence: rows
|
||||
## are read once at startup (`loadScene`) and never queried at runtime for reads.
|
||||
##
|
||||
## Walls (DESIGN 8, FIXED #3): per-scene ids from `scene.next_wall_id`, monotonic and never reused
|
||||
## (a removal leaves the counter alone). Identity is `(scene, id)` in the DB, in memory and on the
|
||||
## wire. Doors are walls with `kind = door`; `blocks = not (kind == door and open)` comes from
|
||||
## geometry.Wall when slice 5 feeds the vision code. `flags` is a free JSON object the server never
|
||||
## interprets (M6/Beyond: window, one-way, secret door live there).
|
||||
##
|
||||
## Wire payload shapes are DESIGN 6.1; the parts it leaves open are fixed here (recorded FIXED
|
||||
## owner-delegated, #19, in DESIGN 6.1/14):
|
||||
## - `scene` is an integer id; in v1 it is always the one seeded scene (id 1), and any other value
|
||||
## is `not-found` (no existence oracle either way: only the GM can send these intents).
|
||||
## - `wall.add`: `open` omitted = false; `open` on a `kind: "wall"` is `invalid` (a wall is never
|
||||
## open), and the stored row normalizes it to false regardless.
|
||||
## - `wall.update` patches `a`, `b`, `kind`, `flags` only (`open` belongs to `door.set`; an `open`
|
||||
## field here is an unknown field and is ignored); at least one patch field is required, else
|
||||
## `invalid`. Changing `kind` door -> wall closes the door.
|
||||
## - `a != b` (a zero-length wall is refused) and both endpoints inside `[0,w] x [0,h]`.
|
||||
## - `flags` must be a JSON object; omitted = `{}`. Coordinates must be finite numbers.
|
||||
##
|
||||
## Persistence order (4.2 step 6): a wall write runs in one transaction with `synchronous=FULL`
|
||||
## around it (Q12 FIXED: GM authoring is the expensive-to-lose data) and the in-memory state is
|
||||
## updated only after COMMIT, so a failing write leaves memory and DB identical. This module does
|
||||
## no locking: the caller holds the global lock (4.3).
|
||||
import std/[json, math, options, strutils]
|
||||
import db_connector/db_sqlite
|
||||
import geometry
|
||||
|
||||
type
|
||||
WallKind* = enum
|
||||
wkWall = "wall"
|
||||
wkDoor = "door"
|
||||
|
||||
WallRec* = object
|
||||
id*: int
|
||||
a*, b*: Vec
|
||||
kind*: WallKind
|
||||
open*: bool
|
||||
flags*: JsonNode ## JObject; never nil for a loaded or created wall
|
||||
|
||||
SceneRec* = object
|
||||
## The one v1 scene (Q3 FIXED). Walls are kept in id order (ids only grow, appends only).
|
||||
id*: int
|
||||
name*: string
|
||||
w*, h*: float
|
||||
tileSize*, cell*: int
|
||||
gridSize*: float
|
||||
visionRadiusDefault*, tokenRadiusDefault*: float
|
||||
artVersion*: int
|
||||
nextWallId*: int
|
||||
extra*: JsonNode
|
||||
walls*: seq[WallRec]
|
||||
|
||||
WallApply* = enum
|
||||
## Outcome of a persistent wall operation; main.nim maps it to the 6.5 codes.
|
||||
waOk
|
||||
waInvalid ## geometry/field semantics: `invalid`
|
||||
waNotFound ## no such wall in the scene: `not-found`
|
||||
waNotDoor ## door.set on a plain wall: `invalid`
|
||||
|
||||
WallPatch* = object
|
||||
## The updatable fields of `wall.update` (DESIGN 6.1); none = the field keeps its value.
|
||||
a*, b*: Option[Vec]
|
||||
kind*: Option[WallKind]
|
||||
flags*: Option[JsonNode]
|
||||
|
||||
SceneError* = object of CatchableError
|
||||
## The DB and this build disagree about the scene (missing seed, unreadable row).
|
||||
|
||||
const
|
||||
DefaultSceneId* = 1
|
||||
## The seeded v1 scene (migration step 3). Exactly one scene exists in v1 (Q3).
|
||||
WallKinds* = [wkWall, wkDoor]
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------
|
||||
# Field parsing (DESIGN 6.1 field notes: px floats, missing or wrongly typed -> `invalid`)
|
||||
|
||||
proc parseKind*(raw: string): Option[WallKind] =
|
||||
for k in WallKinds:
|
||||
if $k == raw: return some(k)
|
||||
|
||||
proc parseVec*(node: JsonNode): Option[Vec] =
|
||||
## `a:[x,y]` / `b:[x,y]`: exactly two finite JSON numbers.
|
||||
if node.isNil or node.kind != JArray or node.len != 2: return none(Vec)
|
||||
var v: Vec
|
||||
for i, field in [node[0], node[1]]:
|
||||
var f: float
|
||||
case field.kind
|
||||
of JInt: f = float(field.getInt)
|
||||
of JFloat: f = field.getFloat
|
||||
else: return none(Vec)
|
||||
if classify(f) in {fcNan, fcInf, fcNegInf}: return none(Vec)
|
||||
if i == 0: v.x = f else: v.y = f
|
||||
some(v)
|
||||
|
||||
proc parseFlags*(node: JsonNode): Option[JsonNode] =
|
||||
## `flags?`: an object or absent (DESIGN 6.1). A non-object is `invalid`.
|
||||
if node.isNil: return some(newJObject())
|
||||
if node.kind != JObject: return none(JsonNode)
|
||||
some(node)
|
||||
|
||||
proc parseOpen*(node: JsonNode): Option[bool] =
|
||||
## `open?`: a boolean or absent (= false).
|
||||
if node.isNil: return some(false)
|
||||
if node.kind != JBool: return none(bool)
|
||||
some(node.getBool)
|
||||
|
||||
proc fieldOrNull*(env: JsonNode, key: string): JsonNode =
|
||||
## `undefined` and `null` are both "field absent" for the wall payloads.
|
||||
if env.isNil: return nil
|
||||
result = env{key}
|
||||
if not result.isNil and result.kind == JNull: result = nil
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------
|
||||
# In-memory rules (pure): validation, lookup and the id allocator
|
||||
|
||||
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 validWall*(sc: SceneRec, rec: WallRec): bool =
|
||||
## DESIGN 6.1 `wall.*` validation: `a != b`, both endpoints in bounds. `kind` and `flags` are
|
||||
## checked by the parsers, so a `WallRec` can only carry valid ones.
|
||||
(rec.a.x != rec.b.x or rec.a.y != rec.b.y) and inBounds(sc, rec.a) and inBounds(sc, rec.b)
|
||||
|
||||
proc normalize*(rec: WallRec): WallRec =
|
||||
## A wall is never open; only a door can be.
|
||||
result = rec
|
||||
if result.kind == wkWall: result.open = false
|
||||
if result.flags.isNil: result.flags = newJObject()
|
||||
|
||||
proc wallIndex*(sc: SceneRec, id: int): Option[int] =
|
||||
for i, w in sc.walls:
|
||||
if w.id == id: return some(i)
|
||||
|
||||
proc wallById*(sc: SceneRec, id: int): Option[WallRec] =
|
||||
let i = wallIndex(sc, id)
|
||||
if i.isSome: return some(sc.walls[i.get])
|
||||
|
||||
proc patched*(w: WallRec, patch: WallPatch): WallRec =
|
||||
## `wall.update` candidate: the stored row with the patch applied (open untouched).
|
||||
result = w
|
||||
if patch.a.isSome: result.a = patch.a.get
|
||||
if patch.b.isSome: result.b = patch.b.get
|
||||
if patch.kind.isSome: result.kind = patch.kind.get
|
||||
if patch.flags.isSome: result.flags = patch.flags.get
|
||||
result = normalize(result)
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------
|
||||
# Persistence (write-through, synchronous=FULL around the transaction, Q12)
|
||||
|
||||
proc flagsText(node: JsonNode): string =
|
||||
if node.isNil: "{}" else: $node
|
||||
|
||||
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.
|
||||
db.exec(sql"PRAGMA synchronous=FULL")
|
||||
try:
|
||||
db.exec(sql"BEGIN")
|
||||
try:
|
||||
body
|
||||
db.exec(sql"COMMIT")
|
||||
except CatchableError:
|
||||
try: db.exec(sql"ROLLBACK")
|
||||
except CatchableError: discard
|
||||
raise
|
||||
finally:
|
||||
db.exec(sql"PRAGMA synchronous=NORMAL")
|
||||
|
||||
proc insertRow(db: DbConn, sceneId: int, w: WallRec) =
|
||||
db.exec(sql"""INSERT INTO wall (scene_id, id, ax, ay, bx, by, kind, open, flags)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||
sceneId, w.id, w.a.x, w.a.y, w.b.x, w.b.y, $w.kind,
|
||||
(if w.open: 1 else: 0), flagsText(w.flags))
|
||||
|
||||
proc replaceRow(db: DbConn, sceneId: int, w: WallRec) =
|
||||
db.exec(sql"""UPDATE wall SET ax = ?, ay = ?, bx = ?, by = ?, kind = ?, open = ?, flags = ?
|
||||
WHERE scene_id = ? AND id = ?""",
|
||||
w.a.x, w.a.y, w.b.x, w.b.y, $w.kind, (if w.open: 1 else: 0), flagsText(w.flags),
|
||||
sceneId, w.id)
|
||||
|
||||
proc addWall*(db: DbConn, sc: var SceneRec, rec: WallRec): Option[int] =
|
||||
## `wall.add`: assigns the scene's next wall id, persists and then appends to memory.
|
||||
## none = invalid geometry (nothing written, nothing applied).
|
||||
let candidate = normalize(rec)
|
||||
if not validWall(sc, candidate): return none(int)
|
||||
var stored = candidate
|
||||
stored.id = max(1, sc.nextWallId)
|
||||
authoringTransaction(db):
|
||||
insertRow(db, sc.id, stored)
|
||||
db.exec(sql"UPDATE scene SET next_wall_id = ? WHERE id = ?", stored.id + 1, sc.id)
|
||||
sc.walls.add stored
|
||||
sc.nextWallId = stored.id + 1
|
||||
some(stored.id)
|
||||
|
||||
proc updateWall*(db: DbConn, sc: var SceneRec, rec: WallRec): WallApply =
|
||||
## `wall.update` = full replacement of the patched row (`remove + add` for the 5.5 status rules,
|
||||
## which slice 5 re-evaluates). A kind change door -> wall closes the door.
|
||||
let idx = wallIndex(sc, rec.id)
|
||||
if idx.isNone: return waNotFound
|
||||
let stored = normalize(rec)
|
||||
if not validWall(sc, stored): return waInvalid
|
||||
authoringTransaction(db):
|
||||
replaceRow(db, sc.id, stored)
|
||||
sc.walls[idx.get] = stored
|
||||
waOk
|
||||
|
||||
proc removeWall*(db: DbConn, sc: var SceneRec, id: int): WallApply =
|
||||
## `wall.remove`: the row goes, `next_wall_id` does not move (ids are never reused).
|
||||
let idx = wallIndex(sc, id)
|
||||
if idx.isNone: return waNotFound
|
||||
authoringTransaction(db):
|
||||
db.exec(sql"DELETE FROM wall WHERE scene_id = ? AND id = ?", sc.id, id)
|
||||
sc.walls.delete idx.get
|
||||
waOk
|
||||
|
||||
proc setDoor*(db: DbConn, sc: var SceneRec, id: int, open: bool): WallApply =
|
||||
## `door.set`: only a door can be opened or closed (`invalid` on a plain wall).
|
||||
let idx = wallIndex(sc, id)
|
||||
if idx.isNone: return waNotFound
|
||||
if sc.walls[idx.get].kind != wkDoor: return waNotDoor
|
||||
var stored = sc.walls[idx.get]
|
||||
stored.open = open
|
||||
authoringTransaction(db):
|
||||
db.exec(sql"UPDATE wall SET open = ? WHERE scene_id = ? AND id = ?",
|
||||
(if open: 1 else: 0), sc.id, id)
|
||||
sc.walls[idx.get] = stored
|
||||
waOk
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------
|
||||
# Loading (4.4 Startup: load everything into memory once)
|
||||
|
||||
proc rowToWall(row: Row): WallRec =
|
||||
var flags: JsonNode
|
||||
try:
|
||||
flags = parseJson(row[7])
|
||||
except CatchableError:
|
||||
flags = newJObject()
|
||||
if flags.isNil or flags.kind != JObject: flags = newJObject()
|
||||
WallRec(id: parseInt(row[0]),
|
||||
a: (parseFloat(row[1]), parseFloat(row[2])),
|
||||
b: (parseFloat(row[3]), parseFloat(row[4])),
|
||||
kind: parseEnum[WallKind](row[5]),
|
||||
open: row[6] == "1",
|
||||
flags: flags)
|
||||
|
||||
proc loadScene*(db: DbConn, sceneId = DefaultSceneId): Option[SceneRec] =
|
||||
## The single scene and its walls, ordered by wall id. none = the scene row is missing (a DB that
|
||||
## migration 3 did not seed): startup treats that as fatal.
|
||||
for row in db.getAllRows(sql"""
|
||||
SELECT id, name, w, h, tile_size, cell, grid_size, vision_radius_default,
|
||||
token_radius_default, art_version, next_wall_id, extra
|
||||
FROM scene WHERE id = ?""", sceneId):
|
||||
var extra: JsonNode
|
||||
try:
|
||||
extra = parseJson(row[11])
|
||||
except CatchableError:
|
||||
extra = newJObject()
|
||||
if extra.isNil: extra = newJObject()
|
||||
result = some(SceneRec(id: parseInt(row[0]), name: row[1],
|
||||
w: parseFloat(row[2]), h: parseFloat(row[3]),
|
||||
tileSize: parseInt(row[4]), cell: parseInt(row[5]),
|
||||
gridSize: parseFloat(row[6]),
|
||||
visionRadiusDefault: parseFloat(row[7]),
|
||||
tokenRadiusDefault: parseFloat(row[8]),
|
||||
artVersion: parseInt(row[9]),
|
||||
nextWallId: parseInt(row[10]),
|
||||
extra: extra))
|
||||
if result.isNone: return
|
||||
var sc = result.get
|
||||
for row in db.getAllRows(sql"""
|
||||
SELECT id, ax, ay, bx, by, kind, open, flags
|
||||
FROM wall WHERE scene_id = ? ORDER BY id""", sceneId):
|
||||
sc.walls.add rowToWall(row)
|
||||
result = some(sc)
|
||||
|
||||
proc sceneCount*(db: DbConn): int =
|
||||
parseInt(db.getValue(sql"SELECT count(*) FROM scene"))
|
||||
Reference in New Issue
Block a user