Changing packet dispatch, packets dying on gateway and not being relayed

This commit is contained in:
dingo
2026-02-28 15:10:49 -05:00
parent fd8fe950f8
commit 285d67374e
7 changed files with 427 additions and 67 deletions
-12
View File
@@ -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
{
@@ -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;
/// <summary>
/// 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.
/// </summary>
public sealed class MessageDispatcher : IMessageDispatcher
{
// IReadOnlyDictionary: immutable after construction.
// StringComparer.OrdinalIgnoreCase: "Chat.Send" and "chat.send" route to the same handler.
private readonly IReadOnlyDictionary<string, IMessageHandler> _handlers;
private readonly IReadOnlyDictionary<string, Type> _localHandlerTypes;
private readonly IServiceScopeFactory _scopeFactory;
private readonly INatsConnection _nats;
private readonly GatewayOptions _options;
private readonly ILogger<MessageDispatcher> _logger;
/// <summary>
/// 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.
/// </summary>
public MessageDispatcher(
IEnumerable<IMessageHandler> handlers,
IServiceScopeFactory scopeFactory,
INatsConnection nats,
IOptions<GatewayOptions> options,
ILogger<MessageDispatcher> 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<string, IMessageHandler>(
StringComparer.OrdinalIgnoreCase);
var table = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase);
using var scope = _scopeFactory.CreateScope();
var handlers = scope.ServiceProvider.GetServices<IMessageHandler>();
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));
}
/// <inheritdoc/>
public bool HasHandler(string messageType) =>
_handlers.ContainsKey(messageType);
_localHandlerTypes.ContainsKey(messageType);
/// <inheritdoc/>
/// <remarks>
/// 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.
/// </remarks>
public async Task<IServerMessage?> 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<IServerMessage?> DispatchLocalAsync(
Type handlerType,
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken cancellationToken)
{
using var scope = _scopeFactory.CreateScope();
var handler = scope.ServiceProvider
.GetServices<IMessageHandler>()
.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<IServerMessage?> 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<RemoteDispatchRequest, RemoteDispatchResponse>(
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()}";
}
+9 -1
View File
@@ -8,7 +8,8 @@ namespace SOR.Gateway;
/// {
/// "Gateway": {
/// "AuthTimeoutMs": 10000,
/// "MaxMessagesPerSecond": 20
/// "MaxMessagesPerSecond": 20,
/// "RemoteDispatchTimeoutMs": 3000
/// }
/// }
/// </summary>
@@ -37,4 +38,11 @@ public sealed class GatewayOptions
/// This option is defined now so configuration is in place before enforcement is added.
/// </summary>
public int MaxMessagesPerSecond { get; set; } = 20;
/// <summary>
/// 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.
/// </summary>
public int RemoteDispatchTimeoutMs { get; set; } = 3_000;
}
@@ -10,6 +10,9 @@
<!-- Redis for the push delivery read side (RedisPushSubscriber) -->
<PackageReference Include="StackExchange.Redis" />
<!-- NATS request/reply for Gateway → worker message relay -->
<PackageReference Include="NATS.Net" />
<!-- gRPC client factory for the Auth validator gRPC client -->
<PackageReference Include="Grpc.Net.ClientFactory" />
@@ -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;
/// <summary>
/// Exposes locally registered IMessageHandler implementations over NATS request/reply
/// so the Gateway can relay client messages to worker processes.
/// </summary>
public sealed class NatsMessageRpcResponder : IHostedService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly INatsConnection _nats;
private readonly ILogger<NatsMessageRpcResponder> _logger;
private readonly List<Task> _listenerTasks = [];
private CancellationTokenSource? _stoppingCts;
public NatsMessageRpcResponder(
IServiceScopeFactory scopeFactory,
INatsConnection nats,
ILogger<NatsMessageRpcResponder> logger)
{
_scopeFactory = scopeFactory;
_nats = nats;
_logger = logger;
}
public Task StartAsync(CancellationToken cancellationToken)
{
using var scope = _scopeFactory.CreateScope();
var handlers = scope.ServiceProvider.GetServices<IMessageHandler>();
var handlerTypes = new Dictionary<string, Type>(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<RemoteDispatchRequest>(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<RemoteDispatchResponse> DispatchAsync(
Type handlerType,
RemoteDispatchRequest request,
CancellationToken cancellationToken)
{
using var scope = _scopeFactory.CreateScope();
var handler = scope.ServiceProvider
.GetServices<IMessageHandler>()
.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<IClientMessage?> ReceiveAsync(CancellationToken cancellationToken) =>
throw new NotSupportedException("RPC relay connections do not support receiving.");
public ValueTask SendBytesAsync(ReadOnlyMemory<byte> 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;
}
}
@@ -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<IEventBus, NatsEventBus>();
services.AddHostedService<NatsMessageRpcResponder>();
return services;
}
@@ -0,0 +1,28 @@
namespace SOR.Shared.Networking;
using System.Text.Json;
/// <summary>
/// NATS request payload used when the Gateway relays a client message to a worker.
/// </summary>
public sealed record RemoteDispatchRequest(
string Type,
int Seq,
byte[] Payload,
string UserId,
string DisplayName,
string SessionToken
);
/// <summary>
/// NATS response payload returned by a worker after handling a relayed client message.
/// </summary>
public sealed record RemoteDispatchResponse(
bool Handled,
bool HasResponse,
string? ResponseType,
int ResponseRef,
JsonElement? ResponsePayload,
string? ErrorCode,
string? ErrorMessage
);