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;
}
}