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? items) { // IAsyncEnumerable is covariant, so this one pattern also catches IAsyncEnumerable // and IAsyncEnumerable — the shapes routes actually yield. items = body as IAsyncEnumerable; return items is not null; } /// /// Encodes one reply item. In envelope mode it becomes a RedbMessage carrying the body plus /// the message headers; in raw mode the bytes go on the wire untouched, which is what a typed /// .proto client expects. The envelope carries the headers the endpoint's strategy lets out. /// private byte[] Encode(object? body, IMessage outMessage, IExchange exchange) { if (!_options.UseEnvelope) return GrpcWire.ToBytes(body); var reply = new RedbMessage(); var bytes = GrpcWire.ToBytes(body); if (bytes.Length > 0) reply.Payload = ByteString.CopyFrom(bytes); foreach (var (key, value) in outMessage.Headers) { if (value is null) continue; if (_headerFilter.FilterOutgoing(key, value, exchange)) continue; reply.Headers[key] = value.ToString() ?? string.Empty; } return reply.ToByteArray(); } /// /// Chooses the status the caller receives: an explicit redbGrpc.StatusCode wins, otherwise the /// transport-neutral status.code that controllers and processors already write is translated. /// private (StatusCode Status, string? Detail) ResolveStatus(IMessage outMessage) { var detail = outMessage.GetHeader(GrpcHeaders.StatusDetail); if (outMessage.Headers.TryGetValue(GrpcHeaders.StatusCode, out var explicitStatus) && explicitStatus is not null) { var raw = explicitStatus.ToString(); if (int.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out var numeric) && Enum.IsDefined(typeof(StatusCode), numeric)) return ((StatusCode)numeric, detail); if (Enum.TryParse(raw, ignoreCase: true, out var named)) return (named, detail); } if (_options.SuppressStatusMapping) return (StatusCode.OK, null); if (outMessage.Headers.TryGetValue("status.code", out var neutral) && neutral is not null && int.TryParse(neutral.ToString(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var httpStatus)) { var mapped = GrpcWire.FromHttpStatus(httpStatus); return (mapped, mapped == StatusCode.OK ? null : detail ?? $"status.code {httpStatus}"); } return (StatusCode.OK, null); } /// Copies redbGrpc.Trailer.* headers into the response trailers. private static void AppendTrailers(HttpResponse response, IMessage outMessage) { foreach (var (key, value) in outMessage.Headers) { if (value is null) continue; if (!key.StartsWith(GrpcHeaders.TrailerPrefix, StringComparison.OrdinalIgnoreCase)) continue; var name = key[GrpcHeaders.TrailerPrefix.Length..]; if (name.Length > 0) response.AppendTrailer(name.ToLowerInvariant(), value.ToString() ?? string.Empty); } } private Exchange BuildExchange(HttpContext http, byte[] payload) { object? body = payload; var headers = new Dictionary(StringComparer.OrdinalIgnoreCase); if (_options.UseEnvelope) { RedbMessage envelope; try { envelope = RedbMessage.Parser.ParseFrom(payload); } catch (InvalidProtocolBufferException ex) { // The caller sent bytes that are not a RedbMessage. Left alone this surfaced through the // catch-all as Internal — which tells the caller "our fault, retry" for input only they // can fix — and put the parser's own wording in grpc-message. Their mistake, their status. throw new GrpcProtocolException(StatusCode.InvalidArgument, "Request is not a valid RedbMessage envelope. Send the raw message instead, or " + $"address an endpoint without envelope mode. ({ex.GetType().Name})"); } body = envelope.Payload.IsEmpty ? null : envelope.Payload.ToByteArray(); foreach (var (key, value) in envelope.Headers) headers[key] = value; } var message = new Message(body) { ContentType = GrpcWire.ProtoContentType }; var exchange = Exchange.Create(message, _endpoint.ScopeFactory); // 1. Caller-supplied headers first — so our own metadata below cannot be overwritten by them. The reserved // prefixes are refused whatever the strategy says; the strategy decides the rest. foreach (var (key, value) in headers) { if (!Accept(key)) continue; if (_headerFilter.FilterIncoming(key, value, exchange)) continue; message.Headers[key] = value; } foreach (var entry in http.Request.Headers) { var key = entry.Key; if (key.StartsWith(':')) continue; // HTTP/2 pseudo-headers if (key.StartsWith("grpc-", StringComparison.OrdinalIgnoreCase)) continue; // protocol plane if (!Accept(key)) continue; var value = entry.Value.ToString(); if (_headerFilter.FilterIncoming(key, value, exchange)) continue; message.Headers[key] = value; } // 2. Transport metadata last: it is ours, and it is what upstream processors trust. var (service, method) = SplitMethod(_options.MethodPath); message.Headers[GrpcHeaders.Route] = _options.MethodPath; message.Headers[GrpcHeaders.Service] = service; message.Headers[GrpcHeaders.Method] = method; message.Headers[GrpcHeaders.Port] = _options.Port; var remote = http.Connection.RemoteIpAddress; if (remote is not null) { var ip = remote.IsIPv4MappedToIPv6 ? remote.MapToIPv4().ToString() : remote.ToString(); message.Headers[GrpcHeaders.RemoteIp] = ip; message.Headers[GrpcHeaders.RemotePort] = http.Connection.RemotePort; message.Headers[GrpcHeaders.RemotePeer] = GrpcWire.FormatPeer(remote, http.Connection.RemotePort); // Opt-in bridge for processors written against the HTTP transport (rate limiting, lockout, // device metadata). Off by default: a header in someone else's namespace is a deliberate act. if (_options.EmitHttpCompatHeaders) message.Headers["redbHttp.RemoteAddress"] = ip; } if (http.Request.Host.HasValue) message.Headers[GrpcHeaders.Authority] = http.Request.Host.Value!; var timeout = GrpcWire.ParseTimeout(http.Request.Headers[GrpcWire.TimeoutHeader]); if (timeout is not null) message.Headers[GrpcHeaders.Deadline] = DateTime.UtcNow.Add(timeout.Value).ToString("O"); var clientCert = http.Connection.ClientCertificate; if (clientCert is not null) { message.Headers[GrpcHeaders.ClientCertThumbprint] = clientCert.Thumbprint; message.Headers[GrpcHeaders.ClientCertSubject] = clientCert.Subject; message.Headers[GrpcHeaders.ClientCertNotAfter] = clientCert.NotAfter.ToUniversalTime().ToString("O"); } ExchangePrincipal.Set(exchange, SharedHttpServerManager.GetResolvedPrincipal(http)); return exchange; bool Accept(string key) => _options.AllowClientReservedHeaders || !GrpcWire.IsReservedKey(key); } private static (string Service, string Method) SplitMethod(string methodPath) { var trimmed = methodPath.TrimStart('/'); var slash = trimmed.LastIndexOf('/'); return slash < 0 ? (trimmed, string.Empty) : (trimmed[..slash], trimmed[(slash + 1)..]); } // ── health ─────────────────────────────────────────────── /// /// Answers grpc.health.v1.Health/Check with SERVING. The response message is two protobuf /// bytes (field 1, varint 1), so the standard health contract is met without generating the proto. /// private async Task HandleHealthCheck(HttpContext http) { http.Response.ContentType = GrpcWire.ContentType; try { // HealthCheckResponse { ServingStatus status = 1; } with SERVING = 1. await GrpcWire.WriteMessageAsync(http.Response, [0x08, 0x01], compress: false, http.RequestAborted).ConfigureAwait(false); GrpcWire.WriteStatus(http.Response, StatusCode.OK); } catch (Exception ex) { _logger?.LogDebug(ex, "gRPC: health check could not be answered"); } } } Path: redb-route/redb.Route.Grpc/GrpcEndpointOptions.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/GrpcEndpointOptions.cs ---- using redb.Route.Abstractions; using redb.Route.Http; using redb.Route.Core; namespace redb.Route.Grpc; /// How the consumer interprets the request body and shapes the reply. public enum GrpcEnvelopeMode { /// /// Envelope for the built-in generic method, raw bytes for any other address. Lets the shipped /// RedbService keep its headers-plus-payload contract while a typed .proto served on /// its own address receives exactly the bytes its client sent. /// Auto, /// Always decode the body as a RedbMessage envelope (payload + string headers). Message, /// Never decode: the exchange body is the raw protobuf message the caller sent. Raw, } /// Message compression codec (gRPC grpc-encoding). public enum GrpcCompression { /// Send replies uncompressed. Default. Compressed requests are still accepted. None, /// Gzip replies, but only when the caller advertises gzip in grpc-accept-encoding. Gzip, } /// Whether the consumer requires, allows, or ignores a client certificate (mTLS). public enum GrpcClientCertificateMode { /// No client certificate is requested. Default. NoCertificate, /// A certificate is requested; the call proceeds when the client presents none. AllowCertificate, /// A certificate is required; the handshake fails without one. RequireCertificate, } /// /// Options for the gRPC endpoint. Shared by both producer and consumer. /// Use URI parameters to configure: grpc:host:port/service/method?deadline=30000 /// public class GrpcEndpointOptions : EndpointOptions { /// The built-in generic unary method served when the URI carries no method address. public const string DefaultMethodPath = "/redb.route.grpc.RedbService/Process"; /// The built-in generic server-streaming method. public const string DefaultStreamMethodPath = "/redb.route.grpc.RedbService/ProcessStream"; // ── Common ────────────────────────────────────────── /// /// A registry reference (#name) to an that /// decides which headers this endpoint carries between the exchange and call metadata or envelope headers (a /// call, a request, a reply both ways), in place of . /// [RegistryReference(typeof(IHeaderFilterStrategy))] public string? HeaderFilterStrategy { get; set; } /// Deadline (timeout) in milliseconds. Default: 30000 (30s). 0 = no deadline. public int Deadline { get; set; } = 30_000; /// Expression override for deadline (resolves to int milliseconds). public string? DeadlineExpression { get; set; } /// /// Full method address this endpoint serves or calls, /package.Service/Method. Taken from the /// URI path after host:port; defaults to . This is the route /// key on the consumer side, so many gRPC methods live on one port as ordinary path routes. /// public string MethodPath { get; set; } = DefaultMethodPath; /// Body handling for the consumer. Default: . public GrpcEnvelopeMode Envelope { get; set; } = GrpcEnvelopeMode.Auto; /// /// Fully-qualified service name, e.g. identity.v1.Identity. Parity with camel-grpc, which /// addresses a service in the URI path and the method as a parameter. Combined with /// it forms . /// public string? Service { get; set; } /// /// Method name within , e.g. Token. Parity with camel-grpc's /// method parameter. /// public string? Method { get; set; } /// /// Single knob for all three size limits (send, receive, server request), mirroring camel-grpc's /// maxMessageSize. An explicit per-direction value in the URI wins over it. /// public int MaxMessageSize { get; set; } /// /// Channel security, mirroring camel-grpc's negotiationType: PLAINTEXT or TLS. /// A convenience over / , which stay authoritative when set /// explicitly. /// public string? NegotiationType { get; set; } // ── Producer (GrpcChannel) ────────────────────────── /// Use plaintext (HTTP/2 without TLS). Default: true. Set to false for TLS. public bool Plaintext { get; set; } = true; /// Max send message size in bytes. Default: 4 MB. 0 = unlimited. public int MaxSendMessageSize { get; set; } = 4 * 1024 * 1024; /// Max receive message size in bytes. Default: 4 MB. 0 = unlimited. public int MaxReceiveMessageSize { get; set; } = 4 * 1024 * 1024; /// /// Throw when the call fails, so .OnException(...), retry and dead-letter see it — the same /// contract as the HTTP and SOAP producers. Default: true. Set false for the legacy behaviour where /// the failure was only recorded on the exchange and the pipeline carried on. /// public bool ThrowOnError { get; set; } = true; /// Path to a PFX client certificate presented to the server (mTLS, producer side). public string? ClientCertPath { get; set; } /// Password for . [Sensitive] public string? ClientCertPassword { get; set; } // ── Consumer (Kestrel, shared host) ───────────────── /// Bind host for the gRPC server. Default: 0.0.0.0. public string Host { get; set; } = "0.0.0.0"; /// Bind port for the gRPC server. Default: 50051. public int Port { get; set; } = 50051; /// Enable TLS for the consumer. Default: false (plaintext HTTP/2, i.e. h2c). public bool Ssl { get; set; } /// Path to PFX certificate file for TLS. Required when ssl=true. public string? SslCertPath { get; set; } /// Password for the PFX certificate. [Sensitive] public string? SslCertPassword { get; set; } /// Client-certificate policy (mTLS). Requires . public GrpcClientCertificateMode ClientCertificateMode { get; set; } = GrpcClientCertificateMode.NoCertificate; /// /// Comma-separated thumbprints of accepted client certificates. When set, a presented certificate /// whose thumbprint is not listed is rejected even if its chain validates. /// public string? AllowedClientThumbprints { get; set; } /// /// Named from the route registry. Lets the TLS certificate /// password live in the registry instead of the endpoint URI, so it never reaches logs /// or dashboards. /// [RegistryReference(typeof(GrpcConnectionFactory))] public string? ConnectionFactory { get; set; } /// Max request message size in bytes for the server. Default: 4 MB. 0 = unlimited. public int MaxRequestMessageSize { get; set; } = 4 * 1024 * 1024; /// /// If true, the consumer returns the exchange Out body as the gRPC response (InOut pattern). /// If false, returns an empty response (InOnly pattern). Default: true for gRPC. /// public bool InOut { get; set; } = true; /// /// Serve this address as a server-streaming method: the route's reply may carry many messages and /// each is written as its own frame. Defaults to true for . /// public bool Streaming { get; set; } /// /// Mirror the resolved client address into redbHttp.RemoteAddress as well, so processors /// written against the HTTP transport (rate limiting, lockout, device metadata) work unchanged /// behind a gRPC facade. Default: false. /// public bool EmitHttpCompatHeaders { get; set; } /// /// Accept caller-supplied headers that carry a transport-reserved prefix (redbGrpc., /// redbHttp., …). Default: false — a client must not be able to forge the metadata that /// upstream processors trust. Turning this on is logged. /// public bool AllowClientReservedHeaders { get; set; } /// /// Do not 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. Default: false. /// public bool SuppressStatusMapping { get; set; } /// /// Also serve grpc.health.v1.Health/Check on this host:port, answering SERVING while the /// route is running. Standard probe for Kubernetes, Consul and Envoy. Default: false. /// public bool Health { get; set; } /// /// Reply compression. Requests are decompressed regardless of this setting (we advertise /// identity,gzip); this only decides whether we compress what we send, and even then only when /// the caller advertised gzip. Default: . /// public GrpcCompression Compression { get; set; } = GrpcCompression.None; // ── Admission limit (HTTP_CONCURRENCY_LIMITS_PLAN) ── /// /// Maximum concurrent executions of this consumer's pipeline for UNARY calls. 0 (default) = /// unlimited. Streaming methods are deliberately not counted — a long-lived stream would hold /// a permit for its whole life and starve the limit (a dedicated maxConcurrentStreams may come /// later); the health method is not counted either, so orchestrator probes never flap under /// load. Overflow beyond the limit and is shed with /// before any pipeline work. /// public int MaxConcurrentRequests { get; set; } /// Requests over the limit that WAIT for a permit (FIFO). 0 (default) = reject immediately. public int RequestQueueLimit { get; set; } /// HTTP status code for a shed request. Default 429 (gRPC clients see an HTTP-level error). public int RejectStatusCode { get; set; } = 429; /// Value of the Retry-After header on a shed request; 0 = do not send it. Default 1. public int RetryAfterSeconds { get; set; } = 1; /// public override void Validate() { ConcurrencyLimitOptions.ValidateShape(MaxConcurrentRequests, RequestQueueLimit, RejectStatusCode, RetryAfterSeconds); if (Deadline < 0) throw new ArgumentException("Deadline must be >= 0."); if (Port is < 0 or > 65535) throw new ArgumentException("Port must be between 0 and 65535."); // No SslCertPath check here on purpose: the certificate may come from a named connection // factory or from the host default (HttpHostingOptions.Tls). The invariant "TLS asked for // and no certificate resolves" is enforced once, at the bind, by SharedHttpServerManager. if (ClientCertificateMode != GrpcClientCertificateMode.NoCertificate && !Ssl) throw new ArgumentException("clientCertificateMode requires ssl=true — mTLS needs a TLS handshake."); if (!string.IsNullOrEmpty(MethodPath) && !MethodPath.StartsWith('/')) MethodPath = "/" + MethodPath; } /// /// True when the URI carried no method address, i.e. this endpoint is the built-in generic service. /// Such a consumer serves both Process and ProcessStream, as it always has. /// internal bool DefaultMethodAddress { get; set; } = true; /// True when the body should be decoded as a RedbMessage envelope. internal bool UseEnvelope => Envelope switch { GrpcEnvelopeMode.Message => true, GrpcEnvelopeMode.Raw => false, _ => string.Equals(MethodPath, DefaultMethodPath, StringComparison.OrdinalIgnoreCase) || string.Equals(MethodPath, DefaultStreamMethodPath, StringComparison.OrdinalIgnoreCase), }; } Path: redb-route/redb.Route.Grpc/GrpcHeaderFilterStrategy.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/GrpcHeaderFilterStrategy.cs ---- using redb.Route.Abstractions; namespace redb.Route.Grpc; /// /// The default of the gRPC component. An endpoint's /// headerFilterStrategy=#name replaces it; derive from it to add to it. /// /// A producer sends every exchange header but the component's own redbGrpc.* and null values as call metadata /// and, in envelope mode, as envelope headers; a consumer's reply envelope carries the same. A consumer brings every /// request metadata entry and envelope header in, and a producer every reply envelope header. /// /// /// Whatever the strategy: HTTP/2 pseudo-headers and grpc-* entries are the protocol's own; a caller's header /// with a transport-reserved prefix (redbGrpc., redbHttp....) is dropped on the way in unless /// allowClientReservedHeaders=true; a metadata key gRPC cannot express is not sent; the consumer's /// redbGrpc.* call metadata, the envelope's Content-Type and the redbGrpc.Trailer.* trailers are /// set by the component; trace context is written by the telemetry layer. /// /// public class GrpcHeaderFilterStrategy : IHeaderFilterStrategy { /// The default strategy of a gRPC endpoint. public static GrpcHeaderFilterStrategy Default { get; } = new(); /// public virtual bool FilterOutgoing(string name, object? value, IExchange exchange) => value is null || GrpcHeaders.IsRedbHeader(name); /// public virtual bool FilterIncoming(string name, object? value, IExchange exchange) => false; } Path: redb-route/redb.Route.Grpc/GrpcHeaders.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/GrpcHeaders.cs ---- namespace redb.Route.Grpc; /// /// Well-known header constants used by the gRPC component. /// Exchange headers with the "redbGrpc." prefix are set/read automatically. /// public static class GrpcHeaders { /// Common prefix for all gRPC component headers. public const string Prefix = "redbGrpc."; /// gRPC service name. Example: "redb.route.grpc.RedbService". public const string Service = "redbGrpc.Service"; /// gRPC method name. Example: "Process". public const string Method = "redbGrpc.Method"; /// /// gRPC status code (int, or the Grpc.Core.StatusCode name). Set by the producer after a /// response; set it on the consumer's Out to choose the status the caller receives. When it is /// absent the consumer falls back to the transport-neutral status.code that controllers write. /// public const string StatusCode = "redbGrpc.StatusCode"; /// gRPC status detail message (the grpc-message trailer). public const string StatusDetail = "redbGrpc.StatusDetail"; /// /// Prefix for response trailers. A header redbGrpc.Trailer.error becomes the trailer /// error, so a route can return structured failure detail without disturbing the body. /// public const string TrailerPrefix = "redbGrpc.Trailer."; /// Full method address the call arrived on, e.g. /identity.v1.Identity/Token. public const string Route = "redbGrpc.Route"; /// Remote peer address (consumer-side), raw gRPC form: ipv4:10.0.0.5:51234. public const string RemotePeer = "redbGrpc.RemotePeer"; /// Remote client address, bare (no scheme, no port) — what IP-based policies expect. public const string RemoteIp = "redbGrpc.RemoteIp"; /// Remote client port (int). public const string RemotePort = "redbGrpc.RemotePort"; /// Thumbprint of the client certificate, when mTLS is enabled and one was presented. public const string ClientCertThumbprint = "redbGrpc.ClientCertThumbprint"; /// Subject of the client certificate. public const string ClientCertSubject = "redbGrpc.ClientCertSubject"; /// Expiry (ISO 8601) of the client certificate. public const string ClientCertNotAfter = "redbGrpc.ClientCertNotAfter"; /// Server port the request was received on (consumer-side). public const string Port = "redbGrpc.Port"; /// Authority (host:port) from the gRPC call. public const string Authority = "redbGrpc.Authority"; /// Deadline for the gRPC call (ISO 8601), if set by the caller. public const string Deadline = "redbGrpc.Deadline"; /// Returns true if the header key belongs to the gRPC component. public static bool IsRedbHeader(string key) => key.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase); } Path: redb-route/redb.Route.Grpc/GrpcProducer.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/GrpcProducer.cs ---- using System.Diagnostics; using System.Net.Http; using System.Security.Cryptography.X509Certificates; using Google.Protobuf; using Grpc.Core; using Grpc.Net.Client; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Grpc.Proto; using redb.Route.Telemetry; namespace redb.Route.Grpc; /// /// gRPC producer (client). Calls the method address carried by the endpoint URI — by default the /// built-in generic RedbService/Process, or any typed /package.Service/Method. /// /// Messages are marshalled as raw bytes, so the producer can call a typed .proto service whose /// stubs it has never seen: in envelope mode the body is wrapped in a RedbMessage, in raw mode /// the exchange body goes on the wire as-is. /// /// public class GrpcProducer : ConnectableProducer { private static readonly Marshaller ByteMarshaller = Marshallers.Create(b => b, b => b); private readonly GrpcEndpoint _endpoint; private readonly GrpcEndpointOptions _options; private GrpcChannel? _channel; private CallInvoker? _invoker; private Method? _method; /// Creates a gRPC producer. public GrpcProducer(GrpcEndpoint endpoint, GrpcEndpointOptions options) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _options = options ?? throw new ArgumentNullException(nameof(options)); _headerFilter = endpoint.HeaderFilterStrategy; } private readonly IHeaderFilterStrategy _headerFilter; /// protected override IEndpoint ProducerEndpoint => _endpoint; /// protected override string ProducerName => $"grpc:{_endpoint.BuildProducerAddress()}{_options.MethodPath}"; /// protected override Task ConnectAsync(CancellationToken ct) { var address = _endpoint.BuildProducerAddress(); var channelOptions = new GrpcChannelOptions(); if (_options.MaxSendMessageSize > 0) channelOptions.MaxSendMessageSize = _options.MaxSendMessageSize; if (_options.MaxReceiveMessageSize > 0) channelOptions.MaxReceiveMessageSize = _options.MaxReceiveMessageSize; // mTLS: present our certificate to the server. if (!string.IsNullOrEmpty(_options.ClientCertPath)) { var handler = new SocketsHttpHandler { EnableMultipleHttp2Connections = true }; handler.SslOptions.ClientCertificates = [LoadClientCertificate()]; channelOptions.HttpHandler = handler; } _channel = GrpcChannel.ForAddress(address, channelOptions); _invoker = _channel.CreateCallInvoker(); var (service, method) = SplitMethod(_options.MethodPath); _method = new Method( _options.Streaming ? MethodType.ServerStreaming : MethodType.Unary, service, method, ByteMarshaller, ByteMarshaller); return Task.CompletedTask; } private X509Certificate2 LoadClientCertificate() { return X509CertificateLoader.LoadPkcs12FromFile(_options.ClientCertPath!, _options.ClientCertPassword); } /// /// Whether a header name can travel as gRPC metadata: lowercase alphanumerics, underscore, hyphen and /// dot, and not the -bin suffix, which the protocol reserves for byte-valued entries. Mirrors /// what validates, so the check here and the throw there cannot disagree. /// private static bool IsSendableMetadataKey(string key) { if (key.EndsWith("-bin", StringComparison.Ordinal)) return false; foreach (var c in key) { var allowed = c is >= 'a' and <= 'z' or >= '0' and <= '9' or '_' or '-' or '.'; if (!allowed) return false; } return true; } private static (string Service, string Method) SplitMethod(string methodPath) { var trimmed = methodPath.TrimStart('/'); var slash = trimmed.LastIndexOf('/'); return slash < 0 ? (trimmed, string.Empty) : (trimmed[..slash], trimmed[(slash + 1)..]); } /// protected override Task DisconnectAsync(CancellationToken ct) { if (_channel is not null) { _channel.Dispose(); _channel = null; _invoker = null; _method = null; } return Task.CompletedTask; } /// public override async Task Process(IExchange exchange, CancellationToken ct = default) { EnsureStarted(); using var activity = RouteTelemetryExtensions.StartTransportSpan( (_endpoint.Component as ComponentBase)?.Context, "grpc.invoke", ActivityKind.Client, "rpc.system", "grpc", _endpoint.Uri.NormalizedKey); var request = BuildRequest(exchange); var callOptions = new CallOptions(cancellationToken: ct); // Deadline: expression > static var deadline = _options.Deadline; if (_options.DeadlineExpression is not null) { var resolved = _options.ResolveOption(_options.DeadlineExpression, exchange); if (resolved is not null && int.TryParse(resolved, out var parsedDeadline)) deadline = parsedDeadline; } if (deadline > 0) callOptions = callOptions.WithDeadline(DateTime.UtcNow.AddMilliseconds(deadline)); // Add exchange headers as gRPC metadata var metadata = new Metadata(); foreach (var (key, value) in exchange.In.Headers) { if (value is null) continue; // gRPC metadata keys must be lowercase ASCII var metaKey = key.ToLowerInvariant(); if (metaKey.StartsWith("grpc-")) continue; // reserved if (_headerFilter.FilterOutgoing(key, value, exchange)) continue; // Exchange headers are whatever upstream put there: copied HTTP request headers, keys a // processor derived from data. gRPC's alphabet is far narrower, and Metadata.Add throws on // anything outside it — including a perfectly legal HTTP name like `trace-bin`, where the // suffix promises a binary value. This loop runs before the try below, so one such header // took the whole call down with an ArgumentException that carried no status and never // reached .OnException / retry / dead-letter. Losing a header the wire cannot express is // recoverable; losing the call is not. if (!IsSendableMetadataKey(metaKey)) { Logger?.LogDebug( "gRPC: header '{Key}' is not a valid metadata key and was not sent with the call", key); continue; } metadata.Add(metaKey, value.ToString() ?? string.Empty); } // The context of this call, over a traceparent the header bridge copied from an incoming request: that one // names the previous hop, and the HTTP handler under Grpc.Net.Client does not overwrite a trace header already // on the request. Metadata keeps repeated keys, so the copied entries go first. RouteTelemetryExtensions.InjectTraceContext(activity, metadata, static (m, name, value) => { while (m.Get(name) is { } copied) m.Remove(copied); m.Add(name, value); }); // Grpc.Net.Client compresses a request when this metadata entry is present; the server then reads // grpc-encoding off the wire. We only ask for it when the endpoint opted in. if (_options.Compression == GrpcCompression.Gzip) metadata.Add("grpc-internal-encoding-request", "gzip"); if (metadata.Count > 0) callOptions = callOptions.WithHeaders(metadata); try { if (_options.Streaming) { // Server-streaming call: the reply is an IAsyncEnumerable, the framework's streaming // shape. It flows straight into a streaming consumer (the HTTP one turns it into SSE or // chunked output) without ever being buffered here. var streamingCall = _invoker!.AsyncServerStreamingCall(_method!, host: null, callOptions, request); exchange.Out = new Message(ReadStream(streamingCall, ct)); exchange.Out.Headers[GrpcHeaders.StatusCode] = (int)StatusCode.OK; return; } using var call = _invoker!.AsyncUnaryCall(_method!, host: null, callOptions, request); var response = await call.ResponseAsync.ConfigureAwait(false); exchange.Out = BuildOutMessage(response, exchange); exchange.Out.Headers[GrpcHeaders.StatusCode] = (int)StatusCode.OK; } catch (RpcException rpcEx) { activity.RecordFailure(rpcEx); Logger?.LogError(rpcEx, "gRPC call failed: endpoint={Endpoint}{Method}, status={StatusCode}, detail={Detail}", _endpoint.BuildProducerAddress(), _options.MethodPath, rpcEx.StatusCode, rpcEx.Status.Detail); exchange.In.Headers[GrpcHeaders.StatusCode] = (int)rpcEx.StatusCode; exchange.In.Headers[GrpcHeaders.StatusDetail] = rpcEx.Status.Detail; exchange.Exception = rpcEx; // Same contract as the HTTP and SOAP producers: a failed call must reach .OnException(...), // retry and dead-letter. Without the throw the pipeline simply carried on with an empty Out // and the failure was visible only in metrics. if (_options.ThrowOnError) throw; } } /// /// Lazily yields the messages of a server-streaming call, one element per frame, and disposes the /// call when the consumer stops reading. Envelope mode unwraps each frame's payload; raw mode yields /// the bytes. /// private async IAsyncEnumerable ReadStream( AsyncServerStreamingCall call, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken ct) { using (call) { while (true) { bool advanced; try { advanced = await call.ResponseStream.MoveNext(ct).ConfigureAwait(false); } catch (RpcException ex) { // A server-streaming call reports failure while the consumer is enumerating — long // after Process returned. So .OnException, retry and dead-letter cannot see it, and // that boundary is inherent to lazy streaming rather than something to paper over. // What is not inherent is the failure being invisible: without this, a stream that // broke every time looked exactly like a stream that ended early. Record it, then // rethrow — the reader still has to learn the stream did not finish. _endpoint.RecordError(ex); Logger?.LogError(ex, "gRPC server stream failed: endpoint={Endpoint}{Method}, status={StatusCode}, detail={Detail}", _endpoint.BuildProducerAddress(), _options.MethodPath, ex.StatusCode, ex.Status.Detail); throw; } if (!advanced) break; var frame = call.ResponseStream.Current; yield return _options.UseEnvelope ? RedbMessage.Parser.ParseFrom(frame).Payload.ToByteArray() : frame; } } } /// /// Turns the reply bytes into the exchange's Out message; the envelope headers come in as the endpoint's strategy /// lets them, against the request . /// private Message BuildOutMessage(byte[] response, IExchange exchange) { if (!_options.UseEnvelope) return new Message(response.Length == 0 ? null : response); var envelope = RedbMessage.Parser.ParseFrom(response); var outMessage = new Message(envelope.Payload.IsEmpty ? null : envelope.Payload.ToByteArray()); foreach (var (key, value) in envelope.Headers) { if (_headerFilter.FilterIncoming(key, value, exchange)) continue; outMessage.Headers[key] = value; } if (envelope.Headers.TryGetValue("Content-Type", out var contentType)) outMessage.ContentType = contentType; return outMessage; } /// /// Builds the request bytes. Envelope mode wraps body and headers in a RedbMessage; raw mode /// sends the body untouched, which is what a typed service on the far side expects. /// private byte[] BuildRequest(IExchange exchange) { if (!_options.UseEnvelope) return GrpcWire.ToBytes(exchange.In.Body); var request = new RedbMessage(); if (exchange.In.Body is not null) { request.Payload = exchange.In.Body switch { byte[] bytes => ByteString.CopyFrom(bytes), string str => ByteString.CopyFromUtf8(str), _ => ByteString.CopyFromUtf8(BodyText.Of(exchange.In.Body)) }; } // Exchange headers → envelope headers, as the endpoint's strategy lets them out foreach (var (key, value) in exchange.In.Headers) { if (value is null) continue; if (_headerFilter.FilterOutgoing(key, value, exchange)) continue; request.Headers[key] = value.ToString() ?? string.Empty; } // Propagate ContentType as a proto header if set if (!string.IsNullOrEmpty(exchange.In.ContentType)) request.Headers["Content-Type"] = exchange.In.ContentType; return request.ToByteArray(); } } Path: redb-route/redb.Route.Grpc/GrpcWire.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/GrpcWire.cs ---- using System.Buffers.Binary; using System.Globalization; using System.IO.Compression; using System.Net; using System.Net.Sockets; using System.Text; using Grpc.Core; using Microsoft.AspNetCore.Http; namespace redb.Route.Grpc; /// /// The gRPC wire protocol over HTTP/2, implemented here rather than taken from the /// Grpc.AspNetCore server stack. /// /// Reason: redb.Route hosts every HTTP-based transport (Http, As2, Soap) as a plain path route on the /// shared Kestrel host and speaks the protocol itself. MapGrpcService would instead demand /// ASP.NET service registration and endpoint routing wired before the host is built, which /// forces one gRPC endpoint per port, a host restart on every hot-reload, and a header-based route /// selector instead of the method address. Owning the framing keeps a gRPC route exactly what every /// other route is: a URI, an endpoint, a consumer. /// /// /// Framing (gRPC over HTTP/2): a message is [1 byte compressed-flag][4 bytes length, big-endian] /// [message bytes], repeated for streams. Request path is /package.Service/Method, /// content-type is application/grpc(+proto). The HTTP status is always 200 — the real /// outcome travels in the grpc-status / grpc-message trailers. A caller deadline arrives /// as grpc-timeout. /// /// internal static class GrpcWire { /// Base content type of a gRPC message stream. public const string ContentType = "application/grpc"; /// Protobuf-qualified content type; what generated clients send. public const string ProtoContentType = "application/grpc+proto"; public const string StatusTrailer = "grpc-status"; public const string MessageTrailer = "grpc-message"; public const string TimeoutHeader = "grpc-timeout"; public const string EncodingHeader = "grpc-encoding"; public const string AcceptEncodingHeader = "grpc-accept-encoding"; /// Size of the length-prefix that precedes every message on the wire. public const int PrefixLength = 5; /// True when the content type belongs to a gRPC call (any sub-format). public static bool IsGrpcContentType(string? contentType) => contentType is not null && contentType.StartsWith(ContentType, StringComparison.OrdinalIgnoreCase); // ── reading ────────────────────────────────────────────── /// Message encodings we can decode and advertise in grpc-accept-encoding. public const string SupportedEncodings = "identity,gzip"; /// /// Reads one length-prefixed message, decompressing it when the caller set the compressed flag and /// declared a codec we support. Returns null at a clean end of stream (no more messages), /// which is how a client signals it is done sending. /// /// /// Truncated prefix/body, an unsupported codec, or a message above /// either on the wire or after decompression. /// public static async Task ReadMessageAsync( Stream body, int maxMessageSize, string? requestEncoding, CancellationToken ct) { var prefix = new byte[PrefixLength]; var read = await ReadExactAsync(body, prefix, ct).ConfigureAwait(false); if (read == 0) return null; // clean end of stream if (read < PrefixLength) throw new GrpcProtocolException(StatusCode.Internal, "Truncated gRPC message prefix."); var compressed = prefix[0] != 0; if (compressed && !IsGzip(requestEncoding)) throw new GrpcProtocolException(StatusCode.Unimplemented, $"Unsupported grpc-encoding '{requestEncoding ?? "(none)"}'. Supported: {SupportedEncodings}."); var length = BinaryPrimitives.ReadUInt32BigEndian(prefix.AsSpan(1, 4)); if (maxMessageSize > 0 && length > (uint)maxMessageSize) throw new GrpcProtocolException(StatusCode.ResourceExhausted, $"Received message exceeds the limit of {maxMessageSize} bytes."); if (length == 0) return []; var payload = new byte[length]; var got = await ReadExactAsync(body, payload, ct).ConfigureAwait(false); if (got < payload.Length) throw new GrpcProtocolException(StatusCode.Internal, "Truncated gRPC message body."); if (!compressed) return payload; // The size limit is re-checked after inflation: the on-wire check alone would let a small // compressed frame expand into an arbitrarily large buffer. return Decompress(payload, maxMessageSize); } /// True when the encoding names gzip (the one codec we implement). public static bool IsGzip(string? encoding) => encoding is not null && encoding.Contains("gzip", StringComparison.OrdinalIgnoreCase); private static byte[] Decompress(byte[] payload, int maxMessageSize) { using var input = new MemoryStream(payload, writable: false); using var gzip = new GZipStream(input, CompressionMode.Decompress); using var output = new MemoryStream(); var buffer = new byte[8192]; int chunk; while ((chunk = gzip.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, chunk); if (maxMessageSize > 0 && output.Length > maxMessageSize) throw new GrpcProtocolException(StatusCode.ResourceExhausted, $"Decompressed message exceeds the limit of {maxMessageSize} bytes."); } return output.ToArray(); } private static byte[] Compress(byte[] payload) { using var output = new MemoryStream(); using (var gzip = new GZipStream(output, CompressionLevel.Fastest, leaveOpen: true)) gzip.Write(payload, 0, payload.Length); return output.ToArray(); } private static async Task ReadExactAsync(Stream stream, byte[] buffer, CancellationToken ct) { var offset = 0; while (offset < buffer.Length) { var read = await stream.ReadAsync(buffer.AsMemory(offset), ct).ConfigureAwait(false); if (read == 0) break; offset += read; } return offset; } // ── writing ────────────────────────────────────────────── /// /// Writes one length-prefixed message and flushes it (a stream consumer must see it now). /// With the payload is gzipped and the compressed flag is set — only ever /// called when the caller advertised gzip in grpc-accept-encoding. /// public static async Task WriteMessageAsync( HttpResponse response, byte[] payload, bool compress, CancellationToken ct) { if (compress) payload = Compress(payload); var frame = new byte[PrefixLength + payload.Length]; frame[0] = compress ? (byte)1 : (byte)0; BinaryPrimitives.WriteUInt32BigEndian(frame.AsSpan(1, 4), (uint)payload.Length); payload.CopyTo(frame, PrefixLength); await response.Body.WriteAsync(frame, ct).ConfigureAwait(false); await response.Body.FlushAsync(ct).ConfigureAwait(false); } /// /// Writes the terminating status. Called exactly once per call, after any messages. When nothing has /// been written yet this produces a valid "trailers-only" response, which is what clients expect for /// a failure with no payload. /// public static void WriteStatus(HttpResponse response, StatusCode status, string? detail = null) { response.AppendTrailer(StatusTrailer, ((int)status).ToString(CultureInfo.InvariantCulture)); if (!string.IsNullOrEmpty(detail)) response.AppendTrailer(MessageTrailer, PercentEncode(detail!)); } /// /// Percent-encodes a status message per the gRPC spec (ASCII outside 0x20..0x7E and % itself /// are escaped as UTF-8 bytes). Over-escaping is allowed and lossless, so the standard escaper is /// used rather than a hand-rolled table. /// private static string PercentEncode(string message) => Uri.EscapeDataString(message); // ── deadlines ──────────────────────────────────────────── /// /// Parses the caller's grpc-timeout (<digits><unit>, units /// H/M/S/m/u/n). Returns null when absent or unparsable — an unreadable deadline must never /// fail the call, it just means we do not enforce one. /// public static TimeSpan? ParseTimeout(string? value) { if (string.IsNullOrWhiteSpace(value) || value!.Length < 2) return null; var unit = value[^1]; if (!long.TryParse(value.AsSpan(0, value.Length - 1), NumberStyles.None, CultureInfo.InvariantCulture, out var amount) || amount < 0) return null; try { return unit switch { 'H' => TimeSpan.FromHours(amount), 'M' => TimeSpan.FromMinutes(amount), 'S' => TimeSpan.FromSeconds(amount), 'm' => TimeSpan.FromMilliseconds(amount), // `checked`: the multiply is on a caller-supplied long, and wrapping it produced a // NEGATIVE tick count — a deadline that either cancels the call at once or makes // CancelAfter throw. Overflow here means "unreadable", which is the null case below. 'u' => TimeSpan.FromTicks(checked(amount * (TimeSpan.TicksPerMillisecond / 1000))), 'n' => TimeSpan.FromTicks(Math.Max(1, amount / 100)), _ => null, }; } // Both, because the two failure modes look nothing alike from here: the multiply above raises // OverflowException, while TimeSpan.FromHours and friends raise ArgumentOutOfRangeException for // an amount they cannot represent. Catching only the first let a crafted `9223372036854775807H` // escape this method entirely — and the consumer parses the deadline BEFORE its own try-block, // so the request died at the host instead of answering a status. catch (Exception ex) when (ex is OverflowException or ArgumentOutOfRangeException) { return null; } } // ── status mapping ─────────────────────────────────────── /// /// Maps the transport-neutral status.code that controllers and processors write (an /// HTTP-shaped int — see redb.Route.Controllers) onto a gRPC status. Keeps a gRPC route /// behaving like the HTTP one without every processor learning a second vocabulary. /// public static StatusCode FromHttpStatus(int httpStatus) => httpStatus switch { >= 200 and <= 299 => StatusCode.OK, 400 or 422 => StatusCode.InvalidArgument, 401 => StatusCode.Unauthenticated, 403 => StatusCode.PermissionDenied, 404 => StatusCode.NotFound, 405 or 501 => StatusCode.Unimplemented, 409 => StatusCode.AlreadyExists, 412 or 428 => StatusCode.FailedPrecondition, 429 => StatusCode.ResourceExhausted, 499 => StatusCode.Cancelled, 503 => StatusCode.Unavailable, 504 => StatusCode.DeadlineExceeded, >= 500 => StatusCode.Internal, _ => StatusCode.Unknown, }; /// /// Maps an unhandled exception onto a status. keeps its own status so a /// processor can be explicit; cancellation splits into deadline vs. caller-abort. /// /// /// Identifier the caller may quote (the exchange id). An unhandled exception's own text never goes /// out as the status detail: it is written by whoever threw it and routinely carries a file path, a /// connection string or the name of an inner service (BR-4). The exception is logged by the consumer /// under the same id. Statuses the framework itself chose — an the route /// raised deliberately, a protocol error, a deadline, a cancellation — keep their text: it is ours. /// public static (StatusCode Status, string Detail) FromException(Exception ex, bool deadlineExceeded, string? reference = null) => ex switch { RpcException rpc => (rpc.StatusCode, rpc.Status.Detail), GrpcProtocolException gpe => (gpe.Status, gpe.Message), OperationCanceledException when deadlineExceeded => (StatusCode.DeadlineExceeded, "Deadline exceeded."), OperationCanceledException => (StatusCode.Cancelled, "Call cancelled."), _ => (StatusCode.Internal, reference is null ? "An unexpected error occurred while processing the request." : $"An unexpected error occurred while processing the request (ref: {reference})."), }; // ── header hygiene (G3) ────────────────────────────────── /// /// Prefixes owned by transports. A client must never be able to forge these: processors upstream /// trust redbHttp.RemoteAddress for rate-limiting, redbGrpc.* for call metadata, and /// so on. Inbound keys carrying one of these prefixes are dropped before the exchange sees them. /// private static readonly string[] ReservedPrefixes = [ "redbGrpc.", "redbHttp.", "redbSoap.", "redbSignalR.", "redbMail.", "redbAs2.", ]; /// True when a caller-supplied header key belongs to a transport and must be dropped. public static bool IsReservedKey(string key) { foreach (var prefix in ReservedPrefixes) { if (key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) return true; } return false; } /// /// Formats a connection endpoint the way gRPC names peers (ipv4:10.0.0.5:51234, /// ipv6:[::1]:5). Kept because redbGrpc.RemotePeer has carried that shape since the /// connector's first release; the bare address lives in redbGrpc.RemoteIp. /// public static string FormatPeer(IPAddress address, int port) { if (address.AddressFamily == AddressFamily.InterNetworkV6 && !address.IsIPv4MappedToIPv6) return $"ipv6:[{address}]:{port}"; var v4 = address.IsIPv4MappedToIPv6 ? address.MapToIPv4() : address; return $"ipv4:{v4}:{port}"; } /// /// Encodes a reply body for the wire. Only bytes and strings are payloads. /// /// Anything else is refused rather than run through ToString(): a route that answers with, say, /// a dictionary would otherwise put the literal text /// System.Collections.Generic.Dictionary`2[…] on the wire and the caller would receive garbage /// with an OK status. That silent-stringification failure is exactly the one the SOAP consumer shipped /// with byte[]; a loud Internal naming the type is strictly better than plausible nonsense. /// /// public static byte[] ToBytes(object? body) => body switch { null => [], byte[] bytes => bytes, string text => Encoding.UTF8.GetBytes(text), _ => throw new GrpcProtocolException(StatusCode.Internal, $"Route replied with {body.GetType().FullName}, which is not a gRPC payload. " + "Encode it to bytes or a string before the reply leaves the route."), }; } /// /// A violation of the gRPC wire contract by the caller (bad framing, unsupported compression, /// oversized message). Carries the status the caller should see. /// internal sealed class GrpcProtocolException(StatusCode status, string message) : Exception(message) { /// Status reported to the caller in the grpc-status trailer. public StatusCode Status { get; } = status; } Path: redb-route/redb.Route.Grpc/Protos/redb_service.proto 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/Protos/redb_service.proto ---- syntax = "proto3"; option csharp_namespace = "redb.Route.Grpc.Proto"; package redb.route.grpc; // Generic ESB service for exchanging messages through the route pipeline. service RedbService { // Unary request-response. rpc Process (RedbMessage) returns (RedbMessage); // Server-side streaming (consumer pushes multiple responses). rpc ProcessStream (RedbMessage) returns (stream RedbMessage); } // Generic message carrying binary payload and string headers. message RedbMessage { // Binary payload (exchange body). bytes payload = 1; // String key-value headers (exchange headers). map headers = 2; } Path: redb-route/redb.Route.Grpc/README.md 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/README.md ---- # redb.Route.Grpc > Documentation and articles: gRPC transport for redb.Route. A gRPC **method address is a route**: the consumer registers `/package.Service/Method` as a path route on the shared Kestrel host, so many methods live on one port as ordinary routes with their own ids, policies and metrics. The producer calls any method address with a `GrpcChannel`. [![NuGet](https://img.shields.io/nuget/v/redb.Route.Grpc?label=NuGet&color=blue)](https://www.nuget.org/packages/redb.Route.Grpc) [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue)](../../LICENSE) ## Installation ```bash dotnet add package redb.Route.Grpc ``` ## Usage ```csharp using redb.Route.Grpc; // One port, three methods — three routes. From(GrpcDsl.Listen("0.0.0.0:5001").Method("/identity.v1.Identity/Token")) .RouteId("grpc-token") .To("direct-vm://identity-token"); From(GrpcDsl.Listen("0.0.0.0:5001").Method("/identity.v1.Identity/Introspect")) .RouteId("grpc-introspect") .To("direct-vm://identity-introspect"); // The built-in generic service (headers + payload envelope), unchanged. From(GrpcDsl.Listen("0.0.0.0:5001")) .Process(exchange => exchange.In.Body = Handle((byte[])exchange.In.Body!)); // Client. From("direct://send") .To(GrpcDsl.Call("grpc-service:5001") .Method("/identity.v1.Identity/Token") .Plaintext() .Deadline(5000)); ``` ## How it works The connector implements the gRPC wire protocol itself (`GrpcWire`) instead of taking the `Grpc.AspNetCore` server stack, and serves on the same `SharedHttpServerManager` as the HTTP, AS2 and SOAP transports. That server stack would need `AddGrpc()` / `MapGrpcService()` wired into an ASP.NET host *before* it is built, which forces one gRPC endpoint per port, a host restart on hot-reload, and a header-based route selector instead of the method address. Owning the framing keeps a gRPC route what every other route is: a URI, an endpoint, a consumer. On the wire: `[1 byte compressed-flag][4 bytes length BE][message]`, content-type `application/grpc`, HTTP status always 200, the real outcome in the `grpc-status` / `grpc-message` trailers, caller deadline in `grpc-timeout`. ## Compression Gzipped requests are always accepted and inflated (the size limit is re-checked after inflation, so a small frame cannot expand into an arbitrarily large buffer). Replies are compressed only with `.Compression(GrpcCompression.Gzip)` **and** only when the caller advertised gzip in `grpc-accept-encoding`; we always advertise `identity,gzip` back. An unknown codec is answered with `Unimplemented` rather than a parse failure. On the client side `.Compression(...)` gzips outgoing requests. ## Statuses A route answers with a status the client actually sees: | Source on `Out` | Result | |---|---| | `redbGrpc.StatusCode` (+ `redbGrpc.StatusDetail`) | used as-is | | `status.code` — what every controller dispatcher writes | mapped (401 → `Unauthenticated`, 403 → `PermissionDenied`, 404 → `NotFound`, 409 → `AlreadyExists`, 429 → `ResourceExhausted`, 503 → `Unavailable`, 504 → `DeadlineExceeded`, other 5xx → `Internal`) | | neither | `OK` | | unhandled exception | `RpcException` keeps its status; cancellation splits into `DeadlineExceeded` / `Cancelled`; anything else is `Internal` | `redbGrpc.Trailer.*` headers become response trailers. A non-OK status is sent trailers-only, because gRPC clients discard the payload of a failed call. `suppressStatusMapping=true` restores the old always-`OK`-plus-error-document behaviour. ## Typed `.proto` services `Envelope=Auto` (default) wraps only the built-in address in the generic `RedbMessage`; any other address receives the caller's protobuf bytes untouched. So a client generated from a real `.proto` can call a redb route with no generated server stubs on our side — the route decodes the message with its own codec. `.Envelope(GrpcEnvelopeMode.Message | Raw)` forces either behaviour. ## Streaming An `IAsyncEnumerable` reply body is written one frame per yield — the framework's own streaming shape, the same one the HTTP consumer honours for chunked and SSE replies. Enabled by default on the built-in `ProcessStream` address, opt-in elsewhere with `.Streaming()`. A collection body (`List`) stays one message, as it is for every other transport. A stream body on a **unary** address is a hard error naming the address — a unary call carries exactly one message, so silently sending the enumerable's type name would be worse. The producer streams too: `.Streaming()` on a client endpoint makes the call server-streaming and puts an `IAsyncEnumerable` into `Out.Body`, so a gRPC stream flows straight into a streaming consumer (the HTTP one turns it into SSE or chunked output) without being buffered in between. ## Fluent Builder API | Category | Methods | |----------|---------| | **Address** | `GrpcDsl.Listen()`, `GrpcDsl.Call()`, `.Method()`, `.Service(service, method)`, `.Host()`, `.Port()` | | **Server** | `.InOut()`, `.Streaming()`, `.Health()`, `.MaxRequestMessageSize()`, `.EmitHttpCompatHeaders()`, `.AllowClientReservedHeaders()`, `.SuppressStatusMapping()` | | **Client** | `.Plaintext()`, `.Deadline()`, `.ThrowOnError()`, `.MaxSendMessageSize()`, `.MaxReceiveMessageSize()`, `.ClientCertificate()` | | **Security** | `.Ssl()`, `.SslCertPath()`, `.SslCertPassword()`, `.ClientCertificates()`, `.ConnectionFactory()`, `.NegotiationType()` | | **Sizes** | `.MaxMessageSize()` | ## Headers | Header | Direction | Meaning | |---|---|---| | `redbGrpc.Route` / `.Service` / `.Method` | in | method address the call arrived on, split | | `redbGrpc.RemoteIp` / `.RemotePort` | in | client address, bare | | `redbGrpc.RemotePeer` | in | gRPC-style peer (`ipv4:10.0.0.5:51234`) | | `redbGrpc.Authority` / `.Deadline` / `.Port` | in | call metadata | | `redbGrpc.ClientCert*` | in | client certificate, when mTLS is on | | `redbGrpc.StatusCode` / `.StatusDetail` | out | status returned to the caller | | `redbGrpc.Trailer.*` | out | response trailers | Inbound headers carrying a transport-reserved prefix (`redbHttp.`, `redbGrpc.`, `redbSoap.`, …) are dropped: a caller must not be able to forge the metadata upstream processors trust, such as the client IP that drives rate limiting. `allowClientReservedHeaders=true` opts out, and says so in the log. `headerFilterStrategy=#name` names an `IHeaderFilterStrategy` in the registry that decides which headers cross, as in Apache Camel: on a producer, which exchange headers go out as call metadata and envelope headers and which reply envelope headers come back; on a consumer, which request headers come in and which go out in the reply envelope. It replaces the default, `GrpcHeaderFilterStrategy` (keeps `redbGrpc.*` back), entirely; derive from that class to add to it. The reserved prefixes above, `grpc-*`, the pseudo-headers, the call metadata the consumer sets and the `redbGrpc.Trailer.*` trailers are not the strategy's. ```csharp ctx.AddToRegistry("correlationOnly", new DefaultHeaderFilterStrategy { OutFilter = ["Correlation-ID"], FilterOnMatch = false, // a whitelist: only the listed headers go out }); // grpc://billing:5001?plaintext=true&headerFilterStrategy=#correlationOnly ``` ## Apache Camel parity | camel-grpc | redb.Route.Grpc | |---|---| | `grpc://host:port/service?method=` | same, plus the full-address form `grpc:host:port/pkg.Service/Method` | | `maxMessageSize` | `maxMessageSize` (or per-direction `maxSend`/`maxReceive`/`maxRequestMessageSize`) | | `negotiationType=PLAINTEXT\|TLS` | `negotiationType`, or `plaintext` / `ssl` | | `keyCertChainResource`, `keyResource`, `trustCertCollectionResource` | `sslCertPath` + `sslCertPassword` (PFX — the .NET idiom), `clientCertificateMode`, `allowedClientThumbprints` | | `producerStrategy=SIMPLE` / `STREAMING` | unary by default, `.Streaming()` for a server-streaming call | | `consumerStrategy=AGGREGATION\|PROPAGATION` | n/a — the consumer serves unary and server-streaming; client-streaming is not implemented | | `forwardOnCompleted`, `forwardOnError` | n/a — same reason | | `flowControlWindow`, `maxConcurrentCallsPerConnection` | not exposed: they are Kestrel listener limits on the shared host | | gzip compression | `.Compression(GrpcCompression.Gzip)`; inbound gzip always accepted | | gRPC server reflection | not served — reflection needs the descriptor set of the `.proto` the routes speak, which belongs to the module that owns it | ## Interop Because the wire protocol is ours, the connector is verified against an independent stack: a Node.js `@grpc/grpc-js` server and client in a container (profile `grpc` of the test stand), both directions, cross-process, covering statuses, server streaming, gzip and a real mTLS handshake with a client certificate. The contract there is a typed `.proto`, so it also proves a generated client can call a redb route with no server stubs on our side. ```bash bash tests/docker/gen-certs.sh # once: the test certificates docker compose -f docker-compose.tests.yml --profile grpc up -d --wait dotnet test tests/redb.Route.Tests.Grpc --filter Category=Interop docker compose -f docker-compose.tests.yml --profile grpc down -v ``` The tests are gated on the container being reachable, so the normal suite stays green without Docker. ## Part of [redb.Route](../README.md) — ESB & EIP Framework for .NET ## Named connection factory Keep credentials out of the route URI: register a factory in the context registry and reference it by name. A set-but-unknown name fails loud at startup — a typo can never silently fall back to inline URI parameters. ```csharp context.AddToRegistry("prod", new GrpcConnectionFactory { Ssl = true, SslCertPath = "/secrets/client.pfx", SslCertPassword = secrets.CertPassword, }); // grpc://inventory.internal:5005/Inventory?connectionFactory=prod ``` ## Concurrency limits Kestrel executes as many handlers as requests arrive; without a limit a route has no ceiling. The admission limit caps concurrent pipeline executions per endpoint and sheds the overflow BEFORE any pipeline work (load shedding, not backpressure): | Parameter | Default | Description | |---|---|---| | `maxConcurrentRequests` | `0` (unlimited) | Max concurrent pipeline executions | | `requestQueueLimit` | `0` | Requests over the limit that WAIT (FIFO) instead of being rejected | | `rejectStatusCode` | `429` | Status for a shed request | | `retryAfterSeconds` | `1` | `Retry-After` header value; `0` = do not send | A shed request is answered before an exchange exists: it appears in the endpoint's `Rejected` counter, not in `MessagesIn` or `Errors`. The limit is strictly per endpoint — other routes on the same listener keep their own budget. For "slow down but do not drop" semantics use `.Threads(n)` in the route instead; the two compose (the limit sheds at the door, Threads paces inside). gRPC specifics: the limit counts **unary** calls only. A streaming call would hold a permit for its whole life and starve the limit, and a shed health probe would flap orchestrators — both are deliberately outside the limit. ## Tracing On the `redb.Route` activity source (`AddSource("redb.Route")`), both spans with `rpc.system = grpc` and `redb.route.endpoint`: - **Consumer.** One `Server` span per call, `grpc receive`. Its parent is the host's ASP.NET Core span when the application instruments ASP.NET Core, otherwise the caller's `traceparent` metadata; without one it is a root. The caller's baggage is back on it, the route's spans are its children, and a failed call marks it an error. - **Producer.** One `Client` span per call, `grpc.invoke`; an error for a failed call. The call carries the context of this span: a `traceparent` the header bridge copied from an incoming request into the metadata is replaced, as it names the previous hop. - `RouteEngineOptions.EnableTelemetry = false` opens neither span. A context that came in still goes out. Path: redb-route/redb.Route.Grpc/redb.Route.Grpc.csproj 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/redb.Route.Grpc.csproj ---- redb.Route.Grpc gRPC transport for redb.Route ESB framework. Serves gRPC methods as path routes on the shared Kestrel host (one port, many methods) and calls them with a GrpcChannel-based producer. esb;messaging;grpc;protobuf;rpc;http2;redb README.md