Bundle: redb-route / redb.Route.Grpc (redb.Route.Grpc.txt), 13 files
Snapshot: 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
Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt
====
Path: redb-route/redb.Route.Grpc/Extensions/ServiceCollectionExtensions.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/Extensions/ServiceCollectionExtensions.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Extensions;
using redb.Route.Http;
namespace redb.Route.Grpc;
///
/// Extension methods for registering the gRPC component with dependency injection.
///
public static class ServiceCollectionExtensions
{
///
/// Registers the gRPC component with the route context.
///
public static IServiceCollection AddRedbRouteGrpc(this IServiceCollection services)
{
// gRPC serves on the shared Kestrel host, same as Http, As2 and Soap. Idempotent, so calling
// several transport registrations in one host still yields one server manager.
services.AddRedbRouteHttpHosting();
services.AddSingleton();
// IRouteContextConfigurator is applied by RouteHostedService at startup --
// the correct registration hook (a lazy marker singleton never fires).
services.AddRouteContextConfigurator((sp, context) =>
{
var component = sp.GetRequiredService();
component.ServerManager = sp.GetRequiredService();
context.AddComponent(component);
});
return services;
}
}
Path: redb-route/redb.Route.Grpc/Fluent/GrpcDsl.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/Fluent/GrpcDsl.cs
----
using System.Text;
using redb.Route.Abstractions;
namespace redb.Route.Grpc;
///
/// Fluent entry point for gRPC endpoints.
///
/// // Producer — call a remote gRPC service:
/// .To(GrpcDsl.Call("localhost:50051").Plaintext().Deadline(10_000))
///
/// // Consumer — host a gRPC service:
/// .From(GrpcDsl.Listen("0.0.0.0:50051"))
///
///
public static class GrpcDsl
{
/// Call a remote gRPC endpoint (producer).
/// Target host:port, e.g. localhost:50051.
public static GrpcBuilder Call(string hostPort) => new(hostPort);
/// Listen for incoming gRPC calls (consumer).
/// Bind address host:port, e.g. 0.0.0.0:50051.
public static GrpcBuilder Listen(string hostPort) => new(hostPort);
}
/// Fluent builder for gRPC endpoint URIs. Scheme: grpc.
public sealed class GrpcBuilder
{
private readonly string _hostPort;
private string? _deadline;
private bool? _plaintext;
private int? _maxSendMessageSize;
private int? _maxReceiveMessageSize;
private int? _maxRequestMessageSize;
private string? _host;
private int? _port;
private bool? _ssl;
private string? _sslCertPath;
private string? _sslCertPassword;
private string? _connectionFactory;
private bool? _inOut;
private string? _methodPath;
private string? _envelope;
private bool? _streaming;
private bool? _throwOnError;
private bool? _health;
private int? _maxConcurrentRequests;
private int? _requestQueueLimit;
private int? _rejectStatusCode;
private int? _retryAfterSeconds;
private string? _clientCertificateMode;
private string? _allowedClientThumbprints;
private string? _clientCertPath;
private string? _clientCertPassword;
private bool? _emitHttpCompatHeaders;
private bool? _allowClientReservedHeaders;
private bool? _suppressStatusMapping;
private string? _service;
private string? _methodName;
private int? _maxMessageSize;
private string? _negotiationType;
private string? _compression;
internal GrpcBuilder(string hostPort)
{
ArgumentException.ThrowIfNullOrWhiteSpace(hostPort);
_hostPort = hostPort;
}
// ── Common ──────────────────────────────────────────────────────
/// Deadline timeout in ms. Default 30000.
public GrpcBuilder Deadline(int ms) { _deadline = ms.ToString(); return this; }
/// Deadline from an expression (resolves to int milliseconds).
public GrpcBuilder Deadline(IExpression expr) { _deadline = expr.ToTemplateString(); return this; }
///
/// Full method address, /package.Service/Method. On the consumer this is the route key, so
/// several gRPC methods are served on one port as separate routes; on the producer it is the method
/// being called. Defaults to the built-in generic RedbService/Process.
///
public GrpcBuilder Method(string methodPath)
{
ArgumentException.ThrowIfNullOrWhiteSpace(methodPath);
_methodPath = methodPath.StartsWith('/') ? methodPath : "/" + methodPath;
return this;
}
///
/// Body handling. Auto (default) uses the generic RedbMessage envelope only for the
/// built-in method address; a typed .proto served on its own address gets raw bytes.
///
public GrpcBuilder Envelope(GrpcEnvelopeMode mode) { _envelope = mode.ToString(); return this; }
///
/// Service plus method, camel-grpc style (grpc://host:port/my.Service?method=Call). Equivalent
/// to with the full address.
///
public GrpcBuilder Service(string service, string? method = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(service);
_service = service;
_methodName = method;
return this;
}
/// One limit for send, receive and server request sizes (camel-grpc's maxMessageSize).
public GrpcBuilder MaxMessageSize(int bytes) { _maxMessageSize = bytes; return this; }
/// Reply compression (server) / request compression (client). Requests are always decoded.
public GrpcBuilder Compression(GrpcCompression codec) { _compression = codec.ToString(); return this; }
/// Channel security, camel-grpc style: PLAINTEXT or TLS.
public GrpcBuilder NegotiationType(string type) { _negotiationType = type; return this; }
// ── Producer ────────────────────────────────────────────────────
/// Use plaintext (no TLS). Default true.
public GrpcBuilder Plaintext(bool value = true) { _plaintext = value; return this; }
/// Max send message size in bytes.
public GrpcBuilder MaxSendMessageSize(int bytes) { _maxSendMessageSize = bytes; return this; }
///
/// Throw when the call fails, so .OnException(...), retry and dead-letter see it — the same
/// contract as the HTTP and SOAP producers. Default true.
///
public GrpcBuilder ThrowOnError(bool value = true) { _throwOnError = value; return this; }
/// Client certificate presented to the server (mTLS, producer side).
public GrpcBuilder ClientCertificate(string pfxPath, string? password = null)
{
_clientCertPath = pfxPath;
_clientCertPassword = password;
return this;
}
/// Max receive message size in bytes.
public GrpcBuilder MaxReceiveMessageSize(int bytes) { _maxReceiveMessageSize = bytes; return this; }
// ── Consumer ────────────────────────────────────────────────────
/// Bind host for consumer. Default 0.0.0.0.
public GrpcBuilder Host(string host) { _host = host; return this; }
/// Bind port for consumer.
public GrpcBuilder Port(int port) { _port = port; return this; }
/// Enable SSL for consumer.
public GrpcBuilder Ssl() { _ssl = true; return this; }
/// Path to SSL certificate.
public GrpcBuilder SslCertPath(string path) { _sslCertPath = path; return this; }
/// SSL certificate password.
public GrpcBuilder SslCertPassword(string password) { _sslCertPassword = password; return this; }
/// References a named from the route registry instead of putting the certificate password in the URI.
public GrpcBuilder ConnectionFactory(string name) { _connectionFactory = name; return this; }
/// Max request message size for consumer.
public GrpcBuilder MaxRequestMessageSize(int bytes) { _maxRequestMessageSize = bytes; return this; }
/// Enable request-response pattern. Default true for gRPC.
public GrpcBuilder InOut(bool value = true) { _inOut = value; return this; }
///
/// Serve this address as a server-streaming method: an IAsyncEnumerable reply body is written
/// one frame per yield — the framework's own streaming shape, the same one the HTTP consumer honours.
/// Default true for the built-in RedbService/ProcessStream, opt-in elsewhere.
///
public GrpcBuilder Streaming(bool value = true) { _streaming = value; return this; }
/// Also serve grpc.health.v1.Health/Check on this host:port.
public GrpcBuilder Health(bool value = true) { _health = value; return this; }
///
/// Admission limit for UNARY calls: at most concurrent pipeline
/// executions; overflow beyond the optional FIFO is shed with an
/// HTTP-level 429 before any pipeline work. Streaming and health methods are not counted.
///
public GrpcBuilder MaxConcurrentRequests(int max, int queue = 0)
{
_maxConcurrentRequests = max;
if (queue > 0) _requestQueueLimit = queue;
return this;
}
/// HTTP status code for a shed request (default 429).
public GrpcBuilder RejectStatusCode(int statusCode) { _rejectStatusCode = statusCode; return this; }
/// Retry-After value for a shed request in seconds; 0 = do not send (default 1).
public GrpcBuilder RetryAfterSeconds(int seconds) { _retryAfterSeconds = seconds; return this; }
///
/// Require or allow a client certificate (mTLS); needs .Ssl(). Optionally pins the accepted
/// certificates by thumbprint.
///
public GrpcBuilder ClientCertificates(
GrpcClientCertificateMode mode = GrpcClientCertificateMode.RequireCertificate,
params string[] allowedThumbprints)
{
_clientCertificateMode = mode.ToString();
if (allowedThumbprints.Length > 0)
_allowedClientThumbprints = string.Join(',', allowedThumbprints);
return this;
}
///
/// Mirror the client address into redbHttp.RemoteAddress as well, so processors written
/// against the HTTP transport (rate limiting, lockout, device metadata) work behind a gRPC facade.
///
public GrpcBuilder EmitHttpCompatHeaders(bool value = true) { _emitHttpCompatHeaders = value; return this; }
///
/// Accept caller headers carrying a transport-reserved prefix (redbGrpc., redbHttp., …).
/// Off by default — a client must not be able to forge metadata that upstream processors trust.
///
public GrpcBuilder AllowClientReservedHeaders(bool value = true) { _allowClientReservedHeaders = value; return this; }
///
/// Never translate a route's status.code into a gRPC status; always answer OK and let the
/// caller read the error out of the body. Escape hatch for clients written against the old behaviour.
///
public GrpcBuilder SuppressStatusMapping(bool value = true) { _suppressStatusMapping = value; return this; }
// ── Build ───────────────────────────────────────────────────────
/// Builds the endpoint URI.
public string Build()
{
var sb = new StringBuilder();
sb.Append("grpc:");
sb.Append(_hostPort);
// The method address lives in the URI path — it is the route key, not a parameter.
if (_methodPath is not null && !_hostPort.Contains('/'))
sb.Append(_methodPath);
var sep = '?';
void Append(string key, string v) { sb.Append(sep); sb.Append(key); sb.Append('='); sb.Append(v); sep = '&'; }
void AppendInt(string key, int? v) { if (v.HasValue) Append(key, v.Value.ToString()); }
void AppendBool(string key, bool? v) { if (v.HasValue) Append(key, v.Value.ToString().ToLowerInvariant()); }
void AppendStr(string key, string? v) { if (v != null) Append(key, v); }
void AppendIntOrExpression(string key, string? v)
{
if (v is null) return;
if (v.Contains("${"))
Append(key + "Expression", v);
else
Append(key, v);
}
AppendIntOrExpression("deadline", _deadline);
AppendBool("plaintext", _plaintext);
AppendInt("maxSendMessageSize", _maxSendMessageSize);
AppendInt("maxReceiveMessageSize", _maxReceiveMessageSize);
AppendInt("maxConcurrentRequests", _maxConcurrentRequests);
AppendInt("requestQueueLimit", _requestQueueLimit);
AppendInt("rejectStatusCode", _rejectStatusCode);
AppendInt("retryAfterSeconds", _retryAfterSeconds);
AppendStr("host", _host);
AppendInt("port", _port);
AppendBool("ssl", _ssl);
AppendStr("sslCertPath", _sslCertPath);
AppendStr("sslCertPassword", _sslCertPassword);
AppendStr("connectionFactory", _connectionFactory);
AppendInt("maxRequestMessageSize", _maxRequestMessageSize);
AppendBool("inOut", _inOut);
AppendStr("envelope", _envelope);
AppendBool("streaming", _streaming);
AppendBool("throwOnError", _throwOnError);
AppendBool("health", _health);
AppendStr("clientCertificateMode", _clientCertificateMode);
AppendStr("allowedClientThumbprints", _allowedClientThumbprints);
AppendStr("clientCertPath", _clientCertPath);
AppendStr("clientCertPassword", _clientCertPassword);
AppendBool("emitHttpCompatHeaders", _emitHttpCompatHeaders);
AppendBool("allowClientReservedHeaders", _allowClientReservedHeaders);
AppendBool("suppressStatusMapping", _suppressStatusMapping);
AppendStr("service", _service);
AppendStr("method", _methodName);
AppendInt("maxMessageSize", _maxMessageSize);
AppendStr("negotiationType", _negotiationType);
AppendStr("compression", _compression);
return sb.ToString();
}
/// Implicitly converts the builder to its endpoint URI.
public static implicit operator string(GrpcBuilder b) => b.Build();
///
public override string ToString() => Build();
}
Path: redb-route/redb.Route.Grpc/GrpcComponent.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/GrpcComponent.cs
----
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Extensions;
using redb.Route.Core;
using redb.Route.Http;
namespace redb.Route.Grpc;
///
/// gRPC component. Scheme: "grpc".
/// Producer: GrpcChannel-based client for calling gRPC services.
///
/// Consumer: a path route on the shared Kestrel host (the same
/// that serves Http, As2 and Soap), speaking the gRPC wire
/// protocol directly. A gRPC method address is just the route path, so many methods share one port.
///
/// URI format: grpc:host:port[/package.Service/Method]?deadline=30000&plaintext=true
///
public class GrpcComponent : ComponentBase
{
// Fallback for a host that never registered the shared manager in DI (a bare gRPC unit test, or a
// process that uses no other HTTP-based transport).
private readonly Lazy _ownServer = new(() => new SharedHttpServerManager());
///
public override string Scheme => "grpc";
///
/// Shared Kestrel host. Set by AddRedbRouteGrpc() from DI so that a gRPC route and an HTTP
/// (or AS2, or SOAP) route in the same worker share one server per host:port and never fight over
/// a port.
///
public SharedHttpServerManager? ServerManager { get; set; }
///
/// Resolution order: explicitly assigned → the host's DI singleton → a private instance. The DI step
/// matters for module hosts that add the component by hand rather than through the extension method.
///
internal SharedHttpServerManager Server =>
ServerManager
?? Context.Resolve()
?? _ownServer.Value;
///
public override IEndpoint CreateEndpoint(EndpointUri uri)
{
ArgumentNullException.ThrowIfNull(uri);
var options = new GrpcEndpointOptions();
options.BindFromUri(uri.RawParameters);
// Path is "host[:port][/package.Service/Method]".
var (authority, methodPath) = SplitPath(uri.Path);
ParseHostPort(authority, options, uri.RawParameters);
if (!uri.RawParameters.ContainsKey("methodPath") && !string.IsNullOrEmpty(methodPath))
options.MethodPath = methodPath!;
// camel-grpc parity: grpc://host:port/my.Service?method=Call — service in the path, method as a
// parameter. Composes into the same MethodPath the full address form produces.
ApplyCamelStyleAddress(options, uri.RawParameters, ref methodPath);
ApplyCamelStyleAliases(options, uri.RawParameters);
options.DefaultMethodAddress =
string.IsNullOrEmpty(methodPath)
&& !uri.RawParameters.ContainsKey("methodPath")
&& string.IsNullOrEmpty(options.Service);
// The built-in streaming address streams by default; any other address opts in explicitly.
if (!uri.RawParameters.ContainsKey("streaming")
&& string.Equals(options.MethodPath, GrpcEndpointOptions.DefaultStreamMethodPath,
StringComparison.OrdinalIgnoreCase))
{
options.Streaming = true;
}
// Named ConnectionFactory keeps the TLS certificate password out of the route URI.
if (!string.IsNullOrEmpty(options.ConnectionFactory))
{
// A set-but-unknown name fails loud -- never a silent fallback to URI params.
var factory = Context.GetRequiredFromRegistry(options.ConnectionFactory);
factory.ApplyTo(options, uri);
}
options.Validate();
if (options.AllowClientReservedHeaders)
Logger?.LogWarning(
"gRPC {Method}: allowClientReservedHeaders=true — callers can set redb* headers that " +
"upstream processors trust (client IP, transport metadata). Only do this behind a trusted proxy.",
options.MethodPath);
return new GrpcEndpoint(uri, this, options);
}
///
/// camel-grpc addresses a service in the URI path and names the method with a parameter
/// (grpc://host:port/my.Service?method=Call). Both spellings end up in
/// , so a Camel-shaped URI works unchanged.
///
private static void ApplyCamelStyleAddress(
GrpcEndpointOptions options, IReadOnlyDictionary rawParams, ref string? methodPath)
{
// A single path segment after the authority is a service name, not a full method address.
if (methodPath is not null && !methodPath.TrimStart('/').Contains('/') && string.IsNullOrEmpty(options.Service))
options.Service = methodPath.TrimStart('/');
if (string.IsNullOrEmpty(options.Service)) return;
var method = string.IsNullOrEmpty(options.Method)
? SplitMethodName(options.MethodPath)
: options.Method!;
options.MethodPath = $"/{options.Service!.Trim('/')}/{method}";
methodPath = options.MethodPath;
static string SplitMethodName(string path)
{
var slash = path.LastIndexOf('/');
return slash < 0 ? path : path[(slash + 1)..];
}
}
///
/// Applies the camel-grpc convenience parameters: negotiationType (PLAINTEXT/TLS) and
/// maxMessageSize. An explicit redb-native parameter always wins, so the two spellings never
/// fight.
///
private static void ApplyCamelStyleAliases(GrpcEndpointOptions options, IReadOnlyDictionary rawParams)
{
if (!string.IsNullOrEmpty(options.NegotiationType))
{
var tls = options.NegotiationType!.Equals("TLS", StringComparison.OrdinalIgnoreCase);
if (!rawParams.ContainsKey("plaintext")) options.Plaintext = !tls;
if (!rawParams.ContainsKey("ssl") && tls) options.Ssl = true;
}
// `ssl=true` and `plaintext` are two spellings of one decision, and only negotiationType used to
// join them. On its own, .Ssl() left Plaintext at its default of true — and the producer builds
// its address from Plaintext alone, so a client explicitly told to use TLS connected over http://
// and said nothing about it. An explicit `plaintext` still wins: someone who asks for cleartext
// by name is debugging, and taking that away would be its own surprise.
if (options.Ssl && !rawParams.ContainsKey("plaintext"))
options.Plaintext = false;
if (options.MaxMessageSize > 0)
{
if (!rawParams.ContainsKey("maxSendMessageSize")) options.MaxSendMessageSize = options.MaxMessageSize;
if (!rawParams.ContainsKey("maxReceiveMessageSize")) options.MaxReceiveMessageSize = options.MaxMessageSize;
if (!rawParams.ContainsKey("maxRequestMessageSize")) options.MaxRequestMessageSize = options.MaxMessageSize;
}
}
///
/// Splits "host:port/package.Service/Method" into the authority and the method address. The method
/// address starts at the first slash after the authority; everything before it is host[:port].
///
private static (string Authority, string? MethodPath) SplitPath(string path)
{
var segment = path.TrimStart('/');
var slash = segment.IndexOf('/');
return slash < 0
? (segment, null)
: (segment[..slash], segment[slash..]);
}
///
/// Extracts host and port from the authority segment (host[:port]).
/// Only overrides options if not already set via query parameters.
///
private static void ParseHostPort(string authority, GrpcEndpointOptions options, IReadOnlyDictionary rawParams)
{
var colonIdx = authority.LastIndexOf(':');
if (colonIdx > 0)
{
var hostPart = authority[..colonIdx];
var portPart = authority[(colonIdx + 1)..];
if (!rawParams.ContainsKey("host") && !string.IsNullOrEmpty(hostPart))
options.Host = hostPart;
if (!rawParams.ContainsKey("port") && int.TryParse(portPart, out var port))
options.Port = port;
}
else if (!rawParams.ContainsKey("host") && !string.IsNullOrEmpty(authority))
{
options.Host = authority;
}
}
}
///
/// gRPC endpoint. Creates either a producer (gRPC client) or consumer (a path route on the shared
/// Kestrel host).
/// URI path format: host[:port][/package.Service/Method]
///
public class GrpcEndpoint : EndpointBase
{
/// Creates a gRPC endpoint.
public GrpcEndpoint(EndpointUri uri, GrpcComponent component, GrpcEndpointOptions options)
: base(uri, component, options)
{
_headerFilter = new EndpointHeaderFilter(this, options.HeaderFilterStrategy);
}
private readonly EndpointHeaderFilter _headerFilter;
///
/// The header filter strategy of this endpoint: the one headerFilterStrategy=#name names, or
/// . A name the registry does not hold fails when the producer or
/// consumer is built.
///
internal IHeaderFilterStrategy HeaderFilterStrategy => _headerFilter.Or(GrpcHeaderFilterStrategy.Default);
/// The endpoint options for external access.
internal GrpcEndpointOptions EndpointOptions => Options;
/// The shared Kestrel host this endpoint serves on.
internal SharedHttpServerManager Server =>
(Component as GrpcComponent)?.Server
?? throw new InvalidOperationException("gRPC endpoint has no GrpcComponent/server.");
///
/// Builds the target address for the producer: scheme + authority, without the method address
/// (the method is addressed per call, not per channel).
///
public string BuildProducerAddress()
{
var scheme = Options.Plaintext ? "http" : "https";
return $"{scheme}://{Options.Host}:{Options.Port}";
}
///
public override IProducer CreateProducer()
{
return new GrpcProducer(this, Options);
}
///
public override IConsumer CreateConsumer(IProcessor processor)
{
ArgumentNullException.ThrowIfNull(processor);
return new GrpcConsumer(this, processor, Options);
}
}
Path: redb-route/redb.Route.Grpc/GrpcConnectionFactory.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/GrpcConnectionFactory.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.Grpc;
///
/// Named connection factory for gRPC. Register it in the route registry and reference it by name
/// from the endpoint URI (connectionFactory=my-grpc) so the TLS certificate password never
/// has to appear in the URI, and therefore can never reach logs, telemetry, or the dashboard.
///
/// The listen/target address stays in the endpoint path — a factory carries TLS material only and
/// can never silently redirect a route.
///
///
public sealed class GrpcConnectionFactory
{
/// Serve/connect over TLS.
public bool Ssl { get; set; }
/// Path to the PFX certificate.
public string? SslCertPath { get; set; }
/// Password for the PFX certificate.
[Sensitive]
public string? SslCertPassword { get; set; }
///
/// Copies this factory's TLS settings onto the endpoint options, but only for parameters the
/// endpoint URI did not set explicitly — an inline URI value always wins.
///
internal void ApplyTo(GrpcEndpointOptions options, EndpointUri uri)
{
var supplied = uri.RawParameters;
if (!supplied.ContainsKey(nameof(options.Ssl))) options.Ssl = Ssl;
if (!supplied.ContainsKey(nameof(options.SslCertPath))) options.SslCertPath = SslCertPath;
if (!supplied.ContainsKey(nameof(options.SslCertPassword)))
options.SslCertPassword = SslCertPassword;
}
}
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