Connection Hub¶
ConnectionHub is the central in-memory registry for live IConnection instances in Nalix.Network. It shards connections across multiple dictionaries, keeps username mappings, supports broadcast and forced disconnect flows, and exposes runtime diagnostics.
Source mapping¶
src/Nalix.Network/Connections/Connection.Hub.cssrc/Nalix.Network/Connections/Connection.Hub.Statistics.cssrc/Nalix.Network/Connections/Connection.Hub.EventArgs.cssrc/Nalix.Network/Configurations/ConnectionHubOptions.cs
Core design¶
- Connections are distributed across internal shards using the connection ID hash.
- Usernames are tracked in two maps:
ID -> usernameusername -> ID- Anonymous connections are also queued in FIFO order so
DROP_OLDESTcan evict them efficiently. Statisticsreturns a structured snapshot with connection count, drop policy, shard count, anonymous queue depth, evicted count, and rejected count.
Main operations¶
| Method | Purpose |
|---|---|
RegisterConnection(connection) |
Adds a connection and subscribes the close event. |
UnregisterConnection(connection) |
Removes the connection, username mapping, and event subscription. |
AssociateUsername(connection, username) |
Applies trim/length/regex rules and stores the username mapping. |
GetConnection(id) / GetConnection(username) |
Resolves an active connection. |
ListConnections() |
Returns a snapshot of active connections. |
BroadcastAsync(...) |
Sends to all active connections. |
BroadcastWhereAsync(...) |
Sends to matching connections only. |
ForceClose(endpoint) |
Disconnects all matching connections by address. |
CloseAllConnections(reason) |
Disconnects everything in parallel. |
GenerateReport() |
Returns a runtime summary string. |
Capacity behavior¶
When MaxConnections is reached:
DROP_NEWESTdisconnects the incoming connection and increments rejected count.DROP_OLDESTsearches the anonymous FIFO for an evictable connection and disconnects it.
In both cases the hub raises CapacityLimitReached.
Broadcast behavior¶
BroadcastBatchSize > 0enables batchedTask.WhenAll(...)fan-out.- Without batching, the hub partitions the connection list and processes partitions in parallel.
ParallelDisconnectDegreecontrols bulk disconnect parallelism.
Username rules¶
AssociateUsername(...) currently:
- ignores null/whitespace usernames
- optionally trims according to
TrimUsernames - truncates to
MaxUsernameLength - only accepts
^[a-zA-Z0-9_]+$
Diagnostics¶
GenerateReport() includes:
- total, anonymous, and authenticated connection counts
- evicted and rejected counts
- shard count and anonymous queue depth
- configured max connection count and drop policy
- bytes sent and uptime aggregates
- per-status and per-algorithm summaries
- the first 15 active connections with usernames
Basic usage¶
hub.RegisterConnection(connection);
hub.AssociateUsername(connection, "sample_user");
IConnection? sameConnection = hub.GetConnection(connection.ID);
await hub.BroadcastAsync(new PingResponse(), ct);