diff --git a/Server/.gitignore b/Server/.gitignore
new file mode 100644
index 0000000..81f6104
--- /dev/null
+++ b/Server/.gitignore
@@ -0,0 +1,15 @@
+# Build outputs
+bin/
+obj/
+
+# User-specific files
+*.user
+*.suo
+.vs/
+
+# Rider/JetBrains
+.idea/
+
+# NuGet
+*.nupkg
+packages/
diff --git a/Server/Directory.Build.props b/Server/Directory.Build.props
new file mode 100644
index 0000000..8966389
--- /dev/null
+++ b/Server/Directory.Build.props
@@ -0,0 +1,27 @@
+
+
+
+ net8.0
+
+
+ enable
+
+
+ latest
+
+
+ true
+
+
+ enable
+
+
+ false
+
+
+ true
+
+
diff --git a/Server/Directory.Packages.props b/Server/Directory.Packages.props
new file mode 100644
index 0000000..d74475f
--- /dev/null
+++ b/Server/Directory.Packages.props
@@ -0,0 +1,69 @@
+
+
+
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Server/SOR.slnx b/Server/SOR.slnx
new file mode 100644
index 0000000..692a0e4
--- /dev/null
+++ b/Server/SOR.slnx
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Server/src/SOR.Auth/Handlers/AuthGrpcHandler.cs b/Server/src/SOR.Auth/Handlers/AuthGrpcHandler.cs
new file mode 100644
index 0000000..82ad288
--- /dev/null
+++ b/Server/src/SOR.Auth/Handlers/AuthGrpcHandler.cs
@@ -0,0 +1,98 @@
+namespace SOR.Auth.Handlers;
+
+using Grpc.Core;
+using Microsoft.Extensions.Logging;
+using SOR.Shared.Proto;
+
+///
+/// gRPC handler stub for the Auth service.
+///
+/// STATUS: Foundation stub only. All methods return placeholder responses.
+/// Real business logic (database, password hashing, session management)
+/// will be implemented when the Auth service is built out.
+///
+/// This stub is sufficient for the networking foundation phase:
+/// - The Gateway calls ValidateToken — this returns Valid=false for all tokens,
+/// meaning no connections will authenticate until the real implementation is in place.
+/// - The project compiles and the gRPC route is registered correctly.
+///
+/// When implementing for real:
+/// 1. Add IAuthService injection to the constructor
+/// 2. Replace each return statement with the actual service call
+/// 3. Map ServiceResult{T} to the Protobuf response message
+///
+public sealed class AuthGrpcHandler : AuthService.AuthServiceBase
+{
+ private readonly ILogger _logger;
+
+ public AuthGrpcHandler(ILogger logger)
+ {
+ _logger = logger;
+ }
+
+ ///
+ /// Validates a session token.
+ /// STUB: always returns Valid=false until real implementation is added.
+ ///
+ public override Task ValidateToken(
+ ValidateTokenRequest request,
+ ServerCallContext context)
+ {
+ _logger.LogDebug("ValidateToken called (stub) for token length={Length}",
+ request.SessionToken.Length);
+
+ // STUB: return invalid until real Auth business logic is implemented.
+ return Task.FromResult(new ValidateTokenResponse
+ {
+ Valid = false,
+ UserId = string.Empty,
+ DisplayName = string.Empty
+ });
+ }
+
+ ///
+ /// Authenticates a user with email + password.
+ /// STUB: always returns failure.
+ ///
+ public override Task Login(
+ LoginRequest request,
+ ServerCallContext context)
+ {
+ _logger.LogDebug("Login called (stub) for email={Email}", request.Email);
+
+ return Task.FromResult(new LoginResponse
+ {
+ Success = false,
+ ErrorCode = "NOT_IMPLEMENTED"
+ });
+ }
+
+ ///
+ /// Registers a new user account.
+ /// STUB: always returns failure.
+ ///
+ public override Task Register(
+ RegisterRequest request,
+ ServerCallContext context)
+ {
+ _logger.LogDebug("Register called (stub)");
+
+ return Task.FromResult(new RegisterResponse
+ {
+ Success = false,
+ ErrorCode = "NOT_IMPLEMENTED"
+ });
+ }
+
+ ///
+ /// Revokes a session token.
+ /// STUB: no-op (returns success — revocation of non-existent tokens is idempotent).
+ ///
+ public override Task Logout(
+ LogoutRequest request,
+ ServerCallContext context)
+ {
+ _logger.LogDebug("Logout called (stub)");
+ return Task.FromResult(new LogoutResponse());
+ }
+}
diff --git a/Server/src/SOR.Auth/SOR.Auth.csproj b/Server/src/SOR.Auth/SOR.Auth.csproj
new file mode 100644
index 0000000..97acd00
--- /dev/null
+++ b/Server/src/SOR.Auth/SOR.Auth.csproj
@@ -0,0 +1,16 @@
+
+
+ SOR.Auth
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Server/src/SOR.Auth/ServiceRegistration.cs b/Server/src/SOR.Auth/ServiceRegistration.cs
new file mode 100644
index 0000000..3caf789
--- /dev/null
+++ b/Server/src/SOR.Auth/ServiceRegistration.cs
@@ -0,0 +1,35 @@
+namespace SOR.Auth;
+
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+
+///
+/// Registers Auth service dependencies in the DI container.
+///
+/// STATUS: Foundation stub only.
+/// Real registration (DbContext, repositories, IAuthService) will be added
+/// when Auth business logic is implemented.
+///
+/// Currently only registers the gRPC infrastructure so the handler can be
+/// mapped in SOR.Host.Program.cs via app.MapGrpcService{AuthGrpcHandler}().
+///
+public static class ServiceRegistration
+{
+ public static IServiceCollection AddAuthService(
+ this IServiceCollection services,
+ IConfiguration configuration)
+ {
+ // AddGrpc() registers the gRPC server infrastructure in ASP.NET Core.
+ // Required before MapGrpcService{T} can be called in Program.cs.
+ // Safe to call multiple times — ASP.NET Core deduplicates registrations.
+ services.AddGrpc();
+
+ // TODO (when implementing Auth business logic):
+ // services.Configure(configuration.GetSection("Auth"));
+ // services.AddDbContext(opts => opts.UseNpgsql(...));
+ // services.AddScoped();
+ // services.AddScoped();
+
+ return services;
+ }
+}
diff --git a/Server/src/SOR.Gateway/Auth/GatewayAuthValidator.cs b/Server/src/SOR.Gateway/Auth/GatewayAuthValidator.cs
new file mode 100644
index 0000000..698917b
--- /dev/null
+++ b/Server/src/SOR.Gateway/Auth/GatewayAuthValidator.cs
@@ -0,0 +1,63 @@
+namespace SOR.Gateway.Auth;
+
+using Microsoft.Extensions.Logging;
+using SOR.Shared.Proto;
+
+///
+/// IGatewayAuthValidator implementation that calls the Auth gRPC service.
+///
+/// This is the only place in SOR.Gateway where the generated gRPC client type appears.
+/// All other Gateway code uses IGatewayAuthValidator (the interface).
+///
+/// The gRPC client (AuthService.AuthServiceClient) is injected via DI.
+/// It is registered in ServiceRegistration.cs using AddGrpcClient{T}(), which
+/// integrates gRPC client lifetime management with ASP.NET Core's HttpClientFactory.
+///
+/// Lifetime: Singleton (gRPC client factory handles connection pooling internally).
+///
+public sealed class GatewayAuthValidator : IGatewayAuthValidator
+{
+ // AuthService.AuthServiceClient is the generated client stub from auth.proto.
+ // It wraps a gRPC channel and provides typed RPC methods (ValidateTokenAsync, etc.).
+ private readonly AuthService.AuthServiceClient _grpcClient;
+ private readonly ILogger _logger;
+
+ public GatewayAuthValidator(
+ AuthService.AuthServiceClient grpcClient,
+ ILogger logger)
+ {
+ _grpcClient = grpcClient;
+ _logger = logger;
+ }
+
+ ///
+ public async Task<(bool Valid, string UserId, string DisplayName)> ValidateAsync(
+ string sessionToken,
+ CancellationToken cancellationToken = default)
+ {
+ try
+ {
+ // Call the Auth service's ValidateToken RPC.
+ // This is a synchronous RPC (request → response) over gRPC.
+ var response = await _grpcClient.ValidateTokenAsync(
+ new ValidateTokenRequest { SessionToken = sessionToken },
+ cancellationToken: cancellationToken);
+
+ if (!response.Valid)
+ {
+ _logger.LogDebug("Token validation failed: token is invalid or expired");
+ return (false, string.Empty, string.Empty);
+ }
+
+ return (true, response.UserId, response.DisplayName);
+ }
+ catch (Grpc.Core.RpcException ex)
+ {
+ // gRPC exception: Auth service is unreachable, overloaded, or returned an error.
+ // Treat as invalid — never accept a connection that cannot be validated.
+ _logger.LogWarning(ex,
+ "Auth gRPC call failed during token validation: {Status}", ex.Status.StatusCode);
+ return (false, string.Empty, string.Empty);
+ }
+ }
+}
diff --git a/Server/src/SOR.Gateway/Auth/IGatewayAuthValidator.cs b/Server/src/SOR.Gateway/Auth/IGatewayAuthValidator.cs
new file mode 100644
index 0000000..6de7cc9
--- /dev/null
+++ b/Server/src/SOR.Gateway/Auth/IGatewayAuthValidator.cs
@@ -0,0 +1,31 @@
+namespace SOR.Gateway.Auth;
+
+///
+/// Validates session tokens during the Gateway auth handshake.
+///
+/// This interface wraps the generated Auth gRPC client stub so that:
+/// - Gateway code depends on this interface, not the gRPC type
+/// - The implementation can be swapped in tests (mock the interface)
+/// - The gRPC dependency is contained within GatewayAuthValidator.cs
+///
+/// If the Auth service call mechanism changes (e.g., gRPC → REST), only
+/// GatewayAuthValidator changes. Gateway.ConnectionLoop does not change.
+///
+public interface IGatewayAuthValidator
+{
+ ///
+ /// Validates a session token by calling the Auth service.
+ ///
+ /// Returns a tuple:
+ /// - Valid: true if the token exists and has not expired or been revoked
+ /// - UserId: the token owner's user ID (empty string if Valid = false)
+ /// - DisplayName: the token owner's display name (empty string if Valid = false)
+ ///
+ /// On Auth service unavailability (gRPC exception), returns Valid = false.
+ /// This treats auth failures as invalid — better to reject than to let
+ /// potentially invalid connections through.
+ ///
+ Task<(bool Valid, string UserId, string DisplayName)> ValidateAsync(
+ string sessionToken,
+ CancellationToken cancellationToken = default);
+}
diff --git a/Server/src/SOR.Gateway/ConnectionLoop.cs b/Server/src/SOR.Gateway/ConnectionLoop.cs
new file mode 100644
index 0000000..42bb75a
--- /dev/null
+++ b/Server/src/SOR.Gateway/ConnectionLoop.cs
@@ -0,0 +1,365 @@
+namespace SOR.Gateway;
+
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Options;
+using StackExchange.Redis;
+using SOR.Gateway.Auth;
+using SOR.Gateway.Dispatch;
+using SOR.Gateway.Push;
+using SOR.Networking.Abstractions.Messaging;
+using SOR.Networking.Abstractions.Transport;
+using SOR.Shared.Networking;
+
+///
+/// Runs the full lifecycle of a single client connection.
+///
+/// This is the most important class in the Gateway. Every connected client
+/// has exactly one ConnectionLoop running as an independent Task.
+///
+/// Lifecycle phases:
+/// Phase 1: Auth handshake — wait for auth.hello, validate token
+/// Phase 2: Promote to authenticated — register in ConnectionManager
+/// Phase 3: Subscribe to Redis push channel
+/// Phase 4: Main message loop — receive → dispatch → optional reply
+/// Phase 5: Cleanup — always runs in finally (guaranteed cleanup)
+///
+/// Lifetime: Transient per connection. GatewayHostedService fires one Task per
+/// accepted IClientConnection. Each Task owns this class for its lifetime.
+///
+public sealed class ConnectionLoop
+{
+ private readonly ConnectionManager _connectionManager;
+ private readonly IMessageDispatcher _dispatcher;
+ private readonly IMessageSerializer _serializer;
+ private readonly IGatewayAuthValidator _authValidator;
+ private readonly IConnectionMultiplexer _redis;
+ private readonly GatewayOptions _options;
+ private readonly ILogger _logger;
+
+ public ConnectionLoop(
+ ConnectionManager connectionManager,
+ IMessageDispatcher dispatcher,
+ IMessageSerializer serializer,
+ IGatewayAuthValidator authValidator,
+ IConnectionMultiplexer redis,
+ IOptions options,
+ ILogger logger)
+ {
+ _connectionManager = connectionManager;
+ _dispatcher = dispatcher;
+ _serializer = serializer;
+ _authValidator = authValidator;
+ _redis = redis;
+ _options = options.Value;
+ _logger = logger;
+ }
+
+ ///
+ /// Runs the full connection lifecycle for a raw, unauthenticated IClientConnection.
+ ///
+ /// This method is called by GatewayHostedService as a fire-and-forget Task.
+ /// It handles its own exceptions — errors here must not propagate to the accept loop.
+ ///
+ /// The 'appCancellationToken' is the application shutdown token. When cancelled,
+ /// the connection closes gracefully.
+ ///
+ public async Task RunAsync(
+ IClientConnection rawConnection,
+ CancellationToken appCancellationToken)
+ {
+ // 'authConn' is null until the handshake completes.
+ // Used in finally to decide whether to unregister from ConnectionManager.
+ AuthenticatedConnection? authConn = null;
+ RedisPushSubscriber? pushSubscriber = null;
+
+ try
+ {
+ // ── Phase 1: Auth Handshake ────────────────────────────────────────────
+
+ _logger.LogDebug(
+ "Connection accepted: ConnectionId={ConnectionId} Remote={Remote}",
+ rawConnection.ConnectionId, rawConnection.RemoteAddress);
+
+ // Create a combined cancellation token: cancel if either the app shuts down
+ // OR the auth timeout expires. Whichever comes first.
+ //
+ // CancellationTokenSource.CreateLinkedTokenSource creates a new token that
+ // is cancelled when ANY of the source tokens are cancelled.
+ using var authTimeoutSts =
+ new CancellationTokenSource(TimeSpan.FromMilliseconds(_options.AuthTimeoutMs));
+ using var authLinked = CancellationTokenSource.CreateLinkedTokenSource(
+ appCancellationToken, authTimeoutSts.Token);
+
+ // Wait for the first message. Must be auth.hello.
+ // Returns null on clean close (client disconnected before sending anything).
+ var rawMsg = await rawConnection.ReceiveAsync(authLinked.Token);
+
+ if (rawMsg is null)
+ {
+ _logger.LogDebug(
+ "Connection closed before auth: ConnectionId={ConnectionId}",
+ rawConnection.ConnectionId);
+ return;
+ }
+
+ // Parse the envelope (type, seq, inner payload bytes).
+ // rawMsg.Payload contains the full wire bytes (envelope + payload).
+ IClientMessage parsedMsg;
+ try
+ {
+ parsedMsg = _serializer.Deserialize(rawMsg.Payload.Span);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogWarning(ex,
+ "Failed to deserialize first message: ConnectionId={ConnectionId}",
+ rawConnection.ConnectionId);
+ await rawConnection.CloseAsync("invalid_message", appCancellationToken);
+ return;
+ }
+
+ // The first message MUST be auth.hello.
+ if (!string.Equals(parsedMsg.Type, "auth.hello", StringComparison.OrdinalIgnoreCase))
+ {
+ _logger.LogWarning(
+ "First message is not auth.hello: Type={Type} ConnectionId={ConnectionId}",
+ parsedMsg.Type, rawConnection.ConnectionId);
+
+ await SendErrorAsync(rawConnection, parsedMsg.Seq,
+ "AUTH_REQUIRED", "First message must be auth.hello.", appCancellationToken);
+ await rawConnection.CloseAsync("auth_required", appCancellationToken);
+ return;
+ }
+
+ // Deserialize the auth.hello payload to get the session token.
+ AuthHelloPayload helloPayload;
+ try
+ {
+ helloPayload = _serializer.DeserializePayload(parsedMsg.Payload);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogWarning(ex,
+ "Failed to deserialize auth.hello payload: ConnectionId={ConnectionId}",
+ rawConnection.ConnectionId);
+ await SendErrorAsync(rawConnection, parsedMsg.Seq,
+ "INVALID_PAYLOAD", "auth.hello payload is malformed.", appCancellationToken);
+ await rawConnection.CloseAsync("invalid_payload", appCancellationToken);
+ return;
+ }
+
+ // ── Phase 2: Token Validation ──────────────────────────────────────────
+
+ var (isValid, userId, displayName) =
+ await _authValidator.ValidateAsync(helloPayload.SessionToken, appCancellationToken);
+
+ if (!isValid)
+ {
+ _logger.LogInformation(
+ "Auth failed: ConnectionId={ConnectionId} Remote={Remote}",
+ rawConnection.ConnectionId, rawConnection.RemoteAddress);
+
+ await SendErrorAsync(rawConnection, parsedMsg.Seq,
+ "AUTH_FAILED", "Invalid or expired session token.", appCancellationToken);
+ await rawConnection.CloseAsync("auth_failed", appCancellationToken);
+ return;
+ }
+
+ // ── Phase 3: Promote to Authenticated Connection ───────────────────────
+
+ authConn = new AuthenticatedConnection(
+ rawConnection, userId, displayName, helloPayload.SessionToken);
+
+ _connectionManager.Register(authConn);
+
+ _logger.LogInformation(
+ "User authenticated: UserId={UserId} DisplayName={DisplayName} " +
+ "ConnectionId={ConnectionId}",
+ userId, displayName, rawConnection.ConnectionId);
+
+ // Send acknowledgement to client.
+ await SendMessageAsync(
+ rawConnection,
+ ServerMessage.Reply("auth.hello.ack", parsedMsg.Seq, new
+ {
+ userId,
+ displayName
+ }),
+ appCancellationToken);
+
+ // ── Phase 4: Subscribe to Redis Push Channel ───────────────────────────
+
+ // Create a logger for the push subscriber that includes the userId.
+ // GetRequiredService would give a generic logger;
+ // we use CreateLogger with a category name that includes the userId for filtering.
+ var pushLogger = _logger as ILogger
+ ?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance;
+
+ pushSubscriber = await RedisPushSubscriber.SubscribeAsync(
+ _redis, authConn, pushLogger, appCancellationToken);
+
+ // ── Phase 5: Main Message Loop ─────────────────────────────────────────
+
+ while (rawConnection.IsConnected && !appCancellationToken.IsCancellationRequested)
+ {
+ // Wait for the next message from the client.
+ // Returns null on clean close (client sent WebSocket close frame).
+ IClientMessage? nextRaw;
+ try
+ {
+ nextRaw = await rawConnection.ReceiveAsync(appCancellationToken);
+ }
+ catch (OperationCanceledException)
+ {
+ // App is shutting down — exit the loop cleanly.
+ break;
+ }
+ catch (Exception ex)
+ {
+ // Network error (connection dropped unexpectedly).
+ _logger.LogDebug(ex,
+ "Receive error for user {UserId}: connection dropped",
+ userId);
+ break;
+ }
+
+ if (nextRaw is null) break; // Clean close from client.
+
+ // Parse the message envelope.
+ IClientMessage nextMsg;
+ try
+ {
+ nextMsg = _serializer.Deserialize(nextRaw.Payload.Span);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogWarning(ex,
+ "Failed to deserialize message from user {UserId}", userId);
+ // Malformed message: send an error but keep the connection alive.
+ await SendErrorAsync(rawConnection, 0,
+ "INVALID_MESSAGE", "Message could not be parsed.", appCancellationToken);
+ continue;
+ }
+
+ // Check that a handler exists for this message type.
+ if (!_dispatcher.HasHandler(nextMsg.Type))
+ {
+ _logger.LogDebug(
+ "Unknown message type '{Type}' from user {UserId}",
+ nextMsg.Type, userId);
+ await SendErrorAsync(rawConnection, nextMsg.Seq,
+ "UNKNOWN_TYPE",
+ $"No handler registered for message type '{nextMsg.Type}'.",
+ appCancellationToken);
+ continue;
+ }
+
+ // Dispatch to the registered handler.
+ IServerMessage? response;
+ try
+ {
+ response = await _dispatcher.DispatchAsync(
+ nextMsg, authConn, appCancellationToken);
+ }
+ catch (Exception ex)
+ {
+ // Handler threw an unexpected exception.
+ _logger.LogError(ex,
+ "Handler for '{Type}' threw for user {UserId}",
+ nextMsg.Type, userId);
+ await SendErrorAsync(rawConnection, nextMsg.Seq,
+ "INTERNAL_ERROR", "An internal error occurred.", appCancellationToken);
+ continue;
+ }
+
+ // Send the handler's reply if one was returned.
+ if (response is not null)
+ {
+ await SendMessageAsync(rawConnection, response, appCancellationToken);
+ }
+ }
+ }
+ catch (OperationCanceledException)
+ {
+ // Normal exit: auth timeout fired, or app shutdown, or client disconnected.
+ // OperationCanceledException is not an error — it's the expected exit signal.
+ _logger.LogDebug(
+ "Connection loop cancelled: ConnectionId={ConnectionId}",
+ rawConnection.ConnectionId);
+ }
+ catch (Exception ex)
+ {
+ // Unexpected error in the connection loop itself (not in a handler).
+ _logger.LogError(ex,
+ "Unexpected error in connection loop: ConnectionId={ConnectionId}",
+ rawConnection.ConnectionId);
+ }
+ finally
+ {
+ // ── Phase 6: Cleanup — ALWAYS runs, regardless of how the loop exited ──
+
+ // Unsubscribe from Redis push channel.
+ if (pushSubscriber is not null)
+ await pushSubscriber.DisposeAsync();
+
+ // Unregister from the connection map.
+ if (authConn is not null)
+ _connectionManager.Unregister(rawConnection.ConnectionId);
+
+ // Dispose the connection (closes WebSocket, signals middleware done TCS).
+ await rawConnection.DisposeAsync();
+
+ _logger.LogDebug(
+ "Connection loop ended: ConnectionId={ConnectionId}",
+ rawConnection.ConnectionId);
+ }
+ }
+
+ // ── Private helpers ────────────────────────────────────────────────────────
+
+ ///
+ /// Serializes and sends a message to the raw (pre-auth) or authenticated connection.
+ /// Errors here are swallowed — if the send fails the connection is already gone.
+ ///
+ private async Task SendMessageAsync(
+ IClientConnection connection,
+ IServerMessage message,
+ CancellationToken cancellationToken)
+ {
+ try
+ {
+ var bytes = _serializer.Serialize(message);
+ await connection.SendBytesAsync(bytes, cancellationToken);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogDebug(ex,
+ "Failed to send message '{Type}' to ConnectionId={ConnectionId}",
+ message.Type, connection.ConnectionId);
+ }
+ }
+
+ private Task SendErrorAsync(
+ IClientConnection connection,
+ int refSeq,
+ string errorCode,
+ string errorMessage,
+ CancellationToken cancellationToken) =>
+ SendMessageAsync(
+ connection,
+ ServerMessage.Error(refSeq, errorCode, errorMessage),
+ cancellationToken);
+
+ // ── Inner type: auth.hello payload ────────────────────────────────────────
+
+ ///
+ /// Deserialization target for the auth.hello message payload.
+ ///
+ /// Client sends:
+ /// { "type": "auth.hello", "seq": 1, "payload": { "sessionToken": "abc123..." } }
+ ///
+ /// 'record' with 'init' properties: immutable after deserialization.
+ /// Properties must match JSON keys (camelCase by default via IMessageSerializer options).
+ ///
+ private sealed record AuthHelloPayload(string SessionToken);
+}
diff --git a/Server/src/SOR.Gateway/ConnectionManager.cs b/Server/src/SOR.Gateway/ConnectionManager.cs
new file mode 100644
index 0000000..2292372
--- /dev/null
+++ b/Server/src/SOR.Gateway/ConnectionManager.cs
@@ -0,0 +1,93 @@
+namespace SOR.Gateway;
+
+using System.Collections.Concurrent;
+using SOR.Networking.Abstractions.Transport;
+
+///
+/// In-process registry of all authenticated connections on this Gateway instance.
+///
+/// Maintains two indexes:
+/// - By connectionId: stable, unique per connection, available before auth
+/// - By userId: available after auth, used by push delivery to find the socket
+///
+/// Important: ConnectionManager only knows about connections on THIS Gateway instance.
+/// For cross-instance lookups (e.g., "is user X connected anywhere?"), use Redis.
+/// This is intentional — Gateway instances are independent; coordination goes through Redis.
+///
+/// Thread safety: ConcurrentDictionary handles concurrent Register/Unregister/lookup
+/// without additional locking.
+///
+/// Lifetime: Singleton.
+///
+public sealed class ConnectionManager
+{
+ // Primary index: connectionId → AuthenticatedConnection
+ // A connectionId uniquely identifies one TCP socket / WebSocket upgrade.
+ private readonly ConcurrentDictionary _byConnectionId = new();
+
+ // Secondary index: userId → connectionId
+ // One active connection per userId on this instance.
+ // If a user opens a second tab, the second connection replaces the first in this map
+ // (both are still tracked in _byConnectionId; only the latest userId→connectionId
+ // mapping is kept for push delivery lookups).
+ private readonly ConcurrentDictionary _userIdToConnectionId = new();
+
+ ///
+ /// Registers an authenticated connection in both indexes.
+ /// Called by ConnectionLoop.RunAsync() after the auth handshake succeeds.
+ ///
+ public void Register(AuthenticatedConnection connection)
+ {
+ var connId = connection.Connection.ConnectionId;
+
+ _byConnectionId[connId] = connection;
+
+ // If the user already has a connection (second tab opened), the new mapping
+ // overwrites the old one. The old connection remains in _byConnectionId and
+ // will clean itself up when its loop exits.
+ _userIdToConnectionId[connection.UserId] = connId;
+ }
+
+ ///
+ /// Removes a connection from both indexes.
+ /// Called by ConnectionLoop.RunAsync() in its finally block — always called
+ /// regardless of how the loop exits (clean close, exception, timeout, etc.).
+ ///
+ public void Unregister(string connectionId)
+ {
+ if (_byConnectionId.TryRemove(connectionId, out var connection))
+ {
+ // Only remove the userId index if it still points to this connection.
+ // If a newer connection from the same user replaced it, leave the index alone.
+ _userIdToConnectionId.TryRemove(
+ new KeyValuePair(connection.UserId, connectionId));
+ }
+ }
+
+ ///
+ /// Looks up a connection by its connection ID.
+ /// Returns null if not registered (already disconnected).
+ ///
+ public AuthenticatedConnection? GetByConnectionId(string connectionId) =>
+ _byConnectionId.GetValueOrDefault(connectionId);
+
+ ///
+ /// Looks up the most recently registered connection for a given user.
+ /// Returns null if the user is not connected on this Gateway instance.
+ ///
+ /// Used by RedisPushSubscriber to find the WebSocket to deliver a pushed message to.
+ ///
+ public AuthenticatedConnection? GetByUserId(string userId)
+ {
+ if (!_userIdToConnectionId.TryGetValue(userId, out var connectionId))
+ return null;
+
+ return _byConnectionId.GetValueOrDefault(connectionId);
+ }
+
+ ///
+ /// Total number of currently authenticated connections on this Gateway instance.
+ /// Used for metrics and health reporting.
+ ///
+ public int ConnectedCount => _byConnectionId.Count;
+}
diff --git a/Server/src/SOR.Gateway/Dispatch/MessageDispatcher.cs b/Server/src/SOR.Gateway/Dispatch/MessageDispatcher.cs
new file mode 100644
index 0000000..c29123a
--- /dev/null
+++ b/Server/src/SOR.Gateway/Dispatch/MessageDispatcher.cs
@@ -0,0 +1,108 @@
+namespace SOR.Gateway.Dispatch;
+
+using Microsoft.Extensions.Logging;
+using SOR.Networking.Abstractions.Messaging;
+using SOR.Networking.Abstractions.Transport;
+
+///
+/// IMessageDispatcher implementation.
+///
+/// Collects all registered IMessageHandler implementations from the DI container
+/// at construction time and builds a frozen dispatch table keyed by message type.
+///
+/// Plugin pattern:
+/// Service modules register handlers with:
+/// services.AddTransient{IMessageHandler, ConcreteHandler}()
+/// This class collects them all via IEnumerable{IMessageHandler} injection.
+/// Adding a new handler to a service module never requires changing this class.
+///
+/// Startup validation:
+/// If two handlers register for the same message type, the constructor throws
+/// InvalidOperationException. This crashes startup rather than silently dropping
+/// one handler — duplicate registrations are always a bug.
+///
+/// Lifetime: Singleton. The dispatch table is immutable after construction.
+///
+public sealed class MessageDispatcher : IMessageDispatcher
+{
+ // IReadOnlyDictionary: immutable after construction.
+ // StringComparer.OrdinalIgnoreCase: "Chat.Send" and "chat.send" route to the same handler.
+ private readonly IReadOnlyDictionary _handlers;
+ private readonly ILogger _logger;
+
+ ///
+ /// Constructor. Called once at application startup by the DI container.
+ ///
+ /// 'IEnumerable{IMessageHandler}' causes the DI container to inject ALL registered
+ /// IMessageHandler implementations as a collection. This is the collection injection
+ /// pattern — a standard .NET DI feature, no special configuration needed.
+ ///
+ public MessageDispatcher(
+ IEnumerable handlers,
+ ILogger logger)
+ {
+ _logger = logger;
+
+ // Build the dispatch table. Dictionary for O(1) type lookup per message.
+ var table = new Dictionary(
+ StringComparer.OrdinalIgnoreCase);
+
+ foreach (var handler in handlers)
+ {
+ // Fail fast on duplicates — this is always a configuration bug.
+ if (!table.TryAdd(handler.MessageType, handler))
+ {
+ throw new InvalidOperationException(
+ $"Duplicate IMessageHandler registered for type '{handler.MessageType}'. " +
+ $"Existing: {table[handler.MessageType].GetType().Name}, " +
+ $"Duplicate: {handler.GetType().Name}. " +
+ "Each message type may have only one handler.");
+ }
+
+ _logger.LogDebug("Registered handler for message type '{Type}': {Handler}",
+ handler.MessageType, handler.GetType().Name);
+ }
+
+ _handlers = table;
+
+ _logger.LogInformation(
+ "MessageDispatcher initialized with {Count} handler(s): [{Types}]",
+ _handlers.Count,
+ string.Join(", ", _handlers.Keys));
+ }
+
+ ///
+ public bool HasHandler(string messageType) =>
+ _handlers.ContainsKey(messageType);
+
+ ///
+ ///
+ /// Precondition: HasHandler(message.Type) == true.
+ /// The Gateway connection loop checks HasHandler before calling DispatchAsync
+ /// and sends an error response for unknown types without reaching this method.
+ ///
+ public async Task DispatchAsync(
+ IClientMessage message,
+ AuthenticatedConnection connection,
+ CancellationToken cancellationToken)
+ {
+ // O(1) lookup — no lock needed (dictionary is read-only after construction).
+ if (!_handlers.TryGetValue(message.Type, out var handler))
+ {
+ // Should not happen: caller checks HasHandler first.
+ // Defensive check in case the method is called incorrectly.
+ _logger.LogError(
+ "DispatchAsync called for unregistered type '{Type}' — this is a bug",
+ message.Type);
+ return null;
+ }
+
+ _logger.LogDebug(
+ "Dispatching '{Type}' seq={Seq} for user {UserId}",
+ message.Type, message.Seq, connection.UserId);
+
+ // Invoke the handler. Exceptions bubble up to the connection loop,
+ // which logs them and sends a generic error response to the client.
+ return await handler.HandleAsync(message, connection, cancellationToken);
+ }
+}
diff --git a/Server/src/SOR.Gateway/GatewayHostedService.cs b/Server/src/SOR.Gateway/GatewayHostedService.cs
new file mode 100644
index 0000000..8c011df
--- /dev/null
+++ b/Server/src/SOR.Gateway/GatewayHostedService.cs
@@ -0,0 +1,142 @@
+namespace SOR.Gateway;
+
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
+using SOR.Networking.Abstractions.Transport;
+
+///
+/// Background service that runs the Gateway's connection accept loop.
+///
+/// IHostedService is the .NET interface for background services.
+/// The framework calls StartAsync() on application startup and StopAsync() on shutdown.
+///
+/// This service runs a tight loop: accept connection → fire ConnectionLoop as a Task.
+/// Each connection gets its own Task and runs fully independently.
+/// The accept loop itself never blocks waiting for an individual connection to finish.
+///
+/// Lifetime: Singleton (IHostedService instances are always Singleton in .NET DI).
+///
+public sealed class GatewayHostedService : IHostedService
+{
+ private readonly ITransport _transport;
+ private readonly ConnectionLoop _connectionLoop;
+ private readonly ILogger _logger;
+
+ // Track all active connection Tasks so we can wait for them on shutdown.
+ // ConcurrentDictionary used as a thread-safe HashSet (value is bool placeholder).
+ private readonly System.Collections.Concurrent.ConcurrentDictionary
+ _activeTasks = new();
+
+ // CancellationTokenSource that we control — cancelled in StopAsync to signal shutdown.
+ private CancellationTokenSource _cts = new();
+
+ public GatewayHostedService(
+ ITransport transport,
+ ConnectionLoop connectionLoop,
+ ILogger logger)
+ {
+ _transport = transport;
+ _connectionLoop = connectionLoop;
+ _logger = logger;
+ }
+
+ ///
+ /// Called by the framework on application startup.
+ /// Fires the accept loop as a background Task (does not block startup).
+ ///
+ public Task StartAsync(CancellationToken cancellationToken)
+ {
+ _logger.LogInformation(
+ "Gateway accept loop starting on transport '{Transport}'", _transport.Name);
+
+ // Fire the accept loop as a background Task.
+ // '_ =' discards the returned Task — the loop manages itself.
+ // We pass _cts.Token (our controlled token) rather than the startup token
+ // because the startup token is only valid during the startup phase.
+ _ = RunAcceptLoopAsync(_cts.Token);
+
+ return Task.CompletedTask;
+ }
+
+ ///
+ /// Called by the framework on application shutdown.
+ /// Cancels the accept loop and waits for all active connection Tasks to finish.
+ ///
+ public async Task StopAsync(CancellationToken cancellationToken)
+ {
+ _logger.LogInformation("Gateway shutting down. Waiting for {Count} connection(s) to close.",
+ _activeTasks.Count);
+
+ // Signal cancellation to the accept loop and all active connection loops.
+ await _cts.CancelAsync();
+
+ // Wait for all in-flight connection Tasks to complete,
+ // but stop waiting after the shutdown timeout (cancellationToken from framework).
+ //
+ // Task.WhenAll runs all tasks concurrently and completes when all finish.
+ // WaitAsync(cancellationToken) limits how long we wait.
+ var allTasks = _activeTasks.Keys.ToArray();
+ if (allTasks.Length > 0)
+ {
+ try
+ {
+ await Task.WhenAll(allTasks).WaitAsync(cancellationToken);
+ }
+ catch (OperationCanceledException)
+ {
+ _logger.LogWarning(
+ "Shutdown timeout reached; {Count} connection(s) may not have closed cleanly.",
+ _activeTasks.Count);
+ }
+ }
+
+ _logger.LogInformation("Gateway shut down.");
+ }
+
+ ///
+ /// The main accept loop. Runs until _cts is cancelled (application shutdown).
+ /// Each accepted connection is handled in a separate Task.
+ ///
+ private async Task RunAcceptLoopAsync(CancellationToken ct)
+ {
+ try
+ {
+ while (!ct.IsCancellationRequested)
+ {
+ // Block until a new connection arrives.
+ // Throws OperationCanceledException on shutdown — caught below.
+ var connection = await _transport.AcceptAsync(ct);
+
+ _logger.LogDebug(
+ "Accepted connection: ConnectionId={ConnectionId}",
+ connection.ConnectionId);
+
+ // Fire the connection loop as an independent Task.
+ // We do NOT await it — the accept loop continues immediately to accept the next.
+ var task = _connectionLoop.RunAsync(connection, ct);
+
+ // Track the task so StopAsync can wait for all connections to close.
+ _activeTasks.TryAdd(task, true);
+
+ // Remove the task from tracking when it completes (success or failure).
+ // ContinueWith runs when the task finishes — this is the cleanup callback.
+ // TaskContinuationOptions.ExecuteSynchronously: run the callback inline
+ // on the completing thread to avoid scheduling overhead.
+ _ = task.ContinueWith(
+ t => _activeTasks.TryRemove(t, out _),
+ TaskContinuationOptions.ExecuteSynchronously);
+ }
+ }
+ catch (OperationCanceledException)
+ {
+ // Normal shutdown — the accept loop was cancelled.
+ }
+ catch (Exception ex)
+ {
+ // Unexpected error in the accept loop itself.
+ // This would stop accepting new connections — log as Critical.
+ _logger.LogCritical(ex,
+ "Gateway accept loop crashed. No new connections will be accepted.");
+ }
+ }
+}
diff --git a/Server/src/SOR.Gateway/GatewayOptions.cs b/Server/src/SOR.Gateway/GatewayOptions.cs
new file mode 100644
index 0000000..c61e283
--- /dev/null
+++ b/Server/src/SOR.Gateway/GatewayOptions.cs
@@ -0,0 +1,40 @@
+namespace SOR.Gateway;
+
+///
+/// Configuration options for the Gateway service.
+/// Bound from the "Gateway" section of appsettings.json.
+///
+/// appsettings.json example:
+/// {
+/// "Gateway": {
+/// "AuthTimeoutMs": 10000,
+/// "MaxMessagesPerSecond": 20
+/// }
+/// }
+///
+public sealed class GatewayOptions
+{
+ ///
+ /// How long the Gateway waits for an auth.hello message after a connection is accepted.
+ /// If the client does not send auth.hello within this window, the connection is closed
+ /// with an "auth_timeout" reason.
+ /// Default: 10 seconds.
+ ///
+ public int AuthTimeoutMs { get; set; } = 10_000;
+
+ ///
+ /// Maximum number of messages per second the Gateway will process per connection.
+ /// Connections exceeding this rate receive a "rate_limit_exceeded" error and are
+ /// disconnected. Protects against runaway clients flooding the server.
+ ///
+ /// Note: rate limiting is tracked per connection, not per user.
+ /// If a user opens multiple connections they get this budget per connection.
+ ///
+ /// Set to 0 to disable rate limiting (not recommended for production).
+ /// Default: 20 messages per second.
+ ///
+ /// Implementation: tracked in ConnectionLoop but not enforced in this foundation phase.
+ /// This option is defined now so configuration is in place before enforcement is added.
+ ///
+ public int MaxMessagesPerSecond { get; set; } = 20;
+}
diff --git a/Server/src/SOR.Gateway/Push/RedisPushSubscriber.cs b/Server/src/SOR.Gateway/Push/RedisPushSubscriber.cs
new file mode 100644
index 0000000..4a95311
--- /dev/null
+++ b/Server/src/SOR.Gateway/Push/RedisPushSubscriber.cs
@@ -0,0 +1,126 @@
+namespace SOR.Gateway.Push;
+
+using Microsoft.Extensions.Logging;
+using StackExchange.Redis;
+using SOR.Networking.Abstractions.Transport;
+using SOR.Shared.Redis;
+
+///
+/// Subscribes to a Redis Pub/Sub channel for a specific user and forwards
+/// received bytes directly to their WebSocket connection.
+///
+/// This is the READ side of the push delivery pipeline (Gateway-internal):
+/// Redis channel "push:{userId}"
+/// → RedisPushSubscriber.OnMessageReceived callback
+/// → IClientConnection.SendBytesAsync (WebSocket send)
+///
+/// The WRITE side is IClientPush (SOR.Networking.Redis.RedisClientPush).
+/// Only the Gateway uses RedisPushSubscriber — it is not part of the public interfaces.
+///
+/// One instance per authenticated connection. Created by ConnectionLoop.RunAsync()
+/// after auth handshake. Disposed when the connection loop exits (user disconnected).
+///
+/// Factory method pattern: constructor is private; call SubscribeAsync() to create.
+///
+public sealed class RedisPushSubscriber : IAsyncDisposable
+{
+ private readonly ISubscriber _subscriber;
+ private readonly RedisChannel _channel;
+ private readonly AuthenticatedConnection _connection;
+ private readonly ILogger _logger;
+
+ private RedisPushSubscriber(
+ ISubscriber subscriber,
+ RedisChannel channel,
+ AuthenticatedConnection connection,
+ ILogger logger)
+ {
+ _subscriber = subscriber;
+ _channel = channel;
+ _connection = connection;
+ _logger = logger;
+ }
+
+ ///
+ /// Creates and starts a push subscriber for the given user connection.
+ ///
+ /// Subscribes to "push:{userId}" on Redis. Any bytes published to this channel
+ /// by IClientPush are immediately forwarded to the connection's WebSocket.
+ ///
+ /// Returns the subscriber instance, which the caller holds until the connection
+ /// ends. Disposing the subscriber unsubscribes from Redis.
+ ///
+ public static async Task SubscribeAsync(
+ IConnectionMultiplexer redis,
+ AuthenticatedConnection connection,
+ ILogger logger,
+ CancellationToken cancellationToken)
+ {
+ var channelKey = RedisKeys.ClientPushChannel(connection.UserId);
+ var channel = RedisChannel.Literal(channelKey);
+ var subscriber = redis.GetSubscriber();
+
+ var instance = new RedisPushSubscriber(subscriber, channel, connection, logger);
+
+ // Subscribe to the channel. OnMessageReceived is called on a Redis
+ // background thread each time a message is published to this channel.
+ await subscriber.SubscribeAsync(channel, instance.OnMessageReceived);
+
+ logger.LogDebug(
+ "Subscribed to Redis push channel '{Channel}' for user {UserId}",
+ channelKey, connection.UserId);
+
+ return instance;
+ }
+
+ ///
+ /// Callback invoked on a Redis background thread when a message arrives on the channel.
+ ///
+ /// We fire-and-forget a Task to forward the bytes asynchronously.
+ /// The send lock inside IClientConnection.SendBytesAsync serializes concurrent sends
+ /// (in case a reply from a handler arrives at the same time as a push).
+ ///
+ /// Errors are logged and swallowed — a failed push must not crash the subscriber.
+ ///
+ private void OnMessageReceived(RedisChannel channel, RedisValue value)
+ {
+ // Don't forward if the connection is already closing.
+ if (!_connection.Connection.IsConnected) return;
+
+ // Fire-and-forget the async send.
+ // '_ =' discards the Task intentionally. We catch exceptions inside.
+ _ = ForwardAsync(value);
+ }
+
+ private async Task ForwardAsync(RedisValue value)
+ {
+ try
+ {
+ // RedisValue is implicitly convertible to byte[].
+ // ReadOnlyMemory wraps it without copying.
+ byte[] bytes = (byte[])value!;
+
+ await _connection.Connection.SendBytesAsync(
+ bytes,
+ CancellationToken.None); // Don't use connection's token — push must complete
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex,
+ "Failed to forward push to user {UserId}", _connection.UserId);
+ }
+ }
+
+ ///
+ /// Unsubscribes from the Redis channel.
+ /// Called by ConnectionLoop.RunAsync() in its finally block.
+ ///
+ public async ValueTask DisposeAsync()
+ {
+ await _subscriber.UnsubscribeAsync(_channel);
+
+ _logger.LogDebug(
+ "Unsubscribed from Redis push channel for user {UserId}",
+ _connection.UserId);
+ }
+}
diff --git a/Server/src/SOR.Gateway/SOR.Gateway.csproj b/Server/src/SOR.Gateway/SOR.Gateway.csproj
new file mode 100644
index 0000000..db3a7ae
--- /dev/null
+++ b/Server/src/SOR.Gateway/SOR.Gateway.csproj
@@ -0,0 +1,25 @@
+
+
+ SOR.Gateway
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Server/src/SOR.Gateway/ServiceRegistration.cs b/Server/src/SOR.Gateway/ServiceRegistration.cs
new file mode 100644
index 0000000..204a2ce
--- /dev/null
+++ b/Server/src/SOR.Gateway/ServiceRegistration.cs
@@ -0,0 +1,75 @@
+namespace SOR.Gateway;
+
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using SOR.Gateway.Auth;
+using SOR.Gateway.Dispatch;
+using SOR.Networking.Abstractions.Messaging;
+using SOR.Shared.Proto;
+
+///
+/// Registers all Gateway services in the DI container.
+/// Called from SOR.Host.Program.cs when "gateway" is in ENABLED_SERVICES.
+///
+public static class ServiceRegistration
+{
+ ///
+ /// Registers:
+ /// - GatewayOptions (from "Gateway" config section)
+ /// - ConnectionManager (Singleton: in-process connection registry)
+ /// - IMessageDispatcher → MessageDispatcher (Singleton: built from all IMessageHandlers)
+ /// - IGatewayAuthValidator → GatewayAuthValidator (Singleton: wraps Auth gRPC client)
+ /// - Auth gRPC client (via AddGrpcClient — uses HttpClientFactory for connection pooling)
+ /// - ConnectionLoop (Transient: new instance per connection)
+ /// - GatewayHostedService (Singleton: runs the accept loop)
+ ///
+ /// Preconditions (must be registered before calling this):
+ /// - ITransport (e.g., via AddWebSocketTransport)
+ /// - IConnectionMultiplexer (StackExchange.Redis, registered in Host)
+ /// - IMessageSerializer (via AddSharedServices)
+ ///
+ public static IServiceCollection AddGatewayService(
+ this IServiceCollection services,
+ IConfiguration configuration)
+ {
+ // Bind "Gateway" config section to GatewayOptions.
+ services.Configure(configuration.GetSection("Gateway"));
+
+ // Singleton: one ConnectionManager for this Gateway instance's lifetime.
+ services.AddSingleton();
+
+ // Singleton: MessageDispatcher collects all IMessageHandler registrations
+ // via IEnumerable{IMessageHandler} injection. Built once at startup.
+ services.AddSingleton();
+
+ // Register the Auth gRPC client using AddGrpcClient.
+ // AddGrpcClient integrates with HttpClientFactory for:
+ // - Connection pooling (one underlying HTTP/2 connection, multiplexed)
+ // - Automatic retries (configurable via AddPolicyHandler)
+ // - Proper lifetime management
+ // The address comes from configuration: Services:Auth (e.g., "http://auth-service:5001")
+ services.AddGrpcClient(opts =>
+ {
+ opts.Address = new Uri(configuration["Services:Auth"]
+ ?? throw new InvalidOperationException(
+ "Missing configuration: Services:Auth. " +
+ "Set this to the Auth service gRPC address (e.g., http://localhost:5001)."));
+ });
+
+ // Singleton: wraps the Auth gRPC client behind IGatewayAuthValidator.
+ services.AddSingleton();
+
+ // Transient: a new ConnectionLoop is created for each connection.
+ // This is safe because ConnectionLoop has no mutable shared state —
+ // all its dependencies (ConnectionManager, IMessageDispatcher, etc.) are Singletons.
+ // Using Transient ensures each connection gets a fresh instance with its own
+ // logger context, even though the dependencies are shared.
+ services.AddTransient();
+
+ // Singleton: IHostedService implementations are always Singleton.
+ // Starts the accept loop on application startup.
+ services.AddHostedService();
+
+ return services;
+ }
+}
diff --git a/Server/src/SOR.Host/Program.cs b/Server/src/SOR.Host/Program.cs
new file mode 100644
index 0000000..b91c194
--- /dev/null
+++ b/Server/src/SOR.Host/Program.cs
@@ -0,0 +1,177 @@
+// SOR.Host — Multi-service runner
+//
+// This is the entry point for the entire SOR server. It reads the ENABLED_SERVICES
+// environment variable and starts exactly those service modules in a single process.
+//
+// This is also the ONLY file in the codebase where concrete networking implementations
+// (WebSocket, NATS, Redis) are wired to their abstractions. All other code depends on
+// interfaces only. To swap a transport or broker, change this file — nothing else.
+//
+// Examples:
+// ENABLED_SERVICES=all → run everything (development)
+// ENABLED_SERVICES=gateway,auth → run only Gateway + Auth (small VM)
+// ENABLED_SERVICES=gateway → run only Gateway (dedicated gateway pod)
+
+using SOR.Auth;
+using SOR.Gateway;
+using SOR.Networking.Nats;
+using SOR.Networking.Redis;
+using SOR.Networking.WebSocket;
+using SOR.Shared;
+using Serilog;
+using StackExchange.Redis;
+using NATS.Client.Core;
+using NATS.Client.Hosting;
+using Microsoft.AspNetCore.WebSockets;
+using SOR.Auth.Handlers;
+
+// ── ENABLED_SERVICES ──────────────────────────────────────────────────────────
+
+// Read which services this instance should run.
+// Environment variable format: comma-separated service names.
+// Special value "all" runs every registered service (convenient for development).
+//
+// Example Kubernetes env:
+// - name: ENABLED_SERVICES
+// value: "gateway,auth"
+var rawServices = Environment.GetEnvironmentVariable("ENABLED_SERVICES") ?? "all";
+
+var enabledServices = rawServices
+ .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
+ .ToHashSet(StringComparer.OrdinalIgnoreCase);
+
+// Local function: returns true if the named service should start on this instance.
+bool IsEnabled(string name) =>
+ enabledServices.Contains("all") || enabledServices.Contains(name);
+
+// ── BUILDER ───────────────────────────────────────────────────────────────────
+
+var builder = WebApplication.CreateBuilder(args);
+
+// ── Logging ───────────────────────────────────────────────────────────────────
+// Replace .NET's default logger with Serilog.
+// Configuration comes from the "Serilog" section of appsettings.json.
+// ReadFrom.Configuration automatically picks up sinks, minimum levels, and enrichers.
+builder.Host.UseSerilog((context, config) =>
+ config.ReadFrom.Configuration(context.Configuration));
+
+// ── Shared services ───────────────────────────────────────────────────────────
+// Registers IMessageSerializer (SystemTextJsonSerializer by default).
+// To swap to MessagePack: after this call, add:
+// builder.Services.AddSingleton()
+// which overrides the default registration.
+builder.Services.AddSharedServices();
+
+// ── Shared infrastructure (Singleton per process) ─────────────────────────────
+
+// Redis connection multiplexer: one connection pool for the entire process.
+// All services that need Redis inject IConnectionMultiplexer from DI.
+// GetConnectionString("Redis") reads from ConnectionStrings:Redis in appsettings.json
+// or the ConnectionStrings__Redis environment variable.
+builder.Services.AddSingleton(
+ ConnectionMultiplexer.Connect(
+ builder.Configuration.GetConnectionString("Redis")
+ ?? throw new InvalidOperationException(
+ "Missing configuration: ConnectionStrings:Redis. " +
+ "Set this to your Redis connection string (e.g., 'localhost:6379').")));
+
+// NATS client: one connection for the entire process.
+// AddNats is from NATS.Client.Hosting and registers NatsConnection as Singleton,
+// exposed as both NatsConnection and INatsConnection.
+// The 'opts with { Url = ... }' syntax uses a C# record 'with' expression to clone the
+// default options and set only the URL — all other defaults remain unchanged.
+builder.Services.AddNats(configureOpts: opts =>
+ opts with
+ {
+ Url = builder.Configuration["Nats:Url"]
+ ?? throw new InvalidOperationException(
+ "Missing configuration: Nats:Url. " +
+ "Set this to your NATS server URL (e.g., 'nats://localhost:4222').")
+ });
+
+// ── Health checks ─────────────────────────────────────────────────────────────
+// Minimal health check for Kubernetes liveness/readiness probes.
+// Returns 200 OK at /health if the process is running.
+// TODO: add dependency health checks (Redis, NATS, Postgres) per service.
+builder.Services.AddHealthChecks();
+
+// ── Networking transports ─────────────────────────────────────────────────────
+// These are the CONCRETE implementations of the networking abstractions.
+// This section is the "wiring" point. To swap a transport, change only here.
+
+// AddWebSockets must be called here (from the Web SDK host project) rather than
+// inside SOR.Networking.WebSocket.ServiceRegistration, because the AddWebSockets
+// extension method resolves correctly only from a Microsoft.NET.Sdk.Web project.
+// Without this call, context.WebSockets.IsWebSocketRequest is always false.
+if (IsEnabled("gateway"))
+ builder.Services.AddWebSockets(opts =>
+ {
+ // ASP.NET Core's built-in keep-alive interval (protocol-level ping/pong).
+ // Our WebSocketClientConnection also sends application-level pings independently.
+ opts.KeepAliveInterval = TimeSpan.FromSeconds(30);
+ });
+
+// WebSocket transport: ITransport → WebSocketTransport
+// Reads options from "WebSocket" config section.
+if (IsEnabled("gateway"))
+ builder.Services.AddWebSocketTransport(builder.Configuration);
+
+// NATS event bus: IEventBus → NatsEventBus (wraps the INatsClient registered above)
+builder.Services.AddNatsEventBus(builder.Configuration);
+
+// Redis client push: IClientPush → RedisClientPush (write side of push delivery)
+// The Gateway's read side (RedisPushSubscriber) is internal to SOR.Gateway.
+builder.Services.AddRedisClientPush();
+
+// ── Service modules ───────────────────────────────────────────────────────────
+// Each service registers its own handlers, options, DbContext, repositories, etc.
+// Only services listed in ENABLED_SERVICES are started.
+
+if (IsEnabled("auth")) builder.Services.AddAuthService(builder.Configuration);
+if (IsEnabled("gateway")) builder.Services.AddGatewayService(builder.Configuration);
+
+// TODO: Uncomment as each service is implemented:
+// if (IsEnabled("chat")) builder.Services.AddChatService(builder.Configuration);
+// if (IsEnabled("collection")) builder.Services.AddCollectionService(builder.Configuration);
+// if (IsEnabled("bazaar")) builder.Services.AddBazaarService(builder.Configuration);
+// if (IsEnabled("leaderboard")) builder.Services.AddLeaderboardService(builder.Configuration);
+// if (IsEnabled("content")) builder.Services.AddContentService(builder.Configuration);
+// if (IsEnabled("admin")) builder.Services.AddAdminService(builder.Configuration);
+
+// ── BUILD ─────────────────────────────────────────────────────────────────────
+
+var app = builder.Build();
+
+// ── Middleware pipeline ───────────────────────────────────────────────────────
+// Middleware runs in the order it's added. Order matters.
+
+// WebSocket upgrade support: MUST come before UseRouting and UseWebSocketTransport.
+// This activates the protocol-level WebSocket upgrade handler in Kestrel.
+if (IsEnabled("gateway"))
+ app.UseWebSockets();
+
+// WebSocket upgrade interceptor: MUST come before UseRouting.
+// Intercepts HTTP upgrade requests to "/ws" and hands them to WebSocketTransport.
+if (IsEnabled("gateway"))
+ app.UseWebSocketTransport();
+
+// Routing: maps URL paths to gRPC service routes.
+app.UseRouting();
+
+// ── Endpoints ─────────────────────────────────────────────────────────────────
+
+// gRPC service routes: map each handler to its Protobuf-defined URL.
+if (IsEnabled("auth"))
+ app.MapGrpcService();
+
+// Health check endpoint: Kubernetes probes GET /health to check liveness.
+app.MapHealthChecks("/health");
+
+// ── RUN ───────────────────────────────────────────────────────────────────────
+
+Log.Information("SOR Host starting. Services: {Services}", rawServices);
+
+// RunAsync blocks until the process receives a shutdown signal (SIGTERM, Ctrl+C).
+// On shutdown, ASP.NET Core calls StopAsync on all IHostedService implementations
+// (including GatewayHostedService) in reverse registration order.
+await app.RunAsync();
diff --git a/Server/src/SOR.Host/SOR.Host.csproj b/Server/src/SOR.Host/SOR.Host.csproj
new file mode 100644
index 0000000..de8d77a
--- /dev/null
+++ b/Server/src/SOR.Host/SOR.Host.csproj
@@ -0,0 +1,33 @@
+
+
+ SOR.Host
+
+
+ Exe
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Server/src/SOR.Host/appsettings.json b/Server/src/SOR.Host/appsettings.json
new file mode 100644
index 0000000..19e392b
--- /dev/null
+++ b/Server/src/SOR.Host/appsettings.json
@@ -0,0 +1,40 @@
+{
+ "ConnectionStrings": {
+ "Redis": "localhost:6379"
+ },
+ "Nats": {
+ "Url": "nats://localhost:4222"
+ },
+ "WebSocket": {
+ "Path": "/ws",
+ "PingIntervalMs": 30000,
+ "MaxMessageSizeBytes": 65536
+ },
+ "Gateway": {
+ "AuthTimeoutMs": 10000,
+ "MaxMessagesPerSecond": 20
+ },
+ "Services": {
+ "Auth": "http://localhost:5001"
+ },
+ "Serilog": {
+ "MinimumLevel": {
+ "Default": "Information",
+ "Override": {
+ "Microsoft": "Warning",
+ "Microsoft.AspNetCore": "Warning",
+ "Grpc": "Warning",
+ "System": "Warning"
+ }
+ },
+ "WriteTo": [
+ {
+ "Name": "Console",
+ "Args": {
+ "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {SourceContext}: {Message:lj}{NewLine}{Exception}"
+ }
+ }
+ ],
+ "Enrich": [ "FromLogContext" ]
+ }
+}
diff --git a/Server/src/SOR.Networking.Abstractions/EventBus/IEventBus.cs b/Server/src/SOR.Networking.Abstractions/EventBus/IEventBus.cs
new file mode 100644
index 0000000..f61bce9
--- /dev/null
+++ b/Server/src/SOR.Networking.Abstractions/EventBus/IEventBus.cs
@@ -0,0 +1,62 @@
+namespace SOR.Networking.Abstractions.EventBus;
+
+///
+/// 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.
+///
+public interface IEventBus
+{
+ ///
+ /// 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.
+ ///
+ Task PublishAsync(
+ string subject,
+ T payload,
+ CancellationToken cancellationToken = default)
+ where T : notnull;
+
+ ///
+ /// 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.
+ ///
+ IAsyncEnumerable SubscribeAsync(
+ string subject,
+ CancellationToken cancellationToken = default)
+ where T : notnull;
+}
diff --git a/Server/src/SOR.Networking.Abstractions/Messaging/IClientMessage.cs b/Server/src/SOR.Networking.Abstractions/Messaging/IClientMessage.cs
new file mode 100644
index 0000000..2cd6011
--- /dev/null
+++ b/Server/src/SOR.Networking.Abstractions/Messaging/IClientMessage.cs
@@ -0,0 +1,42 @@
+namespace SOR.Networking.Abstractions.Messaging;
+
+///
+/// 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.
+///
+public interface IClientMessage
+{
+ ///
+ /// 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.
+ ///
+ string Type { get; }
+
+ ///
+ /// 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.
+ ///
+ int Seq { get; }
+
+ ///
+ /// 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.
+ ///
+ ReadOnlyMemory Payload { get; }
+}
diff --git a/Server/src/SOR.Networking.Abstractions/Messaging/IMessageDispatcher.cs b/Server/src/SOR.Networking.Abstractions/Messaging/IMessageDispatcher.cs
new file mode 100644
index 0000000..9fff16f
--- /dev/null
+++ b/Server/src/SOR.Networking.Abstractions/Messaging/IMessageDispatcher.cs
@@ -0,0 +1,39 @@
+namespace SOR.Networking.Abstractions.Messaging;
+
+using SOR.Networking.Abstractions.Transport;
+
+///
+/// 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.
+///
+public interface IMessageDispatcher
+{
+ ///
+ /// 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.
+ ///
+ bool HasHandler(string messageType);
+
+ ///
+ /// 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.
+ ///
+ Task DispatchAsync(
+ IClientMessage message,
+ AuthenticatedConnection connection,
+ CancellationToken cancellationToken);
+}
diff --git a/Server/src/SOR.Networking.Abstractions/Messaging/IMessageHandler.cs b/Server/src/SOR.Networking.Abstractions/Messaging/IMessageHandler.cs
new file mode 100644
index 0000000..c0b93c1
--- /dev/null
+++ b/Server/src/SOR.Networking.Abstractions/Messaging/IMessageHandler.cs
@@ -0,0 +1,59 @@
+namespace SOR.Networking.Abstractions.Messaging;
+
+using SOR.Networking.Abstractions.Transport;
+
+///
+/// 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).
+///
+public interface IMessageHandler
+{
+ ///
+ /// 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.
+ ///
+ string MessageType { get; }
+
+ ///
+ /// 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.
+ ///
+ Task HandleAsync(
+ IClientMessage message,
+ AuthenticatedConnection connection,
+ CancellationToken cancellationToken);
+}
diff --git a/Server/src/SOR.Networking.Abstractions/Messaging/IMessageSerializer.cs b/Server/src/SOR.Networking.Abstractions/Messaging/IMessageSerializer.cs
new file mode 100644
index 0000000..6431133
--- /dev/null
+++ b/Server/src/SOR.Networking.Abstractions/Messaging/IMessageSerializer.cs
@@ -0,0 +1,50 @@
+namespace SOR.Networking.Abstractions.Messaging;
+
+///
+/// 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.
+///
+public interface IMessageSerializer
+{
+ ///
+ /// 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.
+ ///
+ IClientMessage Deserialize(ReadOnlySpan wireBytes);
+
+ ///
+ /// Encodes an IServerMessage into wire bytes ready for transmission.
+ ///
+ /// Called by the Gateway send path just before calling
+ /// IClientConnection.SendBytesAsync().
+ ///
+ ReadOnlyMemory Serialize(IServerMessage message);
+
+ ///
+ /// 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.
+ ///
+ T DeserializePayload(ReadOnlyMemory payload) where T : notnull;
+}
diff --git a/Server/src/SOR.Networking.Abstractions/Messaging/IServerMessage.cs b/Server/src/SOR.Networking.Abstractions/Messaging/IServerMessage.cs
new file mode 100644
index 0000000..1f4c556
--- /dev/null
+++ b/Server/src/SOR.Networking.Abstractions/Messaging/IServerMessage.cs
@@ -0,0 +1,40 @@
+namespace SOR.Networking.Abstractions.Messaging;
+
+///
+/// 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.
+///
+public interface IServerMessage
+{
+ ///
+ /// Dot-namespaced message type. Convention: "{service}.{action}" or
+ /// "{service}.{action}.ack" for acknowledgement replies.
+ /// Examples: "auth.hello.ack", "game.state_update", "error"
+ ///
+ string Type { get; }
+
+ ///
+ /// 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.
+ ///
+ int Ref { get; }
+
+ ///
+ /// 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).
+ ///
+ object? Payload { get; }
+}
diff --git a/Server/src/SOR.Networking.Abstractions/Push/IClientPush.cs b/Server/src/SOR.Networking.Abstractions/Push/IClientPush.cs
new file mode 100644
index 0000000..bcab3eb
--- /dev/null
+++ b/Server/src/SOR.Networking.Abstractions/Push/IClientPush.cs
@@ -0,0 +1,40 @@
+namespace SOR.Networking.Abstractions.Push;
+
+using SOR.Networking.Abstractions.Messaging;
+
+///
+/// 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.
+///
+public interface IClientPush
+{
+ ///
+ /// 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.
+ ///
+ Task PushAsync(
+ string userId,
+ IServerMessage message,
+ CancellationToken cancellationToken = default);
+}
diff --git a/Server/src/SOR.Networking.Abstractions/SOR.Networking.Abstractions.csproj b/Server/src/SOR.Networking.Abstractions/SOR.Networking.Abstractions.csproj
new file mode 100644
index 0000000..2a26f2e
--- /dev/null
+++ b/Server/src/SOR.Networking.Abstractions/SOR.Networking.Abstractions.csproj
@@ -0,0 +1,9 @@
+
+
+ SOR.Networking.Abstractions
+
+
+
diff --git a/Server/src/SOR.Networking.Abstractions/Transport/AuthenticatedConnection.cs b/Server/src/SOR.Networking.Abstractions/Transport/AuthenticatedConnection.cs
new file mode 100644
index 0000000..86e97b8
--- /dev/null
+++ b/Server/src/SOR.Networking.Abstractions/Transport/AuthenticatedConnection.cs
@@ -0,0 +1,40 @@
+namespace SOR.Networking.Abstractions.Transport;
+
+///
+/// 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.
+///
+public sealed record AuthenticatedConnection(
+ /// The underlying transport connection for sending replies.
+ IClientConnection Connection,
+
+ ///
+ /// 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.
+ ///
+ string UserId,
+
+ ///
+ /// The user's display name at the time of authentication.
+ /// Cached here to avoid repeated lookups during the session.
+ ///
+ string DisplayName,
+
+ ///
+ /// The session token used to authenticate this connection.
+ /// Stored for revocation checks — if the token is invalidated mid-session,
+ /// the connection can be closed.
+ ///
+ string SessionToken
+);
diff --git a/Server/src/SOR.Networking.Abstractions/Transport/IClientConnection.cs b/Server/src/SOR.Networking.Abstractions/Transport/IClientConnection.cs
new file mode 100644
index 0000000..bb2a6e2
--- /dev/null
+++ b/Server/src/SOR.Networking.Abstractions/Transport/IClientConnection.cs
@@ -0,0 +1,69 @@
+namespace SOR.Networking.Abstractions.Transport;
+
+using SOR.Networking.Abstractions.Messaging;
+
+///
+/// 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.
+///
+public interface IClientConnection : IAsyncDisposable
+{
+ ///
+ /// 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.
+ ///
+ string ConnectionId { get; }
+
+ ///
+ /// Remote endpoint for logging (e.g., "203.0.113.42:55201").
+ ///
+ string RemoteAddress { get; }
+
+ ///
+ /// True while the underlying transport channel is open and usable.
+ /// May become false asynchronously when the client drops.
+ ///
+ bool IsConnected { get; }
+
+ ///
+ /// 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.
+ ///
+ Task ReceiveAsync(CancellationToken cancellationToken);
+
+ ///
+ /// 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.
+ ///
+ ValueTask SendBytesAsync(ReadOnlyMemory bytes, CancellationToken cancellationToken);
+
+ ///
+ /// 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.
+ ///
+ Task CloseAsync(string reason, CancellationToken cancellationToken);
+}
diff --git a/Server/src/SOR.Networking.Abstractions/Transport/ITransport.cs b/Server/src/SOR.Networking.Abstractions/Transport/ITransport.cs
new file mode 100644
index 0000000..69c7c56
--- /dev/null
+++ b/Server/src/SOR.Networking.Abstractions/Transport/ITransport.cs
@@ -0,0 +1,31 @@
+namespace SOR.Networking.Abstractions.Transport;
+
+///
+/// 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.
+///
+public interface ITransport
+{
+ ///
+ /// Human-readable identifier for this transport. Used in logs and metrics.
+ /// Examples: "websocket", "tcp", "quic"
+ ///
+ string Name { get; }
+
+ ///
+ /// 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.
+ ///
+ Task AcceptAsync(CancellationToken cancellationToken);
+}
diff --git a/Server/src/SOR.Networking.Nats/NatsEventBus.cs b/Server/src/SOR.Networking.Nats/NatsEventBus.cs
new file mode 100644
index 0000000..fe8eb72
--- /dev/null
+++ b/Server/src/SOR.Networking.Nats/NatsEventBus.cs
@@ -0,0 +1,107 @@
+namespace SOR.Networking.Nats;
+
+using System.Runtime.CompilerServices;
+using global::NATS.Client.Core;
+using Microsoft.Extensions.Logging;
+using SOR.Networking.Abstractions.EventBus;
+
+///
+/// IEventBus implementation backed by NATS.Net.
+///
+/// This class is the only place in the codebase where NATS types appear.
+/// All calling code depends only on IEventBus (the abstraction).
+/// To replace NATS with RabbitMQ or another broker:
+/// 1. Create SOR.Networking.RabbitMq.RabbitMqEventBus implementing IEventBus
+/// 2. Register it in SOR.Host instead of NatsEventBus
+/// 3. No other code changes
+///
+/// NATS delivery guarantee: at-most-once (fire-and-forget) for core NATS.
+/// For at-least-once delivery, use NATS JetStream — add a separate
+/// JetStreamEventBus class when durable subscriber support is needed.
+///
+/// Lifetime: Singleton (INatsConnection is a Singleton from SOR.Host DI registration).
+///
+public sealed class NatsEventBus : IEventBus
+{
+ private readonly INatsConnection _nats;
+ private readonly ILogger _logger;
+
+ // INatsConnection is injected from DI — registered in SOR.Host.Program.cs
+ // via builder.Services.AddNats(...). We don't create it here.
+ public NatsEventBus(INatsConnection nats, ILogger logger)
+ {
+ _nats = nats;
+ _logger = logger;
+ }
+
+ ///
+ ///
+ /// NATS.Net's PublishAsync{T} serializes T to JSON by default.
+ /// The serialization format can be changed by configuring the INatsConnection
+ /// serializer in SOR.Host — NatsEventBus does not need to change.
+ ///
+ public async Task PublishAsync(
+ string subject,
+ T payload,
+ CancellationToken cancellationToken = default)
+ where T : notnull
+ {
+ _logger.LogDebug("Publishing event to NATS subject {Subject}", subject);
+
+ await _nats.PublishAsync(subject, payload, cancellationToken: cancellationToken);
+ }
+
+ ///
+ ///
+ /// Returns an IAsyncEnumerable{T} that projects NATS message envelopes down to T.
+ /// The 'yield return' pattern (async iterator) is used via the AsyncIterator
+ /// helper method below because you cannot use 'await foreach' inside a method
+ /// that also uses 'yield return' directly in older C# versions. In C# 12 with
+ /// async iterators, this is supported directly.
+ ///
+ /// Callers:
+ /// await foreach (var evt in _bus.SubscribeAsync{GameEndedEvent}(subject, ct))
+ /// await HandleAsync(evt);
+ ///
+ public IAsyncEnumerable SubscribeAsync(
+ string subject,
+ CancellationToken cancellationToken = default)
+ where T : notnull
+ {
+ _logger.LogDebug("Subscribing to NATS subject {Subject}", subject);
+ return SubscribeAsyncIterator(subject, cancellationToken);
+ }
+
+ ///
+ /// Async iterator that yields NATS messages as T.
+ ///
+ /// 'async IAsyncEnumerable' with 'yield return' creates an async stream.
+ /// Each 'yield return' produces one item; the caller gets control between items.
+ /// The [EnumeratorCancellation] attribute forwards the caller's cancellation token
+ /// into the iterator automatically when the caller cancels the 'await foreach'.
+ ///
+ private async IAsyncEnumerable SubscribeAsyncIterator(
+ string subject,
+ [EnumeratorCancellation] CancellationToken cancellationToken)
+ where T : notnull
+ {
+ // SubscribeAsync returns IAsyncEnumerable{NatsMsg{T}}.
+ // NatsMsg{T} is the NATS envelope containing the deserialized data plus metadata.
+ await foreach (var msg in _nats
+ .SubscribeAsync(subject, cancellationToken: cancellationToken)
+ .WithCancellation(cancellationToken))
+ {
+ // Skip null data (can occur for empty NATS messages or deserialization failures).
+ if (msg.Data is null)
+ {
+ _logger.LogWarning(
+ "Received null data on NATS subject {Subject} — skipping", subject);
+ continue;
+ }
+
+ // Yield the deserialized value to the caller.
+ // The caller processes it before we loop back to await the next message.
+ yield return msg.Data;
+ }
+ }
+}
diff --git a/Server/src/SOR.Networking.Nats/SOR.Networking.Nats.csproj b/Server/src/SOR.Networking.Nats/SOR.Networking.Nats.csproj
new file mode 100644
index 0000000..c04d9ec
--- /dev/null
+++ b/Server/src/SOR.Networking.Nats/SOR.Networking.Nats.csproj
@@ -0,0 +1,15 @@
+
+
+ SOR.Networking.Nats
+
+
+
+
+
+
+
+
+
+
diff --git a/Server/src/SOR.Networking.Nats/ServiceRegistration.cs b/Server/src/SOR.Networking.Nats/ServiceRegistration.cs
new file mode 100644
index 0000000..85fab5b
--- /dev/null
+++ b/Server/src/SOR.Networking.Nats/ServiceRegistration.cs
@@ -0,0 +1,37 @@
+namespace SOR.Networking.Nats;
+
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using SOR.Networking.Abstractions.EventBus;
+
+///
+/// Registers the NATS event bus in the DI container.
+///
+/// Note: The INatsConnection itself is registered in SOR.Host.Program.cs via
+/// builder.Services.AddNats(...) because it requires the NATS URL from config.
+/// This registration only wraps it behind IEventBus.
+///
+/// To swap NATS for another broker:
+/// In SOR.Host, replace AddNatsEventBus() with AddRabbitMqEventBus() (or equivalent).
+/// No service code changes.
+///
+public static class ServiceRegistration
+{
+ ///
+ /// Registers IEventBus → NatsEventBus as a Singleton.
+ ///
+ /// Precondition: INatsConnection must already be registered in the DI container
+ /// (done in SOR.Host.Program.cs via builder.Services.AddNats(...)).
+ ///
+ public static IServiceCollection AddNatsEventBus(
+ this IServiceCollection services,
+ IConfiguration configuration)
+ {
+ // NatsEventBus depends on INatsConnection (Singleton from Host)
+ // and ILogger{NatsEventBus} (provided by Serilog).
+ // Both are already registered by the time this runs.
+ services.AddSingleton();
+
+ return services;
+ }
+}
diff --git a/Server/src/SOR.Networking.Redis/RedisClientPush.cs b/Server/src/SOR.Networking.Redis/RedisClientPush.cs
new file mode 100644
index 0000000..7ab84dd
--- /dev/null
+++ b/Server/src/SOR.Networking.Redis/RedisClientPush.cs
@@ -0,0 +1,71 @@
+namespace SOR.Networking.Redis;
+
+using Microsoft.Extensions.Logging;
+using StackExchange.Redis;
+using SOR.Networking.Abstractions.Messaging;
+using SOR.Networking.Abstractions.Push;
+using SOR.Shared.Redis;
+
+///
+/// IClientPush implementation using Redis Pub/Sub.
+///
+/// This is the WRITE side of the push delivery pipeline:
+/// Service calls PushAsync(userId, message)
+/// → Serializes message to bytes (via IMessageSerializer)
+/// → Publishes to Redis channel "push:{userId}"
+/// → Gateway (subscribed to that channel) receives the bytes
+/// → Gateway forwards bytes to the user's WebSocket
+///
+/// The Gateway's READ side (RedisPushSubscriber) handles the subscription.
+/// This class only handles publishing — it has no knowledge of Gateway internals.
+///
+/// Best-effort delivery: if no Gateway is subscribed to the userId channel
+/// (user disconnected), the message is dropped silently. This is correct behavior.
+/// Services must not assume push delivery is reliable — use persistent state and
+/// client-initiated sync for any data that must survive disconnections.
+///
+/// Lifetime: Singleton (IConnectionMultiplexer is a Singleton from SOR.Host).
+///
+public sealed class RedisClientPush : IClientPush
+{
+ private readonly IConnectionMultiplexer _redis;
+ private readonly IMessageSerializer _serializer;
+ private readonly ILogger _logger;
+
+ public RedisClientPush(
+ IConnectionMultiplexer redis,
+ IMessageSerializer serializer,
+ ILogger logger)
+ {
+ _redis = redis;
+ _serializer = serializer;
+ _logger = logger;
+ }
+
+ ///
+ public async Task PushAsync(
+ string userId,
+ IServerMessage message,
+ CancellationToken cancellationToken = default)
+ {
+ // Serialize the message to bytes.
+ // The bytes are already in wire format (envelope + payload) — ready for
+ // the Gateway to forward directly to the WebSocket without re-serializing.
+ var bytes = _serializer.Serialize(message);
+
+ // Get the Redis channel key for this user.
+ // RedisKey.Literal wraps the string to avoid StackExchange.Redis interpreting
+ // pattern characters (* ? [) as wildcards.
+ var channel = RedisChannel.Literal(RedisKeys.ClientPushChannel(userId));
+
+ _logger.LogDebug(
+ "Pushing {MessageType} to user {UserId} via Redis Pub/Sub",
+ message.Type, userId);
+
+ // ISubscriber.PublishAsync sends to the channel.
+ // The return value is the number of subscribers that received the message.
+ // We don't check it — zero subscribers (user disconnected) is not an error.
+ var subscriber = _redis.GetSubscriber();
+ await subscriber.PublishAsync(channel, bytes.ToArray());
+ }
+}
diff --git a/Server/src/SOR.Networking.Redis/SOR.Networking.Redis.csproj b/Server/src/SOR.Networking.Redis/SOR.Networking.Redis.csproj
new file mode 100644
index 0000000..e794644
--- /dev/null
+++ b/Server/src/SOR.Networking.Redis/SOR.Networking.Redis.csproj
@@ -0,0 +1,15 @@
+
+
+ SOR.Networking.Redis
+
+
+
+
+
+
+
+
+
+
diff --git a/Server/src/SOR.Networking.Redis/ServiceRegistration.cs b/Server/src/SOR.Networking.Redis/ServiceRegistration.cs
new file mode 100644
index 0000000..d4f415b
--- /dev/null
+++ b/Server/src/SOR.Networking.Redis/ServiceRegistration.cs
@@ -0,0 +1,30 @@
+namespace SOR.Networking.Redis;
+
+using Microsoft.Extensions.DependencyInjection;
+using SOR.Networking.Abstractions.Push;
+
+///
+/// Registers the Redis client push service in the DI container.
+///
+/// Note: IConnectionMultiplexer and IMessageSerializer must already be registered
+/// before calling this (both are registered in SOR.Host.Program.cs).
+///
+/// To replace Redis Pub/Sub with another push delivery mechanism:
+/// Create an alternative IClientPush implementation and call its registration
+/// method instead of AddRedisClientPush(). No Gateway or service code changes.
+///
+public static class ServiceRegistration
+{
+ ///
+ /// Registers IClientPush → RedisClientPush as a Singleton.
+ ///
+ /// Preconditions (must be registered in DI before calling this):
+ /// - IConnectionMultiplexer (StackExchange.Redis)
+ /// - IMessageSerializer (from SOR.Shared.ServiceRegistration.AddSharedServices)
+ ///
+ public static IServiceCollection AddRedisClientPush(this IServiceCollection services)
+ {
+ services.AddSingleton();
+ return services;
+ }
+}
diff --git a/Server/src/SOR.Networking.WebSocket/SOR.Networking.WebSocket.csproj b/Server/src/SOR.Networking.WebSocket/SOR.Networking.WebSocket.csproj
new file mode 100644
index 0000000..e0f272b
--- /dev/null
+++ b/Server/src/SOR.Networking.WebSocket/SOR.Networking.WebSocket.csproj
@@ -0,0 +1,15 @@
+
+
+ SOR.Networking.WebSocket
+
+
+
+
+
+
+
+
+
diff --git a/Server/src/SOR.Networking.WebSocket/ServiceRegistration.cs b/Server/src/SOR.Networking.WebSocket/ServiceRegistration.cs
new file mode 100644
index 0000000..2aeb4c8
--- /dev/null
+++ b/Server/src/SOR.Networking.WebSocket/ServiceRegistration.cs
@@ -0,0 +1,122 @@
+namespace SOR.Networking.WebSocket;
+
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Options;
+using SOR.Networking.Abstractions.Transport;
+
+///
+/// Extension methods to register and wire the WebSocket transport.
+///
+/// Usage in SOR.Host.Program.cs:
+/// builder.Services.AddWebSocketTransport(builder.Configuration);
+/// ...
+/// app.UseWebSocketTransport(); // Must come BEFORE UseRouting()
+///
+public static class ServiceRegistration
+{
+ ///
+ /// Registers the WebSocket transport in the DI container.
+ ///
+ /// What this registers:
+ /// - WebSocketTransportOptions from appsettings.json "WebSocket" section
+ /// - WebSocketTransport as Singleton (the transport lives for the process lifetime)
+ /// - ITransport → WebSocketTransport (the interface Gateway depends on)
+ /// - ASP.NET Core's built-in WebSocket middleware (services.AddWebSockets)
+ ///
+ public static IServiceCollection AddWebSocketTransport(
+ this IServiceCollection services,
+ IConfiguration configuration)
+ {
+ // Bind the "WebSocket" config section to the typed options class.
+ // IOptions{WebSocketTransportOptions} can then be injected anywhere.
+ services.Configure(
+ configuration.GetSection("WebSocket"));
+
+ // Register the concrete transport as Singleton.
+ // GatewayHostedService injects ITransport (the interface).
+ // The middleware (UseWebSocketTransport) injects WebSocketTransport directly
+ // to call EnqueueConnectionAsync — that's why we register it by concrete type too.
+ services.AddSingleton();
+
+ // Register ITransport → resolve WebSocketTransport from the container.
+ // This means: anywhere ITransport is injected, the container provides
+ // the already-registered WebSocketTransport singleton.
+ services.AddSingleton(
+ sp => sp.GetRequiredService());
+
+ // NOTE: services.AddWebSockets() must be called separately in SOR.Host.Program.cs.
+ // AddWebSockets is an ASP.NET Core extension that resolves correctly only from a
+ // Microsoft.NET.Sdk.Web project. SOR.Host (the entry point) calls it before
+ // calling AddWebSocketTransport(). See SOR.Host.Program.cs for details.
+
+ return services;
+ }
+
+ ///
+ /// Inserts the WebSocket upgrade middleware into the ASP.NET Core pipeline.
+ ///
+ /// This middleware intercepts HTTP requests to the configured path ("/ws" by default),
+ /// performs the WebSocket upgrade handshake, and hands the socket to WebSocketTransport.
+ ///
+ /// IMPORTANT: Call this BEFORE app.UseRouting() so the WebSocket middleware
+ /// intercepts upgrade requests before they reach the routing layer.
+ ///
+ /// The middleware holds the request alive (via TaskCompletionSource) until
+ /// the Gateway's ConnectionLoop signals the connection is done. This keeps
+ /// the ASP.NET Core request pipeline entry point open for the duration of
+ /// the WebSocket session.
+ ///
+ public static IApplicationBuilder UseWebSocketTransport(this IApplicationBuilder app)
+ {
+ // NOTE: app.UseWebSockets() is called in SOR.Host.Program.cs before this method.
+ // It must be called from the Web SDK host project (SOR.Host) where the
+ // Microsoft.AspNetCore.WebSockets assembly is fully available.
+
+ // Our custom middleware: intercept WebSocket upgrade requests.
+ app.Use(async (context, next) =>
+ {
+ var options = context.RequestServices
+ .GetRequiredService>().Value;
+
+ // Only intercept requests to the configured WebSocket path.
+ // All other requests pass through to the next middleware (routing, gRPC, etc.).
+ if (context.Request.Path != options.Path ||
+ !context.WebSockets.IsWebSocketRequest)
+ {
+ await next(context);
+ return;
+ }
+
+ // Perform the WebSocket upgrade handshake.
+ // AcceptWebSocketAsync sends the HTTP 101 Switching Protocols response.
+ var socket = await context.WebSockets.AcceptWebSocketAsync();
+
+ // A TaskCompletionSource is a manually controlled Task completion signal.
+ // The Gateway's ConnectionLoop calls connectionDone.SetResult() when it finishes
+ // handling this connection. Until then, this middleware holds the request alive.
+ var connectionDone = new TaskCompletionSource(
+ TaskCreationOptions.RunContinuationsAsynchronously);
+
+ // Register a callback: when the request is aborted (client closes browser,
+ // server shutdown, etc.), signal the done TCS so the middleware exits cleanly.
+ context.RequestAborted.Register(() => connectionDone.TrySetResult());
+
+ var transport = context.RequestServices
+ .GetRequiredService();
+
+ // Enqueue the connection for the Gateway's accept loop.
+ // Pass connectionDone so the connection signals this middleware on dispose.
+ await transport.EnqueueConnectionAsync(
+ socket, context, connectionDone, context.RequestAborted);
+
+ // Wait here until the Gateway signals the connection is done.
+ // This keeps the HTTP request alive for the full WebSocket session duration.
+ await connectionDone.Task;
+ });
+
+ return app;
+ }
+}
diff --git a/Server/src/SOR.Networking.WebSocket/WebSocketClientConnection.cs b/Server/src/SOR.Networking.WebSocket/WebSocketClientConnection.cs
new file mode 100644
index 0000000..6925b5a
--- /dev/null
+++ b/Server/src/SOR.Networking.WebSocket/WebSocketClientConnection.cs
@@ -0,0 +1,281 @@
+namespace SOR.Networking.WebSocket;
+
+using System.Buffers;
+using System.Net.WebSockets;
+using Microsoft.Extensions.Logging;
+using SOR.Networking.Abstractions.Messaging;
+using SOR.Networking.Abstractions.Transport;
+
+///
+/// IClientConnection implementation backed by a System.Net.WebSockets.WebSocket.
+///
+/// Key responsibilities:
+/// - Frame assembly: WebSocket messages can be split across multiple frames.
+/// ReceiveAsync loops until EndOfMessage = true, assembling into a MemoryStream.
+/// - Send serialization: only one send can be in flight at a time per WebSocket.
+/// SemaphoreSlim(1,1) acts as an async mutex on the send path.
+/// - Ping/pong heartbeat: a background task sends periodic ping frames so
+/// disconnected clients are detected within one PingIntervalMs cycle.
+///
+/// Thread safety:
+/// - ReceiveAsync: called only by the ConnectionLoop — no concurrent receive.
+/// - SendBytesAsync: may be called concurrently (push delivery + reply at same time).
+/// The _sendLock serializes concurrent sends.
+///
+/// Lifetime: created by WebSocketTransport per accepted connection.
+/// Disposed by ConnectionLoop.RunAsync() in its finally block.
+///
+public sealed class WebSocketClientConnection : IClientConnection
+{
+ private readonly System.Net.WebSockets.WebSocket _socket;
+ private readonly WebSocketTransportOptions _options;
+ private readonly ILogger _logger;
+
+ // SemaphoreSlim(1, 1) is a lightweight async-compatible mutex.
+ // Unlike 'lock', it can be awaited without blocking the thread.
+ private readonly SemaphoreSlim _sendLock = new(1, 1);
+
+ // CancellationTokenSource for the ping loop. Cancelled on dispose.
+ private readonly CancellationTokenSource _pingSts = new();
+
+ // Signals the middleware that this connection's loop has finished,
+ // so the middleware can release the HTTP request cleanly.
+ private readonly TaskCompletionSource _connectionDone;
+
+ private bool _disposed;
+
+ public string ConnectionId { get; }
+ public string RemoteAddress { get; }
+
+ public bool IsConnected =>
+ !_disposed && _socket.State == WebSocketState.Open;
+
+ public WebSocketClientConnection(
+ System.Net.WebSockets.WebSocket socket,
+ string connectionId,
+ string remoteAddress,
+ WebSocketTransportOptions options,
+ ILogger logger,
+ TaskCompletionSource connectionDone)
+ {
+ _socket = socket;
+ ConnectionId = connectionId;
+ RemoteAddress = remoteAddress;
+ _options = options;
+ _logger = logger;
+ _connectionDone = connectionDone;
+
+ // Start the ping loop in the background immediately.
+ // '_ =' discards the Task intentionally — the loop runs fire-and-forget.
+ // Exceptions inside are caught within the loop and logged.
+ _ = RunPingLoopAsync(_pingSts.Token);
+ }
+
+ ///
+ ///
+ /// Assembles a complete WebSocket message from one or more frames.
+ /// Returns null on clean close (WebSocketMessageType.Close received).
+ /// Throws WebSocketException on unexpected disconnect — the caller handles it.
+ ///
+ /// ArrayPool{byte}.Shared is used to rent receive buffers from a reusable pool
+ /// rather than allocating a new byte[] per receive. Buffers are returned in finally.
+ /// This is a common pattern for high-throughput .NET networking code.
+ ///
+ public async Task ReceiveAsync(CancellationToken cancellationToken)
+ {
+ // Rent a buffer from the shared pool. The buffer may be larger than requested.
+ // Always use ArrayPool.Return() in a finally block to avoid pool exhaustion.
+ var buffer = ArrayPool.Shared.Rent(_options.MaxMessageSizeBytes);
+ try
+ {
+ using var messageStream = new MemoryStream();
+ WebSocketReceiveResult result;
+
+ do
+ {
+ // Receive one frame (may not be the complete message).
+ result = await _socket.ReceiveAsync(
+ new ArraySegment(buffer), cancellationToken);
+
+ switch (result.MessageType)
+ {
+ case WebSocketMessageType.Close:
+ // Client sent a close frame — clean disconnect.
+ _logger.LogDebug(
+ "WebSocket close received: ConnectionId={ConnectionId} Status={Status}",
+ ConnectionId, result.CloseStatus);
+ return null;
+
+ case WebSocketMessageType.Text:
+ case WebSocketMessageType.Binary:
+ // Check if this frame would push us over the size limit.
+ if (messageStream.Length + result.Count > _options.MaxMessageSizeBytes)
+ {
+ _logger.LogWarning(
+ "Message too large: ConnectionId={ConnectionId} Limit={Limit}",
+ ConnectionId, _options.MaxMessageSizeBytes);
+ await CloseAsync("message_too_large", cancellationToken);
+ return null;
+ }
+ // Append this frame's bytes to the message buffer.
+ messageStream.Write(buffer, 0, result.Count);
+ break;
+ }
+
+ // EndOfMessage = true when all frames of this message have arrived.
+ } while (!result.EndOfMessage);
+
+ // Return the assembled bytes as a RawClientMessage.
+ // The serializer will parse the envelope (type, seq, payload) from these bytes.
+ // We import RawClientMessage from SOR.Networking.Abstractions' concrete type
+ // in SOR.Shared — but this project doesn't reference SOR.Shared.
+ // Solution: return the bytes wrapped in a minimal internal implementation.
+ return new ReceivedMessage(messageStream.ToArray());
+ }
+ finally
+ {
+ // Always return the rented buffer, even if an exception is thrown.
+ ArrayPool.Shared.Return(buffer);
+ }
+ }
+
+ ///
+ public async ValueTask SendBytesAsync(ReadOnlyMemory bytes, CancellationToken cancellationToken)
+ {
+ // Acquire the send lock. If another send is in progress, this awaits until it completes.
+ await _sendLock.WaitAsync(cancellationToken);
+ try
+ {
+ if (_socket.State != WebSocketState.Open) return;
+
+ // Send as a binary frame. EndOfMessage = true (single-frame message).
+ await _socket.SendAsync(bytes, WebSocketMessageType.Binary, true, cancellationToken);
+ }
+ finally
+ {
+ // Always release the lock, even if an exception occurs.
+ _sendLock.Release();
+ }
+ }
+
+ ///
+ public async Task CloseAsync(string reason, CancellationToken cancellationToken)
+ {
+ if (_socket.State != WebSocketState.Open) return;
+
+ try
+ {
+ // Send a close frame with a normal closure status.
+ // The client should respond with its own close frame, completing the handshake.
+ await _socket.CloseAsync(
+ WebSocketCloseStatus.NormalClosure,
+ reason,
+ cancellationToken);
+ }
+ catch (Exception ex)
+ {
+ // If the close handshake fails (client already gone), log and continue.
+ _logger.LogDebug(ex,
+ "Close handshake failed: ConnectionId={ConnectionId}", ConnectionId);
+ }
+ }
+
+ // ── Ping/Pong Heartbeat ────────────────────────────────────────────────────
+
+ ///
+ /// Sends periodic ping frames to detect stale connections.
+ /// RFC 6455: the remote end must respond with a pong frame within a reasonable time.
+ /// ASP.NET Core's WebSocket implementation handles pong responses automatically.
+ /// If the connection drops between pings, the next send or receive will throw.
+ ///
+ private async Task RunPingLoopAsync(CancellationToken ct)
+ {
+ try
+ {
+ while (!ct.IsCancellationRequested)
+ {
+ await Task.Delay(_options.PingIntervalMs, ct);
+
+ if (_socket.State != WebSocketState.Open) return;
+
+ await _sendLock.WaitAsync(ct);
+ try
+ {
+ // An empty binary frame acts as a ping in our protocol.
+ // For full RFC 6455 ping/pong, WebSocketMessageType.Close is not applicable;
+ // ASP.NET Core handles pong automatically at the Kestrel level.
+ await _socket.SendAsync(
+ ReadOnlyMemory.Empty,
+ WebSocketMessageType.Binary,
+ endOfMessage: true,
+ ct);
+ }
+ finally
+ {
+ _sendLock.Release();
+ }
+ }
+ }
+ catch (OperationCanceledException)
+ {
+ // Normal exit on dispose or shutdown.
+ }
+ catch (Exception ex)
+ {
+ // Log ping failures but don't crash — the connection loop will detect
+ // the disconnection on the next ReceiveAsync call.
+ _logger.LogDebug(ex,
+ "Ping loop error: ConnectionId={ConnectionId}", ConnectionId);
+ }
+ }
+
+ // ── IAsyncDisposable ──────────────────────────────────────────────────────
+
+ public async ValueTask DisposeAsync()
+ {
+ if (_disposed) return;
+ _disposed = true;
+
+ // Stop the ping loop.
+ await _pingSts.CancelAsync();
+ _pingSts.Dispose();
+
+ // Dispose the send lock.
+ _sendLock.Dispose();
+
+ // Dispose the underlying WebSocket.
+ _socket.Dispose();
+
+ // Signal the middleware that this connection's work is complete.
+ // TrySetResult is used (not SetResult) because RequestAborted may have
+ // already set it if the server is shutting down.
+ _connectionDone.TrySetResult();
+ }
+
+ // ── Inner type: minimal IClientMessage for raw received bytes ─────────────
+
+ ///
+ /// Lightweight IClientMessage carrying raw wire bytes.
+ /// Type and Seq are populated after IMessageSerializer.Deserialize() is called.
+ /// This inner class is private to SOR.Networking.WebSocket — external code
+ /// only sees the IClientMessage interface.
+ ///
+ private sealed class ReceivedMessage : IClientMessage
+ {
+ // Before deserialization, Type and Seq are unknown.
+ // They will be set by the serializer layer before dispatch.
+ // We use a mutable design here because the serializer returns a new
+ // RawClientMessage (from SOR.Shared) — this type is only an interim carrier
+ // from ReceiveAsync up to the serializer call in ConnectionLoop.
+ public string Type { get; init; } = string.Empty;
+ public int Seq { get; init; }
+ public ReadOnlyMemory Payload { get; }
+
+ public ReceivedMessage(byte[] rawBytes)
+ {
+ // The full wire bytes (envelope + payload) are stored as Payload.
+ // The serializer will parse the envelope out of these bytes.
+ Payload = rawBytes;
+ }
+ }
+}
diff --git a/Server/src/SOR.Networking.WebSocket/WebSocketTransport.cs b/Server/src/SOR.Networking.WebSocket/WebSocketTransport.cs
new file mode 100644
index 0000000..a0cde76
--- /dev/null
+++ b/Server/src/SOR.Networking.WebSocket/WebSocketTransport.cs
@@ -0,0 +1,122 @@
+namespace SOR.Networking.WebSocket;
+
+using System.Net.WebSockets;
+using System.Threading.Channels;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Options;
+using SOR.Networking.Abstractions.Transport;
+
+///
+/// ITransport implementation for WebSocket connections.
+///
+/// How the two sides connect:
+///
+/// ┌─────────────────────────────────────────────────────────────┐
+/// │ ASP.NET Core middleware (UseWebSocketTransport) │
+/// │ - Intercepts HTTP upgrade requests to the WS path │
+/// │ - Calls AcceptWebSocketAsync() │
+/// │ - Calls WebSocketTransport.EnqueueConnectionAsync() │
+/// └────────────────────────┬────────────────────────────────────┘
+/// │ Channel.Writer.WriteAsync()
+/// ▼
+/// ┌─────────────────────────────────────────────────────────────┐
+/// │ Channel{IClientConnection} (thread-safe handoff queue) │
+/// └────────────────────────┬────────────────────────────────────┘
+/// │ Channel.Reader.ReadAsync()
+/// ▼
+/// ┌─────────────────────────────────────────────────────────────┐
+/// │ GatewayHostedService │
+/// │ - Calls ITransport.AcceptAsync() (blocks on channel) │
+/// │ - Gets an IClientConnection and fires ConnectionLoop │
+/// └─────────────────────────────────────────────────────────────┘
+///
+/// The Channel is the key: it decouples the ASP.NET Core middleware thread
+/// from the Gateway accept loop without any shared mutable state.
+///
+/// Lifetime: Singleton.
+///
+public sealed class WebSocketTransport : ITransport
+{
+ public string Name => "websocket";
+
+ private readonly WebSocketTransportOptions _options;
+ private readonly ILoggerFactory _loggerFactory;
+ private readonly ILogger _logger;
+
+ // UnboundedChannel: never drops connections. If Gateway is slow to accept,
+ // connections queue. SingleReader = true allows the channel to optimize
+ // for a single consumer (the Gateway accept loop).
+ private readonly Channel _pendingConnections =
+ Channel.CreateUnbounded(
+ new UnboundedChannelOptions
+ {
+ SingleReader = true, // Only GatewayHostedService reads
+ SingleWriter = false, // Multiple middleware calls can write concurrently
+ });
+
+ public WebSocketTransport(
+ IOptions options,
+ ILoggerFactory loggerFactory,
+ ILogger logger)
+ {
+ _options = options.Value;
+ _loggerFactory = loggerFactory;
+ _logger = logger;
+ }
+
+ ///
+ /// Called by the ASP.NET Core middleware (ServiceRegistration.UseWebSocketTransport)
+ /// when a WebSocket upgrade succeeds. Creates a WebSocketClientConnection and
+ /// enqueues it for the Gateway's accept loop.
+ ///
+ /// 'internal' means this method is visible within SOR.Networking.WebSocket but
+ /// not to external assemblies. The middleware and transport live in the same assembly.
+ ///
+ ///
+ /// Called by the ASP.NET Core middleware (ServiceRegistration.UseWebSocketTransport)
+ /// when a WebSocket upgrade succeeds. Creates a WebSocketClientConnection and
+ /// enqueues it for the Gateway's accept loop.
+ ///
+ /// The connectionDone TaskCompletionSource is stored on the connection and signalled
+ /// when the connection is disposed (ConnectionLoop.RunAsync finally block).
+ /// The middleware awaits connectionDone.Task to keep the HTTP request alive for the
+ /// full WebSocket session, then lets the middleware method return to free resources.
+ ///
+ /// 'internal': visible within SOR.Networking.WebSocket but not to external assemblies.
+ ///
+ internal async Task EnqueueConnectionAsync(
+ System.Net.WebSockets.WebSocket socket,
+ HttpContext httpContext,
+ TaskCompletionSource connectionDone,
+ CancellationToken cancellationToken)
+ {
+ var connectionId = Guid.NewGuid().ToString("N");
+ var remote = httpContext.Connection.RemoteIpAddress?.ToString()
+ ?? httpContext.Connection.RemotePort.ToString()
+ ?? "unknown";
+
+ _logger.LogDebug(
+ "WebSocket upgrade accepted: ConnectionId={ConnectionId} Remote={Remote}",
+ connectionId, remote);
+
+ var connLogger = _loggerFactory.CreateLogger(
+ $"SOR.Networking.WebSocket.Connection.{connectionId[..8]}");
+
+ var connection = new WebSocketClientConnection(
+ socket, connectionId, remote, _options, connLogger, connectionDone);
+
+ // WriteAsync never blocks for an UnboundedChannel.
+ await _pendingConnections.Writer.WriteAsync(connection, cancellationToken);
+ }
+
+ ///
+ ///
+ /// Blocks until a connection is enqueued by the middleware, then dequeues and returns it.
+ /// Throws OperationCanceledException on shutdown (cancellationToken cancelled).
+ ///
+ public async Task AcceptAsync(CancellationToken cancellationToken)
+ {
+ return await _pendingConnections.Reader.ReadAsync(cancellationToken);
+ }
+}
diff --git a/Server/src/SOR.Networking.WebSocket/WebSocketTransportOptions.cs b/Server/src/SOR.Networking.WebSocket/WebSocketTransportOptions.cs
new file mode 100644
index 0000000..648e144
--- /dev/null
+++ b/Server/src/SOR.Networking.WebSocket/WebSocketTransportOptions.cs
@@ -0,0 +1,41 @@
+namespace SOR.Networking.WebSocket;
+
+///
+/// Configuration options for the WebSocket transport.
+/// Bound from the "WebSocket" section of appsettings.json via IOptions{WebSocketTransportOptions}.
+///
+/// appsettings.json example:
+/// {
+/// "WebSocket": {
+/// "Path": "/ws",
+/// "PingIntervalMs": 30000,
+/// "MaxMessageSizeBytes": 65536,
+/// "AuthTimeoutMs": 10000
+/// }
+/// }
+///
+public sealed class WebSocketTransportOptions
+{
+ ///
+ /// The URL path the Gateway listens for WebSocket upgrade requests.
+ /// All other paths are passed through to the normal ASP.NET Core routing pipeline.
+ /// Default: "/ws"
+ ///
+ public string Path { get; set; } = "/ws";
+
+ ///
+ /// How often to send a WebSocket ping frame to detect stale connections.
+ /// RFC 6455 compliant clients respond automatically with a pong.
+ /// If no pong is received within this interval the connection is considered dead.
+ /// Default: 30 seconds (30,000 ms)
+ ///
+ public int PingIntervalMs { get; set; } = 30_000;
+
+ ///
+ /// Maximum allowed size of a single WebSocket message in bytes.
+ /// Multi-frame messages are assembled up to this limit.
+ /// Messages exceeding this cause the connection to be closed with code 1009 (too large).
+ /// Default: 64 KB (65,536 bytes) — sufficient for all current game message types.
+ ///
+ public int MaxMessageSizeBytes { get; set; } = 65_536;
+}
diff --git a/Server/src/SOR.Shared.Proto/Protos/auth.proto b/Server/src/SOR.Shared.Proto/Protos/auth.proto
new file mode 100644
index 0000000..716779a
--- /dev/null
+++ b/Server/src/SOR.Shared.Proto/Protos/auth.proto
@@ -0,0 +1,98 @@
+// Protobuf language version 3 — the current standard.
+// proto3 differences from proto2: all fields optional by default,
+// no required fields, simpler default values.
+syntax = "proto3";
+
+// The C# namespace for all generated types from this file.
+// Generated classes: AuthService.AuthServiceBase (server), AuthService.AuthServiceClient (client),
+// LoginRequest, LoginResponse, ValidateTokenRequest, ValidateTokenResponse, etc.
+option csharp_namespace = "SOR.Shared.Proto";
+
+// Package prevents naming collisions with other .proto files.
+// Does not affect the C# namespace (that's controlled by csharp_namespace above).
+package sor.auth;
+
+// ── Request / Response Messages ───────────────────────────────────────────────
+//
+// A 'message' is a structured data type. It compiles to a C# class with properties.
+// Each field has:
+// type — the data type (string, int32, bool, or another message)
+// name — the property name in the generated C# code
+// number — the field number used in binary encoding (NEVER change these;
+// changing a field number is a breaking change in binary format)
+
+// ── Login ─────────────────────────────────────────────────────────────────────
+
+message LoginRequest {
+ string email = 1;
+ string password = 2;
+}
+
+message LoginResponse {
+ bool success = 1;
+
+ // Only populated on success. Empty string ("") on failure.
+ string session_token = 2;
+
+ // Only populated on failure. Examples: "USER_NOT_FOUND", "INVALID_PASSWORD", "ACCOUNT_BANNED"
+ string error_code = 3;
+}
+
+// ── Token Validation ──────────────────────────────────────────────────────────
+
+// Used by Gateway during the auth handshake to validate session tokens.
+// Also used by other services that need to verify caller identity.
+message ValidateTokenRequest {
+ string session_token = 1;
+}
+
+message ValidateTokenResponse {
+ bool valid = 1;
+
+ // Only populated when valid = true.
+ string user_id = 2;
+ string display_name = 3;
+}
+
+// ── Registration ──────────────────────────────────────────────────────────────
+
+message RegisterRequest {
+ string email = 1;
+ string password = 2;
+ string display_name = 3;
+}
+
+message RegisterResponse {
+ bool success = 1;
+ string session_token = 2; // Set on success — user is automatically logged in
+ string error_code = 3; // e.g., "EMAIL_TAKEN", "DISPLAY_NAME_TAKEN", "WEAK_PASSWORD"
+}
+
+// ── Logout ────────────────────────────────────────────────────────────────────
+
+message LogoutRequest {
+ string session_token = 1;
+}
+
+// Empty response — logout always succeeds (idempotent; revoking a non-existent token is fine)
+message LogoutResponse {}
+
+// ── Service Definition ────────────────────────────────────────────────────────
+//
+// 'service' defines the RPC methods. The Protobuf compiler generates:
+// - AuthService.AuthServiceBase: abstract base class for the server handler to inherit
+// - AuthService.AuthServiceClient: client stub for other services to call Auth
+
+service AuthService {
+ // Primary login with email + password
+ rpc Login(LoginRequest) returns (LoginResponse);
+
+ // Validate an opaque session token (called by Gateway on every connection)
+ rpc ValidateToken(ValidateTokenRequest) returns (ValidateTokenResponse);
+
+ // Create a new account
+ rpc Register(RegisterRequest) returns (RegisterResponse);
+
+ // Revoke a session token (called on explicit logout or ban)
+ rpc Logout(LogoutRequest) returns (LogoutResponse);
+}
diff --git a/Server/src/SOR.Shared.Proto/SOR.Shared.Proto.csproj b/Server/src/SOR.Shared.Proto/SOR.Shared.Proto.csproj
new file mode 100644
index 0000000..c7be774
--- /dev/null
+++ b/Server/src/SOR.Shared.Proto/SOR.Shared.Proto.csproj
@@ -0,0 +1,24 @@
+
+
+ SOR.Shared.Proto
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Server/src/SOR.Shared/Models/ServiceResult.cs b/Server/src/SOR.Shared/Models/ServiceResult.cs
new file mode 100644
index 0000000..dac81f3
--- /dev/null
+++ b/Server/src/SOR.Shared/Models/ServiceResult.cs
@@ -0,0 +1,60 @@
+namespace SOR.Shared.Models;
+
+///
+/// Standardized return type for business logic operations.
+///
+/// Expected failures (user not found, invalid input, duplicate name, etc.) are
+/// returned as ServiceResult.Fail(...) — no exception is thrown.
+/// Exceptions are reserved for truly unexpected failures (database unreachable, OOM).
+///
+/// Usage in a service:
+/// public async Task{ServiceResult{string}} LoginAsync(string email, string password)
+/// {
+/// var user = await _repo.FindByEmailAsync(email);
+/// if (user is null) return ServiceResult{string}.Fail("USER_NOT_FOUND", "...");
+/// ...
+/// return ServiceResult{string}.Ok(token);
+/// }
+///
+/// Usage in a handler:
+/// var result = await _authService.LoginAsync(email, password);
+/// if (!result.Success) return ServerMessage.Error(req.Seq, result.ErrorCode!, result.ErrorMessage!);
+/// return ServerMessage.Reply("auth.login.ack", req.Seq, new { Token = result.Value });
+///
+/// 'record' generates equality, ToString(), and a compact constructor automatically.
+/// The generic parameter T is the success value type.
+///
+public sealed record ServiceResult
+{
+ /// True if the operation completed without an expected failure.
+ public required bool Success { get; init; }
+
+ ///
+ /// The operation's output value. Non-null when Success = true.
+ /// The '?' after T makes this property nullable (can hold null).
+ ///
+ public T? Value { get; init; }
+
+ ///
+ /// Machine-readable error code. Non-null when Success = false.
+ /// Convention: SCREAMING_SNAKE_CASE. Examples: "USER_NOT_FOUND", "INVALID_PASSWORD"
+ /// Handlers map these to IServerMessage error responses sent to the client.
+ ///
+ public string? ErrorCode { get; init; }
+
+ ///
+ /// Human-readable error description. Non-null when Success = false.
+ /// May be sent to the client in development; use generic messages in production.
+ ///
+ public string? ErrorMessage { get; init; }
+
+ // ── Factory methods ────────────────────────────────────────────────────────
+
+ /// Returns a successful result containing the given value.
+ public static ServiceResult Ok(T value) =>
+ new() { Success = true, Value = value };
+
+ /// Returns a failed result with the given error code and message.
+ public static ServiceResult Fail(string errorCode, string message) =>
+ new() { Success = false, ErrorCode = errorCode, ErrorMessage = message };
+}
diff --git a/Server/src/SOR.Shared/Nats/NatsSubjects.cs b/Server/src/SOR.Shared/Nats/NatsSubjects.cs
new file mode 100644
index 0000000..a703156
--- /dev/null
+++ b/Server/src/SOR.Shared/Nats/NatsSubjects.cs
@@ -0,0 +1,76 @@
+namespace SOR.Shared.Nats;
+
+///
+/// All NATS subject names used for inter-service async pub/sub, in one place.
+///
+/// Same rationale as RedisKeys: centralizing prevents typos, collisions, and makes
+/// the full event catalog visible at a glance. A rename touches one file.
+///
+/// Naming convention: "sor.{service}.{event}" — all lowercase, dot-separated.
+/// This matches NATS subject hierarchy conventions and allows wildcard subscriptions
+/// like "sor.game.*" (all game events) or "sor.>" (all SOR events, for a logging service).
+///
+/// Subjects defined here are for NATS fan-out (IEventBus).
+/// Redis Pub/Sub keys (IClientPush) are in RedisKeys.
+///
+public static class NatsSubjects
+{
+ // ── Game ──────────────────────────────────────────────────────────────────
+
+ ///
+ /// Published by Game service when a match ends.
+ /// Consumers: Leaderboard (update MMR), Collection (grant rewards), Chat (notify channel)
+ /// Payload: GameEndedEvent { GameId, WinnerId, LoserId, DurationSeconds, EndedAt }
+ ///
+ public const string GameEnded = "sor.game.ended";
+
+ ///
+ /// Published by Game service when a match is about to start (all players connected).
+ /// Consumers: Chat (create match channel)
+ /// Payload: GameStartedEvent { GameId, PlayerIds[], StartedAt }
+ ///
+ public const string GameStarted = "sor.game.started";
+
+ // ── Bazaar / Economy ──────────────────────────────────────────────────────
+
+ ///
+ /// Published by Bazaar service when a purchase completes successfully.
+ /// Consumers: Collection (grant purchased cards/packs)
+ /// Payload: PurchaseCompletedEvent { UserId, ItemId, ItemType, PricePaid, CurrencyType }
+ ///
+ public const string BazaarPurchaseCompleted = "sor.bazaar.purchase.completed";
+
+ // ── Collection ────────────────────────────────────────────────────────────
+
+ ///
+ /// Published by Collection service when a card is added to a user's collection.
+ /// Consumers: any service that tracks collection state
+ /// Payload: CardGrantedEvent { UserId, CardId, Source, GrantedAt }
+ ///
+ public const string CollectionCardGranted = "sor.collection.card.granted";
+
+ // ── Leaderboard ───────────────────────────────────────────────────────────
+
+ ///
+ /// Published by Leaderboard service after MMR is updated for a match.
+ /// Consumers: Gateway (push rating change notification to affected users)
+ /// Payload: MatchRatedEvent { GameId, WinnerId, WinnerNewMmr, LoserId, LoserNewMmr }
+ ///
+ public const string LeaderboardMatchRated = "sor.leaderboard.match.rated";
+
+ // ── Admin ─────────────────────────────────────────────────────────────────
+
+ ///
+ /// Published by Admin service when a player is banned.
+ /// Consumers: Gateway (disconnect the player immediately), Auth (revoke all sessions)
+ /// Payload: PlayerBannedEvent { UserId, BannedBy, Reason, ExpiresAt (null = permanent) }
+ ///
+ public const string AdminPlayerBanned = "sor.admin.player.banned";
+
+ ///
+ /// Published by Admin service when a feature flag changes.
+ /// Consumers: any service that caches feature flags in memory
+ /// Payload: FeatureFlagChangedEvent { Flag, Enabled }
+ ///
+ public const string AdminFeatureFlagChanged = "sor.admin.featureflag.changed";
+}
diff --git a/Server/src/SOR.Shared/Networking/RawClientMessage.cs b/Server/src/SOR.Shared/Networking/RawClientMessage.cs
new file mode 100644
index 0000000..85a1a79
--- /dev/null
+++ b/Server/src/SOR.Shared/Networking/RawClientMessage.cs
@@ -0,0 +1,45 @@
+namespace SOR.Shared.Networking;
+
+using SOR.Networking.Abstractions.Messaging;
+
+///
+/// Concrete implementation of IClientMessage.
+///
+/// Lifecycle:
+/// 1. The transport (WebSocketClientConnection.ReceiveAsync) produces raw bytes
+/// and creates a pre-parse RawClientMessage with only Payload set.
+/// 2. IMessageSerializer.Deserialize(wireBytes) parses the envelope and returns
+/// a fully populated RawClientMessage with Type, Seq, and inner Payload.
+/// 3. The dispatcher delivers it to the correct IMessageHandler.
+/// 4. The handler calls IMessageSerializer.DeserializePayload{T}(message.Payload)
+/// to convert the inner payload bytes into its specific request record.
+///
+/// Why separate pre-parse and post-parse?
+/// The transport reads bytes without knowing the serialization format.
+/// The serializer knows the format but not the transport.
+/// Keeping them separate respects the single-responsibility principle and
+/// makes swapping either independently possible.
+///
+public sealed class RawClientMessage : IClientMessage
+{
+ ///
+ public string Type { get; }
+
+ ///
+ public int Seq { get; }
+
+ ///
+ public ReadOnlyMemory Payload { get; }
+
+ ///
+ /// Post-parse constructor: created by IMessageSerializer.Deserialize()
+ /// after the envelope fields have been extracted from wire bytes.
+ /// Type, Seq, and the inner payload bytes are all known at this point.
+ ///
+ public RawClientMessage(string type, int seq, ReadOnlyMemory payload)
+ {
+ Type = type;
+ Seq = seq;
+ Payload = payload;
+ }
+}
diff --git a/Server/src/SOR.Shared/Networking/ServerMessage.cs b/Server/src/SOR.Shared/Networking/ServerMessage.cs
new file mode 100644
index 0000000..95a8b56
--- /dev/null
+++ b/Server/src/SOR.Shared/Networking/ServerMessage.cs
@@ -0,0 +1,57 @@
+namespace SOR.Shared.Networking;
+
+using SOR.Networking.Abstractions.Messaging;
+
+///
+/// Standard concrete implementation of IServerMessage.
+///
+/// Handlers and services construct ServerMessage instances to send to clients.
+/// The static factory methods (Reply, Push, Error) cover the three common cases
+/// and provide a readable, self-documenting call site.
+///
+/// Examples:
+/// return ServerMessage.Reply("auth.hello.ack", req.Seq, new { UserId = "..." });
+/// return ServerMessage.Error(req.Seq, "DECK_TOO_LARGE", "Max 40 cards per deck.");
+/// await _push.PushAsync(userId, ServerMessage.Push("game.state_update", gameState));
+///
+/// 'sealed record' generates constructor, equality, ToString() automatically.
+/// The primary constructor syntax '(string Type, int Ref, object? Payload)'
+/// creates the three properties and a constructor in one line.
+///
+public sealed record ServerMessage(string Type, int Ref, object? Payload) : IServerMessage
+{
+ // ── Factory methods ────────────────────────────────────────────────────────
+
+ ///
+ /// Creates a direct reply to a client request.
+ /// Sets Ref = refSeq so the client can match this response to its request.
+ ///
+ /// Use when:
+ /// - A client sent a message and expects an immediate acknowledgement
+ /// - The operation completed synchronously within the handler
+ ///
+ public static ServerMessage Reply(string type, int refSeq, object? payload = null) =>
+ new(type, refSeq, payload);
+
+ ///
+ /// Creates an unsolicited server-initiated push event.
+ /// Sets Ref = 0 (no corresponding client request).
+ ///
+ /// Use when:
+ /// - The server is pushing a state change the client did not request
+ /// - Examples: opponent played a card, a game invite arrived, MMR updated
+ ///
+ public static ServerMessage Push(string type, object? payload = null) =>
+ new(type, 0, payload);
+
+ ///
+ /// Creates a structured error response.
+ /// Sets Type = "error", Ref = refSeq, Payload = { errorCode, message }.
+ ///
+ /// Use when:
+ /// - A client request failed for an expected reason (validation, not found, banned)
+ /// - The client needs a machine-readable errorCode to display the right UI state
+ ///
+ public static ServerMessage Error(int refSeq, string errorCode, string message) =>
+ new("error", refSeq, new { errorCode, message });
+}
diff --git a/Server/src/SOR.Shared/Redis/RedisKeys.cs b/Server/src/SOR.Shared/Redis/RedisKeys.cs
new file mode 100644
index 0000000..dc0a2e1
--- /dev/null
+++ b/Server/src/SOR.Shared/Redis/RedisKeys.cs
@@ -0,0 +1,71 @@
+namespace SOR.Shared.Redis;
+
+///
+/// All Redis key name patterns used across the entire server, in one place.
+///
+/// Why centralize here?
+/// - Prevents typos (a mistyped key silently produces cache misses or data loss)
+/// - Prevents key collisions between services
+/// - Makes the full set of Redis keys auditable at a glance
+/// - A rename touches one file, not a scattered grep
+///
+/// Naming convention: "{scope}:{identifier}"
+/// All keys are lowercase, colon-separated.
+///
+/// 'static class' means this class cannot be instantiated — it only contains static members.
+///
+public static class RedisKeys
+{
+ // ── Auth / Sessions ────────────────────────────────────────────────────────
+
+ ///
+ /// Opaque session token → serialized session data (userId, displayName, createdAt).
+ /// TTL set to Auth:SessionTtlMinutes on creation; refreshed on each valid request.
+ /// Example: "session:a1b2c3d4e5f6..."
+ ///
+ public static string Session(string token) => $"session:{token}";
+
+ ///
+ /// Set of all active session tokens for a user.
+ /// Used to enumerate and revoke all sessions when a user is banned or changes password.
+ /// Example: "user_sessions:550e8400-e29b-41d4-a716-446655440000"
+ ///
+ public static string UserSessions(string userId) => $"user_sessions:{userId}";
+
+ // ── Gateway / Push Delivery ────────────────────────────────────────────────
+
+ ///
+ /// Redis Pub/Sub channel for pushing messages to a specific user's connected client.
+ /// The Gateway subscribes to this channel for each authenticated connection.
+ /// Other services publish to it via IClientPush.PushAsync().
+ /// Example: "push:550e8400-e29b-41d4-a716-446655440000"
+ ///
+ public static string ClientPushChannel(string userId) => $"push:{userId}";
+
+ // ── Live Game State ────────────────────────────────────────────────────────
+
+ ///
+ /// Serialized active game state. Stored in Redis for fast reads; Game service
+ /// is the only writer. Keyed by game ID (a GUID assigned at game creation).
+ /// Example: "game:active:7c9e6679-7425-40de-944b-e07fc1f90ae7"
+ ///
+ public static string ActiveGame(string gameId) => $"game:active:{gameId}";
+
+ // ── Leaderboard ───────────────────────────────────────────────────────────
+
+ ///
+ /// Redis Sorted Set for the ranked leaderboard.
+ /// Members: userId strings. Score: current MMR (Matchmaking Rating).
+ /// ZADD / ZINCRBY / ZRANK operations run in O(log N) time.
+ ///
+ public static string LeaderboardRanked() => "leaderboard:ranked";
+
+ // ── Feature Flags ─────────────────────────────────────────────────────────
+
+ ///
+ /// Runtime feature flag value. "1" = enabled, "0" = disabled.
+ /// Set by Admin service; read by any service via Redis GET.
+ /// Example: "config:flag:ranked_queue_open"
+ ///
+ public static string FeatureFlag(string flag) => $"config:flag:{flag}";
+}
diff --git a/Server/src/SOR.Shared/SOR.Shared.csproj b/Server/src/SOR.Shared/SOR.Shared.csproj
new file mode 100644
index 0000000..854eae7
--- /dev/null
+++ b/Server/src/SOR.Shared/SOR.Shared.csproj
@@ -0,0 +1,20 @@
+
+
+ SOR.Shared
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Server/src/SOR.Shared/Serialization/SystemTextJsonSerializer.cs b/Server/src/SOR.Shared/Serialization/SystemTextJsonSerializer.cs
new file mode 100644
index 0000000..290d7a7
--- /dev/null
+++ b/Server/src/SOR.Shared/Serialization/SystemTextJsonSerializer.cs
@@ -0,0 +1,114 @@
+namespace SOR.Shared.Serialization;
+
+using System.Text.Json;
+using SOR.Networking.Abstractions.Messaging;
+using SOR.Shared.Networking;
+
+///
+/// IMessageSerializer implementation using System.Text.Json.
+///
+/// Wire format — Client to Server:
+/// { "type": "chat.send", "seq": 7, "payload": { "message": "Hello" } }
+///
+/// Wire format — Server to Client (reply, ref = client seq):
+/// { "type": "chat.send.ack", "ref": 7, "payload": { "messageId": "..." } }
+///
+/// Wire format — Server to Client (unsolicited push, ref = 0):
+/// { "type": "game.state_update", "ref": 0, "payload": { ... } }
+///
+/// To swap to MessagePack:
+/// 1. Create MessagePackSerializer implementing IMessageSerializer
+/// 2. In SOR.Shared.ServiceRegistration: replace AddSingleton{IMessageSerializer, SystemTextJsonSerializer}
+/// with AddSingleton{IMessageSerializer, MessagePackSerializer}
+/// 3. Update client to send/receive MessagePack frames instead of JSON
+/// 4. Nothing else changes — all handlers, all services, all tests are unaffected
+///
+/// Lifetime: Singleton. This class is thread-safe (no mutable state; JsonSerializerOptions
+/// is immutable after construction).
+///
+public sealed class SystemTextJsonSerializer : IMessageSerializer
+{
+ ///
+ /// Shared options instance. Created once; reuse avoids repeated allocation.
+ /// 'static readonly' = initialized once at class load time, shared across all instances.
+ ///
+ private static readonly JsonSerializerOptions Options = new()
+ {
+ // camelCase property names: C# 'SessionToken' → JSON 'sessionToken'
+ PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
+
+ // Case-insensitive property matching for deserialization:
+ // JSON "SessionToken" and "sessionToken" both map to C# 'SessionToken'
+ PropertyNameCaseInsensitive = true,
+
+ // Compact output — no indentation in production
+ WriteIndented = false,
+ };
+
+ ///
+ ///
+ /// Parses the JSON envelope and extracts the type, seq, and inner payload.
+ /// The 'payload' JSON object is re-serialized to bytes so downstream code
+ /// can deserialize it independently into the handler-specific type.
+ ///
+ public IClientMessage Deserialize(ReadOnlySpan wireBytes)
+ {
+ // JsonDocument provides a DOM view of JSON bytes without full deserialization.
+ // It is more efficient than JsonSerializer.Deserialize when we only need
+ // a few fields and want to defer inner payload deserialization.
+ // JsonDocument.Parse does not have a ReadOnlySpan{byte} overload in .NET 8.
+ // .ToArray() copies the span into a byte[] — minimal overhead for the parse path.
+ using var doc = JsonDocument.Parse(wireBytes.ToArray());
+ var root = doc.RootElement;
+
+ // Extract envelope fields. GetString() returns null if the property is missing
+ // or not a string — the ?? throw gives a clear error instead of a null ref later.
+ var type = root.GetProperty("type").GetString()
+ ?? throw new JsonException("Client message missing required 'type' field.");
+
+ // TryGetProperty returns false (not an exception) if the field is absent.
+ // Seq defaults to 0 if not provided — older clients or fire-and-forget messages.
+ var seq = root.TryGetProperty("seq", out var seqEl) ? seqEl.GetInt32() : 0;
+
+ // Re-serialize the payload sub-object to bytes for handler deserialization.
+ // If no payload field exists, use empty bytes (handler will receive default(T)).
+ ReadOnlyMemory payloadBytes = ReadOnlyMemory.Empty;
+ if (root.TryGetProperty("payload", out var payloadEl))
+ {
+ // SerializeToUtf8Bytes allocates a new byte[] — this is fine since it
+ // happens once per message and the bytes are owned by RawClientMessage.
+ payloadBytes = JsonSerializer.SerializeToUtf8Bytes(payloadEl, Options);
+ }
+
+ return new RawClientMessage(type, seq, payloadBytes);
+ }
+
+ ///
+ ///
+ /// Serializes the full message envelope (type + ref + payload) to JSON bytes.
+ ///
+ public ReadOnlyMemory Serialize(IServerMessage message)
+ {
+ // Anonymous type: a lightweight C# feature that creates a temporary class
+ // with named properties without explicitly defining a class.
+ // The '@' prefix on 'ref' is needed because 'ref' is a C# keyword.
+ var envelope = new
+ {
+ type = message.Type,
+ @ref = message.Ref,
+ payload = message.Payload,
+ };
+
+ return JsonSerializer.SerializeToUtf8Bytes(envelope, Options);
+ }
+
+ ///
+ public T DeserializePayload(ReadOnlyMemory payload) where T : notnull
+ {
+ // Span is a stack-allocated view of the memory — no copy.
+ return JsonSerializer.Deserialize(payload.Span, Options)
+ ?? throw new JsonException(
+ $"Payload deserialized to null for type {typeof(T).Name}. " +
+ "Ensure the payload JSON is not 'null'.");
+ }
+}
diff --git a/Server/src/SOR.Shared/ServiceRegistration.cs b/Server/src/SOR.Shared/ServiceRegistration.cs
new file mode 100644
index 0000000..41b56d0
--- /dev/null
+++ b/Server/src/SOR.Shared/ServiceRegistration.cs
@@ -0,0 +1,29 @@
+namespace SOR.Shared;
+
+using Microsoft.Extensions.DependencyInjection;
+using SOR.Networking.Abstractions.Messaging;
+using SOR.Shared.Serialization;
+
+///
+/// Registers SOR.Shared services into the DI container.
+/// Called once in SOR.Host.Program.cs before any other service registration.
+///
+public static class ServiceRegistration
+{
+ ///
+ /// Registers all shared infrastructure services:
+ /// - IMessageSerializer (SystemTextJsonSerializer by default)
+ ///
+ /// To swap the serializer to MessagePack, replace this registration in Program.cs:
+ /// builder.Services.AddSingleton{IMessageSerializer, MessagePackSerializer}()
+ /// after calling AddSharedServices(), which will override the default.
+ ///
+ public static IServiceCollection AddSharedServices(this IServiceCollection services)
+ {
+ // Singleton: one serializer instance for the process lifetime.
+ // SystemTextJsonSerializer has no mutable state — safe to share across threads.
+ services.AddSingleton();
+
+ return services;
+ }
+}