Files
FFF_vtt_frozen/tests/tprotocol.nim
T

247 lines
11 KiB
Nim

## 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 == 29 # slice 10 (#25): `scene.set` closed the last gap
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 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)
for t in ["token.create", "token.update", "token.move", "token.remove"]:
check isImplementedIntent(t)
for t in ["player.setname", "player.rename", "key.show", "token.resize", "status.set",
"status.clear", "prop.set", "prop.unset", "character.create", "character.update",
"character.remove", "character.reassign", "name.reveal", "name.reveal_all",
"encountered.remove", "scene.set"]:
check isImplementedIntent(t)
check isGmOnlyIntent("scene.set") # scene edits are GM-only (6.1)
# Every catalogue intent has a handler now (#25): no `unknown-type` gap is left.
for t in IntentCatalogue:
check isImplementedIntent(t)
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 not h.hasKey("scene") # an unnamed player gets proto, role, me only (6.1)
check not h.hasKey("extra")
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 "a named recipient's hello carries the scene block, and the GM also `extra`":
let sceneJson = %*{"id": 1, "w": 4096}
let p = helloFrame(ProtoVersion, 3, "player", 4, %"Alice", sceneJson)
check p["scene"]["id"].getInt == 1
check not p.hasKey("extra")
let gm = helloFrame(ProtoVersion, 4, "gm", 1, %"GM", sceneJson, %*{})
check gm["extra"].kind == JObject
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"]
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