Path: redb-route/tests/Shared/Conformance/ConnectorConformance.Flow.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/Shared/Conformance/ConnectorConformance.Flow.cs
----
using System.Collections.Concurrent;
using System.Diagnostics;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Telemetry;
namespace redb.Route.Tests.Conformance;
///
/// The part of about what goes through: headers and the trace context across
/// the broker, the statistics of both sides, the concurrency bound under a slow route, and a batch accepted, rejected
/// and returned.
///
public abstract partial class ConnectorConformance
{
private const string HeaderName = "x-conformance-id";
[Fact]
public async Task A_header_set_by_the_sender_reaches_the_route_and_both_sides_count_the_message_and_its_bytes()
{
var queue = await CreateQueueAsync(deadLetter: false);
try
{
var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using var context = NewContext();
var consumerUri = ConsumerUri(queue, new ConsumerSettings());
context.AddRoutes(r => r.From(consumerUri).Process(e => received.TrySetResult(e.In)));
var producerUri = ProducerUri(queue, transacted: false);
AddSendRoute(context, producerUri);
await context.Start();
const string body = "a message with a header";
await SendAsync(context, body, new Dictionary { [HeaderName] = "42" });
var message = await received.Task.WaitAsync(Wait);
Text(message).Should().Be(body);
message.Headers.Should().ContainKey(HeaderName);
message.Headers[HeaderName]?.ToString().Should().Be("42", "a header set by the sender crosses the broker");
var sent = (IEndpointStatistics)context.GetEndpoint(producerUri);
var read = (IEndpointStatistics)context.GetEndpoint(consumerUri);
sent.MessagesOut.Should().BeGreaterThanOrEqualTo(1);
sent.BytesOut.Should().BeGreaterThanOrEqualTo(body.Length, "the producer counts the bytes it sent");
(await Until(() => read.MessagesIn >= 1)).Should().BeTrue("the consumer counts the message it read");
read.BytesIn.Should().BeGreaterThanOrEqualTo(body.Length, "the consumer counts the bytes it read");
}
finally
{
await DeleteQueueAsync(queue);
}
}
[Fact]
public async Task The_trace_context_of_the_sender_crosses_the_broker_to_the_route()
{
var queue = await CreateQueueAsync(deadLetter: false);
using var listener = new ActivityListener
{
ShouldListenTo = source => source.Name == RouteActivitySource.SourceName,
Sample = (ref ActivityCreationOptions _) => ActivitySamplingResult.AllDataAndRecorded,
};
ActivitySource.AddActivityListener(listener);
try
{
var routeActivity = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using var context = NewContext();
context.AddRoutes(r => r.From(ConsumerUri(queue, new ConsumerSettings()))
.Process(_ => routeActivity.TrySetResult(Activity.Current)));
AddSendRoute(context, ProducerUri(queue, transacted: false));
await context.Start();
ActivityTraceId senderTrace;
using (var sender = RouteActivitySource.Source.StartActivity("conformance sender"))
{
sender.Should().NotBeNull();
senderTrace = sender!.TraceId;
await SendAsync(context, "traced");
}
var activity = await routeActivity.Task.WaitAsync(Wait);
activity.Should().NotBeNull("the route runs inside the consumer's receive span");
var receive = activity;
while (receive is not null && receive.Kind != ActivityKind.Consumer)
receive = receive.Parent;
receive.Should().NotBeNull("the route's span has the consumer's receive span above it");
receive!.TraceId.Should().Be(senderTrace, "the receive span continues the sender's trace");
}
finally
{
await DeleteQueueAsync(queue);
}
}
[Fact]
public async Task No_more_messages_run_at_once_than_the_concurrency_bound_under_a_slow_route()
{
if (!Traits.Concurrency)
return;
var queue = await CreateQueueAsync(deadLetter: false);
try
{
const int messages = 6;
var running = 0;
var peak = 0;
var done = 0;
await using (var context = NewContext())
{
context.AddRoutes(r => r.From(ConsumerUri(queue, new ConsumerSettings { Concurrency = 2 })).Process(async (_, ct) =>
{
var now = Interlocked.Increment(ref running);
int seen;
while ((seen = Volatile.Read(ref peak)) < now && Interlocked.CompareExchange(ref peak, now, seen) != seen) { }
await Task.Delay(300, ct);
Interlocked.Decrement(ref running);
Interlocked.Increment(ref done);
}));
for (var i = 0; i < messages; i++)
await Stand.PutAsync(queue.Name, $"m{i}");
await context.Start();
(await Until(() => Volatile.Read(ref done) == messages)).Should().BeTrue("every message is run");
}
Volatile.Read(ref peak).Should().Be(2, "two at a time: more breaks the bound, fewer means the bound is not used");
}
finally
{
await DeleteQueueAsync(queue);
}
}
[Fact]
public async Task A_batch_is_handed_to_the_route_as_one_list_and_acknowledged_after_it()
{
if (!Traits.Batch)
return;
var queue = await CreateQueueAsync(deadLetter: false);
try
{
var batches = new ConcurrentQueue();
await using (var context = NewContext())
{
context.AddRoutes(r => r.From(ConsumerUri(queue, new ConsumerSettings { BatchSize = 3 }))
.Process(e => batches.Enqueue(Batch(e).Select(Text).ToArray())));
foreach (var body in new[] { "a", "b", "c" })
await Stand.PutAsync(queue.Name, body);
await context.Start();
(await Until(() => batches.Sum(b => b.Length) == 3)).Should().BeTrue("all three are run");
await Task.Delay(500);
}
batches.Should().ContainSingle().Which.Should().BeEquivalentTo(["a", "b", "c"], "three messages, one batch of three");
(await Stand.DrainAsync(queue.Name, TimeSpan.FromSeconds(1))).Should().BeEmpty("the batch is acknowledged after the route");
}
finally
{
await DeleteQueueAsync(queue);
}
}
[Fact]
public async Task A_batch_that_fails_its_attempts_sends_every_message_of_it_to_the_dead_letter_queue()
{
if (!Traits.Batch || !Traits.DeadLetter)
return;
var queue = await CreateQueueAsync(deadLetter: true, attempts: 2);
try
{
var attempts = 0;
var deadLettered = new List();
await using (var context = NewContext())
{
context.AddRoutes(r => r.From(ConsumerUri(queue, new ConsumerSettings { BatchSize = 2, Attempts = 2 }))
.Process(_ =>
{
Interlocked.Increment(ref attempts);
throw new InvalidOperationException("the batch fails");
}));
await Stand.PutAsync(queue.Name, "a");
await Stand.PutAsync(queue.Name, "b");
await context.Start();
var deadline = DateTime.UtcNow + Wait;
while (deadLettered.Count < 2 && DateTime.UtcNow < deadline)
deadLettered.AddRange(await Stand.DrainAsync(queue.DeadLetter!, TimeSpan.FromSeconds(1)));
}
deadLettered.Should().BeEquivalentTo(["a", "b"], "every message of the rejected batch");
Volatile.Read(ref attempts).Should().Be(2, "the batch runs its attempts and no more");
(await Stand.DrainAsync(queue.Name, TimeSpan.FromSeconds(1))).Should().BeEmpty();
}
finally
{
await DeleteQueueAsync(queue);
}
}
[Fact]
public async Task A_batch_half_collected_when_the_consumer_stops_is_not_run_and_its_messages_go_back()
{
if (!Traits.Batch)
return;
var queue = await CreateQueueAsync(deadLetter: false);
try
{
var runs = 0;
var context = NewContext();
var settings = new ConsumerSettings { BatchSize = 10, BatchWait = TimeSpan.FromMinutes(1) };
context.AddRoutes(r => r.From(ConsumerUri(queue, settings)).Process(_ => Interlocked.Increment(ref runs)));
await Stand.PutAsync(queue.Name, "a");
await Stand.PutAsync(queue.Name, "b");
await context.Start();
await Task.Delay(TimeSpan.FromSeconds(3));
await context.Stop();
await context.DisposeAsync();
Volatile.Read(ref runs).Should().Be(0, "the batch was still being collected");
(await Stand.DrainAsync(queue.Name, Wait)).Should().BeEquivalentTo(["a", "b"], "both went back to the queue");
}
finally
{
await DeleteQueueAsync(queue);
}
}
/// The messages of a batch exchange.
protected static IReadOnlyList Batch(IExchange exchange) => exchange.In.Body switch
{
IReadOnlyList list => list,
IEnumerable items => items.ToList(),
var body => throw new InvalidOperationException($"A batch body is a list of messages, not {body?.GetType().Name ?? "null"}."),
};
private const string SendRoute = "direct://conformance-send";
///
/// A route from to , added before the context starts: a send
/// goes through a route's send step, which counts the message on the endpoint, as in a real route.
///
protected static void AddSendRoute(RouteContext context, string producerUri)
=> context.AddRoutes(r => r.From(SendRoute).To(producerUri));
/// Sends one message through the route of .
protected static async Task SendAsync(RouteContext context, string body, IReadOnlyDictionary? headers = null)
{
var producer = context.GetEndpoint(SendRoute).CreateProducer();
await producer.Start();
try
{
var message = new Message(body);
foreach (var (name, value) in headers ?? new Dictionary())
message.Headers[name] = value;
await producer.Process(new Exchange(message));
}
finally
{
await producer.Stop();
}
}
}