Path: redb-route/redb.Route.Grpc/GrpcConsumer.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.Grpc/GrpcConsumer.cs
----
using System.Diagnostics;
using System.Globalization;
using System.Net;
using Google.Protobuf;
using Grpc.Core;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Grpc.Proto;
using redb.Route.Http;
using redb.Route.Telemetry;
using KestrelClientCertificateMode = Microsoft.AspNetCore.Server.Kestrel.Https.ClientCertificateMode;
using IMessage = redb.Route.Abstractions.IMessage;
using HttpProtocol = redb.Route.Http.HttpProtocol;
namespace redb.Route.Grpc;
///
/// gRPC consumer. Registers the endpoint's method address as a path route on the shared Kestrel host
/// and speaks the gRPC wire protocol itself (see ) — the same shape as the AS2
/// and SOAP consumers, which also own their protocol on top of that host.
///
/// Because the route key is the method address, many gRPC methods live on one port as ordinary routes:
/// From("grpc:0.0.0.0:5001/identity.v1.Identity/Token") and
/// From("grpc:0.0.0.0:5001/identity.v1.Identity/Introspect") are two routes with their own ids,
/// policies, metrics and lifecycle.
///
///
public class GrpcConsumer : IConsumer
{
private const string HealthCheckPath = "/grpc.health.v1.Health/Check";
private readonly GrpcEndpoint _endpoint;
private readonly IProcessor _processor;
private readonly GrpcEndpointOptions _options;
private ILogger? _logger;
private RouteRegistration? _registration;
private RouteRegistration? _streamRegistration;
private RouteRegistration? _healthRegistration;
private long _processedCount;
// Unregistering the routes stops new calls; the ones already in the pipeline still have to
// finish, and the listener stays up while another route holds the port.
private readonly InflightDrainGuard _drain = new();
/// Creates a gRPC consumer.
public GrpcConsumer(GrpcEndpoint endpoint, IProcessor processor, GrpcEndpointOptions options)
{
_endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
_processor = processor ?? throw new ArgumentNullException(nameof(processor));
_options = options ?? throw new ArgumentNullException(nameof(options));
_logger = (endpoint.Component as ComponentBase)?.Logger;
_headerFilter = endpoint.HeaderFilterStrategy;
}
private readonly IHeaderFilterStrategy _headerFilter;
///
public IEndpoint Endpoint => _endpoint;
/// Number of requests successfully processed.
public long ProcessedCount => Interlocked.Read(ref _processedCount);
/// The base URL the gRPC server is listening on. Available after Start().
public string? BaseUrl { get; private set; }
private SharedHttpServerManager Server => _endpoint.Server;
///
public async Task Start(CancellationToken ct = default)
{
_drain.Start(ct);
var host = _options.Host;
var port = _options.Port;
// The admission limit counts UNARY calls only — a long-lived
// stream would hold a permit forever, and shed health probes would flap orchestrators.
_registration = RegisterRoute(_options.MethodPath, http => HandleRequest(http, _options.Streaming),
limited: !_options.Streaming);
// A URI with no method address ("grpc:host:port") is the generic service, and that service has
// always answered both its unary and its streaming method. Keep serving both so those endpoints
// behave exactly as they did before the address became the route key.
if (_options.DefaultMethodAddress)
_streamRegistration = RegisterRoute(GrpcEndpointOptions.DefaultStreamMethodPath,
http => HandleRequest(http, streaming: true));
// Health is a plain unary method, so it is simply another path route on the same host:port.
if (_options.Health)
_healthRegistration = RegisterRoute(HealthCheckPath, HandleHealthCheck);
try
{
await Server.EnsureStarted(host, port, ct).ConfigureAwait(false);
}
catch
{
// The listener did not come up: the methods leave it, so a later Start registers them once.
await Stop(CancellationToken.None).ConfigureAwait(false);
throw;
}
BaseUrl = Server.GetBaseUrl(host, port);
_logger ??= (_endpoint.Component as ComponentBase)?.Logger;
_logger?.LogInformation("gRPC consumer started: {Host}:{Port}{Method}", host, port, _options.MethodPath);
}
private RouteRegistration RegisterRoute(string path, Func handler, bool limited = false) =>
Server.RegisterRoute(
_options.Host,
_options.Port,
path,
"POST", // gRPC is POST-only
handler,
_options.Ssl,
_options.SslCertPath,
_options.SslCertPassword,
corsOptions: null, // gRPC is not a browser transport
maxRequestBodySize: 0, // message size is enforced per frame, not per body
protocol: HttpProtocol.Http2,
clientCertificateMode: MapClientCertificateMode(_options.ClientCertificateMode),
clientCertificateValidation: BuildThumbprintValidator(),
concurrencyLimit: limited
? ConcurrencyLimitOptions.FromEndpoint(
_options.MaxConcurrentRequests, _options.RequestQueueLimit,
_options.RejectStatusCode, _options.RetryAfterSeconds,
onRejected: _endpoint.RecordRejected)
: null);
private static KestrelClientCertificateMode? MapClientCertificateMode(GrpcClientCertificateMode mode) => mode switch
{
GrpcClientCertificateMode.AllowCertificate => KestrelClientCertificateMode.AllowCertificate,
GrpcClientCertificateMode.RequireCertificate => KestrelClientCertificateMode.RequireCertificate,
_ => null,
};
///
/// Builds the allow-list check for client certificates. Chain validation is Kestrel's job; this adds
/// "and it must be one of ours", which is what pins a partner in a service-to-service contour.
///
private Func? BuildThumbprintValidator()
{
if (string.IsNullOrWhiteSpace(_options.AllowedClientThumbprints)) return null;
var allowed = _options.AllowedClientThumbprints!
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Select(t => t.Replace(" ", string.Empty))
.ToHashSet(StringComparer.OrdinalIgnoreCase);
return (cert, _, _) => allowed.Contains(cert.Thumbprint);
}
///
public async Task Stop(CancellationToken ct = default)
{
if (_registration is not null)
{
Server.UnregisterRoute(_registration);
_registration = null;
}
if (_streamRegistration is not null)
{
Server.UnregisterRoute(_streamRegistration);
_streamRegistration = null;
}
if (_healthRegistration is not null)
{
Server.UnregisterRoute(_healthRegistration);
_healthRegistration = null;
}
await _drain.DrainAsync(ct, _logger, $"grpc://{_options.Host}:{_options.Port}").ConfigureAwait(false);
await Server.StopIfEmpty(_options.Host, _options.Port, ct).ConfigureAwait(false);
_logger ??= (_endpoint.Component as ComponentBase)?.Logger;
_logger?.LogInformation("gRPC consumer stopped: {Host}:{Port}{Method}",
_options.Host, _options.Port, _options.MethodPath);
}
// ── request handling ─────────────────────────────────────
private async Task HandleRequest(HttpContext http, bool streaming)
{
// Counted for the drain: a call inside the pipeline must finish before Stop returns.
_drain.Increment();
try
{
await HandleRequestCore(http, streaming).ConfigureAwait(false);
}
finally
{
_drain.Decrement();
}
}
private async Task HandleRequestCore(HttpContext http, bool streaming)
{
// The caller's trace goes on from the host's span of this request when ASP.NET Core instrumentation opened
// one, else from the traceparent the call carries; without either the span is a root.
using var span = RouteTelemetryExtensions.StartConsumerSpan(
(_endpoint.Component as ComponentBase)?.Context,
"grpc receive", ActivityKind.Server, "rpc.system", "grpc", _endpoint.Uri.NormalizedKey,
http.Request.Headers, static (headers, name) => headers.TryGetValue(name, out var value) ? value.ToString() : null,
InboundParent.HostRequest);
// MessagesIn is counted by the core StatisticsProcessor around the routed pipeline.
// Content type must be on the response before anything is written, otherwise a client sees a
// non-gRPC reply and reports a protocol error instead of our status.
http.Response.ContentType = GrpcWire.ContentType;
// Codec negotiation. We always advertise what we can decode; we only compress the reply when the
// route asked for it AND the caller said it can inflate it.
var requestEncoding = http.Request.Headers[GrpcWire.EncodingHeader].ToString();
var compressReply = _options.Compression == GrpcCompression.Gzip
&& GrpcWire.IsGzip(http.Request.Headers[GrpcWire.AcceptEncodingHeader].ToString());
http.Response.Headers[GrpcWire.AcceptEncodingHeader] = GrpcWire.SupportedEncodings;
if (compressReply)
http.Response.Headers[GrpcWire.EncodingHeader] = "gzip";
var timeout = GrpcWire.ParseTimeout(http.Request.Headers[GrpcWire.TimeoutHeader]);
using var deadline = timeout is null
? null
: CancellationTokenSource.CreateLinkedTokenSource(http.RequestAborted);
deadline?.CancelAfter(timeout!.Value);
var ct = deadline?.Token ?? http.RequestAborted;
var status = StatusCode.OK;
string? detail = null;
IExchange? exchange = null;
IMessage? outMessage = null;
var pipelineFailed = false;
try
{
if (!GrpcWire.IsGrpcContentType(http.Request.ContentType))
throw new GrpcProtocolException(StatusCode.Internal,
$"Expected content-type {GrpcWire.ContentType}, got '{http.Request.ContentType}'.");
var payload = await GrpcWire.ReadMessageAsync(http.Request.Body, _options.MaxRequestMessageSize, requestEncoding, ct)
.ConfigureAwait(false)
?? throw new GrpcProtocolException(StatusCode.Internal, "Request carried no message.");
// BytesIn is the core StatisticsProcessor's estimate of the same payload.
exchange = BuildExchange(http, payload);
exchange.Pattern = _options.InOut ? ExchangePattern.InOut : ExchangePattern.InOnly;
try
{
await _processor.Process(exchange, ct).ConfigureAwait(false);
if (exchange.Exception is not null && !exchange.ExceptionHandled)
throw exchange.Exception;
}
catch
{
// Counted by the core's StatisticsProcessor - the transport catch below must not.
pipelineFailed = true;
throw;
}
// Identity's convention: a processor may answer on Out or write back into In. Same fallback
// the SOAP consumer uses. InOut only selects the exchange pattern the route sees — the reply
// is written either way, which is how this endpoint has always behaved.
outMessage = exchange.HasOut ? exchange.Out! : exchange.In;
(status, detail) = ResolveStatus(outMessage);
// A non-OK status is delivered trailers-only: gRPC clients discard the payload of a failed
// call, so writing it would just be bytes nobody reads. Detail travels in grpc-message and
// any redbGrpc.Trailer.* headers.
if (status == StatusCode.OK)
await WriteReply(http, outMessage, exchange, streaming, compressReply, ct).ConfigureAwait(false);
Interlocked.Increment(ref _processedCount);
}
catch (Exception ex)
{
var deadlineHit = deadline is { IsCancellationRequested: true }
&& !http.RequestAborted.IsCancellationRequested;
(status, detail) = GrpcWire.FromException(ex, deadlineHit, exchange?.ExchangeId);
// Only the caller going away is a stop; an exceeded deadline or any other cancellation is a failure.
if (ex is not OperationCanceledException || !http.RequestAborted.IsCancellationRequested)
span.Activity.RecordFailure(ex);
// Pipeline failures are already counted by the core; everything else here - a failure
// before the exchange existed (wire read, deserialization) or after the pipeline
// succeeded (reply encoding/writing) - is invisible to the core, so the transport records it.
if (!pipelineFailed)
_endpoint.RecordError(ex);
_logger?.LogError(ex, "gRPC request failed: method={Method} peer={Peer} status={Status}",
_options.MethodPath, http.Connection.RemoteIpAddress, status);
}
finally
{
if (exchange is not null)
await exchange.DisposeAsync().ConfigureAwait(false);
}
try
{
if (outMessage is not null)
AppendTrailers(http.Response, outMessage);
GrpcWire.WriteStatus(http.Response, status, detail);
}
catch (Exception ex)
{
// The caller went away mid-reply; nothing left to report to.
_logger?.LogDebug(ex, "gRPC: could not write status trailers (client gone)");
}
}
///
/// Writes the reply. A route may answer with one message or, on a streaming address, with many:
/// any IEnumerable / IAsyncEnumerable body that is not itself a payload
/// (string, byte[]) is written element by element as its own frame.
///
private async Task WriteReply(HttpContext http, IMessage outMessage, IExchange exchange, bool streaming, bool compress,
CancellationToken ct)
{
if (!streaming && TryGetStreamItems(outMessage.Body, out _))
{
// A unary method carries exactly one message, so a stream body here cannot be delivered.
// Without this guard it would fall through to ToBytes() and the caller would receive the
// enumerable's type name as the payload — the same silent-garbage failure the SOAP consumer
// had with byte[]. Fail loudly and say what to change.
throw new GrpcProtocolException(StatusCode.Internal,
$"Route replied with a stream ({outMessage.Body!.GetType().Name}) on the unary method " +
$"'{_options.MethodPath}'. Declare the address as server-streaming (.Streaming()) or " +
"materialize the body into a single message.");
}
if (streaming && TryGetStreamItems(outMessage.Body, out var items))
{
await foreach (var item in items!.WithCancellation(ct).ConfigureAwait(false))
{
var frame = Encode(item, outMessage, exchange);
await GrpcWire.WriteMessageAsync(http.Response, frame, compress, ct).ConfigureAwait(false);
}
return;
}
var single = Encode(outMessage.Body, outMessage, exchange);
await GrpcWire.WriteMessageAsync(http.Response, single, compress, ct).ConfigureAwait(false);
// MessagesOut per exchange is the core's; frame-level counting doubled it.
}
///
/// Recognises a multi-message body. The signal is the framework's own streaming shape — an
/// IAsyncEnumerable, one yield per message — the same contract the HTTP consumer honours for
/// chunked/SSE replies and the one StreamingSplitterProcessor produces. A List is
/// deliberately not a stream: a collection body stays one message, as it is for every other transport.
///
private static bool TryGetStreamItems(object? body, out IAsyncEnumerable