From 7e2d5b8dc03872900e91699bbd5ad952b6182c98 Mon Sep 17 00:00:00 2001 From: Davide Cappellini Date: Sun, 15 Nov 2026 08:33:07 +0100 Subject: [PATCH] server: per-connection wire state and closing frames in the conn registry (#18) Conn now carries what DESIGN 6/6.4/6.5 need per connection, all under the one registry lock: the outgoing n counter (starts at 1, server frames only), the intent token bucket, the malformed-flood window, the player's named flag and the last Pong. None of it is shared, so the n counter is not a global side channel (H25). activate/revokePlayer now hand back the doomed Conn values instead of raw sockets: the caller still has the frame count, so the final closing frame carries the right n before the close. Tests cover per-connection counters, the bucket and the flood window in isolation, and that a snapshot survives the lock. --- server/conns.nim | 78 +++++++++++++++++++++++++++++++++++++++++++----- tests/tconns.nim | 71 +++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 139 insertions(+), 10 deletions(-) diff --git a/server/conns.nim b/server/conns.nim index ebfdfe3..cf1bf51 100644 --- a/server/conns.nim +++ b/server/conns.nim @@ -1,18 +1,31 @@ -## Live WebSocket connection registry (DESIGN 4.3, 6.5; issue #17). +## Live WebSocket connection registry (DESIGN 4.3, 6.5; issues #17, #18). ## Caps FIXED (owner-delegated, #15): 4 connections per player (a 5th evicts that player's oldest), ## 16 total (the 17th is refused before the upgrade). Connections are kept in activation order, which ## is the eviction order. Keyed by an app connId, not by WebSocket fields (H19). ## One lock, held only for these O(16) list operations. The caller closes the tickets returned. +## +## Wire state per connection (#18): the outgoing `n` counter (DESIGN 6), the intent token bucket and +## the malformed-flood window (6.4, 6.5 row 8), and the last Pong seen. All of it lives here so the +## one lock also serializes it; none of it is shared between connections (no global counter, H25). +## `activate`/`revokePlayer` hand back the doomed `Conn` *values*: the caller still has the id, the +## socket and the frame count, so it can send the final `closing` frame with `frames + 1` and only +## then close (6.5, FIXED #18). A registry never holds a connection that is being closed. import std/[locks, options] import mummy -import auth +import auth, protocol type Conn* = object id*: int playerId*: int role*: PlayerRole + named*: bool ## the player has a display name (DESIGN 6.1 Roles), as of activation ws*: WebSocket + frames*: int ## server frames sent on this connection: `n` counts from here + limiter*: RateLimiter + flood*: FloodWindow + pongSeq*: int64 ## payload of the last Pong the client sent back + lastPongMs*: int64 ## when it arrived (lag tracking is M5, 4.3) Conns* = ref object lock: Lock @@ -25,7 +38,7 @@ type Activation* = object id*: int evictedId*: Option[int] - evicted*: Option[WebSocket] + evicted*: Option[Conn] const MaxConnsPerPlayer* = 4 @@ -49,7 +62,8 @@ proc playerConnIndices(c: Conns, playerId: int): seq[int] = for i, conn in c.active: if conn.playerId == playerId: result.add i -proc activate*(c: Conns, playerId: int, role: PlayerRole, ws: WebSocket): Activation = +proc activate*(c: Conns, playerId: int, role: PlayerRole, ws: WebSocket, + named = true): Activation = ## After a successful upgrade. A 5th connection of one player evicts that player's oldest. withLock c.lock: if c.pending > 0: dec c.pending @@ -57,11 +71,13 @@ proc activate*(c: Conns, playerId: int, role: PlayerRole, ws: WebSocket): Activa if mine.len >= c.maxPerPlayer: let oldest = mine[0] result.evictedId = some(c.active[oldest].id) - result.evicted = some(c.active[oldest].ws) + result.evicted = some(c.active[oldest]) c.active.delete(oldest) inc c.nextId result.id = c.nextId - c.active.add Conn(id: c.nextId, playerId: playerId, role: role, ws: ws) + c.active.add Conn(id: c.nextId, playerId: playerId, role: role, named: named, ws: ws, + limiter: newRateLimiter()) + # (frame/flood state starts empty: first frame n = 1, full bucket, no malformed frames) proc remove*(c: Conns, connId: int) = withLock c.lock: @@ -81,13 +97,18 @@ proc connForWs*(c: Conns, ws: WebSocket): Option[Conn] = for conn in c.active: if conn.ws == ws: return some(conn) -proc revokePlayer*(c: Conns, playerId: int): seq[WebSocket] = +proc snapshot*(c: Conns): seq[Conn] = + ## All live connections, for the ping heartbeat (nothing is sent under the lock). + withLock c.lock: + result = c.active + +proc revokePlayer*(c: Conns, playerId: int): seq[Conn] = ## key.replace / player.remove / GM key rotation: every live connection of that player. withLock c.lock: var i = 0 while i < c.active.len: if c.active[i].playerId == playerId: - result.add c.active[i].ws + result.add c.active[i] c.active.delete(i) else: inc i @@ -103,3 +124,44 @@ proc activeCountFor*(c: Conns, playerId: int): int = proc pendingCount*(c: Conns): int = withLock c.lock: result = c.pending + +# --------------------------------------------------------------------------------------------------- +# Per-connection wire state (DESIGN 6, 6.4, 6.5 row 8). Every proc returns a defensive value when +# the connection is already gone: the caller simply sends nothing. + +proc frameNo*(conn: Conn): int = + ## The number the next frame on this (possibly already removed) connection would carry. A removed + ## connection is sent its final `closing` frame by the caller with this value (FIXED #18). + conn.frames + 1 + +proc nextFrameNo*(c: Conns, connId: int): int = + ## The per-connection counter, incremented under the lock so concurrent senders never collide. + ## 0 = the connection is gone; the caller must drop the frame. + withLock c.lock: + for i in 0 ..< c.active.len: + if c.active[i].id == connId: + inc c.active[i].frames + return c.active[i].frames + +proc takeIntentToken*(c: Conns, connId: int, nowMs: int64): bool = + ## DESIGN 6.4/6.5 step 3. Unknown connection = no token (nothing will be answered anyway). + withLock c.lock: + for i in 0 ..< c.active.len: + if c.active[i].id == connId: + return c.active[i].limiter.allow(nowMs) + +proc recordMalformed*(c: Conns, connId: int, nowMs: int64): bool = + ## DESIGN 6.5 row 8. true = this frame trips the flood rule: the caller closes with 1008. + withLock c.lock: + for i in 0 ..< c.active.len: + if c.active[i].id == connId: + return c.active[i].flood.recordMalformed(nowMs) + +proc notePong*(c: Conns, connId: int, seqNo, nowMs: int64) = + ## Records the Pong the client sent back. Enforcement (stop feeding a lagging client) is M5. + withLock c.lock: + for i in 0 ..< c.active.len: + if c.active[i].id == connId: + c.active[i].pongSeq = seqNo + c.active[i].lastPongMs = nowMs + return diff --git a/tests/tconns.nim b/tests/tconns.nim index cf7bdf7..14bbe83 100644 --- a/tests/tconns.nim +++ b/tests/tconns.nim @@ -1,7 +1,9 @@ ## Connection caps (#17, DESIGN 4.3/6.5): 4 per player (5th evicts the oldest), 16 total (17th refused). +## Per-connection wire state (#18, DESIGN 6/6.4/6.5 row 8): the `n` counter, the intent bucket and +## the malformed-flood window are per connection and none of them is global. import std/[unittest, options] import mummy -import conns, auth +import conns, auth, protocol proc dummyWs(): WebSocket = # Mummy's fields are private; an all-zero value is enough for registry bookkeeping tests. @@ -50,6 +52,8 @@ suite "per-player cap": check c.reserve() let fifth = c.activate(7, prPlayer, dummyWs()) check fifth.evictedId == some(ids[0]) + check fifth.evicted.get.playerId == 7 + check fifth.evicted.get.frameNo == 1 # a fresh connection: its closing frame is n = 1 check c.activeCountFor(7) == 4 check c.connById(ids[0]).isNone check c.connById(fifth.id).isSome @@ -85,7 +89,10 @@ suite "revocation": discard c.activate(1, prPlayer, dummyWs()) discard c.activate(2, prPlayer, dummyWs()) discard c.activate(1, prPlayer, dummyWs()) - check c.revokePlayer(1).len == 2 + let revoked = c.revokePlayer(1) + check revoked.len == 2 + check revoked[0].playerId == 1 + for conn in revoked: check c.connById(conn.id).isNone check c.activeCountFor(1) == 0 check c.activeCountFor(2) == 1 check c.activeCount == 1 @@ -106,3 +113,63 @@ suite "revocation": check c.connForWs(ws).get.id == a.id var other: WebSocket # another all-zero value still equals the first one structurally check c.connForWs(other).isSome + +suite "per-connection wire state (#18)": + test "the frame counter starts at 1 on each connection and is never global": + let c = newConns() + let a = c.activate(1, prPlayer, dummyWs()) + let b = c.activate(1, prPlayer, dummyWs()) + check c.nextFrameNo(a.id) == 1 + check c.nextFrameNo(a.id) == 2 + check c.nextFrameNo(b.id) == 1 # per connection, not a server-wide sequence (H25) + check c.nextFrameNo(a.id) == 3 + check c.connById(b.id).get.frames == 1 + + test "a removed connection has no next frame number; the caller sends closing with frameNo": + let c = newConns() + let a = c.activate(1, prPlayer, dummyWs()) + discard c.nextFrameNo(a.id) + discard c.nextFrameNo(a.id) + let doomed = c.connById(a.id).get + check doomed.frameNo == 3 + c.remove(a.id) + check c.nextFrameNo(a.id) == 0 # gone: drop the frame + check doomed.frameNo == 3 # the snapshot still says which number closes it + + test "the intent bucket is per connection: draining one leaves the other full": + let c = newConns() + let a = c.activate(1, prPlayer, dummyWs()) + let b = c.activate(2, prPlayer, dummyWs()) + for _ in 0 ..< RateBurst: check c.takeIntentToken(a.id, 0) + check not c.takeIntentToken(a.id, 0) + check c.takeIntentToken(b.id, 0) + check not c.takeIntentToken(999, 0) # unknown connection: nothing to spend it on + + test "the malformed window is per connection and fires on the tenth frame": + let c = newConns() + let a = c.activate(1, prPlayer, dummyWs()) + let b = c.activate(2, prPlayer, dummyWs()) + for i in 0 ..< MalformedFloodLimit - 1: + check not c.recordMalformed(a.id, int64(i)) + check c.recordMalformed(a.id, int64(MalformedFloodLimit - 1)) + check not c.recordMalformed(b.id, 0) + + test "a Pong is recorded on the right connection": + let c = newConns() + let a = c.activate(1, prPlayer, dummyWs()) + let b = c.activate(2, prPlayer, dummyWs()) + c.notePong(a.id, 5, 4242) + check c.connById(a.id).get.pongSeq == 5 + check c.connById(a.id).get.lastPongMs == 4242 + check c.connById(b.id).get.pongSeq == 0 + + test "a snapshot hands out every live connection without holding the lock afterwards": + let c = newConns() + let a = c.activate(1, prPlayer, dummyWs()) + discard c.activate(2, prGm, dummyWs()) + let snap = c.snapshot() + check snap.len == 2 + check snap[0].id == a.id + c.remove(a.id) + check snap.len == 2 + check c.activeCount == 1