Files
FFF_vtt_frozen/server/protocol.nim
T
SirStone eb48034eba server: wire protocol module - envelope, frames, rate limit, flood window (#18)
Pure, mummy-free module for the protocol shell: the envelope rules of DESIGN 6.5
step 2 (UTF-8 text, JSON object, string t, integer reqId in 0..2^31-1), the frame
builders of 6.1 including closal/closing, the per-connection intent token bucket
(30/s, burst 100) and the malformed-flood window (10 in any 10 s), plus the FIXED
constants: proto 1, 64 KB inbound, close codes 4001/4002/4003/1008 and their reason
strings. The 29-intent catalogue and the GM-only set live here so 'unknown type'
and role checks have one definition.

Found while testing: std/json parseJson("") returns nil instead of raising, and
node{"t"} is nil for a missing key, so both are guarded (a bare {} would have
crashed the handler).
2026-11-15 08:33:01 +01:00

217 lines
9.3 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]
const
ProtoVersion* = 1
## M3 ships proto 1 (DESIGN 6.2). 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"
# 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", "player.remove"]
## What this slice actually handles. The rest of the catalogue answers `unknown-type` until
## its slice lands (DESIGN 6.1 note, #18).
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 =
result = node
result["n"] = %n
proc helloFrame*(proto, n: int, role: string, playerId: int, name: JsonNode): JsonNode =
## DESIGN 6.1 `hello`. The `scene` block and the world fields arrive with slice 5; M3 slice 3
## sends what exists: proto, role, me.
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}
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. Unused until
## slice 5's `token.move`; kept with the frame builders 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}
# ---------------------------------------------------------------------------------------------------
# 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