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