Add networking foundation — 9-project C# solution (compiles clean)

Implements the modular networking layer for SOR Server:
- SOR.Networking.Abstractions: pure interfaces (ITransport, IClientConnection,
  IMessageSerializer, IMessageDispatcher, IMessageHandler, IEventBus, IClientPush)
- SOR.Networking.WebSocket: ITransport + IClientConnection over System.Net.WebSockets
- SOR.Networking.Nats: IEventBus over NATS.Net (INatsConnection)
- SOR.Networking.Redis: IClientPush over Redis Pub/Sub
- SOR.Shared: ServiceResult<T>, RedisKeys, NatsSubjects, ServerMessage, JSON serializer
- SOR.Shared.Proto: auth.proto with gRPC AuthService contract
- SOR.Gateway: accept loop, auth handshake, dispatcher, Redis push subscriber
- SOR.Auth: stub gRPC handler (placeholder responses)
- SOR.Host: multi-service runner via ENABLED_SERVICES env var; wires all DI

All concrete implementations are wired exclusively in SOR.Host — every transport,
broker, and push implementation can be swapped by changing only Program.cs.

dotnet build SOR.slnx → 0 errors, 0 warnings

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
dingo
2026-02-24 21:01:38 -05:00
co-authored by Claude Happy
parent 0f95a0721b
commit d21adbc8d0
52 changed files with 3522 additions and 0 deletions
@@ -0,0 +1,62 @@
namespace SOR.Networking.Abstractions.EventBus;
/// <summary>
/// Async publish/subscribe event bus.
///
/// Current implementation: NATS (SOR.Networking.Nats.NatsEventBus).
/// To swap to RabbitMQ: create SOR.Networking.RabbitMq.RabbitMqEventBus,
/// register it instead of NatsEventBus in SOR.Host. Service code does not change.
///
/// Usage pattern:
/// - Publishers call PublishAsync on domain events (game ended, card purchased, etc.)
/// - Subscribers (IHostedService) call SubscribeAsync and process via await foreach
///
/// The Gateway does NOT use IEventBus for client push delivery — that goes through
/// IClientPush → Redis Pub/Sub → Gateway Redis subscriber → WebSocket.
/// IEventBus is for inter-service async fan-out only.
///
/// Lifetime: Singleton.
/// </summary>
public interface IEventBus
{
/// <summary>
/// Publishes an event to the named subject.
///
/// Fire-and-forget from the publisher's perspective — delivery to subscribers
/// is handled by the broker. No reply is expected or waited for.
///
/// Subject naming convention: "sor.{service}.{event}"
/// Examples: "sor.game.ended", "sor.bazaar.purchase.completed"
/// All subject constants are defined in SOR.Shared.Nats.NatsSubjects.
///
/// T must be serializable by the underlying broker's serializer.
/// The default NATS implementation uses System.Text.Json.
/// </summary>
Task PublishAsync<T>(
string subject,
T payload,
CancellationToken cancellationToken = default)
where T : notnull;
/// <summary>
/// Subscribes to a subject and returns an async stream of received messages.
///
/// Callers consume this with 'await foreach':
/// await foreach (var evt in _bus.SubscribeAsync{GameEndedEvent}(subject, ct))
/// {
/// await ProcessAsync(evt);
/// }
///
/// The stream ends when cancellationToken is cancelled (application shutdown).
/// Callers should catch OperationCanceledException as the normal exit signal.
///
/// Each subscriber receives its own copy of published messages (fan-out).
/// Multiple instances of the same service subscribing to the same subject
/// each receive a copy — use NATS JetStream with queue groups for
/// competing-consumer (load-balanced) patterns when needed.
/// </summary>
IAsyncEnumerable<T> SubscribeAsync<T>(
string subject,
CancellationToken cancellationToken = default)
where T : notnull;
}
@@ -0,0 +1,42 @@
namespace SOR.Networking.Abstractions.Messaging;
/// <summary>
/// A single message received from a client, after the transport layer has
/// read the raw bytes and the serializer has parsed the envelope.
///
/// Wire format (JSON):
/// { "type": "chat.send", "seq": 7, "payload": { ... } }
///
/// The transport produces a RawClientMessage with just the raw bytes.
/// IMessageSerializer.Deserialize() populates Type, Seq, and Payload from those bytes.
/// The dispatcher then calls IMessageSerializer.DeserializePayload{T}(Payload)
/// to get the handler-specific request object.
/// </summary>
public interface IClientMessage
{
/// <summary>
/// Dot-namespaced message type string. Convention: "{service}.{action}".
/// Examples: "auth.hello", "game.play_card", "chat.send", "collection.view_deck"
///
/// Used by IMessageDispatcher to look up the correct IMessageHandler.
/// </summary>
string Type { get; }
/// <summary>
/// Client-assigned sequence number. Monotonically increasing per connection.
/// The server echoes this back in the 'ref' field of the response so the client
/// can match async responses to the original requests.
/// </summary>
int Seq { get; }
/// <summary>
/// Serialized inner payload — the message-type-specific data.
/// The envelope (type, seq) has already been extracted.
/// Each IMessageHandler calls IMessageSerializer.DeserializePayload{T}(Payload)
/// to convert this into its specific request type.
///
/// ReadOnlyMemory{byte} avoids copying: the bytes are owned by the transport
/// receive buffer and valid for the lifetime of this message object.
/// </summary>
ReadOnlyMemory<byte> Payload { get; }
}
@@ -0,0 +1,39 @@
namespace SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Transport;
/// <summary>
/// Routes an incoming client message to the IMessageHandler registered for its type.
///
/// Built once at startup from all IMessageHandler registrations in the DI container.
/// The dispatch table is frozen after construction — handlers cannot be added at runtime.
///
/// Lifetime: Singleton.
/// </summary>
public interface IMessageDispatcher
{
/// <summary>
/// Returns true if a handler is registered for the given message type.
/// Gateway uses this to reject messages with unknown types before attempting dispatch,
/// providing a clear "UNKNOWN_TYPE" error response instead of a null return.
/// </summary>
bool HasHandler(string messageType);
/// <summary>
/// Finds and invokes the handler registered for message.Type.
///
/// Returns the handler's response, or null if the handler returned null
/// (fire-and-forget or deferred push). The Gateway connection loop sends
/// the response if non-null.
///
/// Precondition: HasHandler(message.Type) is true. The caller checks this
/// before calling DispatchAsync — an unknown type produces an error reply,
/// not a dispatch call.
///
/// The connection parameter is forwarded to the handler unchanged.
/// </summary>
Task<IServerMessage?> DispatchAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken cancellationToken);
}
@@ -0,0 +1,59 @@
namespace SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Transport;
/// <summary>
/// Handles one specific message type received from a client.
///
/// Registration pattern (plugin-style):
/// Each service module registers its handlers in DI:
/// services.AddTransient{IMessageHandler, ChatSendHandler}()
///
/// MessageDispatcher collects all registered IMessageHandler implementations
/// via IEnumerable{IMessageHandler} injection and builds a dispatch table.
/// No Gateway code changes when a new service adds handlers.
///
/// Convention:
/// - One handler class per message type.
/// - File name matches: "{MessageType}.Replace('.', '_')}Handler.cs"
/// - Example: "chat.send" → ChatSendHandler.cs
///
/// Lifetime: Transient. A new handler instance is created per message.
/// This means handlers can safely use Scoped services (injected into the constructor
/// via the DI scope created around each dispatch call in MessageDispatcher).
/// </summary>
public interface IMessageHandler
{
/// <summary>
/// The message type this handler processes.
/// Must be unique across all registered handlers in the process.
/// Convention: "{service}.{action}" — all lowercase, dot-separated.
/// Examples: "auth.hello", "game.play_card", "chat.send", "collection.view_deck"
///
/// MessageDispatcher throws InvalidOperationException at startup if two handlers
/// share the same MessageType, making duplicate registrations a startup crash
/// rather than a silent bug.
/// </summary>
string MessageType { get; }
/// <summary>
/// Handles the incoming message and returns an optional direct reply.
///
/// Return null when:
/// - The handler is fire-and-forget (no client reply needed)
/// - The reply will arrive later as a push event via IClientPush
///
/// Return a ServerMessage when:
/// - A synchronous acknowledgement is appropriate ("auth.hello.ack", etc.)
/// - An error response must be sent
///
/// The connection parameter carries the userId (connection.UserId) and
/// a reference to the underlying IClientConnection for sending if needed.
/// Prefer returning a non-null IServerMessage over calling SendBytesAsync
/// directly — the Gateway connection loop handles the send uniformly.
/// </summary>
Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken cancellationToken);
}
@@ -0,0 +1,50 @@
namespace SOR.Networking.Abstractions.Messaging;
/// <summary>
/// Serializes and deserializes message envelopes and payloads.
///
/// Two responsibilities:
/// 1. Envelope codec: converts wire bytes ↔ IClientMessage / IServerMessage
/// 2. Payload codec: converts payload bytes ↔ handler-specific request/response types
///
/// Default implementation: SystemTextJsonSerializer (System.Text.Json, camelCase)
/// Swap-in: MessagePackSerializer — register it instead of the JSON implementation
/// in SOR.Host. No other code changes anywhere.
///
/// Lifetime: Singleton. Implementations must be thread-safe.
/// </summary>
public interface IMessageSerializer
{
/// <summary>
/// Parses a complete wire frame into its envelope fields (type, seq) plus
/// the raw serialized payload bytes.
///
/// Called once per received message in the transport layer before dispatch.
/// The returned IClientMessage's Payload contains only the inner payload bytes,
/// not the full envelope — the envelope fields have been extracted.
///
/// Throws JsonException (or equivalent) on malformed input.
/// </summary>
IClientMessage Deserialize(ReadOnlySpan<byte> wireBytes);
/// <summary>
/// Encodes an IServerMessage into wire bytes ready for transmission.
///
/// Called by the Gateway send path just before calling
/// IClientConnection.SendBytesAsync().
/// </summary>
ReadOnlyMemory<byte> Serialize(IServerMessage message);
/// <summary>
/// Deserializes a raw payload into a handler-specific request type T.
///
/// Called by each IMessageHandler after receiving IClientMessage.Payload.
/// The payload bytes were extracted from the original envelope by Deserialize().
///
/// Example:
/// var req = _serializer.DeserializePayload{ChatSendRequest}(message.Payload);
///
/// Throws on type mismatch or malformed payload.
/// </summary>
T DeserializePayload<T>(ReadOnlyMemory<byte> payload) where T : notnull;
}
@@ -0,0 +1,40 @@
namespace SOR.Networking.Abstractions.Messaging;
/// <summary>
/// An outbound message to be sent to a client.
///
/// Produced by:
/// - IMessageHandler.HandleAsync() — reply to a specific client request
/// - IClientPush.PushAsync() — unsolicited server-initiated event
///
/// Wire format (JSON) for a reply:
/// { "type": "chat.send.ack", "ref": 7, "payload": { ... } }
///
/// Wire format (JSON) for an unsolicited push (ref = 0):
/// { "type": "game.state_update", "ref": 0, "payload": { ... } }
///
/// IMessageSerializer.Serialize() converts this into bytes for transmission.
/// </summary>
public interface IServerMessage
{
/// <summary>
/// Dot-namespaced message type. Convention: "{service}.{action}" or
/// "{service}.{action}.ack" for acknowledgement replies.
/// Examples: "auth.hello.ack", "game.state_update", "error"
/// </summary>
string Type { get; }
/// <summary>
/// The client Seq number this message is a response to.
/// Set to 0 for unsolicited push events (no corresponding client request).
/// The client uses this to match async responses to pending requests.
/// </summary>
int Ref { get; }
/// <summary>
/// The payload object. Will be serialized by IMessageSerializer.Serialize().
/// Can be any serializable C# object (anonymous types, records, DTOs).
/// Null is valid for messages that carry no payload (e.g., a bare acknowledgement).
/// </summary>
object? Payload { get; }
}
@@ -0,0 +1,40 @@
namespace SOR.Networking.Abstractions.Push;
using SOR.Networking.Abstractions.Messaging;
/// <summary>
/// Pushes a server-initiated message to a specific user's connected client.
///
/// This is the WRITE side of the push delivery pipeline:
/// Caller → IClientPush → Redis Pub/Sub → Gateway subscriber → WebSocket → Client
///
/// Current implementation: RedisClientPush (SOR.Networking.Redis).
/// To swap: create an alternative IClientPush implementation (e.g., direct in-process
/// for single-instance deployments) and register it instead. No service code changes.
///
/// The GATEWAY also has a READ side (RedisPushSubscriber) that subscribes to
/// the Redis channels for its connected users and forwards messages over WebSocket.
/// The read side is internal to SOR.Gateway and not exposed through this interface.
///
/// Lifetime: Singleton.
/// </summary>
public interface IClientPush
{
/// <summary>
/// Publishes a push message targeting the specified user.
///
/// Best-effort delivery: if no Gateway instance has the user connected,
/// the message is dropped. This is intentional — push is not a reliable
/// message queue. Use persistent storage + client sync for reliable delivery
/// of important state (e.g., game state is stored in Redis and clients
/// request it on reconnect; the push is just a notification to refresh).
///
/// Multiple Gateway instances may be subscribed to the same userId channel
/// (e.g., if the user has two browser tabs open). All will receive and
/// forward the message — the client is responsible for idempotent handling.
/// </summary>
Task PushAsync(
string userId,
IServerMessage message,
CancellationToken cancellationToken = default);
}
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AssemblyName>SOR.Networking.Abstractions</AssemblyName>
<!-- This project is purely interfaces and records.
It has zero NuGet dependencies — only the .NET BCL (Base Class Library).
Keeping it dependency-free means any project can reference it without
pulling in heavy transitive packages. -->
</PropertyGroup>
</Project>
@@ -0,0 +1,40 @@
namespace SOR.Networking.Abstractions.Transport;
/// <summary>
/// An IClientConnection that has completed the auth handshake successfully.
///
/// Created by ConnectionLoop.RunAsync() after GatewayAuthValidator confirms the
/// session token is valid. Immutable — properties are set once and never changed.
///
/// This is the context object passed to every IMessageHandler. Handlers use it to:
/// - Know which user sent the message (UserId, DisplayName)
/// - Send replies back to the correct client (Connection.SendBytesAsync)
///
/// 'record' in C# generates equality comparison (by value of all properties),
/// a ToString() override, and a constructor automatically. The 'sealed' modifier
/// means no class can inherit from it.
/// </summary>
public sealed record AuthenticatedConnection(
/// <summary>The underlying transport connection for sending replies.</summary>
IClientConnection Connection,
/// <summary>
/// The authenticated user's unique identifier. A GUID stored as a string.
/// This is the authoritative identity for all service calls made on behalf
/// of this connection.
/// </summary>
string UserId,
/// <summary>
/// The user's display name at the time of authentication.
/// Cached here to avoid repeated lookups during the session.
/// </summary>
string DisplayName,
/// <summary>
/// The session token used to authenticate this connection.
/// Stored for revocation checks — if the token is invalidated mid-session,
/// the connection can be closed.
/// </summary>
string SessionToken
);
@@ -0,0 +1,69 @@
namespace SOR.Networking.Abstractions.Transport;
using SOR.Networking.Abstractions.Messaging;
/// <summary>
/// Represents a single connected client for the lifetime of their connection —
/// from the moment the transport accepts them to the moment they disconnect.
///
/// IClientConnection is the raw, unauthenticated view of a connection.
/// After the auth handshake succeeds, it is wrapped in an AuthenticatedConnection
/// which adds the userId and display name.
///
/// Thread safety: ReceiveAsync and SendBytesAsync must NOT be called concurrently.
/// The Gateway connection loop ensures only one receive and one send are in flight
/// at a time per connection. The send lock in the implementation handles concurrent
/// send attempts (e.g., push delivery arriving while a reply is being sent).
///
/// Lifetime: Scoped to one connection. Disposed by ConnectionLoop.RunAsync()
/// in its finally block regardless of how the loop exits.
/// </summary>
public interface IClientConnection : IAsyncDisposable
{
/// <summary>
/// Stable identifier for this connection. Assigned at accept time as a GUID.
/// This is NOT the user ID — the connection exists before authentication.
/// Used in logs and the ConnectionManager index.
/// </summary>
string ConnectionId { get; }
/// <summary>
/// Remote endpoint for logging (e.g., "203.0.113.42:55201").
/// </summary>
string RemoteAddress { get; }
/// <summary>
/// True while the underlying transport channel is open and usable.
/// May become false asynchronously when the client drops.
/// </summary>
bool IsConnected { get; }
/// <summary>
/// Reads and returns the next complete message from the client.
/// Returns null on a clean close (client sent a close frame or disconnected gracefully).
/// Throws on network error — the connection loop catches and breaks.
///
/// The returned IClientMessage contains raw bytes. The message type and seq are
/// populated by IMessageSerializer.Deserialize() before dispatch.
/// </summary>
Task<IClientMessage?> ReceiveAsync(CancellationToken cancellationToken);
/// <summary>
/// Sends pre-serialized bytes to the client.
///
/// Callers (Gateway send path and RedisPushSubscriber) pass bytes that have
/// already been serialized by IMessageSerializer.Serialize(). This keeps
/// the transport layer ignorant of the message format.
///
/// Implementations must serialize concurrent send calls — only one send may
/// be in flight over the underlying transport at a time.
/// </summary>
ValueTask SendBytesAsync(ReadOnlyMemory<byte> bytes, CancellationToken cancellationToken);
/// <summary>
/// Initiates a graceful close. Implementations send a protocol-level close
/// frame where supported (e.g., WebSocket close frame with status code).
/// After this call IsConnected becomes false.
/// </summary>
Task CloseAsync(string reason, CancellationToken cancellationToken);
}
@@ -0,0 +1,31 @@
namespace SOR.Networking.Abstractions.Transport;
/// <summary>
/// Manages the server-side lifecycle of incoming connections for one transport protocol.
///
/// Current implementation: WebSocket (SOR.Networking.WebSocket.WebSocketTransport).
/// To swap to raw TCP: create SOR.Networking.Tcp.TcpTransport implementing this interface,
/// register it in SOR.Host instead of WebSocketTransport. Gateway code does not change.
///
/// Lifetime: Singleton. One ITransport instance exists for the process lifetime.
/// </summary>
public interface ITransport
{
/// <summary>
/// Human-readable identifier for this transport. Used in logs and metrics.
/// Examples: "websocket", "tcp", "quic"
/// </summary>
string Name { get; }
/// <summary>
/// Blocks until the next client connection is ready to hand off.
/// Returns a raw, unauthenticated IClientConnection.
///
/// The connection is in "just accepted" state — the caller (GatewayHostedService)
/// is responsible for running the auth handshake before trusting it.
///
/// Throws OperationCanceledException when the cancellation token is cancelled
/// (i.e., on application shutdown). This is the normal exit signal.
/// </summary>
Task<IClientConnection> AcceptAsync(CancellationToken cancellationToken);
}