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