Bundle: redb-route / tests/redb.Route.Tests.Grpc (tests.redb.Route.Tests.Grpc.txt), 22 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/tests/redb.Route.Tests.Grpc/GrpcBuilderTests.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/tests/redb.Route.Tests.Grpc/GrpcBuilderTests.cs ---- using redb.Route.Core; using redb.Route.Grpc; namespace redb.Route.Tests.Grpc; public class GrpcBuilderTests { // ── Factory ───────────────────────────────────────────────────── [Fact] public void Call_StartsWithGrpcScheme() { var uri = GrpcDsl.Call("localhost:50051").Build(); uri.Should().StartWith("grpc:localhost:50051"); } [Fact] public void Listen_StartsWithGrpcScheme() { var uri = GrpcDsl.Listen("0.0.0.0:50051").Build(); uri.Should().StartWith("grpc:0.0.0.0:50051"); } [Fact] public void NullHostPort_Throws() { var act = () => GrpcDsl.Call(null!); act.Should().Throw(); } [Fact] public void EmptyHostPort_Throws() { var act = () => GrpcDsl.Listen(""); act.Should().Throw(); } // ── Common ────────────────────────────────────────────────────── [Fact] public void Deadline_SetsParam() { var uri = GrpcDsl.Call("h:50051").Deadline(5000).Build(); uri.Should().Contain("deadline=5000"); } // ── Producer ──────────────────────────────────────────────────── [Fact] public void Plaintext_SetsParam() { var uri = GrpcDsl.Call("h:50051").Plaintext().Build(); uri.Should().Contain("plaintext=true"); } [Fact] public void MaxSendMessageSize_SetsParam() { var uri = GrpcDsl.Call("h:50051").MaxSendMessageSize(4096).Build(); uri.Should().Contain("maxSendMessageSize=4096"); } [Fact] public void MaxReceiveMessageSize_SetsParam() { var uri = GrpcDsl.Call("h:50051").MaxReceiveMessageSize(8192).Build(); uri.Should().Contain("maxReceiveMessageSize=8192"); } // ── Consumer ──────────────────────────────────────────────────── [Fact] public void Host_SetsParam() { var uri = GrpcDsl.Listen("0.0.0.0:50051").Host("127.0.0.1").Build(); uri.Should().Contain("host=127.0.0.1"); } [Fact] public void Port_SetsParam() { var uri = GrpcDsl.Listen("0.0.0.0:50051").Port(50052).Build(); uri.Should().Contain("port=50052"); } [Fact] public void Ssl_SetsParam() { var uri = GrpcDsl.Listen("0.0.0.0:50051").Ssl().Build(); uri.Should().Contain("ssl=true"); } [Fact] public void SslCertPath_SetsParam() { var uri = GrpcDsl.Listen("0.0.0.0:50051").SslCertPath("/certs/server.pfx").Build(); uri.Should().Contain("sslCertPath="); } [Fact] public void InOut_SetsParam() { var uri = GrpcDsl.Listen("0.0.0.0:50051").InOut().Build(); uri.Should().Contain("inOut=true"); } [Fact] public void MaxRequestMessageSize_SetsParam() { var uri = GrpcDsl.Listen("0.0.0.0:50051").MaxRequestMessageSize(16384).Build(); uri.Should().Contain("maxRequestMessageSize=16384"); } // ── Conversion ────────────────────────────────────────────────── [Fact] public void ImplicitConversion_ReturnsUri() { string uri = GrpcDsl.Call("h:50051").Plaintext().Deadline(10000); uri.Should().StartWith("grpc:h:50051?"); } [Fact] public void ToString_ReturnsSameAsBuild() { var builder = GrpcDsl.Call("h:50051").Plaintext(); builder.ToString().Should().Be(builder.Build()); } // ── Full chain ────────────────────────────────────────────────── [Fact] public void FullChain_Producer_BuildsCorrectUri() { var uri = GrpcDsl.Call("api.example.com:50051") .Plaintext() .Deadline(10000) .MaxSendMessageSize(4096) .MaxReceiveMessageSize(8192) .Build(); uri.Should().StartWith("grpc:api.example.com:50051?"); uri.Should().Contain("plaintext=true"); uri.Should().Contain("deadline=10000"); } [Fact] public void FullChain_Consumer_BuildsCorrectUri() { var uri = GrpcDsl.Listen("0.0.0.0:50051") .Ssl() .SslCertPath("/certs/server.pfx") .SslCertPassword("pass") .MaxRequestMessageSize(16384) .InOut() .Build(); uri.Should().StartWith("grpc:0.0.0.0:50051?"); uri.Should().Contain("ssl=true"); uri.Should().Contain("inOut=true"); } // ── Round-trip ────────────────────────────────────────────────── [Fact] public void RoundTrip_ParseAndReconstruct() { var original = GrpcDsl.Call("h:50051").Plaintext().Deadline(5000).Build(); var parsed = EndpointUriParser.Parse(original); parsed.Scheme.Should().Be("grpc"); parsed.Path.Should().Contain("50051"); parsed.RawParameters["plaintext"].Should().Be("true"); parsed.RawParameters["deadline"].Should().Be("5000"); } } Path: redb-route/tests/redb.Route.Tests.Grpc/GrpcComponentTests.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/tests/redb.Route.Tests.Grpc/GrpcComponentTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Grpc; namespace redb.Route.Tests.Grpc; public class GrpcComponentTests { [Fact] public void Scheme_IsGrpc() { var component = new GrpcComponent(); component.Scheme.Should().Be("grpc"); } [Fact] public void CreateEndpoint_ReturnsGrpcEndpoint() { var component = new GrpcComponent(); var uri = new EndpointUri("grpc", "/localhost:50051", "grpc:localhost:50051", new Dictionary()); var endpoint = component.CreateEndpoint(uri); endpoint.Should().BeOfType(); } [Fact] public void CreateEndpoint_DefaultOptions() { var component = new GrpcComponent(); var uri = new EndpointUri("grpc", "/localhost:50051", "grpc:localhost:50051", new Dictionary()); var endpoint = (GrpcEndpoint)component.CreateEndpoint(uri); endpoint.EndpointOptions.Deadline.Should().Be(30_000); endpoint.EndpointOptions.Plaintext.Should().BeTrue(); endpoint.EndpointOptions.Port.Should().Be(50051); endpoint.EndpointOptions.Host.Should().Be("localhost"); endpoint.EndpointOptions.Ssl.Should().BeFalse(); endpoint.EndpointOptions.InOut.Should().BeTrue(); endpoint.EndpointOptions.MaxSendMessageSize.Should().Be(4 * 1024 * 1024); endpoint.EndpointOptions.MaxReceiveMessageSize.Should().Be(4 * 1024 * 1024); endpoint.EndpointOptions.MaxRequestMessageSize.Should().Be(4 * 1024 * 1024); } [Fact] public void CreateEndpoint_BindsUriParameters() { var component = new GrpcComponent(); var parameters = new Dictionary { ["deadline"] = "5000", ["plaintext"] = "false", ["port"] = "9999", ["host"] = "127.0.0.1", ["inOut"] = "false", ["maxSendMessageSize"] = "1048576", ["maxReceiveMessageSize"] = "2097152" }; var uri = new EndpointUri("grpc", "/localhost:9999", "grpc:localhost:9999", parameters); var endpoint = (GrpcEndpoint)component.CreateEndpoint(uri); endpoint.EndpointOptions.Deadline.Should().Be(5000); endpoint.EndpointOptions.Plaintext.Should().BeFalse(); endpoint.EndpointOptions.Port.Should().Be(9999); endpoint.EndpointOptions.Host.Should().Be("127.0.0.1"); endpoint.EndpointOptions.InOut.Should().BeFalse(); endpoint.EndpointOptions.MaxSendMessageSize.Should().Be(1048576); endpoint.EndpointOptions.MaxReceiveMessageSize.Should().Be(2097152); } [Fact] public void CreateEndpoint_InvalidPort_Throws() { var component = new GrpcComponent(); var parameters = new Dictionary { ["port"] = "70000" }; var uri = new EndpointUri("grpc", "/localhost:70000", "grpc:localhost:70000", parameters); var act = () => component.CreateEndpoint(uri); act.Should().Throw().WithMessage("*Port*"); } [Fact] public void CreateEndpoint_NegativeDeadline_Throws() { var component = new GrpcComponent(); var parameters = new Dictionary { ["deadline"] = "-1" }; var uri = new EndpointUri("grpc", "/localhost:50051", "grpc:localhost:50051", parameters); var act = () => component.CreateEndpoint(uri); act.Should().Throw().WithMessage("*Deadline*"); } [Fact] public void CreateEndpoint_SslWithoutCert_DefersToTheBind() { // The certificate may come from a named connection factory or from the host default // (HttpHostingOptions.Tls), which an endpoint cannot see. "TLS asked for and nothing // resolves" is enforced once, at the bind, by SharedHttpServerManager — see // SharedHostTlsTests, which asserts the listener refuses to open rather than serving // plaintext under an https:// banner. var component = new GrpcComponent(); var parameters = new Dictionary { ["ssl"] = "true" }; var uri = new EndpointUri("grpc", "/localhost:50051", "grpc:localhost:50051", parameters); var act = () => component.CreateEndpoint(uri); act.Should().NotThrow(); } [Fact] public void BuildProducerAddress_Plaintext_ReturnsHttp() { var component = new GrpcComponent(); var parameters = new Dictionary { ["plaintext"] = "true" }; var uri = new EndpointUri("grpc", "/localhost:50051", "grpc:localhost:50051", parameters); var endpoint = (GrpcEndpoint)component.CreateEndpoint(uri); endpoint.BuildProducerAddress().Should().Be("http://localhost:50051"); } [Fact] public void BuildProducerAddress_NoPlaintext_ReturnsHttps() { var component = new GrpcComponent(); var parameters = new Dictionary { ["plaintext"] = "false" }; var uri = new EndpointUri("grpc", "/localhost:50051", "grpc:localhost:50051", parameters); var endpoint = (GrpcEndpoint)component.CreateEndpoint(uri); endpoint.BuildProducerAddress().Should().Be("https://localhost:50051"); } [Fact] public void CreateProducer_ReturnsGrpcProducer() { var component = new GrpcComponent(); var uri = new EndpointUri("grpc", "/localhost:50051", "grpc:localhost:50051", new Dictionary()); var endpoint = component.CreateEndpoint(uri); var producer = endpoint.CreateProducer(); producer.Should().BeOfType(); } [Fact] public void CreateConsumer_ReturnsGrpcConsumer() { var component = new GrpcComponent(); var uri = new EndpointUri("grpc", "/localhost:50051", "grpc:localhost:50051", new Dictionary()); var endpoint = component.CreateEndpoint(uri); var processor = Substitute.For(); var consumer = endpoint.CreateConsumer(processor); consumer.Should().BeOfType(); } [Fact] public void CreateConsumer_NullProcessor_Throws() { var component = new GrpcComponent(); var uri = new EndpointUri("grpc", "/localhost:50051", "grpc:localhost:50051", new Dictionary()); var endpoint = component.CreateEndpoint(uri); var act = () => endpoint.CreateConsumer(null!); act.Should().Throw(); } } Path: redb-route/tests/redb.Route.Tests.Grpc/GrpcConcurrencyLimitTests.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/tests/redb.Route.Tests.Grpc/GrpcConcurrencyLimitTests.cs ---- using System.Net; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Grpc; namespace redb.Route.Tests.Grpc; /// /// Admission limit on the gRPC consumer: /// UNARY calls are counted, overflow is shed with an HTTP-level 429 before any /// pipeline work; streaming and health methods are deliberately outside the limit. /// public class GrpcConcurrencyLimitTests : IAsyncLifetime { private GrpcConsumer? _consumer; private int _port; public Task InitializeAsync() { _port = GetFreePort(); return Task.CompletedTask; } public async Task DisposeAsync() { if (_consumer is not null) await _consumer.Stop(); } private (GrpcConsumer Consumer, GrpcEndpoint Endpoint) CreateConsumer( Dictionary extra, Func onProcess) { var parameters = new Dictionary { ["host"] = "127.0.0.1", ["port"] = _port.ToString(), }; foreach (var (k, v) in extra) parameters[k] = v; var uri = new EndpointUri("grpc", $"/127.0.0.1:{_port}", $"grpc:127.0.0.1:{_port}", parameters); var endpoint = (GrpcEndpoint)new GrpcComponent().CreateEndpoint(uri); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => onProcess(ci.Arg())); _consumer = new GrpcConsumer(endpoint, processor, endpoint.EndpointOptions); return (_consumer, endpoint); } /// Raw h2c POST to the gRPC method path — the shed happens at the HTTP layer. private HttpClient H2cClient() => new(new SocketsHttpHandler()) { DefaultRequestVersion = HttpVersion.Version20, DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact, }; private Task PostUnary(HttpClient client) { var content = new ByteArrayContent(new byte[5]); // empty gRPC frame (flag 0 + length 0) content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/grpc"); return client.PostAsync( $"http://127.0.0.1:{_port}{GrpcEndpointOptions.DefaultMethodPath}", content); } [Fact] public async Task UnaryOverLimit_IsShedWith429_AndCountedAsRejected() { var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var processed = 0; var (consumer, endpoint) = CreateConsumer( new Dictionary { ["maxConcurrentRequests"] = "1" }, async _ => { Interlocked.Increment(ref processed); entered.TrySetResult(); await gate.Task; }); await consumer.Start(); using var client = H2cClient(); var first = PostUnary(client); await entered.Task.WaitAsync(TimeSpan.FromSeconds(5)); // the single permit is held var second = await PostUnary(client); second.StatusCode.Should().Be(HttpStatusCode.TooManyRequests, "a unary call over the limit is rejected at the HTTP level before the pipeline"); second.Headers.RetryAfter.Should().NotBeNull(); gate.SetResult(); (await first).StatusCode.Should().Be(HttpStatusCode.OK); processed.Should().Be(1, "a rejected call must not touch the pipeline"); endpoint.Rejected.Should().Be(1); endpoint.Errors.Should().Be(0, "a rejection is not a processing error"); } [Fact] public async Task HealthMethod_IsNotCounted_EvenWhenTheLimitIsSaturated() { var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var (consumer, _) = CreateConsumer( new Dictionary { ["maxConcurrentRequests"] = "1", ["health"] = "true", }, async _ => { entered.TrySetResult(); await gate.Task; }); await consumer.Start(); using var client = H2cClient(); var held = PostUnary(client); await entered.Task.WaitAsync(TimeSpan.FromSeconds(5)); // permit taken by the unary call var health = new ByteArrayContent(new byte[5]); health.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/grpc"); var probe = await client.PostAsync( $"http://127.0.0.1:{_port}/grpc.health.v1.Health/Check", health); probe.StatusCode.Should().Be(HttpStatusCode.OK, "the health probe is outside the limit: the orchestrator must not flap under load"); gate.SetResult(); await held; } [Fact] public void UriAndDsl_CarryTheOptions() { var built = GrpcDsl.Listen($"127.0.0.1:{_port}") .MaxConcurrentRequests(4, queue: 8) .RejectStatusCode(503) .RetryAfterSeconds(0) .Build(); built.Should().Contain("maxConcurrentRequests=4") .And.Contain("requestQueueLimit=8") .And.Contain("rejectStatusCode=503") .And.Contain("retryAfterSeconds=0"); var endpoint = (GrpcEndpoint)new GrpcComponent().CreateEndpoint(EndpointUriParser.Parse(built)); endpoint.EndpointOptions.MaxConcurrentRequests.Should().Be(4); endpoint.EndpointOptions.RequestQueueLimit.Should().Be(8); endpoint.EndpointOptions.RejectStatusCode.Should().Be(503); endpoint.EndpointOptions.RetryAfterSeconds.Should().Be(0); } private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); } Path: redb-route/tests/redb.Route.Tests.Grpc/GrpcConnectionFactoryTests.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/tests/redb.Route.Tests.Grpc/GrpcConnectionFactoryTests.cs ---- using redb.Route.Core; using redb.Route.Grpc; namespace redb.Route.Tests.Grpc; /// /// The TLS certificate password must be able to live in the registry instead of the endpoint URI, /// so it never reaches logs, telemetry, or the dashboard. /// public sealed class GrpcConnectionFactoryTests { private const string Secret = "pfxP4ssw0rd"; private static GrpcComponent Wire(string name, GrpcConnectionFactory factory) { var context = new RouteContext(); var component = new GrpcComponent(); context.AddComponent(component); context.AddToRegistry(name, factory); return component; } [Fact] public void Factory_SuppliesCertPassword_WhenUriCarriesNone() { var component = Wire("secure-grpc", new GrpcConnectionFactory { Ssl = true, SslCertPath = "/etc/redb/certs/server.pfx", SslCertPassword = Secret }); var uri = EndpointUriParser.Parse("grpc://0.0.0.0:50051?connectionFactory=secure-grpc"); var endpoint = component.CreateEndpoint(uri); endpoint.Should().NotBeNull(); uri.ToUriString().Should().NotContain(Secret); uri.ToString().Should().NotContain(Secret); } [Fact] public void ExplicitUriValue_WinsOverFactory() { var component = Wire("f", new GrpcConnectionFactory { Ssl = true, SslCertPath = "/from/factory.pfx" }); var uri = EndpointUriParser.Parse( "grpc://0.0.0.0:50051?connectionFactory=f&sslCertPath=/from/uri.pfx"); component.CreateEndpoint(uri).Should().NotBeNull(); uri.RawParameters["sslCertPath"].Should().Be("/from/uri.pfx"); } [Fact] public void MissingFactory_FailsLoud() { var context = new RouteContext(); var component = new GrpcComponent(); context.AddComponent(component); var uri = EndpointUriParser.Parse("grpc://0.0.0.0:50051?connectionFactory=absent"); var act = () => component.CreateEndpoint(uri); // A typo in connectionFactory must fail loud, not fall back silently act.Should().Throw() .Which.Message.Should().Contain("absent"); } } Path: redb-route/tests/redb.Route.Tests.Grpc/GrpcConsumerFeatureTests.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/tests/redb.Route.Tests.Grpc/GrpcConsumerFeatureTests.cs ---- using System.Net; using System.Net.Sockets; using Google.Protobuf; using Grpc.Core; using Grpc.Net.Client; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Grpc; using redb.Route.Grpc.Proto; namespace redb.Route.Tests.Grpc; /// /// Consumer behaviour introduced with the shared-host rewrite: real gRPC statuses, trailers, header /// hygiene, client address, per-method routing, streaming, health and the camel-grpc URI spelling. /// Every test drives a real , so these assert the wire, not our own bookkeeping. /// public sealed class GrpcConsumerFeatureTests : IAsyncLifetime { private readonly GrpcComponent _component = new(); private readonly List _consumers = []; private readonly List _channels = []; private int _port; public Task InitializeAsync() { _port = GetFreePort(); return Task.CompletedTask; } public async Task DisposeAsync() { foreach (var channel in _channels) channel.Dispose(); foreach (var consumer in _consumers) await consumer.Stop(); } // ── statuses (G2) ──────────────────────────────────────── [Fact] public async Task Neutral_status_code_becomes_a_real_grpc_status() { await Start(ex => { ex.Out = new Message("denied"); ex.Out.Headers["status.code"] = 403; // what every controller dispatcher writes return Task.CompletedTask; }); var act = async () => await Client().ProcessAsync(new RedbMessage()); var ex = await act.Should().ThrowAsync(); ex.Which.StatusCode.Should().Be(StatusCode.PermissionDenied); } [Fact] public async Task Explicit_grpc_status_wins_over_the_neutral_one() { await Start(ex => { ex.Out = new Message("nope"); ex.Out.Headers["status.code"] = 500; ex.Out.Headers[GrpcHeaders.StatusCode] = (int)StatusCode.ResourceExhausted; ex.Out.Headers[GrpcHeaders.StatusDetail] = "quota exhausted"; return Task.CompletedTask; }); var act = async () => await Client().ProcessAsync(new RedbMessage()); var ex = await act.Should().ThrowAsync(); ex.Which.StatusCode.Should().Be(StatusCode.ResourceExhausted); ex.Which.Status.Detail.Should().Be("quota exhausted"); } [Fact] public async Task SuppressStatusMapping_keeps_the_old_ok_plus_body_behaviour() { await Start(ex => { ex.Out = new Message("error-document"); ex.Out.Headers["status.code"] = 404; return Task.CompletedTask; }, new Dictionary { ["suppressStatusMapping"] = "true" }); var reply = await Client().ProcessAsync(new RedbMessage()); reply.Payload.ToStringUtf8().Should().Be("error-document"); } [Fact] public async Task Processor_exception_reaches_the_caller_as_internal() { await Start(_ => throw new InvalidOperationException("boom")); var act = async () => await Client().ProcessAsync(new RedbMessage()); var ex = await act.Should().ThrowAsync(); ex.Which.StatusCode.Should().Be(StatusCode.Internal); // BR-4: generic detail with a reference, not the exception text. ex.Which.Status.Detail.Should().NotContain("boom").And.Contain("ref: "); } [Fact] public async Task Trailer_headers_reach_the_client() { await Start(ex => { ex.Out = new Message("body"); ex.Out.Headers[GrpcHeaders.TrailerPrefix + "error"] = "invalid_scope"; return Task.CompletedTask; }); using var call = Client().ProcessAsync(new RedbMessage()); await call.ResponseAsync; call.GetTrailers().GetValue("error").Should().Be("invalid_scope"); } // ── header hygiene + client address (G3, G4) ───────────── [Fact] public async Task Caller_cannot_forge_transport_headers() { IExchange? seen = null; await Start(ex => { seen = ex; return Task.CompletedTask; }); var request = new RedbMessage(); request.Headers["redbHttp.RemoteAddress"] = "1.2.3.4"; // would hijack the rate-limit bucket request.Headers["redbGrpc.RemoteIp"] = "1.2.3.4"; request.Headers["dispatch-method"] = "Echo"; // legitimate: a Controllers dispatch key await Client().ProcessAsync(request); seen!.In.Headers.Should().NotContainKey("redbHttp.RemoteAddress"); seen.In.GetHeader(GrpcHeaders.RemoteIp).Should().Be("127.0.0.1"); seen.In.GetHeader("dispatch-method").Should().Be("Echo"); } [Fact] public async Task Client_address_is_resolved_and_optionally_bridged() { IExchange? seen = null; await Start(ex => { seen = ex; return Task.CompletedTask; }, new Dictionary { ["emitHttpCompatHeaders"] = "true" }); await Client().ProcessAsync(new RedbMessage()); seen!.In.GetHeader(GrpcHeaders.RemoteIp).Should().Be("127.0.0.1"); seen.In.Headers.Should().ContainKey(GrpcHeaders.RemotePort); seen.In.GetHeader(GrpcHeaders.RemotePeer).Should().StartWith("ipv4:127.0.0.1:"); // The bridge is what makes IP-keyed processors written for HTTP (rate limiting, lockout, // device metadata) work behind a gRPC facade unchanged. seen.In.GetHeader("redbHttp.RemoteAddress").Should().Be("127.0.0.1"); } [Fact] public async Task Route_address_is_visible_to_the_pipeline() { IExchange? seen = null; await Start(ex => { seen = ex; return Task.CompletedTask; }); await Client().ProcessAsync(new RedbMessage()); seen!.In.GetHeader(GrpcHeaders.Route).Should().Be(GrpcEndpointOptions.DefaultMethodPath); seen.In.GetHeader(GrpcHeaders.Service).Should().Be("redb.route.grpc.RedbService"); seen.In.GetHeader(GrpcHeaders.Method).Should().Be("Process"); } // ── one port, many methods (G1) ────────────────────────── [Fact] public async Task Two_consumers_serve_two_methods_on_one_port() { // The whole reason for the rewrite: this used to be impossible — the second consumer bound its // own Kestrel to the same port. await StartAt("/identity.v1.Identity/Token", ex => { ex.Out = new Message("token-reply"); return Task.CompletedTask; }); await StartAt("/identity.v1.Identity/Introspect", ex => { ex.Out = new Message("introspect-reply"); return Task.CompletedTask; }); (await CallRaw("/identity.v1.Identity/Token")).Should().Be("token-reply"); (await CallRaw("/identity.v1.Identity/Introspect")).Should().Be("introspect-reply"); } [Fact] public async Task Unknown_method_address_is_unimplemented() { await StartAt("/identity.v1.Identity/Token", ex => { ex.Out = new Message("token"); return Task.CompletedTask; }); var act = async () => await CallRaw("/identity.v1.Identity/Nope"); var ex = await act.Should().ThrowAsync(); ex.Which.StatusCode.Should().Be(StatusCode.Unimplemented); } [Fact] public async Task Camel_style_service_and_method_address_the_same_route() { // grpc://host:port/my.Service?method=Call — the camel-grpc spelling. await Start(ex => { ex.Out = new Message("camel-reply"); return Task.CompletedTask; }, new Dictionary { ["service"] = "identity.v1.Identity", ["method"] = "Token" }, path: "/identity.v1.Identity"); (await CallRaw("/identity.v1.Identity/Token")).Should().Be("camel-reply"); } // ── streaming (G8) ─────────────────────────────────────── [Fact] public async Task Async_enumerable_body_streams_one_frame_per_yield() { await Start(ex => { ex.Out = new Message(Pages()); return Task.CompletedTask; }); using var call = Client().ProcessStream(new RedbMessage()); var items = new List(); while (await call.ResponseStream.MoveNext(CancellationToken.None)) items.Add(call.ResponseStream.Current.Payload.ToStringUtf8()); items.Should().Equal("page-1", "page-2", "page-3"); static async IAsyncEnumerable Pages() { for (var i = 1; i <= 3; i++) { await Task.Yield(); yield return $"page-{i}"; } } } [Fact] public async Task Stream_body_on_a_unary_method_fails_loudly() { // A unary call carries exactly one message, so a stream body cannot be delivered. Without the // guard the enumerable's type name would go on the wire as the payload — silent garbage. await Start(ex => { ex.Out = new Message(Empty()); return Task.CompletedTask; }); var act = async () => await Client().ProcessAsync(new RedbMessage()); var ex = await act.Should().ThrowAsync(); ex.Which.Status.Detail.Should().Contain("Streaming"); static async IAsyncEnumerable Empty() { await Task.Yield(); yield return "x"; } } // ── compression ────────────────────────────────────────── [Fact] public async Task Gzip_is_accepted_inbound_and_used_outbound_when_the_caller_allows_it() { // Asserted at the wire level on purpose: Grpc.Net.Client consumes grpc-encoding / // grpc-accept-encoding itself and inflates transparently, so a client-side assertion would pass // even if we never compressed anything. string? received = null; await Start(ex => { // In envelope mode the consumer has already unwrapped RedbMessage — the body is the // payload itself, not the envelope. received = System.Text.Encoding.UTF8.GetString((byte[])ex.In.Body!); ex.Out = new Message(new string('z', 4096)); return Task.CompletedTask; }, new Dictionary { ["compression"] = "Gzip" }); var request = new RedbMessage { Payload = ByteString.CopyFromUtf8(new string('q', 2048)) }; var (headers, frame) = await PostFrame(GrpcEndpointOptions.DefaultMethodPath, request.ToByteArray(), compressRequest: true); received.Should().Be(new string('q', 2048), "the server must inflate a compressed request"); headers.GetValues("grpc-accept-encoding").Should().Contain(v => v.Contains("gzip")); headers.GetValues("grpc-encoding").Should().Contain("gzip"); frame[0].Should().Be(1, "the reply frame must carry the compressed flag"); var payload = Gunzip(frame[5..]); RedbMessage.Parser.ParseFrom(payload).Payload.ToStringUtf8().Should().Be(new string('z', 4096)); // Compression has to actually pay for itself on repetitive content. frame.Length.Should().BeLessThan(4096); } [Fact] public async Task Uncompressed_reply_when_the_caller_does_not_advertise_gzip() { await Start(ex => { ex.Out = new Message("plain"); return Task.CompletedTask; }, new Dictionary { ["compression"] = "Gzip" }); var (headers, frame) = await PostFrame(GrpcEndpointOptions.DefaultMethodPath, new RedbMessage().ToByteArray(), acceptEncoding: "identity"); headers.Contains("grpc-encoding").Should().BeFalse(); frame[0].Should().Be(0); } [Fact] public async Task Producer_reads_a_server_stream_as_an_async_enumerable() { // Client side of streaming: the reply lands in Out.Body as an IAsyncEnumerable, the framework's // streaming shape — so a gRPC stream can flow straight into a streaming consumer (the HTTP one // turns it into SSE) without being buffered in between. await Start(ex => { ex.Out = new Message(Pages()); return Task.CompletedTask; }); var producerUri = new EndpointUri("grpc", $"/127.0.0.1:{_port}{GrpcEndpointOptions.DefaultStreamMethodPath}", $"grpc:127.0.0.1:{_port}{GrpcEndpointOptions.DefaultStreamMethodPath}", new Dictionary { ["plaintext"] = "true", ["streaming"] = "true" }); var producerEndpoint = (GrpcEndpoint)_component.CreateEndpoint(producerUri); var producer = new GrpcProducer(producerEndpoint, producerEndpoint.EndpointOptions); await producer.Start(); var exchange = new Exchange(new Message(Array.Empty())); await producer.Process(exchange); var items = new List(); await foreach (var item in (IAsyncEnumerable)exchange.Out!.Body!) items.Add(System.Text.Encoding.UTF8.GetString((byte[])item!)); items.Should().Equal("page-1", "page-2", "page-3"); await producer.Stop(); static async IAsyncEnumerable Pages() { for (var i = 1; i <= 3; i++) { await Task.Yield(); yield return $"page-{i}"; } } } // ── health (G8) ────────────────────────────────────────── [Fact] public async Task Health_check_answers_serving() { await Start(_ => Task.CompletedTask, new Dictionary { ["health"] = "true" }); var reply = await CallRawBytes("/grpc.health.v1.Health/Check"); // HealthCheckResponse { status = SERVING } → field 1, varint 1. reply.Should().Equal((byte)0x08, (byte)0x01); } // ── helpers ─────────────────────────────────────────────── [Fact] public async Task A_malformed_envelope_is_the_callers_fault_not_ours() { // Envelope mode parses caller-supplied bytes as a RedbMessage. Garbage there used to fall through // the catch-all as Internal — which tells the caller "our fault, retry" about input only they can // fix — and put the protobuf parser's own wording into grpc-message. Their mistake, their status. await Start(ex => { ex.Out = new Message("never reached"); return Task.CompletedTask; }, new Dictionary { ["envelope"] = "message" }); // Not a protobuf message: a wire type nothing defines, then trailing junk. var garbage = new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0x7A, 0x7A }; var act = async () => await CallRawBytesWith(GrpcEndpointOptions.DefaultMethodPath, garbage); var ex = await act.Should().ThrowAsync(); ex.Which.StatusCode.Should().Be(StatusCode.InvalidArgument, "a request the caller malformed is not an internal server failure"); ex.Which.Status.Detail.Should().Contain("RedbMessage", "the answer should name what was expected, so the caller can fix it"); } /// Calls a method address with an arbitrary request body. private async Task CallRawBytesWith(string methodPath, byte[] payload) { var channel = GrpcChannel.ForAddress($"http://127.0.0.1:{_port}"); _channels.Add(channel); var slash = methodPath.LastIndexOf('/'); var marshaller = Marshallers.Create(b => (byte[])b, b => b); var method = new Method( MethodType.Unary, methodPath[1..slash], methodPath[(slash + 1)..], marshaller, marshaller); return await channel.CreateCallInvoker() .AsyncUnaryCall(method, null, new CallOptions(), payload); } [Fact] public async Task A_server_stream_that_breaks_mid_flight_is_recorded_not_swallowed() { // A server-streaming call reports failure while the consumer enumerates — long after Process has // returned. That is inherent to lazy streaming: .OnException, retry and dead-letter cannot see it, // and pretending otherwise would be a lie. What is NOT inherent is the failure being invisible: it // used to escape with no log and no metric, so a stream that broke every time looked like a stream // that simply ended early. await Start(ex => { ex.Out = new Message(FailingPages()); return Task.CompletedTask; }); var producerUri = new EndpointUri("grpc", $"/127.0.0.1:{_port}{GrpcEndpointOptions.DefaultStreamMethodPath}", $"grpc:127.0.0.1:{_port}{GrpcEndpointOptions.DefaultStreamMethodPath}", new Dictionary { ["plaintext"] = "true", ["streaming"] = "true" }); var producerEndpoint = (GrpcEndpoint)_component.CreateEndpoint(producerUri); var producer = new GrpcProducer(producerEndpoint, producerEndpoint.EndpointOptions); await producer.Start(); var before = producerEndpoint.Errors; var exchange = new Exchange(new Message(Array.Empty())); await producer.Process(exchange); var received = new List(); var act = async () => { await foreach (var item in (IAsyncEnumerable)exchange.Out!.Body!) received.Add(System.Text.Encoding.UTF8.GetString((byte[])item!)); }; // The break still reaches whoever is reading — swallowing it would be worse than not logging it. await act.Should().ThrowAsync(); received.Should().NotBeEmpty("the frames sent before the break are real and were delivered"); producerEndpoint.Errors.Should().BeGreaterThan(before, "a broken stream must show up on the endpoint, not only in the reader's stack trace"); await producer.Stop(); static async IAsyncEnumerable FailingPages() { yield return System.Text.Encoding.UTF8.GetBytes("page-1"); await Task.Yield(); throw new InvalidOperationException("upstream died mid-stream"); } } private Task Start(Func onProcess, Dictionary? extra = null, string path = "") => StartConsumer(path, onProcess, extra); private Task StartAt(string methodPath, Func onProcess) => StartConsumer(methodPath, onProcess, null); private async Task StartConsumer(string path, Func onProcess, Dictionary? extra) { // One component per scheme, as a RouteContext holds it — that is what makes several gRPC routes // share a single Kestrel host. A second component instance would bring its own fallback manager // and the two would fight over the port. var component = _component; var parameters = new Dictionary { ["host"] = "127.0.0.1", ["port"] = _port.ToString(), }; if (extra is not null) foreach (var (key, value) in extra) parameters[key] = value; var uriPath = $"/127.0.0.1:{_port}{path}"; var uri = new EndpointUri("grpc", uriPath, $"grpc:127.0.0.1:{_port}{path}", parameters); var endpoint = (GrpcEndpoint)component.CreateEndpoint(uri); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(async ci => await onProcess(ci.Arg())); var consumer = new GrpcConsumer(endpoint, processor, endpoint.EndpointOptions); _consumers.Add(consumer); await consumer.Start(); } private RedbService.RedbServiceClient Client() { var channel = GrpcChannel.ForAddress($"http://127.0.0.1:{_port}"); _channels.Add(channel); return new RedbService.RedbServiceClient(channel); } /// /// Calls a typed method address. Such an address is served in raw mode (Envelope=Auto), so the reply /// is the route's body verbatim — no RedbMessage wrapper, which is exactly what a client /// generated from a real .proto expects. /// private async Task CallRaw(string methodPath) => System.Text.Encoding.UTF8.GetString(await CallRawBytes(methodPath)); /// Calls any method address with the generic message, bypassing generated stubs. private async Task CallRawBytes(string methodPath) { var channel = GrpcChannel.ForAddress($"http://127.0.0.1:{_port}"); _channels.Add(channel); var slash = methodPath.LastIndexOf('/'); var marshaller = Marshallers.Create(b => (byte[])b, b => b); var method = new Method( MethodType.Unary, methodPath[1..slash], methodPath[(slash + 1)..], marshaller, marshaller); return await channel.CreateCallInvoker() .AsyncUnaryCall(method, null, new CallOptions(), new RedbMessage().ToByteArray()); } /// /// Sends one gRPC frame over raw HTTP/2 and returns the response headers plus the reply frame, so a /// test can inspect the bytes a generated client would hide. /// private async Task<(System.Net.Http.Headers.HttpResponseHeaders Headers, byte[] Frame)> PostFrame( string methodPath, byte[] message, string acceptEncoding = "identity,gzip", bool compressRequest = false) { var payload = compressRequest ? Gzip(message) : message; var frame = new byte[5 + payload.Length]; frame[0] = compressRequest ? (byte)1 : (byte)0; System.Buffers.Binary.BinaryPrimitives.WriteUInt32BigEndian(frame.AsSpan(1, 4), (uint)payload.Length); payload.CopyTo(frame, 5); using var client = new System.Net.Http.HttpClient(); using var content = new System.Net.Http.ByteArrayContent(frame); content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/grpc"); using var request = new System.Net.Http.HttpRequestMessage( System.Net.Http.HttpMethod.Post, $"http://127.0.0.1:{_port}{methodPath}") { Content = content, Version = System.Net.HttpVersion.Version20, VersionPolicy = System.Net.Http.HttpVersionPolicy.RequestVersionExact, }; request.Headers.TryAddWithoutValidation("te", "trailers"); request.Headers.TryAddWithoutValidation("grpc-accept-encoding", acceptEncoding); if (frame[0] == 1) request.Headers.TryAddWithoutValidation("grpc-encoding", "gzip"); var response = await client.SendAsync(request); // Surface the gRPC outcome: a failed call answers HTTP 200 with a grpc-status trailer, so a bare // status assertion downstream would say nothing useful. var body = await response.Content.ReadAsByteArrayAsync(); var grpcStatus = response.TrailingHeaders.TryGetValues("grpc-status", out var st) ? string.Join(",", st) : "(none)"; var grpcMessage = response.TrailingHeaders.TryGetValues("grpc-message", out var msg) ? string.Join(",", msg) : ""; response.IsSuccessStatusCode.Should().BeTrue($"HTTP {(int)response.StatusCode}"); grpcStatus.Should().Be("0", $"call failed: {Uri.UnescapeDataString(grpcMessage)}"); return (response.Headers, body); } private static byte[] Gzip(byte[] data) { using var output = new MemoryStream(); using (var gzip = new System.IO.Compression.GZipStream(output, System.IO.Compression.CompressionLevel.Fastest, leaveOpen: true)) gzip.Write(data, 0, data.Length); return output.ToArray(); } private static byte[] Gunzip(byte[] data) { using var input = new MemoryStream(data); using var gzip = new System.IO.Compression.GZipStream(input, System.IO.Compression.CompressionMode.Decompress); using var output = new MemoryStream(); gzip.CopyTo(output); return output.ToArray(); } private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); } Path: redb-route/tests/redb.Route.Tests.Grpc/GrpcConsumerTests.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/tests/redb.Route.Tests.Grpc/GrpcConsumerTests.cs ---- using System.Net; using Google.Protobuf; using Grpc.Net.Client; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Grpc; using redb.Route.Grpc.Proto; namespace redb.Route.Tests.Grpc; public class GrpcConsumerTests : IAsyncLifetime { private GrpcConsumer? _consumer; private GrpcChannel? _channel; private RedbService.RedbServiceClient? _client; private int _port; private IExchange? _lastExchange; private readonly List _capturedExchanges = new(); private Func? _processorAction; public Task InitializeAsync() { _port = GetFreePort(); return Task.CompletedTask; } public async Task DisposeAsync() { _channel?.Dispose(); if (_consumer is not null) await _consumer.Stop(); } private GrpcConsumer CreateConsumer(Dictionary? extraParams = null) { var component = new GrpcComponent(); var parameters = new Dictionary { ["host"] = "127.0.0.1", ["port"] = _port.ToString() }; if (extraParams is not null) { foreach (var (key, value) in extraParams) parameters[key] = value; } var uri = new EndpointUri("grpc", $"/127.0.0.1:{_port}", $"grpc:127.0.0.1:{_port}", parameters); var endpoint = (GrpcEndpoint)component.CreateEndpoint(uri); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(async ci => { var ex = ci.Arg(); _lastExchange = ex; _capturedExchanges.Add(ex); if (_processorAction is not null) await _processorAction(ex); }); _consumer = new GrpcConsumer(endpoint, processor, endpoint.EndpointOptions); return _consumer; } private RedbService.RedbServiceClient CreateClient() { var handler = new SocketsHttpHandler { EnableMultipleHttp2Connections = true }; _channel = GrpcChannel.ForAddress($"http://127.0.0.1:{_port}", new GrpcChannelOptions { HttpHandler = handler }); _client = new RedbService.RedbServiceClient(_channel); return _client; } // ── Lifecycle tests ── [Fact] public async Task Start_SetsBaseUrl() { var consumer = CreateConsumer(); await consumer.Start(); consumer.BaseUrl.Should().Be($"http://127.0.0.1:{_port}"); } [Fact] public async Task Stop_CleansUp() { var consumer = CreateConsumer(); await consumer.Start(); await consumer.Stop(); consumer.BaseUrl.Should().NotBeNull(); // BaseUrl remains set after stop } // ── Request handling ── [Fact] public async Task Process_ReceivesRequest_ProcessorCalled() { var consumer = CreateConsumer(); await consumer.Start(); var client = CreateClient(); var request = new RedbMessage { Payload = ByteString.CopyFromUtf8("hello grpc") }; await client.ProcessAsync(request); _lastExchange.Should().NotBeNull(); _lastExchange!.In.Body.Should().BeOfType(); System.Text.Encoding.UTF8.GetString((byte[])_lastExchange.In.Body!).Should().Be("hello grpc"); } [Fact] public async Task Process_EmptyPayload_BodyIsNull() { var consumer = CreateConsumer(); await consumer.Start(); var client = CreateClient(); var request = new RedbMessage(); await client.ProcessAsync(request); _lastExchange.Should().NotBeNull(); _lastExchange!.In.Body.Should().BeNull(); } [Fact] public async Task Process_Headers_MappedToExchange() { var consumer = CreateConsumer(); await consumer.Start(); var client = CreateClient(); var request = new RedbMessage { Payload = ByteString.CopyFromUtf8("test") }; request.Headers["custom-key"] = "custom-value"; request.Headers["another"] = "42"; await client.ProcessAsync(request); _lastExchange.Should().NotBeNull(); _lastExchange!.In.Headers["custom-key"].Should().Be("custom-value"); _lastExchange!.In.Headers["another"].Should().Be("42"); } [Fact] public async Task Process_GrpcHeaders_Set() { var consumer = CreateConsumer(); await consumer.Start(); var client = CreateClient(); var request = new RedbMessage { Payload = ByteString.CopyFromUtf8("test") }; await client.ProcessAsync(request); _lastExchange.Should().NotBeNull(); // gRPC method header should be set _lastExchange!.In.Headers.Should().ContainKey(GrpcHeaders.Method); _lastExchange!.In.Headers[GrpcHeaders.Method].Should().NotBeNull(); // Port should be set _lastExchange!.In.Headers.Should().ContainKey(GrpcHeaders.Port); ((int)_lastExchange!.In.Headers[GrpcHeaders.Port]!).Should().Be(_port); } [Fact] public async Task Process_InOut_ReturnsResponse() { _processorAction = ex => { ex.Out = new Message("response-payload"); ex.Out.Headers["result"] = "ok"; return Task.CompletedTask; }; var consumer = CreateConsumer(); await consumer.Start(); var client = CreateClient(); var request = new RedbMessage { Payload = ByteString.CopyFromUtf8("request") }; var response = await client.ProcessAsync(request); response.Payload.ToStringUtf8().Should().Be("response-payload"); response.Headers.Should().ContainKey("result"); response.Headers["result"].Should().Be("ok"); } [Fact] public async Task Process_InOnly_ReturnsInBody() { var consumer = CreateConsumer(new Dictionary { ["inOut"] = "false" }); await consumer.Start(); var client = CreateClient(); var request = new RedbMessage { Payload = ByteString.CopyFromUtf8("fire-and-forget") }; var response = await client.ProcessAsync(request); // InOnly: response should contain the In body (since no Out is set) response.Payload.ToStringUtf8().Should().Be("fire-and-forget"); } [Fact] public async Task Process_BytePayload_PreservedCorrectly() { _processorAction = ex => { // Echo back the same bytes ex.Out = new Message(ex.In.Body); return Task.CompletedTask; }; var consumer = CreateConsumer(); await consumer.Start(); var client = CreateClient(); var payload = new byte[] { 0x00, 0x01, 0x02, 0xFF, 0xFE }; var request = new RedbMessage { Payload = ByteString.CopyFrom(payload) }; var response = await client.ProcessAsync(request); response.Payload.ToByteArray().Should().BeEquivalentTo(payload); } [Fact] public async Task Process_ProcessorException_ReturnsRpcError() { _processorAction = _ => throw new InvalidOperationException("test error"); var consumer = CreateConsumer(); await consumer.Start(); var client = CreateClient(); var request = new RedbMessage { Payload = ByteString.CopyFromUtf8("fail") }; var act = async () => await client.ProcessAsync(request); var ex = await act.Should().ThrowAsync(); ex.Which.StatusCode.Should().Be(global::Grpc.Core.StatusCode.Internal); // BR-4: the action's own text never becomes the status detail; the caller gets a reference to quote. ex.Which.Status.Detail.Should().NotContain("test error").And.Contain("ref: "); } [Fact] public async Task Process_ProcessedCount_Increments() { var consumer = CreateConsumer(); await consumer.Start(); var client = CreateClient(); consumer.ProcessedCount.Should().Be(0); var request = new RedbMessage { Payload = ByteString.CopyFromUtf8("test") }; await client.ProcessAsync(request); consumer.ProcessedCount.Should().Be(1); await client.ProcessAsync(request); consumer.ProcessedCount.Should().Be(2); } [Fact] public async Task Process_GrpcMetadata_MappedToHeaders() { var consumer = CreateConsumer(); await consumer.Start(); var client = CreateClient(); var metadata = new global::Grpc.Core.Metadata { { "x-request-id", "grpc-meta-123" }, { "x-tenant", "acme" } }; var request = new RedbMessage { Payload = ByteString.CopyFromUtf8("meta") }; await client.ProcessAsync(request, metadata); _lastExchange.Should().NotBeNull(); _lastExchange!.In.Headers["x-request-id"].Should().Be("grpc-meta-123"); _lastExchange!.In.Headers["x-tenant"].Should().Be("acme"); } [Fact] public async Task ProcessStream_InOut_ReturnsStreamedResponse() { _processorAction = ex => { ex.Out = new Message("streamed-response"); return Task.CompletedTask; }; var consumer = CreateConsumer(); await consumer.Start(); var client = CreateClient(); var request = new RedbMessage { Payload = ByteString.CopyFromUtf8("stream-request") }; using var stream = client.ProcessStream(request); var items = new List(); while (await stream.ResponseStream.MoveNext(CancellationToken.None)) { items.Add(stream.ResponseStream.Current); } items.Should().HaveCount(1); items[0].Payload.ToStringUtf8().Should().Be("streamed-response"); } [Fact] public async Task Process_MultipleRequests_AllProcessed() { var consumer = CreateConsumer(); await consumer.Start(); var client = CreateClient(); for (int i = 0; i < 10; i++) { var request = new RedbMessage { Payload = ByteString.CopyFromUtf8($"request-{i}") }; await client.ProcessAsync(request); } _capturedExchanges.Should().HaveCount(10); consumer.ProcessedCount.Should().Be(10); } [Fact] public async Task Process_RedbHeaders_NotCopiedToResponse() { _processorAction = ex => { ex.Out = new Message("ok"); ex.Out.Headers[GrpcHeaders.Method] = "should-be-stripped"; ex.Out.Headers["keep-me"] = "yes"; return Task.CompletedTask; }; var consumer = CreateConsumer(); await consumer.Start(); var client = CreateClient(); var request = new RedbMessage { Payload = ByteString.CopyFromUtf8("test") }; var response = await client.ProcessAsync(request); response.Headers.Should().NotContainKey(GrpcHeaders.Method); response.Headers.Should().ContainKey("keep-me"); response.Headers["keep-me"].Should().Be("yes"); } private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); } Path: redb-route/tests/redb.Route.Tests.Grpc/GrpcExpressionTests.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/tests/redb.Route.Tests.Grpc/GrpcExpressionTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.Grpc; namespace redb.Route.Tests.Grpc; /// /// Tests for expression resolution in gRPC producer options (Phase 2). /// Verifies that DeadlineExpression binds and resolves correctly. /// public class GrpcExpressionTests { // ── BindFromUri: expression binds to *Expression property ──────── [Fact] public void BindFromUri_DeadlineExpression_BindsCorrectly() { var opts = new GrpcEndpointOptions(); opts.BindFromUri(new Dictionary { ["deadlineExpression"] = "${header.timeout}" }); opts.DeadlineExpression.Should().Be("${header.timeout}"); opts.Deadline.Should().Be(30_000); // default unchanged } // ── ResolveOption: deadline expression resolves from exchange ──── [Fact] public void ResolveOption_DeadlineExpression_ResolvesFromExchange() { var opts = new GrpcEndpointOptions { DeadlineExpression = "${header.timeout}" }; var msg = new Message("body"); msg.Headers["timeout"] = "5000"; var exchange = new Exchange(msg); var resolved = opts.ResolveOption(opts.DeadlineExpression, exchange); resolved.Should().Be("5000"); int.TryParse(resolved, out var deadline).Should().BeTrue(); deadline.Should().Be(5000); } [Fact] public void ResolveOption_DeadlineExpression_InvalidValue_TryParseFails() { var opts = new GrpcEndpointOptions { DeadlineExpression = "${header.timeout}" }; var msg = new Message("body"); msg.Headers["timeout"] = "not-a-number"; var exchange = new Exchange(msg); var resolved = opts.ResolveOption(opts.DeadlineExpression, exchange); resolved.Should().Be("not-a-number"); int.TryParse(resolved, out _).Should().BeFalse(); } [Fact] public void ResolveOption_StaticValue_ReturnsAsIs() { var opts = new GrpcEndpointOptions(); var exchange = new Exchange(new Message("body")); opts.ResolveOption("plain-string", exchange).Should().Be("plain-string"); } // ── DSL: expression routing in Build ───────────────────────────── [Fact] public void DslBuild_DeadlineExpression_RoutesToExpressionParam() { var uri = GrpcDsl.Call("localhost:50051") .Deadline(new HeaderExpression("timeout")) .Build(); uri.Should().Contain("deadlineExpression="); uri.Should().NotContain("&deadline="); } [Fact] public void DslBuild_DeadlineStatic_RoutesToNormalParam() { var uri = GrpcDsl.Call("localhost:50051") .Deadline(10_000) .Build(); uri.Should().Contain("deadline=10000"); uri.Should().NotContain("deadlineExpression"); } [Fact] public void DslBuild_DeadlineExpression_FullRoundtrip() { // Build URI with expression var uri = GrpcDsl.Call("localhost:50051") .Deadline(new HeaderExpression("dlTimeout")) .Plaintext() .Build(); // Parse URI into options var opts = new GrpcEndpointOptions(); var queryString = uri.Substring(uri.IndexOf('?') + 1); var queryParams = System.Web.HttpUtility.ParseQueryString(queryString); var dict = new Dictionary(); foreach (string key in queryParams) dict[key] = queryParams[key]!; opts.BindFromUri(dict); // Verify expression bound correctly opts.DeadlineExpression.Should().NotBeNull(); opts.DeadlineExpression.Should().Contain("${"); // Resolve against exchange var msg = new Message("body"); msg.Headers["dlTimeout"] = "15000"; var exchange = new Exchange(msg); var resolved = opts.ResolveOption(opts.DeadlineExpression!, exchange); resolved.Should().Be("15000"); } } Path: redb-route/tests/redb.Route.Tests.Grpc/GrpcHeaderFilterStrategyTests.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/tests/redb.Route.Tests.Grpc/GrpcHeaderFilterStrategyTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Grpc; namespace redb.Route.Tests.Grpc; /// /// headerFilterStrategy=#name on gRPC endpoints: on a producer it decides 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. The reserved prefixes and the consumer's redbGrpc.* call metadata /// stay outside the strategy. /// public sealed class GrpcHeaderFilterStrategyTests { private static async Task<(Dictionary Request, Dictionary Reply)> Call( string producerOptions, string consumerOptions) { var port = global::redb.Route.Tests.Shared.TestPorts.Next(); var received = new TaskCompletionSource>(TaskCreationOptions.RunContinuationsAsynchronously); await using var ctx = new RouteContext(); ctx.AddComponent(new GrpcComponent()); ctx.AddToRegistry("correlationOnly", new DefaultHeaderFilterStrategy { OutFilter = ["Correlation-ID"], FilterOnMatch = false }); ctx.AddToRegistry("noSecrets", new DefaultHeaderFilterStrategy { InFilter = ["Authorization"] }); ctx.AddRoutes(r => r.From($"grpc://127.0.0.1:{port}?inOut=true{consumerOptions}").Process(e => { received.TrySetResult(new Dictionary(e.In.Headers, StringComparer.OrdinalIgnoreCase)); e.Out = new Message("reply"); e.Out.Headers["Correlation-ID"] = "c-42"; e.Out.Headers["X-Reply"] = "r1"; e.Out.Headers["Authorization"] = "Bearer secret"; })); await ctx.Start(); var producer = ctx.GetEndpoint($"grpc://127.0.0.1:{port}?plaintext=true{producerOptions}").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("body")); exchange.In.Headers["Correlation-ID"] = "c-42"; exchange.In.Headers["X-Corr"] = "c1"; exchange.In.Headers["Authorization"] = "Bearer secret"; exchange.In.Headers["redbHttp.Method"] = "DELETE"; await producer.Process(exchange); await producer.Stop(); var request = await received.Task.WaitAsync(TimeSpan.FromSeconds(10)); var reply = new Dictionary((exchange.HasOut ? exchange.Out! : exchange.In).Headers, StringComparer.OrdinalIgnoreCase); return (request, reply); } [Fact] public async Task OnAProducer_AWhitelistSendsOnlyTheNamedHeader() { var (request, _) = await Call("&headerFilterStrategy=#correlationOnly", ""); request["Correlation-ID"].Should().Be("c-42"); request.Should().NotContainKey("X-Corr"); request.Should().NotContainKey("Authorization"); request.Should().ContainKey(GrpcHeaders.Route, "the consumer's own call metadata is set whatever the strategy says"); } [Fact] public async Task OnAConsumer_TheStrategyDecidesWhatComesIn_AndTheReservedPrefixesStayOut() { var (request, _) = await Call("", "&headerFilterStrategy=#noSecrets"); request["X-Corr"].Should().Be("c1"); request.Should().NotContainKey("Authorization", "the consumer's strategy drops it on the way in"); request.Should().NotContainKey("redbHttp.Method", "a reserved prefix is refused whatever the strategy says, unless allowClientReservedHeaders"); } [Fact] public async Task OnAReplyingConsumer_TheStrategyDecidesWhatTheReplyCarries() { var (_, reply) = await Call("", "&headerFilterStrategy=#correlationOnly"); reply["Correlation-ID"].Should().Be("c-42"); reply.Should().NotContainKey("X-Reply"); reply.Should().NotContainKey("Authorization"); } [Fact] public async Task OnAProducer_TheStrategyDecidesWhatComesBackWithTheReply() { var (_, reply) = await Call("&headerFilterStrategy=#noSecrets", ""); reply["X-Reply"].Should().Be("r1"); reply.Should().NotContainKey("Authorization", "the producer's strategy drops it on the way back in"); } } Path: redb-route/tests/redb.Route.Tests.Grpc/GrpcHeaderMappingCharacterizationTests.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/tests/redb.Route.Tests.Grpc/GrpcHeaderMappingCharacterizationTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Grpc; namespace redb.Route.Tests.Grpc; /// /// What crosses a gRPC call today, all four points: pinned before the header filter strategy /// takes the rule over, so the transport's default keeps it exactly. /// The producer sends every exchange header but its own redbGrpc.*, the reserved grpc-* keys and null /// values as request metadata (keys lowercased by gRPC); the consumer takes every request metadata entry but the /// pseudo-headers, grpc-* and the reserved keys (the control prefixes of every transport: redbHttp., /// redbSoap....), so unlike the brokers a control header cannot come in this way. The consumer answers with every exchange header but /// redbGrpc.* as response metadata, redbGrpc.Trailer.X as trailer X; the producer takes the /// response metadata back. /// public sealed class GrpcHeaderMappingCharacterizationTests { [Fact] public async Task RequestAndResponse_TheMetadataThatCrosses() { var port = global::redb.Route.Tests.Shared.TestPorts.Next(); var received = new TaskCompletionSource>(TaskCreationOptions.RunContinuationsAsynchronously); await using var ctx = new RouteContext(); ctx.AddComponent(new GrpcComponent()); ctx.AddRoutes(r => r.From($"grpc://127.0.0.1:{port}?inOut=true").Process(e => { received.TrySetResult(new Dictionary(e.In.Headers, StringComparer.OrdinalIgnoreCase)); e.Out = new Message("reply"); e.Out.Headers["X-Reply"] = "r1"; e.Out.Headers["X-Int"] = 7; e.Out.Headers["X-Null"] = null; e.Out.Headers[GrpcHeaders.Prefix + "Custom"] = "own"; e.Out.Headers[GrpcHeaders.TrailerPrefix + "x-trail"] = "t1"; })); await ctx.Start(); var producer = ctx.GetEndpoint($"grpc://127.0.0.1:{port}?plaintext=true").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("body")); exchange.In.Headers["X-Corr"] = "c1"; exchange.In.Headers["X-Int"] = 42; exchange.In.Headers["X-Null"] = null; exchange.In.Headers["Authorization"] = "Bearer secret"; exchange.In.Headers["redbHttp.Method"] = "DELETE"; exchange.In.Headers[GrpcHeaders.Prefix + "Custom"] = "own"; await producer.Process(exchange); await producer.Stop(); var request = await received.Task.WaitAsync(TimeSpan.FromSeconds(10)); request["x-corr"].Should().Be("c1", "gRPC lowercases metadata keys"); request["x-int"].Should().Be("42"); request.Should().NotContainKey("x-null", "a null value is skipped"); request["authorization"].Should().Be("Bearer secret", "nothing filters a credential"); request.Should().NotContainKey("redbhttp.method", "the consumer drops the control prefixes of every transport (GrpcWire.IsReservedKey) unless allowClientReservedHeaders"); request.Should().NotContainKey(GrpcHeaders.Prefix + "custom", "the producer keeps its own redbGrpc.* back"); var response = (exchange.HasOut ? exchange.Out! : exchange.In).Headers; response["x-reply"].Should().Be("r1"); response["x-int"].Should().Be("7"); response.Should().NotContainKey("x-null"); response.Keys.Should().NotContain(k => k.Equals(GrpcHeaders.Prefix + "Custom", StringComparison.OrdinalIgnoreCase)); } } Path: redb-route/tests/redb.Route.Tests.Grpc/GrpcHeadersTests.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/tests/redb.Route.Tests.Grpc/GrpcHeadersTests.cs ---- using redb.Route.Grpc; namespace redb.Route.Tests.Grpc; public class GrpcHeadersTests { [Theory] [InlineData("redbGrpc.Method")] [InlineData("redbGrpc.StatusCode")] [InlineData("redbGrpc.Port")] [InlineData("redbGrpc.RemotePeer")] [InlineData("redbGrpc.Authority")] [InlineData("redbGrpc.Deadline")] [InlineData("redbGrpc.Service")] [InlineData("redbGrpc.StatusDetail")] public void IsRedbHeader_WithPrefix_ReturnsTrue(string key) { GrpcHeaders.IsRedbHeader(key).Should().BeTrue(); } [Theory] [InlineData("Content-Type")] [InlineData("X-Custom")] [InlineData("grpc-status")] [InlineData("method")] [InlineData("")] public void IsRedbHeader_WithoutPrefix_ReturnsFalse(string key) { GrpcHeaders.IsRedbHeader(key).Should().BeFalse(); } [Fact] public void Constants_HaveCorrectPrefix() { GrpcHeaders.Method.Should().StartWith("redbGrpc."); GrpcHeaders.StatusCode.Should().StartWith("redbGrpc."); GrpcHeaders.StatusDetail.Should().StartWith("redbGrpc."); GrpcHeaders.RemotePeer.Should().StartWith("redbGrpc."); GrpcHeaders.Port.Should().StartWith("redbGrpc."); GrpcHeaders.Authority.Should().StartWith("redbGrpc."); GrpcHeaders.Deadline.Should().StartWith("redbGrpc."); GrpcHeaders.Service.Should().StartWith("redbGrpc."); } } Path: redb-route/tests/redb.Route.Tests.Grpc/GrpcIntegrationTests.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/tests/redb.Route.Tests.Grpc/GrpcIntegrationTests.cs ---- using System.Net; using System.Text; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Grpc; namespace redb.Route.Tests.Grpc; /// /// Integration tests: GrpcConsumer ← GrpcProducer round-trip. /// public class GrpcIntegrationTests : IAsyncLifetime { private GrpcConsumer? _consumer; private GrpcProducer? _producer; private int _port; private IExchange? _receivedExchange; public Task InitializeAsync() { _port = GetFreePort(); return Task.CompletedTask; } public async Task DisposeAsync() { if (_producer is not null) await _producer.Stop(); if (_consumer is not null) await _consumer.Stop(); } private (GrpcConsumer consumer, GrpcProducer producer) CreatePair( bool inOut = true, Func? onProcess = null) { // Consumer (server) var consumerComponent = new GrpcComponent(); var consumerParams = new Dictionary { ["host"] = "127.0.0.1", ["port"] = _port.ToString(), ["inOut"] = inOut.ToString().ToLower() }; var consumerUri = new EndpointUri("grpc", $"/127.0.0.1:{_port}", $"grpc:127.0.0.1:{_port}", consumerParams); var consumerEndpoint = (GrpcEndpoint)consumerComponent.CreateEndpoint(consumerUri); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(async ci => { var ex = ci.Arg(); _receivedExchange = ex; if (onProcess is not null) await onProcess(ex); }); _consumer = new GrpcConsumer(consumerEndpoint, processor, consumerEndpoint.EndpointOptions); // Producer (client) var producerComponent = new GrpcComponent(); var producerParams = new Dictionary { ["plaintext"] = "true" }; var producerUri = new EndpointUri("grpc", $"/127.0.0.1:{_port}", $"grpc:127.0.0.1:{_port}", producerParams); var producerEndpoint = (GrpcEndpoint)producerComponent.CreateEndpoint(producerUri); _producer = new GrpcProducer(producerEndpoint, producerEndpoint.EndpointOptions); return (_consumer, _producer); } [Fact] public async Task Integration_InOut_RoundTrip() { var (consumer, producer) = CreatePair(inOut: true, onProcess: ex => { var input = Encoding.UTF8.GetString((byte[])ex.In.Body!); ex.Out = new Message($"ECHO: {input}"); ex.Out.Headers["processed"] = "true"; return Task.CompletedTask; }); await consumer.Start(); await producer.Start(); var exchange = new Exchange(new Message("hello gRPC")); await producer.Process(exchange); // Verify consumer received _receivedExchange.Should().NotBeNull(); Encoding.UTF8.GetString((byte[])_receivedExchange!.In.Body!).Should().Be("hello gRPC"); // Verify producer got response exchange.Out.Should().NotBeNull(); Encoding.UTF8.GetString((byte[])exchange.Out!.Body!).Should().Be("ECHO: hello gRPC"); exchange.Out.Headers["processed"].Should().Be("true"); } [Fact] public async Task Integration_InOnly_ReturnsInBody() { var (consumer, producer) = CreatePair(inOut: false); await consumer.Start(); await producer.Start(); var exchange = new Exchange(new Message("fire-and-forget")); await producer.Process(exchange); // Consumer received _receivedExchange.Should().NotBeNull(); Encoding.UTF8.GetString((byte[])_receivedExchange!.In.Body!).Should().Be("fire-and-forget"); // Producer gets response (In body echoed for InOnly since no Out set) exchange.Out.Should().NotBeNull(); } [Fact] public async Task Integration_BytePayload_Preserved() { var (consumer, producer) = CreatePair(inOut: true, onProcess: ex => { // Return the payload reversed var input = (byte[])ex.In.Body!; var reversed = new byte[input.Length]; Array.Copy(input, reversed, input.Length); Array.Reverse(reversed); ex.Out = new Message(reversed); return Task.CompletedTask; }); await consumer.Start(); await producer.Start(); var payload = new byte[] { 1, 2, 3, 4, 5 }; var exchange = new Exchange(new Message(payload)); await producer.Process(exchange); ((byte[])exchange.Out!.Body!).Should().BeEquivalentTo(new byte[] { 5, 4, 3, 2, 1 }); } [Fact] public async Task Integration_Headers_Preserved() { var (consumer, producer) = CreatePair(inOut: true, onProcess: ex => { ex.Out = new Message("ok"); // Echo the custom header back if (ex.In.Headers.ContainsKey("x-correlation-id")) ex.Out.Headers["x-correlation-id"] = ex.In.Headers["x-correlation-id"]!.ToString()!; return Task.CompletedTask; }); await consumer.Start(); await producer.Start(); var exchange = new Exchange(new Message("test")); exchange.In.Headers["x-correlation-id"] = "corr-123"; await producer.Process(exchange); exchange.Out.Should().NotBeNull(); exchange.Out!.Headers["x-correlation-id"].Should().Be("corr-123"); } [Fact] public async Task Integration_ProcessorModifies_ResponseReflects() { var (consumer, producer) = CreatePair(inOut: true, onProcess: ex => { var body = Encoding.UTF8.GetString((byte[])ex.In.Body!); ex.Out = new Message($"{body} TRANSFORMED"); ex.Out.Headers["stage"] = "enriched"; return Task.CompletedTask; }); await consumer.Start(); await producer.Start(); var exchange = new Exchange(new Message("raw-data")); await producer.Process(exchange); Encoding.UTF8.GetString((byte[])exchange.Out!.Body!).Should().Be("raw-data TRANSFORMED"); exchange.Out.Headers["stage"].Should().Be("enriched"); } [Fact] public async Task Integration_ProcessorThrows_ProducerGetsError() { var (consumer, producer) = CreatePair(inOut: true, onProcess: _ => throw new Exception("pipeline failure")); await consumer.Start(); await producer.Start(); var exchange = new Exchange(new Message("fail-me")); // The producer rethrows (ThrowOnError, default) so .OnException / retry / dead-letter see the // failure — the same contract as the HTTP and SOAP producers. The exchange still carries the // status for handlers that want to branch on it. var act = async () => await producer.Process(exchange); await act.Should().ThrowAsync(); exchange.Exception.Should().NotBeNull(); exchange.Exception.Should().BeOfType(); exchange.In.Headers.Should().ContainKey(GrpcHeaders.StatusCode); } [Fact] public async Task Integration_MultipleRequests_AllProcessed() { int counter = 0; var (consumer, producer) = CreatePair(inOut: true, onProcess: ex => { Interlocked.Increment(ref counter); ex.Out = new Message($"ack-{counter}"); return Task.CompletedTask; }); await consumer.Start(); await producer.Start(); for (int i = 0; i < 20; i++) { var exchange = new Exchange(new Message($"msg-{i}")); await producer.Process(exchange); exchange.Out.Should().NotBeNull(); } counter.Should().Be(20); consumer.ProcessedCount.Should().Be(20); } [Fact] public async Task Integration_LargePayload_Works() { var (consumer, producer) = CreatePair(inOut: true, onProcess: ex => { ex.Out = new Message(ex.In.Body); return Task.CompletedTask; }); await consumer.Start(); await producer.Start(); // ~1MB payload var largePayload = new byte[1024 * 1024]; Random.Shared.NextBytes(largePayload); var exchange = new Exchange(new Message(largePayload)); await producer.Process(exchange); // Ordered byte compare: BeEquivalentTo on megabytes runs for tens of seconds, for minutes on a slow Linux stand. var echoed = (byte[])exchange.Out!.Body!; echoed.Length.Should().Be(largePayload.Length); echoed.AsSpan().SequenceEqual(largePayload).Should().BeTrue("the payload comes back unchanged"); } [Fact] public async Task Integration_EmptyPayload_RoundTrip() { var (consumer, producer) = CreatePair(inOut: true, onProcess: ex => { ex.Out = new Message("received-empty"); return Task.CompletedTask; }); await consumer.Start(); await producer.Start(); var exchange = new Exchange(new Message(null)); await producer.Process(exchange); exchange.Out.Should().NotBeNull(); Encoding.UTF8.GetString((byte[])exchange.Out!.Body!).Should().Be("received-empty"); } // ── Expression support: deadline from exchange header ── [Fact] public async Task Integration_ExpressionDeadline_ResolvesAtRuntime() { // Create pair with deadlineExpression in producer options var consumerComponent = new GrpcComponent(); var consumerParams = new Dictionary { ["host"] = "127.0.0.1", ["port"] = _port.ToString(), ["inOut"] = "true" }; var consumerUri = new EndpointUri("grpc", $"/127.0.0.1:{_port}", $"grpc:127.0.0.1:{_port}", consumerParams); var consumerEndpoint = (GrpcEndpoint)consumerComponent.CreateEndpoint(consumerUri); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { var ex = ci.Arg(); _receivedExchange = ex; ex.Out = new Message("deadline-ok"); return Task.CompletedTask; }); _consumer = new GrpcConsumer(consumerEndpoint, processor, consumerEndpoint.EndpointOptions); // Producer with expression deadline var producerComponent = new GrpcComponent(); var producerParams = new Dictionary { ["plaintext"] = "true", ["deadlineExpression"] = "${header.timeout}" }; var producerUri = new EndpointUri("grpc", $"/127.0.0.1:{_port}", $"grpc:127.0.0.1:{_port}", producerParams); var producerEndpoint = (GrpcEndpoint)producerComponent.CreateEndpoint(producerUri); _producer = new GrpcProducer(producerEndpoint, producerEndpoint.EndpointOptions); await _consumer.Start(); await _producer.Start(); // Send with resolved deadline 30000ms — more than enough var msg = new Message("expression deadline test"); msg.Headers["timeout"] = "30000"; var exchange = new Exchange(msg); await _producer.Process(exchange); // The call should succeed (deadline was resolved and applied) exchange.Out.Should().NotBeNull(); Encoding.UTF8.GetString((byte[])exchange.Out!.Body!).Should().Be("deadline-ok"); _receivedExchange.Should().NotBeNull(); } [Theory] [InlineData("trace-bin")] // a legal HTTP header name; -bin means "binary value" to gRPC [InlineData("has space")] [InlineData("unicode-ключ")] public async Task A_header_that_cannot_be_a_metadata_key_does_not_kill_the_call(string headerName) { // Exchange headers are whatever upstream put there — copied HTTP request headers, values a // processor derived from data. gRPC metadata keys are a far narrower alphabet, and Metadata.Add // throws ArgumentException on anything outside it. That loop runs BEFORE the producer's try // block, so one odd header name took the whole call down with an exception carrying no status // and no route error contract. A header that cannot be represented must be dropped, not fatal. var (consumer, producer) = CreatePair(inOut: true, onProcess: ex => { ex.Out = new Message("ok"); return Task.CompletedTask; }); await consumer.Start(); await producer.Start(); var exchange = new Exchange(new Message("payload")); exchange.In.Headers[headerName] = "value"; exchange.In.Headers["x-normal"] = "kept"; await producer.Process(exchange); Encoding.UTF8.GetString((byte[])exchange.Out!.Body!).Should().Be("ok"); // The representable header still travelled: dropping the bad one must not drop the rest. _receivedExchange!.In.Headers.Should().ContainKey("x-normal"); } private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); } Path: redb-route/tests/redb.Route.Tests.Grpc/GrpcInteropTests.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/tests/redb.Route.Tests.Grpc/GrpcInteropTests.cs ---- using System.Diagnostics; using System.Net.Sockets; using System.Text; using System.Text.Json; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Grpc; namespace redb.Route.Tests.Grpc; /// /// Live interop against an independent gRPC stack — @grpc/grpc-js, which shares no code with this /// connector (profile grpc of docker-compose.tests.yml). This is what loopback e2e cannot prove: that a foreign /// implementation accepts our hand-written framing, trailers, statuses, mTLS handshake and gzip, and that /// we accept its. It is also the only cross-process coverage — the client runs inside the container. /// /// The contract is a typed .proto (interop.Echo), not the generic RedbService, /// so it doubles as proof that a generated client can call a redb route with no server stubs on our side. /// Messages are encoded by hand here (one string field) to keep the test free of generated code. /// /// /// GATED: every test no-ops unless the container answers on 127.0.0.1:18100, so the normal suite stays /// green without it. Run with --filter Category=Interop once the grpc profile is up: /// docker compose -f redb.Route/docker-compose.tests.yml --profile grpc up -d --wait. /// /// [Trait("Category", "Interop")] public class GrpcInteropTests { private const string Host = "127.0.0.1"; private const int ServerPort = 18100; // @grpc/grpc-js echo server (compose mapping) // The mTLS material from redb.Route/tests/docker/gen-certs.sh (.generated/grpc). private static string CertDir => Environment.GetEnvironmentVariable("REDB_GRPC_CERTS") ?? global::redb.Route.Tests.Shared.TestStand.Generated("grpc"); // Our consumers; the container reaches them via host-gateway. Offset by runtime major so the parallel // multi-TFM test hosts never contend for the same port. private static readonly int PlainPort = 18110 + Environment.Version.Major; private static readonly int TlsPort = 18120 + Environment.Version.Major; private static readonly int StreamPort = 18130 + Environment.Version.Major; private static readonly int StatusPort = 18140 + Environment.Version.Major; // ── Direction A: our producer → the independent grpc-js server ── [Fact] public async Task Redb_producer_to_grpcjs_server_echoes() { if (!IsReachable(Host, ServerPort)) return; // gated: profile grpc of docker-compose.tests.yml await using var ctx = NewContext(); ctx.AddRoutes(r => r.From("direct://call") .To(GrpcDsl.Call($"{Host}:{ServerPort}").Method("/interop.Echo/Say").Plaintext())); await ctx.Start(); var producer = ctx.GetEndpoint("direct://call").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message(EncodeString("hello-redb"))); await producer.Process(exchange); // A foreign gRPC server parsed our request frame, ran Say, and we read its reply frame back. exchange.HasOut.Should().BeTrue(); DecodeString((byte[])exchange.Out!.Body!).Should().Be("echo:hello-redb"); } [Fact] public async Task Redb_producer_reads_a_grpcjs_server_stream() { if (!IsReachable(Host, ServerPort)) return; await using var ctx = NewContext(); ctx.AddRoutes(r => r.From("direct://stream") .To(GrpcDsl.Call($"{Host}:{ServerPort}").Method("/interop.Echo/SayMany").Plaintext().Streaming())); await ctx.Start(); var producer = ctx.GetEndpoint("direct://stream").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message(EncodeString("go"))); await producer.Process(exchange); var items = new List(); await foreach (var item in (IAsyncEnumerable)exchange.Out!.Body!) items.Add(DecodeString((byte[])item!)); items.Should().Equal("page-1", "page-2", "page-3"); } // ── Direction B: the independent grpc-js client → our consumer ── [Fact] public async Task Grpcjs_client_to_redb_consumer_echoes() { if (!IsReachable(Host, ServerPort)) return; await using var ctx = NewContext(); ctx.AddRoutes(r => r.From(GrpcDsl.Listen($"0.0.0.0:{PlainPort}").Method("/interop.Echo/Say")) .Process(e => e.Out = new Message(EncodeString("echo:" + DecodeString((byte[])e.In.Body!))))); await ctx.Start(); var result = RunClient($"host.docker.internal:{PlainPort}", "say"); result.GetProperty("ok").GetBoolean().Should().BeTrue(); result.GetProperty("value").GetString().Should().Be("echo:hello-redb"); } [Fact] public async Task Grpcjs_client_gets_a_real_status_from_our_consumer() { if (!IsReachable(Host, ServerPort)) return; await using var ctx = NewContext(); ctx.AddRoutes(r => r.From(GrpcDsl.Listen($"0.0.0.0:{StatusPort}").Method("/interop.Echo/Say")) .Process(e => { e.Out = new Message(Array.Empty()); e.Out.Headers["status.code"] = 403; // what a controller dispatcher writes e.Out.Headers[GrpcHeaders.StatusDetail] = "scope required"; })); await ctx.Start(); var result = RunClient($"host.docker.internal:{StatusPort}", "say"); result.GetProperty("ok").GetBoolean().Should().BeFalse(); result.GetProperty("code").GetInt32().Should().Be(7); // PERMISSION_DENIED result.GetProperty("details").GetString().Should().Be("scope required"); } [Fact] public async Task Grpcjs_client_reads_our_server_stream() { if (!IsReachable(Host, ServerPort)) return; await using var ctx = NewContext(); ctx.AddRoutes(r => r.From(GrpcDsl.Listen($"0.0.0.0:{StreamPort}") .Method("/interop.Echo/SayMany").Streaming()) .Process(e => e.Out = new Message(Pages()))); await ctx.Start(); var result = RunClient($"host.docker.internal:{StreamPort}", "saymany"); result.GetProperty("ok").GetBoolean().Should().BeTrue(); result.GetProperty("value").EnumerateArray().Select(x => x.GetString()) .Should().Equal("page-1", "page-2", "page-3"); static async IAsyncEnumerable Pages() { for (var i = 1; i <= 3; i++) { await Task.Yield(); yield return EncodeString($"page-{i}"); } } } [Fact] public async Task Grpcjs_client_over_mtls_is_authenticated_by_thumbprint() { if (!IsReachable(Host, ServerPort)) return; if (!File.Exists(Path.Combine(CertDir, "server.pfx"))) return; // gated: certs not generated var clientThumbprint = ThumbprintOf(Path.Combine(CertDir, "client.crt")); await using var ctx = NewContext(); ctx.AddRoutes(r => r.From(GrpcDsl.Listen($"0.0.0.0:{TlsPort}") .Method("/interop.Echo/Say") .Ssl() .SslCertPath(Path.Combine(CertDir, "server.pfx")) .SslCertPassword("redb") .ClientCertificates(GrpcClientCertificateMode.RequireCertificate, clientThumbprint)) .Process(e => e.Out = new Message(EncodeString( "mtls:" + e.In.GetHeader(GrpcHeaders.ClientCertSubject))))); await ctx.Start(); var result = RunClient($"host.docker.internal:{TlsPort}", "say", "--tls"); // A real TLS handshake with a client certificate, driven by a foreign stack, and the certificate // surfaced to the route. result.GetProperty("ok").GetBoolean().Should().BeTrue(); result.GetProperty("value").GetString().Should().Contain("redb-interop-client"); } [Fact] public async Task Grpcjs_client_may_gzip_its_request() { if (!IsReachable(Host, ServerPort)) return; var port = PlainPort + 100; await using var ctx = NewContext(); ctx.AddRoutes(r => r.From(GrpcDsl.Listen($"0.0.0.0:{port}") .Method("/interop.Echo/Say").Compression(GrpcCompression.Gzip)) .Process(e => e.Out = new Message(EncodeString("gz:" + DecodeString((byte[])e.In.Body!))))); await ctx.Start(); var result = RunClient($"host.docker.internal:{port}", "say", "--gzip", "--msg=" + new string('c', 512)); result.GetProperty("ok").GetBoolean().Should().BeTrue(); result.GetProperty("value").GetString().Should().Be("gz:" + new string('c', 512)); } // ── helpers ─────────────────────────────────────────────── private static RouteContext NewContext() { var ctx = new RouteContext(); ctx.AddComponent(new GrpcComponent()); return ctx; } /// Runs the container's grpc-js client and returns its JSON verdict. private static JsonElement RunClient(string target, string method, params string[] flags) { var args = $"exec grpc-echo node client.js {target} {method} {string.Join(' ', flags)}"; using var process = Process.Start(new ProcessStartInfo("docker", args) { RedirectStandardOutput = true, RedirectStandardError = true, })!; var stdout = process.StandardOutput.ReadToEnd(); var stderr = process.StandardError.ReadToEnd(); process.WaitForExit(60_000); var line = stdout.Split('\n', StringSplitOptions.RemoveEmptyEntries) .LastOrDefault(l => l.TrimStart().StartsWith('{')); line.Should().NotBeNull($"client produced no verdict. stdout={stdout} stderr={stderr}"); return JsonDocument.Parse(line!).RootElement.Clone(); } /// Encodes { string field 1 } — the whole schema of the interop messages. private static byte[] EncodeString(string value) { var utf8 = Encoding.UTF8.GetBytes(value); var length = new List(); var remaining = (uint)utf8.Length; do { var chunk = (byte)(remaining & 0x7F); remaining >>= 7; if (remaining > 0) chunk |= 0x80; length.Add(chunk); } while (remaining > 0); var result = new byte[1 + length.Count + utf8.Length]; result[0] = 0x0A; // field 1, wire type 2 (length-delimited) length.CopyTo(result, 1); utf8.CopyTo(result, 1 + length.Count); return result; } private static string DecodeString(byte[] message) { if (message.Length == 0) return string.Empty; message[0].Should().Be(0x0A); var offset = 1; var length = 0; var shift = 0; while (true) { var b = message[offset++]; length |= (b & 0x7F) << shift; if ((b & 0x80) == 0) break; shift += 7; } return Encoding.UTF8.GetString(message, offset, length); } private static string ThumbprintOf(string pemPath) { var cert = System.Security.Cryptography.X509Certificates.X509Certificate2 .CreateFromPem(File.ReadAllText(pemPath)); return cert.Thumbprint; } private static bool IsReachable(string host, int port) { try { using var client = new TcpClient(); return client.ConnectAsync(host, port).Wait(TimeSpan.FromMilliseconds(750)) && client.Connected; } catch { return false; } } } Path: redb-route/tests/redb.Route.Tests.Grpc/GrpcPrincipalTests.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/tests/redb.Route.Tests.Grpc/GrpcPrincipalTests.cs ---- using System.Net; using System.Net.Sockets; using System.Security.Claims; using System.Text; using Grpc.Core; using Grpc.Net.Client; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Grpc; using redb.Route.Http; namespace redb.Route.Tests.Grpc; /// /// The caller's identity on gRPC exchanges: the shared host's resolver identifies the call from its /// metadata, and the consumer puts the principal on the exchange (). /// public sealed class GrpcPrincipalTests : IAsyncLifetime { private const string MethodPath = "/probe.v1.Probe/Who"; private int _port; private SharedHttpServerManager _manager = null!; private RouteContext _context = null!; public async Task InitializeAsync() { _port = GetFreePort(); _manager = new SharedHttpServerManager(new HttpHostingOptions { ResolvePrincipal = ctx => Task.FromResult(ctx.Request.Headers["x-test-token"].ToString() == "good" ? new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, "grpc-user")], "test")) : null), }); _context = new RouteContext(); _context.AddComponent(new GrpcComponent { ServerManager = _manager }); _context.AddRoutes(r => r.From(GrpcDsl.Listen($"127.0.0.1:{_port}").Method(MethodPath)) .Process(e => e.Out = new Message( ExchangePrincipal.Get(e)?.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "anonymous"))); await _context.Start(); } public async Task DisposeAsync() { await _context.DisposeAsync(); await _manager.DisposeAsync(); } [Fact] public async Task IdentifiedCall_PrincipalReachesTheExchange() { (await Call("good")).Should().Be("grpc-user"); } [Fact] public async Task AnonymousCall_CarriesNoIdentity() { (await Call(null)).Should().Be("anonymous"); } private async Task Call(string? token) { using var channel = GrpcChannel.ForAddress($"http://127.0.0.1:{_port}"); var slash = MethodPath.LastIndexOf('/'); var marshaller = Marshallers.Create(b => (byte[])b, b => b); var method = new Method( MethodType.Unary, MethodPath[1..slash], MethodPath[(slash + 1)..], marshaller, marshaller); var metadata = new Metadata(); if (token is not null) metadata.Add("x-test-token", token); var reply = await channel.CreateCallInvoker() .AsyncUnaryCall(method, null, new CallOptions(metadata), Array.Empty()); return Encoding.UTF8.GetString(reply); } private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); } Path: redb-route/tests/redb.Route.Tests.Grpc/GrpcProducerTests.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/tests/redb.Route.Tests.Grpc/GrpcProducerTests.cs ---- using System.Net; using Google.Protobuf; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Grpc; using redb.Route.Grpc.Proto; namespace redb.Route.Tests.Grpc; /// /// Producer tests. Starts a real gRPC consumer (server) and uses GrpcProducer to call it. /// public class GrpcProducerTests : IAsyncLifetime { private GrpcConsumer? _consumer; private GrpcProducer? _producer; private int _port; private IExchange? _serverExchange; public Task InitializeAsync() { _port = GetFreePort(); return Task.CompletedTask; } public async Task DisposeAsync() { if (_producer is not null) await _producer.Stop(); if (_consumer is not null) await _consumer.Stop(); } /// Starts a consumer as the test gRPC server. private async Task StartTestServer(Func? onProcess = null) { var component = new GrpcComponent(); var parameters = new Dictionary { ["host"] = "127.0.0.1", ["port"] = _port.ToString(), ["inOut"] = "true" }; var uri = new EndpointUri("grpc", $"/127.0.0.1:{_port}", $"grpc:127.0.0.1:{_port}", parameters); var endpoint = (GrpcEndpoint)component.CreateEndpoint(uri); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(async ci => { var ex = ci.Arg(); _serverExchange = ex; if (onProcess is not null) await onProcess(ex); }); _consumer = new GrpcConsumer(endpoint, processor, endpoint.EndpointOptions); await _consumer.Start(); return _consumer; } private GrpcProducer CreateProducer(Dictionary? extraParams = null) { var component = new GrpcComponent(); var parameters = new Dictionary { ["plaintext"] = "true" }; if (extraParams is not null) { foreach (var (key, value) in extraParams) parameters[key] = value; } var uri = new EndpointUri("grpc", $"/127.0.0.1:{_port}", $"grpc:127.0.0.1:{_port}", parameters); var endpoint = (GrpcEndpoint)component.CreateEndpoint(uri); _producer = new GrpcProducer(endpoint, endpoint.EndpointOptions); return _producer; } // ── Lifecycle ── [Fact] public async Task Start_CreatesChannel() { await StartTestServer(); var producer = CreateProducer(); await producer.Start(); // Should not throw — producer starts successfully } [Fact] public async Task Process_NotStarted_Throws() { var producer = CreateProducer(); var exchange = new Exchange(new Message("test")); var act = async () => await producer.Process(exchange); await act.Should().ThrowAsync(); } // ── Request/Response ── [Fact] public async Task Process_SendsRequest_ServerReceives() { await StartTestServer(ex => { ex.Out = new Message("ack"); return Task.CompletedTask; }); var producer = CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("producer-payload")); await producer.Process(exchange); _serverExchange.Should().NotBeNull(); System.Text.Encoding.UTF8.GetString((byte[])_serverExchange!.In.Body!).Should().Be("producer-payload"); } [Fact] public async Task Process_ReceivesResponse_MapsToOut() { await StartTestServer(ex => { ex.Out = new Message("server-response"); ex.Out.Headers["result"] = "success"; return Task.CompletedTask; }); var producer = CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("request")); await producer.Process(exchange); exchange.Out.Should().NotBeNull(); var responseBody = System.Text.Encoding.UTF8.GetString((byte[])exchange.Out!.Body!); responseBody.Should().Be("server-response"); exchange.Out.Headers["result"].Should().Be("success"); } [Fact] public async Task Process_StatusCode_SetToOK() { await StartTestServer(ex => { ex.Out = new Message("ok"); return Task.CompletedTask; }); var producer = CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("test")); await producer.Process(exchange); exchange.Out.Should().NotBeNull(); exchange.Out!.Headers.Should().ContainKey(GrpcHeaders.StatusCode); ((int)exchange.Out.Headers[GrpcHeaders.StatusCode]!).Should().Be(0); // OK = 0 } [Fact] public async Task Process_ByteBody_Preserved() { await StartTestServer(ex => { // Echo back ex.Out = new Message(ex.In.Body); return Task.CompletedTask; }); var producer = CreateProducer(); await producer.Start(); var payload = new byte[] { 0xDE, 0xAD, 0xBE, 0xEF }; var exchange = new Exchange(new Message(payload)); await producer.Process(exchange); exchange.Out.Should().NotBeNull(); ((byte[])exchange.Out!.Body!).Should().BeEquivalentTo(payload); } [Fact] public async Task Process_StringBody_Handled() { await StartTestServer(ex => { ex.Out = new Message("echo"); return Task.CompletedTask; }); var producer = CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("string-body")); await producer.Process(exchange); _serverExchange.Should().NotBeNull(); System.Text.Encoding.UTF8.GetString((byte[])_serverExchange!.In.Body!).Should().Be("string-body"); } [Fact] public async Task Process_ObjectBody_UsesToString() { await StartTestServer(ex => { ex.Out = new Message("ok"); return Task.CompletedTask; }); var producer = CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message(12345)); await producer.Process(exchange); _serverExchange.Should().NotBeNull(); System.Text.Encoding.UTF8.GetString((byte[])_serverExchange!.In.Body!).Should().Be("12345"); } [Fact] public async Task Process_NullBody_ServerReceivesEmpty() { await StartTestServer(ex => { ex.Out = new Message("ack"); return Task.CompletedTask; }); var producer = CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message(null)); await producer.Process(exchange); _serverExchange.Should().NotBeNull(); _serverExchange!.In.Body.Should().BeNull(); } [Fact] public async Task Process_Headers_PropagatedAsProtoHeaders() { await StartTestServer(ex => { ex.Out = new Message("ok"); return Task.CompletedTask; }); var producer = CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("test")); exchange.In.Headers["custom-key"] = "custom-value"; exchange.In.Headers["operation"] = "update"; await producer.Process(exchange); // The server receives the headers via proto message headers _serverExchange.Should().NotBeNull(); _serverExchange!.In.Headers["custom-key"].Should().Be("custom-value"); _serverExchange!.In.Headers["operation"].Should().Be("update"); } [Fact] public async Task Process_RedbHeaders_NotPropagated() { await StartTestServer(ex => { ex.Out = new Message("ok"); return Task.CompletedTask; }); var producer = CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("test")); exchange.In.Headers[GrpcHeaders.Method] = "should-be-skipped"; exchange.In.Headers["keep-me"] = "yes"; await producer.Process(exchange); _serverExchange.Should().NotBeNull(); // The redb header should not be in the proto headers on the server side _serverExchange!.In.Headers.Keys .Where(k => k.ToString()! == "keep-me") .Should().NotBeEmpty(); } [Fact] public async Task Process_ServerError_SetsExceptionAndStatusHeaders() { await StartTestServer(_ => throw new InvalidOperationException("server fault")); var producer = CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("fail")); // ThrowOnError (default) — a failed call must reach .OnException / retry, like Http and Soap. var act = async () => await producer.Process(exchange); await act.Should().ThrowAsync(); exchange.Exception.Should().BeOfType(); exchange.In.Headers.Should().ContainKey(GrpcHeaders.StatusCode); ((int)exchange.In.Headers[GrpcHeaders.StatusCode]!).Should().Be((int)global::Grpc.Core.StatusCode.Internal); exchange.In.Headers.Should().ContainKey(GrpcHeaders.StatusDetail); } [Fact] public async Task Process_Deadline_Passed() { // Use a very long deadline so it doesn't expire await StartTestServer(ex => { ex.Out = new Message("ok"); return Task.CompletedTask; }); var producer = CreateProducer(new Dictionary { ["deadline"] = "60000" }); await producer.Start(); var exchange = new Exchange(new Message("deadline-test")); await producer.Process(exchange); exchange.Out.Should().NotBeNull(); } private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); [Fact] public void Asking_a_producer_for_tls_does_not_leave_it_in_cleartext() { // .Ssl() is the obvious way to ask a client for TLS. It sets ssl=true — and the producer builds // its address from Plaintext, which defaults to true and which nothing here touched. The call // then goes out over http:// with the endpoint believing it is secured. Only negotiationType=TLS // happened to link the two. var uri = GrpcDsl.Call("secure.internal:443").Ssl().Build(); var endpoint = (GrpcEndpoint)new GrpcComponent().CreateEndpoint( EndpointUriParser.Parse(uri + "&sslCertPath=/etc/redb/x.pfx")); endpoint.BuildProducerAddress().Should().StartWith("https://", "a producer told to use TLS must not connect in the clear"); } [Fact] public void An_explicit_plaintext_still_wins_over_ssl() { // The inverse must keep working: someone who says plaintext outright gets it, whatever else the // URI carries. Otherwise the fix above would take away a knob people use for local debugging. var uri = GrpcDsl.Call("localhost:5000").Ssl().Plaintext().Build(); var endpoint = (GrpcEndpoint)new GrpcComponent().CreateEndpoint( EndpointUriParser.Parse(uri + "&sslCertPath=/etc/redb/x.pfx")); endpoint.BuildProducerAddress().Should().StartWith("http://"); } } Path: redb-route/tests/redb.Route.Tests.Grpc/GrpcRawFramingProbeTests.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/tests/redb.Route.Tests.Grpc/GrpcRawFramingProbeTests.cs ---- using System.Buffers.Binary; using System.Net; using System.Net.Sockets; using Google.Protobuf; using Grpc.Core; using Grpc.Net.Client; using Microsoft.AspNetCore.Http; using redb.Route.Grpc.Proto; using redb.Route.Http; using RouteHttpProtocol = redb.Route.Http.HttpProtocol; namespace redb.Route.Tests.Grpc; /// /// PROBE (G1 option C): can we serve gRPC as a plain path route on the shared Kestrel host, /// with our own wire framing, instead of pulling in the Grpc.AspNetCore server stack? /// /// The whole point is the client side: every test here drives a real /// + generated RedbServiceClient. If our framing were wrong the /// client would fail, so a green run is interop evidence, not a self-consistent mock. /// /// /// Wire format under test (gRPC over HTTP/2, unary): /// request/response body = [1 byte compressed-flag][4 bytes length BE][message], /// content-type application/grpc, HTTP status always 200, real status in the /// grpc-status / grpc-message trailers, deadline arrives as grpc-timeout. /// /// public sealed class GrpcRawFramingProbeTests : IAsyncLifetime { private const string Host = "127.0.0.1"; private const string ProcessPath = "/redb.route.grpc.RedbService/Process"; private const string GrpcContentType = "application/grpc"; private readonly SharedHttpServerManager _server = new(); private int _port; public Task InitializeAsync() { _port = GetFreePort(); return Task.CompletedTask; } public async Task DisposeAsync() => await _server.DisposeAsync(); // ── Probe 1: does a real gRPC client accept our hand-rolled unary response? ── [Fact] public async Task Unary_RoundTrip_Works_Against_A_Real_Grpc_Client() { await Serve(async http => { var request = await ReadMessage(http, RedbMessage.Parser); var reply = new RedbMessage { Payload = ByteString.CopyFromUtf8("pong:" + request.Payload.ToStringUtf8()), }; reply.Headers["handled-by"] = "raw-framing"; reply.Headers["echo-operation"] = request.Headers["operation"]; await WriteMessage(http, reply, StatusCode.OK); }); var client = CreateClient(); var request = new RedbMessage { Payload = ByteString.CopyFromUtf8("ping") }; request.Headers["operation"] = "echo"; var reply = await client.ProcessAsync(request); reply.Payload.ToStringUtf8().Should().Be("pong:ping"); reply.Headers["handled-by"].Should().Be("raw-framing"); reply.Headers["echo-operation"].Should().Be("echo"); } // ── Probe 2: can we return a real gRPC status (the thing G2 needs)? ── [Fact] public async Task Trailers_Only_Error_Surfaces_As_RpcException_With_The_Right_Status() { await Serve(http => WriteMessage(http, null, StatusCode.PermissionDenied, "scope 'identity:manage' required")); var client = CreateClient(); var act = async () => await client.ProcessAsync(new RedbMessage()); var ex = await act.Should().ThrowAsync(); ex.Which.StatusCode.Should().Be(StatusCode.PermissionDenied); ex.Which.Status.Detail.Should().Be("scope 'identity:manage' required"); } // ── Probe 3: does the client's deadline reach us as a header we can honour? ── [Fact] public async Task Client_Deadline_Arrives_As_Grpc_Timeout_Header() { string? timeout = null; await Serve(async http => { timeout = http.Request.Headers["grpc-timeout"].ToString(); await ReadMessage(http, RedbMessage.Parser); await WriteMessage(http, new RedbMessage(), StatusCode.OK); }); var client = CreateClient(); await client.ProcessAsync(new RedbMessage(), deadline: DateTime.UtcNow.AddSeconds(30)); timeout.Should().NotBeNullOrEmpty("the client must send its deadline as grpc-timeout"); // Format is , e.g. "29999m" (milliseconds) or "30S". timeout.Should().MatchRegex("^[0-9]+[HMSmun]$"); } // ── Probe 4: many methods on one port — the reason for option C in the first place ── [Fact] public async Task Two_Methods_On_One_Port_Are_Routed_By_Path() { _server.RegisterRoute(Host, _port, "/identity.v1.Identity/Token", "POST", http => Reply(http, "token"), protocol: RouteHttpProtocol.Http2); _server.RegisterRoute(Host, _port, "/identity.v1.Identity/Introspect", "POST", http => Reply(http, "introspect"), protocol: RouteHttpProtocol.Http2); await _server.EnsureStarted(Host, _port); using var channel = GrpcChannel.ForAddress($"http://{Host}:{_port}"); (await CallRaw(channel, "/identity.v1.Identity/Token")).Should().Be("token"); (await CallRaw(channel, "/identity.v1.Identity/Introspect")).Should().Be("introspect"); static async Task Reply(HttpContext http, string who) { await ReadMessage(http, RedbMessage.Parser); await WriteMessage(http, new RedbMessage { Payload = ByteString.CopyFromUtf8(who) }, StatusCode.OK); } } // ── helpers ─────────────────────────────────────────────── private async Task Serve(Func handler) { _server.RegisterRoute(Host, _port, ProcessPath, "POST", handler, protocol: RouteHttpProtocol.Http2); await _server.EnsureStarted(Host, _port); } private RedbService.RedbServiceClient CreateClient() => new(GrpcChannel.ForAddress($"http://{Host}:{_port}")); /// Calls an arbitrary method path with the generic message, bypassing generated stubs. private static async Task CallRaw(GrpcChannel channel, string fullMethodPath) { var slash = fullMethodPath.LastIndexOf('/'); var method = new Method( MethodType.Unary, fullMethodPath[1..slash], fullMethodPath[(slash + 1)..], Marshallers.Create(m => m.ToByteArray(), RedbMessage.Parser.ParseFrom), Marshallers.Create(m => m.ToByteArray(), RedbMessage.Parser.ParseFrom)); var reply = await channel.CreateCallInvoker() .AsyncUnaryCall(method, null, new CallOptions(), new RedbMessage()); return reply.Payload.ToStringUtf8(); } private static async Task ReadMessage(HttpContext http, MessageParser parser) where T : IMessage { using var buffer = new MemoryStream(); await http.Request.Body.CopyToAsync(buffer, http.RequestAborted); var bytes = buffer.ToArray(); bytes.Length.Should().BeGreaterThanOrEqualTo(5, "a gRPC frame carries a 5-byte prefix"); bytes[0].Should().Be(0, "compressed frames are out of scope for the probe"); var length = BinaryPrimitives.ReadUInt32BigEndian(bytes.AsSpan(1, 4)); return parser.ParseFrom(bytes.AsSpan(5, (int)length).ToArray()); } private static async Task WriteMessage(HttpContext http, IMessage? message, StatusCode status, string? detail = null) { http.Response.ContentType = GrpcContentType; if (message is not null) { var payload = message.ToByteArray(); var frame = new byte[5 + payload.Length]; frame[0] = 0; BinaryPrimitives.WriteUInt32BigEndian(frame.AsSpan(1, 4), (uint)payload.Length); payload.CopyTo(frame, 5); await http.Response.Body.WriteAsync(frame, http.RequestAborted); await http.Response.Body.FlushAsync(http.RequestAborted); } http.Response.AppendTrailer("grpc-status", ((int)status).ToString()); if (!string.IsNullOrEmpty(detail)) http.Response.AppendTrailer("grpc-message", Uri.EscapeDataString(detail)); } private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); } Path: redb-route/tests/redb.Route.Tests.Grpc/GrpcRestartTests.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/tests/redb.Route.Tests.Grpc/GrpcRestartTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Grpc; namespace redb.Route.Tests.Grpc; /// /// A gRPC consumer and producer keep working after Stop() and Start() of the same route context: the stop /// gives the listener back, the start takes it again, and the producer of the cached endpoint still calls. /// public sealed class GrpcRestartTests { private static string? Text(object? body) => body is byte[] bytes ? System.Text.Encoding.UTF8.GetString(bytes) : body?.ToString(); [Fact] public async Task Consumer_and_producer_work_after_the_context_is_stopped_and_started_again() { var port = global::redb.Route.Tests.Shared.TestPorts.Next(); await using var ctx = new RouteContext(); ctx.AddComponent(new GrpcComponent()); ctx.AddRoutes(r => r.From($"grpc://127.0.0.1:{port}?inOut=true").Process(e => e.Out = new Message($"re:{Text(e.In.Body)}"))); ctx.AddRoutes(r => r.From("direct://call").To($"grpc://127.0.0.1:{port}?plaintext=true")); async Task CheckAsync(string body) { var producer = ctx.GetEndpoint("direct://call").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message(body)); await producer.Process(exchange); exchange.Exception.Should().BeNull("a gRPC call after a restart arrives"); var reply = (exchange.HasOut ? exchange.Out! : exchange.In).Body; Text(reply).Should().Be($"re:{body}"); } await ctx.Start(); await CheckAsync("first"); await ctx.Stop(); await ctx.Start(); await CheckAsync("second"); } } Path: redb-route/tests/redb.Route.Tests.Grpc/GrpcRouteEngineTests.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/tests/redb.Route.Tests.Grpc/GrpcRouteEngineTests.cs ---- using System.Net; using System.Net.Sockets; using Google.Protobuf; using Grpc.Core; using Grpc.Net.Client; using Microsoft.Extensions.DependencyInjection; using redb.Route.Core; using redb.Route.Grpc; using redb.Route.Grpc.Proto; namespace redb.Route.Tests.Grpc; /// /// End-to-end through the real engine: routes declared with the DSL inside a , /// started by the context, called by a real gRPC client. The consumer-level tests build endpoints by /// hand; this one proves the same thing the way a module actually wires it — including that several gRPC /// routes in one context share a single Kestrel host instead of fighting over the port. /// public sealed class GrpcRouteEngineTests : IAsyncLifetime { private ServiceProvider _sp = null!; private RouteContext _context = null!; private int _port; public Task InitializeAsync() { _port = GetFreePort(); var services = new ServiceCollection(); services.AddRedbRouteGrpc(); // registers the component + shared Kestrel host _sp = services.BuildServiceProvider(); _context = new RouteContext(_sp, "grpc-engine-test"); _context.AddComponent(new GrpcComponent { ServerManager = _sp.GetRequiredService(), }); return Task.CompletedTask; } public async ValueTask DisposeAsyncCore() { await _context.DisposeAsync(); await _sp.DisposeAsync(); } public async Task DisposeAsync() => await DisposeAsyncCore(); [Fact] public async Task Two_dsl_routes_share_one_port_and_answer_by_method_address() { _context.AddRoutes(r => { r.From(GrpcDsl.Listen($"127.0.0.1:{_port}").Method("/identity.v1.Identity/Token")) .RouteId("grpc-token") .Process(e => e.Out = new Message("token-reply")); }); _context.AddRoutes(r => { r.From(GrpcDsl.Listen($"127.0.0.1:{_port}").Method("/identity.v1.Identity/Introspect")) .RouteId("grpc-introspect") .Process(e => e.Out = new Message("introspect-reply")); }); await _context.Start(); (await Call("/identity.v1.Identity/Token")).Should().Be("token-reply"); (await Call("/identity.v1.Identity/Introspect")).Should().Be("introspect-reply"); // Each address is its own route, with its own id and lifecycle — the point of the whole design. _context.Routes.Select(x => x.RouteId).Should().Contain(["grpc-token", "grpc-introspect"]); } [Fact] public async Task Generic_service_route_still_works_through_the_dsl() { _context.AddRoutes(r => { r.From(GrpcDsl.Listen($"127.0.0.1:{_port}")) .RouteId("grpc-generic") .Process(e => e.Out = new Message("generic-reply")); }); await _context.Start(); using var channel = GrpcChannel.ForAddress($"http://127.0.0.1:{_port}"); var reply = await new RedbService.RedbServiceClient(channel) .ProcessAsync(new RedbMessage { Payload = ByteString.CopyFromUtf8("ping") }); reply.Payload.ToStringUtf8().Should().Be("generic-reply"); } private async Task Call(string methodPath) { using var channel = GrpcChannel.ForAddress($"http://127.0.0.1:{_port}"); var slash = methodPath.LastIndexOf('/'); var marshaller = Marshallers.Create(b => (byte[])b, b => b); var method = new Method( MethodType.Unary, methodPath[1..slash], methodPath[(slash + 1)..], marshaller, marshaller); var reply = await channel.CreateCallInvoker() .AsyncUnaryCall(method, null, new CallOptions(), Array.Empty()); return System.Text.Encoding.UTF8.GetString(reply); } private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); } Path: redb-route/tests/redb.Route.Tests.Grpc/GrpcStopDrainsInflightTests.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/tests/redb.Route.Tests.Grpc/GrpcStopDrainsInflightTests.cs ---- using System.Net; using System.Net.Sockets; using AwesomeAssertions; using Google.Protobuf; using Grpc.Net.Client; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Grpc; using redb.Route.Grpc.Proto; namespace redb.Route.Tests.Grpc; /// /// Stopping a gRPC route must wait for the calls it is already serving. It used to unregister its /// routes and ask the listener to stop when empty, and a listener shared with another route stays up /// — so nobody waited and a deploy cut the call mid-pipeline. Reported by the AS4 agent 2026-09-25; /// the drain is the engine's . /// public class GrpcStopDrainsInflightTests { private static int FreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); [Fact] public async Task Stop_waits_for_a_call_already_in_the_pipeline() { var port = FreePort(); var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var finished = false; var component = new GrpcComponent(); var uri = new EndpointUri("grpc", $"/127.0.0.1:{port}", $"grpc:127.0.0.1:{port}", new Dictionary { ["host"] = "127.0.0.1", ["port"] = port.ToString() }); var endpoint = (GrpcEndpoint)component.CreateEndpoint(uri); var consumer = new GrpcConsumer(endpoint, new redb.Route.Processors.DelegateProcessor(async (e, ct) => { entered.TrySetResult(); await release.Task; finished = true; e.Out = new Message(ByteString.CopyFromUtf8("ok").ToByteArray()); }), endpoint.EndpointOptions); await consumer.Start(); using var channel = GrpcChannel.ForAddress($"http://127.0.0.1:{port}", new GrpcChannelOptions { HttpHandler = new SocketsHttpHandler { EnableMultipleHttp2Connections = true } }); var client = new RedbService.RedbServiceClient(channel); var call = client.ProcessAsync(new RedbMessage { Payload = ByteString.CopyFromUtf8("payload") }).ResponseAsync; await entered.Task.WaitAsync(TimeSpan.FromSeconds(10)); var stop = consumer.Stop(); (await Task.WhenAny(stop, Task.Delay(500)) == stop) .Should().BeFalse("Stop must not return while a call is still inside the pipeline"); release.TrySetResult(); await stop.WaitAsync(TimeSpan.FromSeconds(15)); finished.Should().BeTrue(); await call; } } Path: redb-route/tests/redb.Route.Tests.Grpc/GrpcTelemetrySmokeTests.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/tests/redb.Route.Tests.Grpc/GrpcTelemetrySmokeTests.cs ---- using System.Diagnostics; using System.Net; using System.Net.Sockets; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Grpc; using redb.Route.Telemetry; using redb.Route.Tests.Shared; namespace redb.Route.Tests.Grpc; /// Smoke test for the P1 transport span opened by . public sealed class GrpcTelemetrySmokeTests : IAsyncLifetime { private GrpcConsumer? _consumer; private GrpcProducer? _producer; private int _port; public Task InitializeAsync() { _port = GetFreePort(); return Task.CompletedTask; } public async Task DisposeAsync() { if (_producer is not null) await _producer.Stop(); if (_consumer is not null) await _consumer.Stop(); } [Fact] public async Task GrpcProducer_EmitsTransportSpanWithRpcTags() { var component = new GrpcComponent(); // Server var serverPars = new Dictionary { ["host"] = "127.0.0.1", ["port"] = _port.ToString(), ["inOut"] = "true" }; var serverUri = new EndpointUri("grpc", $"/127.0.0.1:{_port}", $"grpc:127.0.0.1:{_port}", serverPars); var serverEndpoint = (GrpcEndpoint)component.CreateEndpoint(serverUri); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { ci.Arg().Out = new Message("ack"); return Task.CompletedTask; }); _consumer = new GrpcConsumer(serverEndpoint, processor, serverEndpoint.EndpointOptions); await _consumer.Start(); // Client var clientPars = new Dictionary { ["plaintext"] = "true" }; var clientUri = new EndpointUri("grpc", $"/127.0.0.1:{_port}", $"grpc:127.0.0.1:{_port}", clientPars); var clientEndpoint = (GrpcEndpoint)component.CreateEndpoint(clientUri); _producer = new GrpcProducer(clientEndpoint, clientEndpoint.EndpointOptions); using var capture = new SpanCapture(); // this test's spans only await _producer.Start(); await _producer.Process(new Exchange(new Message("hello"))); var activities = capture.Spans; activities.Should().NotBeEmpty(); // Both sides emit a span in this test's trace (the consumer opens "grpc receive" as a Server span, // mirroring the As2 and Soap consumers), so select the producer's span by name and kind. var activity = activities.First(a => a.Kind == ActivityKind.Client && a.OperationName == "grpc.invoke"); activity.Source.Name.Should().Be(RouteActivitySource.SourceName); activity.GetTagItem("rpc.system").Should().Be("grpc"); activity.GetTagItem("redb.route.endpoint").Should().NotBeNull(); } private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); } Path: redb-route/tests/redb.Route.Tests.Grpc/GrpcTracePropagationTests.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/tests/redb.Route.Tests.Grpc/GrpcTracePropagationTests.cs ---- using System.Diagnostics; using System.Text; using Grpc.Core; using Grpc.Net.Client; using Microsoft.Extensions.DependencyInjection; using redb.Route.Configuration; using redb.Route.Core; using redb.Route.Grpc; using redb.Route.Telemetry; using redb.Route.Tests.Telemetry; namespace redb.Route.Tests.Grpc; /// /// A gRPC call is inbound traffic like an HTTP request: the consumer's server span continues the caller's trace from /// traceparent and puts the caller's baggage back, the route's spans sit under it, and a failed route marks it /// red. A proxying producer sends the context of its own span, not the caller's header the bridge copied into the /// metadata. EnableTelemetry=false opens none of these spans, while the caller's context still reaches the next /// hop. /// public sealed class GrpcTracePropagationTests : IAsyncLifetime { private const string Service = "trace.v1.Trace"; private ServiceProvider _sp = null!; private RouteContext _ctx = null!; private RouteContext _offCtx = null!; private int _port; private int _offPort; public async Task InitializeAsync() { _port = global::redb.Route.Tests.Shared.TestPorts.Next(); _offPort = global::redb.Route.Tests.Shared.TestPorts.Next(); var services = new ServiceCollection(); services.AddRedbRouteGrpc(); _sp = services.BuildServiceProvider(); var servers = _sp.GetRequiredService(); var port = _port; _ctx = new RouteContext(_sp, $"grpc-trace-{port}"); _ctx.AddComponent(new GrpcComponent { ServerManager = servers }); _ctx.AddRoutes(r => { r.From(GrpcDsl.Listen($"127.0.0.1:{port}").Method($"/{Service}/Traced")).RouteId($"grpc-trace-{port}-traced") .Process(e => e.Out = new Message("ok")); r.From(GrpcDsl.Listen($"127.0.0.1:{port}").Method($"/{Service}/Fails")).RouteId($"grpc-trace-{port}-fails") .Process(_ => throw new InvalidOperationException("route failed")); r.From(GrpcDsl.Listen($"127.0.0.1:{port}").Method($"/{Service}/Baggage")).RouteId($"grpc-trace-{port}-baggage") .Process(e => e.Out = new Message(Activity.Current?.GetBaggageItem("tenant") ?? "")); r.From(GrpcDsl.Listen($"127.0.0.1:{port}").Method($"/{Service}/Proxy")).RouteId($"grpc-trace-{port}-proxy") .To(GrpcDsl.Call($"127.0.0.1:{port}").Method($"/{Service}/Echo")); r.From(GrpcDsl.Listen($"127.0.0.1:{port}").Method($"/{Service}/Cancelled")).RouteId($"grpc-trace-{port}-cancelled") .Process(_ => throw new TaskCanceledException("a call inside the route timed out")); r.From(GrpcDsl.Listen($"127.0.0.1:{port}").Method($"/{Service}/Slow")).RouteId($"grpc-trace-{port}-slow") .Process(async (_, ct) => await Task.Delay(5000, ct)); r.From(GrpcDsl.Listen($"127.0.0.1:{port}").Method($"/{Service}/Echo")).RouteId($"grpc-trace-{port}-echo") .Process(e => e.Out = new Message(e.In.Headers.TryGetValue("traceparent", out var tp) ? tp?.ToString() : "")); }); await _ctx.Start(); var offPort = _offPort; _offCtx = new RouteContext(_sp, $"grpc-trace-off-{offPort}", options: new RouteEngineOptions { EnableTelemetry = false }); _offCtx.AddComponent(new GrpcComponent { ServerManager = servers }); _offCtx.AddRoutes(r => { r.From(GrpcDsl.Listen($"127.0.0.1:{offPort}").Method($"/{Service}/Proxy")) .To(GrpcDsl.Call($"127.0.0.1:{offPort}").Method($"/{Service}/Echo")); r.From(GrpcDsl.Listen($"127.0.0.1:{offPort}").Method($"/{Service}/Echo")) .Process(e => e.Out = new Message(e.In.Headers.TryGetValue("traceparent", out var tp) ? tp?.ToString() : "")); }); await _offCtx.Start(); } public async Task DisposeAsync() { await _ctx.DisposeAsync(); await _offCtx.DisposeAsync(); await _sp.DisposeAsync(); } private static (ActivityTraceId TraceId, ActivitySpanId SpanId, string Header) Caller() { var traceId = ActivityTraceId.CreateRandom(); var spanId = ActivitySpanId.CreateRandom(); return (traceId, spanId, $"00-{traceId}-{spanId}-01"); } /// Calls with as metadata, outside any activity. private static async Task Call(int port, string method, params (string Name, string Value)[] headers) { var ambient = Activity.Current; Activity.Current = null; // the metadata alone carries the caller's context try { using var channel = GrpcChannel.ForAddress($"http://127.0.0.1:{port}"); var marshaller = Marshallers.Create(b => b, b => b); var call = new Method(MethodType.Unary, Service, method, marshaller, marshaller); var metadata = new Metadata(); foreach (var (name, value) in headers) metadata.Add(name, value); var reply = await channel.CreateCallInvoker() .AsyncUnaryCall(call, null, new CallOptions(metadata), Array.Empty()); return Encoding.UTF8.GetString(reply); } finally { Activity.Current = ambient; } } private static Activity ServerSpan(RouteTelemetryProbe probe, string method) => probe.Activities.Single(a => a.Kind == ActivityKind.Server && RouteTelemetryProbe.Tag(a, RouteTelemetryProbe.EndpointTag)!.Contains(method, StringComparison.Ordinal)); [Fact] public async Task A_call_opens_a_server_span_that_continues_the_callers_trace() { using var probe = RouteTelemetryProbe.ForEndpointContaining($"{_port}/{Service}/Traced"); using var routes = RouteTelemetryProbe.ForRouteIdPrefix($"grpc-trace-{_port}-traced"); var caller = Caller(); (await Call(_port, "Traced", ("traceparent", caller.Header))).Should().Be("ok"); var server = ServerSpan(probe, "/Traced"); server.TraceId.Should().Be(caller.TraceId); server.ParentSpanId.Should().Be(caller.SpanId); server.GetTagItem("rpc.system").Should().Be("grpc"); routes.Activities.Should().ContainSingle().Which.ParentSpanId.Should().Be(server.SpanId, "the route runs inside the call"); } [Fact] public async Task A_call_without_context_opens_a_root_server_span() { using var probe = RouteTelemetryProbe.ForEndpointContaining($"{_port}/{Service}/Traced"); await Call(_port, "Traced"); ServerSpan(probe, "/Traced").ParentSpanId.Should().Be(default(ActivitySpanId)); } [Fact] public async Task The_callers_baggage_reaches_the_route() { using var probe = RouteTelemetryProbe.ForEndpointContaining($"{_port}/{Service}/Baggage"); var headers = new Dictionary(); using (var send = new Activity("caller").Start()) { send.AddBaggage("tenant", "t1"); RouteTelemetryExtensions.InjectTraceContext(send, headers, static (h, name, value) => h[name] = value); } (await Call(_port, "Baggage", headers.Select(h => (h.Key, h.Value)).ToArray())).Should().Be("t1"); } [Fact] public async Task A_failed_route_marks_the_server_span_red() { using var probe = RouteTelemetryProbe.ForEndpointContaining($"{_port}/{Service}/Fails"); var act = () => Call(_port, "Fails"); await act.Should().ThrowAsync(); ServerSpan(probe, "/Fails").Status.Should().Be(ActivityStatusCode.Error); } [Fact] public async Task A_timeout_inside_the_route_marks_the_server_span_red() { using var probe = RouteTelemetryProbe.ForEndpointContaining($"{_port}/{Service}/Cancelled"); var act = () => Call(_port, "Cancelled"); await act.Should().ThrowAsync(); ServerSpan(probe, "/Cancelled").Status.Should().Be(ActivityStatusCode.Error); } /// Calls the slow method with , and waits for its server span. private async Task SlowCallSpan(CallOptions options) { using var probe = RouteTelemetryProbe.ForEndpointContaining($"{_port}/{Service}/Slow"); using var channel = GrpcChannel.ForAddress($"http://127.0.0.1:{_port}"); var marshaller = Marshallers.Create(b => b, b => b); var method = new Method(MethodType.Unary, Service, "Slow", marshaller, marshaller); var act = () => channel.CreateCallInvoker().AsyncUnaryCall(method, null, options, Array.Empty()).ResponseAsync; await act.Should().ThrowAsync(); var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10); while (probe.Activities.Count == 0 && DateTime.UtcNow < deadline) await Task.Delay(100); return probe.Activities.Should().ContainSingle().Subject; } [Fact] public async Task The_caller_going_away_is_a_stop_not_a_failure() { using var cancel = new CancellationTokenSource(TimeSpan.FromMilliseconds(300)); var server = await SlowCallSpan(new CallOptions(cancellationToken: cancel.Token)); server.Status.Should().NotBe(ActivityStatusCode.Error, "the caller cancelled the call it made"); } [Fact] public async Task A_proxy_sends_the_context_of_its_own_span_not_the_copied_caller_header() { using var probe = RouteTelemetryProbe.ForEndpointContaining($"{_port}/{Service}/Echo"); var caller = Caller(); var received = await Call(_port, "Proxy", ("traceparent", caller.Header)); var send = probe.Activities.Single(a => a.Kind == ActivityKind.Client); received.Should().Be($"00-{caller.TraceId}-{send.SpanId}-{(int)send.ActivityTraceFlags:x2}", "the next hop is a child of the send, in the caller's trace"); } [Fact] public async Task Tracing_off_opens_no_span_and_still_passes_the_callers_context_on() { using var probe = RouteTelemetryProbe.ForEndpointContaining($":{_offPort}/"); var caller = Caller(); (await Call(_offPort, "Proxy", ("traceparent", caller.Header))).Should().Contain(caller.TraceId.ToString()); probe.Activities.Should().BeEmpty(); } } Path: redb-route/tests/redb.Route.Tests.Grpc/GrpcWireTests.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/tests/redb.Route.Tests.Grpc/GrpcWireTests.cs ---- using System.Buffers.Binary; using System.IO.Compression; using redb.Route.Grpc; namespace redb.Route.Tests.Grpc; /// Unit-level checks of the wire codec itself, isolated from Kestrel and the client. public class GrpcWireTests { [Fact] public async Task Gzipped_frame_round_trips() { var message = System.Text.Encoding.UTF8.GetBytes(new string('a', 1000)); using var compressedBody = new MemoryStream(); using (var gzip = new GZipStream(compressedBody, CompressionLevel.Fastest, leaveOpen: true)) gzip.Write(message, 0, message.Length); var payload = compressedBody.ToArray(); var frame = new byte[5 + payload.Length]; frame[0] = 1; BinaryPrimitives.WriteUInt32BigEndian(frame.AsSpan(1, 4), (uint)payload.Length); payload.CopyTo(frame, 5); var read = await GrpcWire.ReadMessageAsync(new MemoryStream(frame), 4 * 1024 * 1024, "gzip", default); read.Should().Equal(message); } [Fact] public async Task Compressed_frame_without_a_supported_encoding_is_unimplemented() { var frame = new byte[5]; frame[0] = 1; var act = async () => await GrpcWire.ReadMessageAsync(new MemoryStream(frame), 0, null, default); (await act.Should().ThrowAsync()) .Which.Status.Should().Be(global::Grpc.Core.StatusCode.Unimplemented); } [Fact] public void A_body_that_is_not_a_payload_is_refused_not_stringified() { // Running an arbitrary object through ToString() would put text like // "System.Collections.Generic.Dictionary`2[…]" on the wire with an OK status — the same // silent-garbage failure the SOAP consumer had with byte[]. Fail loudly and name the type. var act = () => GrpcWire.ToBytes(new Dictionary { ["error"] = "server_error" }); (act.Should().Throw()) .Which.Message.Should().Contain("Dictionary"); } [Fact] public void Bytes_and_strings_are_payloads() { GrpcWire.ToBytes("abc").Should().Equal(System.Text.Encoding.UTF8.GetBytes("abc")); GrpcWire.ToBytes(new byte[] { 1, 2 }).Should().Equal((byte)1, (byte)2); GrpcWire.ToBytes(null).Should().BeEmpty(); } // ── deadlines ──────────────────────────────────────────── [Theory] [InlineData("100u")] // ordinary microsecond deadline [InlineData("5S")] [InlineData("250m")] public void A_well_formed_timeout_is_parsed(string header) { GrpcWire.ParseTimeout(header).Should().NotBeNull(); } [Theory] [InlineData("9223372036854775807u")] // long.MaxValue: *10 wraps to a tiny negative [InlineData("1000000000000000000u")] // wraps to a huge negative [InlineData("922337203685477581u")] public void A_timeout_that_overflows_is_ignored_not_turned_into_a_negative_deadline(string header) { // ParseTimeout promises that an unreadable deadline never fails the call — it just means we do // not enforce one. The microsecond arm multiplied a caller-supplied long by 10 unchecked, so a // crafted header produced a NEGATIVE TimeSpan. The consumer then either cancelled the call // immediately or, for the larger values, threw ArgumentOutOfRangeException out of CancelAfter // before the try-block that exists to contain exactly this. Either way the promise was broken by // untrusted input. var parsed = GrpcWire.ParseTimeout(header); parsed.Should().BeNull("an overflowing deadline is unreadable, and unreadable means unenforced"); } [Fact] public void A_parsed_timeout_is_never_negative() { // The property that matters downstream: CancelAfter rejects anything below -1ms, and a negative // deadline that does not throw silently cancels the call at once. Neither is "no deadline". foreach (var unit in new[] { "H", "M", "S", "m", "u", "n" }) { foreach (var amount in new[] { "1", "1000", "9223372036854775807", "1000000000000000000" }) { var parsed = GrpcWire.ParseTimeout(amount + unit); if (parsed is not null) parsed.Value.Should().BeGreaterThanOrEqualTo(TimeSpan.Zero, "header was '{0}'", amount + unit); } } } } Path: redb-route/tests/redb.Route.Tests.Grpc/redb.Route.Tests.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/tests/redb.Route.Tests.Grpc/redb.Route.Tests.Grpc.csproj ----