diff --git a/Server/src/SOR.Gateway/ConnectionLoop.cs b/Server/src/SOR.Gateway/ConnectionLoop.cs index a5cdd66..8c53b42 100644 --- a/Server/src/SOR.Gateway/ConnectionLoop.cs +++ b/Server/src/SOR.Gateway/ConnectionLoop.cs @@ -234,18 +234,6 @@ public sealed class ConnectionLoop continue; } - 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; - } - IServerMessage? response; try { diff --git a/Server/src/SOR.Gateway/Dispatch/MessageDispatcher.cs b/Server/src/SOR.Gateway/Dispatch/MessageDispatcher.cs index c29123a..ddd659c 100644 --- a/Server/src/SOR.Gateway/Dispatch/MessageDispatcher.cs +++ b/Server/src/SOR.Gateway/Dispatch/MessageDispatcher.cs @@ -1,60 +1,50 @@ namespace SOR.Gateway.Dispatch; +using System.Linq; +using System.Text.Json; +using global::NATS.Client.Core; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; using SOR.Networking.Abstractions.Messaging; using SOR.Networking.Abstractions.Transport; +using SOR.Shared.Networking; /// -/// 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. +/// Gateway message dispatcher. +/// Resolves co-located handlers locally and falls back to NATS request/reply for +/// worker-owned handlers that are not loaded into the Gateway process. /// 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 IReadOnlyDictionary _localHandlerTypes; + private readonly IServiceScopeFactory _scopeFactory; + private readonly INatsConnection _nats; + private readonly GatewayOptions _options; 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, + IServiceScopeFactory scopeFactory, + INatsConnection nats, + IOptions options, ILogger logger) { + _scopeFactory = scopeFactory; + _nats = nats; + _options = options.Value; _logger = logger; - // Build the dispatch table. Dictionary for O(1) type lookup per message. - var table = new Dictionary( - StringComparer.OrdinalIgnoreCase); + var table = new Dictionary(StringComparer.OrdinalIgnoreCase); + using var scope = _scopeFactory.CreateScope(); + var handlers = scope.ServiceProvider.GetServices(); foreach (var handler in handlers) { - // Fail fast on duplicates — this is always a configuration bug. - if (!table.TryAdd(handler.MessageType, handler)) + if (!table.TryAdd(handler.MessageType, handler.GetType())) { throw new InvalidOperationException( $"Duplicate IMessageHandler registered for type '{handler.MessageType}'. " + - $"Existing: {table[handler.MessageType].GetType().Name}, " + + $"Existing: {table[handler.MessageType].Name}, " + $"Duplicate: {handler.GetType().Name}. " + "Each message type may have only one handler."); } @@ -63,46 +53,143 @@ public sealed class MessageDispatcher : IMessageDispatcher handler.MessageType, handler.GetType().Name); } - _handlers = table; + _localHandlerTypes = table; _logger.LogInformation( - "MessageDispatcher initialized with {Count} handler(s): [{Types}]", - _handlers.Count, - string.Join(", ", _handlers.Keys)); + "MessageDispatcher initialized with {Count} local handler(s): [{Types}]", + _localHandlerTypes.Count, + string.Join(", ", _localHandlerTypes.Keys)); } /// public bool HasHandler(string messageType) => - _handlers.ContainsKey(messageType); + _localHandlerTypes.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)) + if (_localHandlerTypes.TryGetValue(message.Type, out var handlerType)) + return await DispatchLocalAsync(handlerType, message, connection, cancellationToken); + + return await DispatchRemoteAsync(message, connection, cancellationToken); + } + + private async Task DispatchLocalAsync( + Type handlerType, + IClientMessage message, + AuthenticatedConnection connection, + CancellationToken cancellationToken) + { + using var scope = _scopeFactory.CreateScope(); + var handler = scope.ServiceProvider + .GetServices() + .FirstOrDefault(candidate => candidate.GetType() == handlerType); + + if (handler is null) { - // 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; + "Handler type {HandlerType} for '{Type}' was registered but could not be resolved", + handlerType.Name, message.Type); + return ServerMessage.Error(message.Seq, "INTERNAL_ERROR", "Message handler could not be resolved."); } _logger.LogDebug( - "Dispatching '{Type}' seq={Seq} for user {UserId}", + "Dispatching '{Type}' locally 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); } + + private async Task DispatchRemoteAsync( + IClientMessage message, + AuthenticatedConnection connection, + CancellationToken cancellationToken) + { + var subject = GetRpcSubject(message.Type); + using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeoutCts.CancelAfter(_options.RemoteDispatchTimeoutMs); + + try + { + _logger.LogDebug( + "Dispatching '{Type}' remotely on {Subject} seq={Seq} for user {UserId}", + message.Type, subject, message.Seq, connection.UserId); + + var reply = await _nats.RequestAsync( + subject, + new RemoteDispatchRequest( + message.Type, + message.Seq, + message.Payload.ToArray(), + connection.UserId, + connection.DisplayName, + connection.SessionToken), + null, + null, + null, + null, + new NatsSubOpts + { + Timeout = TimeSpan.FromMilliseconds(_options.RemoteDispatchTimeoutMs), + ThrowIfNoResponders = true + }, + timeoutCts.Token); + + var remote = reply.Data; + if (remote is null) + { + _logger.LogWarning( + "Remote dispatch for '{Type}' returned an empty reply", + message.Type); + return ServerMessage.Error(message.Seq, "INTERNAL_ERROR", "Internal service returned an empty reply."); + } + + if (!remote.Handled) + { + return ServerMessage.Error( + message.Seq, + remote.ErrorCode ?? "UNKNOWN_TYPE", + remote.ErrorMessage ?? $"No handler registered for message type '{message.Type}'."); + } + + if (!remote.HasResponse) + return null; + + var payload = remote.ResponsePayload is { } element && + element.ValueKind is not JsonValueKind.Undefined and not JsonValueKind.Null + ? element + : null; + + return new ServerMessage( + remote.ResponseType ?? "error", + remote.ResponseRef, + payload); + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + _logger.LogWarning( + "Remote dispatch timed out for '{Type}' after {TimeoutMs}ms", + message.Type, _options.RemoteDispatchTimeoutMs); + return ServerMessage.Error( + message.Seq, + "SERVICE_UNAVAILABLE", + $"No internal service replied for message type '{message.Type}'."); + } + catch (Exception ex) + { + _logger.LogWarning(ex, + "Remote dispatch failed for '{Type}' on {Subject}", + message.Type, subject); + return ServerMessage.Error( + message.Seq, + "SERVICE_UNAVAILABLE", + $"No internal service is available for message type '{message.Type}'."); + } + } + + private static string GetRpcSubject(string messageType) => + $"sor.rpc.{messageType.ToLowerInvariant()}"; } diff --git a/Server/src/SOR.Gateway/GatewayOptions.cs b/Server/src/SOR.Gateway/GatewayOptions.cs index c61e283..8c2500b 100644 --- a/Server/src/SOR.Gateway/GatewayOptions.cs +++ b/Server/src/SOR.Gateway/GatewayOptions.cs @@ -8,7 +8,8 @@ namespace SOR.Gateway; /// { /// "Gateway": { /// "AuthTimeoutMs": 10000, -/// "MaxMessagesPerSecond": 20 +/// "MaxMessagesPerSecond": 20, +/// "RemoteDispatchTimeoutMs": 3000 /// } /// } /// @@ -37,4 +38,11 @@ public sealed class GatewayOptions /// This option is defined now so configuration is in place before enforcement is added. /// public int MaxMessagesPerSecond { get; set; } = 20; + + /// + /// Maximum time the Gateway waits for an internal worker to reply to a relayed + /// client message before returning an error to the client. + /// Default: 3 seconds. + /// + public int RemoteDispatchTimeoutMs { get; set; } = 3_000; } diff --git a/Server/src/SOR.Gateway/SOR.Gateway.csproj b/Server/src/SOR.Gateway/SOR.Gateway.csproj index db3a7ae..f9aa3b4 100644 --- a/Server/src/SOR.Gateway/SOR.Gateway.csproj +++ b/Server/src/SOR.Gateway/SOR.Gateway.csproj @@ -10,6 +10,9 @@ + + + diff --git a/Server/src/SOR.Networking.Nats/NatsMessageRpcResponder.cs b/Server/src/SOR.Networking.Nats/NatsMessageRpcResponder.cs new file mode 100644 index 0000000..be11e48 --- /dev/null +++ b/Server/src/SOR.Networking.Nats/NatsMessageRpcResponder.cs @@ -0,0 +1,245 @@ +namespace SOR.Networking.Nats; + +using System.Linq; +using System.Text.Json; +using global::NATS.Client.Core; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using SOR.Networking.Abstractions.Messaging; +using SOR.Networking.Abstractions.Transport; +using SOR.Shared.Networking; + +/// +/// Exposes locally registered IMessageHandler implementations over NATS request/reply +/// so the Gateway can relay client messages to worker processes. +/// +public sealed class NatsMessageRpcResponder : IHostedService +{ + private readonly IServiceScopeFactory _scopeFactory; + private readonly INatsConnection _nats; + private readonly ILogger _logger; + private readonly List _listenerTasks = []; + private CancellationTokenSource? _stoppingCts; + + public NatsMessageRpcResponder( + IServiceScopeFactory scopeFactory, + INatsConnection nats, + ILogger logger) + { + _scopeFactory = scopeFactory; + _nats = nats; + _logger = logger; + } + + public Task StartAsync(CancellationToken cancellationToken) + { + using var scope = _scopeFactory.CreateScope(); + var handlers = scope.ServiceProvider.GetServices(); + var handlerTypes = new Dictionary(StringComparer.OrdinalIgnoreCase); + + foreach (var handler in handlers) + { + if (!handlerTypes.TryAdd(handler.MessageType, handler.GetType())) + { + throw new InvalidOperationException( + $"Duplicate IMessageHandler registered for type '{handler.MessageType}'. " + + $"Existing: {handlerTypes[handler.MessageType].Name}, " + + $"Duplicate: {handler.GetType().Name}."); + } + } + + if (handlerTypes.Count == 0) + { + _logger.LogDebug("NATS RPC responder found no local message handlers; not starting listeners."); + return Task.CompletedTask; + } + + _stoppingCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + + foreach (var pair in handlerTypes) + { + var messageType = pair.Key; + var handlerType = pair.Value; + _listenerTasks.Add(Task.Run( + () => ListenAsync(messageType, handlerType, _stoppingCts.Token), + CancellationToken.None)); + } + + _logger.LogInformation( + "NATS RPC responder started for {Count} handler(s): [{Types}]", + handlerTypes.Count, + string.Join(", ", handlerTypes.Keys)); + + return Task.CompletedTask; + } + + public async Task StopAsync(CancellationToken cancellationToken) + { + if (_stoppingCts is null) + return; + + _stoppingCts.Cancel(); + + try + { + await Task.WhenAll(_listenerTasks).WaitAsync(cancellationToken); + } + catch (OperationCanceledException) + { + } + finally + { + _stoppingCts.Dispose(); + _stoppingCts = null; + _listenerTasks.Clear(); + } + } + + private async Task ListenAsync( + string messageType, + Type handlerType, + CancellationToken cancellationToken) + { + var subject = GetRpcSubject(messageType); + var queueGroup = GetRpcQueueGroup(messageType); + + try + { + await foreach (var msg in _nats + .SubscribeAsync(subject, queueGroup, cancellationToken: cancellationToken) + .WithCancellation(cancellationToken)) + { + if (msg.Data is null) + continue; + + if (string.IsNullOrWhiteSpace(msg.ReplyTo)) + { + _logger.LogWarning( + "Received RPC request for '{Type}' without a reply subject", + messageType); + continue; + } + + var response = await DispatchAsync(handlerType, msg.Data, cancellationToken); + await _nats.PublishAsync(msg.ReplyTo, response, cancellationToken: cancellationToken); + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + } + catch (Exception ex) + { + _logger.LogError(ex, + "NATS RPC listener for '{Type}' on {Subject} stopped unexpectedly", + messageType, subject); + } + } + + private async Task DispatchAsync( + Type handlerType, + RemoteDispatchRequest request, + CancellationToken cancellationToken) + { + using var scope = _scopeFactory.CreateScope(); + var handler = scope.ServiceProvider + .GetServices() + .FirstOrDefault(candidate => candidate.GetType() == handlerType); + + if (handler is null) + { + _logger.LogError( + "RPC handler type {HandlerType} for '{Type}' could not be resolved", + handlerType.Name, request.Type); + return new RemoteDispatchResponse( + false, + false, + null, + request.Seq, + null, + "INTERNAL_ERROR", + "Message handler could not be resolved."); + } + + try + { + var response = await handler.HandleAsync( + new RawClientMessage(request.Type, request.Seq, request.Payload), + new AuthenticatedConnection( + NullClientConnection.Instance, + request.UserId, + request.DisplayName, + request.SessionToken), + cancellationToken); + + if (response is null) + { + return new RemoteDispatchResponse( + true, + false, + null, + request.Seq, + null, + null, + null); + } + + return new RemoteDispatchResponse( + true, + true, + response.Type, + response.Ref, + SerializePayload(response.Payload), + null, + null); + } + catch (Exception ex) + { + _logger.LogError(ex, + "RPC handler for '{Type}' threw", + request.Type); + return new RemoteDispatchResponse( + true, + true, + "error", + request.Seq, + SerializePayload(new { errorCode = "INTERNAL_ERROR", message = "An internal error occurred." }), + null, + null); + } + } + + private static JsonElement? SerializePayload(object? payload) + { + if (payload is null) + return null; + + return JsonSerializer.SerializeToElement(payload, payload.GetType()); + } + + private static string GetRpcSubject(string messageType) => + $"sor.rpc.{messageType.ToLowerInvariant()}"; + + private static string GetRpcQueueGroup(string messageType) => + $"rpc.{messageType.ToLowerInvariant()}"; + + private sealed class NullClientConnection : IClientConnection + { + public static NullClientConnection Instance { get; } = new(); + + public string ConnectionId => "rpc"; + public string RemoteAddress => "nats-rpc"; + public bool IsConnected => false; + + public Task ReceiveAsync(CancellationToken cancellationToken) => + throw new NotSupportedException("RPC relay connections do not support receiving."); + + public ValueTask SendBytesAsync(ReadOnlyMemory bytes, CancellationToken cancellationToken) => + ValueTask.FromException(new NotSupportedException("RPC relay connections do not support direct sends.")); + + public Task CloseAsync(string reason, CancellationToken cancellationToken) => + Task.CompletedTask; + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } +} diff --git a/Server/src/SOR.Networking.Nats/ServiceRegistration.cs b/Server/src/SOR.Networking.Nats/ServiceRegistration.cs index 85fab5b..ee247e1 100644 --- a/Server/src/SOR.Networking.Nats/ServiceRegistration.cs +++ b/Server/src/SOR.Networking.Nats/ServiceRegistration.cs @@ -31,6 +31,7 @@ public static class ServiceRegistration // and ILogger{NatsEventBus} (provided by Serilog). // Both are already registered by the time this runs. services.AddSingleton(); + services.AddHostedService(); return services; } diff --git a/Server/src/SOR.Shared/Networking/RemoteDispatchContracts.cs b/Server/src/SOR.Shared/Networking/RemoteDispatchContracts.cs new file mode 100644 index 0000000..803e3b6 --- /dev/null +++ b/Server/src/SOR.Shared/Networking/RemoteDispatchContracts.cs @@ -0,0 +1,28 @@ +namespace SOR.Shared.Networking; + +using System.Text.Json; + +/// +/// NATS request payload used when the Gateway relays a client message to a worker. +/// +public sealed record RemoteDispatchRequest( + string Type, + int Seq, + byte[] Payload, + string UserId, + string DisplayName, + string SessionToken +); + +/// +/// NATS response payload returned by a worker after handling a relayed client message. +/// +public sealed record RemoteDispatchResponse( + bool Handled, + bool HasResponse, + string? ResponseType, + int ResponseRef, + JsonElement? ResponsePayload, + string? ErrorCode, + string? ErrorMessage +);