Path: redb-route/redb.Route.Controllers/GrpcControllerDispatcher.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Controllers/GrpcControllerDispatcher.cs
----
using System.Collections.Frozen;
using System.Reflection;
using System.Text.Json;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
namespace redb.Route.Controllers;
///
/// Dispatches gRPC requests to controller methods by method name.
///
/// The method name is read from dispatch-method header (a regular header
/// that flows through gRPC metadata without being filtered by producer/consumer).
/// Body is treated as JSON — single value or array of positional arguments.
///
///
/// Usage: the client (or middleware) sets exchange.In.Headers["dispatch-method"] = "MethodName"
/// before sending via . Qualified names like
/// "Controller.Method" are supported for multi-controller dispatch.
///
///
public sealed class GrpcControllerDispatcher : IProcessor
{
private readonly FrozenDictionary _methods;
private readonly IRouteContext _context;
private readonly ILogger? _logger;
/// Header key for the dispatch method name (flows through gRPC metadata unfiltered).
internal const string MethodHeader = "dispatch-method";
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// Route context for controller instantiation.
/// One or more controller types to register.
public GrpcControllerDispatcher(IRouteContext context, params Type[] controllerTypes)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
if (controllerTypes is null || controllerTypes.Length == 0)
throw new ArgumentException("At least one controller type is required.", nameof(controllerTypes));
_methods = BuildMethodMap(controllerTypes);
_logger = ControllerErrorReporting.CreateLogger(context);
}
///
public async Task Process(IExchange exchange, CancellationToken ct = default)
{
var methodName = exchange.In.GetHeader(MethodHeader);
if (string.IsNullOrEmpty(methodName))
{
WriteError(exchange, 400, "BadRequest", $"Missing required header: {MethodHeader}");
return;
}
if (!_methods.TryGetValue(methodName, out var entry))
{
WriteError(exchange, 404, "NotFound", $"Method '{methodName}' not found on registered controllers");
return;
}
// Binding failures are the caller's 400, action failures are our 500 — the boundary is
// the resolution step, same as the HTTP dispatcher.
object?[] parameters;
try
{
// gRPC body is byte[] — deserialize from JSON for positional binding
var body = DeserializeBody(exchange.In.Body);
parameters = ParameterResolver.ResolvePositional(entry.Method, body, ct);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
WriteError(exchange, 400, ControllerErrorReporting.BadRequestCode,
ControllerErrorReporting.ReportBadRequest(_logger, ex, exchange, methodName));
return;
}
try
{
var controller = (RedbController)Activator.CreateInstance(entry.ControllerType)!;
controller.Context = _context;
controller.Exchange = exchange;
// The action's own exception, one TargetInvocationException removed (see ActionInvoker).
var result = await ActionInvoker.InvokeAsync(entry.Method, controller, parameters);
WriteResult(exchange, result);
}
catch (Exception ex)
{
WriteError(exchange, 500, ControllerErrorReporting.ErrorCode,
ControllerErrorReporting.Report(_logger, ex, exchange, methodName));
}
}
///
/// Deserializes gRPC body. The consumer stores body as byte[].
/// If the JSON is an array, unpacks to object[] for positional binding.
///
private static object? DeserializeBody(object? body)
{
if (body is null) return null;
if (body is byte[] bytes)
{
if (bytes.Length == 0) return null;
var element = JsonSerializer.Deserialize(bytes, JsonOptions);
return UnpackJsonElement(element);
}
// Already deserialized (e.g., in unit tests)
return body;
}
private static object? UnpackJsonElement(JsonElement element)
{
if (element.ValueKind == JsonValueKind.Array)
{
var items = new object?[element.GetArrayLength()];
for (var i = 0; i < items.Length; i++)
items[i] = element[i];
return items;
}
return element;
}
private static FrozenDictionary BuildMethodMap(Type[] controllerTypes)
{
var map = new Dictionary(StringComparer.OrdinalIgnoreCase);
foreach (var type in controllerTypes)
{
if (!type.IsSubclassOf(typeof(RedbController)))
throw new ArgumentException($"Type '{type.Name}' does not inherit from RedbController.");
var controllerName = type.Name.EndsWith("Controller", StringComparison.Ordinal)
? type.Name[..^10]
: type.Name;
foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
var entry = new MethodEntry(type, method);
// [GrpcMethod] pins the wire name so renaming the C# method is not a breaking change for
// callers. Same role SoapOperationAttribute plays for SOAP operations.
var name = method.GetCustomAttribute()?.Method ?? method.Name;
// Qualified name: "Modules.GetAll" — always registered, last-write wins per controller
map[$"{controllerName}.{name}"] = entry;
// Short name: "GetAll" — only if no collision across controllers
map.TryAdd(name, entry);
}
}
return map.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);
}
private static void WriteResult(IExchange exchange, object? result)
{
// An Out that already exists was written by the action (or a step before the dispatcher): that is the reply,
// with its own body and status. Only a clone the dispatcher makes here carries the request body.
var createdHere = exchange.Out is null;
exchange.Out ??= exchange.In.Clone();
if (result is null)
{
if (createdHere)
exchange.Out.Body = null; // our own clone of the request is not the reply
if (!exchange.Out.Headers.ContainsKey("status.code"))
exchange.Out.setHeader("status.code", 204);
return;
}
// Serialize result to JSON bytes for gRPC response
if (result is not byte[] and not string)
result = JsonSerializer.SerializeToUtf8Bytes(result, JsonOptions);
exchange.Out.Body = result;
exchange.Out.setHeader("status.code", 200);
}
private static void WriteError(IExchange exchange, int statusCode, string error, string message)
{
exchange.Out ??= exchange.In.Clone();
exchange.Out.Body = JsonSerializer.SerializeToUtf8Bytes(
new ControllerErrorResponse
{
Error = error,
Message = message,
StatusCode = statusCode
}, JsonOptions);
exchange.Out.setHeader("status.code", statusCode);
}
internal sealed record MethodEntry(Type ControllerType, MethodInfo Method);
}