Bundle: redb-route / tests/redb.Route.Tests.Sqs (tests.redb.Route.Tests.Sqs.txt), 14 files
Snapshot: 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
Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt
====
Path: redb-route/tests/redb.Route.Tests.Sqs/AckModeOptionsTests.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/AckModeOptionsTests.cs
----
using AwesomeAssertions;
using redb.Route.Core;
using redb.Route.Sqs;
namespace redb.Route.Tests.Sqs;
///
/// ackMode, the one option that says when a consumer settles what it received (manual: after the route,
/// auto: on receipt). The connector's former option is refused with its replacement named.
///
public class AckModeOptionsTests
{
private static SqsEndpointOptions Bind(params (string Key, string Value)[] parameters)
{
var options = new SqsEndpointOptions();
options.BindFromUri(parameters.ToDictionary(p => p.Key, p => p.Value));
return options;
}
[Fact]
public void The_default_is_manual() => new SqsEndpointOptions().AckMode.Should().Be(AckMode.Manual);
[Fact]
public void Auto_binds_from_the_uri() => Bind(("ackMode", "auto")).AckMode.Should().Be(AckMode.Auto);
[Fact]
public void The_former_option_is_refused_with_its_replacement()
{
var act = () => Bind(("deleteAfterRead", "false"));
act.Should().Throw().WithMessage("*'deleteAfterRead' is replaced by 'ackMode'*");
}
[Fact]
public void Auto_with_resetVisibilityOnFailure_is_refused()
{
var options = Bind(("region", "us-east-1"), ("useDefaultCredentialsProvider", "true"), ("ackMode", "auto"), ("resetVisibilityOnFailure", "true"));
var act = () => options.Validate();
act.Should().Throw().WithMessage("*ackMode=auto*resetVisibilityOnFailure*");
}
}
Path: redb-route/tests/redb.Route.Tests.Sqs/AwsClientLogTests.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/AwsClientLogTests.cs
----
using Microsoft.Extensions.Logging;
using redb.Route.Core;
using redb.Route.Sqs;
using redb.Route.Tests.Cluster;
namespace redb.Route.Tests.Sqs;
///
/// The SQS and SNS "client created" logs name the region and service URL the client talks to: a connection factory's,
/// read from the client's own configuration, not the endpoint's defaults.
///
public sealed class AwsClientLogTests
{
private static AwsConnectionFactory Factory() => new()
{
ServiceUrl = "http://localstack.internal:4566", Region = "eu-north-1", AccessKey = "ak", SecretKey = "sk",
};
[Fact]
public async Task SqsClientCreated_WithAConnectionFactory_LogsTheFactorysTarget()
{
var capture = new CapturingLoggerProvider();
using var loggerFactory = LoggerFactory.Create(b => b.AddProvider(capture).SetMinimumLevel(LogLevel.Debug));
await using var context = new RouteContext(loggerFactory: loggerFactory);
context.AddComponent(new SqsComponent());
context.AddToRegistry("aws", Factory());
var endpoint = (SqsEndpoint)context.GetEndpoint("sqs://orders?connectionFactory=aws");
await endpoint.GetOrCreateClientAsync();
var created = capture.Entries.Single(e => e.Message.StartsWith("SQS client created", StringComparison.Ordinal)).Message;
created.Should().Contain("localstack.internal:4566").And.Contain("eu-north-1").And.Contain("aws");
created.Should().NotContain("(default)");
}
[Fact]
public async Task SnsClientCreated_WithAConnectionFactory_LogsTheFactorysTarget()
{
var capture = new CapturingLoggerProvider();
using var loggerFactory = LoggerFactory.Create(b => b.AddProvider(capture).SetMinimumLevel(LogLevel.Debug));
await using var context = new RouteContext(loggerFactory: loggerFactory);
context.AddComponent(new SnsComponent());
context.AddToRegistry("aws", Factory());
var endpoint = (SnsEndpoint)context.GetEndpoint("sns://alerts?connectionFactory=aws");
await endpoint.GetOrCreateClientAsync();
var created = capture.Entries.Single(e => e.Message.StartsWith("SNS client created", StringComparison.Ordinal)).Message;
created.Should().Contain("localstack.internal:4566").And.Contain("eu-north-1").And.Contain("aws");
created.Should().NotContain("(default)");
}
}
Path: redb-route/tests/redb.Route.Tests.Sqs/ComponentSideTests.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/ComponentSideTests.cs
----
using redb.Route.Core;
using redb.Route.Sqs;
namespace redb.Route.Tests.Sqs;
/// The component declares the only side it has ([EndpointRole] , Apache Camel's producerOnly / consumerOnly).
public sealed class ComponentSideTests
{
[Fact]
public void The_component_declares_its_only_side()
{
EndpointSides.Declaration(typeof(SnsComponent))!.Role.Should().Be(EndpointRole.Producer);
EndpointSides.Declaration(typeof(SqsComponent)).Should().BeNull("sqs has both sides");
}
}
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");
}
}
Path: redb-route/tests/redb.Route.Tests.Sqs/SqsBatchOptionsTests.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/SqsBatchOptionsTests.cs
----
using redb.Route.Core;
using redb.Route.Sqs;
namespace redb.Route.Tests.Sqs;
/// SQS batch options: resolved when the endpoint is created; each configuration that cannot work refused.
public sealed class SqsBatchOptionsTests
{
private static SqsEndpoint Create(string query)
=> (SqsEndpoint)new SqsComponent().CreateEndpoint(EndpointUriParser.Parse($"sqs://orders?region=us-east-1&accessKey=test&secretKey=test&{query}"));
[Theory]
[InlineData("maxBatchMessages=5", "maxBatchMessages")]
[InlineData("batchingIntervalMs=1000", "batchingIntervalMs")]
public void A_batch_option_without_batching_is_refused(string query, string named)
{
var act = () => Create(query);
act.Should().Throw().WithMessage($"*sqs://orders*{named}*batching=true*");
}
[Theory]
[InlineData("maxBatchMessages=0", "maxBatchMessages")]
[InlineData("pollTimeoutMs=0", "pollTimeoutMs")]
[InlineData("batchingIntervalMs=0", "batchingIntervalMs")]
public void A_value_out_of_range_is_refused(string query, string named)
{
var act = () => Create($"batching=true&{query}");
act.Should().Throw().WithMessage($"*{named}*");
}
[Fact]
public void Batching_with_extendMessageVisibility_is_refused()
{
var act = () => Create("batching=true&visibilityTimeout=30&extendMessageVisibility=true");
act.Should().Throw().WithMessage("*batching=true*extendMessageVisibility*visibilityTimeout*");
}
[Fact]
public void Batching_defaults_to_a_batch_of_one_receive()
{
var options = new SqsEndpointOptions { Batching = true };
options.ResolveBatch("sqs://orders");
options.Batch!.MaxMessages.Should().Be(10);
options.Batch.PollTimeout.Should().Be(TimeSpan.FromSeconds(1));
options.Batch.Interval.Should().BeNull();
}
[Fact]
public void A_batch_may_be_larger_than_one_receive()
{
var options = new SqsEndpointOptions { Batching = true, MaxBatchMessages = 25, BatchingIntervalMs = 5000 };
options.ResolveBatch("sqs://orders");
options.Batch!.MaxMessages.Should().Be(25);
options.Batch.Interval.Should().Be(TimeSpan.FromSeconds(5));
}
[Fact]
public void Without_batching_there_are_no_batch_options()
{
var options = new SqsEndpointOptions();
options.ResolveBatch("sqs://orders");
options.Batch.Should().BeNull();
}
[Theory]
[InlineData("enableBatch=true")]
[InlineData("batchMaxMessages=5")]
public void The_removed_producer_batch_options_are_unknown(string query)
{
var act = () => Create(query);
act.Should().Throw().WithMessage(query.Split('=')[0] is var name ? $"*{name}*" : "*");
}
}
Path: redb-route/tests/redb.Route.Tests.Sqs/SqsBatchStopTests.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/SqsBatchStopTests.cs
----
using System.Reflection;
using Amazon.SQS;
using Amazon.SQS.Model;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Sqs;
using SqsMessage = Amazon.SQS.Model.Message;
namespace redb.Route.Tests.Sqs;
///
/// The SQS batch consumer's stop, against a client stub: a receive in flight is not abandoned (an abandoned long poll
/// stays open at the queue and would take the messages the stop gives back); it runs to its end, and the stop gives
/// the whole batch, its messages included, back before it returns.
///
public sealed class SqsBatchStopTests
{
private const string QueueUrl = "http://sqs.local/000000000000/orders";
private static string Uri =>
$"sqs://orders?region=us-east-1&accessKey=t&secretKey=t&queueUrl={System.Uri.EscapeDataString(QueueUrl)}" +
"&batching=true&maxBatchMessages=10&pollTimeoutMs=60000";
private static SqsMessage Msg(string id) => new() { MessageId = id, ReceiptHandle = "h" + id, Body = id };
///
/// A client whose first receive returns two messages and whose second blocks until release lets it return a
/// third, the way a long poll answers when its message comes or its wait ends.
///
private static IAmazonSQS Stub(SqsEndpoint endpoint, TaskCompletionSource inFlight, TaskCompletionSource release,
List tokens)
{
var client = Substitute.For();
typeof(SqsEndpoint).GetField("_client", BindingFlags.Instance | BindingFlags.NonPublic)!.SetValue(endpoint, client);
var calls = 0;
client.ReceiveMessageAsync(Arg.Any(), Arg.Any()).Returns(async call =>
{
lock (tokens) tokens.Add(call.Arg());
switch (Interlocked.Increment(ref calls))
{
case 1:
return new ReceiveMessageResponse { Messages = [Msg("1"), Msg("2")] };
case 2:
inFlight.TrySetResult();
await release.Task;
return new ReceiveMessageResponse { Messages = [Msg("3")] };
default:
throw new InvalidOperationException("no receive after the stop");
}
});
client.ChangeMessageVisibilityBatchAsync(Arg.Any(), Arg.Any())
.Returns(new ChangeMessageVisibilityBatchResponse { Successful = [], Failed = [] });
return client;
}
private static async Task ExpectAllGivenBack(IAmazonSQS client, List tokens)
{
await client.Received(1).ChangeMessageVisibilityBatchAsync(
Arg.Is(r =>
r.Entries.Select(e => e.ReceiptHandle).SequenceEqual(new[] { "h1", "h2", "h3" })
&& r.Entries.All(e => e.VisibilityTimeout == 0)),
Arg.Any());
tokens.Should().OnlyContain(t => !t.CanBeCanceled, "a receive is never cancelled by the stop");
}
[Fact]
public async Task A_stop_during_collection_lets_the_receive_end_and_gives_every_collected_message_back()
{
var endpoint = (SqsEndpoint)new SqsComponent().CreateEndpoint(EndpointUriParser.Parse(Uri));
var inFlight = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var tokens = new List();
var client = Stub(endpoint, inFlight, release, tokens);
var processor = Substitute.For();
var consumer = endpoint.CreateConsumer(processor);
await consumer.Start();
await inFlight.Task.WaitAsync(TimeSpan.FromSeconds(10));
var stop = consumer.Stop();
await Task.Delay(200);
stop.IsCompleted.Should().BeFalse("the stop waits for the receive in flight");
release.SetResult();
await stop.WaitAsync(TimeSpan.FromSeconds(10));
await processor.DidNotReceive().Process(Arg.Any(), Arg.Any());
await ExpectAllGivenBack(client, tokens);
}
[Fact]
public async Task A_route_contexts_stop_during_collection_gives_every_collected_message_back()
{
var context = new RouteContext();
context.AddComponent(new SqsComponent());
var endpoint = (SqsEndpoint)context.GetEndpoint(Uri);
var inFlight = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var tokens = new List();
var client = Stub(endpoint, inFlight, release, tokens);
var routed = 0;
context.AddRoutes(r => r.From(Uri).Process(_ => Interlocked.Increment(ref routed)));
await context.Start();
await inFlight.Task.WaitAsync(TimeSpan.FromSeconds(10));
var stop = context.DisposeAsync().AsTask();
release.SetResult();
await stop.WaitAsync(TimeSpan.FromSeconds(30));
routed.Should().Be(0);
await ExpectAllGivenBack(client, tokens);
}
}
Path: redb-route/tests/redb.Route.Tests.Sqs/SqsErrorDetailTests.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/SqsErrorDetailTests.cs
----
using System.Reflection;
using Amazon.SQS;
using Amazon.SQS.Model;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Sqs;
using SqsMessage = Amazon.SQS.Model.Message;
namespace redb.Route.Tests.Sqs;
///
/// A transport failure the SQS connector records on its endpoint carries its text, so the dashboard's last error says
/// what went wrong: a failed receive, single and batch, a batch that failed to settle, the entries SQS refused in a
/// batch delete or a batch send. Against a client stub; no queue.
///
public sealed class SqsErrorDetailTests
{
private const string QueueUrl = "http://sqs.local/000000000000/orders";
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(10);
private static string Uri(string extra = "") =>
$"sqs://orders?region=us-east-1&accessKey=t&secretKey=t&queueUrl={System.Uri.EscapeDataString(QueueUrl)}" +
"&pollTimeoutMs=1000" + extra;
private static IAmazonSQS Stub(SqsEndpoint endpoint)
{
var client = Substitute.For();
typeof(SqsEndpoint).GetField("_client", BindingFlags.Instance | BindingFlags.NonPublic)!.SetValue(endpoint, client);
return client;
}
/// The first receive throws ; later ones return nothing after a short wait.
private static void FailFirstReceive(IAmazonSQS client, Exception failure)
{
var calls = 0;
client.ReceiveMessageAsync(Arg.Any(), Arg.Any()).Returns(async _ =>
{
if (Interlocked.Increment(ref calls) == 1)
throw failure;
await Task.Delay(50);
return new ReceiveMessageResponse { Messages = [] };
});
}
/// The first receive returns one message; later ones return nothing after a short wait.
private static void OneMessage(IAmazonSQS client)
{
var calls = 0;
client.ReceiveMessageAsync(Arg.Any(), Arg.Any()).Returns(async _ =>
{
if (Interlocked.Increment(ref calls) == 1)
return new ReceiveMessageResponse { Messages = [new SqsMessage { MessageId = "m1", ReceiptHandle = "h1", Body = "b" }] };
await Task.Delay(50);
return new ReceiveMessageResponse { Messages = [] };
});
}
private static async Task LastErrorOf(SqsEndpoint endpoint, IConsumer consumer)
{
await consumer.Start();
try
{
var deadline = DateTime.UtcNow + Wait;
while (endpoint.Errors == 0 && DateTime.UtcNow < deadline)
await Task.Delay(20);
endpoint.Errors.Should().BeGreaterThan(0, "the failure is recorded on the endpoint");
return endpoint.LastErrorMessage;
}
finally
{
await consumer.Stop();
}
}
[Fact]
public async Task A_failed_receive_is_recorded_with_its_text()
{
var endpoint = (SqsEndpoint)new SqsComponent().CreateEndpoint(EndpointUriParser.Parse(Uri()));
FailFirstReceive(Stub(endpoint), new InvalidOperationException("receive refused by the test"));
var lastError = await LastErrorOf(endpoint, endpoint.CreateConsumer(Substitute.For()));
lastError.Should().Contain("receive refused by the test");
}
[Fact]
public async Task A_failed_batch_receive_is_recorded_with_its_text()
{
var endpoint = (SqsEndpoint)new SqsComponent().CreateEndpoint(EndpointUriParser.Parse(Uri("&batching=true&maxBatchMessages=10")));
FailFirstReceive(Stub(endpoint), new InvalidOperationException("batch receive refused by the test"));
var lastError = await LastErrorOf(endpoint, endpoint.CreateConsumer(Substitute.For()));
lastError.Should().Contain("batch receive refused by the test");
}
[Fact]
public async Task A_batch_that_failed_to_settle_is_recorded_with_its_text()
{
var endpoint = (SqsEndpoint)new SqsComponent().CreateEndpoint(EndpointUriParser.Parse(Uri("&batching=true&maxBatchMessages=10")));
var client = Stub(endpoint);
OneMessage(client);
client.DeleteMessageBatchAsync(Arg.Any(), Arg.Any())
.Returns(_ => throw new InvalidOperationException("delete failed in the test"));
var lastError = await LastErrorOf(endpoint, endpoint.CreateConsumer(Substitute.For()));
lastError.Should().Contain("delete failed in the test");
}
[Fact]
public async Task Entries_refused_in_a_batch_delete_are_recorded_with_their_code()
{
var endpoint = (SqsEndpoint)new SqsComponent().CreateEndpoint(EndpointUriParser.Parse(Uri("&batching=true&maxBatchMessages=10")));
var client = Stub(endpoint);
OneMessage(client);
client.DeleteMessageBatchAsync(Arg.Any(), Arg.Any())
.Returns(new DeleteMessageBatchResponse
{
Successful = [],
Failed = [new BatchResultErrorEntry { Id = "0", Code = "ReceiptHandleIsInvalid", Message = "handle expired", SenderFault = true }],
});
var lastError = await LastErrorOf(endpoint, endpoint.CreateConsumer(Substitute.For()));
lastError.Should().Contain("ReceiptHandleIsInvalid").And.Contain("m1");
}
[Fact]
public async Task Entries_refused_in_a_batch_send_are_recorded_with_their_code()
{
var endpoint = (SqsEndpoint)new SqsComponent().CreateEndpoint(EndpointUriParser.Parse(Uri()));
var client = Stub(endpoint);
client.SendMessageBatchAsync(Arg.Any(), Arg.Any())
.Returns(new SendMessageBatchResponse
{
Successful = [],
Failed = [new BatchResultErrorEntry { Id = "0", Code = "InvalidParameterValue", Message = "body too long", SenderFault = true }],
});
var producer = endpoint.CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new redb.Route.Core.Message(new List { new redb.Route.Core.Message("a") })));
await producer.Stop();
endpoint.Errors.Should().Be(1);
endpoint.LastErrorMessage.Should().Contain("InvalidParameterValue").And.Contain("body too long");
}
}
Path: redb-route/tests/redb.Route.Tests.Sqs/SqsHeaderFilterStrategyTests.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/SqsHeaderFilterStrategyTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Sqs;
using Message = redb.Route.Core.Message;
using SqsDsl = redb.Route.Sqs.Fluent.Sqs;
namespace redb.Route.Tests.Sqs;
///
/// headerFilterStrategy=#name on SQS endpoints: on a producer it decides which plain exchange headers go out as
/// message attributes, on a consumer which attributes come in (asked with the attribute's own name). A
/// redbSqs.attr.X header and the consumer's redbSqs.* metadata stay outside the strategy.
///
[Trait("Category", "Integration")]
public sealed class SqsHeaderFilterStrategyTests
{
private const string Attr = SqsHeaders.MessageAttributePrefix;
private static string Uri(string queue, string options) => SqsDsl.Queue(queue).ServiceUrl("http://localhost:4566")
.Region("us-east-1").Credentials("test", "test").AutoCreateQueue().Build() + options;
private static async Task> RoundTrip(string producerOptions, string consumerOptions)
{
var queue = $"hdr-strategy-{Guid.NewGuid():N}";
var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using var ctx = new RouteContext();
ctx.AddComponent(new SqsComponent());
ctx.AddToRegistry("correlationOnly", new DefaultHeaderFilterStrategy { OutFilter = ["Correlation-ID"], FilterOnMatch = false });
ctx.AddToRegistry("noSecrets", new DefaultHeaderFilterStrategy { InFilter = ["Authorization"] });
ctx.AddRoutes(r => r.From(Uri(queue, consumerOptions)).Process(e => received.TrySetResult(e)));
await ctx.Start();
var exchange = new Exchange(new Message("body"));
exchange.In.Headers["Correlation-ID"] = "c-42";
exchange.In.Headers["X-Corr"] = "c1";
exchange.In.Headers["Authorization"] = "Bearer secret";
exchange.In.Headers[Attr + "Named"] = "by-prefix";
var producer = ctx.GetEndpoint(Uri(queue, producerOptions)).CreateProducer();
await producer.Start();
await producer.Process(exchange);
await producer.Stop();
return new Dictionary((await received.Task.WaitAsync(TimeSpan.FromSeconds(30))).In.Headers);
}
[Fact]
public async Task OnAProducer_AWhitelistSendsOnlyTheNamedHeader_AndTheExplicitAttribute()
{
var headers = await RoundTrip("&headerFilterStrategy=#correlationOnly", "");
headers[Attr + "Correlation-ID"].Should().Be("c-42");
headers.Should().NotContainKey(Attr + "X-Corr");
headers.Should().NotContainKey(Attr + "Authorization");
headers[Attr + "Named"].Should().Be("by-prefix", "a redbSqs.attr.X header is an explicit request");
headers.Should().ContainKey(SqsHeaders.MessageId, "the consumer's own metadata is set whatever the strategy says");
}
[Fact]
public async Task OnAConsumer_TheStrategyDecidesWhatComesIn_ByTheAttributeName()
{
var headers = await RoundTrip("", "&headerFilterStrategy=#noSecrets");
headers[Attr + "X-Corr"].Should().Be("c1");
headers.Should().NotContainKey(Attr + "Authorization", "the consumer's strategy drops it on the way in");
}
}
Path: redb-route/tests/redb.Route.Tests.Sqs/SqsHeaderMappingCharacterizationTests.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/SqsHeaderMappingCharacterizationTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Sqs;
using Message = redb.Route.Core.Message;
using SqsDsl = redb.Route.Sqs.Fluent.Sqs;
namespace redb.Route.Tests.Sqs;
///
/// What crosses an SQS message today, producer to consumer: pinned before the header filter strategy
/// takes the rule over, so the transport's default keeps it exactly.
/// The producer sends every exchange header but its own redbSqs.* /redbSns.* and null values as a string
/// message attribute (a redbSqs.attr.X header as attribute X ). The consumer does not put attributes back
/// under their names: each comes as redbSqs.attr.X , so a received attribute cannot pose as a control header.
///
[Trait("Category", "Integration")]
public sealed class SqsHeaderMappingCharacterizationTests
{
private static string Uri(string queue) => SqsDsl.Queue(queue).ServiceUrl("http://localhost:4566").Region("us-east-1")
.Credentials("test", "test").AutoCreateQueue().Build();
[Fact]
public async Task ProducerToConsumer_TheHeadersThatCrossTheMessage()
{
var queue = $"hdr-char-{Guid.NewGuid():N}";
var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using var ctx = new RouteContext();
ctx.AddComponent(new SqsComponent());
ctx.AddRoutes(r => r.From(Uri(queue)).Process(e => received.TrySetResult(e)));
await ctx.Start();
var exchange = new Exchange(new Message("body"));
exchange.In.Headers["X-Corr"] = "c1";
exchange.In.Headers["X-Int"] = 42;
exchange.In.Headers["X-Null"] = null;
exchange.In.Headers["Authorization"] = "Bearer secret";
exchange.In.Headers["redbHttp.Method"] = "DELETE";
exchange.In.Headers[SqsHeaders.MessageAttributePrefix + "Named"] = "by-prefix";
exchange.In.Headers[SqsHeaders.Prefix + "Custom"] = "own";
var producer = ctx.GetEndpoint(Uri(queue)).CreateProducer();
await producer.Start();
await producer.Process(exchange);
await producer.Stop();
var headers = (await received.Task.WaitAsync(TimeSpan.FromSeconds(30))).In.Headers;
const string attr = SqsHeaders.MessageAttributePrefix;
headers[attr + "X-Corr"].Should().Be("c1");
headers[attr + "X-Int"].Should().Be("42", "an attribute is sent as a String");
headers.Should().NotContainKey(attr + "X-Null", "a null value is skipped");
headers[attr + "Authorization"].Should().Be("Bearer secret", "nothing filters a credential on the way out");
headers[attr + "redbHttp.Method"].Should().Be("DELETE", "it crosses, but only under the attribute prefix");
headers.Should().NotContainKey("redbHttp.Method", "a received attribute never comes under its own name");
headers.Should().NotContainKey("X-Corr");
headers[attr + "Named"].Should().Be("by-prefix", "a redbSqs.attr.X header is sent as attribute X");
headers.Should().NotContainKey(attr + SqsHeaders.Prefix + "Custom", "the producer keeps its own redbSqs.* back");
}
}
Path: redb-route/tests/redb.Route.Tests.Sqs/SqsIntegrationTests.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/SqsIntegrationTests.cs
----
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Text;
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 SqsDsl = redb.Route.Sqs.Fluent.Sqs;
using SnsDsl = redb.Route.Sqs.Fluent.Sns;
namespace redb.Route.Tests.Sqs;
///
/// Integration tests for the SQS/SNS connector against LocalStack.
/// Requires: docker compose -f redb.Route/docker-compose.tests.yml --profile sqs up -d --wait
/// Endpoint: http://localhost:4566 (community, anonymous test/test creds).
///
[Trait("Category", "Integration")]
public sealed class SqsIntegrationTests
{
private const string ServiceUrl = "http://localhost:4566";
private const string Region = "us-east-1";
private readonly ITestOutputHelper _output;
public SqsIntegrationTests(ITestOutputHelper output) => _output = output;
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 });
// Base builder: serviceUrl + region + creds + autoCreate always applied; chain extras inline.
private static redb.Route.Sqs.Fluent.SqsBuilder Q(string name) =>
SqsDsl.Queue(name).ServiceUrl(ServiceUrl).Region(Region).Credentials("test", "test").AutoCreateQueue();
private static SqsEndpoint MakeEndpoint(redb.Route.Sqs.Fluent.SqsBuilder b) =>
(SqsEndpoint)new SqsComponent().CreateEndpoint(EndpointUriParser.Parse(b.Build()));
private static IProcessor Recorder(Func onEach)
{
var p = Substitute.For();
p.Process(Arg.Any(), Arg.Any())
.Returns(call => onEach(call.Arg()));
return p;
}
private static async Task WaitFor(Func cond, TimeSpan timeout)
{
using var cts = new CancellationTokenSource(timeout);
while (!cond())
{
cts.Token.ThrowIfCancellationRequested();
await Task.Delay(20, cts.Token);
}
}
// ── Roundtrip ─────────────────────────────────────────────────────
[Fact]
public async Task Roundtrip_SendReceive_BodyAndAttributes()
{
var queue = UniqueName("rt");
var received = new ConcurrentBag();
var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var consumer = MakeEndpoint(Q(queue)).CreateConsumer(Recorder(ex =>
{
received.Add(ex);
tcs.TrySetResult();
return Task.CompletedTask;
}));
await consumer.Start();
try
{
var prod = MakeEndpoint(Q(queue));
var producer = prod.CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("hello-sqs"));
exchange.In.Headers["orderId"] = "42";
await producer.Process(exchange);
await Task.WhenAny(tcs.Task, Task.Delay(15_000));
received.Should().NotBeEmpty();
var got = received.First();
got.In.Body!.ToString().Should().Be("hello-sqs");
got.In.Headers[SqsHeaders.MessageAttributePrefix + "orderId"].Should().Be("42");
await producer.Stop();
}
finally { await consumer.Stop(); }
}
// ── Concurrency ───────────────────────────────────────────────────
[Fact]
public async Task ConcurrentConsumers_ProcessUpToNInParallel()
{
const int pool = 5, total = 20;
var queue = UniqueName("conc");
var current = 0; var max = 0; var maxLock = new object(); var received = 0;
var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
// maxNumberOfMessages=1 so each of the N workers holds one message at a time — the pool truly saturates.
var consumer = MakeEndpoint(Q(queue).ConcurrentConsumers(pool).MaxNumberOfMessages(1).WaitTimeSeconds(1))
.CreateConsumer(Recorder(async _ =>
{
var c = Interlocked.Increment(ref current);
lock (maxLock) { if (c > max) max = c; }
await Task.Delay(200);
Interlocked.Decrement(ref current);
if (Interlocked.Increment(ref received) >= total) done.TrySetResult();
}));
// Row 67: all messages are in the queue before the consumer starts, so the pool meets a full queue at once.
// Sent while it ran, a slow producer on a loaded stand could keep fewer than N messages waiting.
var producer = MakeEndpoint(Q(queue)).CreateProducer();
await producer.Start();
for (var i = 0; i < total; i++)
await producer.Process(new Exchange(new Message($"m{i}")));
await producer.Stop();
await consumer.Start();
try
{
await Task.WhenAny(done.Task, Task.Delay(30_000));
Volatile.Read(ref received).Should().Be(total, "no message lost");
max.Should().Be(pool, "the pool saturates to N concurrent workers");
_output.WriteLine("max concurrency = {0}, received = {1}", max, received);
}
finally { await consumer.Stop(); }
}
// ── FIFO ordering ─────────────────────────────────────────────────
[Fact]
public async Task Fifo_SingleConsumer_PreservesOrder()
{
const int total = 10;
var queue = UniqueName("ord") + ".fifo";
var received = new List();
var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var consumer = MakeEndpoint(Q(queue).ConcurrentConsumers(1).MaxNumberOfMessages(1))
.CreateConsumer(Recorder(ex =>
{
lock (received)
{
received.Add(int.Parse(ex.In.Body!.ToString()!));
if (received.Count >= total) done.TrySetResult();
}
return Task.CompletedTask;
}));
await consumer.Start();
try
{
var producer = MakeEndpoint(Q(queue).MessageGroupId("g1")).CreateProducer();
await producer.Start();
for (var i = 0; i < total; i++)
await producer.Process(new Exchange(new Message(i.ToString())));
await producer.Stop();
await Task.WhenAny(done.Task, Task.Delay(30_000));
received.Should().HaveCount(total);
received.Should().BeInAscendingOrder("a FIFO queue with one consumer preserves order");
}
finally { await consumer.Stop(); }
}
// ── Batch send ────────────────────────────────────────────────────
[Fact]
public async Task A_plain_list_is_one_message_its_JSON()
{
var queue = UniqueName("plain");
var received = new ConcurrentBag();
var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var consumer = MakeEndpoint(Q(queue)).CreateConsumer(Recorder(ex =>
{
received.Add(ex.In.Body!.ToString()!);
done.TrySetResult();
return Task.CompletedTask;
}));
await consumer.Start();
try
{
var producer = MakeEndpoint(Q(queue)).CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message(new[] { "a", "b", "c", "d", "e" })));
await producer.Stop();
await done.Task.WaitAsync(TimeSpan.FromSeconds(15));
received.Should().Equal("[\"a\",\"b\",\"c\",\"d\",\"e\"]");
}
finally { await consumer.Stop(); }
}
// ── Visibility redelivery on failure (at-least-once) ──────────────
[Fact]
public async Task Failure_LeavesMessageForRedelivery_ThenSucceeds()
{
var queue = UniqueName("vis");
var attempts = 0;
var succeeded = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
// visibilityTimeout=2s + resetVisibilityOnFailure so the first (throwing) receive redelivers quickly.
var consumer = MakeEndpoint(Q(queue).VisibilityTimeout(2).ResetVisibilityOnFailure().MaxNumberOfMessages(1))
.CreateConsumer(Recorder(_ =>
{
var n = Interlocked.Increment(ref attempts);
if (n == 1) throw new InvalidOperationException("boom on first attempt");
succeeded.TrySetResult();
return Task.CompletedTask;
}));
await consumer.Start();
try
{
var producer = MakeEndpoint(Q(queue)).CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message("retry-me")));
await producer.Stop();
await Task.WhenAny(succeeded.Task, Task.Delay(30_000));
Volatile.Read(ref attempts).Should().BeGreaterThanOrEqualTo(2,
"a failed message is not deleted and is redelivered after the visibility timeout");
}
finally { await consumer.Stop(); }
}
// ── SNS → SQS fan-out ─────────────────────────────────────────────
[Fact]
public async Task SnsToSqs_PublishReachesSubscribedQueue()
{
var queue = UniqueName("snsq");
var topic = UniqueName("evt");
// Create the queue up front and read its ARN for the subscription.
using var raw = RawSqs();
var queueUrl = (await raw.CreateQueueAsync(queue)).QueueUrl;
var arn = (await raw.GetQueueAttributesAsync(new GetQueueAttributesRequest
{
QueueUrl = queueUrl,
AttributeNames = ["QueueArn"],
})).Attributes["QueueArn"];
var received = new ConcurrentBag();
var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var consumer = MakeEndpoint(Q(queue)).CreateConsumer(Recorder(ex =>
{
received.Add(ex.In.Body!.ToString()!);
done.TrySetResult();
return Task.CompletedTask;
}));
await consumer.Start();
try
{
var snsUri = SnsDsl.Topic(topic)
.ServiceUrl(ServiceUrl).Region(Region).Credentials("test", "test")
.AutoCreateTopic().SubscribeSnsToSqs(arn).Build();
var snsEndpoint = (SnsEndpoint)new SnsComponent().CreateEndpoint(EndpointUriParser.Parse(snsUri));
var producer = snsEndpoint.CreateProducer();
await producer.Start(); // subscribes the queue to the topic
await producer.Process(new Exchange(new Message("via-sns")));
await Task.WhenAny(done.Task, Task.Delay(20_000));
received.Should().NotBeEmpty("the SNS message must fan out to the subscribed SQS queue");
// SNS delivers a JSON envelope; the payload is inside "Message".
received.First().Should().Contain("via-sns");
// Ownership audit: a hand-built publish moves nothing into MessagesOut - the core
// (ToProcessor / the template) owns it; self-recording doubled routed sends.
snsEndpoint.MessagesOut.Should().Be(0, "MessagesOut is written by the core");
await producer.Stop();
}
finally { await consumer.Stop(); }
}
// ── SNS → SQS raw message delivery (bare payload + attribute passthrough) ──
[Fact]
public async Task SnsToSqs_RawDelivery_DeliversBarePayloadAndAttributes()
{
var queue = UniqueName("rawq");
var topic = UniqueName("rawevt");
// Create the queue up front and read its ARN for the subscription.
using var raw = RawSqs();
var queueUrl = (await raw.CreateQueueAsync(queue)).QueueUrl;
var arn = (await raw.GetQueueAttributesAsync(new GetQueueAttributesRequest
{
QueueUrl = queueUrl,
AttributeNames = ["QueueArn"],
})).Attributes["QueueArn"];
var received = new ConcurrentBag();
var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var consumer = MakeEndpoint(Q(queue)).CreateConsumer(Recorder(ex =>
{
received.Add(ex);
done.TrySetResult();
return Task.CompletedTask;
}));
await consumer.Start();
try
{
// rawMessageDelivery: the subscription is set to RawMessageDelivery=true, so the queue gets
// the bare payload (not the JSON envelope) and SNS attributes arrive as SQS attributes.
var snsUri = SnsDsl.Topic(topic)
.ServiceUrl(ServiceUrl).Region(Region).Credentials("test", "test")
.AutoCreateTopic().SubscribeSnsToSqs(arn).RawMessageDelivery().Build();
var snsEndpoint = (SnsEndpoint)new SnsComponent().CreateEndpoint(EndpointUriParser.Parse(snsUri));
var producer = snsEndpoint.CreateProducer();
await producer.Start(); // subscribes the queue with RawMessageDelivery=true
var exchange = new Exchange(new Message("bare-payload"));
exchange.In.Headers["eventType"] = "created";
await producer.Process(exchange);
await Task.WhenAny(done.Task, Task.Delay(20_000));
received.Should().NotBeEmpty("the SNS message must fan out to the subscribed SQS queue");
var got = received.First();
// Raw delivery → the body is the exact payload, NOT a {"Type":"Notification",...} envelope.
got.In.Body!.ToString().Should().Be("bare-payload");
// SNS message attributes are delivered as SQS message attributes (the envelope mode hides them).
got.In.Headers[SqsHeaders.MessageAttributePrefix + "eventType"].Should().Be("created");
await producer.Stop();
}
finally { await consumer.Stop(); }
}
// ── Transacted ack (SqsAckAction) ─────────────────────────────────
[Fact]
public async Task AckAction_CommitDeletes_RollbackRedelivers()
{
var queue = UniqueName("ack");
using var raw = RawSqs();
var url = (await raw.CreateQueueAsync(queue)).QueueUrl;
await raw.SendMessageAsync(url, "commit-me");
await raw.SendMessageAsync(url, "rollback-me");
// Receive both with a comfortable visibility window.
var msgs = new List();
var recvDeadline = DateTime.UtcNow.AddSeconds(15);
while (msgs.Count < 2 && DateTime.UtcNow < recvDeadline)
{
var r = await raw.ReceiveMessageAsync(new ReceiveMessageRequest
{
QueueUrl = url, MaxNumberOfMessages = 10, WaitTimeSeconds = 2, VisibilityTimeout = 30,
});
if (r.Messages is not null) msgs.AddRange(r.Messages);
}
msgs.Should().HaveCount(2);
var commit = msgs.First(m => m.Body == "commit-me");
var rollback = msgs.First(m => m.Body == "rollback-me");
// Commit deletes; Rollback resets visibility to 0 → immediate redelivery.
await new SqsAckAction(raw, url, commit.ReceiptHandle, deleteAfterRead: true).Commit();
await new SqsAckAction(raw, url, rollback.ReceiptHandle, deleteAfterRead: true).Rollback();
var seen = new HashSet();
var deadline = DateTime.UtcNow.AddSeconds(15);
while (DateTime.UtcNow < deadline && !seen.Contains("rollback-me"))
{
var r = await raw.ReceiveMessageAsync(new ReceiveMessageRequest
{
QueueUrl = url, MaxNumberOfMessages = 10, WaitTimeSeconds = 2,
});
foreach (var m in r.Messages ?? [])
{
seen.Add(m.Body);
await raw.DeleteMessageAsync(url, m.ReceiptHandle);
}
}
seen.Should().Contain("rollback-me", "rollback reset visibility → the message is redelivered");
seen.Should().NotContain("commit-me", "commit deleted the message");
}
// ── Distributed trace propagation ─────────────────────────────────
[Fact]
public async Task TraceContext_Producer_Injects_Consumer_Surfaces()
{
// Listen to the redb.Route source so producer/consumer spans (and thus injection) are created.
using var listener = new ActivityListener
{
ShouldListenTo = s => s.Name == "redb.Route",
Sample = (ref ActivityCreationOptions _) => ActivitySamplingResult.AllDataAndRecorded,
};
ActivitySource.AddActivityListener(listener);
var queue = UniqueName("trace");
string? traceparent = null;
var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var consumer = MakeEndpoint(Q(queue)).CreateConsumer(Recorder(ex =>
{
traceparent = ex.In.Headers.TryGetValue(SqsHeaders.MessageAttributePrefix + "traceparent", out var v)
? v?.ToString() : null;
done.TrySetResult();
return Task.CompletedTask;
}));
await consumer.Start();
try
{
var producer = MakeEndpoint(Q(queue)).CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message("traced")));
await producer.Stop();
await Task.WhenAny(done.Task, Task.Delay(15_000));
traceparent.Should().NotBeNullOrEmpty(
"the producer injects W3C traceparent as a message attribute so the trace continues across SQS");
}
finally { await consumer.Stop(); }
}
// ── Statistics ownership (audit follow-up) ──
[Fact]
public async Task Statistics_AreOwnedByTheCore_NotSelfRecorded()
{
// Ownership audit: MessagesOut belongs to the core (ToProcessor / the template) and
// MessagesIn to the core's StatisticsProcessor around a routed From(). A hand-built
// producer/consumer pair therefore moves NOTHING into those counters - self-recording
// here used to double every routed number.
var queue = UniqueName("own");
var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var consumerEndpoint = MakeEndpoint(Q(queue));
var consumer = consumerEndpoint.CreateConsumer(Recorder(_ =>
{
done.TrySetResult();
return Task.CompletedTask;
}));
await consumer.Start();
try
{
var producerEndpoint = MakeEndpoint(Q(queue));
var producer = producerEndpoint.CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message("owned")));
await Task.WhenAny(done.Task, Task.Delay(15_000));
done.Task.IsCompleted.Should().BeTrue("the message must arrive");
await producer.Stop();
producerEndpoint.MessagesOut.Should().Be(0, "MessagesOut is written by the core, the own write doubled it in the route");
consumerEndpoint.MessagesIn.Should().Be(0, "MessagesIn is written by StatisticsProcessor around From()");
}
finally { await consumer.Stop(); }
}
}
Path: redb-route/tests/redb.Route.Tests.Sqs/SqsTracePropagationTests.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/SqsTracePropagationTests.cs
----
using System.Diagnostics;
using Amazon.Runtime;
using Amazon.SQS;
using Amazon.SQS.Model;
using redb.Route.Abstractions;
using redb.Route.Configuration;
using redb.Route.Core;
using redb.Route.Sqs;
using redb.Route.Telemetry;
using redb.Route.Tests.Telemetry;
using Message = redb.Route.Core.Message;
using SqsDsl = redb.Route.Sqs.Fluent.Sqs;
using SnsDsl = redb.Route.Sqs.Fluent.Sns;
namespace redb.Route.Tests.Sqs;
///
/// W3C trace context through SQS message attributes (and SNS attributes delivered raw to SQS), through the connector
/// against LocalStack. The consumer opens a receive span per message: a child of the sender's context, or a root without
/// one — never a child of the activity the receive loop inherited from whoever started it — with the sender's baggage
/// back on it and the route's spans under it; a failed route, a timeout inside it included, marks it red, our own stop
/// does not. The producers write the context of their own span over a copied one, and refuse a message whose attributes
/// the trace context would push past the limit of ten instead of dropping any. EnableTelemetry=false opens none
/// of these spans, while the ambient context still goes out.
/// Requires LocalStack at http://localhost:4566.
///
[Trait("Category", "Integration")]
public sealed class SqsTracePropagationTests
{
private const string ServiceUrl = "http://localhost:4566";
private const string Region = "us-east-1";
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(20);
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 string Q(string name) =>
SqsDsl.Queue(name).ServiceUrl(ServiceUrl).Region(Region).Credentials("test", "test").AutoCreateQueue().Build();
private static (ActivityTraceId TraceId, ActivitySpanId SpanId, string Header) Caller()
{
var traceId = ActivityTraceId.CreateRandom();
var spanId = ActivitySpanId.CreateRandom();
return (traceId, spanId, $"00-{traceId}-{spanId}-01");
}
private static RouteTelemetryProbe SpansOf(string queue, ActivityKind kind)
=> new(a => a.Kind == kind && RouteTelemetryProbe.Tag(a, "messaging.destination.name") == queue);
/// Sends one message straight through the SDK, as a sender that is not redb would.
private static async Task SendRaw(string queue, IDictionary? attributes = null)
{
using var sqs = RawSqs();
var url = (await sqs.CreateQueueAsync(queue)).QueueUrl;
var request = new SendMessageRequest { QueueUrl = url, MessageBody = "payload", MessageAttributes = [] };
foreach (var (key, value) in attributes ?? new Dictionary())
request.MessageAttributes[key] = new MessageAttributeValue { DataType = "String", StringValue = value };
await sqs.SendMessageAsync(request);
}
/// Receives one message straight through the SDK, attributes included.
private static async Task ReceiveRaw(string queue)
{
using var sqs = RawSqs();
var url = (await sqs.CreateQueueAsync(queue)).QueueUrl;
var deadline = DateTime.UtcNow + Wait;
while (DateTime.UtcNow < deadline)
{
var response = await sqs.ReceiveMessageAsync(new ReceiveMessageRequest
{
QueueUrl = url, WaitTimeSeconds = 2, MaxNumberOfMessages = 1, MessageAttributeNames = ["All"],
});
if (response.Messages is { Count: > 0 } messages)
return messages[0];
}
throw new TimeoutException($"No message arrived on {queue}.");
}
private static async Task Send(string uri, IExchange exchange, bool telemetry = true)
{
await using var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = telemetry });
ctx.AddComponent(new SqsComponent());
ctx.AddComponent(new SnsComponent());
await ctx.Start();
using var template = new ProducerTemplate(ctx);
template.Start();
await template.SendAsync(uri, exchange);
}
/// A context with one consuming route, started inside a host span the receive loop inherits.
private static async Task StartConsumer(string queue, Func step,
bool telemetry = true, TimeSpan? shutdown = null)
{
var options = new RouteEngineOptions { EnableTelemetry = telemetry };
if (shutdown is { } timeout)
options.ShutdownTimeout = timeout;
var ctx = new RouteContext(options: options);
ctx.AddComponent(new SqsComponent());
ctx.AddRoutes(r => r.From(Q(queue)).RouteId($"sqs-{queue}").Process(step));
using (new Activity("host startup").SetIdFormat(ActivityIdFormat.W3C).Start())
await ctx.Start();
return ctx;
}
private static Task StartConsumer(string queue, Action step, bool telemetry = true)
=> StartConsumer(queue, (e, _) => { step(e); return Task.CompletedTask; }, telemetry);
private static async Task Arrived(Task task)
=> (await Task.WhenAny(task, Task.Delay(Wait))).Should().Be(task, "the message should reach the route");
private static async Task SpanEnded(RouteTelemetryProbe probe)
{
var deadline = DateTime.UtcNow + Wait;
while (probe.Activities.Count == 0 && DateTime.UtcNow < deadline)
await Task.Delay(100);
}
[Fact]
public async Task A_message_without_context_opens_a_root_receive_span()
{
var queue = UniqueName("trace-root");
using var probe = SpansOf(queue, ActivityKind.Consumer);
var done = new TaskCompletionSource();
await using (await StartConsumer(queue, _ => done.TrySetResult()))
{
await SendRaw(queue);
await Arrived(done.Task);
}
var receive = probe.Activities.Should().ContainSingle().Subject;
receive.ParentSpanId.Should().Be(default(ActivitySpanId),
"a message that carries no context starts a trace, not a child of the host's startup span");
RouteTelemetryProbe.Tag(receive, RouteTelemetryProbe.EndpointTag).Should().StartWith("sqs:");
}
[Fact]
public async Task A_message_with_context_continues_the_senders_trace_and_the_route_runs_under_it()
{
var queue = UniqueName("trace-child");
using var probe = SpansOf(queue, ActivityKind.Consumer);
using var routes = RouteTelemetryProbe.ForRouteIdPrefix($"sqs-{queue}");
var caller = Caller();
var done = new TaskCompletionSource();
await using (await StartConsumer(queue, _ => done.TrySetResult()))
{
await SendRaw(queue, new Dictionary { ["traceparent"] = caller.Header });
await Arrived(done.Task);
}
var receive = probe.Activities.Should().ContainSingle().Subject;
receive.TraceId.Should().Be(caller.TraceId);
receive.ParentSpanId.Should().Be(caller.SpanId);
routes.Activities.Should().ContainSingle().Which.ParentSpanId.Should().Be(receive.SpanId);
}
[Fact]
public async Task The_senders_baggage_reaches_the_route()
{
var queue = UniqueName("trace-bag");
using var probe = SpansOf(queue, ActivityKind.Consumer);
var seen = new TaskCompletionSource();
await using (await StartConsumer(queue, _ => seen.TrySetResult(Activity.Current?.GetBaggageItem("tenant"))))
{
await SendRaw(queue, new Dictionary { ["traceparent"] = Caller().Header, ["baggage"] = "tenant=t1" });
await Arrived(seen.Task);
}
seen.Task.Result.Should().Be("t1");
}
[Theory]
[InlineData("route failed")]
[InlineData("a call inside the route timed out")]
public async Task A_failed_route_marks_the_receive_span_red(string failure)
{
var queue = UniqueName("trace-fail");
using var probe = SpansOf(queue, ActivityKind.Consumer);
var thrown = new TaskCompletionSource();
await using (await StartConsumer(queue, _ =>
{
thrown.TrySetResult();
throw failure.Contains("timed out")
? new TaskCanceledException(failure)
: new InvalidOperationException(failure);
}))
{
await SendRaw(queue);
await Arrived(thrown.Task);
await SpanEnded(probe);
}
probe.Activities.Should().NotBeEmpty();
probe.Activities[0].Status.Should().Be(ActivityStatusCode.Error);
}
[Fact]
public async Task Stopping_the_consumer_does_not_mark_the_interrupted_message_red()
{
var queue = UniqueName("trace-stop");
using var probe = SpansOf(queue, ActivityKind.Consumer);
var started = new TaskCompletionSource();
var ctx = await StartConsumer(queue, async (_, ct) =>
{
started.TrySetResult();
await Task.Delay(Timeout.Infinite, ct);
}, shutdown: TimeSpan.FromSeconds(2));
await SendRaw(queue);
await Arrived(started.Task);
await ctx.DisposeAsync(); // the drain gives up and cancels the processing token
await SpanEnded(probe);
probe.Activities.Should().NotBeEmpty();
probe.Activities.Should().OnlyContain(a => a.Status != ActivityStatusCode.Error, "our own stop is not a failure");
}
[Fact]
public async Task The_producer_sends_the_context_of_its_own_span_over_a_copied_one()
{
var queue = UniqueName("trace-send");
using var sends = SpansOf(queue, ActivityKind.Producer);
using var outer = new Activity("caller").SetIdFormat(ActivityIdFormat.W3C).Start();
var exchange = new Exchange(new Message("payload"));
// What the header bridge copies from a received message.
exchange.In.Headers[SqsHeaders.MessageAttributePrefix + "traceparent"] = Caller().Header;
await Send(Q(queue), exchange);
var send = sends.Activities.Should().ContainSingle().Subject;
var received = await ReceiveRaw(queue);
received.MessageAttributes["traceparent"].StringValue.Should().Be($"00-{outer.TraceId}-{send.SpanId}-{(int)send.ActivityTraceFlags:x2}");
}
[Fact]
public async Task Tracing_off_opens_no_span_and_still_passes_the_context_on()
{
var queue = UniqueName("trace-off");
using var spans = new RouteTelemetryProbe(a => RouteTelemetryProbe.Tag(a, "messaging.destination.name") == queue);
using (var outer = new Activity("caller").SetIdFormat(ActivityIdFormat.W3C).Start())
{
await Send(Q(queue), new Exchange(new Message("payload")), telemetry: false);
var received = await ReceiveRaw(queue);
received.MessageAttributes["traceparent"].StringValue.Should().Be(outer.Id,
"with no send span the ambient context goes out");
}
var done = new TaskCompletionSource();
await using (await StartConsumer(queue, _ => done.TrySetResult(), telemetry: false))
{
await SendRaw(queue, new Dictionary { ["traceparent"] = Caller().Header });
await Arrived(done.Task);
}
spans.Activities.Should().BeEmpty();
}
[Fact]
public async Task A_message_the_trace_context_pushes_past_ten_attributes_is_refused_not_trimmed()
{
var queue = UniqueName("trace-limit");
using var outer = new Activity("caller").SetIdFormat(ActivityIdFormat.W3C).Start();
var exchange = new Exchange(new Message("payload"));
for (var i = 0; i < 10; i++)
exchange.In.Headers[$"h{i}"] = "v";
var act = () => Send(Q(queue), exchange);
(await act.Should().ThrowAsync())
.Which.Message.Should().Contain("10 from the exchange headers").And.Contain("trace context");
}
// ── SNS ──
private static async Task SubscribedTopic(string queue, string topic)
{
using var sqs = RawSqs();
var url = (await sqs.CreateQueueAsync(queue)).QueueUrl;
var arn = (await sqs.GetQueueAttributesAsync(new GetQueueAttributesRequest
{
QueueUrl = url, AttributeNames = ["QueueArn"],
})).Attributes["QueueArn"];
return SnsDsl.Topic(topic).ServiceUrl(ServiceUrl).Region(Region).Credentials("test", "test")
.AutoCreateTopic().SubscribeSnsToSqs(arn).RawMessageDelivery().Build();
}
[Fact]
public async Task Sns_tracing_off_opens_no_span_and_still_passes_the_context_on()
{
var queue = UniqueName("sns-off-q");
var topic = UniqueName("sns-off");
var snsUri = await SubscribedTopic(queue, topic);
using var spans = new RouteTelemetryProbe(a => RouteTelemetryProbe.Tag(a, "messaging.destination.name") == topic);
using var outer = new Activity("caller").SetIdFormat(ActivityIdFormat.W3C).Start();
await Send(snsUri, new Exchange(new Message("payload")), telemetry: false);
var received = await ReceiveRaw(queue);
received.MessageAttributes["traceparent"].StringValue.Should().Be(outer.Id);
spans.Activities.Should().BeEmpty();
}
[Fact]
public async Task Sns_a_message_the_trace_context_pushes_past_ten_attributes_is_refused_not_trimmed()
{
var topic = UniqueName("sns-limit");
var snsUri = await SubscribedTopic(UniqueName("sns-limit-q"), topic);
using var outer = new Activity("caller").SetIdFormat(ActivityIdFormat.W3C).Start();
var exchange = new Exchange(new Message("payload"));
for (var i = 0; i < 10; i++)
exchange.In.Headers[$"h{i}"] = "v";
var act = () => Send(snsUri, exchange);
(await act.Should().ThrowAsync())
.Which.Message.Should().Contain("10 from the exchange headers").And.Contain("trace context");
}
}
Path: redb-route/tests/redb.Route.Tests.Sqs/SqsTransactedSendTests.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/SqsTransactedSendTests.cs
----
using Amazon.Runtime;
using Amazon.SQS;
using Amazon.SQS.Model;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Processors;
using redb.Route.Sqs;
using redb.Route.Transactions;
using Message = redb.Route.Core.Message;
using SnsDsl = redb.Route.Sqs.Fluent.Sns;
using SqsDsl = redb.Route.Sqs.Fluent.Sqs;
namespace redb.Route.Tests.Sqs;
///
/// SQS sends and SNS publishes inside .Transacted() : unset, they join the block and leave only after the database
/// commits; transacted=false sends at once; transacted=true outside a block is refused.
///
[Trait("Category", "Integration")]
public sealed class SqsTransactedSendTests
{
private const string ServiceUrl = "http://localhost:4566";
private const string Region = "us-east-1";
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 IProducer SqsProducer(string queue, bool? transacted) => SqsEndpoint(queue, transacted).CreateProducer();
private static IEndpoint SqsEndpoint(string queue, bool? transacted)
{
var builder = SqsDsl.Queue(queue).ServiceUrl(ServiceUrl).Region(Region).Credentials("test", "test").AutoCreateQueue();
if (transacted is { } value) builder = builder.Transacted(value);
return new SqsComponent().CreateEndpoint(EndpointUriParser.Parse(builder.Build()));
}
private static Task InTransaction(IExchange exchange, Func body) =>
new TransactedProcessor(new DelegateProcessor(body), new TransactionPolicy()).Process(exchange);
private static async Task SendFromAFailedBlock(IProducer producer, string body)
{
await producer.Start();
var failed = () => InTransaction(new Exchange(new Message(body)), async (ex, ct) =>
{
await producer.Process(ex, ct);
throw new InvalidOperationException("the unit of work failed");
});
await failed.Should().ThrowAsync();
await producer.Stop();
}
private static async Task> ReceiveAll(IAmazonSQS sqs, string queueUrl)
{
var response = await sqs.ReceiveMessageAsync(new ReceiveMessageRequest
{
QueueUrl = queueUrl,
MaxNumberOfMessages = 10,
WaitTimeSeconds = 3,
});
return (response.Messages ?? []).Select(m => m.Body).ToList();
}
[Fact]
public async Task Sqs_send_without_transacted_joins_the_block_and_leaves_nothing_when_it_fails()
{
var queue = UniqueName("tx-join");
using var sqs = RawSqs();
var queueUrl = (await sqs.CreateQueueAsync(queue)).QueueUrl;
await SendFromAFailedBlock(SqsProducer(queue, transacted: null), "sent-from-a-failed-block");
(await ReceiveAll(sqs, queueUrl)).Should().BeEmpty(
"inside .Transacted() a send joins the transaction unless transacted=false opts out");
}
[Fact]
public async Task Sqs_send_with_transacted_false_goes_out_at_once_even_from_a_failed_block()
{
var queue = UniqueName("tx-optout");
using var sqs = RawSqs();
var queueUrl = (await sqs.CreateQueueAsync(queue)).QueueUrl;
await SendFromAFailedBlock(SqsProducer(queue, transacted: false), "sent-from-a-failed-block");
(await ReceiveAll(sqs, queueUrl)).Should().Equal("sent-from-a-failed-block");
}
[Fact]
public async Task Sqs_send_inside_a_block_goes_out_after_the_commit()
{
var queue = UniqueName("tx-commit");
using var sqs = RawSqs();
var queueUrl = (await sqs.CreateQueueAsync(queue)).QueueUrl;
var endpoint = SqsEndpoint(queue, transacted: null);
var producer = endpoint.CreateProducer();
await producer.Start();
List? insideTheBlock = null;
long bytesOutInsideTheBlock = -1;
await InTransaction(new Exchange(new Message("committed")), async (ex, ct) =>
{
await producer.Process(ex, ct);
insideTheBlock = await ReceiveAll(sqs, queueUrl);
bytesOutInsideTheBlock = ((IEndpointStatistics)endpoint).BytesOut;
});
insideTheBlock.Should().BeEmpty("nothing leaves before the database has committed");
bytesOutInsideTheBlock.Should().Be(0, "a deferred send counts when it goes out, after the commit");
((IEndpointStatistics)endpoint).BytesOut.Should().Be(9, "the committed send counts its UTF-8 body");
(await ReceiveAll(sqs, queueUrl)).Should().Equal("committed");
await producer.Stop();
}
[Fact]
public async Task Sqs_send_with_transacted_true_outside_a_block_is_refused()
{
var producer = SqsProducer(UniqueName("tx-none"), transacted: true);
await producer.Start();
var act = () => producer.Process(new Exchange(new Message("nobody would commit this")));
await act.Should().ThrowAsync().WithMessage("*Transacted()*");
await producer.Stop();
}
[Fact]
public async Task Sns_publish_without_transacted_joins_the_block_and_leaves_nothing_when_it_fails()
{
var (sqs, queueUrl, producer, _) = await SnsSubscribedToAQueue(transacted: null);
using (sqs)
{
await SendFromAFailedBlock(producer, "published-from-a-failed-block");
(await ReceiveAll(sqs, queueUrl)).Should().BeEmpty(
"inside .Transacted() a publish joins the transaction unless transacted=false opts out");
}
}
[Fact]
public async Task Sns_publish_with_transacted_false_goes_out_at_once_even_from_a_failed_block()
{
var (sqs, queueUrl, producer, endpoint) = await SnsSubscribedToAQueue(transacted: false);
using (sqs)
{
await SendFromAFailedBlock(producer, "published-from-a-failed-block");
(await ReceiveAll(sqs, queueUrl)).Should().ContainSingle().Which.Should().Be("published-from-a-failed-block");
((IEndpointStatistics)endpoint).BytesOut.Should().Be(29, "a publish that went out at once counts its UTF-8 body");
}
}
[Fact]
public async Task Sqs_consumer_does_not_delete_a_rolled_back_unit_of_work()
{
var queue = UniqueName("tx-rbonly");
using var sqs = RawSqs();
var queueUrl = (await sqs.CreateQueueAsync(queue)).QueueUrl;
await sqs.SendMessageAsync(queueUrl, "rolled-back");
// What .RollbackAll() does inside .Transacted(): mark the unit of work rollback-only and stop the route.
var deliveries = 0;
var deliveredAgain = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var route = new TransactedProcessor(new DelegateProcessor(ex =>
{
if (Interlocked.Increment(ref deliveries) >= 2) deliveredAgain.TrySetResult();
ex.MarkRollbackOnly();
ex.Stop();
}), new TransactionPolicy());
var builder = SqsDsl.Queue(queue).ServiceUrl(ServiceUrl).Region(Region).Credentials("test", "test")
.WaitTimeSeconds(1).ResetVisibilityOnFailure();
var consumer = new SqsComponent().CreateEndpoint(EndpointUriParser.Parse(builder.Build())).CreateConsumer(route);
await consumer.Start();
await Task.WhenAny(deliveredAgain.Task, Task.Delay(15_000));
await consumer.Stop();
deliveries.Should().BeGreaterThanOrEqualTo(2,
"a rolled-back unit of work is not deleted, so the queue delivers the message again");
}
private static async Task<(IAmazonSQS Sqs, string QueueUrl, IProducer Producer, IEndpoint Endpoint)> SnsSubscribedToAQueue(bool? transacted)
{
var sqs = RawSqs();
var queueUrl = (await sqs.CreateQueueAsync(UniqueName("snsq"))).QueueUrl;
var arn = (await sqs.GetQueueAttributesAsync(new GetQueueAttributesRequest
{
QueueUrl = queueUrl,
AttributeNames = ["QueueArn"],
})).Attributes["QueueArn"];
var builder = SnsDsl.Topic(UniqueName("evt"))
.ServiceUrl(ServiceUrl).Region(Region).Credentials("test", "test")
.AutoCreateTopic().SubscribeSnsToSqs(arn).RawMessageDelivery();
if (transacted is { } value) builder = builder.Transacted(value);
var endpoint = new SnsComponent().CreateEndpoint(EndpointUriParser.Parse(builder.Build()));
var producer = endpoint.CreateProducer();
return (sqs, queueUrl, producer, endpoint);
}
}
Path: redb-route/tests/redb.Route.Tests.Sqs/SqsUnitTests.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/SqsUnitTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Sqs;
using SqsDsl = redb.Route.Sqs.Fluent.Sqs;
using SnsDsl = redb.Route.Sqs.Fluent.Sns;
namespace redb.Route.Tests.Sqs;
///
/// Unit tests for the SQS/SNS connector — no broker required. Cover URI→options binding, validation,
/// FIFO detection, component scheme + endpoint creation, the fluent DSL, and header helpers.
///
public class SqsUnitTests
{
private static SqsEndpointOptions BindSqs(string query)
{
var uri = EndpointUriParser.Parse($"sqs://q?{query}");
var options = new SqsEndpointOptions();
options.BindFromUri(uri.RawParameters);
return options;
}
// ── Options binding ───────────────────────────────────────────────
[Fact]
public void Options_BindAllConsumerParams()
{
var o = BindSqs("accessKey=k&secretKey=s®ion=eu-west-1&serviceUrl=http://localhost:4566"
+ "&waitTimeSeconds=15&maxNumberOfMessages=5&visibilityTimeout=45&concurrentConsumers=4"
+ "&extendMessageVisibility=true&transacted=true&autoCreateQueue=true");
o.AccessKey.Should().Be("k");
o.SecretKey.Should().Be("s");
o.Region.Should().Be("eu-west-1");
o.ServiceUrl.Should().Be("http://localhost:4566");
o.WaitTimeSeconds.Should().Be(15);
o.MaxNumberOfMessages.Should().Be(5);
o.VisibilityTimeout.Should().Be(45);
o.ResolvedConcurrentConsumers.Should().Be(4);
o.ExtendMessageVisibility.Should().BeTrue();
o.AckMode.Should().Be(AckMode.Manual);
o.Transacted.Should().BeTrue();
o.AutoCreateQueue.Should().BeTrue();
}
[Fact]
public void Options_Defaults()
{
var o = BindSqs("accessKey=k&secretKey=s");
o.WaitTimeSeconds.Should().Be(20);
o.MaxNumberOfMessages.Should().Be(10);
o.ResolvedConcurrentConsumers.Should().Be(1);
o.AckMode.Should().Be(AckMode.Manual);
o.Region.Should().Be("us-east-1");
}
[Theory]
[InlineData("accessKey=k&secretKey=s&waitTimeSeconds=21")]
[InlineData("accessKey=k&secretKey=s&maxNumberOfMessages=11")]
[InlineData("accessKey=k&secretKey=s&maxNumberOfMessages=0")]
[InlineData("accessKey=k&secretKey=s&concurrentConsumers=0")]
[InlineData("accessKey=k&secretKey=s&extendMessageVisibility=true")] // requires visibilityTimeout>0
[InlineData("accessKey=k&secretKey=s&delaySeconds=901")]
public void Validate_RejectsBadValues(string query)
{
var act = () => BindSqs(query).Validate();
act.Should().Throw();
}
[Fact]
public void Validate_RejectsMissingCredentials()
{
var act = () => BindSqs("region=us-east-1").Validate();
act.Should().Throw().WithMessage("*credentials*");
}
[Theory]
[InlineData("accessKey=k&secretKey=s")]
[InlineData("useDefaultCredentialsProvider=true")]
[InlineData("profileName=dev")]
public void Validate_AcceptsValidCredentialModes(string query)
{
var act = () => BindSqs(query).Validate();
act.Should().NotThrow();
}
// ── FIFO detection ────────────────────────────────────────────────
[Theory]
[InlineData("orders.fifo", true)]
[InlineData("orders", false)]
public void Sqs_FifoDetectedFromQueueName(string name, bool expected)
{
var endpoint = (SqsEndpoint)new SqsComponent()
.CreateEndpoint(EndpointUriParser.Parse($"sqs://{name}?accessKey=k&secretKey=s"));
endpoint.IsFifo.Should().Be(expected);
endpoint.QueueName.Should().Be(name);
}
// ── Component + endpoint ──────────────────────────────────────────
[Fact]
public void SqsComponent_SchemeAndEndpoint()
{
var component = new SqsComponent();
component.Scheme.Should().Be("sqs");
var endpoint = component.CreateEndpoint(EndpointUriParser.Parse("sqs://q?accessKey=k&secretKey=s"));
endpoint.Should().BeOfType();
endpoint.CreateProducer().Should().BeAssignableTo();
endpoint.CreateConsumer(Substitute.For()).Should().BeAssignableTo();
}
[Fact]
public void SnsComponent_SchemeAndPublishOnly()
{
var component = new SnsComponent();
component.Scheme.Should().Be("sns");
var endpoint = (SnsEndpoint)component.CreateEndpoint(EndpointUriParser.Parse("sns://t?accessKey=k&secretKey=s"));
endpoint.TopicName.Should().Be("t");
endpoint.CreateProducer().Should().BeAssignableTo();
var act = () => endpoint.CreateConsumer(Substitute.For());
act.Should().Throw().WithMessage("*publish-only*");
}
[Fact]
public void Sns_ValidateRequiresQueueArnForSubscription()
{
var uri = EndpointUriParser.Parse("sns://t?accessKey=k&secretKey=s&subscribeSnsToSqs=true");
var options = new SnsEndpointOptions();
options.BindFromUri(uri.RawParameters);
var act = () => options.Validate();
act.Should().Throw().WithMessage("*subscribeQueueArn*");
}
// ── Fluent DSL ────────────────────────────────────────────────────
[Fact]
public void SqsDsl_EmitsUri()
{
string uri = SqsDsl.Queue("orders").Region("eu-west-1").WaitTimeSeconds(20).ConcurrentConsumers(4);
uri.Should().StartWith("sqs://orders?");
uri.Should().Contain("region=eu-west-1");
uri.Should().Contain("waitTimeSeconds=20");
uri.Should().Contain("concurrentConsumers=4");
}
[Fact]
public void SnsDsl_EmitsUri_AndSubscribeSetsBothParams()
{
string uri = SnsDsl.Topic("events").Region("us-east-1").SubscribeSnsToSqs("arn:aws:sqs:us-east-1:0:q");
uri.Should().StartWith("sns://events?");
uri.Should().Contain("subscribeSnsToSqs=true");
uri.Should().Contain("subscribeQueueArn=");
}
[Fact]
public void Dsl_RoundTripsThroughOptions()
{
string uri = SqsDsl.Queue("orders").Credentials("k", "s").MaxNumberOfMessages(7);
var parsed = EndpointUriParser.Parse(uri);
var options = new SqsEndpointOptions();
options.BindFromUri(parsed.RawParameters);
options.MaxNumberOfMessages.Should().Be(7);
}
// ── Headers ───────────────────────────────────────────────────────
[Fact]
public void Headers_PrefixAndGuard()
{
SqsHeaders.MessageId.Should().StartWith("redbSqs.");
SqsHeaders.IsSqsHeader(SqsHeaders.ReceiptHandle).Should().BeTrue();
SqsHeaders.IsSqsHeader("customHeader").Should().BeFalse();
SnsHeaders.TopicArn.Should().StartWith("redbSns.");
SnsHeaders.IsSnsHeader(SnsHeaders.MessageId).Should().BeTrue();
SnsHeaders.IsSnsHeader("customHeader").Should().BeFalse();
}
}
Path: redb-route/tests/redb.Route.Tests.Sqs/redb.Route.Tests.Sqs.csproj
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/redb.Route.Tests.Sqs.csproj
----