Path: redb-route/tests/redb.Route.Tests.Amqp/AmqpBatchIntegrationTests.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.Amqp/AmqpBatchIntegrationTests.cs ---- using System.Collections.Concurrent; using System.Text; using Amqp; using Amqp.Framing; using redb.Route.Abstractions; using redb.Route.Amqp; using redb.Route.Core; using AmqpMessage = global::Amqp.Message; namespace redb.Route.Tests.Amqp; /// /// Batch mode of the AMQP 1.0 consumer against ActiveMQ Artemis (localhost:5673, admin/admin), on the core batch /// contract: a batch closes by size or by the idle timeout, its body is a list of one message per delivery with that /// delivery's body and headers, it is settled once after the route (accepted on success, released for redelivery on /// failure), a stop gives an unfinished batch back, and a delivery with a reply-to is rejected unless disableReplyTo. /// [Trait("Category", "Integration")] public sealed class AmqpBatchIntegrationTests { private const string Broker = "host=localhost&port=5673&user=admin&password=admin"; private static AmqpEndpoint Endpoint(string address, string query) => (AmqpEndpoint)new AmqpComponent().CreateEndpoint(EndpointUriParser.Parse($"amqp://{address}?{Broker}&{query}")); private static async Task SendAsync(string address, params (string Body, string? ReplyTo)[] messages) { var connection = await Connection.Factory.CreateAsync(new Address("amqp://admin:admin@localhost:5673")); try { var session = new Session(connection); // An ANYCAST target (the queue capability), as the consumer reads it: without it Artemis creates the address // MULTICAST on the first send, and an ANYCAST receiver link is refused. var sender = new SenderLink(session, $"test-sender-{Guid.NewGuid():N}", new Target { Address = address, Capabilities = [new global::Amqp.Types.Symbol("queue")] }, null); foreach (var (body, replyTo) in messages) { var msg = new AmqpMessage(body) { Properties = new Properties { MessageId = Guid.NewGuid().ToString("N"), ReplyTo = replyTo }, ApplicationProperties = new ApplicationProperties { ["tag"] = "t-" + body }, }; await sender.SendAsync(msg).WaitAsync(TimeSpan.FromSeconds(15)); } await sender.CloseAsync(); await session.CloseAsync(); } finally { await connection.CloseAsync(); } } private static Task SendAsync(string address, params string[] bodies) => SendAsync(address, bodies.Select(b => (b, (string?)null)).ToArray()); /// Records each batch as the list of its bodies; fails the batches says to. private sealed class Route(Func? fail = null) : IProcessor { public readonly ConcurrentQueue> Batches = new(); private int _calls; public Task Process(IExchange exchange, CancellationToken ct = default) { var call = Interlocked.Increment(ref _calls); Batches.Enqueue(((List)exchange.In.Body!).ToList()); if (fail?.Invoke(call) == true) throw new InvalidOperationException($"batch {call} fails"); return Task.CompletedTask; } public IEnumerable Bodies(List batch) => batch.Select(m => m.Body is byte[] bytes ? Encoding.UTF8.GetString(bytes) : m.Body?.ToString() ?? ""); public int Delivered => Batches.Sum(b => b.Count); } private static async Task WaitUntil(Func condition, int timeoutMs = 15_000) { var deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs); while (!condition() && DateTime.UtcNow < deadline) await Task.Delay(50); return condition(); } [Fact] public async Task A_full_batch_is_one_exchange_with_a_message_per_delivery() { var address = $"batch.size.{Guid.NewGuid():N}"; await SendAsync(address, "a", "b", "c", "d", "e"); var route = new Route(); var endpoint = Endpoint(address, "batching=true&maxBatchMessages=5&pollTimeoutMs=5000"); var consumer = endpoint.CreateConsumer(route); await consumer.Start().WaitAsync(TimeSpan.FromSeconds(30)); try { (await WaitUntil(() => route.Batches.Count >= 1)).Should().BeTrue(); } finally { await consumer.Stop().WaitAsync(TimeSpan.FromSeconds(30)); await endpoint.Stop(); } var batch = route.Batches.Single(); route.Bodies(batch).Should().Equal("a", "b", "c", "d", "e"); batch.Select(m => m.Headers["tag"]).Should().Equal("t-a", "t-b", "t-c", "t-d", "t-e"); batch.Should().OnlyContain(m => m.Headers.ContainsKey(AmqpHeaders.MessageId)); } [Fact] public async Task A_batch_closes_by_the_idle_timeout_and_one_delivery_is_a_list_too() { var address = $"batch.idle.{Guid.NewGuid():N}"; var route = new Route(); var endpoint = Endpoint(address, "batching=true&maxBatchMessages=10&pollTimeoutMs=500"); var consumer = endpoint.CreateConsumer(route); await consumer.Start().WaitAsync(TimeSpan.FromSeconds(30)); try { await SendAsync(address, "only"); (await WaitUntil(() => route.Batches.Count >= 1)).Should().BeTrue(); await Task.Delay(1000); } finally { await consumer.Stop().WaitAsync(TimeSpan.FromSeconds(30)); await endpoint.Stop(); } route.Batches.Should().ContainSingle(); route.Bodies(route.Batches.Single()).Should().Equal("only"); } [Fact] public async Task A_failed_batch_is_released_and_delivered_again() { var address = $"batch.fail.{Guid.NewGuid():N}"; await SendAsync(address, "x", "y", "z"); var route = new Route(fail: call => call == 1); var endpoint = Endpoint(address, "batching=true&maxBatchMessages=3&pollTimeoutMs=2000"); var consumer = endpoint.CreateConsumer(route); await consumer.Start().WaitAsync(TimeSpan.FromSeconds(30)); try { (await WaitUntil(() => route.Batches.Count >= 2)).Should().BeTrue("the released deliveries come again"); await Task.Delay(1500); } finally { await consumer.Stop().WaitAsync(TimeSpan.FromSeconds(30)); await endpoint.Stop(); } var batches = route.Batches.ToList(); batches.Should().HaveCount(2, "the second batch is accepted and nothing comes a third time"); route.Bodies(batches[1]).Should().BeEquivalentTo("x", "y", "z"); } [Fact] public async Task A_stop_gives_the_unfinished_batch_back() { var address = $"batch.stop.{Guid.NewGuid():N}"; await SendAsync(address, "p", "q"); var first = new Route(); var endpoint = Endpoint(address, "batching=true&maxBatchMessages=10&pollTimeoutMs=8000"); var consumer = endpoint.CreateConsumer(first); await consumer.Start().WaitAsync(TimeSpan.FromSeconds(30)); await Task.Delay(1500); // both deliveries are in the collector; the idle timeout is far away await consumer.Stop().WaitAsync(TimeSpan.FromSeconds(30)); await endpoint.Stop(); first.Batches.Should().BeEmpty("an interrupted batch is not run"); var again = new Route(); var endpoint2 = Endpoint(address, "batching=true&maxBatchMessages=2&pollTimeoutMs=2000"); var consumer2 = endpoint2.CreateConsumer(again); await consumer2.Start().WaitAsync(TimeSpan.FromSeconds(30)); try { (await WaitUntil(() => again.Delivered >= 2)).Should().BeTrue("the released deliveries come again"); } finally { await consumer2.Stop().WaitAsync(TimeSpan.FromSeconds(30)); await endpoint2.Stop(); } again.Batches.SelectMany(again.Bodies).Should().BeEquivalentTo("p", "q"); } [Fact] public async Task A_delivery_with_a_reply_to_is_rejected_and_the_rest_goes_on() { var address = $"batch.reply.{Guid.NewGuid():N}"; var marker = Guid.NewGuid().ToString("N"); await SendAsync(address, ("one", null), ("request-" + marker, "some.reply.address"), ("two", null)); var route = new Route(); var endpoint = Endpoint(address, "batching=true&maxBatchMessages=2&pollTimeoutMs=1500"); var consumer = endpoint.CreateConsumer(route); await consumer.Start().WaitAsync(TimeSpan.FromSeconds(30)); try { (await WaitUntil(() => route.Delivered >= 2)).Should().BeTrue(); await Task.Delay(1500); } finally { await consumer.Stop().WaitAsync(TimeSpan.FromSeconds(30)); await endpoint.Stop(); } route.Batches.SelectMany(route.Bodies).Should().BeEquivalentTo("one", "two"); (await DeadLetteredAsync("request-" + marker)).Should().BeTrue("Artemis moves a rejected delivery to its dead letter address"); } [Fact] public async Task With_disableReplyTo_a_delivery_with_a_reply_to_is_batched_without_a_reply() { var address = $"batch.noreply.{Guid.NewGuid():N}"; await SendAsync(address, ("one", null), ("asks", "some.reply.address")); var route = new Route(); var endpoint = Endpoint(address, "batching=true&maxBatchMessages=2&pollTimeoutMs=3000&disableReplyTo=true"); var consumer = endpoint.CreateConsumer(route); await consumer.Start().WaitAsync(TimeSpan.FromSeconds(30)); try { (await WaitUntil(() => route.Delivered >= 2)).Should().BeTrue(); } finally { await consumer.Stop().WaitAsync(TimeSpan.FromSeconds(30)); await endpoint.Stop(); } route.Batches.SelectMany(route.Bodies).Should().BeEquivalentTo("one", "asks"); } [Fact] public async Task Concurrent_workers_each_batch_and_every_delivery_is_processed_once() { var address = $"batch.workers.{Guid.NewGuid():N}"; await SendAsync(address, Enumerable.Range(0, 40).Select(i => $"m{i}").ToArray()); var route = new Route(); var endpoint = Endpoint(address, "batching=true&maxBatchMessages=10&pollTimeoutMs=1000&concurrentConsumers=2&credit=10"); var consumer = endpoint.CreateConsumer(route); await consumer.Start().WaitAsync(TimeSpan.FromSeconds(30)); try { (await WaitUntil(() => route.Delivered >= 40)).Should().BeTrue(); await Task.Delay(1500); } finally { await consumer.Stop().WaitAsync(TimeSpan.FromSeconds(30)); await endpoint.Stop(); } route.Batches.SelectMany(route.Bodies).Should().BeEquivalentTo(Enumerable.Range(0, 40).Select(i => $"m{i}")); route.Batches.Should().OnlyContain(b => b.Count <= 10); } [Fact] public async Task With_ackMode_auto_a_failed_batch_is_not_delivered_again() { var address = $"batch.auto.{Guid.NewGuid():N}"; await SendAsync(address, "g", "h"); var route = new Route(fail: _ => true); var endpoint = Endpoint(address, "batching=true&maxBatchMessages=2&pollTimeoutMs=2000&ackMode=auto"); var consumer = endpoint.CreateConsumer(route); await consumer.Start().WaitAsync(TimeSpan.FromSeconds(30)); try { (await WaitUntil(() => route.Batches.Count >= 1)).Should().BeTrue(); await Task.Delay(2500); } finally { await consumer.Stop().WaitAsync(TimeSpan.FromSeconds(30)); await endpoint.Stop(); } route.Batches.Should().ContainSingle("ackMode=auto accepts on receipt, before the route"); } /// Whether the delivery with sits in Artemis's dead letter queue (DLQ). private static async Task DeadLetteredAsync(string body) { var connection = await Connection.Factory.CreateAsync(new Address("amqp://admin:admin@localhost:5673")); try { var session = new Session(connection); var receiver = new ReceiverLink(session, $"test-dlq-{Guid.NewGuid():N}", new Source { Address = "DLQ", Capabilities = [new global::Amqp.Types.Symbol("queue")] }, null); var deadline = DateTime.UtcNow.AddSeconds(10); while (DateTime.UtcNow < deadline) { var msg = await receiver.ReceiveAsync(TimeSpan.FromSeconds(1)); if (msg is null) continue; var text = msg.Body is byte[] bytes ? Encoding.UTF8.GetString(bytes) : msg.Body?.ToString(); if (text == body) { receiver.Accept(msg); return true; } receiver.Release(msg); } return false; } finally { await connection.CloseAsync(); } } // ── A wait under one millisecond (the collector's last wait before a deadline) ── /// Opens a receiver link on an empty queue . private static async Task<(Connection Connection, ReceiverLink Receiver)> OpenReceiver(string address) { var connection = await Connection.Factory.CreateAsync(new Address("amqp://admin:admin@localhost:5673")); var receiver = new ReceiverLink(new Session(connection), $"test-receiver-{Guid.NewGuid():N}", new Source { Address = address, Capabilities = [new global::Amqp.Types.Symbol("queue")] }, null); return (connection, receiver); } [Fact] public async Task AMQPNetLite_never_completes_a_receive_shorter_than_a_millisecond() { // The cause the consumer works around: ReceiveAsync counts whole milliseconds, and 0 ms with no delivery at hand // creates no waiter. Should the library ever complete it, WholeMilliseconds may go. var (connection, receiver) = await OpenReceiver($"batch.submillisecond.{Guid.NewGuid():N}"); try { var receive = receiver.ReceiveAsync(TimeSpan.FromTicks(5_000)); (await Task.WhenAny(receive, Task.Delay(2_000))).Should().NotBeSameAs(receive); } finally { await connection.CloseAsync(); } } [Fact] public async Task The_batch_receive_completes_after_a_wait_shorter_than_a_millisecond() { var address = $"batch.submillisecond.{Guid.NewGuid():N}"; var consumer = (AmqpConsumer)Endpoint(address, "batching=true").CreateConsumer(new Route()); var (connection, receiver) = await OpenReceiver(address); try { var receive = consumer.ReceiveIntoBatchAsync(receiver, [], 10, TimeSpan.FromTicks(5_000), CancellationToken.None) .AsTask(); (await receive.WaitAsync(TimeSpan.FromSeconds(5))).Should().Be(0, "no delivery came, and the wait ended"); } finally { await connection.CloseAsync(); } } [Theory] [InlineData(5_000L, 1)] // 0.5 ms [InlineData(0L, 1)] [InlineData(12_000L, 2)] // 1.2 ms [InlineData(50_000L, 5)] // 5 ms public void A_wait_is_rounded_up_to_whole_milliseconds_and_at_least_one(long ticks, int milliseconds) => AmqpConsumer.WholeMilliseconds(TimeSpan.FromTicks(ticks)).Should().Be(TimeSpan.FromMilliseconds(milliseconds)); }