server: wall and door intents, GM wall snapshot and fan-out (#19)
wall.add, wall.update, wall.remove and door.set leave the unknown-type rollout
list: field shapes and ranges per 6.1 (and the payload rules recorded FIXED in
4.4/6.1), lookup failures not-found, non-GM refused by the existing GM-only
gate. wall.add acks {id} from the scene's next_wall_id; wall.update patches
a/b/kind/flags only (open belongs to door.set); door.set is invalid on a plain
wall. Effects go to every GM connection only: wall / wall_gone, plus one walls
snapshot right after hello (the wall part of the 6.3 resync). Players receive
no wall data in any message (3.1, T2).
protocol.nim gains the wallObject/wallsFrame/wallFrame/wallGoneFrame builders
(no n: the sender stamps it per recipient) and the five wall intents in the
implemented set.
This commit is contained in:
+223
-2
@@ -4,6 +4,9 @@
|
||||
## M3 slice 3 (#18): the WS protocol shell - `hello`, the per-connection `n` counter, exactly one
|
||||
## `ack` per intent, `error` frames, the intent rate limit, the malformed-flood close, the proto
|
||||
## version check, the oversize frame limit (mummy's 64 KB) and the server Ping heartbeat.
|
||||
## M3 slice 4 (#19): walls and doors - the one scene loaded at startup, `wall.add`, `wall.update`,
|
||||
## `wall.remove` and `door.set` (GM only), the GM `walls` snapshot on connect, `wall`/`wall_gone`
|
||||
## to every GM connection, and nothing about walls ever reaching a player (DESIGN 3.1, 6.1, 8).
|
||||
## Close reasons (FIXED, owner decision #18): mummy 0.4.8 cannot put a code in the close frame, so
|
||||
## every server-initiated close is preceded by a `closing {reason, code}` message and the client
|
||||
## reads 1005 + that message (DESIGN 6.5).
|
||||
@@ -12,7 +15,7 @@ import std/[atomics, json, locks, options, os, strutils]
|
||||
import std/typedthreads
|
||||
import db_connector/db_sqlite
|
||||
import mummy, mummy/routers
|
||||
import config, db, eventlog, crypto, auth, conns, instancelock, protocol
|
||||
import config, db, eventlog, crypto, auth, conns, instancelock, protocol, world
|
||||
|
||||
const
|
||||
CookieName* = "fff_session"
|
||||
@@ -26,8 +29,11 @@ type
|
||||
lg: Logger
|
||||
db: DbConn
|
||||
dbLock: Lock
|
||||
## The one global lock (DESIGN 4.3): it serializes every mutation, the DB and `scene`.
|
||||
conns: Conns
|
||||
instanceLock: InstanceLock
|
||||
scene: SceneRec
|
||||
## The single v1 scene with its walls, loaded at startup and never re-read (4.1).
|
||||
|
||||
var appHandle: pointer
|
||||
## The one App for the process. A plain pointer keeps worker-thread handlers `{.gcsafe.}`
|
||||
@@ -79,6 +85,55 @@ proc closeGone(conn: Conn, reason: string, code: int) =
|
||||
conn.ws.send($closingFrame(reason, code, conn.frameNo))
|
||||
conn.ws.close()
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------
|
||||
# Wall fan-out (DESIGN 3.1: walls are GM-only data; a player never receives one, in any message).
|
||||
|
||||
proc wallObjectOf(w: WallRec): JsonNode =
|
||||
wallObject(w.id, w.a, w.b, $w.kind, w.open, w.flags)
|
||||
|
||||
proc wallsSnapshot(sc: SceneRec): JsonNode =
|
||||
var walls: seq[JsonNode]
|
||||
for w in sc.walls: walls.add wallObjectOf(w)
|
||||
wallsFrame(sc.id, walls)
|
||||
|
||||
proc sendToGms(frame: JsonNode) =
|
||||
## Every GM connection, each with its own `n` (DESIGN 6.1 `wall`/`wall_gone`, 6). The loop is
|
||||
## sequential on this thread, so reusing one frame object while stamping `n` is safe.
|
||||
for c in app.conns.snapshot():
|
||||
if c.role != prGm: continue
|
||||
let n = nextN(c)
|
||||
if n > 0: c.ws.send($withN(frame, n))
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------
|
||||
# Intent field helpers (DESIGN 6.1, 6.5 steps 7-8): shape first, then lookup.
|
||||
|
||||
type
|
||||
SceneCheck = enum
|
||||
scOk
|
||||
scInvalid ## `scene` missing or not an integer -> `invalid`
|
||||
scNotFound ## an integer, but not the one scene of v1 -> `not-found`
|
||||
|
||||
proc checkScene(env: Envelope): SceneCheck =
|
||||
## `scene` is the id of the single v1 scene (DESIGN 6.1, 6.5 step 8: a GM's missing target is
|
||||
## `not-found`; a wrongly typed field is `invalid`).
|
||||
let node = env.node{"scene"}
|
||||
if node.isNil or node.kind != JInt: return scInvalid
|
||||
if node.getInt != app.scene.id: return scNotFound
|
||||
scOk
|
||||
|
||||
proc intField(env: Envelope, key: string, dest: var int): bool =
|
||||
let node = env.node{key}
|
||||
if node.isNil or node.kind != JInt: return false
|
||||
dest = node.getInt
|
||||
true
|
||||
|
||||
proc sceneOk(conn: Conn, env: Envelope): bool =
|
||||
## Sends the refusal itself (6.5 steps 7-8); true = the intent names the one v1 scene.
|
||||
case checkScene(env)
|
||||
of scInvalid: ackErr(conn, env.reqId, CodeInvalid)
|
||||
of scNotFound: ackErr(conn, env.reqId, CodeNotFound)
|
||||
of scOk: return true
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------
|
||||
# HTTP helpers
|
||||
|
||||
@@ -249,6 +304,15 @@ proc wsUpgrade(request: Request) {.gcsafe.} =
|
||||
ws.send($helloFrame(ProtoVersion, helloN, $role, pid, me))
|
||||
# One Ping right away, then one every PingIntervalMs: the browser answers without JS (4.3).
|
||||
ws.send($nextPingSeq(), Ping)
|
||||
if player.get.role == prGm:
|
||||
# The wall part of the GM snapshot (6.1 `walls`: on connect and resync). The rest of the 6.3
|
||||
# sequence (roster, characters, encountered, tokens) arrives with slices 5-8; players never
|
||||
# receive wall data at all (3.1, T2).
|
||||
var snapshot: JsonNode
|
||||
withLock app.dbLock:
|
||||
snapshot = wallsSnapshot(app.scene)
|
||||
let snapN = app.conns.nextFrameNo(activated.id)
|
||||
if snapN > 0: ws.send($withN(snapshot, snapN))
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------
|
||||
# Intent pipeline (DESIGN 6.5). Order: parse, rate limit, unknown type, unnamed player, role,
|
||||
@@ -362,8 +426,157 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
|
||||
ackOk(conn, env.reqId)
|
||||
return
|
||||
|
||||
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:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
let kindNode = env.node{"kind"}
|
||||
if kindNode.isNil or kindNode.kind != JString:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
let kind = parseKind(kindNode.getStr)
|
||||
if kind.isNone:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
let open = parseOpen(fieldOrNull(env.node, "open"))
|
||||
if open.isNone:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
if kind.get == wkWall and open.get:
|
||||
# A wall is never open; only a door has an open state (DESIGN 6.1, 8).
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
let flags = parseFlags(fieldOrNull(env.node, "flags"))
|
||||
if flags.isNone:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
let candidate = WallRec(a: a.get, b: b.get, kind: kind.get, open: open.get, flags: flags.get)
|
||||
var added: Option[WallRec]
|
||||
withLock app.dbLock:
|
||||
let id = addWall(app.db, app.scene, candidate)
|
||||
if id.isSome: added = wallById(app.scene, id.get)
|
||||
if added.isNone:
|
||||
ackErr(conn, env.reqId, CodeInvalid) # degenerate or out-of-bounds geometry
|
||||
return
|
||||
app.lg.log(lvInfo, "wall_add", [("scene", $app.scene.id), ("wall", $added.get.id),
|
||||
("kind", $added.get.kind)])
|
||||
ackOk(conn, env.reqId, %*{"id": added.get.id})
|
||||
sendToGms(wallFrame(app.scene.id, wallObjectOf(added.get)))
|
||||
return
|
||||
|
||||
of "wall.update":
|
||||
if not sceneOk(conn, env): return
|
||||
var id = 0
|
||||
if not intField(env, "id", id):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
var patch: WallPatch
|
||||
var anyField = false
|
||||
if not fieldOrNull(env.node, "a").isNil:
|
||||
let a = parseVec(env.node{"a"})
|
||||
if a.isNone:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
patch.a = a
|
||||
anyField = true
|
||||
if not fieldOrNull(env.node, "b").isNil:
|
||||
let b = parseVec(env.node{"b"})
|
||||
if b.isNone:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
patch.b = b
|
||||
anyField = true
|
||||
if not fieldOrNull(env.node, "kind").isNil:
|
||||
let node = env.node{"kind"}
|
||||
if node.kind != JString:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
let kind = parseKind(node.getStr)
|
||||
if kind.isNone:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
patch.kind = kind
|
||||
anyField = true
|
||||
if not fieldOrNull(env.node, "flags").isNil:
|
||||
let flags = parseFlags(env.node{"flags"})
|
||||
if flags.isNone:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
patch.flags = flags
|
||||
anyField = true
|
||||
if not anyField:
|
||||
# `wall.update` changes at least one of a, b, kind, flags (6.1).
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
var outcome = waNotFound
|
||||
var updated: Option[WallRec]
|
||||
withLock app.dbLock:
|
||||
let current = wallById(app.scene, id)
|
||||
if current.isSome:
|
||||
outcome = updateWall(app.db, app.scene, patched(current.get, patch))
|
||||
if outcome == waOk: updated = wallById(app.scene, id)
|
||||
if outcome == waNotFound:
|
||||
ackErr(conn, env.reqId, CodeNotFound)
|
||||
return
|
||||
if outcome != waOk or updated.isNone:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
app.lg.log(lvInfo, "wall_update", [("scene", $app.scene.id), ("wall", $id),
|
||||
("kind", $updated.get.kind)])
|
||||
ackOk(conn, env.reqId)
|
||||
sendToGms(wallFrame(app.scene.id, wallObjectOf(updated.get)))
|
||||
return
|
||||
|
||||
of "wall.remove":
|
||||
if not sceneOk(conn, env): return
|
||||
var id = 0
|
||||
if not intField(env, "id", id):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
var outcome = waNotFound
|
||||
withLock app.dbLock:
|
||||
outcome = removeWall(app.db, app.scene, id)
|
||||
if outcome == waNotFound:
|
||||
ackErr(conn, env.reqId, CodeNotFound)
|
||||
return
|
||||
app.lg.log(lvInfo, "wall_remove", [("scene", $app.scene.id), ("wall", $id)])
|
||||
ackOk(conn, env.reqId)
|
||||
sendToGms(wallGoneFrame(app.scene.id, id))
|
||||
return
|
||||
|
||||
of "door.set":
|
||||
if not sceneOk(conn, env): return
|
||||
var id = 0
|
||||
if not intField(env, "id", id):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
let openNode = env.node{"open"}
|
||||
if openNode.isNil or openNode.kind != JBool:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
let open = openNode.getBool
|
||||
var outcome = waNotFound
|
||||
var updated: Option[WallRec]
|
||||
withLock app.dbLock:
|
||||
outcome = setDoor(app.db, app.scene, id, open)
|
||||
if outcome == waOk: updated = wallById(app.scene, id)
|
||||
if outcome == waNotFound:
|
||||
ackErr(conn, env.reqId, CodeNotFound)
|
||||
return
|
||||
if outcome != waOk or updated.isNone:
|
||||
ackErr(conn, env.reqId, CodeInvalid) # waNotDoor: a plain wall has no open state
|
||||
return
|
||||
app.lg.log(lvInfo, "door_set", [("scene", $app.scene.id), ("wall", $id),
|
||||
("open", $open)])
|
||||
ackOk(conn, env.reqId)
|
||||
sendToGms(wallFrame(app.scene.id, wallObjectOf(updated.get)))
|
||||
return
|
||||
|
||||
else:
|
||||
# A catalogue intent whose slice has not landed yet (#19-#25). It still gets its one ack, with
|
||||
# A catalogue intent whose slice has not landed yet (#20-#25). It still gets its one ack, with
|
||||
# a static code and no state; `unknown-type` is the honest answer until the handler exists
|
||||
# (DESIGN 6.1, slice-3 note).
|
||||
ackErr(conn, env.reqId, CodeUnknownType)
|
||||
@@ -557,6 +770,14 @@ proc runServer(cfg: Config): int =
|
||||
let state = App(cfg: cfg, lg: lg, db: conn, conns: newConns(), instanceLock: instanceLock)
|
||||
initLock(state.dbLock)
|
||||
readRedactionSecrets(conn, lg)
|
||||
# DESIGN 4.1/4.4: load everything into memory once; migration 3 seeds the single v1 scene.
|
||||
let loaded = loadScene(conn)
|
||||
if loaded.isNone:
|
||||
lg.log(lvError, "scene_missing", [("path", cfg.dbPath), ("scene", $DefaultSceneId)])
|
||||
return 1
|
||||
state.scene = loaded.get
|
||||
lg.log(lvInfo, "scene_loaded", [("scene", $state.scene.id), ("walls", $state.scene.walls.len),
|
||||
("next_wall_id", $state.scene.nextWallId)])
|
||||
appHandle = cast[pointer](state)
|
||||
|
||||
createThread(heartbeatThread, heartbeat)
|
||||
|
||||
+26
-3
@@ -11,6 +11,7 @@
|
||||
## 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* = 1
|
||||
@@ -79,9 +80,10 @@ const
|
||||
"name.reveal", "name.reveal_all", "encountered.remove",
|
||||
]
|
||||
|
||||
ImplementedIntents* = ["conn.ping", "act.do", "key.create", "key.replace", "player.remove"]
|
||||
## What this slice actually handles. The rest of the catalogue answers `unknown-type` until
|
||||
## its slice lands (DESIGN 6.1 note, #18).
|
||||
ImplementedIntents* = ["conn.ping", "act.do", "key.create", "key.replace", "player.remove",
|
||||
"wall.add", "wall.update", "wall.remove", "door.set"]
|
||||
## What the built slices actually handle (slice 3 #18 plus slice 4 #19's walls and doors).
|
||||
## The rest of the catalogue answers `unknown-type` until its slice lands (DESIGN 6.1 note).
|
||||
|
||||
type
|
||||
Envelope* = object
|
||||
@@ -179,6 +181,27 @@ proc closingFrame*(reason: string, code, n: int): JsonNode =
|
||||
## reason and the code the close frame cannot carry at the mummy pin.
|
||||
%*{"t": "closing", "reason": reason, "code": code, "n": n}
|
||||
|
||||
# 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.
|
||||
|
||||
proc wallObject*(id: int, a, b: Vec, kind: string, open: bool, flags: JsonNode): JsonNode =
|
||||
## One wall as the wire shows it: the same shape inside `walls` and in a `wall` upsert.
|
||||
%*{"id": id, "a": [a.x, a.y], "b": [b.x, b.y], "kind": kind, "open": open,
|
||||
"flags": (if flags.isNil: newJObject() else: 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)
|
||||
|
||||
|
||||
+42
-3
@@ -40,7 +40,7 @@ suite "envelope (6.5 step 2)":
|
||||
|
||||
test "the catalogue is the 29 intents of 6.1 and the built set is a subset":
|
||||
check IntentCatalogue.len == 29
|
||||
check ImplementedIntents.len == 5
|
||||
check ImplementedIntents.len == 9 # slice 3's five + slice 4's four wall intents
|
||||
for t in ImplementedIntents:
|
||||
check t in IntentCatalogue
|
||||
check isCatalogueIntent(t)
|
||||
@@ -55,11 +55,15 @@ suite "envelope (6.5 step 2)":
|
||||
for t in GmOnlyIntents:
|
||||
check isCatalogueIntent(t)
|
||||
|
||||
test "only this slice's intents answer with a real handler":
|
||||
test "only the built slices' intents answer with a real handler":
|
||||
check isImplementedIntent("conn.ping")
|
||||
check isImplementedIntent("key.create")
|
||||
for t in ["wall.add", "wall.update", "wall.remove", "door.set"]:
|
||||
check isImplementedIntent(t)
|
||||
check isGmOnlyIntent(t) # walls are GM-only (3.1, T2)
|
||||
check not isImplementedIntent("player.setname")
|
||||
check not isImplementedIntent("wall.add")
|
||||
check not isImplementedIntent("scene.set")
|
||||
check not isImplementedIntent("token.create")
|
||||
|
||||
suite "intent rate limit (6.4: 30/s, burst 100)":
|
||||
test "a fresh bucket allows exactly the burst, then refuses":
|
||||
@@ -187,3 +191,38 @@ suite "server frames (6.1)":
|
||||
check CloseMalformedFlood == 1008
|
||||
check [ReasonRevoked, ReasonEvicted, ReasonProtoMismatch, ReasonMalformedFlood] ==
|
||||
["revoked", "evicted", "proto-mismatch", "malformed-flood"]
|
||||
|
||||
suite "wall frames (6.1 `walls`, `wall`, `wall_gone`; GM only)":
|
||||
test "one wall carries id, a, b, kind, open and flags in the 6.1 shape":
|
||||
let w = wallObject(7, (10.0, 20.5), (300.0, 20.5), "door", true, %*{"locked": false})
|
||||
check w["id"].getInt == 7
|
||||
check w["a"][0].getFloat == 10.0
|
||||
check w["a"][1].getFloat == 20.5
|
||||
check w["b"][0].getFloat == 300.0
|
||||
check w["kind"].getStr == "door"
|
||||
check w["open"].getBool
|
||||
check w["flags"]["locked"].getBool == false
|
||||
# an absent flags object is still an object on the wire
|
||||
check wallObject(1, (0.0, 0.0), (1.0, 0.0), "wall", false, nil)["flags"].kind == JObject
|
||||
|
||||
test "`walls` is the full list plus the scene, `wall` is one upsert, `wall_gone` an id":
|
||||
let snap = wallsFrame(1, @[wallObject(1, (0.0, 0.0), (9.0, 0.0), "wall", false, nil)])
|
||||
check snap["t"].getStr == "walls"
|
||||
check snap["scene"].getInt == 1
|
||||
check snap["walls"].len == 1
|
||||
check snap["walls"][0]["id"].getInt == 1
|
||||
let one = wallFrame(1, wallObject(2, (0.0, 5.0), (9.0, 5.0), "door", false, nil))
|
||||
check one["t"].getStr == "wall"
|
||||
check one["scene"].getInt == 1
|
||||
check one["id"].getInt == 2
|
||||
check one["kind"].getStr == "door"
|
||||
let gone = wallGoneFrame(1, 2)
|
||||
check gone["t"].getStr == "wall_gone"
|
||||
check gone["scene"].getInt == 1
|
||||
check gone["id"].getInt == 2
|
||||
|
||||
test "the fan-out frames carry no n: the sender stamps it per recipient":
|
||||
check not wallsFrame(1, @[]).hasKey("n")
|
||||
check not wallFrame(1, wallObject(1, (0.0, 0.0), (1.0, 1.0), "wall", false, nil)).hasKey("n")
|
||||
check not wallGoneFrame(1, 1).hasKey("n")
|
||||
check withN(wallGoneFrame(1, 1), 12)["n"].getInt == 12
|
||||
|
||||
Reference in New Issue
Block a user