diff --git a/docs/DESIGN.md b/docs/DESIGN.md index cdb09b9..29d1923 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -632,9 +632,10 @@ explored_chunk(player_id, scene_id, cx, cy, bits BLOB, PRIMARY KEY(player_id, sc 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 - '{}', 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))` + '{}', PRIMARY KEY (scene_id, id), CHECK (open = 0 OR door = 1), CHECK (open = 0 OR locked = 0), + 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))` 3. `INSERT INTO wall (...) SELECT ..., 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` — every existing wall becomes today's behaviour: `thickness 0`, `position center`, @@ -659,8 +660,8 @@ explored_chunk(player_id, scene_id, cx, cy, bits BLOB, PRIMARY KEY(player_id, sc answer (5.7). - **`label` and `height` NULL binding:** db_connector quotes every bound argument as text and cannot bind NULL, so both columns are written as SQL literals (`NULL` when absent) by one helper - in `server/world.nim` (`world.sqlLitText` doubles `'`; a real is formatted with a fixed - locale-free form). The `''`-for-NULL trick used by `encountered.actual_name` does not apply: + in `server/db.nim` (`db.sqlLitText` doubles `'` and refuses NUL or other control characters; a + real is formatted with a fixed locale-free form). The `''`-for-NULL trick used by `encountered.actual_name` does not apply: `''` is not a legal label (`1..64`) and `0` is not a legal height (`> 0`), so a sentinel would make the load path lie about the domain. - **Startup and write timing:** `marker_seen` rows are loaded per player with the explored chunks @@ -1394,7 +1395,9 @@ switch a boolean and `sight_dir` one of `both|left|right`, with a non-`both` `si `blocks_sight:true` (#47); `open`/`secret`/`locked` only with `door`; a secret door closed, two-way and opaque (`blocks_sight` and `blocks_movement` both true); `open:true` with `secret` or `locked` is `invalid` (#46, 5.8); `label` an optional 6.5 text string of 1..64 code points, or `null`; -`preset` is `wall|door|window|one_way` and never with a raw switch in the same payload (5.8, #48). +`preset` is `wall|door|window|one_way` and never with any raw switch or setting in the same +payload — including `open:false`: the payload is preset XOR raw, and any raw field beside a preset +is `invalid` (5.8, #48). **One expand-and-validate path [FIXED (owner-delegated), 2026-11-17, #49]:** `wall.add`, `wall.update` and the M6 UVTT importer build the same candidate (geometry + expanded switches + label) and run the same validation function; a preset is expanded before validation and sets only @@ -1433,8 +1436,8 @@ switches, never `thickness`, `position` or `height` (#50). `label`), and a `preset` replaces the whole switch set, so `preset:"door"` on a window turns it into a closed opaque door, and `preset:"window"` sets `player_marker:true` as part of the expansion. `open` is not a patch field: it belongs to `door.set`, and an `open` field in - `wall.update` is an unknown field (ignored, 6.2; a `preset` carrying `open:true` is `invalid` as - above). Fields are checked before the target lookup (6.5 steps 7 then 8), so a fieldless + `wall.update` is an unknown field (ignored, 6.2) when it stands alone; beside a `preset`, any raw + switch or setting is `invalid`, `open:false` included (preset XOR raw, above). Fields are checked before the target lookup (6.5 steps 7 then 8), so a fieldless `wall.update` is `invalid` whatever the id. - `id` is an integer; lookup failures are `not-found` (a GM's missing target, 6.5 step 8). `door.set` on a row whose `door` is false is `invalid`, and so is `open:true` on a secret door diff --git a/server/db.nim b/server/db.nim index a6fadea..7b39f3b 100644 --- a/server/db.nim +++ b/server/db.nim @@ -41,7 +41,7 @@ ## 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 std/[json, options, strutils, times] import db_connector/db_sqlite type @@ -59,6 +59,22 @@ type ## backfill). Runs after `stmts` and before the history row, inside the same transaction. MigrationRow* = tuple[version: int, name: string] +proc sqlLitText*(value: string): string = + ## A SQL text literal (DESIGN 4.4): single quotes doubled. + ## + ## Precondition, enforced here rather than left to the caller: `value` contains no NUL or other + ## control character. db_connector cannot bind NULL and callers may pass GM-authored text, so + ## this helper refuses a value whose control characters could corrupt the statement; a raise is + ## a bug in the caller, never a way to smuggle one past validation. + for c in value: + if c.ord < 0x20 or c.ord == 0x7F: + raise newException(ValueError, "SQL text literal contains a control character") + "'" & value.replace("'", "''") & "'" + +proc sqlLitTextOrNull*(value: Option[string]): string = + ## `sqlLitText`, or `NULL` for an absent value. + if value.isSome: sqlLitText(value.get) else: "NULL" + 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. @@ -68,8 +84,12 @@ proc backfillHeights(db: DbConn) = var props: JsonNode try: props = parseJson(row[1]) - except CatchableError: - continue # unreadable props are left exactly as they are + except CatchableError as e: + # DESIGN 4.4: a failing step rolls back completely. A row whose props_gm is not JSON means + # the backfill cannot decide, so the step fails instead of leaving that row stale. + raise newException(ValueError, + "migration 8 height backfill: " & table & " row " & row[0] & + " has malformed props_gm: " & e.msg) if props.isNil or props.kind != JObject or props.hasKey("height"): continue props["height"] = newJFloat(1.8) diff --git a/server/main.nim b/server/main.nim index 630d3e6..80a086b 100644 --- a/server/main.nim +++ b/server/main.nim @@ -355,9 +355,12 @@ proc resync(connId: int, named: bool, player: Player) = refreshPlayer(player.id) # A marker minted here (a window the player had not seen before connecting) must be durable like # any other derived memory before the resync sends it (5.8, 4.2 step 6). Only markers: the - # explored grid keeps its own existing connect behaviour (nothing is stored here). - app.db.withTransaction: - persistMarkers(@[player.id]) + # explored grid keeps its own existing connect behaviour (nothing is stored here). No + # transaction when there is nothing to write: the common connect must not open one. + if app.visions.mgetOrPut(player.id, PlayerVision()).markerDead.len > 0 or + app.visions.mgetOrPut(player.id, PlayerVision()).markerFresh.len > 0: + app.db.withTransaction: + persistMarkers(@[player.id]) # A token visible right now is a sighting: record it before the `encountered` list is built (the # player may have been offline while something walked into their sight). recordEncounters() @@ -522,83 +525,12 @@ proc declared(env: Envelope, key: string): bool = # they are unknown fields and ignored (6.2). Absent and JSON null are the same field-absent for # every wall field except `height` and `label`, where an explicit null means "clear it". -proc parseWallGeometry(env: Envelope, rec: var WallRec): bool = - ## thickness (px), position and height (metres); the ranges are checked by `validWall`. - if present(env, "thickness"): - let v = parseFinite(fieldOrNull(env.node, "thickness")) - if v.isNone: return false - rec.thickness = v.get - if present(env, "position"): - let node = env.node{"position"} - if node.kind != JString: return false - let p = parsePosition(node.getStr) - if p.isNone: return false - rec.position = p.get - if declared(env, "height"): - let node = env.node{"height"} - if node.kind == JNull: - rec.height = none(float) - else: - let v = parseFinite(node) - if v.isNone: return false - rec.height = v - true - -proc parseWallLabel(env: Envelope, rec: var WallRec): bool = - ## `label` absent leaves it alone on an update (the caller seeds `rec` from the stored row); - ## an explicit null clears it; anything but a string is `invalid`. The 6.5 text rule (trimmed, - ## 1..64 code points, no control characters) is enforced by `validWall` before the write (#55). - if not declared(env, "label"): return true - let node = env.node{"label"} - if node.kind == JNull: - rec.label = none(string) - elif node.kind == JString: - rec.label = some(node.getStr) - else: - return false - true - -proc parseWallPreset(env: Envelope, dest: var Option[Preset]): bool = - ## `preset` is a 5.8 name, never JSON null; anything else is `invalid`. - if not declared(env, "preset"): return true - let node = env.node{"preset"} - if node.kind != JString: return false - let p = parsePreset(node.getStr) - if p.isNone: return false - dest = p - true - -proc parseWallSwitch(env: Envelope, key: string, dest: var Option[bool]): bool = - ## One raw switch: absent = not patched; a non-boolean is `invalid`. - if not present(env, key): return true - var bit: bool - if not boolField(env, key, bit): return false - dest = some(bit) - true - -proc parseWallSwitches(env: Envelope, sw: var WallSwitches, allowOpen: bool): bool = - ## Collects the raw 5.8 switches the payload names. `open` is collected only on a create; in an - ## update it is an unknown field and is ignored (`door.set` owns it, DESIGN 6.1). - if not parseWallSwitch(env, "blocks_sight", sw.blocksSight): return false - if not parseWallSwitch(env, "blocks_movement", sw.blocksMovement): return false - if not parseWallSwitch(env, "player_marker", sw.playerMarker): return false - if not parseWallSwitch(env, "door", sw.door): return false - if allowOpen and not parseWallSwitch(env, "open", sw.open): return false - if not parseWallSwitch(env, "secret", sw.secret): return false - if not parseWallSwitch(env, "locked", sw.locked): return false - if present(env, "sight_dir"): - let node = env.node{"sight_dir"} - if node.kind != JString: return false - let d = parseSightDir(node.getStr) - if d.isNone: return false - sw.sightDir = d - true - -proc parseWallPatch(env: Envelope, patch: var WallPatch): bool = - ## `wall.update` names only the fields it patches. `open` and `kind` are unknown here and are - ## ignored: a door's open state changes only through `door.set` (DESIGN 6.1, #54). A preset - ## replaces the whole switch set and may not appear with any raw switch, `open` included (#55). - if not parseWallPreset(env, patch.preset): return false +proc parseWallGeometryAndLabel(env: Envelope, patch: var WallPatch): bool = + ## THE one parser for the geometry and label fields of `wall.add` and `wall.update` (6.1). + ## One rule for both payloads: `a`, `b`, `thickness` and `position` treat absent and JSON null as + ## the same field-absent, while `height` and `label` treat an explicit null as a real patch + ## ("clear it"), carried by `clearHeight`/`clearLabel`. Ranges and the 6.5 text rule are checked + ## once on the resulting wall by `validWall`. if present(env, "a"): let v = parseVec(env.node{"a"}) if v.isNone: return false @@ -633,9 +565,54 @@ proc parseWallPatch(env: Envelope, patch: var WallPatch): bool = patch.label = some(node.getStr) else: return false - if not parseWallSwitches(env, patch.switches, false): return false - if patch.preset.isSome and (patch.switches.hasAnySwitch or declared(env, "open")): - # preset xor raw switches; an `open` field alongside a preset is `invalid` even though open is + true + +proc parseWallPreset(env: Envelope, dest: var Option[Preset]): bool = + ## `preset` is a 5.8 name, never JSON null; anything else is `invalid`. + if not declared(env, "preset"): return true + let node = env.node{"preset"} + if node.kind != JString: return false + let p = parsePreset(node.getStr) + if p.isNone: return false + dest = p + true + +proc parseWallSetting(env: Envelope, key: string, dest: var Option[bool]): bool = + ## One raw setting: absent = not patched; a non-boolean is `invalid`. + if not present(env, key): return true + var bit: bool + if not boolField(env, key, bit): return false + dest = some(bit) + true + +proc parseWallSettings(env: Envelope, sw: var WallSettings, allowOpen: bool): bool = + ## Collects the raw 5.8 settings the payload names. `open` is collected only on a create; in an + ## update it is an unknown field and is ignored (`door.set` owns it, DESIGN 6.1). + if not parseWallSetting(env, "blocks_sight", sw.blocksSight): return false + if not parseWallSetting(env, "blocks_movement", sw.blocksMovement): return false + if not parseWallSetting(env, "player_marker", sw.playerMarker): return false + if not parseWallSetting(env, "door", sw.door): return false + if allowOpen and not parseWallSetting(env, "open", sw.open): return false + if not parseWallSetting(env, "secret", sw.secret): return false + if not parseWallSetting(env, "locked", sw.locked): return false + if present(env, "sight_dir"): + let node = env.node{"sight_dir"} + if node.kind != JString: return false + let d = parseSightDir(node.getStr) + if d.isNone: return false + sw.sightDir = d + true + +proc parseWallPatch(env: Envelope, patch: var WallPatch, allowOpen = false): bool = + ## The one wall-field parser: `wall.update` and, with `allowOpen`, `wall.add`. `open` and `kind` + ## are unknown on an update and are ignored: a door's open state changes only through `door.set` + ## (DESIGN 6.1, #54). A preset replaces the whole setting set and may not appear with any raw + ## setting, `open` included (`open:false` too, #55). + if not parseWallGeometryAndLabel(env, patch): return false + if not parseWallPreset(env, patch.preset): return false + if not parseWallSettings(env, patch.settings, allowOpen): return false + if patch.preset.isSome and (patch.settings.hasAnySetting or declared(env, "open")): + # preset xor raw settings; an `open` field alongside a preset is `invalid` even though open is # otherwise an ignored unknown field on an update (DESIGN 6.1, #55). return false if present(env, "flags"): @@ -647,7 +624,7 @@ proc parseWallPatch(env: Envelope, patch: var WallPatch): bool = proc wallPatchHasField(patch: WallPatch): bool = patch.a.isSome or patch.b.isSome or patch.thickness.isSome or patch.position.isSome or patch.height.isSome or patch.clearHeight or patch.label.isSome or patch.clearLabel or - patch.preset.isSome or patch.switches.hasAnySwitch or patch.flags.isSome + patch.preset.isSome or patch.settings.hasAnySetting or patch.flags.isSome type ControllerCheck = enum @@ -2057,29 +2034,24 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = of "wall.add": if not sceneOk(conn, env): return - let a = parseVec(fieldOrNull(env.node, "a")) - let b = parseVec(fieldOrNull(env.node, "b")) - if a.isNone or b.isNone: + # One parser for add and update. A raw-setting create starts from the `wall` defaults; a preset + # replaces the setting set. Both go through the same expand-and-validate path (DESIGN 6.1, + # #55); `a` and `b` are the only required fields here. + var patch: WallPatch + if not parseWallPatch(env, patch, allowOpen = true): ackErr(conn, env.reqId, CodeInvalid) return - # A raw-switch create starts from the `wall` defaults; a preset replaces the switch set. Both - # go through the same expand-and-validate path (DESIGN 6.1, #55). - var candidate = defaultWall(a.get, b.get) - var preset: Option[Preset] - var switches: WallSwitches - if not parseWallGeometry(env, candidate) or not parseWallPreset(env, preset) or - not parseWallSwitches(env, switches, true) or not parseWallLabel(env, candidate): + if patch.a.isNone or patch.b.isNone: ackErr(conn, env.reqId, CodeInvalid) return - let resolved = resolveWall(candidate, preset, switches) + let resolved = patched(defaultWall(patch.a.get, patch.b.get), patch) if resolved.isNone: ackErr(conn, env.reqId, CodeInvalid) return - candidate = resolved.get - let flags = parseFlags(fieldOrNull(env.node, "flags")) - if flags.isNone: - ackErr(conn, env.reqId, CodeInvalid) - return + var candidate = resolved.get + # `label` is the intent's string: copy it at the boundary so the stored wall shares no payload + # with the request (ANALYSIS 4.1, jsonbound). + if candidate.label.isSome: candidate.label = some(detachedString(candidate.label.get)) var addedId = 0 var addedKind = "" var sceneId = 0 @@ -2089,7 +2061,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = # The record is copied here so its `flags` object and the record copy both die under the # lock; `detachedJson` keeps the stored object independent of `env` (ANALYSIS 4.1). var stored = candidate - stored.flags = detachedJson(flags.get) + stored.flags = detachedJson(candidate.flags) # 5.5 SET: the new wall sticks every token its circle overlaps. The rules run on a snapshot # taken before the write (the id is assigned by the write), and their outcome is applied only # after it committed, so a failed write leaves every token untouched. @@ -2136,9 +2108,10 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = var ok = false withLock app.dbLock: sceneId = app.scene.id # the request's one read (#31) - # The flags object goes into the wall record verbatim: detach it here so both the record and - # this local die under the lock (ANALYSIS 4.1). + # The label string and flags object go into the wall record verbatim: detach them here so + # both the record and this local die under the lock (ANALYSIS 4.1). var storedPatch = patch + if patch.label.isSome: storedPatch.label = some(detachedString(patch.label.get)) if patch.flags.isSome: storedPatch.flags = some(detachedJson(patch.flags.get)) let current = wallById(app.scene, id) if current.isSome: diff --git a/server/markers.nim b/server/markers.nim index a169ee9..9fdf791 100644 --- a/server/markers.nim +++ b/server/markers.nim @@ -32,11 +32,6 @@ proc anchorOf*(w: WallRec): (int, int) = ## The wall's drawn midpoint, rounded once to integer px and fixed for the wall (5.8, 6.1). (int(round((w.a.x + w.b.x) / 2.0)), int(round((w.a.y + w.b.y) / 2.0))) -proc wallSig(w: WallRec): string = - ## Alias for the shared signature in `world` (5.8, #60): the write path deletes the persisted - ## rows by the same rule the online retraction uses. - markerSig(w) - proc extentSeen*(pv: PlayerVision, a, b: Vec): bool = ## True when any point of the wall's visible extent (the segment in this round) is inside one of ## the player's polygons: an endpoint inside, or the segment crossing a polygon edge. Boundary @@ -84,10 +79,12 @@ proc syncMarkers*(pv: var PlayerVision, sc: SceneRec): int = ## Retraction is first, so a moved wall gives up its old id even when the new geometry is already ## in sight; the mint below is still the ordinary extent gate, never a "the wall moved" shortcut. ## `markerDead` feeds the same derived-memory transaction as `markerFresh` (4.2 step 6). + ## One id->wall table per refresh: the retraction is a lookup, not a scan of every wall per marker. + var byId = initTable[int, WallRec]() + for w in sc.walls: byId[w.id] = w var retract: seq[int] for wallId in pv.markers.keys: - let wall = sc.wallById(wallId) - if wall.isNone or pv.markers[wallId].sig != wallSig(wall.get): + if not byId.hasKey(wallId) or pv.markers[wallId].sig != markerSig(byId[wallId]): retract.add wallId for wallId in retract: pv.markerDead.add pv.markers[wallId].id @@ -99,7 +96,7 @@ proc syncMarkers*(pv: var PlayerVision, sc: SceneRec): int = if w.id in pv.markers: continue if not pv.qualifies(w): continue let (x, y) = anchorOf(w) - let marker = Marker(id: freshMarkerId(pv), x: x, y: y, sig: wallSig(w)) + let marker = Marker(id: freshMarkerId(pv), x: x, y: y, sig: markerSig(w)) pv.markers[w.id] = marker pv.markerFresh.add (w.id, marker) inc result @@ -156,7 +153,7 @@ proc restore*(db: DbConn, sc: SceneRec, visions: var Table[int, PlayerVision]) = if wall.isNone: continue let (x, y) = anchorOf(wall.get) visions.mgetOrPut(pid, PlayerVision()).markers[wallId] = - Marker(id: row[2], x: x, y: y, sig: wallSig(wall.get)) + Marker(id: row[2], x: x, y: y, sig: markerSig(wall.get)) proc markerCount*(db: DbConn, sceneId: int): int = ## Scene-wide marker rows: an O(1) startup log number (11.3) and a test probe. diff --git a/server/tokens.nim b/server/tokens.nim index 4af4a98..1e82c20 100644 --- a/server/tokens.nim +++ b/server/tokens.nim @@ -33,7 +33,7 @@ ## 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, props, text, world +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 @@ -277,7 +277,7 @@ proc sqlLitId(id: Option[string]): string = for c in v: if c notin {'A'..'Z', 'a'..'z', '0'..'9', '_', '-'}: raise newException(ValueError, "character id outside the id alphabet") - "'" & v & "'" + sqlLitText(v) proc writeStatuses*(db: DbConn, t: TokenRec) = ## Rewrites the token's `entity_status` rows to exactly `t.statuses`. No transaction control: the diff --git a/server/views.nim b/server/views.nim index 37ea32c..60e7e2b 100644 --- a/server/views.nim +++ b/server/views.nim @@ -299,7 +299,8 @@ proc playerView*(ctx: Context, playerId: int): PlayerView = result.encountered.add EncounteredView(id: eid, name: e.entryName, grey: eid notin visible) when defined(leakfault): # Negative controls (DESIGN 10.3): add what the honest rule just refused, so the harness proves - # it would notice. Never a second copy of the visibility rule. # The two "add a token the honest rule refused" controls build the frame exactly as the honest + # it would notice. Never a second copy of the visibility rule. + # The two "add a token the honest rule refused" controls build the frame exactly as the honest # path would, so the class they report stays the one they were built for (a bucket mismatch here # would add an OWNER_PROP/CHAR_OWNER_PROP class and blunt the assertion). proc leakedView(t: TokenRec): PlayerTokenView = diff --git a/server/vision.nim b/server/vision.nim index 89e6af8..e3bb22c 100644 --- a/server/vision.nim +++ b/server/vision.nim @@ -40,9 +40,10 @@ type ## the anchor is the wall's drawn midpoint, rounded once at mint time and never updated. `sig` ## is the retraction-relevant wall state (geometry, switch, derived kind) the marker was earned ## for: a different signature at the next refresh means the cause changed and the marker dies. + ## It is compared field by field, never as a formatted string. id*: string x*, y*: int - sig*: string + sig*: MarkerSig PlayerVision* = object polys*: seq[Poly] diff --git a/server/world.nim b/server/world.nim index fce42d3..3f14850 100644 --- a/server/world.nim +++ b/server/world.nim @@ -32,7 +32,7 @@ ## no locking: the caller holds the global lock (4.3). import std/[json, math, options, strutils] import db_connector/db_sqlite -import geometry, text +import db, geometry, text type WallPosition* = enum @@ -53,8 +53,9 @@ type pwWindow = "window" pwOneWay = "one_way" - WallSwitches* = object - ## The raw switches a payload names. A field that is `none` is not patched, which is what makes + WallSettings* = object + ## The raw settings a payload names (GLOSSARY: a wall *switch* is not a door/open/secret/ + ## locked/sight-dir setting). A field that is `none` is not patched, which is what makes ## a raw-switch `wall.update` patch-only and a raw-switch `wall.add` start from the `wall` ## defaults (DESIGN 6.1). `open` is collected only for `wall.add`; on an update it is an ## unknown field and `door.set` owns it. @@ -110,7 +111,7 @@ type label*: Option[string] clearLabel*: bool preset*: Option[Preset] ## replaces the whole switch set; never with a raw switch - switches*: WallSwitches ## the raw switches present; patches only those + settings*: WallSettings ## the raw settings present; patches only those flags*: Option[JsonNode] ScenePatch* = object @@ -158,13 +159,23 @@ proc derivedKind*(w: WallRec): string = else: "custom" -proc markerSig*(w: WallRec): string = - ## The marker cause signature of DESIGN 5.8: exactly the wall fields whose change retracts a - ## player marker — endpoints, thickness, placement, the `player_marker` switch and the derived - ## `window` gate. Height and label have no marker consequence and are deliberately absent. Shared - ## with `server/markers.nim` so the online retraction and the write-time delete cannot drift. - $w.a.x & "," & $w.a.y & "," & $w.b.x & "," & $w.b.y & "," & - $w.thickness & "," & $w.position & "," & $w.playerMarker & "," & derivedKind(w) +type + MarkerSig* = object + ## The marker cause signature of DESIGN 5.8: exactly the wall fields whose change retracts a + ## player marker. Compared field by field (never as a formatted string), so two signatures are + ## equal exactly when those fields are. Height and label have no marker consequence and are + ## deliberately absent. + a*, b*: Vec + thickness*: float + position*: WallPosition + playerMarker*: bool + kind*: string + +proc markerSig*(w: WallRec): MarkerSig = + ## The marker cause signature of DESIGN 5.8, shared with `server/markers.nim` so the online + ## retraction and the write-time delete cannot drift. + MarkerSig(a: w.a, b: w.b, thickness: w.thickness, position: w.position, + playerMarker: w.playerMarker, kind: derivedKind(w)) # --------------------------------------------------------------------------------------------------- # The one expand-and-validate path for wall writes (DESIGN 5.8, 6.1 FIXED #49/#55) @@ -183,8 +194,8 @@ proc storable*(rec: WallRec): bool = if rec.sightDir != sdBoth and not rec.blocksSight: return false true -proc hasAnySwitch*(sw: WallSwitches): bool = - ## True when the payload named any raw switch (a preset may not appear with one). +proc hasAnySetting*(sw: WallSettings): bool = + ## True when the payload named any raw setting (a preset may not appear with one). sw.blocksSight.isSome or sw.blocksMovement.isSome or sw.playerMarker.isSome or sw.door.isSome or sw.open.isSome or sw.secret.isSome or sw.locked.isSome or sw.sightDir.isSome @@ -213,7 +224,7 @@ proc expandPreset*(base: WallRec, preset: Preset): WallRec = result.secret = false result.locked = false -proc applySwitches(base: WallRec, sw: WallSwitches): Option[WallRec] = +proc applySettings(base: WallRec, sw: WallSettings): Option[WallRec] = ## A raw-switch write patches only the switches it names. A door-only switch set to true on a ## non-door is `invalid` (never silently dropped); when the write clears `door`, inherited ## door-only settings are closed and de-secreted (DESIGN 5.8, 6.1). @@ -235,16 +246,16 @@ proc applySwitches(base: WallRec, sw: WallSwitches): Option[WallRec] = some(r) proc resolveWall*(base: WallRec, preset: Option[Preset], - sw: WallSwitches): Option[WallRec] = + sw: WallSettings): Option[WallRec] = ## THE single path shared by `wall.add`, `wall.update` and the future UVTT importer: a preset is ## expanded before validation and may not appear with any raw switch; raw switches patch the ## base; the resulting switch set is then checked by `storable`. Geometry, height and label are ## validated by `validWall`; a preset never touches them (DESIGN 5.8, 6.1 FIXED #49/#55). if preset.isSome: - if sw.hasAnySwitch: return none(WallRec) + if sw.hasAnySetting: return none(WallRec) result = some(expandPreset(base, preset.get)) else: - result = applySwitches(base, sw) + result = applySettings(base, sw) if result.isSome and not storable(result.get): result = none(WallRec) # --------------------------------------------------------------------------------------------------- @@ -397,7 +408,7 @@ proc patched*(w: WallRec, patch: WallPatch): Option[WallRec] = if patch.clearLabel: base.label = none(string) elif patch.label.isSome: base.label = patch.label if patch.flags.isSome: base.flags = patch.flags.get - result = resolveWall(base, patch.preset, patch.switches) + result = resolveWall(base, patch.preset, patch.settings) if result.isSome: result = some(normalize(result.get)) @@ -407,17 +418,10 @@ proc patched*(w: WallRec, patch: WallPatch): Option[WallRec] = proc flagsText(node: JsonNode): string = if node.isNil: "{}" else: $node -proc sqlLitText*(value: string): string = - ## A SQL text literal (DESIGN 4.4): single quotes doubled. Used for `label`, which is nullable. - "'" & value.replace("'", "''") & "'" - proc sqlLitReal*(value: float): string = ## A fixed, locale-free SQL number literal. Used for `height`, which is nullable. $value -proc sqlLitTextOrNull*(value: Option[string]): string = - if value.isSome: sqlLitText(value.get) else: "NULL" - proc sqlLitRealOrNull*(value: Option[float]): string = if value.isSome: sqlLitReal(value.get) else: "NULL" diff --git a/server/worldmap.nim b/server/worldmap.nim index 6ccd9c6..a7ae333 100644 --- a/server/worldmap.nim +++ b/server/worldmap.nim @@ -30,10 +30,14 @@ proc geometryWalls*(sc: SceneRec, forSight = false): seq[Wall] = of sdBoth: wdBoth of sdLeft: wdLeft of sdRight: wdRight - var wall = Wall(a: w.a, b: w.b, door: w.door, open: w.open, sightDir: dir, + var open = w.open + when defined(leakfault): + # Negative control for the door-equivalence group (#56): a secret door behaves like an open + # one, in a `-d:leakfault` build only. The shipped build has no fault path at all. + if forSight and w.secret and faultActive("secretgap"): + open = true + let wall = Wall(a: w.a, b: w.b, door: w.door, open: open, sightDir: dir, sightBarrier: w.blocksSight, movementBarrier: w.blocksMovement) - if forSight and w.secret and faultActive("secretgap"): - wall.open = true result.add wall proc ruleWall*(w: WallRec): Wall = diff --git a/tests/tdb.nim b/tests/tdb.nim index d021d0e..5e049ca 100644 --- a/tests/tdb.nim +++ b/tests/tdb.nim @@ -346,3 +346,29 @@ suite "step 8 wall CHECKs (DESIGN 4.4)": check db.getValue(sql"SELECT count(*) FROM pragma_table_info('wall') WHERE name = 'kind'") == "1" check db.getValue(sql"SELECT count(*) FROM pragma_table_info('wall') WHERE name = 'thickness'") == "0" check db.getValue(sql"SELECT count(*) FROM sqlite_master WHERE name = 'wall_v1'") == "0" + + test "a malformed props_gm refuses step 8 and leaves the schema-7 DB untouched": + let d = tmpDir() + let db = openFresh(d) + defer: + close(db) + removeDir(d) + applySteps(db, 7) + # The height backfill cannot decide for this row: the step fails rather than silently skipping + # it (DESIGN 4.4: a failing step rolls back completely). + db.exec(sql"""INSERT INTO entity (id, scene_id, kind, descriptive_name, actual_name, x, y, + created_at, props_gm) + VALUES ('tok000000009', 1, 'pc', 'x', 'x', 0, 0, 'x', 'not json')""") + var raised = false + try: + discard migrate(db) + except MigrationError: + raised = true + check raised + check schemaVersion(db) == 7 + check appliedMigrations(db).len == 7 + check db.getValue(sql"SELECT count(*) FROM pragma_table_info('wall') WHERE name = 'kind'") == "1" + check db.getValue(sql"SELECT count(*) FROM pragma_table_info('wall') WHERE name = 'thickness'") == "0" + check db.getValue(sql"SELECT count(*) FROM sqlite_master WHERE name = 'wall_v1'") == "0" + check db.getValue(sql"SELECT count(*) FROM sqlite_master WHERE name = 'marker_seen'") == "0" + check db.getValue(sql"SELECT props_gm FROM entity WHERE id = 'tok000000009'") == "not json" diff --git a/tests/tworld.nim b/tests/tworld.nim index c74526a..af00afe 100644 --- a/tests/tworld.nim +++ b/tests/tworld.nim @@ -230,6 +230,8 @@ suite "persistence (write-through, restart-identical)": check conn.getValue(sql("SELECT label FROM wall WHERE id = " & $id)) == "the king's window" check sqlLitText("the king's window") == "'the king''s window'" check sqlLitTextOrNull(none(string)) == "NULL" + expect ValueError: + discard sqlLitText("a\0b") # the helper refuses a NUL itself (#4, r1 review) check sqlLitRealOrNull(none(float)) == "NULL" check sqlLitRealOrNull(some(1.8)) == "1.8" check conn.getValue(sql("SELECT count(*) FROM wall WHERE id = " & $plain & " AND height IS NULL")) == "1" @@ -312,38 +314,38 @@ suite "validation (DESIGN 6.1 `wall.*`)": check parsePreset("wall").get == pwWall check parsePreset("one_way").get == pwOneWay check parsePreset("terrain").isNone - let window = resolveWall(sized, some(pwWindow), WallSwitches()).get + let window = resolveWall(sized, some(pwWindow), WallSettings()).get check not window.blocksSight and window.blocksMovement check window.door and not window.open and window.playerMarker check window.thickness == 12 and window.position == wpLeft and window.height == some(3.0) check window.label == some("railing") # a preset never touches non-switch fields - let oneWay = resolveWall(sized, some(pwOneWay), WallSwitches()).get + let oneWay = resolveWall(sized, some(pwOneWay), WallSettings()).get check oneWay.sightDir == sdLeft and oneWay.blocksSight and not oneWay.door # preset xor raw switches: even a switch equal to the expansion is a mix - check resolveWall(sized, some(pwDoor), WallSwitches(blocksSight: some(true))).isNone - check resolveWall(sized, some(pwDoor), WallSwitches(open: some(true))).isNone + check resolveWall(sized, some(pwDoor), WallSettings(blocksSight: some(true))).isNone + check resolveWall(sized, some(pwDoor), WallSettings(open: some(true))).isNone test "the switch-set invariants reject door-only settings on a non-door (#55)": let plain = defaultWall((0.0, 0.0), (10.0, 0.0)) - check resolveWall(plain, none(Preset), WallSwitches(open: some(true))).isNone - check resolveWall(plain, none(Preset), WallSwitches(secret: some(true))).isNone - check resolveWall(plain, none(Preset), WallSwitches(locked: some(true))).isNone - check resolveWall(plain, none(Preset), WallSwitches(secret: some(false))).isSome + check resolveWall(plain, none(Preset), WallSettings(open: some(true))).isNone + check resolveWall(plain, none(Preset), WallSettings(secret: some(true))).isNone + check resolveWall(plain, none(Preset), WallSettings(locked: some(true))).isNone + check resolveWall(plain, none(Preset), WallSettings(secret: some(false))).isSome # clearing door closes and de-secrets, but naming a true door-only switch with it is invalid var secretDoor = plain secretDoor.door = true secretDoor.secret = true - let closed = resolveWall(secretDoor, none(Preset), WallSwitches(door: some(false))).get + let closed = resolveWall(secretDoor, none(Preset), WallSettings(door: some(false))).get check not closed.door and not closed.open and not closed.secret and not closed.locked check resolveWall(secretDoor, none(Preset), - WallSwitches(door: some(false), secret: some(true))).isNone + WallSettings(door: some(false), secret: some(true))).isNone # open excludes secret and locked; a direction needs sight to block var lockedDoor = plain lockedDoor.door = true lockedDoor.locked = true - check resolveWall(lockedDoor, none(Preset), WallSwitches(open: some(true))).isNone + check resolveWall(lockedDoor, none(Preset), WallSettings(open: some(true))).isNone check resolveWall(plain, none(Preset), - WallSwitches(blocksSight: some(false), sightDir: some(sdLeft))).isNone + WallSettings(blocksSight: some(false), sightDir: some(sdLeft))).isNone test "a label is 1..64 code points, trimmed and free of control characters (#55)": let (conn, d) = freshScene()