Path: redb-route/tests/redb.Route.Tests.Sqs/SqsBatchConsumerTests.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.Sqs/SqsBatchConsumerTests.cs ---- using System.Collections.Concurrent; using System.Diagnostics; using System.Net.Http; using System.Text.Json; using Amazon.Runtime; using Amazon.SQS; using Amazon.SQS.Model; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Sqs; using Xunit.Abstractions; using Message = redb.Route.Core.Message; using SqsMessage = Amazon.SQS.Model.Message; namespace redb.Route.Tests.Sqs; /// /// SQS batch consumer (batching=true) and the list producer against LocalStack: collection by size and by /// timeout over receives of up to 10, the batch body, Split, deletion after the route, a failed batch brought back by /// the visibility timeout, the dead letter queue through the redrive policy, stops, and concurrency. /// Requires: docker compose -f redb.Route/docker-compose.tests.yml --profile sqs up -d --wait (http://localhost:4566). /// [Trait("Category", "Integration")] public sealed class SqsBatchConsumerTests(ITestOutputHelper output) { private const string ServiceUrl = "http://localhost:4566"; private const string Region = "us-east-1"; private const string Connection = $"serviceUrl={ServiceUrl}®ion={Region}&accessKey=test&secretKey=test"; private static string UniqueName(string prefix) => $"{prefix}-{Guid.NewGuid():N}"; private static IAmazonSQS RawSqs() => new AmazonSQSClient(new BasicAWSCredentials("test", "test"), new AmazonSQSConfig { ServiceURL = ServiceUrl, AuthenticationRegion = Region }); private static async Task CreateQueue(IAmazonSQS sqs, string name, Dictionary? attributes = null) => (await sqs.CreateQueueAsync(new CreateQueueRequest { QueueName = name, Attributes = attributes ?? [] })).QueueUrl; private static async Task SendAll(IAmazonSQS sqs, string queueUrl, IEnumerable bodies) { foreach (var chunk in bodies.Chunk(10)) await sqs.SendMessageBatchAsync(new SendMessageBatchRequest { QueueUrl = queueUrl, Entries = chunk.Select((b, i) => new SendMessageBatchRequestEntry($"e{i}", b) { MessageAttributes = new Dictionary { ["XRecord"] = new() { DataType = "String", StringValue = "rec-" + b }, }, }).ToList(), }); } /// Visible plus in-flight messages of the queue. private static async Task<(int Visible, int InFlight)> Count(IAmazonSQS sqs, string queueUrl) { var response = await sqs.GetQueueAttributesAsync(queueUrl, ["ApproximateNumberOfMessages", "ApproximateNumberOfMessagesNotVisible"]); return (response.ApproximateNumberOfMessages, response.ApproximateNumberOfMessagesNotVisible); } private static async Task Until(Func> condition, TimeSpan limit, string because) { var deadline = DateTime.UtcNow + limit; while (!await condition()) { if (DateTime.UtcNow > deadline) throw new TimeoutException($"Not reached within {limit}: {because}"); await Task.Delay(100); } } private static Task Until(Func condition, TimeSpan limit, string because) => Until(() => Task.FromResult(condition()), limit, because); /// What the route saw of one batch. private sealed record Seen(List Bodies, List Records, List MessageIds, string? SharedQueue, ExchangePattern Pattern); private static Seen Capture(IExchange exchange) { var messages = (List)exchange.In.Body!; return new Seen( messages.Select(m => (string)m.Body!).ToList(), messages.Select(m => m.Headers.TryGetValue(SqsHeaders.MessageAttributePrefix + "XRecord", out var v) ? v?.ToString() : null).ToList(), messages.Select(m => m.Headers.TryGetValue(SqsHeaders.MessageId, out var v) ? v?.ToString() : null).ToList(), exchange.In.Headers.TryGetValue(SqsHeaders.Queue, out var q) ? q?.ToString() : null, exchange.Pattern); } private static async Task StartRoute(string queue, string options, Func route) { var context = new RouteContext(); context.AddComponent(new SqsComponent()); context.AddRoutes(r => r .From($"sqs://{queue}?{Connection}&batching=true&{options}") .Process(async (ex, _) => await route(ex))); await context.Start(); return context; } // ── The stand ── [Fact] public async Task The_stand_reports_its_LocalStack_version() { using var http = new HttpClient(); var json = await http.GetStringAsync($"{ServiceUrl}/_localstack/health"); using var doc = JsonDocument.Parse(json); var version = doc.RootElement.TryGetProperty("version", out var v) ? v.GetString() : null; output.WriteLine($"LocalStack version: {version}; edition: " + (doc.RootElement.TryGetProperty("edition", out var e) ? e.GetString() : "?")); version.Should().NotBeNullOrEmpty(); } // ── Collection ── [Fact] public async Task A_batch_is_collected_by_size_over_receives_of_up_to_ten() { using var sqs = RawSqs(); var queue = UniqueName("bsize"); var url = await CreateQueue(sqs, queue); var bodies = Enumerable.Range(0, 25).Select(i => $"m{i:D2}").ToList(); await SendAll(sqs, url, bodies); var batches = new ConcurrentQueue(); await using (await StartRoute(queue, "maxBatchMessages=25&pollTimeoutMs=5000", ex => { batches.Enqueue(Capture(ex)); return Task.CompletedTask; })) { await Until(() => batches.Sum(b => b.Bodies.Count) >= 25, TimeSpan.FromSeconds(60), "25 messages routed"); } foreach (var b in batches) output.WriteLine($"batch of {b.Bodies.Count}"); batches.Should().HaveCount(1, "25 messages wait in the queue: one batch of 25, collected over several receives"); var batch = batches.Single(); batch.Bodies.Should().BeEquivalentTo(bodies); batch.Records.Should().BeEquivalentTo(bodies.Select(b => "rec-" + b), "each message keeps its own attributes"); batch.MessageIds.Should().OnlyHaveUniqueItems().And.NotContainNulls(); batch.SharedQueue.Should().Be(queue, "the queue is the same for every message, so the batch message carries it"); batch.Pattern.Should().Be(ExchangePattern.InOnly); } [Fact] public async Task A_batch_smaller_than_maxBatchMessages_goes_on_after_pollTimeoutMs() { using var sqs = RawSqs(); var queue = UniqueName("btime"); var url = await CreateQueue(sqs, queue); await SendAll(sqs, url, ["a", "b", "c"]); var batches = new ConcurrentQueue(); await using (await StartRoute(queue, "maxBatchMessages=50&pollTimeoutMs=1000", ex => { batches.Enqueue(Capture(ex)); return Task.CompletedTask; })) { await Until(() => batches.Sum(b => b.Bodies.Count) >= 3, TimeSpan.FromSeconds(30), "3 messages routed"); } batches.Should().ContainSingle().Which.Bodies.Should().BeEquivalentTo("a", "b", "c"); } [Fact] public async Task A_split_part_gets_its_messages_body_and_attributes() { using var sqs = RawSqs(); var queue = UniqueName("bsplit"); var url = await CreateQueue(sqs, queue); await SendAll(sqs, url, ["a", "b"]); var parts = new ConcurrentQueue<(string Body, string? Record)>(); var context = new RouteContext(); context.AddComponent(new SqsComponent()); context.AddRoutes(r => r .From($"sqs://{queue}?{Connection}&batching=true&maxBatchMessages=2&pollTimeoutMs=2000") .Split(ex => (IEnumerable)ex.In.Body!) .Process(ex => parts.Enqueue(((string)ex.In.Body!, ex.In.Headers.TryGetValue(SqsHeaders.MessageAttributePrefix + "XRecord", out var v) ? v?.ToString() : null))) .EndSplit()); await using (context) { await context.Start(); await Until(() => parts.Count >= 2, TimeSpan.FromSeconds(30), "2 parts"); } parts.Should().BeEquivalentTo([("a", (string?)"rec-a"), ("b", (string?)"rec-b")]); } // ── Settlement ── [Fact] public async Task A_routed_batch_is_deleted() { using var sqs = RawSqs(); var queue = UniqueName("bdel"); var url = await CreateQueue(sqs, queue); await SendAll(sqs, url, Enumerable.Range(0, 12).Select(i => $"d{i}")); var routed = 0; await using (await StartRoute(queue, "maxBatchMessages=12&pollTimeoutMs=2000&visibilityTimeout=60", ex => { Interlocked.Add(ref routed, ((List)ex.In.Body!).Count); return Task.CompletedTask; })) { await Until(() => Volatile.Read(ref routed) >= 12, TimeSpan.FromSeconds(30), "12 routed"); await Until(async () => await Count(sqs, url) == (0, 0), TimeSpan.FromSeconds(30), "the batch is deleted after the route: nothing visible, nothing in flight"); } } [Fact] public async Task A_failed_batch_comes_back_after_the_visibility_timeout_and_is_deleted_once_it_succeeds() { using var sqs = RawSqs(); var queue = UniqueName("bfail"); var url = await CreateQueue(sqs, queue); await SendAll(sqs, url, ["x", "y", "z"]); var runs = new ConcurrentQueue>(); await using (await StartRoute(queue, "maxBatchMessages=3&pollTimeoutMs=2000&visibilityTimeout=2", ex => { var seen = Capture(ex); runs.Enqueue(seen.Bodies); if (runs.Count == 1) throw new InvalidOperationException("the first run fails"); return Task.CompletedTask; })) { await Until(() => runs.Count >= 2, TimeSpan.FromSeconds(60), "the batch ran again"); await Until(async () => await Count(sqs, url) == (0, 0), TimeSpan.FromSeconds(30), "deleted after success"); } runs.First().Should().BeEquivalentTo("x", "y", "z"); runs.Skip(1).SelectMany(r => r).Should().BeEquivalentTo(["x", "y", "z"], "the failed messages came back"); } [Fact] public async Task With_resetVisibilityOnFailure_a_failed_batch_is_visible_again_at_once() { using var sqs = RawSqs(); var queue = UniqueName("breset"); var url = await CreateQueue(sqs, queue); await SendAll(sqs, url, ["r1", "r2"]); var runs = 0; var sw = Stopwatch.StartNew(); TimeSpan? second = null; await using (await StartRoute(queue, "maxBatchMessages=2&pollTimeoutMs=1000&visibilityTimeout=120&resetVisibilityOnFailure=true", _ => { if (Interlocked.Increment(ref runs) == 1) throw new InvalidOperationException("the first run fails"); second ??= sw.Elapsed; return Task.CompletedTask; })) { await Until(() => second is not null, TimeSpan.FromSeconds(60), "the batch ran again"); } second!.Value.Should().BeLessThan(TimeSpan.FromSeconds(120), "the reset makes the messages visible at once, not after the 120 s visibility timeout"); } [Fact] public async Task A_batch_that_keeps_failing_reaches_the_dead_letter_queue_through_the_redrive_policy() { using var sqs = RawSqs(); var dlqName = UniqueName("bdlq"); var dlqUrl = await CreateQueue(sqs, dlqName); var dlqArn = (await sqs.GetQueueAttributesAsync(dlqUrl, ["QueueArn"])).QueueARN; var queue = UniqueName("bsrc"); var url = await CreateQueue(sqs, queue, new Dictionary { ["RedrivePolicy"] = JsonSerializer.Serialize(new { deadLetterTargetArn = dlqArn, maxReceiveCount = 2 }), }); await SendAll(sqs, url, ["p1", "p2"]); var runs = 0; await using (await StartRoute(queue, "maxBatchMessages=2&pollTimeoutMs=1000&visibilityTimeout=1", _ => { Interlocked.Increment(ref runs); throw new InvalidOperationException("always fails"); })) { await Until(async () => (await Count(sqs, dlqUrl)).Visible >= 2, TimeSpan.FromSeconds(90), "both messages moved to the dead letter queue"); } var moved = await sqs.ReceiveMessageAsync(new ReceiveMessageRequest { QueueUrl = dlqUrl, MaxNumberOfMessages = 10 }); moved.Messages.Select(m => m.Body).Should().BeEquivalentTo("p1", "p2"); output.WriteLine($"runs before the dead letter queue: {runs}"); } // ── Stop ── [Fact] public async Task A_stop_during_collection_makes_the_collected_messages_visible_again() { using var sqs = RawSqs(); var queue = UniqueName("bstop"); var url = await CreateQueue(sqs, queue); await SendAll(sqs, url, ["s1", "s2"]); var routed = 0; var context = await StartRoute(queue, "maxBatchMessages=10&pollTimeoutMs=60000&visibilityTimeout=300", _ => { Interlocked.Increment(ref routed); return Task.CompletedTask; }); await Until(async () => (await Count(sqs, url)).InFlight == 2, TimeSpan.FromSeconds(30), "both messages received and held by the collection"); await context.DisposeAsync(); Volatile.Read(ref routed).Should().Be(0, "the batch was still collecting"); // The messages are received again well inside the 300 s visibility timeout: the stop gave them back. var again = await ReceiveAll(sqs, url, 2); output.WriteLine($"received again after the stop: {string.Join(",", again.Select(m => m.Body))}; counts now {await Count(sqs, url)}"); again.Select(m => m.Body).Should().BeEquivalentTo("s1", "s2"); } [Fact] public async Task A_stop_after_a_failed_batch_does_not_wait_for_its_visibility_timeout() { using var sqs = RawSqs(); var queue = UniqueName("bstopfail"); var url = await CreateQueue(sqs, queue); await SendAll(sqs, url, ["f1"]); var runs = 0; var context = await StartRoute(queue, "maxBatchMessages=1&pollTimeoutMs=1000&visibilityTimeout=300", _ => { Interlocked.Increment(ref runs); throw new InvalidOperationException("fails"); }); await Until(() => Volatile.Read(ref runs) == 1, TimeSpan.FromSeconds(30), "the batch ran and failed"); var sw = Stopwatch.StartNew(); await context.DisposeAsync(); sw.Stop(); output.WriteLine($"stop took {sw.Elapsed}"); sw.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(60), "the stop does not wait out the 300 s visibility timeout"); (await Count(sqs, url)).InFlight.Should().Be(1, "the failed message waits for its visibility timeout in the queue"); } // ── Concurrency ── [Fact] public async Task Concurrent_consumers_route_batches_in_parallel_and_every_message_once() { using var sqs = RawSqs(); var queue = UniqueName("bconc"); var url = await CreateQueue(sqs, queue); var bodies = Enumerable.Range(0, 60).Select(i => $"c{i:D2}").ToList(); await SendAll(sqs, url, bodies); var seen = new ConcurrentQueue(); var running = 0; var maxRunning = 0; await using (await StartRoute(queue, "concurrentConsumers=3&maxBatchMessages=5&pollTimeoutMs=1000&visibilityTimeout=60", async ex => { var now = Interlocked.Increment(ref running); InterlockedMax(ref maxRunning, now); await Task.Delay(300); foreach (var b in Capture(ex).Bodies) seen.Enqueue(b); Interlocked.Decrement(ref running); })) { await Until(() => seen.Count >= 60, TimeSpan.FromSeconds(90), "60 messages routed"); } seen.Should().BeEquivalentTo(bodies, "every message once"); maxRunning.Should().BeGreaterThan(1, "three workers route batches at the same time"); static void InterlockedMax(ref int target, int value) { int current; while ((current = Volatile.Read(ref target)) < value && Interlocked.CompareExchange(ref target, value, current) != current) { } } } // ── Producer: a list of IMessage ── private static async Task> ReceiveAll(IAmazonSQS sqs, string url, int expected) { var all = new List(); var deadline = DateTime.UtcNow.AddSeconds(30); while (all.Count < expected && DateTime.UtcNow < deadline) { var r = await sqs.ReceiveMessageAsync(new ReceiveMessageRequest { QueueUrl = url, MaxNumberOfMessages = 10, WaitTimeSeconds = 1, MessageAttributeNames = ["All"], MessageSystemAttributeNames = ["All"], }); all.AddRange(r.Messages ?? []); } return all; } private static IProducer Producer(string queue) => new SqsComponent().CreateEndpoint(EndpointUriParser.Parse($"sqs://{queue}?{Connection}")).CreateProducer(); [Fact] public async Task A_list_of_messages_goes_out_one_SQS_message_per_element_with_its_own_body_and_attributes() { using var sqs = RawSqs(); var queue = UniqueName("plist"); var url = await CreateQueue(sqs, queue); var elements = Enumerable.Range(0, 23) .Select(i => (IMessage)new Message($"e{i:D2}") { Headers = { ["XElement"] = $"h{i:D2}" } }) .ToList(); var exchange = new Exchange(new Message(elements) { Headers = { ["XParent"] = "parent" } }); var producer = Producer(queue); await producer.Start(); await producer.Process(exchange); await producer.Stop(); exchange.In.Headers[SqsHeaders.BatchSuccessful].Should().Be(23); exchange.In.Headers[SqsHeaders.BatchFailed].Should().Be(0); exchange.In.Headers.Should().NotContainKey(SqsHeaders.BatchFailedEntries); var got = await ReceiveAll(sqs, url, 23); got.Select(m => m.Body).Should().BeEquivalentTo(elements.Select(e => (string)e.Body!)); foreach (var m in got) { m.MessageAttributes["XElement"].StringValue.Should().Be("h" + m.Body[1..]); m.MessageAttributes.Should().NotContainKey("XParent", "the parent's headers do not go onto the elements"); } } [Fact] public async Task A_list_to_a_FIFO_queue_takes_each_elements_group_and_deduplication_id() { using var sqs = RawSqs(); var queue = UniqueName("plistfifo") + ".fifo"; var url = await CreateQueue(sqs, queue, new Dictionary { ["FifoQueue"] = "true" }); var elements = new List { new Message("g1-a") { Headers = { [SqsHeaders.MessageGroupId] = "g1", [SqsHeaders.MessageDeduplicationId] = "d1" } }, new Message("g2-a") { Headers = { [SqsHeaders.MessageGroupId] = "g2", [SqsHeaders.MessageDeduplicationId] = "d2" } }, new Message("g1-b") { Headers = { [SqsHeaders.MessageGroupId] = "g1", [SqsHeaders.MessageDeduplicationId] = "d3" } }, }; var producer = Producer(queue); await producer.Start(); await producer.Process(new Exchange(new Message(elements))); await producer.Stop(); var got = await ReceiveAll(sqs, url, 3); got.Select(m => (m.Body, m.Attributes["MessageGroupId"])).Should().BeEquivalentTo( [("g1-a", "g1"), ("g2-a", "g2"), ("g1-b", "g1")]); got.Where(m => m.Attributes["MessageGroupId"] == "g1").Select(m => m.Body).Should().Equal("g1-a", "g1-b"); } [Fact] public async Task Entries_SQS_refuses_do_not_throw_they_are_counted_in_headers() { using var sqs = RawSqs(); var queue = UniqueName("plistbad"); var url = await CreateQueue(sqs, queue); // U+0001 is outside the characters SQS allows in a message body: SQS refuses that entry alone. var elements = new List { new Message("good-1"), new Message("bad-\u0001"), new Message("good-2") }; var exchange = new Exchange(new Message(elements)); var producer = Producer(queue); await producer.Start(); await producer.Process(exchange); await producer.Stop(); output.WriteLine($"failed entries: {string.Join("; ", exchange.In.Headers.TryGetValue(SqsHeaders.BatchFailedEntries, out var f) ? (List)f! : [])}"); exchange.In.Headers[SqsHeaders.BatchSuccessful].Should().Be(2); exchange.In.Headers[SqsHeaders.BatchFailed].Should().Be(1); ((List)exchange.In.Headers[SqsHeaders.BatchFailedEntries]!).Should().ContainSingle().Which.Should().StartWith("m1:"); (await ReceiveAll(sqs, url, 2)).Select(m => m.Body).Should().BeEquivalentTo("good-1", "good-2"); } [Fact] public async Task A_list_sent_inside_a_failed_transacted_block_leaves_nothing() { using var sqs = RawSqs(); var queue = UniqueName("plisttx"); var url = await CreateQueue(sqs, queue); var producer = Producer(queue); await producer.Start(); var failed = () => new redb.Route.Transactions.TransactedProcessor( new redb.Route.Processors.DelegateProcessor(async (ex, ct) => { await producer.Process(ex, ct); throw new InvalidOperationException("the unit of work failed"); }), new redb.Route.Transactions.TransactionPolicy()) .Process(new Exchange(new Message(new List { new Message("t1"), new Message("t2") }))); await failed.Should().ThrowAsync(); await producer.Stop(); var r = await sqs.ReceiveMessageAsync(new ReceiveMessageRequest { QueueUrl = url, MaxNumberOfMessages = 10, WaitTimeSeconds = 3 }); (r.Messages ?? []).Should().BeEmpty("the list send joined the block and the block rolled back"); } }