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.
This commit is contained in:
2026-11-15 08:33:07 +01:00
parent eb48034eba
commit 7e2d5b8dc0
2 changed files with 139 additions and 10 deletions
+70 -8
View File
@@ -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