Files

181 lines
6.9 KiB
Nim

## 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, 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
nextId: int
pending: int ## upgrades in flight, reserved against the total cap
maxPerPlayer: int
maxTotal: int
active: seq[Conn] ## activation order; active[0] is the oldest of the whole server
Activation* = object
id*: int
evictedId*: Option[int]
evicted*: Option[Conn]
const
MaxConnsPerPlayer* = 4
MaxConnsTotal* = 16
proc newConns*(maxPerPlayer = MaxConnsPerPlayer, maxTotal = MaxConnsTotal): Conns =
result = Conns(maxPerPlayer: maxPerPlayer, maxTotal: maxTotal)
initLock(result.lock)
proc reserve*(c: Conns): bool =
## Before the upgrade: false means the 17th connection - answer HTTP 503, no upgrade.
withLock c.lock:
result = c.active.len + c.pending < c.maxTotal
if result: inc c.pending
proc cancelReserve*(c: Conns) =
withLock c.lock:
if c.pending > 0: dec c.pending
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,
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
let mine = c.playerConnIndices(playerId)
if mine.len >= c.maxPerPlayer:
let oldest = mine[0]
result.evictedId = some(c.active[oldest].id)
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, 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:
for i, conn in c.active:
if conn.id == connId:
c.active.delete(i)
return
proc connById*(c: Conns, connId: int): Option[Conn] =
withLock c.lock:
for conn in c.active:
if conn.id == connId: return some(conn)
proc connForWs*(c: Conns, ws: WebSocket): Option[Conn] =
## Mummy hands the same WebSocket value back on MessageEvent/CloseEvent (H19 layout check).
withLock c.lock:
for conn in c.active:
if conn.ws == ws: return some(conn)
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]
c.active.delete(i)
else:
inc i
proc activeCount*(c: Conns): int =
withLock c.lock:
result = c.active.len
proc markNamed*(c: Conns, playerId: int) =
## `player.setname` succeeded: from now on that player's connections are fed state (6.3). Without
## this an unnamed connection would keep receiving nothing but `hello` for ever.
withLock c.lock:
for i in 0 ..< c.active.len:
if c.active[i].playerId == playerId: c.active[i].named = true
proc connectionsOf*(c: Conns, playerId: int): seq[Conn] =
## Every live connection of one player, in activation order (6.1: `hello` + resync to each).
withLock c.lock:
for conn in c.active:
if conn.playerId == playerId: result.add conn
proc activeCountFor*(c: Conns, playerId: int): int =
withLock c.lock:
result = c.playerConnIndices(playerId).len
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