Path: redb-route/tests/Shared/Conformance/ConnectorConformance.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.cs
----
using System.Collections.Concurrent;
using System.Text;
using redb.Route.Abstractions;
using redb.Route.Configuration;
using redb.Route.Core;
using redb.Route.Processors;
using redb.Route.Transactions;
namespace redb.Route.Tests.Conformance;
///
/// What a queue connector must do, as tests a connector's suite inherits: the class gives the endpoints and the stand,
/// the tests check the connector against the broker read and written through the broker's own client
/// (). This part holds the lifecycle and the acknowledgement: a start while the broker is
/// down, a broker restart, a stop with a message in work, a retry, a poison message, receipt acknowledgement and a
/// rolled back send. A case the connector does not have () passes without running; the
/// trait list of the suite says which ones those are.
///
/// The restart case breaks the broker's container: it runs only in a fault run (),
/// so a suite that inherits this class puts it in a collection that runs alone.
///
///
/// The connector's stand.
public abstract partial class ConnectorConformance where TStand : IConnectorStand
{
/// How long a test waits for the broker or the route.
protected TimeSpan Wait => Stand.Wait;
/// The broker the suite runs against.
protected abstract TStand Stand { get; }
/// What the connector has; the cases it lacks pass without running.
protected abstract ConnectorTraits Traits { get; }
/// The port the broker takes connections on, for the case of a start while the broker is down.
protected abstract int BrokerPort { get; }
/// A new component of the connector, added to each test's context.
protected abstract IComponent CreateComponent();
///
/// Makes an empty queue for one test, with a dead letter queue when is set; the queue
/// takes messages put by before a consumer starts.
///
protected abstract Task CreateQueueAsync(bool deadLetter);
///
/// The queue of a test that asks for attempts per message. Where the broker counts the
/// attempts on the queue itself (the delivery count of a Service Bus entity), the queue is chosen by them; by default
/// the connector counts them and this is .
///
protected virtual Task CreateQueueAsync(bool deadLetter, int attempts) => CreateQueueAsync(deadLetter);
/// Removes what made, or empties it where the queues are fixed.
protected abstract Task DeleteQueueAsync(ConformanceQueue queue);
/// The consumer endpoint on with .
protected abstract string ConsumerUri(ConformanceQueue queue, ConsumerSettings settings);
///
/// The producer endpoint that sends to ; joins a transacted block.
///
protected abstract string ProducerUri(ConformanceQueue queue, bool transacted);
///
/// Whether takes messages again after a broker restart; a broker that keeps nothing over a
/// restart has it only once the consumer declared it anew. Default: true.
///
protected virtual Task QueueIsBackAsync(ConformanceQueue queue) => Task.FromResult(true);
/// The text of a received message: UTF-8 bytes or a string.
protected virtual string Text(IMessage message) => message.Body switch
{
byte[] bytes => Encoding.UTF8.GetString(bytes),
null => "",
var body => body.ToString() ?? "",
};
[Fact]
public async Task A_consumer_started_while_the_broker_is_down_receives_once_it_is_up()
{
if (!Traits.LateBroker)
return;
var queue = await CreateQueueAsync(deadLetter: false);
try
{
await using var broker = new LateBroker("localhost", BrokerPort);
var received = new ConcurrentQueue();
await using var context = NewContext(new RouteEngineOptions
{
ShutdownTimeout = TimeSpan.FromSeconds(5),
ConsumerStartRetry = new ConsumerStartRetryOptions
{
Delay = TimeSpan.FromMilliseconds(200), Multiplier = 1.0, MaxDelay = TimeSpan.FromMilliseconds(200),
},
});
context.AddRoutes(r => r.From(ConsumerUri(queue, new ConsumerSettings { Port = broker.Port })).RouteId("late")
.Process(e => received.Enqueue(Text(e.In))));
await context.Start();
context.GetRoute("late")!.Status.Should().Be(RouteStatus.Errored, "nothing takes connections on the port yet");
broker.Open();
(await Until(() => context.GetRoute("late")!.Status == RouteStatus.Started)).Should()
.BeTrue("the consumer start retry starts the consumer once the broker is up");
await Stand.PutAsync(queue.Name, "after the broker came up");
(await Until(() => received.Contains("after the broker came up"))).Should().BeTrue();
}
finally
{
await DeleteQueueAsync(queue);
}
}
[BrokerFaultFact]
public async Task A_consumer_reads_the_queue_again_after_the_broker_restarts()
{
var fault = Stand.Fault ?? throw new InvalidOperationException(
"A fault run without the broker's container: the stand's container variable is not set.");
var queue = await CreateQueueAsync(deadLetter: false);
try
{
var received = new ConcurrentQueue();
await using var context = NewContext();
var uri = ConsumerUri(queue, new ConsumerSettings());
context.AddRoutes(r => r.From(uri).RouteId("restarted").Process(e => received.Enqueue(Text(e.In))));
await context.Start();
await Stand.PutAsync(queue.Name, "before");
(await Until(() => received.Contains("before"))).Should().BeTrue("the route reads the queue before the restart");
await fault.RestartAsync();
var statistics = (IEndpointStatistics)context.GetEndpoint(uri);
(await Until(() => statistics.Reconnects > 0)).Should().BeTrue("the connection supervisor counts the reconnect");
// The broker may take the first put after a restart only once its listener and the queue are back.
(await BrokerFault.UntilAsync(() => QueueIsBackAsync(queue), Wait, TimeSpan.FromMilliseconds(500))).Should()
.BeTrue("the queue is back with the subscription");
(await BrokerFault.UntilAsync(async () =>
{
try { await Stand.PutAsync(queue.Name, "after"); return true; }
catch (Exception) { return false; }
}, Wait, TimeSpan.FromMilliseconds(500))).Should().BeTrue("the broker takes a message once it is back");
(await Until(() => received.Contains("after"))).Should().BeTrue("the consumer reads what was put after the restart");
statistics.Reconnects.Should().Be(1, "one restart is one reconnect");
statistics.HealthStatus.Should().Be(EndpointHealthStatus.Healthy, "the connection is back");
context.GetRoute("restarted")!.Status.Should().Be(RouteStatus.Started, "a lost connection does not stop the route");
}
finally
{
await DeleteQueueAsync(queue);
}
}
[Fact]
public async Task A_stop_waits_for_the_message_in_work_and_nothing_goes_back_to_the_queue()
{
var queue = await CreateQueueAsync(deadLetter: false);
try
{
var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var finished = 0;
var context = NewContext();
context.AddRoutes(r => r.From(ConsumerUri(queue, new ConsumerSettings())).Process(async (_, ct) =>
{
started.TrySetResult();
await Task.Delay(500, ct);
Interlocked.Increment(ref finished);
}));
await context.Start();
await Stand.PutAsync(queue.Name, "in work");
await started.Task.WaitAsync(Wait);
await context.Stop();
await context.DisposeAsync();
Volatile.Read(ref finished).Should().Be(1, "the stop waits for the message in work");
(await Stand.DrainAsync(queue.Name, TimeSpan.FromSeconds(1))).Should().BeEmpty(
"the message finished before the stop is acknowledged");
}
finally
{
await DeleteQueueAsync(queue);
}
}
[Fact]
public async Task A_failed_message_is_tried_again_and_acknowledged_once_it_succeeds()
{
var queue = await CreateQueueAsync(deadLetter: Traits.DeadLetter, attempts: 3);
try
{
var attempts = 0;
var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using (var context = NewContext())
{
context.AddRoutes(r => r.From(ConsumerUri(queue, new ConsumerSettings { Attempts = 3 })).Process(_ =>
{
if (Interlocked.Increment(ref attempts) < 3)
throw new InvalidOperationException("this attempt fails");
done.TrySetResult();
}));
await context.Start();
await Stand.PutAsync(queue.Name, "flaky");
await done.Task.WaitAsync(Wait);
await Task.Delay(500);
}
Volatile.Read(ref attempts).Should().Be(3, "two failed attempts, then the one that succeeds");
(await Stand.DrainAsync(queue.Name, TimeSpan.FromSeconds(1))).Should().BeEmpty("the success is acknowledged");
if (queue.DeadLetter is { } deadLetter)
(await Stand.DrainAsync(deadLetter, TimeSpan.FromSeconds(1))).Should().BeEmpty("it never failed for good");
}
finally
{
await DeleteQueueAsync(queue);
}
}
[Fact]
public async Task A_poison_message_lands_in_the_dead_letter_queue_after_its_attempts()
{
if (!Traits.DeadLetter)
return;
var queue = await CreateQueueAsync(deadLetter: true, attempts: 3);
try
{
var attempts = 0;
IReadOnlyList deadLettered;
await using (var context = NewContext())
{
context.AddRoutes(r => r.From(ConsumerUri(queue, new ConsumerSettings { Attempts = 3 })).Process(_ =>
{
Interlocked.Increment(ref attempts);
throw new InvalidOperationException("always fails");
}));
await context.Start();
await Stand.PutAsync(queue.Name, "poison");
deadLettered = await Stand.DrainAsync(queue.DeadLetter!, Wait);
await Task.Delay(500);
}
deadLettered.Should().Equal("poison");
Volatile.Read(ref attempts).Should().Be(3, "three attempts and no more: a poison message must not loop");
(await Stand.DrainAsync(queue.Name, TimeSpan.FromSeconds(1))).Should().BeEmpty();
}
finally
{
await DeleteQueueAsync(queue);
}
}
[Fact]
public async Task With_acknowledgement_on_receipt_a_failed_message_is_not_tried_again()
{
if (!Traits.AckOnReceipt)
return;
var queue = await CreateQueueAsync(deadLetter: false);
try
{
var attempts = 0;
await using (var context = NewContext())
{
// One attempt in the consumer: what is checked is that the broker does not deliver the message again.
var settings = new ConsumerSettings { AckOnReceipt = true, Attempts = 1 };
context.AddRoutes(r => r.From(ConsumerUri(queue, settings)).Process(_ =>
{
Interlocked.Increment(ref attempts);
throw new InvalidOperationException("fails");
}));
await context.Start();
await Stand.PutAsync(queue.Name, "at most once");
(await Until(() => Volatile.Read(ref attempts) > 0)).Should().BeTrue();
await Task.Delay(2000);
}
Volatile.Read(ref attempts).Should().Be(1,
"the broker settled the message when it handed it over and does not deliver it again");
(await Stand.DrainAsync(queue.Name, TimeSpan.FromSeconds(1))).Should().BeEmpty();
}
finally
{
await DeleteQueueAsync(queue);
}
}
[Fact]
public async Task A_send_in_a_rolled_back_block_sends_nothing_and_one_in_a_committed_block_arrives()
{
if (!Traits.Transactions)
return;
var queue = await CreateQueueAsync(deadLetter: false);
try
{
await using var context = NewContext();
await context.Start();
var producer = context.GetEndpoint(ProducerUri(queue, transacted: true)).CreateProducer();
await producer.Start();
try
{
var failed = () => InTransaction(new Exchange(new Message("rolled back")), async (e, ct) =>
{
await producer.Process(e, ct);
throw new InvalidOperationException("the unit of work failed");
});
await failed.Should().ThrowAsync();
await InTransaction(new Exchange(new Message("committed")), (e, ct) => producer.Process(e, ct));
}
finally
{
await producer.Stop();
}
(await Stand.DrainAsync(queue.Name, Wait)).Should().Equal(["committed"],
"the rolled back send never reaches the queue, the committed one does");
}
finally
{
await DeleteQueueAsync(queue);
}
}
/// A context with the connector's component.
protected RouteContext NewContext(RouteEngineOptions? options = null)
{
var context = options is null ? new RouteContext() : new RouteContext(options: options);
context.AddComponent(CreateComponent());
return context;
}
/// Runs as a .Transacted() block does: the sends commit or roll back with it.
protected static Task InTransaction(IExchange exchange, Func body)
=> new TransactedProcessor(new DelegateProcessor(body), new TransactionPolicy()).Process(exchange);
/// Waits up to for .
protected async Task Until(Func condition)
{
var deadline = DateTime.UtcNow + Wait;
while (!condition())
{
if (DateTime.UtcNow > deadline)
return false;
await Task.Delay(50);
}
return true;
}
}
/// What a connector has, for : a case it lacks passes without running.
public sealed record ConnectorTraits
{
/// The broker can settle a message on hand-off (at most once): RabbitMQ ackMode=auto.
public bool AckOnReceipt { get; init; }
/// A producer joins a transacted block: its sends commit or roll back with it.
public bool Transactions { get; init; }
/// A message that fails all its attempts goes to a dead letter queue.
public bool DeadLetter { get; init; }
/// The consumer runs more than one message at a time when asked ().
public bool Concurrency { get; init; }
/// The consumer hands the route a batch of messages ().
public bool Batch { get; init; }
///
/// A consumer started while nothing takes connections fails its start and comes up through the consumer start retry
/// once the broker is there (, a port opened late). false where that does not apply:
/// the client opens no connection at start, or it is sent past the late port to the address the broker announces.
///
public bool LateBroker { get; init; } = true;
}
/// A queue of one conformance test: its name and its dead letter queue, if it has one.
public sealed record ConformanceQueue(string Name, string? DeadLetter);
/// How a conformance test wants its consumer.
public sealed record ConsumerSettings
{
/// Attempts per message, the first included; null: the connector's default.
public int? Attempts { get; init; }
/// The broker settles the message on hand-off.
public bool AckOnReceipt { get; init; }
/// The port to connect to instead of the broker's (a ); null: the broker's.
public int? Port { get; init; }
/// How many messages run at once; null: the connector's default.
public int? Concurrency { get; init; }
///
/// Batch mode: up to this many messages per exchange, the body a list of ; null: one
/// message per exchange.
///
public int? BatchSize { get; init; }
/// In batch mode, how long the consumer waits for more messages before it runs a batch that is not full.
public TimeSpan BatchWait { get; init; } = TimeSpan.FromSeconds(2);
}