Path: redb-route/tests/redb.Route.Tests.RabbitMQ/RabbitMQBatchConsumerTests.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/RabbitMQBatchConsumerTests.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; /// /// The batch contract on the RabbitMQ consumer against the broker: collection by size and by idle timeout, the body /// shape, Split, settlement after the route, a delivery with a reply-to refused from a batch (batched with /// disableReplyTo), a stop during the pause between attempts, and concurrency bounded by concurrentConsumers; a failed /// batch dead-lettered and a stop with a half-collected batch are cases of RabbitMQConformanceTests. Queues are /// durable (RabbitMQ 4.3 refuses transient non-exclusive ones), with a real dead letter exchange and queue. /// [Trait("Category", "Integration")] public sealed class RabbitMQBatchConsumerTests { 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(); private sealed class Topology : IAsyncDisposable { public string Queue { get; } = $"batch-in-{Guid.NewGuid():N}"; public string DeadLetterExchange { get; } = $"batch-dlx-{Guid.NewGuid():N}"; public string DeadLetterQueue { get; } = $"batch-dlq-{Guid.NewGuid():N}"; private IConnection? _connection; public IChannel Channel { get; private set; } = null!; public static async Task CreateAsync() { var t = new Topology(); t._connection = await ConnectAsync(); t.Channel = await t._connection.CreateChannelAsync(); await t.Channel.ExchangeDeclareAsync(t.DeadLetterExchange, ExchangeType.Direct, durable: true, autoDelete: false); await t.Channel.QueueDeclareAsync(t.DeadLetterQueue, durable: true, exclusive: false, autoDelete: false); await t.Channel.QueueBindAsync(t.DeadLetterQueue, t.DeadLetterExchange, "failed"); await t.Channel.QueueDeclareAsync(t.Queue, durable: true, exclusive: false, autoDelete: false, arguments: new Dictionary { ["x-dead-letter-exchange"] = t.DeadLetterExchange, ["x-dead-letter-routing-key"] = "failed", }); return t; } public async Task PublishAsync(params string[] bodies) { foreach (var body in bodies) { var properties = new BasicProperties { Headers = new Dictionary { ["X-Record"] = "rec-" + body } }; await Channel.BasicPublishAsync(string.Empty, Queue, mandatory: false, properties, Encoding.UTF8.GetBytes(body)); } } public async Task PublishWithReplyToAsync(string body, string replyTo) => await Channel.BasicPublishAsync(string.Empty, Queue, mandatory: false, new BasicProperties { ReplyTo = replyTo }, Encoding.UTF8.GetBytes(body)); public async Task ReadyAsync(string queue) => await Channel.MessageCountAsync(queue); public async Task> DeadLettersAsync(int expected, TimeSpan within) { var got = new List(); var deadline = DateTime.UtcNow + within; while (got.Count < expected && DateTime.UtcNow < deadline) { var item = await Channel.BasicGetAsync(DeadLetterQueue, autoAck: true); if (item is null) { await Task.Delay(100); continue; } got.Add(Encoding.UTF8.GetString(item.Body.Span)); } return got; } public async ValueTask DisposeAsync() { await Channel.QueueDeleteAsync(Queue); await Channel.QueueDeleteAsync(DeadLetterQueue); await Channel.ExchangeDeleteAsync(DeadLetterExchange); await Channel.DisposeAsync(); await _connection!.DisposeAsync(); } } private static async Task Start(string queue, string options, Action? extra, Func route) { var context = new RouteContext(); context.AddComponent(new RabbitMQComponent()); context.AddRoutes(r => { r.From($"rabbitmq://{queue}?{Connection}&batching=true&{options}").Process(async (ex, _) => await route(ex)); extra?.Invoke(r); }); await context.Start(); return context; } private static List Records(IExchange exchange) => (List)exchange.In.Body!; private static string Text(IMessage message) => Encoding.UTF8.GetString((byte[])message.Body!); private static string? HeaderText(IDictionary headers, string name) => headers.TryGetValue(name, out var value) ? value is byte[] bytes ? Encoding.UTF8.GetString(bytes) : value?.ToString() : null; [Fact] public async Task A_batch_is_collected_up_to_maxBatchMessages_and_the_rest_by_the_idle_timeout() { await using var topology = await Topology.CreateAsync(); await topology.PublishAsync("a", "b", "c", "d", "e", "f", "g"); var batches = new ConcurrentQueue>(); var all = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await using (await Start(topology.Queue, "maxBatchMessages=3&pollTimeoutMs=1500", null, ex => { batches.Enqueue(Records(ex).Select(Text).ToList()); if (batches.Sum(b => b.Count) == 7) all.TrySetResult(); return Task.CompletedTask; })) { await all.Task.WaitAsync(TimeSpan.FromSeconds(30)); } batches.Select(b => b.Count).Should().Equal(3, 3, 1); batches.SelectMany(b => b).Should().Equal("a", "b", "c", "d", "e", "f", "g"); (await topology.ReadyAsync(topology.Queue)).Should().Be(0, "every delivery was acknowledged after its batch"); } [Fact] public async Task One_delivery_is_still_a_list_with_its_own_headers_and_the_routing_key_on_the_batch() { await using var topology = await Topology.CreateAsync(); await topology.PublishAsync("only"); var seen = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await using (await Start(topology.Queue, "pollTimeoutMs=500", null, ex => { seen.TrySetResult(ex); return Task.CompletedTask; })) { var batch = await seen.Task.WaitAsync(TimeSpan.FromSeconds(30)); batch.Pattern.Should().Be(ExchangePattern.InOnly); var record = Records(batch).Should().ContainSingle().Subject; Text(record).Should().Be("only"); record.Headers.Should().ContainKey(RmqHeaders.DeliveryTag); batch.In.Headers[RmqHeaders.RoutingKey].Should().Be(topology.Queue); } } [Fact] public async Task A_split_part_gets_its_deliverys_body_and_headers_and_the_split_metadata_as_properties() { await using var topology = await Topology.CreateAsync(); await topology.PublishAsync("a", "b"); var parts = new ConcurrentQueue<(string Body, string? Header, int Index)>(); var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var context = new RouteContext(); context.AddComponent(new RabbitMQComponent()); context.AddRoutes(r => r .From($"rabbitmq://{topology.Queue}?{Connection}&batching=true&maxBatchMessages=2&pollTimeoutMs=2000") .Split(ex => (IEnumerable)ex.In.Body!) .Process(ex => { parts.Enqueue((Encoding.UTF8.GetString((byte[])ex.In.Body!), HeaderText(ex.In.Headers, "X-Record"), ex.GetProperty(ExchangePropertyKeys.SplitIndex))); if (parts.Count == 2) done.TrySetResult(); }) .EndSplit()); await using (context) { await context.Start(); await done.Task.WaitAsync(TimeSpan.FromSeconds(30)); } parts.Select(p => (p.Body, p.Header, p.Index)).Should().Equal(("a", "rec-a", 0), ("b", "rec-b", 1)); } [Fact] public async Task A_delivery_with_a_reply_to_is_rejected_from_the_batch_and_the_others_run() { await using var topology = await Topology.CreateAsync(); await topology.PublishAsync("a"); await topology.PublishWithReplyToAsync("request", "somebodys-replies"); await topology.PublishAsync("b"); var batched = new ConcurrentQueue(); var both = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await using (await Start(topology.Queue, "pollTimeoutMs=1000", null, ex => { foreach (var record in Records(ex)) batched.Enqueue(Text(record)); if (batched.Count >= 2) both.TrySetResult(); return Task.CompletedTask; })) { await both.Task.WaitAsync(TimeSpan.FromSeconds(30)); (await topology.DeadLettersAsync(1, TimeSpan.FromSeconds(15))).Should().Equal("request"); } batched.Should().BeEquivalentTo(["a", "b"]); } [Fact] public async Task With_disableReplyTo_a_delivery_with_a_reply_to_is_batched_and_nobody_replies() { await using var topology = await Topology.CreateAsync(); await topology.PublishWithReplyToAsync("request", "somebodys-replies"); var batched = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await using (await Start(topology.Queue, "pollTimeoutMs=500&disableReplyTo=true", null, ex => { batched.TrySetResult(Text(Records(ex)[0])); return Task.CompletedTask; })) { (await batched.Task.WaitAsync(TimeSpan.FromSeconds(30))).Should().Be("request"); } (await topology.DeadLettersAsync(1, TimeSpan.FromSeconds(1))).Should().BeEmpty(); } [Fact] public async Task A_stop_during_the_pause_between_attempts_gives_every_delivery_back() { await using var topology = await Topology.CreateAsync(); await topology.PublishAsync("a", "b"); var attempts = 0; var firstFailed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var context = await Start(topology.Queue, "maxBatchMessages=2&pollTimeoutMs=1000&retryDelay=30000", null, _ => { Interlocked.Increment(ref attempts); firstFailed.TrySetResult(); throw new InvalidOperationException("fails"); }); await firstFailed.Task.WaitAsync(TimeSpan.FromSeconds(30)); await context.Stop(); await context.DisposeAsync(); attempts.Should().Be(1, "the stop ended the pause before the second attempt"); (await topology.DeadLettersAsync(1, TimeSpan.FromSeconds(1))).Should().BeEmpty(); (await topology.ReadyAsync(topology.Queue)).Should().Be(2, "both deliveries went back to the queue"); } [Fact] public async Task ConcurrentConsumers_bounds_how_many_batches_run_at_once() { await using var topology = await Topology.CreateAsync(); await topology.PublishAsync(Enumerable.Range(0, 20).Select(i => $"m{i}").ToArray()); var running = 0; var maxRunning = 0; var processed = 0; var all = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await using (await Start(topology.Queue, "maxBatchMessages=4&pollTimeoutMs=500&concurrentConsumers=2&prefetchCount=20", null, async ex => { var now = Interlocked.Increment(ref running); int seen; while ((seen = Volatile.Read(ref maxRunning)) < now && Interlocked.CompareExchange(ref maxRunning, now, seen) != seen) { } await Task.Delay(300); Interlocked.Decrement(ref running); if (Interlocked.Add(ref processed, Records(ex).Count) == 20) all.TrySetResult(); })) { await all.Task.WaitAsync(TimeSpan.FromSeconds(60)); } maxRunning.Should().BeInRange(1, 2, "two workers run at most two batches at once"); (await topology.ReadyAsync(topology.Queue)).Should().Be(0); } }