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