Path: redb-route/tests/redb.Route.Tests.AzureServiceBus/AzureServiceBusBatchTests.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.AzureServiceBus/AzureServiceBusBatchTests.cs ---- using System.Collections.Concurrent; using System.Text; using redb.Route.Abstractions; using redb.Route.AzureServiceBus; using redb.Route.Core; namespace redb.Route.Tests.AzureServiceBus; /// /// Batch mode of the Service Bus consumer against the emulator (queue.1, localhost:5300), on the core batch contract: a /// batch closes by size or by the idle timeout, its body is a list of one message per Service Bus message, and it is /// settled once after the route: completed on success, abandoned (delivered again) or dead-lettered on failure; a stop /// abandons an unfinished batch. /// [Trait("Category", "Integration")] [Collection(AsbEmulatorQueue.Name)] public sealed class AzureServiceBusBatchTests { private const string ConnectionString = "Endpoint=sb://localhost:5300;SharedAccessKeyName=RootManageSharedAccessKey;" + "SharedAccessKey=SAS_KEY_VALUE;UseDevelopmentEmulator=true;"; private const string Queue = "queue.1"; private static AzureServiceBusEndpoint Endpoint(string query = "") => (AzureServiceBusEndpoint)new AzureServiceBusComponent().CreateEndpoint( EndpointUriParser.Parse($"asb://{Queue}?connectionString={ConnectionString}{(query.Length > 0 ? "&" + query : "")}")); private static string Tag() => Guid.NewGuid().ToString("N")[..8]; private static async Task SendAsync(params IMessage[] messages) { var endpoint = Endpoint(); var producer = endpoint.CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message(messages.ToList()))); await producer.Stop(); await endpoint.Stop(); } private static IMessage Element(string body) => new Message(body) { Headers = { ["element"] = body } }; private static async Task DrainAsync(string query = "") { var endpoint = Endpoint("ackMode=auto&maxConcurrentCalls=5" + (query.Length > 0 ? "&" + query : "")); var consumer = endpoint.CreateConsumer(Substitute.For()); await consumer.Start(); await Task.Delay(2000); await consumer.Stop(); await endpoint.Stop(); } /// Records each batch's messages that carry the tag; fails the calls fail picks. private sealed class Route(string tag, Func? fail = null) : IProcessor { public readonly ConcurrentQueue> Batches = new(); private int _calls; public Task Process(IExchange exchange, CancellationToken ct = default) { var batch = ((List)exchange.In.Body!).Where(m => Body(m).StartsWith(tag)).ToList(); if (batch.Count == 0) return Task.CompletedTask; Batches.Enqueue(batch); if (fail?.Invoke(Interlocked.Increment(ref _calls), exchange) == true) throw new InvalidOperationException("batch fails"); return Task.CompletedTask; } public static string Body(IMessage m) => m.Body is byte[] b ? Encoding.UTF8.GetString(b) : m.Body?.ToString() ?? ""; public int Delivered => Batches.Sum(b => b.Count); } private static async Task ConsumeAsync(Route route, string query, Func until, int settleMs = 1500) { var endpoint = Endpoint(query); var consumer = endpoint.CreateConsumer(route); await consumer.Start(); try { var deadline = DateTime.UtcNow.AddSeconds(20); while (!until(route) && DateTime.UtcNow < deadline) await Task.Delay(100); await Task.Delay(settleMs); } finally { await consumer.Stop(); await endpoint.Stop(); } return route; } [Fact] public async Task A_full_batch_is_one_exchange_with_a_message_per_service_bus_message() { await DrainAsync(); var tag = Tag(); await SendAsync(Enumerable.Range(0, 5).Select(i => Element($"{tag}-{i}")).ToArray()); var route = await ConsumeAsync(new Route(tag), "batching=true&maxBatchMessages=5&pollTimeoutMs=3000", r => r.Delivered >= 5); route.Batches.SelectMany(b => b).Select(Route.Body).Should().BeEquivalentTo(Enumerable.Range(0, 5).Select(i => $"{tag}-{i}")); route.Batches.SelectMany(b => b).Should().OnlyContain(m => (string)m.Headers["element"]! == Route.Body(m) && m.Headers.ContainsKey(AzureServiceBusHeaders.MessageId)); route.Batches.Should().HaveCountLessThanOrEqualTo(2, "five messages fill one batch, at most two receives apart"); } [Fact] public async Task One_message_is_a_list_of_one_after_the_idle_timeout() { await DrainAsync(); var tag = Tag(); await SendAsync(Element($"{tag}-only")); var route = await ConsumeAsync(new Route(tag), "batching=true&maxBatchMessages=10&pollTimeoutMs=500", r => r.Delivered >= 1); route.Batches.Should().ContainSingle().Which.Select(Route.Body).Should().Equal($"{tag}-only"); } [Fact] public async Task A_failed_batch_is_abandoned_and_delivered_again() { await DrainAsync(); var tag = Tag(); await SendAsync(Element($"{tag}-x"), Element($"{tag}-y")); var route = await ConsumeAsync(new Route(tag, (call, _) => call == 1), "batching=true&maxBatchMessages=2&pollTimeoutMs=2000", r => r.Delivered >= 4); var delivered = route.Batches.SelectMany(b => b).ToList(); delivered.Select(Route.Body).Should().BeEquivalentTo([$"{tag}-x", $"{tag}-y", $"{tag}-x", $"{tag}-y"], "the abandoned messages come again and are completed the second time"); delivered.Max(m => Convert.ToInt32(m.Headers[AzureServiceBusHeaders.DeliveryCount])).Should().BeGreaterThanOrEqualTo(2); } [Fact] public async Task With_autoDeadLetter_a_failed_batch_goes_to_the_dead_letter_subqueue() { await DrainAsync(); await DrainAsync("subQueue=deadletter"); var tag = Tag(); await SendAsync(Element($"{tag}-d1"), Element($"{tag}-d2")); var failed = await ConsumeAsync(new Route(tag, (_, _) => true), "batching=true&maxBatchMessages=2&pollTimeoutMs=2000&autoDeadLetter=true&deadLetterReason=batch-failed", r => r.Delivered >= 2); failed.Delivered.Should().Be(2, "a dead-lettered message does not come back"); var dead = await ConsumeAsync(new Route(tag), "subQueue=deadletter&batching=true&maxBatchMessages=10&pollTimeoutMs=2000", r => r.Delivered >= 2); dead.Batches.SelectMany(b => b).Select(Route.Body).Should().BeEquivalentTo($"{tag}-d1", $"{tag}-d2"); dead.Batches.SelectMany(b => b).Should().OnlyContain(m => (string)m.Headers[AzureServiceBusHeaders.DeadLetterReason]! == "batch-failed"); } [Fact] public async Task A_rolled_back_batch_is_abandoned_even_with_autoDeadLetter() { await DrainAsync(); var tag = Tag(); await SendAsync(Element($"{tag}-r")); var route = await ConsumeAsync(new Route(tag, (call, exchange) => { if (call == 1) exchange.MarkRollbackOnly(); return false; }), "batching=true&maxBatchMessages=1&pollTimeoutMs=1000&autoDeadLetter=true", r => r.Batches.Count >= 2); route.Batches.Should().HaveCount(2, "a rollback is delivered again, not dead-lettered"); } [Fact] public async Task A_stop_abandons_the_unfinished_batch() { await DrainAsync(); var tag = Tag(); await SendAsync(Element($"{tag}-p"), Element($"{tag}-q")); var first = new Route(tag); var endpoint = Endpoint("batching=true&maxBatchMessages=10&pollTimeoutMs=10000"); var consumer = endpoint.CreateConsumer(first); await consumer.Start(); await Task.Delay(3000); await consumer.Stop(); await endpoint.Stop(); first.Batches.Should().BeEmpty("an interrupted batch is not run"); var again = await ConsumeAsync(new Route(tag), "batching=true&maxBatchMessages=2&pollTimeoutMs=2000", r => r.Delivered >= 2); again.Batches.SelectMany(b => b).Select(Route.Body).Should().BeEquivalentTo($"{tag}-p", $"{tag}-q"); } [Fact] public async Task With_ackMode_auto_a_failed_batch_is_not_delivered_again() { await DrainAsync(); var tag = Tag(); await SendAsync(Element($"{tag}-g"), Element($"{tag}-h")); var route = await ConsumeAsync(new Route(tag, (_, _) => true), "batching=true&maxBatchMessages=2&pollTimeoutMs=2000&ackMode=auto", r => r.Delivered >= 2, settleMs: 3000); route.Delivered.Should().Be(2, "ReceiveAndDelete: the messages are gone on receipt"); } }