Files
SirStone a5c0ee5d4c fix: dispatch guard and Defect-safe rollback (#32)
A readable intent that fails in handling now always gets exactly one ack:
the new static internal code, unless the handler's own ack was already
enqueued. Both transaction helpers roll back on every unwind path,
Defect included, so the shared SQLite connection never keeps an open
transaction. Test-only dispfault build covers catchable/defect/after-ack;
DESIGN 6.5 records internal as an owner decision and 6.2 names refusal
codes as additive.
2026-11-20 21:36:44 +01:00

300 lines
14 KiB
Nim

## The wire protocol shell (DESIGN 6, 6.2, 6.4, 6.5; M3 slice 3, issue #18).
## Pure, mummy-free logic: the frame catalogue answers, the envelope rules, the intent rate
## limiter and the malformed-flood window. main.nim only wires these to sockets.
##
## Numbers here are FIXED (owner-delegated, #15/#18) and mirrored in DESIGN:
## max inbound message 64 KB (mummy's own default, inbound only), intent bucket 30/s with a
## burst of 100 per connection, 10 malformed frames inside any 10 s close the connection.
##
## Close codes (DESIGN 6.5): mummy 0.4.8's `close(ws)` sends an EMPTY close frame, so a browser
## reports 1005 and the application codes 4001/4002/4003 cannot ride the close frame. Owner
## decision (#18, option A): the server sends one final `closing {reason, code}` message and then
## closes; the client reads the reason from that message and 1005 from the close event.
import std/[json, monotimes, unicode]
import geometry
const
ProtoVersion* = 2
## proto 2 is the wall-model build (DESIGN 6.2, ADR-0011, #54): the wall payloads carry the
## typed geometry and switches, `kind` is output-only and the GM frames echo the full record.
## The client announces it as `/ws?proto=N`.
MaxInboundBytes* = 64 * 1024
## DESIGN 6.4: mummy's `maxMessageLen`, inbound and cumulative across fragments.
RatePerSecond* = 30
## DESIGN 6.4: intents per second sustained, per connection, same for GM and players.
RateBurst* = 100
## DESIGN 6.4: bucket size; a burst of 100 is free, then 30/s.
MalformedFloodLimit* = 10
## DESIGN 6.5 row 8: this many malformed frames inside the window closes with 1008.
MalformedFloodWindowMs* = 10_000
PingIntervalMs* = 20_000
## FIXED (owner-delegated, #18): the server pings every 20 s (a browser answers by itself).
## Lag tracking and stop-feeding-on-no-pong stay M5 (DESIGN 4.3); this slice only keeps the
## connection warm and gives the harness a frame to see.
MaxReqId* = (1 shl 31) - 1
## DESIGN 6: 0 <= reqId < 2^31.
# Connection-level outcomes (DESIGN 6.5). The values are the app's range 4001-4003 plus the
# RFC 6455 standard 1008; they travel in `closing.code`, not in the close frame.
CloseRevoked* = 4001
CloseEvicted* = 4002
CloseProtoMismatch* = 4003
CloseMalformedFlood* = 1008
# The static reason strings of 6.5, one per outcome. Never carry state.
ReasonRevoked* = "revoked"
ReasonEvicted* = "evicted"
ReasonProtoMismatch* = "proto-mismatch"
ReasonMalformedFlood* = "malformed-flood"
# Ack / error codes (DESIGN 6.5, static strings, never carry state).
CodeRateLimited* = "rate-limited"
CodeUnknownType* = "unknown-type"
CodeNotAllowed* = "not-allowed"
CodeNotFound* = "not-found"
CodeInvalid* = "invalid"
CodeNameTaken* = "name-taken"
CodeCapReached* = "cap-reached"
CodeInUse* = "in-use"
CodeNoRules* = "no-rules"
CodeMalformed* = "malformed"
CodeInternal* = "internal"
## #32: the server failed while handling a readable intent; nothing was applied. Static, no
## detail (DESIGN 6.5).
# The complete M3 intent catalogue (DESIGN 6.1: 29 intents). A name in here but not yet built
# by its slice still gets exactly one ack; see `isImplementedIntent`.
IntentCatalogue* = [
"conn.ping", "act.do",
"player.setname", "player.rename", "player.remove",
"key.create", "key.replace", "key.show",
"scene.set", "wall.add", "wall.update", "wall.remove", "door.set",
"token.create", "token.update", "token.move", "token.resize", "token.remove",
"status.set", "status.clear", "prop.set", "prop.unset",
"character.create", "character.update", "character.remove", "character.reassign",
"name.reveal", "name.reveal_all", "encountered.remove",
]
## 2 + 6 + 5 + 9 + 7 = 29 (DESIGN 6.1).
GmOnlyIntents* = [
"player.rename", "player.remove", "key.create", "key.replace", "key.show",
"scene.set", "wall.add", "wall.update", "wall.remove", "door.set",
"token.create", "token.update", "token.resize", "token.remove",
"status.set", "status.clear", "prop.set", "prop.unset",
"character.create", "character.update", "character.remove", "character.reassign",
"name.reveal", "name.reveal_all", "encountered.remove",
]
ImplementedIntents* = ["conn.ping", "act.do", "key.create", "key.replace", "key.show",
"player.setname", "player.rename", "player.remove",
"scene.set", "wall.add", "wall.update", "wall.remove", "door.set",
"token.create", "token.update", "token.move", "token.resize",
"token.remove", "status.set", "status.clear", "prop.set", "prop.unset",
"character.create", "character.update", "character.remove",
"character.reassign", "name.reveal", "name.reveal_all",
"encountered.remove"]
## What the built slices actually handle (slice 3 #18: the shell and the auth intents; slice 4
## #19: walls and doors; slice 5 #20: tokens and sight; slice 7 #22: sizes, statuses and props;
## slice 8 #23: characters, names, encountered, and the players/keys rows; slice 10 #25:
## `scene.set`). With slice 10 the whole 29-intent catalogue of 6.1 has a handler.
type
Envelope* = object
ok*: bool
## false = the frame cannot be acked: it gets `error malformed` (DESIGN 6.5 step 2).
t*: string
reqId*: int
node*: JsonNode
RateLimiter* = object
## Token bucket per connection (DESIGN 6.4). `nowMs` is injected so tests need no clock.
tokens*: float
burst*: float
perSecond*: float
lastMs*: int64
## -1 = never used, so the first intent fills nothing and costs one token.
FloodWindow* = object
## Ring of the last MalformedFloodLimit malformed-frame timestamps (DESIGN 6.5 row 8).
times*: array[MalformedFloodLimit, int64]
count*: int
next*: int
proc monotonicMs*(): int64 =
getMonoTime().ticks div 1_000_000
# ---------------------------------------------------------------------------------------------------
# Envelope (DESIGN 6, 6.5 step 2)
proc parseEnvelope*(text: string): Envelope =
## A readable intent: UTF-8 text, a JSON object, a string `t` and an integer `reqId` in range.
## Anything else is "malformed": no reqId can be echoed, so the reply is an `error` frame.
if validateUtf8(text) != -1: return
var node: JsonNode
try:
node = parseJson(text)
except CatchableError:
return
if node.isNil or node.kind != JObject: return # parseJson("") yields nil, not an exception
let t = node{"t"}
let reqIdNode = node{"reqId"}
if t.isNil or reqIdNode.isNil: return
if t.kind != JString or reqIdNode.kind != JInt: return
let reqId = reqIdNode.getInt
if reqId < 0 or reqId > MaxReqId: return
Envelope(ok: true, t: t.getStr, reqId: reqId, node: node)
proc isCatalogueIntent*(t: string): bool =
t in IntentCatalogue
proc isGmOnlyIntent*(t: string): bool =
t in GmOnlyIntents
proc isImplementedIntent*(t: string): bool =
t in ImplementedIntents
# ---------------------------------------------------------------------------------------------------
# Server -> client frames (DESIGN 6.1). Every frame carries `n`, the per-connection counter:
# starts at 1 on the connection's first frame and counts server frames only.
proc withN*(node: JsonNode, n: int): JsonNode =
## Stamps the per-connection counter on a copy. The copy is load-bearing: the egress keeps the
## frame it built in the connection's `known` table as the diff base, and mutating that node here
## would make the *next* comparison see a different frame and re-send state nobody changed (T11,
## 6.4). A deep copy of one frame is cheap next to a send.
result = copy(node)
result["n"] = %n
proc helloFrame*(proto, n: int, role: string, playerId: int, name: JsonNode,
scene: JsonNode = nil, extra: JsonNode = nil): JsonNode =
## DESIGN 6.1 `hello`. `scene` is the scene block (views.sceneBlock) and `extra` the scene's free
## object (GM only); both are absent for an unnamed player, which gets `proto, role, me` only.
var me = newJObject()
me["id"] = %playerId
me["name"] = name # null while the player has no name yet
result = %*{"t": "hello", "proto": proto, "role": role, "me": me, "n": n}
if not scene.isNil: result["scene"] = scene
if not extra.isNil: result["extra"] = extra
proc ackFrame*(reqId, n: int, extra: JsonNode = nil): JsonNode =
## `ack {reqId, ok:true, ...result fields}`; `extra` holds `id`, `key`, `pos`, `ts`.
result = %*{"t": "ack", "reqId": reqId, "ok": true}
if not extra.isNil:
for key, value in extra: result[key] = value
result["n"] = %n
proc nackFrame*(reqId, n: int, code: string): JsonNode =
## `ack {reqId, ok:false, code}`: a static code, never state (T9).
%*{"t": "ack", "reqId": reqId, "ok": false, "code": code, "n": n}
proc nackMoveFrame*(reqId, n: int, x, y: float): JsonNode =
## The uniform move refusal of DESIGN 5.5/T9: `ok:false, pos` and NO code. `token.move` sends it
## from main.nim; it lives here so the shape has one definition.
%*{"t": "ack", "reqId": reqId, "ok": false, "pos": [x, y], "n": n}
proc errorFrame*(code: string, n: int): JsonNode =
## `error {code}`: only `malformed` and `rate-limited`, only for frames with no readable reqId.
%*{"t": "error", "code": code, "n": n}
proc closingFrame*(reason: string, code, n: int): JsonNode =
## The last frame before a server-initiated close (DESIGN 6.5, FIXED #18): it carries the
## reason and the code the close frame cannot carry at the mummy pin.
%*{"t": "closing", "reason": reason, "code": code, "n": n}
proc rosterFrame*(players: seq[JsonNode]): JsonNode =
## `roster {players:[{id, name, role, colour, connected}]}` (6.1): the full list every time, so a
## client never merges. The caller already dropped what this recipient may not see (players get
## named players only, 6.1 leak note 4); the frame itself takes no `n` because it is fanned out to
## several recipients, like the wall frames.
%*{"t": "roster", "players": players}
proc rosterEntry*(id: int, name: JsonNode, role: string, colour: string,
connected: bool): JsonNode =
%*{"id": id, "name": name, "role": role, "colour": colour, "connected": connected}
# Walls and doors (DESIGN 6.1, GM only; slice 4 / #19). These three builders deliberately take NO
# `n`: they are the only frames fanned out to several recipients at once (every GM connection), and
# each recipient gets its own number, added by the sender with `withN` right before the send.
type
WallView* = object
## One wall as the GM's `wall`/`walls` frames show it (DESIGN 6.1, proto 2, #54). The typed
## record plus the derived shape label; `height` and `label` are always present and null when
## unset (the frame is GM-only, so their presence marks nothing). This is the narrow wire shape,
## kept out of `world.nim` so the protocol shell stays free of storage imports.
id*: int
a*, b*: Vec
thickness*: float
position*: string
blocksSight*, blocksMovement*: bool
sightDir*: string
playerMarker*, door*, open*, secret*, locked*: bool
height*: float
hasHeight*: bool ## false = full height (`height:null`)
label*: string
hasLabel*: bool ## false = no label (`label:null`)
kind*: string ## the derived 5.8 shape label, output only
flags*: JsonNode
proc wallObject*(w: WallView): JsonNode =
## One wall as the wire shows it: the same shape inside `walls` and in a `wall` upsert.
%*{
"id": w.id, "a": [w.a.x, w.a.y], "b": [w.b.x, w.b.y],
"thickness": w.thickness, "position": w.position,
"height": (if w.hasHeight: %w.height else: newJNull()),
"kind": w.kind,
"blocks_sight": w.blocksSight, "blocks_movement": w.blocksMovement,
"sight_dir": w.sightDir, "player_marker": w.playerMarker,
"door": w.door, "open": w.open, "secret": w.secret, "locked": w.locked,
"label": (if w.hasLabel: %w.label else: newJNull()),
"flags": (if w.flags.isNil: newJObject() else: w.flags)
}
proc wallsFrame*(scene: int, walls: seq[JsonNode]): JsonNode =
## The GM snapshot of every wall in the scene (DESIGN 6.1 `walls`, 6.3: on connect and resync).
%*{"t": "walls", "scene": scene, "walls": walls}
proc wallFrame*(scene: int, wall: JsonNode): JsonNode =
## `wall` upsert (doors included; this replaces the prototype's `door` message).
result = %*{"t": "wall", "scene": scene}
for key, value in wall: result[key] = value
proc wallGoneFrame*(scene, id: int): JsonNode =
%*{"t": "wall_gone", "scene": scene, "id": id}
# ---------------------------------------------------------------------------------------------------
# Intent rate limit (DESIGN 6.4)
proc newRateLimiter*(perSecond = RatePerSecond, burst = RateBurst): RateLimiter =
RateLimiter(tokens: float(burst), burst: float(burst), perSecond: float(perSecond), lastMs: -1)
proc allow*(r: var RateLimiter, nowMs: int64): bool =
## Takes one token if the bucket has one. Refill is continuous and capped at the burst size.
if r.lastMs < 0:
r.lastMs = nowMs
else:
let elapsed = nowMs - r.lastMs
if elapsed > 0:
r.tokens = min(r.burst, r.tokens + float(elapsed) * r.perSecond / 1000.0)
r.lastMs = nowMs
if r.tokens >= 1.0:
r.tokens -= 1.0
return true
false
proc available*(r: RateLimiter): float =
r.tokens
# ---------------------------------------------------------------------------------------------------
# Malformed flood (DESIGN 6.5 row 8)
proc recordMalformed*(f: var FloodWindow, nowMs: int64): bool =
## Records one malformed frame; true = the flood rule fires now (10 inside any 10 s).
## The counter is a ring of the last 10 timestamps: the frame that overwrites the oldest still
## inside the window is the one that trips the limit, so the 10th malformed frame closes.
f.times[f.next] = nowMs
f.next = (f.next + 1) mod MalformedFloodLimit
if f.count < MalformedFloodLimit: inc f.count
let oldest = f.times[f.next]
result = f.count >= MalformedFloodLimit and (nowMs - oldest) <= MalformedFloodWindowMs