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).
This commit is contained in:
@@ -0,0 +1,189 @@
|
||||
## Wire protocol shell unit tests (#18, DESIGN 6, 6.2, 6.4, 6.5). Pure logic, no sockets:
|
||||
## the black-box behaviour over a real socket lives in tools/protocol.test.mjs.
|
||||
import std/[json, unittest]
|
||||
import protocol
|
||||
|
||||
suite "envelope (6.5 step 2)":
|
||||
test "a well-formed intent parses and keeps its reqId and node":
|
||||
let e = parseEnvelope("""{"t":"conn.ping","reqId":7,"ts":123}""")
|
||||
check e.ok
|
||||
check e.t == "conn.ping"
|
||||
check e.reqId == 7
|
||||
check e.node{"ts"}.getInt == 123
|
||||
|
||||
test "reqId boundaries: 0 and 2^31-1 pass, 2^31 and -1 are malformed":
|
||||
check parseEnvelope("""{"t":"conn.ping","reqId":0}""").reqId == 0
|
||||
check parseEnvelope("""{"t":"conn.ping","reqId":2147483647}""").reqId == MaxReqId
|
||||
check not parseEnvelope("""{"t":"conn.ping","reqId":2147483648}""").ok
|
||||
check not parseEnvelope("""{"t":"conn.ping","reqId":-1}""").ok
|
||||
|
||||
test "every unreadable frame is malformed, never an ack":
|
||||
for text in [
|
||||
"", # empty
|
||||
"not json", # not JSON
|
||||
"[1,2,3]", # not an object
|
||||
"123", # not an object
|
||||
"null",
|
||||
"""{"reqId":1}""", # no t
|
||||
"""{"t":5,"reqId":1}""", # t is not a string
|
||||
"""{"t":"conn.ping"}""", # no reqId
|
||||
"""{"t":"conn.ping","reqId":"1"}""", # reqId is not an integer
|
||||
"""{"t":"conn.ping","reqId":1.5}""", # reqId is not an integer
|
||||
"""{"t":"conn.ping","reqId":null}""",
|
||||
"""{"t":"conn.ping","reqId":1""", # truncated JSON
|
||||
]:
|
||||
check not parseEnvelope(text).ok
|
||||
|
||||
test "a payload that is not UTF-8 is malformed even when it parses as JSON bytes":
|
||||
check not parseEnvelope("{\"t\":\"conn.ping\",\"reqId\":1,\"x\":\"\xC3\x28\"}").ok
|
||||
check parseEnvelope("{\"t\":\"conn.ping\",\"reqId\":1,\"x\":\"caf\xC3\xA9\"}").ok
|
||||
|
||||
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
|
||||
for t in ImplementedIntents:
|
||||
check t in IntentCatalogue
|
||||
check isCatalogueIntent(t)
|
||||
check not isCatalogueIntent("token.teleport")
|
||||
check not isCatalogueIntent("TOKEN.MOVE")
|
||||
|
||||
test "role classes: the GM-only set never swallows the intents both roles may send":
|
||||
for t in ["conn.ping", "act.do", "player.setname", "token.move"]:
|
||||
check not isGmOnlyIntent(t)
|
||||
for t in ["key.create", "key.replace", "player.remove", "wall.add"]:
|
||||
check isGmOnlyIntent(t)
|
||||
for t in GmOnlyIntents:
|
||||
check isCatalogueIntent(t)
|
||||
|
||||
test "only this slice's intents answer with a real handler":
|
||||
check isImplementedIntent("conn.ping")
|
||||
check isImplementedIntent("key.create")
|
||||
check not isImplementedIntent("player.setname")
|
||||
check not isImplementedIntent("wall.add")
|
||||
|
||||
suite "intent rate limit (6.4: 30/s, burst 100)":
|
||||
test "a fresh bucket allows exactly the burst, then refuses":
|
||||
var r = newRateLimiter()
|
||||
for i in 0 ..< RateBurst:
|
||||
check r.allow(0)
|
||||
check r.available < 1.0
|
||||
check not r.allow(0)
|
||||
|
||||
test "refill is continuous at 30/s, capped at the burst":
|
||||
var r = newRateLimiter()
|
||||
for i in 0 ..< RateBurst: check r.allow(1000)
|
||||
check not r.allow(1000)
|
||||
check not r.allow(1032) # 32 ms -> 0.96 tokens: still empty
|
||||
check r.allow(1034) # 34 ms -> 1.02 tokens: one intent
|
||||
check not r.allow(1034)
|
||||
check r.allow(1100) # +66 ms -> ~1.98 more: two intents
|
||||
check r.allow(1100)
|
||||
check not r.allow(1100)
|
||||
check r.allow(2100) # a second of idle: 30 tokens
|
||||
var taken = 1
|
||||
for i in 0 ..< 40:
|
||||
if r.allow(2100): inc taken
|
||||
check taken == 30
|
||||
|
||||
test "the refill never exceeds the burst, however long the connection idles":
|
||||
var r = newRateLimiter()
|
||||
for i in 0 ..< RateBurst: check r.allow(0)
|
||||
discard r.allow(10_000_000)
|
||||
check r.available < float(RateBurst)
|
||||
var taken = 1
|
||||
for i in 0 ..< RateBurst * 3:
|
||||
if r.allow(10_000_000): inc taken
|
||||
check taken == RateBurst
|
||||
|
||||
test "the bucket is per connection and starts full: no shared state":
|
||||
var a = newRateLimiter()
|
||||
var b = newRateLimiter()
|
||||
for i in 0 ..< RateBurst: check a.allow(0)
|
||||
check not a.allow(0)
|
||||
check b.allow(0)
|
||||
|
||||
suite "malformed flood (6.5 row 8: 10 inside any 10 s)":
|
||||
test "nine malformed frames are tolerated, the tenth closes":
|
||||
var f: FloodWindow
|
||||
for i in 0 ..< MalformedFloodLimit - 1:
|
||||
check not f.recordMalformed(int64(i * 100))
|
||||
check f.recordMalformed(int64((MalformedFloodLimit - 1) * 100))
|
||||
|
||||
test "a frame slower than the window does not count: 9 fast + 1 slow is not a flood":
|
||||
var f: FloodWindow
|
||||
for i in 0 ..< MalformedFloodLimit - 1:
|
||||
check not f.recordMalformed(int64(i))
|
||||
check not f.recordMalformed(MalformedFloodWindowMs + 1000)
|
||||
|
||||
test "the window slides: the flood fires again only on a fresh ten inside it":
|
||||
var f: FloodWindow
|
||||
for i in 0 ..< MalformedFloodLimit:
|
||||
discard f.recordMalformed(int64(i))
|
||||
check not f.recordMalformed(MalformedFloodWindowMs + 5000)
|
||||
# that frame is itself one of the next ten: the tenth fresh one inside the window trips it
|
||||
for i in 0 ..< MalformedFloodLimit - 2:
|
||||
check not f.recordMalformed(MalformedFloodWindowMs + 6000 + int64(i))
|
||||
check f.recordMalformed(MalformedFloodWindowMs + 6000 + int64(MalformedFloodLimit - 2))
|
||||
|
||||
test "a second connection has its own window":
|
||||
var a, b: FloodWindow
|
||||
for i in 0 ..< MalformedFloodLimit: discard a.recordMalformed(int64(i))
|
||||
check not b.recordMalformed(3)
|
||||
|
||||
suite "server frames (6.1)":
|
||||
test "hello carries proto, role, me and n; an unnamed player's name is null":
|
||||
let h = helloFrame(ProtoVersion, 1, "player", 4, newJNull())
|
||||
check h["t"].getStr == "hello"
|
||||
check h["proto"].getInt == 1
|
||||
check h["role"].getStr == "player"
|
||||
check h["me"]["id"].getInt == 4
|
||||
check h["me"]["name"].kind == JNull
|
||||
check h["n"].getInt == 1
|
||||
let named = helloFrame(ProtoVersion, 2, "gm", 1, %"GM")
|
||||
check named["me"]["name"].getStr == "GM"
|
||||
|
||||
test "ack ok carries its result fields and never a code":
|
||||
let a = ackFrame(9, 3, %*{"key": "ABCD-EFGH"})
|
||||
check a["t"].getStr == "ack"
|
||||
check a["reqId"].getInt == 9
|
||||
check a["ok"].getBool
|
||||
check a["key"].getStr == "ABCD-EFGH"
|
||||
check a["n"].getInt == 3
|
||||
check not a.hasKey("code")
|
||||
let bare = ackFrame(9, 4)
|
||||
check bare["ok"].getBool
|
||||
check bare.len == 4 # t, reqId, ok, n
|
||||
|
||||
test "a refusal is a static code and no state":
|
||||
let r = nackFrame(9, 5, CodeRateLimited)
|
||||
check r["ok"].getBool == false
|
||||
check r["code"].getStr == "rate-limited"
|
||||
check not r.hasKey("pos")
|
||||
check r.len == 5 # t, reqId, ok, code, n
|
||||
|
||||
test "the uniform move refusal carries pos and no code (5.5, T9)":
|
||||
let m = nackMoveFrame(9, 6, 10.5, 20.25)
|
||||
check m["ok"].getBool == false
|
||||
check not m.hasKey("code")
|
||||
check m["pos"][0].getFloat == 10.5
|
||||
check m["pos"][1].getFloat == 20.25
|
||||
|
||||
test "error and closing frames have no reqId":
|
||||
let e = errorFrame(CodeMalformed, 7)
|
||||
check e["t"].getStr == "error"
|
||||
check not e.hasKey("reqId")
|
||||
check e["code"].getStr == "malformed"
|
||||
let c = closingFrame(ReasonRevoked, CloseRevoked, 8)
|
||||
check c["t"].getStr == "closing"
|
||||
check not c.hasKey("reqId")
|
||||
check c["reason"].getStr == "revoked"
|
||||
check c["code"].getInt == 4001
|
||||
check c["n"].getInt == 8
|
||||
|
||||
test "the close-code table of 6.5 is the app range plus 1008":
|
||||
check CloseRevoked == 4001
|
||||
check CloseEvicted == 4002
|
||||
check CloseProtoMismatch == 4003
|
||||
check CloseMalformedFlood == 1008
|
||||
check [ReasonRevoked, ReasonEvicted, ReasonProtoMismatch, ReasonMalformedFlood] ==
|
||||
["revoked", "evicted", "proto-mismatch", "malformed-flood"]
|
||||
Reference in New Issue
Block a user