Bundle: redb-route / redb.Route.Sqs (redb.Route.Sqs.txt), 20 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/redb.Route.Sqs/AwsClientSupport.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/redb.Route.Sqs/AwsClientSupport.cs
----
using System.Text;
using System.Text.Json;
using Amazon;
using Amazon.Runtime;
namespace redb.Route.Sqs;
///
/// Shared AWS client plumbing for the SQS and SNS endpoints: credential resolution and the common
/// settings (region vs explicit service URL, timeouts, retries, proxy).
/// Mirrors redb.Route.S3 so behaviour is identical across the AWS connectors.
///
internal static class AwsClientSupport
{
///
/// The region and service URL a built client talks to, for the "client created" log: read from the client's own
/// configuration, so a connection factory's values show, not the endpoint's defaults.
///
internal static (string Region, string ServiceUrl) Target(IClientConfig config) => (
config.RegionEndpoint?.SystemName ?? (string.IsNullOrEmpty(config.AuthenticationRegion) ? "(default)" : config.AuthenticationRegion),
string.IsNullOrEmpty(config.ServiceURL) ? "(default)" : redb.Route.Abstractions.EndpointUri.Sanitize(config.ServiceURL));
///
/// Resolves AWS credentials with the same precedence as the S3 connector:
/// default provider chain → named profile → static session token → static access/secret keys.
///
public static AWSCredentials ResolveCredentials(AwsEndpointOptions o)
{
if (o.UseDefaultCredentialsProvider)
// SDK v4: the non-deprecated default-chain resolver (env -> profile -> IMDS etc.)
return Amazon.Runtime.Credentials.DefaultAWSCredentialsIdentityResolver.GetCredentials();
if (!string.IsNullOrEmpty(o.ProfileName))
{
var chain = new Amazon.Runtime.CredentialManagement.CredentialProfileStoreChain();
if (chain.TryGetAWSCredentials(o.ProfileName, out var profileCreds))
return profileCreds;
throw new InvalidOperationException($"AWS profile '{o.ProfileName}' not found.");
}
if (!string.IsNullOrEmpty(o.SessionToken))
return new SessionAWSCredentials(o.AccessKey, o.SecretKey, o.SessionToken);
return new BasicAWSCredentials(o.AccessKey, o.SecretKey);
}
///
/// Applies region / explicit service URL, timeout, retry and proxy settings onto an AWS service
/// config. ServiceUrl and RegionEndpoint are mutually exclusive — an explicit URL
/// (LocalStack / ElasticMQ) wins and the region is kept only for request signing.
///
public static void ApplyCommonConfig(ClientConfig config, AwsEndpointOptions o)
{
config.Timeout = TimeSpan.FromMilliseconds(o.ConnectionTimeout);
config.MaxErrorRetry = o.RetryCount;
if (!string.IsNullOrEmpty(o.ServiceUrl))
{
config.ServiceURL = o.ServiceUrl;
config.AuthenticationRegion = o.Region;
}
else
{
config.RegionEndpoint = RegionEndpoint.GetBySystemName(o.Region);
}
if (!string.IsNullOrEmpty(o.ProxyHost) && o.ProxyPort > 0)
{
config.ProxyHost = o.ProxyHost;
config.ProxyPort = o.ProxyPort;
}
}
///
/// Maps an exchange header to the message-attribute name a producer should send, or null to
/// skip it. User headers pass through unchanged; a received SQS attribute (re-exposed under
/// redbSqs.attr.) is forwarded with the prefix stripped (so sqs→sqs/sns bridges preserve
/// attributes); framework headers (redbSqs.* / redbSns.*) are dropped.
///
/// The most message attributes SQS and SNS accept on one message.
public const int MaxMessageAttributes = 10;
///
/// Fails the send when the message carries more attributes than SQS/SNS accept, naming how many came from the
/// exchange headers and how many from the trace context, instead of letting the service refuse it with a bare count.
/// Nothing is dropped to make it fit: which attribute to lose is not the connector's call.
///
/// Attributes on the message, trace context included.
/// Attributes mapped from the exchange headers.
/// The producer, for the message.
public static void EnsureAttributeLimit(int total, int fromHeaders, string producer)
{
if (total <= MaxMessageAttributes)
return;
throw new InvalidOperationException(
$"'{producer}' would send {total} message attributes, at most {MaxMessageAttributes} are accepted: " +
$"{fromHeaders} from the exchange headers and {total - fromHeaders} for the trace context " +
"(traceparent, tracestate, baggage). Nothing was sent. Remove the headers the next hop does not need " +
"before this step (.RemoveHeaders(...)).");
}
public static string? MapHeaderToAttributeName(string key)
{
if (key.StartsWith(SqsHeaders.MessageAttributePrefix, StringComparison.Ordinal))
return key[SqsHeaders.MessageAttributePrefix.Length..];
if (SqsHeaders.IsSqsHeader(key) || SnsHeaders.IsSnsHeader(key))
return null;
return key;
}
///
/// Coerces an exchange body to the text payload SQS/SNS carry: strings pass through, byte[]
/// is decoded as UTF-8, everything else is JSON-serialized.
///
public static string ResolveTextBody(object? body) => body switch
{
null => "",
string s => s,
byte[] bytes => Encoding.UTF8.GetString(bytes),
_ => JsonSerializer.Serialize(body),
};
}
Path: redb-route/redb.Route.Sqs/AwsConnectionFactory.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/redb.Route.Sqs/AwsConnectionFactory.cs
----
using Amazon.Runtime;
using Amazon.SimpleNotificationService;
using Amazon.SQS;
namespace redb.Route.Sqs;
///
/// Reusable AWS credentials/endpoint holder that can be pre-registered in the route registry and
/// referenced from a URI via connectionFactory=name (mirrors redb.Route.S3). One factory
/// builds both SQS and SNS clients since they share credentials, region and service URL.
///
public sealed class AwsConnectionFactory : AwsEndpointOptions
{
///
/// No endpoint-shape validation for a bare factory — only credential resolution matters.
public override void Validate() => ValidateAws();
/// Builds a configured client.
public IAmazonSQS BuildSqs()
{
var config = new AmazonSQSConfig();
AwsClientSupport.ApplyCommonConfig(config, this);
return new AmazonSQSClient(AwsClientSupport.ResolveCredentials(this), config);
}
/// Builds a configured client.
public IAmazonSimpleNotificationService BuildSns()
{
var config = new AmazonSimpleNotificationServiceConfig();
AwsClientSupport.ApplyCommonConfig(config, this);
return new AmazonSimpleNotificationServiceClient(AwsClientSupport.ResolveCredentials(this), config);
}
}
Path: redb-route/redb.Route.Sqs/AwsEndpointOptions.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/redb.Route.Sqs/AwsEndpointOptions.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.Sqs;
///
/// Base endpoint options shared by the SQS and SNS endpoints — AWS connection/credentials.
/// Bound from the URI query string by (reflection includes
/// these inherited properties). Credentials resolution mirrors redb.Route.S3.
///
public abstract class AwsEndpointOptions : EndpointOptions
{
///
/// Explicit service endpoint URL (e.g. http://localhost:4566 for LocalStack / ElasticMQ).
/// When set, it overrides the region endpoint. Empty = use the AWS region endpoint.
///
public string ServiceUrl { get; set; } = "";
/// AWS region (e.g. us-east-1, eu-west-1). Default us-east-1.
public string Region { get; set; } = "us-east-1";
///
/// A registry reference (#name) to an that
/// decides which headers this endpoint carries between the exchange and message attributes, in place of
/// (SQS) or (SNS).
///
[RegistryReference(typeof(IHeaderFilterStrategy))]
public string? HeaderFilterStrategy { get; set; }
/// AWS access key ID. Required unless or is used.
[Sensitive]
public string AccessKey { get; set; } = "";
/// AWS secret access key.
[Sensitive]
public string SecretKey { get; set; } = "";
/// AWS session token for temporary (STS) credentials.
[Sensitive]
public string SessionToken { get; set; } = "";
/// Named AWS profile from the shared credentials file. Overrides access/secret keys when set.
public string ProfileName { get; set; } = "";
/// Use the default AWS credential provider chain (env vars / instance profile / SSO). Default false.
public bool UseDefaultCredentialsProvider { get; set; }
/// Name of a pre-registered connection factory in the route registry (overrides URI credentials when found).
[RegistryReference(typeof(AwsConnectionFactory))]
public string ConnectionFactory { get; set; } = "";
/// Maximum SDK retry attempts on transient errors. Default 3.
public int RetryCount { get; set; } = 3;
/// HTTP client timeout in milliseconds. Default 30000.
public int ConnectionTimeout { get; set; } = 30000;
/// Optional HTTP proxy host.
public string ProxyHost { get; set; } = "";
/// Optional HTTP proxy port.
public int ProxyPort { get; set; }
/// Validates the shared AWS options. Concrete option classes call this from .
protected void ValidateAws()
{
var haveStaticKeys = !string.IsNullOrEmpty(AccessKey) && !string.IsNullOrEmpty(SecretKey);
if (!UseDefaultCredentialsProvider
&& string.IsNullOrEmpty(ProfileName)
&& string.IsNullOrEmpty(ConnectionFactory)
&& !haveStaticKeys)
{
throw new ArgumentException(
"AWS credentials required: set accessKey+secretKey, or profileName, or useDefaultCredentialsProvider=true, "
+ "or a registered connectionFactory.");
}
if (RetryCount < 0)
throw new ArgumentException($"retryCount cannot be negative. Got: {RetryCount}");
if (ConnectionTimeout <= 0)
throw new ArgumentException($"connectionTimeout must be positive. Got: {ConnectionTimeout}");
}
}
Path: redb-route/redb.Route.Sqs/Extensions/ServiceCollectionExtensions.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/redb.Route.Sqs/Extensions/ServiceCollectionExtensions.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Extensions;
namespace redb.Route.Sqs;
///
/// Extension methods for registering the Amazon SQS + SNS transport in a DI container.
///
public static class ServiceCollectionExtensions
{
///
/// Registers the (sqs://) and
/// (sns://) in the route context.
///
///
/// services.AddRedbRoute(route =>
/// {
/// route.Services.AddRedbRouteSqs();
/// route.AddRouteBuilder<MyRoutes>();
/// });
///
///
///
public static IServiceCollection AddRedbRouteSqs(this IServiceCollection services)
{
services.AddSingleton();
services.AddSingleton();
// IRouteContextConfigurator is applied by RouteHostedService at startup --
// the correct registration hook (a lazy marker singleton never fires).
services.AddRouteContextConfigurator((sp, context) =>
{
context.AddComponent(sp.GetRequiredService());
context.AddComponent(sp.GetRequiredService());
});
return services;
}
}
Path: redb-route/redb.Route.Sqs/Fluent/AwsDsl.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/redb.Route.Sqs/Fluent/AwsDsl.cs
----
using redb.Route.Core;
namespace redb.Route.Sqs.Fluent;
///
/// Fluent URI builder entry point for Amazon SQS queues. Produces a sqs://queue-name?... URI
/// that drops straight into .From(...) / .To(...).
///
/// From(Sqs.Queue("orders").WaitTimeSeconds(20).ConcurrentConsumers(4))
/// .Process(...);
/// To(Sqs.Queue("orders").Region("eu-west-1"));
///
///
public static class Sqs
{
/// Starts an SQS endpoint builder for the given queue name (use the .fifo suffix for FIFO queues).
public static SqsBuilder Queue(string name) => new(name);
}
/// Fluent builder for an sqs:// endpoint URI.
public sealed class SqsBuilder
{
private readonly string _name;
private readonly Dictionary _params = new(StringComparer.Ordinal);
internal SqsBuilder(string name) => _name = name;
private SqsBuilder Set(string key, string value) { _params[key] = value; return this; }
// ── Connection / credentials ──
/// AWS region (e.g. us-east-1).
public SqsBuilder Region(string region) => Set("region", region);
/// Explicit service URL (LocalStack / ElasticMQ).
public SqsBuilder ServiceUrl(string url) => Set("serviceUrl", url);
/// Static access + secret keys.
public SqsBuilder Credentials(string accessKey, string secretKey) => Set("accessKey", accessKey).Set("secretKey", secretKey);
/// Session token for temporary (STS) credentials.
public SqsBuilder SessionToken(string token) => Set("sessionToken", token);
/// Named AWS profile.
public SqsBuilder Profile(string profileName) => Set("profileName", profileName);
/// Use the default AWS credential provider chain.
public SqsBuilder UseDefaultCredentials(bool value = true) => Set("useDefaultCredentialsProvider", value ? "true" : "false");
/// Reference a pre-registered connection factory by name.
public SqsBuilder ConnectionFactory(string name) => Set("connectionFactory", name);
/// Create the queue if it does not exist.
public SqsBuilder AutoCreateQueue(bool value = true) => Set("autoCreateQueue", value ? "true" : "false");
// ── Consumer ──
/// Long-poll wait time in seconds (0–20).
public SqsBuilder WaitTimeSeconds(int seconds) => Set("waitTimeSeconds", seconds.ToString());
/// Messages fetched per receive (1–10).
public SqsBuilder MaxNumberOfMessages(int count) => Set("maxNumberOfMessages", count.ToString());
/// Visibility timeout in seconds.
public SqsBuilder VisibilityTimeout(int seconds) => Set("visibilityTimeout", seconds.ToString());
/// Number of concurrent receive loops.
public SqsBuilder ConcurrentConsumers(int count) => Set("concurrentConsumers", count.ToString());
/// Consumer parallelism as a string: a number or "auto" (= max(CPU, 2)).
public SqsBuilder ConcurrentConsumers(string count) => Set("concurrentConsumers", count);
/// Keep extending visibility while a message is processing (requires visibilityTimeout > 0).
public SqsBuilder ExtendMessageVisibility(bool value = true) => Set("extendMessageVisibility", value ? "true" : "false");
/// When a message is deleted: after the route (, default) or on receipt ().
public SqsBuilder AckMode(AckMode mode) => Set("ackMode", mode.ToString().ToLowerInvariant());
/// Reset visibility to 0 on failure for immediate redelivery.
public SqsBuilder ResetVisibilityOnFailure(bool value = true) => Set("resetVisibilityOnFailure", value ? "true" : "false");
/// Batch mode: the route gets a List<IMessage> of up to maxBatchMessages messages, deleted once after the route.
public SqsBuilder Batching(bool value = true) => Set("batching", value ? "true" : "false");
/// Batch mode: largest number of messages in a batch (default 10).
public SqsBuilder MaxBatchMessages(int count) => Set("maxBatchMessages", count.ToString());
/// Batch mode: a batch is sent on once no message came for this many milliseconds (default 1000).
public SqsBuilder PollTimeoutMs(int ms) => Set("pollTimeoutMs", ms.ToString());
/// Batch mode: a batch is sent on once this many milliseconds have passed since its first message.
public SqsBuilder BatchingIntervalMs(int ms) => Set("batchingIntervalMs", ms.ToString());
///
/// Sets transacted for a producer: true requires an enclosing .Transacted() block,
/// false sends at once even inside one; left unset, the producer follows the block.
///
public SqsBuilder Transacted(bool value = true) => Set("transacted", value ? "true" : "false");
// ── Producer ──
/// Delivery delay in seconds (0–900).
public SqsBuilder DelaySeconds(int seconds) => Set("delaySeconds", seconds.ToString());
/// FIFO message group id (constant or ${...} expression).
public SqsBuilder MessageGroupId(string value) => Set("messageGroupId", value);
/// FIFO deduplication id (constant or ${...} expression).
public SqsBuilder MessageDeduplicationId(string value) => Set("messageDeduplicationId", value);
/// Sets an arbitrary URI parameter not covered by a typed method.
public SqsBuilder Param(string key, string value) => Set(key, value);
/// Builds the sqs:// URI.
public string Build()
{
var qs = string.Join("&", _params.Select(kv => $"{kv.Key}={Uri.EscapeDataString(kv.Value)}"));
return qs.Length > 0 ? $"sqs://{_name}?{qs}" : $"sqs://{_name}";
}
///
public override string ToString() => Build();
/// Implicit conversion to the URI string.
public static implicit operator string(SqsBuilder builder) => builder.Build();
}
///
/// Fluent URI builder entry point for Amazon SNS topics. Produces a sns://topic-name?... URI.
/// SNS is publish-only.
///
/// To(Sns.Topic("events").Region("us-east-1"));
///
///
public static class Sns
{
/// Starts an SNS endpoint builder for the given topic name (use the .fifo suffix for FIFO topics).
public static SnsBuilder Topic(string name) => new(name);
}
/// Fluent builder for an sns:// endpoint URI.
public sealed class SnsBuilder
{
private readonly string _name;
private readonly Dictionary _params = new(StringComparer.Ordinal);
internal SnsBuilder(string name) => _name = name;
private SnsBuilder Set(string key, string value) { _params[key] = value; return this; }
/// AWS region (e.g. us-east-1).
public SnsBuilder Region(string region) => Set("region", region);
/// Explicit service URL (LocalStack).
public SnsBuilder ServiceUrl(string url) => Set("serviceUrl", url);
/// Static access + secret keys.
public SnsBuilder Credentials(string accessKey, string secretKey) => Set("accessKey", accessKey).Set("secretKey", secretKey);
/// Named AWS profile.
public SnsBuilder Profile(string profileName) => Set("profileName", profileName);
/// Use the default AWS credential provider chain.
public SnsBuilder UseDefaultCredentials(bool value = true) => Set("useDefaultCredentialsProvider", value ? "true" : "false");
/// Reference a pre-registered connection factory by name.
public SnsBuilder ConnectionFactory(string name) => Set("connectionFactory", name);
/// Explicit topic ARN (skips name resolution).
public SnsBuilder TopicArn(string arn) => Set("topicArn", arn);
/// Create the topic if it does not exist.
public SnsBuilder AutoCreateTopic(bool value = true) => Set("autoCreateTopic", value ? "true" : "false");
/// Message subject (email delivery; constant or ${...}).
public SnsBuilder Subject(string subject) => Set("subject", subject);
/// Message structure (json for per-protocol payloads).
public SnsBuilder MessageStructure(string structure) => Set("messageStructure", structure);
/// FIFO message group id.
public SnsBuilder MessageGroupId(string value) => Set("messageGroupId", value);
/// FIFO deduplication id.
public SnsBuilder MessageDeduplicationId(string value) => Set("messageDeduplicationId", value);
/// Subscribe the given SQS queue ARN to this topic at start.
public SnsBuilder SubscribeSnsToSqs(string queueArn) => Set("subscribeSnsToSqs", "true").Set("subscribeQueueArn", queueArn);
///
/// On the auto-created SNS→SQS subscription, enable raw message delivery — the queue receives the
/// bare payload (and SNS attributes map to SQS attributes) instead of the JSON notification envelope.
///
public SnsBuilder RawMessageDelivery(bool value = true) => Set("rawMessageDelivery", value ? "true" : "false");
///
/// Sets transacted: true requires an enclosing .Transacted() block, false publishes at
/// once even inside one; left unset, the publish follows the block.
///
public SnsBuilder Transacted(bool value = true) => Set("transacted", value ? "true" : "false");
/// Sets an arbitrary URI parameter not covered by a typed method.
public SnsBuilder Param(string key, string value) => Set(key, value);
/// Builds the sns:// URI.
public string Build()
{
var qs = string.Join("&", _params.Select(kv => $"{kv.Key}={Uri.EscapeDataString(kv.Value)}"));
return qs.Length > 0 ? $"sns://{_name}?{qs}" : $"sns://{_name}";
}
///
public override string ToString() => Build();
/// Implicit conversion to the URI string.
public static implicit operator string(SnsBuilder builder) => builder.Build();
}
Path: redb-route/redb.Route.Sqs/README.md
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/redb.Route.Sqs/README.md
----
# redb.Route.Sqs
Amazon **SQS** + **SNS** transport for [redb.Route](https://github.com/redbase-app/redb), via the native
**AWS SDK for .NET v4** (`AWSSDK.SQS`, `AWSSDK.SimpleNotificationService`). One package, two schemes —
`sqs://` (queue: consume + produce) and `sns://` (topic: publish + SNS→SQS fan-out). LocalStack /
ElasticMQ compatible.
## Installation
```bash
dotnet add package redb.Route.Sqs
```
```csharp
services.AddRedbRoute(route =>
{
route.Services.AddRedbRouteSqs(); // registers sqs:// and sns://
route.AddRouteBuilder();
});
```
## Usage
```csharp
using redb.Route.Sqs.Fluent;
// Consume a queue — long-poll, 4 competing consumers, delete after processing
From(Sqs.Queue("orders").WaitTimeSeconds(20).ConcurrentConsumers(4))
.Process(HandleOrder);
// Produce to a queue
.To(Sqs.Queue("orders").Region("eu-west-1"));
// FIFO queue (name ends in .fifo) — group id required
.To(Sqs.Queue("orders.fifo").MessageGroupId("${header.customerId}"));
// Publish to an SNS topic
.To(Sns.Topic("events").Region("us-east-1"));
// SNS → SQS fan-out: subscribe a queue, then consume it with sqs://
.To(Sns.Topic("events").SubscribeSnsToSqs("arn:aws:sqs:us-east-1:000000000000:events-q"));
// Same, but raw delivery — the queue gets the bare payload (no SNS JSON envelope),
// and SNS attributes arrive as SQS attributes (so trace context survives the hop):
.To(Sns.Topic("events")
.SubscribeSnsToSqs("arn:aws:sqs:us-east-1:000000000000:events-q")
.RawMessageDelivery());
```
> **Envelope vs raw.** By default SNS wraps the payload in a JSON notification envelope
> (`{"Type":"Notification","Message":"",...}`), so the subscribing queue receives the
> *envelope*, not your payload — and SNS message attributes are buried inside it. Add
> `.RawMessageDelivery()` (sets `RawMessageDelivery=true` on the auto-created subscription) to get the
> **bare payload** and have SNS attributes map to SQS message attributes. It applies only to the
> `subscribeSnsToSqs` auto-subscription; the default stays `false` (AWS-compatible envelope).
Raw URIs work too: `sqs://orders?waitTimeSeconds=20&concurrentConsumers=4`,
`sns://events?region=us-east-1`.
## Concurrency & delivery
- **`concurrentConsumers=N`** runs N competing receive loops — up to N messages processed in parallel
(the SQS-native model). See the framework-wide **Concurrency & Parallelism** guide
(`CONCURRENCY.md`) for how this compares to the `.Threads(N)` processing EIP.
- **At-least-once**: a message is deleted only after it processes successfully. On failure it is left
for redelivery after the **visibility timeout** (or reset to 0 immediately with
`resetVisibilityOnFailure=true`).
- **`extendMessageVisibility=true`** keeps a message hidden while a long handler runs (heartbeat).
- **Inside `.Transacted()`** the delete comes last, after the database and the deferred sends have committed.
- **Producers join the transaction.** Inside `.Transacted()` an SQS send or an SNS publish leaves once the database has
committed and is dropped if the block rolls back. `transacted=false` sends at once, outside the transaction;
`transacted=true` requires an enclosing block and fails outside one. See the **Transactions** guide
(`TRANSACTIONS.md` in the [redb.Route repository](https://github.com/redbase-app/redb)).
- **Ordering** is preserved only per FIFO message group and only with `concurrentConsumers=1`.
## Batch mode
`batching=true` hands the route one InOnly exchange per batch, its body a `List` with one message per SQS
message (its body, its `redbSqs.*` headers and attributes, as a single message gets them), on the batch contract every
broker of redb.Route shares, with Apache Camel's option names:
- `maxBatchMessages` (default 10): the largest batch, collected over receives of up to 10 (the SQS limit per receive);
- `pollTimeoutMs` (default 1000): the batch goes on once no message came for that long; every receive that brings one
restarts it. SQS long-polls in whole seconds, so one receive waits at least a second;
- `batchingIntervalMs`: the batch goes on at the latest this long after its first message.
`maxNumberOfMessages`, `waitTimeSeconds` and `delay` are not used in batch mode. The batch message carries
`redbSqs.queue`.
Settlement, once after the route, by the rule of a single message applied to every message of the batch:
- the route succeeded: the batch is deleted (`DeleteMessageBatch`, 10 per call); an entry SQS refuses is logged and
comes back after its visibility timeout;
- the route failed: the messages stay invisible until the visibility timeout and come back (with
`resetVisibilityOnFailure=true` at once); the queue's redrive policy moves a message to its dead letter queue after
`maxReceiveCount` receives;
- the consumer stops while a batch is collected or routed: its messages are made visible again at once. A receive
in flight is not abandoned (an abandoned long poll stays open at the queue and would take those messages again):
the stop waits for it, at most `pollTimeoutMs` rounded up to whole seconds and never over 20 s, and gives its
messages back with the rest;
- `ackMode=auto` deletes the batch on receipt, before the route.
A batch's messages stay invisible while it is collected and routed: give the queue (or `visibilityTimeout`) a timeout
longer than both. `extendMessageVisibility` is refused with `batching=true`. Each of `concurrentConsumers` workers
collects and routes its own batches.
Verified against LocalStack 3.8.1 (community, the emulator of the test stand), not against AWS. What an
emulator does not show: duplicate deliveries on a standard queue (at-least-once: a batch may hold a message delivered
before), throttling of the batch calls, IAM permissions (`sqs:DeleteMessageBatch`, `sqs:ChangeMessageVisibilityBatch`
besides the single-message ones), and the real timing of long polls.
## Sending a list
A body that is a list of `IMessage` goes out one SQS message per element, in `SendMessageBatch` calls of up to 10: each
element with its own body and attributes (the parent's headers are not copied), and on a FIFO queue its own
`redbSqs.messageGroupId` and `redbSqs.messageDeduplicationId` headers, else the endpoint's options. As in Apache Camel,
entries SQS refuses do not fail the send: `redbSqs.batchSuccessful` and `redbSqs.batchFailed` count them,
`redbSqs.batchFailedEntries` lists the refused ones, and the endpoint records an error. Any other list goes out as one
message, its JSON.
## Key options
| Option | Applies to | Notes |
|---|---|---|
| `region`, `serviceUrl`, `accessKey`/`secretKey`, `sessionToken`, `profileName`, `useDefaultCredentialsProvider` | both | `serviceUrl` targets LocalStack/ElasticMQ |
| `waitTimeSeconds` (0–20), `maxNumberOfMessages` (1–10), `visibilityTimeout` | SQS consumer | long-poll + messages per receive + hide time |
| `concurrentConsumers`, `extendMessageVisibility`, `ackMode`, `resetVisibilityOnFailure` | SQS consumer | concurrency + ack |
| `batching`, `maxBatchMessages`, `pollTimeoutMs`, `batchingIntervalMs` | SQS consumer | batch mode |
| `delaySeconds`, `messageGroupId`, `messageDeduplicationId` | SQS producer | FIFO; a list of `IMessage` goes out by `SendMessageBatch` |
| `transacted` | SQS and SNS producer | unset follows an enclosing `.Transacted()` block, `false` sends at once, `true` requires a block |
| `autoCreateQueue` / `autoCreateTopic`, `topicArn`, `subject`, `messageStructure` | both | topology + SNS payload |
| `subscribeSnsToSqs` + `subscribeQueueArn` | SNS | subscribe a queue to the topic on start |
| `rawMessageDelivery` | SNS | on that auto-subscription, deliver the bare payload + map SNS attrs → SQS attrs (default `false` = JSON envelope) |
## Headers
A producer sends exchange headers as string message attributes of the same name; a `redbSqs.attr.X` header goes out
as attribute `X`, and the other `redbSqs.*` / `redbSns.*` headers never go out. A consumer puts each attribute under
`redbSqs.attr.X`, so a received attribute cannot pose as a control header of the route.
`headerFilterStrategy=#name` (SQS and SNS) names an `IHeaderFilterStrategy` in the registry that decides which plain
headers go out and which attributes come in, as in Apache Camel. It replaces the default, `SqsHeaderFilterStrategy`
or `SnsHeaderFilterStrategy`, entirely; derive from that class to add to it. On the way in the strategy is asked
with the attribute's own name (`X`, not `redbSqs.attr.X`). A `redbSqs.attr.X` header is an explicit request and goes
out whatever the strategy says.
```csharp
ctx.AddToRegistry("correlationOnly", new DefaultHeaderFilterStrategy
{
OutFilter = ["Correlation-ID"],
FilterOnMatch = false, // a whitelist: only the listed headers go out
});
// sqs://orders?region=eu-west-1&headerFilterStrategy=#correlationOnly
```
## Part of
Part of the [redb.Route](https://github.com/redbase-app/redb) enterprise integration framework.
## Named connection factory
Keep credentials out of the route URI: register a factory in the context registry and
reference it by name. A set-but-unknown name fails loud at startup — a typo can never
silently fall back to inline URI parameters.
```csharp
context.AddToRegistry("prod", new AwsConnectionFactory
{
Region = "eu-west-1",
AccessKey = "svc",
SecretKey = secrets.AwsSecret,
});
// sqs://orders?connectionFactory=prod
```
## Concurrency
The default is **1** concurrent consumer — the industry norm (Camel, Spring, the Azure SDK all
ship 1): a single consumer preserves ordering and your handlers need no thread safety.
Parallelism is an explicit opt-in:
```
concurrentConsumers=4 # a fixed worker count
concurrentConsumers=auto # max(CPU count, 2) — the NServiceBus formula
```
Anything else — `0`, a negative, a typo — fails at endpoint creation naming the option (the old
int-typed option silently fell back to 1). Raising the value trades ordering for throughput:
messages from the same queue are processed out of order, and your processors must be safe to
run in parallel.
## Tracing
On the `redb.Route` activity source (`AddSource("redb.Route")`). The W3C context travels in the message attributes
`traceparent`, `tracestate` and `baggage`; SNS attributes reach SQS with `rawMessageDelivery`.
- **SQS consumer.** One `Consumer` span per message, `{queue} receive`, over the whole unit of work. Its parent is the
sender's `traceparent`; without one it is a root, never a child of the activity the receive loop inherited from
whoever started the routes. The sender's baggage is back on it, the route's spans are its children. A failed route,
a timeout inside it included, marks it an error; the consumer's own stop does not. In batch mode one span per
batch, a root linked to the `traceparent` of every message that has one, with `messaging.batch.message_count`.
- **SQS and SNS producers.** One `Producer` span per send or publish; an error when it fails, unless our own token
cancelled it. The message carries the context of this span: a `traceparent` copied from a received message is
replaced. A message may carry at most 10 attributes: when the headers and the trace context together exceed that,
the send fails naming both counts, and nothing is dropped to make it fit. A list of `IMessage` is one span with
`messaging.batch.message_count`; every element carries its context.
- `RouteEngineOptions.EnableTelemetry = false` opens none of these spans. A context that came in still goes out.
Path: redb-route/redb.Route.Sqs/SnsComponent.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/redb.Route.Sqs/SnsComponent.cs
----
using Amazon.SimpleNotificationService;
using Amazon.SimpleNotificationService.Model;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Extensions;
using redb.Route.Core;
namespace redb.Route.Sqs;
///
/// Amazon SNS transport component for redb.Route. Scheme: sns.
/// Publisher: sns://my-topic?region=us-east-1 — publishes the exchange body to the topic.
/// SNS has no pull consumer; consume a topic by subscribing an SQS queue to it (see
/// subscribeSnsToSqs) and reading with the sqs:// connector.
///
[EndpointRole(EndpointRole.Producer, Hint = "To consume an SNS topic, subscribe an SQS queue to it "
+ "(sns://topic?subscribeSnsToSqs=true&subscribeQueueArn=...) and read with sqs://.")]
public sealed class SnsComponent : ComponentBase
{
///
public override string Scheme => "sns";
///
public override IEndpoint CreateEndpoint(EndpointUri uri)
{
ArgumentNullException.ThrowIfNull(uri);
var options = new SnsEndpointOptions();
options.BindFromUri(uri.RawParameters);
options.Validate();
return new SnsEndpoint(uri, this, options);
}
}
///
/// SNS endpoint — owns the shared client and resolves
/// the topic ARN (creating the topic on demand when autoCreateTopic=true). Producer-only.
///
public sealed class SnsEndpoint : EndpointBase, IDisposable
{
private IAmazonSimpleNotificationService? _client;
private readonly SemaphoreSlim _clientLock = new(1, 1);
private string? _topicArn;
private readonly SemaphoreSlim _arnLock = new(1, 1);
/// Topic name parsed from the URI path.
public string TopicName { get; }
/// True when the topic is FIFO (the name or an explicit topic ARN ends in .fifo).
public bool IsFifo => TopicName.EndsWith(".fifo", StringComparison.Ordinal)
|| Options.TopicArn.EndsWith(".fifo", StringComparison.Ordinal);
/// Logger from the parent component.
internal ILogger? Logger { get; }
/// Typed options.
internal SnsEndpointOptions EndpointOptions => Options;
/// Creates an SNS endpoint.
public SnsEndpoint(EndpointUri uri, SnsComponent component, SnsEndpointOptions options)
: base(uri, component, options)
{
Logger = component.Logger;
TopicName = uri.Path.TrimStart('/');
if (string.IsNullOrEmpty(TopicName) && string.IsNullOrEmpty(options.TopicArn))
throw new ArgumentException("SNS URI must include a topic name in the path (sns://topic-name).");
_headerFilter = new EndpointHeaderFilter(this, options.HeaderFilterStrategy);
}
private readonly EndpointHeaderFilter _headerFilter;
///
/// The header filter strategy of this endpoint: the one headerFilterStrategy=#name names, or
/// . A name the registry does not hold fails when the producer is
/// built.
///
internal IHeaderFilterStrategy HeaderFilterStrategy => _headerFilter.Or(SnsHeaderFilterStrategy.Default);
///
public override IProducer CreateProducer() => new SnsProducer(this, Options);
///
public override IConsumer CreateConsumer(IProcessor processor) =>
throw new NotSupportedException(
"SNS is publish-only — it has no pull consumer. To consume an SNS topic, subscribe an SQS "
+ "queue to it (sns://topic?subscribeSnsToSqs=true&subscribeQueueArn=...) and read with sqs://.");
/// Gets or creates the shared client.
internal async Task GetOrCreateClientAsync(CancellationToken ct = default)
{
if (_client is not null) return _client;
await _clientLock.WaitAsync(ct).ConfigureAwait(false);
try
{
if (_client is not null) return _client;
if (!string.IsNullOrEmpty(Options.ConnectionFactory))
{
// A set-but-unknown name fails loud — never a silent fallback.
var context = (Component as SnsComponent)?.Context;
_client = context.GetRequiredFromRegistry(Options.ConnectionFactory).BuildSns();
}
else
{
var config = new AmazonSimpleNotificationServiceConfig();
AwsClientSupport.ApplyCommonConfig(config, Options);
_client = new AmazonSimpleNotificationServiceClient(AwsClientSupport.ResolveCredentials(Options), config);
}
var (region, serviceUrl) = AwsClientSupport.Target(_client.Config);
Logger?.LogInformation("SNS client created: Region={Region}, ServiceUrl={ServiceUrl}, Topic={Topic}, ConnectionFactory={ConnectionFactory}",
region, serviceUrl, TopicName, string.IsNullOrEmpty(Options.ConnectionFactory) ? "-" : Options.ConnectionFactory);
return _client;
}
finally
{
_clientLock.Release();
}
}
/// Resolves (and caches) the topic ARN, creating the topic first when autoCreateTopic=true.
internal async Task GetTopicArnAsync(CancellationToken ct = default)
{
if (_topicArn is not null) return _topicArn;
await _arnLock.WaitAsync(ct).ConfigureAwait(false);
try
{
if (_topicArn is not null) return _topicArn;
if (!string.IsNullOrEmpty(Options.TopicArn))
return _topicArn = Options.TopicArn;
var client = await GetOrCreateClientAsync(ct).ConfigureAwait(false);
if (Options.AutoCreateTopic)
{
var request = new CreateTopicRequest { Name = TopicName };
if (IsFifo)
{
// AWS SDK v4 does not initialize request collections — assign the dictionary.
request.Attributes = new Dictionary
{
["FifoTopic"] = "true",
["ContentBasedDeduplication"] = "true",
};
}
var created = await client.CreateTopicAsync(request, ct).ConfigureAwait(false);
return _topicArn = created.TopicArn;
}
// No ARN and no auto-create: build the conventional ARN is not reliable — require an explicit ARN.
throw new InvalidOperationException(
$"SNS topic ARN unknown for '{TopicName}'. Set topicArn=... or autoCreateTopic=true.");
}
finally
{
_arnLock.Release();
}
}
///
public override async Task Stop(CancellationToken ct = default)
{
if (_client is not null)
{
try { _client.Dispose(); }
catch (Exception ex) { Logger?.LogWarning(ex, "Error disposing SNS client"); }
_client = null;
}
Logger?.LogInformation("SNS endpoint stopped: {Uri}", EndpointUri.ForLog(Uri.ToString(), Logger));
await Task.CompletedTask.ConfigureAwait(false);
}
///
public void Dispose()
{
_client?.Dispose();
_client = null;
_clientLock.Dispose();
_arnLock.Dispose();
}
}
Path: redb-route/redb.Route.Sqs/SnsEndpointOptions.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/redb.Route.Sqs/SnsEndpointOptions.cs
----
using redb.Route.Core;
namespace redb.Route.Sqs;
///
/// Options for an SNS endpoint (sns://topic-name?...). SNS is publish-only (there is no pull
/// consumer — delivery is push to SQS/HTTP/email/SMS), so these options drive the publisher plus the
/// optional SNS→SQS auto-subscription convenience.
///
public sealed class SnsEndpointOptions : AwsEndpointOptions
{
/// Explicit topic ARN. When empty it is resolved from the topic name (path) at start.
public string TopicArn { get; set; } = "";
/// Create the topic if it does not exist (FIFO when the name ends in .fifo). Default false.
public bool AutoCreateTopic { get; set; }
/// Optional message subject (used by email delivery). Supports ${...} expressions.
public string Subject { get; set; } = "";
/// Set to json to send a protocol-specific message structure (per-transport payloads).
public string MessageStructure { get; set; } = "";
/// FIFO topic message group id. Supports ${...} expressions.
public DynamicValue? MessageGroupId { get; set; }
/// FIFO deduplication id. Supports ${...} expressions. Omit for content-based dedup.
public DynamicValue? MessageDeduplicationId { get; set; }
/// At start, subscribe the SQS queue named by to this topic. Default false.
public bool SubscribeSnsToSqs { get; set; }
/// ARN of the SQS queue to subscribe when is true.
public string SubscribeQueueArn { get; set; } = "";
///
/// When auto-subscribing via , also set the subscription's
/// RawMessageDelivery=true so the SQS queue receives the bare payload (and SNS message
/// attributes map to SQS message attributes — which restores W3C trace continuity across the hop)
/// instead of the default SNS JSON notification envelope. Default false (AWS-compatible envelope).
///
public bool RawMessageDelivery { get; set; }
///
/// Whether the publish joins the enclosing .Transacted() block. Unset, it follows the block: deferred until
/// the database commits inside one, published at once outside. true requires a block and fails outside one;
/// false publishes at once even inside one.
///
public bool? Transacted { get; set; }
///
public override void Validate()
{
ValidateAws();
if (SubscribeSnsToSqs && string.IsNullOrEmpty(SubscribeQueueArn))
throw new ArgumentException("subscribeSnsToSqs=true requires subscribeQueueArn (the SQS queue ARN).");
}
}
Path: redb-route/redb.Route.Sqs/SnsHeaderFilterStrategy.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/redb.Route.Sqs/SnsHeaderFilterStrategy.cs
----
using redb.Route.Abstractions;
namespace redb.Route.Sqs;
///
/// The default of the SNS component. An endpoint's
/// headerFilterStrategy=#name replaces it; derive from it to add to it.
///
/// A producer publishes every exchange header but the component's own redbSns.* / redbSqs.* and null
/// values as a message attribute of the same name. Whatever the strategy, a redbSqs.attr.<name> header
/// is an explicit request and goes out as attribute <name>, the other redbSns.* /
/// redbSqs.* headers never go out, and trace context is written by the telemetry layer.
///
///
public class SnsHeaderFilterStrategy : IHeaderFilterStrategy
{
/// The default strategy of an SNS endpoint.
public static SnsHeaderFilterStrategy Default { get; } = new();
///
public virtual bool FilterOutgoing(string name, object? value, IExchange exchange)
=> value is null || SnsHeaders.IsSnsHeader(name) || SqsHeaders.IsSqsHeader(name);
///
public virtual bool FilterIncoming(string name, object? value, IExchange exchange) => false;
}
Path: redb-route/redb.Route.Sqs/SnsHeaders.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/redb.Route.Sqs/SnsHeaders.cs
----
namespace redb.Route.Sqs;
///
/// Exchange header keys for the SNS transport. All carry the so the producer can
/// forward only genuine user headers as message attributes.
///
public static class SnsHeaders
{
/// Common prefix for all SNS headers.
public const string Prefix = "redbSns.";
/// Topic ARN the message was published to.
public const string TopicArn = Prefix + "topicArn";
/// SNS message id assigned on publish.
public const string MessageId = Prefix + "messageId";
/// Message subject.
public const string Subject = Prefix + "subject";
/// FIFO message group id.
public const string MessageGroupId = Prefix + "messageGroupId";
/// FIFO deduplication id.
public const string MessageDeduplicationId = Prefix + "messageDeduplicationId";
/// FIFO sequence number returned by SNS.
public const string SequenceNumber = Prefix + "sequenceNumber";
/// True if is an SNS framework header (not a user attribute).
public static bool IsSnsHeader(string header) =>
header.StartsWith(Prefix, StringComparison.Ordinal);
}
Path: redb-route/redb.Route.Sqs/SnsProducer.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/redb.Route.Sqs/SnsProducer.cs
----
using System.Diagnostics;
using System.Globalization;
using System.Text;
using Amazon.SimpleNotificationService;
using Amazon.SimpleNotificationService.Model;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Telemetry;
using redb.Route.Transactions;
namespace redb.Route.Sqs;
///
/// SNS producer — publishes the exchange body to the topic. User headers become message attributes;
/// FIFO group/dedup ids resolve from headers or options. When subscribeSnsToSqs=true it
/// subscribes the configured SQS queue to the topic on start (a convenience for the SNS→SQS pattern).
///
internal sealed class SnsProducer : ConnectableProducer
{
private readonly SnsEndpoint _endpoint;
private readonly SnsEndpointOptions _options;
private readonly IHeaderFilterStrategy _headerFilter;
private IAmazonSimpleNotificationService? _client;
private string _topicArn = "";
internal SnsProducer(SnsEndpoint endpoint, SnsEndpointOptions options)
{
_endpoint = endpoint;
_options = options;
_headerFilter = endpoint.HeaderFilterStrategy;
}
///
protected override IEndpoint ProducerEndpoint => _endpoint;
///
protected override string ProducerName => $"sns://{_endpoint.TopicName}";
///
protected override async Task ConnectAsync(CancellationToken ct)
{
_client = await _endpoint.GetOrCreateClientAsync(ct).ConfigureAwait(false);
_topicArn = await _endpoint.GetTopicArnAsync(ct).ConfigureAwait(false);
if (_options.SubscribeSnsToSqs && !string.IsNullOrEmpty(_options.SubscribeQueueArn))
{
var subscription = await _client.SubscribeAsync(new SubscribeRequest
{
TopicArn = _topicArn,
Protocol = "sqs",
Endpoint = _options.SubscribeQueueArn,
ReturnSubscriptionArn = true,
}, ct).ConfigureAwait(false);
Logger?.LogInformation("SNS: subscribed SQS {QueueArn} to topic {Topic}", _options.SubscribeQueueArn, _topicArn);
// Raw delivery: the queue gets the bare payload (and SNS attributes become SQS attributes)
// instead of the default JSON notification envelope. Set it on the subscription we just made.
if (_options.RawMessageDelivery && !string.IsNullOrEmpty(subscription.SubscriptionArn))
{
await _client.SetSubscriptionAttributesAsync(new SetSubscriptionAttributesRequest
{
SubscriptionArn = subscription.SubscriptionArn,
AttributeName = "RawMessageDelivery",
AttributeValue = "true",
}, ct).ConfigureAwait(false);
Logger?.LogInformation("SNS: enabled RawMessageDelivery on subscription {Sub}", subscription.SubscriptionArn);
}
}
}
///
public override async Task Process(IExchange exchange, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(exchange);
EnsureStarted();
using var activity = RouteTelemetryExtensions.StartTransportSpan(
(_endpoint.Component as ComponentBase)?.Context,
$"{_endpoint.TopicName} publish", ActivityKind.Producer,
"messaging.system", "sns",
_endpoint.Uri.NormalizedKey,
destination: _endpoint.TopicName,
operation: "publish");
var request = new PublishRequest
{
TopicArn = _topicArn,
Message = AwsClientSupport.ResolveTextBody(exchange.In.Body),
MessageAttributes = BuildAttributes(exchange, activity),
};
var subject = ResolveHeader(exchange, SnsHeaders.Subject) ?? _options.ResolveOption(_options.Subject, exchange);
if (!string.IsNullOrEmpty(subject))
request.Subject = subject;
if (!string.IsNullOrEmpty(_options.MessageStructure))
request.MessageStructure = _options.MessageStructure;
if (_endpoint.IsFifo)
{
request.MessageGroupId = ResolveGroupId(exchange) ?? throw new InvalidOperationException(
"FIFO topic requires a messageGroupId (set the option or the redbSns.messageGroupId header).");
var dedup = ResolveHeader(exchange, SnsHeaders.MessageDeduplicationId)
?? _options.MessageDeduplicationId?.Resolve(exchange);
if (!string.IsNullOrEmpty(dedup))
request.MessageDeduplicationId = dedup;
}
async Task Publish(CancellationToken token)
{
var response = await _client!.PublishAsync(request, token).ConfigureAwait(false);
_endpoint.RecordBytesOut(Encoding.UTF8.GetByteCount(request.Message));
exchange.In.Headers[SnsHeaders.MessageId] = response.MessageId;
if (!string.IsNullOrEmpty(response.SequenceNumber))
exchange.In.Headers[SnsHeaders.SequenceNumber] = response.SequenceNumber;
}
// The request is built now, from the exchange as it is at this step; only the publish itself waits for the
// commit when the producer joins the enclosing .Transacted() block.
if (TransactedActions.Defers(exchange, _options.Transacted))
{
TransactedActions.RegisterSend(exchange, $"sns-publish-{Guid.NewGuid():N}", Publish, ProducerName);
return;
}
try
{
await Publish(ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
{
// Only our own token cancelling the publish is a stop; a timeout or any other failure marks the span.
activity.RecordFailure(ex);
throw;
}
// No RecordMessageOut: the core (ToProcessor / the template) owns it (ownership audit).
}
private string? ResolveGroupId(IExchange exchange) =>
ResolveHeader(exchange, SnsHeaders.MessageGroupId) ?? _options.MessageGroupId?.Resolve(exchange);
private static string? ResolveHeader(IExchange exchange, string key) =>
exchange.In.Headers.TryGetValue(key, out var v) && v is not null ? v.ToString() : null;
///
/// Maps forwardable headers to message attributes and adds the trace context of (the
/// publish span; without one, the ambient context), replacing a traceparent copied from a received message.
///
private Dictionary BuildAttributes(IExchange exchange, Activity? activity)
{
var attrs = new Dictionary();
foreach (var (key, value) in exchange.In.Headers)
{
if (value is null) continue;
var name = AwsClientSupport.MapHeaderToAttributeName(key);
if (name is null) continue;
// A redbSqs.attr. header is an explicit request; the strategy decides the plain headers.
if (!key.StartsWith(SqsHeaders.MessageAttributePrefix, StringComparison.Ordinal)
&& _headerFilter.FilterOutgoing(key, value, exchange)) continue;
attrs[name] = new MessageAttributeValue
{
DataType = "String",
StringValue = Convert.ToString(value, CultureInfo.InvariantCulture) ?? "",
};
}
var fromHeaders = attrs.Count;
RouteTelemetryExtensions.InjectTraceContext(activity, attrs, static (a, name, value) =>
a[name] = new MessageAttributeValue { DataType = "String", StringValue = value });
AwsClientSupport.EnsureAttributeLimit(attrs.Count, fromHeaders, ProducerName);
return attrs;
}
}
Path: redb-route/redb.Route.Sqs/SqsAckAction.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/redb.Route.Sqs/SqsAckAction.cs
----
using Amazon.SQS;
using redb.Route.Abstractions;
namespace redb.Route.Sqs;
///
/// Deferred SQS acknowledgement enrolled as an when the endpoint is
/// transacted=true. Commit deletes the message (or is a no-op when deleteAfterRead=false);
/// rollback resets its visibility to 0 so the broker redelivers it immediately. The surrounding
/// TransactedProcessor drives commit/rollback together with any redb DB work.
///
internal sealed class SqsAckAction : ITransactedAction
{
private readonly IAmazonSQS _client;
private readonly string _queueUrl;
private readonly string _receiptHandle;
private readonly bool _deleteAfterRead;
private int _settled;
public SqsAckAction(IAmazonSQS client, string queueUrl, string receiptHandle, bool deleteAfterRead)
{
_client = client;
_queueUrl = queueUrl;
_receiptHandle = receiptHandle;
_deleteAfterRead = deleteAfterRead;
}
/// True once commit or rollback has run — guards against a double settle.
public bool Settled => Volatile.Read(ref _settled) == 1;
///
public async Task Commit(CancellationToken ct = default)
{
if (Interlocked.CompareExchange(ref _settled, 1, 0) != 0) return;
if (_deleteAfterRead)
await _client.DeleteMessageAsync(_queueUrl, _receiptHandle, ct).ConfigureAwait(false);
}
///
public async Task Rollback(CancellationToken ct = default)
{
if (Interlocked.CompareExchange(ref _settled, 1, 0) != 0) return;
await _client.ChangeMessageVisibilityAsync(_queueUrl, _receiptHandle, 0, ct).ConfigureAwait(false);
}
}
Path: redb-route/redb.Route.Sqs/SqsComponent.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/redb.Route.Sqs/SqsComponent.cs
----
using Amazon.SQS;
using Amazon.SQS.Model;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Extensions;
using redb.Route.Core;
namespace redb.Route.Sqs;
///
/// Amazon SQS transport component for redb.Route. Scheme: sqs.
/// Consumer: sqs://my-queue?waitTimeSeconds=20&concurrentConsumers=4
/// Producer: sqs://my-queue?region=us-east-1 (send to the queue).
/// FIFO queues are addressed by their .fifo name; LocalStack/ElasticMQ via serviceUrl=.
///
public sealed class SqsComponent : ComponentBase
{
///
public override string Scheme => "sqs";
///
public override IEndpoint CreateEndpoint(EndpointUri uri)
{
ArgumentNullException.ThrowIfNull(uri);
var options = new SqsEndpointOptions();
options.BindFromUri(uri.RawParameters);
options.Validate();
options.ResolveBatch(EndpointUri.Sanitize(uri.BaseKey));
return new SqsEndpoint(uri, this, options);
}
}
///
/// SQS endpoint — owns the shared client and resolves the queue URL
/// (creating the queue on demand when autoCreateQueue=true).
///
public sealed class SqsEndpoint : EndpointBase, IDisposable
{
private IAmazonSQS? _client;
private readonly SemaphoreSlim _clientLock = new(1, 1);
private string? _queueUrl;
private readonly SemaphoreSlim _urlLock = new(1, 1);
/// Queue name parsed from the URI path.
public string QueueName { get; }
/// True when the queue is FIFO (the name or an explicit queue URL ends in .fifo).
public bool IsFifo => QueueName.EndsWith(".fifo", StringComparison.Ordinal)
|| Options.QueueUrl.EndsWith(".fifo", StringComparison.Ordinal);
/// Logger from the parent component.
internal ILogger? Logger { get; }
/// Typed options (exposed for consumer/producer).
internal SqsEndpointOptions EndpointOptions => Options;
/// Creates an SQS endpoint.
public SqsEndpoint(EndpointUri uri, SqsComponent component, SqsEndpointOptions options)
: base(uri, component, options)
{
Logger = component.Logger;
QueueName = uri.Path.TrimStart('/');
if (string.IsNullOrEmpty(QueueName) && string.IsNullOrEmpty(options.QueueUrl))
throw new ArgumentException("SQS URI must include a queue name in the path (sqs://queue-name).");
_headerFilter = new EndpointHeaderFilter(this, options.HeaderFilterStrategy);
}
private readonly EndpointHeaderFilter _headerFilter;
///
/// The header filter strategy of this endpoint: the one headerFilterStrategy=#name names, or
/// . A name the registry does not hold fails when the producer or
/// consumer is built.
///
internal IHeaderFilterStrategy HeaderFilterStrategy => _headerFilter.Or(SqsHeaderFilterStrategy.Default);
///
public override IProducer CreateProducer() => new SqsProducer(this, Options);
///
public override IConsumer CreateConsumer(IProcessor processor)
{
ArgumentNullException.ThrowIfNull(processor);
return new SqsConsumer(this, processor, Options);
}
/// Gets or creates the shared client.
internal async Task GetOrCreateClientAsync(CancellationToken ct = default)
{
if (_client is not null) return _client;
await _clientLock.WaitAsync(ct).ConfigureAwait(false);
try
{
if (_client is not null) return _client;
if (!string.IsNullOrEmpty(Options.ConnectionFactory))
{
// A set-but-unknown name fails loud — never a silent fallback.
var context = (Component as SqsComponent)?.Context;
_client = context.GetRequiredFromRegistry(Options.ConnectionFactory).BuildSqs();
}
else
{
var config = new AmazonSQSConfig();
AwsClientSupport.ApplyCommonConfig(config, Options);
_client = new AmazonSQSClient(AwsClientSupport.ResolveCredentials(Options), config);
}
var (region, serviceUrl) = AwsClientSupport.Target(_client.Config);
Logger?.LogInformation("SQS client created: Region={Region}, ServiceUrl={ServiceUrl}, Queue={Queue}, ConnectionFactory={ConnectionFactory}",
region, serviceUrl, QueueName, string.IsNullOrEmpty(Options.ConnectionFactory) ? "-" : Options.ConnectionFactory);
return _client;
}
finally
{
_clientLock.Release();
}
}
/// Resolves (and caches) the queue URL, creating the queue first when autoCreateQueue=true.
internal async Task GetQueueUrlAsync(CancellationToken ct = default)
{
if (_queueUrl is not null) return _queueUrl;
await _urlLock.WaitAsync(ct).ConfigureAwait(false);
try
{
if (_queueUrl is not null) return _queueUrl;
if (!string.IsNullOrEmpty(Options.QueueUrl))
return _queueUrl = Options.QueueUrl;
var client = await GetOrCreateClientAsync(ct).ConfigureAwait(false);
if (Options.AutoCreateQueue)
{
var request = new CreateQueueRequest { QueueName = QueueName };
if (IsFifo)
{
// AWS SDK v4 does not initialize request collections — assign the dictionary.
request.Attributes = new Dictionary
{
["FifoQueue"] = "true",
["ContentBasedDeduplication"] = "true",
};
}
var created = await client.CreateQueueAsync(request, ct).ConfigureAwait(false);
return _queueUrl = created.QueueUrl;
}
var resp = await client.GetQueueUrlAsync(QueueName, ct).ConfigureAwait(false);
return _queueUrl = resp.QueueUrl;
}
finally
{
_urlLock.Release();
}
}
///
public override async Task Stop(CancellationToken ct = default)
{
if (_client is not null)
{
try { _client.Dispose(); }
catch (Exception ex) { Logger?.LogWarning(ex, "Error disposing SQS client"); }
_client = null;
}
Logger?.LogInformation("SQS endpoint stopped: {Uri}", EndpointUri.ForLog(Uri.ToString(), Logger));
await Task.CompletedTask.ConfigureAwait(false);
}
///
public void Dispose()
{
_client?.Dispose();
_client = null;
_clientLock.Dispose();
_urlLock.Dispose();
}
}
Path: redb-route/redb.Route.Sqs/SqsConsumer.Batch.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/redb.Route.Sqs/SqsConsumer.Batch.cs
----
using Amazon.SQS.Model;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Batching;
using redb.Route.Core;
using redb.Route.Telemetry;
using SqsMessage = Amazon.SQS.Model.Message;
namespace redb.Route.Sqs;
///
/// Batch mode of the SQS consumer (batching=true), on the core batch contract: each worker collects up to
/// maxBatchMessages messages over receives of up to 10, runs them through the route once and settles them once.
/// Success deletes the batch (DeleteMessageBatch); a failure applies the rule of a failed single message to every
/// message: it stays invisible until the visibility timeout, or is made visible at once with
/// resetVisibilityOnFailure=true, and the queue's redrive policy moves it to the dead letter queue after
/// maxReceiveCount receives. A batch the consumer stops on is made visible again.
///
internal sealed partial class SqsConsumer
{
/// The most entries one SQS batch request takes, and the most messages one receive returns.
private const int SqsBatchLimit = 10;
private async Task BatchWorkerLoop(BatchOptions batch, CancellationToken pollCt, CancellationToken processingCt)
{
if (_options.InitialDelay > 0)
{
try { await Task.Delay(_options.InitialDelay, pollCt).ConfigureAwait(false); }
catch (OperationCanceledException) { return; }
}
var settlement = new SqsBatchSettlement(this);
var dispatcher = new BatchDispatcher(Processor, settlement, ToMessage, _endpoint.ScopeFactory,
[SqsHeaders.Queue]);
var collector = new BatchCollector(batch, ReceiveIntoBatch);
while (!pollCt.IsCancellationRequested)
{
CollectedBatch collected;
try
{
collected = await collector.CollectAsync(pollCt).ConfigureAwait(false);
}
catch (Exception ex)
{
Logger?.LogError(ex, "SQS batch receive error on queue {Queue}", _endpoint.QueueName);
_endpoint.RecordError(ex);
try { await Task.Delay(1000, pollCt).ConfigureAwait(false); }
catch (OperationCanceledException) { return; }
continue;
}
if (collected.Items.Count == 0)
continue;
if (collected.Interrupted)
{
await settlement.ReturnAsync(collected.Items, CancellationToken.None).ConfigureAwait(false);
return;
}
var items = collected.Items;
using var span = BatchDispatcher.StartSpan(
(_endpoint.Component as ComponentBase)?.Context, $"{_endpoint.QueueName} receive", "sqs",
_endpoint.Uri.NormalizedKey, _endpoint.QueueName,
items.Select(m => RouteTelemetryExtensions.ExtractTraceContext(m.MessageAttributes,
static (attrs, name) => attrs is not null && attrs.TryGetValue(name, out var value) ? value.StringValue : null)),
items.Count);
IncrementInflight();
try
{
await dispatcher.DispatchAsync(items, span, processingCt).ConfigureAwait(false);
}
catch (OperationCanceledException) when (processingCt.IsCancellationRequested)
{
return;
}
catch (Exception ex)
{
Logger?.LogError(ex, "SQS batch failed to settle on queue {Queue}", _endpoint.QueueName);
_endpoint.RecordError(ex);
}
finally
{
DecrementInflight();
}
}
}
///
/// The transport's part of collection: one ReceiveMessage of up to 10 messages, long-polling for the wait rounded
/// up to whole seconds (SQS waits in seconds, 1 to 20). A stop does not cancel a receive in flight: a long poll the
/// client abandons stays open at the queue and takes the messages the stop makes visible again, holding them for
/// their visibility timeout. The receive runs to its end, its messages join the batch, and the stop then gives the
/// whole batch back; a stop waits at most one receive.
///
private async ValueTask ReceiveIntoBatch(List into, int max, TimeSpan wait, CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
var request = new ReceiveMessageRequest
{
QueueUrl = _queueUrl,
MaxNumberOfMessages = Math.Min(SqsBatchLimit, max),
WaitTimeSeconds = (int)Math.Clamp(Math.Ceiling(wait.TotalSeconds), 1, 20),
MessageSystemAttributeNames = _systemAttributeNames,
MessageAttributeNames = _messageAttributeNames,
};
if (_options.VisibilityTimeout > 0)
request.VisibilityTimeout = _options.VisibilityTimeout;
var response = await _client!.ReceiveMessageAsync(request, CancellationToken.None).ConfigureAwait(false);
var messages = response.Messages ?? [];
into.AddRange(messages);
ct.ThrowIfCancellationRequested();
return messages.Count;
}
/// Deletes the messages in requests of up to 10. An entry SQS refuses is logged: it comes back after its visibility timeout.
private async Task DeleteBatchAsync(IReadOnlyList items, CancellationToken ct)
{
foreach (var chunk in items.Chunk(SqsBatchLimit))
{
var request = new DeleteMessageBatchRequest
{
QueueUrl = _queueUrl,
Entries = chunk.Select((m, i) => new DeleteMessageBatchRequestEntry(i.ToString(), m.ReceiptHandle)).ToList(),
};
var response = await _client!.DeleteMessageBatchAsync(request, ct).ConfigureAwait(false);
ReportFailedEntries(response.Failed, chunk, "delete");
}
}
/// Makes the messages visible again at once, in requests of up to 10.
private async Task MakeVisibleAsync(IReadOnlyList items)
{
foreach (var chunk in items.Chunk(SqsBatchLimit))
{
try
{
var request = new ChangeMessageVisibilityBatchRequest
{
QueueUrl = _queueUrl,
Entries = chunk.Select((m, i) =>
new ChangeMessageVisibilityBatchRequestEntry(i.ToString(), m.ReceiptHandle) { VisibilityTimeout = 0 }).ToList(),
};
var response = await _client!.ChangeMessageVisibilityBatchAsync(request, CancellationToken.None).ConfigureAwait(false);
ReportFailedEntries(response.Failed, chunk, "visibility reset");
}
catch (Exception ex)
{
Logger?.LogWarning(ex, "SQS: failed to reset visibility of {Count} messages on {Queue}",
chunk.Length, _endpoint.QueueName);
}
}
}
private void ReportFailedEntries(List? failed, SqsMessage[] chunk, string operation)
{
if (failed is not { Count: > 0 })
return;
var refused = new List(failed.Count);
foreach (var entry in failed)
{
var messageId = int.TryParse(entry.Id, out var index) && index < chunk.Length ? chunk[index].MessageId : entry.Id;
refused.Add($"{messageId}: {entry.Code} {entry.Message}");
Logger?.LogWarning("SQS batch {Operation} refused for messageId={MessageId} on {Queue}: {Code} {Message}",
operation, messageId, _endpoint.QueueName, entry.Code, entry.Message);
}
_endpoint.RecordError(new InvalidOperationException(
$"SQS batch {operation} on {_endpoint.QueueName}: {failed.Count} of {chunk.Length} messages refused: {string.Join("; ", refused)}"));
}
///
/// SQS's settlement of a batch: each message by its receipt handle, in batch requests. One instance per worker,
/// used by one batch at a time.
///
private sealed class SqsBatchSettlement(SqsConsumer owner) : IBatchSettlement
{
/// The batch in flight was deleted on receipt (ackMode=auto): there is nothing to give back.
private bool _deletedOnReceipt;
public async ValueTask BeforeRouteAsync(IExchange batch, IReadOnlyList items, CancellationToken ct)
{
// ackMode=auto: deleted on receipt, before the route runs (at-most-once), as a single message is.
if (owner._options.AckMode == AckMode.Auto)
{
await owner.DeleteBatchAsync(items, ct).ConfigureAwait(false);
_deletedOnReceipt = true;
}
return null;
}
public async ValueTask AcceptAsync(IExchange batch, IReadOnlyList items, CancellationToken ct)
{
if (!_deletedOnReceipt)
await owner.DeleteBatchAsync(items, ct).ConfigureAwait(false);
_deletedOnReceipt = false;
}
public async ValueTask RejectAsync(IExchange batch, IReadOnlyList items, Exception failure, CancellationToken ct)
{
owner.Logger?.LogError(failure, "SQS batch of {Count} failed on queue {Queue}", items.Count, owner._endpoint.QueueName);
if (!_deletedOnReceipt && owner._options.ResetVisibilityOnFailure)
await owner.MakeVisibleAsync(items).ConfigureAwait(false);
_deletedOnReceipt = false;
}
public async ValueTask ReturnAsync(IReadOnlyList items, CancellationToken ct)
{
if (!_deletedOnReceipt)
await owner.MakeVisibleAsync(items).ConfigureAwait(false);
_deletedOnReceipt = false;
}
}
}
Path: redb-route/redb.Route.Sqs/SqsConsumer.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/redb.Route.Sqs/SqsConsumer.cs
----
using System.Collections.Concurrent;
using System.Diagnostics;
using Amazon.SQS;
using Amazon.SQS.Model;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Telemetry;
using redb.Route.Transactions;
using RouteMessage = redb.Route.Core.Message;
using SqsMessage = Amazon.SQS.Model.Message;
namespace redb.Route.Sqs;
///
/// SQS consumer — long-polls the queue and dispatches each message through the route pipeline.
/// Extends for two-CTS graceful shutdown. Runs
/// concurrentConsumers competing receive loops (the SQS-native concurrency model). A message is
/// deleted (acknowledged) only after it processes successfully; on failure it is left for redelivery
/// after the visibility timeout (or reset to 0 immediately when resetVisibilityOnFailure=true).
/// Inside a .Transacted() route the delete comes last, after the database and the deferred sends have committed.
///
internal sealed partial class SqsConsumer : DrainableConsumer
{
private readonly SqsEndpoint _endpoint;
private readonly SqsEndpointOptions _options;
private readonly IHeaderFilterStrategy _headerFilter;
private IAmazonSQS? _client;
private string _queueUrl = "";
private readonly List _systemAttributeNames;
private readonly List _messageAttributeNames;
protected override IEndpoint ConsumerEndpoint => _endpoint;
protected override string ConsumerName => $"sqs://{_endpoint.QueueName}";
internal SqsConsumer(SqsEndpoint endpoint, IProcessor processor, SqsEndpointOptions options)
: base(processor)
{
_endpoint = endpoint;
_options = options;
_headerFilter = endpoint.HeaderFilterStrategy;
_systemAttributeNames = SplitCsv(options.AttributeNames);
_messageAttributeNames = SplitCsv(options.MessageAttributeNames);
}
///
protected override async Task OnStarting(CancellationToken ct)
{
_client = await _endpoint.GetOrCreateClientAsync(ct).ConfigureAwait(false);
_queueUrl = await _endpoint.GetQueueUrlAsync(ct).ConfigureAwait(false);
}
///
protected override Task RunAsync(CancellationToken pollCt, CancellationToken processingCt)
{
// N competing receive loops — the SQS-native concurrency model (multiple receivers on one queue).
var workers = new Task[_options.ResolvedConcurrentConsumers];
for (var i = 0; i < _options.ResolvedConcurrentConsumers; i++)
workers[i] = _options.Batch is { } batch
? Task.Run(() => BatchWorkerLoop(batch, pollCt, processingCt), CancellationToken.None)
: Task.Run(() => WorkerLoop(pollCt, processingCt), CancellationToken.None);
return Task.WhenAll(workers);
}
private async Task WorkerLoop(CancellationToken pollCt, CancellationToken processingCt)
{
if (_options.InitialDelay > 0)
{
try { await Task.Delay(_options.InitialDelay, pollCt).ConfigureAwait(false); }
catch (OperationCanceledException) { return; }
}
while (!pollCt.IsCancellationRequested)
{
try
{
var messages = await ReceiveAsync(pollCt).ConfigureAwait(false);
if (messages.Count == 0)
{
if (_options.Delay > 0)
await Task.Delay(_options.Delay, pollCt).ConfigureAwait(false);
continue;
}
foreach (var msg in messages)
{
if (processingCt.IsCancellationRequested) break;
await HandleMessageAsync(msg, processingCt).ConfigureAwait(false);
}
}
catch (OperationCanceledException) when (pollCt.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
Logger?.LogError(ex, "SQS receive error on queue {Queue}", _endpoint.QueueName);
_endpoint.RecordError(ex);
try { await Task.Delay(1000, pollCt).ConfigureAwait(false); }
catch (OperationCanceledException) { break; }
}
}
}
private async Task> ReceiveAsync(CancellationToken ct)
{
var request = new ReceiveMessageRequest
{
QueueUrl = _queueUrl,
MaxNumberOfMessages = _options.MaxNumberOfMessages,
WaitTimeSeconds = _options.WaitTimeSeconds,
MessageSystemAttributeNames = _systemAttributeNames,
MessageAttributeNames = _messageAttributeNames,
};
if (_options.VisibilityTimeout > 0)
request.VisibilityTimeout = _options.VisibilityTimeout;
var response = await _client!.ReceiveMessageAsync(request, ct).ConfigureAwait(false);
return response.Messages ?? [];
}
private async Task HandleMessageAsync(SqsMessage msg, CancellationToken processingCt)
{
using var span = StartConsumerSpan(msg);
IncrementInflight();
IExchange? exchange = null;
IDisposable? heartbeat = null;
try
{
exchange = CreateExchange(msg);
// ackMode=auto: deleted on receipt, before the route runs (at-most-once).
if (_options.AckMode == AckMode.Auto)
await _client!.DeleteMessageAsync(_queueUrl, msg.ReceiptHandle, processingCt).ConfigureAwait(false);
// The message is deleted (or made visible again) by this consumer below, after the whole unit of
// work ended well; the route transaction owns the database and the outgoing sends.
heartbeat = StartVisibilityHeartbeat(msg.ReceiptHandle, processingCt);
// No RecordMessageIn: the core's StatisticsProcessor around From() owns it (ownership audit).
await Processor.Process(exchange, processingCt).ConfigureAwait(false);
// Stop the heartbeat BEFORE acknowledging so it can never re-hide a message that is about
// to be deleted, nor undo a rollback's visibility reset (transacted fast-retry).
heartbeat?.Dispose();
heartbeat = null;
// A rollback-only exchange (.RollbackAll()) counts as failed: its work was rolled back.
var failed = exchange.EndedInFailure();
// A failed route marks the span, a rolled-back one does not; our own stop is not a failure.
if (exchange.Exception is { } failure && !exchange.ExceptionHandled
&& (failure is not OperationCanceledException || !processingCt.IsCancellationRequested))
span.Activity.RecordFailure(failure);
// Settle here whether or not the route is transacted: the acknowledgement is the consumer's, and by now
// the route transaction has committed the database and sent what it deferred.
if (!failed && _options.AckMode == AckMode.Manual)
await _client!.DeleteMessageAsync(_queueUrl, msg.ReceiptHandle, processingCt).ConfigureAwait(false);
else if (failed && _options.ResetVisibilityOnFailure)
await SafeResetVisibilityAsync(msg.ReceiptHandle).ConfigureAwait(false);
}
catch (OperationCanceledException) when (processingCt.IsCancellationRequested)
{
// Graceful shutdown — leave the message for redelivery (do not delete).
}
catch (Exception ex)
{
// Any other failure (incl. a downstream TaskCanceledException that is NOT our shutdown token).
// No RecordError: the pipeline already counted it (StatisticsProcessor); this catch only
// logs and restores visibility (ownership audit).
span.Activity.RecordFailure(ex);
Logger?.LogError(ex, "SQS message processing failed on queue {Queue}, messageId={MessageId}",
_endpoint.QueueName, msg.MessageId);
if (_options.ResetVisibilityOnFailure)
await SafeResetVisibilityAsync(msg.ReceiptHandle).ConfigureAwait(false);
}
finally
{
heartbeat?.Dispose();
DecrementInflight();
if (exchange is not null)
await exchange.DisposeAsync().ConfigureAwait(false);
}
}
private async Task SafeResetVisibilityAsync(string receiptHandle)
{
try
{
await _client!.ChangeMessageVisibilityAsync(_queueUrl, receiptHandle, 0, CancellationToken.None)
.ConfigureAwait(false);
}
catch (Exception ex)
{
Logger?.LogWarning(ex, "SQS: failed to reset visibility on {Queue}", _endpoint.QueueName);
}
}
// ── Exchange + telemetry ──────────────────────────────────────────
private IExchange CreateExchange(SqsMessage msg)
{
var message = new RouteMessage();
var exchange = Exchange.Create(message, _endpoint.ScopeFactory);
FillMessage(msg, message, exchange);
return exchange;
}
/// One SQS message into a batch's message, mapped as a single message's exchange message is.
private IMessage ToMessage(SqsMessage msg, IExchange batch)
{
var message = new RouteMessage();
FillMessage(msg, message, batch);
return message;
}
private void FillMessage(SqsMessage msg, RouteMessage message, IExchange exchange)
{
message.Body = msg.Body;
var headers = message.Headers;
headers[SqsHeaders.Queue] = _endpoint.QueueName;
headers[SqsHeaders.MessageId] = msg.MessageId;
headers[SqsHeaders.ReceiptHandle] = msg.ReceiptHandle;
if (!string.IsNullOrEmpty(msg.MD5OfBody))
headers[SqsHeaders.Md5OfBody] = msg.MD5OfBody;
headers[SqsHeaders.Timestamp] = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
if (msg.Attributes is not null)
{
if (msg.Attributes.TryGetValue("ApproximateReceiveCount", out var arc))
headers[SqsHeaders.ApproximateReceiveCount] = arc;
if (msg.Attributes.TryGetValue("SentTimestamp", out var st))
headers[SqsHeaders.SentTimestamp] = st;
if (msg.Attributes.TryGetValue("MessageGroupId", out var gid))
headers[SqsHeaders.MessageGroupId] = gid;
if (msg.Attributes.TryGetValue("SequenceNumber", out var seq))
headers[SqsHeaders.SequenceNumber] = seq;
}
// Message attributes, as the endpoint's strategy lets them in (asked with the attribute's own name)
if (msg.MessageAttributes is not null)
foreach (var (name, value) in msg.MessageAttributes)
{
if (_headerFilter.FilterIncoming(name, value.StringValue, exchange)) continue;
headers[SqsHeaders.MessageAttributePrefix + name] = value.StringValue;
}
}
private TransportSpan StartConsumerSpan(SqsMessage msg)
{
// The W3C context rides in the message attributes: traceparent, tracestate, baggage.
var span = RouteTelemetryExtensions.StartConsumerSpan(
(_endpoint.Component as ComponentBase)?.Context,
$"{_endpoint.QueueName} receive", ActivityKind.Consumer,
"messaging.system", "sqs", _endpoint.Uri.NormalizedKey,
msg.MessageAttributes,
static (attrs, name) => attrs is not null && attrs.TryGetValue(name, out var value) ? value.StringValue : null,
destination: _endpoint.QueueName, operation: "receive");
if (span.Activity is { IsAllDataRequested: true } activity)
activity.SetTag("messaging.message.id", msg.MessageId);
return span;
}
// ── Visibility heartbeat ──────────────────────────────────────────
private IDisposable? StartVisibilityHeartbeat(string receiptHandle, CancellationToken ct)
{
if (!_options.ExtendMessageVisibility || _options.VisibilityTimeout <= 0)
return null;
var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
var interval = TimeSpan.FromSeconds(Math.Max(1, _options.VisibilityTimeout / 2.0));
_ = Task.Run(async () =>
{
try
{
while (!cts.Token.IsCancellationRequested)
{
await Task.Delay(interval, cts.Token).ConfigureAwait(false);
await _client!.ChangeMessageVisibilityAsync(
_queueUrl, receiptHandle, _options.VisibilityTimeout, cts.Token).ConfigureAwait(false);
}
}
catch (OperationCanceledException) { }
catch (Exception ex)
{
Logger?.LogDebug(ex, "SQS visibility heartbeat ended for {Queue}", _endpoint.QueueName);
}
}, cts.Token);
return new HeartbeatHandle(cts);
}
private sealed class HeartbeatHandle(CancellationTokenSource cts) : IDisposable
{
public void Dispose()
{
try { cts.Cancel(); } catch (ObjectDisposedException) { }
cts.Dispose();
}
}
// ── Helpers ───────────────────────────────────────────────────────
private static List SplitCsv(string csv) =>
string.IsNullOrWhiteSpace(csv)
? []
: csv.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList();
}
Path: redb-route/redb.Route.Sqs/SqsEndpointOptions.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/redb.Route.Sqs/SqsEndpointOptions.cs
----
using redb.Route.Core;
namespace redb.Route.Sqs;
///
/// Options for an SQS endpoint (sqs://queue-name?...). The queue name is taken from the URI
/// path; every value below is bound from the query string. Consumer and producer options coexist —
/// only the relevant subset applies to each direction.
///
public sealed class SqsEndpointOptions : AwsEndpointOptions
{
// ── Addressing ────────────────────────────────────────────────────
/// Explicit queue URL. When empty it is resolved from the queue name (path) at start.
public string QueueUrl { get; set; } = "";
/// Create the queue if it does not exist (uses the queue name; FIFO if it ends in .fifo). Default false.
public bool AutoCreateQueue { get; set; }
// ── Consumer (receive) ────────────────────────────────────────────
/// Long-poll wait time in seconds (0–20). Default 20 — fewer empty receives, lower cost.
public int WaitTimeSeconds { get; set; } = 20;
/// Messages fetched per ReceiveMessage call (1–10). Default 10.
public int MaxNumberOfMessages { get; set; } = 10;
/// Visibility timeout in seconds for received messages. 0 = use the queue default.
public int VisibilityTimeout { get; set; }
/// Concurrent receive/processing loops: a number or "auto" (= max(CPU, 2)). Default 1 (serial).
// A string so "auto" binds verbatim instead of silently degrading to the int default.
public string? ConcurrentConsumers { get; set; }
/// Resolved consumer parallelism (see ).
public int ResolvedConcurrentConsumers => ConcurrencyOption.Resolve(ConcurrentConsumers, "concurrentConsumers");
///
/// Keep extending a message's visibility while it is still being processed, so long handlers never
/// trigger redelivery. Requires > 0. Default false.
///
public bool ExtendMessageVisibility { get; set; }
///
/// When a message is deleted from the queue (). Manual (default): after a turn that
/// ended well; a failed one becomes visible again (at-least-once). Auto: on receipt, before the route runs
/// (at-most-once).
///
public AckMode AckMode { get; set; } = AckMode.Manual;
///
protected override string? UnknownParameterHint(string name)
=> name.Equals("deleteAfterRead", StringComparison.OrdinalIgnoreCase)
? "'deleteAfterRead' is replaced by 'ackMode': ackMode=manual (the default) deletes after the route, as " +
"deleteAfterRead=true did; ackMode=auto deletes on receipt. deleteAfterRead=false never deleted a message, " +
"so every message came back after its visibility timeout."
: null;
///
/// On processing failure, immediately reset visibility to 0 so the message is redelivered at once
/// (rather than waiting out the visibility timeout). Default false.
///
public bool ResetVisibilityOnFailure { get; set; }
/// Comma-separated system attribute names to request (e.g. All). Default All.
public string AttributeNames { get; set; } = "All";
/// Comma-separated message-attribute names to request. Default All.
public string MessageAttributeNames { get; set; } = "All";
// ── Batch mode ──
///
/// Batch mode (Apache Camel batching): the route gets one InOnly exchange whose body is a
/// List<IMessage> of up to messages, deleted once after the route.
/// Collection is ruled by the batch options: , and
/// are not used in batch mode. A batch's messages stay invisible while it is collected and
/// routed, so (or the queue's own) must cover both.
///
public bool Batching { get; set; }
/// Largest number of messages in a batch (default 10). Collected over several receives of up to 10.
public int? MaxBatchMessages { get; set; }
///
/// Batch mode: a batch with messages is sent on once no message came for this many milliseconds, restarted by every
/// receive that brought one (default 1000). A receive waits at least a second (SQS long-poll is in seconds).
///
public int PollTimeoutMs { get; set; } = 1000;
/// Batch mode: a batch is sent on once this many milliseconds have passed since its first message.
public int? BatchingIntervalMs { get; set; }
/// The default of : one receive's worth.
internal const int DefaultMaxBatchMessages = 10;
/// The batch options, or null outside batch mode. Set by .
internal redb.Route.Batching.BatchOptions? Batch { get; private set; }
///
/// Resolves the batch options. Fails, naming the endpoint, for a batch option without batching=true, a value
/// out of range, and extendMessageVisibility (a batch is not kept invisible message by message: set a
/// visibilityTimeout longer than a batch's route).
///
internal void ResolveBatch(string endpoint)
{
Batch = redb.Route.Batching.BatchOptions.Resolve(endpoint, Batching, MaxBatchMessages, PollTimeoutMs,
BatchingIntervalMs, DefaultMaxBatchMessages);
if (Batch is not null && ExtendMessageVisibility)
throw new InvalidOperationException(
$"Endpoint '{endpoint}': batching=true cannot be combined with extendMessageVisibility: give the queue a " +
"visibilityTimeout longer than a batch's route instead.");
}
///
/// Producer: whether the send joins the enclosing .Transacted() block. Unset, it follows the block: deferred
/// until the database commits inside one, sent at once outside. true requires a block and fails outside one;
/// false sends at once even inside one. A consumer always deletes the message itself once the route has
/// finished successfully, so the option does not apply to it.
///
public bool? Transacted { get; set; }
/// Delay in milliseconds after an empty receive before polling again. Default 0.
public int Delay { get; set; }
/// Initial delay in milliseconds before the first poll. Default 0.
public int InitialDelay { get; set; }
// ── Producer (send) ───────────────────────────────────────────────
/// Delivery delay in seconds for sent messages (0–900). Default 0.
public int DelaySeconds { get; set; }
/// FIFO message group id (required for FIFO queues). Supports ${...} expressions.
public DynamicValue? MessageGroupId { get; set; }
/// FIFO deduplication id. Supports ${...} expressions. Omit when the queue has content-based dedup.
public DynamicValue? MessageDeduplicationId { get; set; }
///
public override void Validate()
{
ValidateAws();
if (WaitTimeSeconds is < 0 or > 20)
throw new ArgumentException($"waitTimeSeconds must be 0–20. Got: {WaitTimeSeconds}");
if (MaxNumberOfMessages is < 1 or > 10)
throw new ArgumentException($"maxNumberOfMessages must be 1–10. Got: {MaxNumberOfMessages}");
_ = ConcurrencyOption.Resolve(ConcurrentConsumers, "concurrentConsumers"); // loud on garbage
if (VisibilityTimeout < 0)
throw new ArgumentException($"visibilityTimeout cannot be negative. Got: {VisibilityTimeout}");
if (ExtendMessageVisibility && VisibilityTimeout <= 0)
throw new ArgumentException("extendMessageVisibility requires visibilityTimeout > 0.");
if (AckMode == AckMode.Auto && (ExtendMessageVisibility || ResetVisibilityOnFailure))
throw new ArgumentException(
"ackMode=auto deletes a message on receipt, so there is no visibility left to extend or reset: " +
"extendMessageVisibility and resetVisibilityOnFailure need ackMode=manual.");
if (DelaySeconds is < 0 or > 900)
throw new ArgumentException($"delaySeconds must be 0–900. Got: {DelaySeconds}");
}
}
Path: redb-route/redb.Route.Sqs/SqsHeaderFilterStrategy.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/redb.Route.Sqs/SqsHeaderFilterStrategy.cs
----
using redb.Route.Abstractions;
namespace redb.Route.Sqs;
///
/// The default of the SQS component. An endpoint's
/// headerFilterStrategy=#name replaces it; derive from it to add to it.
///
/// A producer sends every exchange header but the component's own redbSqs.* / redbSns.* and null values
/// as a message attribute of the same name; a consumer brings every message attribute in. The strategy is asked with
/// the attribute's own name, on the way in as well, although the consumer stores it under
/// redbSqs.attr.<name>.
///
///
/// Whatever the strategy: a redbSqs.attr.<name> header is an explicit request and goes out as attribute
/// <name>; the other redbSqs.* / redbSns.* headers never go out; the consumer's
/// redbSqs.* metadata is set by the consumer; trace context is written by the telemetry layer.
///
///
public class SqsHeaderFilterStrategy : IHeaderFilterStrategy
{
/// The default strategy of an SQS endpoint.
public static SqsHeaderFilterStrategy Default { get; } = new();
///
public virtual bool FilterOutgoing(string name, object? value, IExchange exchange)
=> value is null || SqsHeaders.IsSqsHeader(name) || SnsHeaders.IsSnsHeader(name);
///
public virtual bool FilterIncoming(string name, object? value, IExchange exchange) => false;
}
Path: redb-route/redb.Route.Sqs/SqsHeaders.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/redb.Route.Sqs/SqsHeaders.cs
----
namespace redb.Route.Sqs;
///
/// Exchange header keys for the SQS transport. All carry the so the producer can
/// tell framework/broker headers apart from user headers it must forward as message attributes.
///
public static class SqsHeaders
{
/// Common prefix for all SQS headers.
public const string Prefix = "redbSqs.";
/// Queue name (or URL) the message was received from / is sent to.
public const string Queue = Prefix + "queue";
/// SQS message id.
public const string MessageId = Prefix + "messageId";
/// Receipt handle — required to delete or change visibility of a received message.
public const string ReceiptHandle = Prefix + "receiptHandle";
/// MD5 of the message body (integrity check).
public const string Md5OfBody = Prefix + "md5OfBody";
/// FIFO message group id.
public const string MessageGroupId = Prefix + "messageGroupId";
/// FIFO deduplication id.
public const string MessageDeduplicationId = Prefix + "messageDeduplicationId";
/// FIFO sequence number assigned by SQS.
public const string SequenceNumber = Prefix + "sequenceNumber";
/// Approximate number of times the message has been received.
public const string ApproximateReceiveCount = Prefix + "approximateReceiveCount";
/// Epoch-millis the message was sent.
public const string SentTimestamp = Prefix + "sentTimestamp";
/// Receive timestamp (epoch millis) set by the consumer.
public const string Timestamp = Prefix + "timestamp";
/// Prefix under which incoming message attributes are exposed as headers.
public const string MessageAttributePrefix = Prefix + "attr.";
/// Producer, list body: the number of messages SQS took from the SendMessageBatch calls.
public const string BatchSuccessful = Prefix + "batchSuccessful";
/// Producer, list body: the number of messages SQS refused; the send does not throw for them.
public const string BatchFailed = Prefix + "batchFailed";
/// Producer, list body: the refused entries (List<string>, "entry id: code message"), set when there are any.
public const string BatchFailedEntries = Prefix + "batchFailedEntries";
/// True if is an SQS framework/broker header (should not be re-sent as a user attribute).
public static bool IsSqsHeader(string header) =>
header.StartsWith(Prefix, StringComparison.Ordinal);
}
Path: redb-route/redb.Route.Sqs/SqsProducer.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/redb.Route.Sqs/SqsProducer.cs
----
using System.Diagnostics;
using System.Globalization;
using System.Text;
using Amazon.SQS;
using Amazon.SQS.Model;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Telemetry;
using redb.Route.Transactions;
namespace redb.Route.Sqs;
///
/// SQS producer: sends the exchange body to the queue as a single message, or a List<IMessage> body as
/// one SQS message per element in SendMessageBatch calls of up to 10. Any other list is one message, its JSON.
/// User headers become message attributes; FIFO group/dedup ids are resolved from headers or options.
///
internal sealed class SqsProducer : ConnectableProducer
{
/// The most entries one SendMessageBatch takes.
private const int SqsBatchLimit = 10;
private readonly SqsEndpoint _endpoint;
private readonly SqsEndpointOptions _options;
private readonly IHeaderFilterStrategy _headerFilter;
private IAmazonSQS? _client;
private string _queueUrl = "";
internal SqsProducer(SqsEndpoint endpoint, SqsEndpointOptions options)
{
_endpoint = endpoint;
_options = options;
_headerFilter = endpoint.HeaderFilterStrategy;
}
///
protected override IEndpoint ProducerEndpoint => _endpoint;
///
protected override string ProducerName => $"sqs://{_endpoint.QueueName}";
///
protected override async Task ConnectAsync(CancellationToken ct)
{
_client = await _endpoint.GetOrCreateClientAsync(ct).ConfigureAwait(false);
_queueUrl = await _endpoint.GetQueueUrlAsync(ct).ConfigureAwait(false);
}
///
public override async Task Process(IExchange exchange, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(exchange);
EnsureStarted();
using var activity = RouteTelemetryExtensions.StartTransportSpan(
(_endpoint.Component as ComponentBase)?.Context,
$"{_endpoint.QueueName} send", ActivityKind.Producer,
"messaging.system", "sqs",
_endpoint.Uri.NormalizedKey,
destination: _endpoint.QueueName,
operation: "send");
// No RecordMessageOut: the core (ToProcessor / the template) owns it (ownership audit).
// The requests are built now, from the exchange as it is at this step; only the send itself waits for the
// commit when the producer joins the enclosing .Transacted() block.
// A list of IMessage goes out element by element in SendMessageBatch calls; any other body, a plain list
// included (as JSON), is one message.
var send = ListBody.Messages(exchange.In.Body) is { } messages
? await PrepareListAsync(exchange, messages, activity).ConfigureAwait(false)
: PrepareSingle(exchange, activity);
if (TransactedActions.Defers(exchange, _options.Transacted))
{
TransactedActions.RegisterSend(exchange, $"sqs-send-{Guid.NewGuid():N}", send, ProducerName);
return;
}
try
{
await send(ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
{
// Only our own token cancelling the send is a stop; a timeout or any other failure marks the span.
activity.RecordFailure(ex);
throw;
}
}
private Func PrepareSingle(IExchange exchange, Activity? activity)
{
var request = new SendMessageRequest
{
QueueUrl = _queueUrl,
MessageBody = AwsClientSupport.ResolveTextBody(exchange.In.Body),
MessageAttributes = BuildAttributes(exchange, activity),
};
if (_options.DelaySeconds > 0 && !_endpoint.IsFifo)
request.DelaySeconds = _options.DelaySeconds; // FIFO queues reject per-message delay
ApplyFifo(request, exchange);
return async ct =>
{
var response = await _client!.SendMessageAsync(request, ct).ConfigureAwait(false);
_endpoint.RecordBytesOut(Encoding.UTF8.GetByteCount(request.MessageBody));
exchange.In.Headers[SqsHeaders.MessageId] = response.MessageId;
if (!string.IsNullOrEmpty(response.SequenceNumber))
exchange.In.Headers[SqsHeaders.SequenceNumber] = response.SequenceNumber;
};
}
///
/// A list of : one SendMessageBatch per 10 elements, each element its own SQS message
/// with its own body and attributes and, on a FIFO queue, its own group and deduplication id (its headers, else the
/// endpoint's options), as a Split part's single send would have them. As in Apache Camel's sendBatchMessage,
/// entries SQS refuses do not throw: the counts land in and
/// , the refused entries in , and
/// the endpoint records an error.
///
private async Task> PrepareListAsync(IExchange exchange, IReadOnlyList messages,
Activity? activity)
{
var requests = new List();
var index = 0;
foreach (var chunk in messages.Chunk(SqsBatchLimit))
{
// AWS SDK v4 does not initialize request collections: start with an empty entry list.
var request = new SendMessageBatchRequest { QueueUrl = _queueUrl, Entries = [] };
foreach (var message in chunk)
{
var element = ListBody.ElementExchange(exchange, message);
try
{
var entry = new SendMessageBatchRequestEntry
{
Id = $"m{index++}",
MessageBody = AwsClientSupport.ResolveTextBody(element.In.Body),
MessageAttributes = BuildAttributes(element, activity),
};
if (_options.DelaySeconds > 0 && !_endpoint.IsFifo)
entry.DelaySeconds = _options.DelaySeconds;
if (_endpoint.IsFifo)
{
entry.MessageGroupId = ResolveGroupId(element) ?? throw new InvalidOperationException(
"FIFO queue requires a messageGroupId (set the option or the redbSqs.messageGroupId header).");
var dedup = ResolveDeduplicationId(element);
if (!string.IsNullOrEmpty(dedup))
entry.MessageDeduplicationId = dedup;
}
request.Entries.Add(entry);
}
finally
{
if (element is IAsyncDisposable disposable)
await disposable.DisposeAsync().ConfigureAwait(false);
}
}
requests.Add(request);
}
activity?.SetTag("messaging.batch.message_count", messages.Count);
return async ct =>
{
var successful = 0;
var failed = new List();
foreach (var request in requests)
{
var response = await _client!.SendMessageBatchAsync(request, ct).ConfigureAwait(false);
successful += response.Successful?.Count ?? 0;
// Wire bytes of the entries SQS took; a refused entry sent nothing.
var refused = (response.Failed ?? []).Select(f => f.Id).ToHashSet(StringComparer.Ordinal);
long sent = 0;
foreach (var entry in request.Entries)
{
if (!refused.Contains(entry.Id))
sent += Encoding.UTF8.GetByteCount(entry.MessageBody);
}
if (sent > 0)
_endpoint.RecordBytesOut(sent);
foreach (var entry in response.Failed ?? [])
failed.Add($"{entry.Id}: {entry.Code} {entry.Message}");
}
var headers = exchange.In.Headers;
headers[SqsHeaders.Queue] = _endpoint.QueueName;
headers[SqsHeaders.BatchSuccessful] = successful;
headers[SqsHeaders.BatchFailed] = failed.Count;
if (failed.Count > 0)
{
headers[SqsHeaders.BatchFailedEntries] = failed;
_endpoint.RecordError(new InvalidOperationException(
$"SQS SendMessageBatch to {_endpoint.QueueName}: {failed.Count} of {messages.Count} messages refused: {string.Join("; ", failed)}"));
Logger?.LogWarning(
"SQS SendMessageBatch to {Queue}: {Failed} of {Total} messages refused: {Entries}",
_endpoint.QueueName, failed.Count, messages.Count, string.Join("; ", failed));
}
};
}
private void ApplyFifo(SendMessageRequest request, IExchange exchange)
{
if (!_endpoint.IsFifo) return;
request.MessageGroupId = ResolveGroupId(exchange) ?? throw new InvalidOperationException(
"FIFO queue requires a messageGroupId (set the option or the redbSqs.messageGroupId header).");
var dedup = ResolveDeduplicationId(exchange);
if (!string.IsNullOrEmpty(dedup))
request.MessageDeduplicationId = dedup;
}
private string? ResolveGroupId(IExchange exchange) =>
ResolveHeader(exchange, SqsHeaders.MessageGroupId) ?? _options.MessageGroupId?.Resolve(exchange);
private string? ResolveDeduplicationId(IExchange exchange) =>
ResolveHeader(exchange, SqsHeaders.MessageDeduplicationId) ?? _options.MessageDeduplicationId?.Resolve(exchange);
private static string? ResolveHeader(IExchange exchange, string key) =>
exchange.In.Headers.TryGetValue(key, out var v) && v is not null ? v.ToString() : null;
///
/// Maps forwardable headers to SQS message attributes (String values) and injects the current
/// trace context of (the send span; without one, the ambient context) so the
/// downstream consumer can continue the distributed trace. A traceparent copied from a received message is replaced.
///
private Dictionary BuildAttributes(IExchange exchange, Activity? activity)
{
var attrs = new Dictionary();
foreach (var (key, value) in exchange.In.Headers)
{
if (value is null) continue;
var name = AwsClientSupport.MapHeaderToAttributeName(key);
if (name is null) continue;
// A redbSqs.attr. header is an explicit request; the strategy decides the plain headers.
if (!key.StartsWith(SqsHeaders.MessageAttributePrefix, StringComparison.Ordinal)
&& _headerFilter.FilterOutgoing(key, value, exchange)) continue;
attrs[name] = new MessageAttributeValue
{
DataType = "String",
StringValue = Convert.ToString(value, CultureInfo.InvariantCulture) ?? "",
};
}
var fromHeaders = attrs.Count;
RouteTelemetryExtensions.InjectTraceContext(activity, attrs, static (a, name, value) =>
a[name] = new MessageAttributeValue { DataType = "String", StringValue = value });
AwsClientSupport.EnsureAttributeLimit(attrs.Count, fromHeaders, ProducerName);
return attrs;
}
}
Path: redb-route/redb.Route.Sqs/redb.Route.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/redb.Route.Sqs/redb.Route.Sqs.csproj
----
redb.Route.Sqs
Amazon SQS + SNS transport for redb.Route ESB framework via the native AWS SDK for .NET. SQS queue consumer (long-poll, concurrent consumers, visibility, FIFO) + producer (send/batch), and SNS topic publisher with SNS-to-SQS fan-out. LocalStack/ElasticMQ compatible.
esb;messaging;aws;sqs;sns;queue;pubsub;redb
README.md