Path: redb-route/tests/redb.Route.Tests.RabbitMQ/RabbitMQFailedMessageTests.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.RabbitMQ/RabbitMQFailedMessageTests.cs
----
using System.Collections.Concurrent;
using System.Text;
using RabbitMQ.Client;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.RabbitMQ;
namespace redb.Route.Tests.RabbitMQ;
///
/// A failed delivery by Apache Camel's spring-rabbitmq rule, the parts only RabbitMQ has: requeued with
/// rejectAndDontRequeue=false, and a stop during the attempts gives the delivery back. The attempts and the dead
/// letter queue are cases of RabbitMQConformanceTests. Expects RabbitMQ at localhost:5672.
/// The queues are durable: RabbitMQ 4.3 refuses transient non-exclusive queues.
///
[Trait("Category", "Integration")]
public sealed class RabbitMQFailedMessageTests
{
private const string Connection = "host=localhost&port=5672&username=admin&password=admin";
private static async Task ConnectAsync()
=> await new ConnectionFactory { HostName = "localhost", Port = 5672, UserName = "admin", Password = "admin" }.CreateConnectionAsync();
/// A queue with a dead letter exchange and its dead letter queue; one message published to the queue.
private sealed class Topology : IAsyncDisposable
{
public string Queue { get; } = $"fail-in-{Guid.NewGuid():N}";
public string DeadLetterExchange { get; } = $"fail-dlx-{Guid.NewGuid():N}";
public string DeadLetterQueue { get; } = $"fail-dlq-{Guid.NewGuid():N}";
private IConnection? _connection;
private IChannel? _channel;
public async Task CreateAsync(string body)
{
_connection = await ConnectAsync();
_channel = await _connection.CreateChannelAsync();
await _channel.ExchangeDeclareAsync(DeadLetterExchange, ExchangeType.Direct, durable: true, autoDelete: false);
await _channel.QueueDeclareAsync(DeadLetterQueue, durable: true, exclusive: false, autoDelete: false);
await _channel.QueueBindAsync(DeadLetterQueue, DeadLetterExchange, "failed");
await _channel.QueueDeclareAsync(Queue, durable: true, exclusive: false, autoDelete: false,
arguments: new Dictionary
{
["x-dead-letter-exchange"] = DeadLetterExchange,
["x-dead-letter-routing-key"] = "failed",
});
await _channel.BasicPublishAsync(string.Empty, Queue, Encoding.UTF8.GetBytes(body));
}
public async Task ReadyAsync(string queue) => await _channel!.MessageCountAsync(queue);
public async Task TakeDeadLetterAsync(TimeSpan within)
{
var deadline = DateTime.UtcNow + within;
while (DateTime.UtcNow < deadline)
{
var got = await _channel!.BasicGetAsync(DeadLetterQueue, autoAck: true);
if (got is not null)
return Encoding.UTF8.GetString(got.Body.Span);
await Task.Delay(100);
}
return null;
}
public async ValueTask DisposeAsync()
{
if (_channel is not null)
{
await _channel.QueueDeleteAsync(Queue);
await _channel.QueueDeleteAsync(DeadLetterQueue);
await _channel.ExchangeDeleteAsync(DeadLetterExchange);
await _channel.DisposeAsync();
}
if (_connection is not null)
await _connection.DisposeAsync();
}
}
private static async Task Start(string queue, string options, Func route,
ConcurrentQueue redelivered)
{
var attempt = 0;
var context = new RouteContext();
context.AddComponent(new RabbitMQComponent());
context.AddRoutes(r => r
.From($"rabbitmq://{queue}?{Connection}&{options}")
.Process(async (ex, _) =>
{
redelivered.Enqueue(ex.In.GetHeader(RmqHeaders.Redelivered));
await route(ex, Interlocked.Increment(ref attempt));
}));
await context.Start();
return context;
}
[Fact]
public async Task With_rejectAndDontRequeue_false_the_failed_message_is_requeued_and_tried_again()
{
await using var topology = new Topology();
await topology.CreateAsync("requeued");
var attempts = new ConcurrentQueue();
var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
// Two attempts per delivery: the first delivery fails both and is requeued; the redelivery succeeds on its first.
await using (await Start(topology.Queue, "retryDelay=100&maximumRetryAttempts=2&rejectAndDontRequeue=false", (_, n) =>
{
if (n <= 2) throw new InvalidOperationException($"attempt {n} fails");
done.TrySetResult();
return Task.CompletedTask;
}, attempts))
{
await done.Task.WaitAsync(TimeSpan.FromSeconds(30));
await Task.Delay(500);
}
attempts.Should().Equal(false, false, true);
(await topology.TakeDeadLetterAsync(TimeSpan.FromSeconds(1))).Should().BeNull();
(await topology.ReadyAsync(topology.Queue)).Should().Be(0);
}
[Fact]
public async Task A_stop_during_the_attempts_gives_the_delivery_back_instead_of_dead_lettering_it()
{
await using var topology = new Topology();
await topology.CreateAsync("interrupted");
var attempts = new ConcurrentQueue();
var firstFailed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var context = await Start(topology.Queue, "retryDelay=30000", (_, _) =>
{
firstFailed.TrySetResult();
throw new InvalidOperationException("fails");
}, attempts);
await firstFailed.Task.WaitAsync(TimeSpan.FromSeconds(30));
await context.Stop();
await context.DisposeAsync();
attempts.Should().HaveCount(1);
(await topology.TakeDeadLetterAsync(TimeSpan.FromSeconds(1))).Should().BeNull();
(await topology.ReadyAsync(topology.Queue)).Should().Be(1, "the delivery went back to its queue");
}
}