Files
FFF_vtt_frozen/server/db.nim
T

324 lines
18 KiB
Nim

## SQLite open + forward-only migration runner (DESIGN 4.4, H13). DDL and version rule FIXED
## owner-delegated, #16:
## - `schema_migration(version, name, applied_at)` is the history table; `PRAGMA user_version`
## carries the same latest version (external tools read it cheaply). They must agree, and
## history is contiguous from 1, otherwise startup refuses.
## - A DB whose user_version is above this build's latest is refused, never downgraded.
## - 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).
## 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` arrives with slice 7.
## Step 5 ("explored", M3 slice 6 / #21) creates `explored_chunk`, the chunked explored bitmaps
## (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
## 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.
## Step 7 ("characters", M3 slice 8 / #23) creates `character` (DESIGN 8: one owner, which is a real
## player id and may be the GM's, both names, `reveal_all`, the three property buckets), `name_reveal`
## (per-player reveal of one subject id: a character id or a plain token id, both from the token id
## alphabet) and `encountered` (the per-player "met before" snapshot of DESIGN 8: names, optional
## character link, no FK cascade so it survives token and character removal). It also adds
## `entity.character_id` (NULL = a plain token; the character a token figures) and
## `entity.reveal_all` for plain tokens, whose names the GM can reveal to everyone at once.
## `character.owner_player_id` has no cascade on purpose: 3.2 hands a removed player's characters to
## the GM, and `player.remove` reassigns them before the DELETE (a raw delete raises instead of
## orphaning a record). `name_reveal` and `encountered` DO cascade on the player, because 6.1 deletes
## that player's reveals and encountered list with them.
## Step 8 ("wall record", Walls r1 / #53) rebuilds `wall` into the typed record of DESIGN 8 and adds
## `marker_seen`. The legacy `kind` column is dropped, not preserved: every row is mapped to today's
## behaviour (thickness 0, centre, both blocks on, both-way sight, no marker/door settings; a legacy
## door keeps its `open`). `height` and `label` are nullable and written as SQL literals because
## db_connector cannot bind NULL (4.4). The step's `data` hook is the height backfill: every entity
## and character whose `props_gm` lacks a `height` key gets `1.8`, and nothing else is touched (5.7).
## One connection, used under the server's global lock (4.3); this module does no locking itself.
import std/[json, strutils, times]
import db_connector/db_sqlite
type
MigrationError* = object of CatchableError
## The DB cannot be brought to this build's schema: newer DB, inconsistent history, or a
## failed step (already rolled back).
Migration* = object
version*: int
name*: string
stmts*: seq[string]
## One or more DDL statements, run in order inside the step's transaction.
## db_connector's exec() prepares a single statement, so they cannot be one string.
data*: proc(db: DbConn) {.nimcall.}
## Optional in-transaction data hook for what SQL cannot express portably (step 8's height
## backfill). Runs after `stmts` and before the history row, inside the same transaction.
MigrationRow* = tuple[version: int, name: string]
proc backfillHeights(db: DbConn) =
## Migration step 8's `data` hook (DESIGN 4.4, 5.7): every existing token and character gets
## `height: 1.8` in its GM bucket when that bucket is a JSON object without a `height` key.
## `eye_height` is never written (the 93% rule derives it) and a hand-set height is untouched.
for table in ["entity", "character"]:
for row in db.getAllRows(sql("SELECT id, props_gm FROM " & table)):
var props: JsonNode
try:
props = parseJson(row[1])
except CatchableError:
continue # unreadable props are left exactly as they are
if props.isNil or props.kind != JObject or props.hasKey("height"):
continue
props["height"] = newJFloat(1.8)
db.exec(sql("UPDATE " & table & " SET props_gm = ? WHERE id = ?"), $props, row[0])
const
MigrationHistoryDdl* = """
CREATE TABLE IF NOT EXISTS schema_migration (
version INTEGER PRIMARY KEY,
name TEXT NOT NULL,
applied_at TEXT NOT NULL
)"""
migrations* = [
Migration(version: 1, name: "meta", stmts: @["""
CREATE TABLE meta (
k TEXT PRIMARY KEY,
v TEXT NOT NULL
)"""]),
Migration(version: 2, name: "auth", stmts: @["""
CREATE TABLE player (
id INTEGER PRIMARY KEY,
name TEXT UNIQUE, -- NULL until first sign-in; unique among players
role TEXT NOT NULL CHECK (role IN ('gm', 'player')),
colour TEXT NOT NULL,
created_at TEXT NOT NULL
)""", """
CREATE UNIQUE INDEX player_single_gm ON player(role) WHERE role = 'gm'""", """
CREATE TABLE player_key (
player_id INTEGER PRIMARY KEY REFERENCES player(id) ON DELETE CASCADE,
secret TEXT NOT NULL, -- plaintext: the GM can re-show it (Q11)
created_at TEXT NOT NULL
)""", """
CREATE TABLE session (
id INTEGER PRIMARY KEY,
player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE,
token_hash TEXT NOT NULL UNIQUE, -- SHA-256 of the cookie token; the token is never stored
created_at TEXT NOT NULL,
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, '{}')"""]),
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
)"""]),
Migration(version: 5, name: "explored", stmts: @["""
CREATE TABLE explored_chunk (
player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE,
scene_id INTEGER NOT NULL REFERENCES scene(id) ON DELETE CASCADE,
cx INTEGER NOT NULL, -- chunk coordinate: cell div 64 (server/explored.nim)
cy INTEGER NOT NULL,
bits BLOB NOT NULL CHECK (length(bits) = 512), -- 64x64 cells, LSB-first row-major
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)
)"""]),
Migration(version: 7, name: "characters", stmts: @["""
CREATE TABLE character (
id TEXT PRIMARY KEY, -- same 12-char alphabet and namespace as entity ids (8)
owner_player_id INTEGER NOT NULL REFERENCES player(id), -- always a real player id, GM included
descriptive_name TEXT NOT NULL,
actual_name TEXT NOT NULL,
reveal_all INTEGER NOT NULL DEFAULT 0 CHECK (reveal_all IN (0, 1)),
props_public TEXT NOT NULL DEFAULT '{}',
props_owner TEXT NOT NULL DEFAULT '{}',
props_gm TEXT NOT NULL DEFAULT '{}',
created_at TEXT NOT NULL
)""", """
CREATE INDEX character_owner ON character(owner_player_id)""", """
CREATE TABLE name_reveal (
player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE,
subject_id TEXT NOT NULL, -- a character id, or a plain token id (never both for one subject)
created_at TEXT NOT NULL,
PRIMARY KEY (player_id, subject_id)
)""", """
CREATE TABLE encountered (
player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE,
entity_id TEXT NOT NULL, -- no FK: the entry outlives the token (8)
character_id TEXT, -- NULL for a plain token; no FK, the entry outlives it too
descriptive_name TEXT NOT NULL, -- the snapshot of the name this player knows (8)
actual_name TEXT, -- NULL = this player has not been told the actual name
created_at TEXT NOT NULL,
PRIMARY KEY (player_id, entity_id)
)""", """
CREATE INDEX encountered_character ON encountered(character_id)""", """
ALTER TABLE entity ADD COLUMN character_id TEXT REFERENCES character(id)""", """
ALTER TABLE entity ADD COLUMN reveal_all INTEGER NOT NULL DEFAULT 0 CHECK (reveal_all IN (0, 1))"""]),
Migration(version: 8, name: "wall record", stmts: @["""
ALTER TABLE wall RENAME TO wall_v1""", """
CREATE TABLE wall (
scene_id INTEGER NOT NULL REFERENCES scene(id) ON DELETE CASCADE,
id INTEGER NOT NULL,
ax REAL NOT NULL, ay REAL NOT NULL,
bx REAL NOT NULL, by REAL NOT NULL,
thickness REAL NOT NULL DEFAULT 0 CHECK (thickness >= 0 AND thickness <= 256),
position TEXT NOT NULL DEFAULT 'center' CHECK (position IN ('center', 'left', 'right')),
blocks_sight INTEGER NOT NULL DEFAULT 1 CHECK (blocks_sight IN (0, 1)),
blocks_movement INTEGER NOT NULL DEFAULT 1 CHECK (blocks_movement IN (0, 1)),
sight_dir TEXT NOT NULL DEFAULT 'both' CHECK (sight_dir IN ('both', 'left', 'right')),
player_marker INTEGER NOT NULL DEFAULT 0 CHECK (player_marker IN (0, 1)),
door INTEGER NOT NULL DEFAULT 0 CHECK (door IN (0, 1)),
open INTEGER NOT NULL DEFAULT 0 CHECK (open IN (0, 1)),
secret INTEGER NOT NULL DEFAULT 0 CHECK (secret IN (0, 1)),
locked INTEGER NOT NULL DEFAULT 0 CHECK (locked IN (0, 1)),
height REAL NULL CHECK (height IS NULL OR (height > 0 AND height <= 100)),
label TEXT NULL CHECK (label IS NULL OR (length(label) >= 1 AND length(label) <= 64)),
flags TEXT NOT NULL DEFAULT '{}', -- JSON object, GM-defined, never interpreted
PRIMARY KEY (scene_id, id),
CHECK (open = 0 OR door = 1),
CHECK (secret = 0 OR (door = 1 AND open = 0 AND blocks_sight = 1 AND blocks_movement = 1
AND sight_dir = 'both')),
CHECK (locked = 0 OR door = 1),
CHECK (sight_dir = 'both' OR blocks_sight = 1)
)""", """
INSERT INTO wall (scene_id, id, ax, ay, bx, by, thickness, position, blocks_sight,
blocks_movement, sight_dir, player_marker, door, open, secret, locked,
height, label, flags)
SELECT scene_id, id, ax, ay, bx, by, 0, 'center', 1, 1, 'both', 0,
CASE kind WHEN 'door' THEN 1 ELSE 0 END,
CASE kind WHEN 'door' THEN open ELSE 0 END,
0, 0, NULL, NULL, flags
FROM wall_v1""", """
DROP TABLE wall_v1""", """
CREATE TABLE marker_seen (
player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE,
scene_id INTEGER NOT NULL,
wall_id INTEGER NOT NULL,
marker_id TEXT NOT NULL, -- the opaque per-player 12-character id on the wire
PRIMARY KEY (player_id, scene_id, wall_id),
UNIQUE (player_id, marker_id),
FOREIGN KEY (scene_id, wall_id) REFERENCES wall(scene_id, id) ON DELETE CASCADE
)"""], data: backfillHeights),
]
LatestVersion* = migrations[^1].version
## Derived, so adding a step cannot leave it stale.
proc openDatabase*(path: string): DbConn =
result = open(path, "", "", "")
discard result.getAllRows(sql"PRAGMA journal_mode=WAL")
result.exec(sql"PRAGMA synchronous=NORMAL")
result.exec(sql"PRAGMA busy_timeout=5000")
result.exec(sql"PRAGMA foreign_keys=ON")
proc schemaVersion*(db: DbConn): int =
parseInt(db.getValue(sql"PRAGMA user_version"))
template withTransaction*(db: DbConn, body: untyped) =
## One explicit transaction (DESIGN 4.2 step 6): COMMIT on success, ROLLBACK and re-raise on any
## failure. A template rather than a proc taking a closure: call sites run under the global lock
## inside `{.gcsafe.}` handlers, where a closure would need its own gcsafe proof.
db.exec(sql"BEGIN")
try:
body
db.exec(sql"COMMIT")
except CatchableError:
try: db.exec(sql"ROLLBACK")
except CatchableError: discard # the original error is the one worth reporting
raise
proc appliedMigrations*(db: DbConn): seq[MigrationRow] =
for r in db.getAllRows(sql"SELECT version, name FROM schema_migration ORDER BY version"):
result.add (version: parseInt(r[0]), name: r[1])
proc migrate*(db: DbConn): int =
## Applies every step above the DB's version; returns how many ran (0 for an up-to-date DB).
db.exec(sql(MigrationHistoryDdl))
let version = schemaVersion(db)
if version > LatestVersion:
raise newException(MigrationError,
"database schema version " & $version & " is newer than this server (" & $LatestVersion &
"); refusing to run")
let history = appliedMigrations(db)
var historyProblem = ""
if history.len != version:
historyProblem = "user_version=" & $version & " but history has " & $history.len & " steps"
else:
for i, row in history:
if row.version != i + 1:
historyProblem = "history is not contiguous from 1 (found " & $row.version & " at step " & $(i + 1) & ")"
elif row.version > migrations.len or row.name != migrations[row.version - 1].name:
historyProblem = "step " & $row.version & " is recorded as \"" & row.name & "\""
if historyProblem.len > 0:
raise newException(MigrationError, "schema_migration and user_version disagree: " & historyProblem)
for m in migrations:
if m.version <= version: continue
db.exec(sql"BEGIN")
try:
for stmt in m.stmts:
db.exec(sql(stmt))
if m.data != nil:
m.data(db)
let stamp = now().utc.format("yyyy-MM-dd'T'HH:mm:ss'Z'")
db.exec(sql"INSERT INTO schema_migration (version, name, applied_at) VALUES (?, ?, ?)",
m.version, m.name, stamp)
db.exec(sql("PRAGMA user_version = " & $m.version)) # PRAGMA does not take bound values
db.exec(sql"COMMIT")
inc result
except CatchableError as e:
try: db.exec(sql"ROLLBACK")
except CatchableError: discard # the original error is the one worth reporting
raise newException(MigrationError,
"migration " & $m.version & " (" & m.name & ") failed: " & e.msg)