Path: redb-route/redb.Route.AzureServiceBus/AzureServiceBusBatchConsumer.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.AzureServiceBus/AzureServiceBusBatchConsumer.cs ---- using Azure.Messaging.ServiceBus; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Batching; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.AzureServiceBus; /// /// Batch mode of the Service Bus consumer (batching=true), on the core batch contract: each of /// maxConcurrentCalls workers collects up to maxBatchMessages messages with ReceiveMessagesAsync, /// runs them through the route once and settles them once. With ackMode=manual (PeekLock) success completes every /// message; a failure applies the rule of a failed single message to each: abandoned, so it is delivered again (and /// moved to the dead letter sub-queue by the entity after its MaxDeliveryCount), or dead-lettered at once with /// autoDeadLetter=true; a batch the route rolled back (.RollbackAll()) is abandoned. The locks of the /// batch are renewed while the route runs, up to maxAutoLockRenewalDuration, as the processor renews a single /// message's. A batch the consumer stops on is abandoned. With ackMode=auto (ReceiveAndDelete) the messages are /// gone on receipt and nothing is settled. /// internal sealed class AzureServiceBusBatchConsumer : IConsumer { private readonly AzureServiceBusEndpoint _endpoint; private readonly IProcessor _pipeline; private readonly AzureServiceBusEndpointOptions _options; private readonly BatchOptions _batch; private readonly IHeaderFilterStrategy _headerFilter; private readonly InflightDrainGuard _drain = new(); private readonly List<(ServiceBusReceiver Receiver, Task Loop)> _workers = []; private CancellationTokenSource? _stop; private ILogger? _logger; private AzureServiceBusConnectionWatch? _watch; public IEndpoint? Endpoint => _endpoint; internal AzureServiceBusBatchConsumer(AzureServiceBusEndpoint endpoint, IProcessor pipeline, AzureServiceBusEndpointOptions options, BatchOptions batch) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); _options = options ?? throw new ArgumentNullException(nameof(options)); _batch = batch ?? throw new ArgumentNullException(nameof(batch)); _headerFilter = endpoint.HeaderFilterStrategy; } private bool PeekLock => _options.ParsedReceiveMode == ServiceBusReceiveMode.PeekLock; public async Task Start(CancellationToken ct = default) { _logger ??= (_endpoint.Component as ComponentBase)?.Logger; var client = await _endpoint.GetOrCreateClientAsync(ct).ConfigureAwait(false); var receiverOptions = new ServiceBusReceiverOptions { ReceiveMode = _options.ParsedReceiveMode, PrefetchCount = _options.PrefetchCount, }; if (_options.ParsedSubQueue is not null) receiverOptions.SubQueue = _options.ParsedSubQueue.Value; _watch = new AzureServiceBusConnectionWatch(_endpoint, client, _options.SubscriptionName, _logger, probe: false); _stop = new CancellationTokenSource(); _drain.Start(ct); var workers = _options.ResolvedMaxConcurrentCalls; for (var i = 0; i < workers; i++) { var receiver = _endpoint.IsTopic ? client.CreateReceiver(_endpoint.EntityName, _options.SubscriptionName, receiverOptions) : client.CreateReceiver(_endpoint.EntityName, receiverOptions); var stop = _stop.Token; _workers.Add((receiver, Task.Run(() => WorkerLoopAsync(receiver, stop), stop))); } _logger?.LogInformation("ASB batch consumer started: entity={Entity}, ackMode={Mode}, workers={Workers}, batch={Batch}", _endpoint.EntityName, _options.AckMode, workers, _batch.MaxMessages); } public async Task Stop(CancellationToken ct = default) { _watch?.Stop(); _watch = null; _stop?.Cancel(); await _drain.DrainAsync(ct, _logger, $"asb:{_endpoint.EntityName}").ConfigureAwait(false); foreach (var (receiver, loop) in _workers) { try { await loop.ConfigureAwait(false); } catch (OperationCanceledException) { } catch (Exception ex) { _logger?.LogDebug(ex, "ASB batch worker faulted during stop"); } await receiver.DisposeAsync().ConfigureAwait(false); } _workers.Clear(); _drain.Dispose(); _stop?.Dispose(); _stop = null; _logger?.LogInformation("ASB batch consumer stopped: entity={Entity}", _endpoint.EntityName); } private async Task WorkerLoopAsync(ServiceBusReceiver receiver, CancellationToken stop) { var settlement = new Settlement(this, receiver); var dispatcher = new BatchDispatcher(_pipeline, settlement, ToMessage, _endpoint.ScopeFactory, [AzureServiceBusHeaders.SessionId]); var collector = new BatchCollector(_batch, (into, max, wait, ct) => ReceiveIntoBatchAsync(receiver, into, max, wait, ct)); while (!stop.IsCancellationRequested) { CollectedBatch collected; try { collected = await collector.CollectAsync(stop).ConfigureAwait(false); } catch (Exception ex) when (!stop.IsCancellationRequested) { // The client retried the receive by itself (RetryOptions) before it threw: a connection error is the // supervisor's (health shows the loss and each failed receive), not a failed message. if (_watch?.Report(ex) == true) { _logger?.LogDebug(ex, "ASB batch receive: connection error on {Entity}", _endpoint.EntityName); } else { _endpoint.RecordError(ex); _logger?.LogError(ex, "ASB batch receive error on {Entity}", _endpoint.EntityName); } try { await Task.Delay(1000, stop).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.EntityName} receive", "azureservicebus", _endpoint.Uri.NormalizedKey, _endpoint.EntityName, items.Select(m => RouteTelemetryExtensions.ExtractTraceContext(m.ApplicationProperties, AzureServiceBusTrace.Read)), items.Count); _drain.Increment(); try { await dispatcher.DispatchAsync(items, span, _drain.ProcessingToken).ConfigureAwait(false); } catch (OperationCanceledException) when (_drain.ProcessingToken.IsCancellationRequested) { return; } catch (Exception ex) { _endpoint.RecordError(ex); _logger?.LogError(ex, "ASB batch failed to settle on {Entity}", _endpoint.EntityName); } finally { _drain.Decrement(); } } } /// /// The transport's part of collection: one ReceiveMessagesAsync of up to messages, /// waiting at most . A stop does not cancel a receive in flight: messages it locks are taken /// into the batch, and the stop then abandons the whole batch; a stop waits at most one receive. /// private async ValueTask ReceiveIntoBatchAsync(ServiceBusReceiver receiver, List into, int max, TimeSpan wait, CancellationToken ct) { ct.ThrowIfCancellationRequested(); var received = await receiver.ReceiveMessagesAsync(max, wait, CancellationToken.None).ConfigureAwait(false); // A receive that came back, empty or not, is the connection being there. _watch?.Traffic(); into.AddRange(received); ct.ThrowIfCancellationRequested(); return received.Count; } /// One received message as an element of a batch, built as a single message is. private IMessage ToMessage(ServiceBusReceivedMessage msg, IExchange batch) { var message = new Message(); AzureServiceBusConsumer.FillMessage(msg, message, batch, _options, _headerFilter); return message; } /// Service Bus's settlement of a batch: each message by its lock. One instance per worker. private sealed class Settlement(AzureServiceBusBatchConsumer owner, ServiceBusReceiver receiver) : IBatchSettlement { public ValueTask BeforeRouteAsync(IExchange batch, IReadOnlyList items, CancellationToken ct) => ValueTask.FromResult(owner.PeekLock && owner._options.MaxAutoLockRenewalDuration > 0 ? new LockRenewal(owner, receiver, items) : null); public async ValueTask AcceptAsync(IExchange batch, IReadOnlyList items, CancellationToken ct) { if (owner.PeekLock) await SettleAsync(items, m => receiver.CompleteMessageAsync(m, ct), "complete").ConfigureAwait(false); } public async ValueTask RejectAsync(IExchange batch, IReadOnlyList items, Exception failure, CancellationToken ct) { owner._logger?.LogError(failure, "ASB batch of {Count} failed on {Entity}", items.Count, owner._endpoint.EntityName); if (!owner.PeekLock) return; // A rolled-back batch (.RollbackAll()) is delivered again, as a rolled-back single message; a failure is // dead-lettered at once with autoDeadLetter, else abandoned. if (owner._options.AutoDeadLetter && !batch.IsRollbackOnly()) await SettleAsync(items, m => receiver.DeadLetterMessageAsync(m, owner._options.DeadLetterReason ?? "ProcessingError", failure.Message, ct), "dead-letter").ConfigureAwait(false); else await SettleAsync(items, m => receiver.AbandonMessageAsync(m, cancellationToken: ct), "abandon").ConfigureAwait(false); } public async ValueTask ReturnAsync(IReadOnlyList items, CancellationToken ct) { if (owner.PeekLock) await SettleAsync(items, m => receiver.AbandonMessageAsync(m, cancellationToken: ct), "abandon").ConfigureAwait(false); } /// Settles each message; one that fails (its lock lost) is logged, and the entity delivers it again. private async Task SettleAsync(IReadOnlyList items, Func settle, string operation) { foreach (var msg in items) { try { await settle(msg).ConfigureAwait(false); } catch (Exception ex) { owner._endpoint.RecordError(ex); owner._logger?.LogWarning(ex, "ASB batch {Operation} failed for messageId={MessageId} on {Entity}", operation, msg.MessageId, owner._endpoint.EntityName); } } } } /// /// Renews the locks of a batch while the route runs: each time the earliest lock is half-way to its end, every lock /// is renewed, until maxAutoLockRenewalDuration has passed or the route returned (dispose). /// internal sealed class LockRenewal : IDisposable { private readonly CancellationTokenSource _cts = new(); internal LockRenewal(AzureServiceBusBatchConsumer owner, ServiceBusReceiver receiver, IReadOnlyList items) { _cts.CancelAfter(TimeSpan.FromSeconds(owner._options.MaxAutoLockRenewalDuration)); _ = RenewAsync(owner, receiver, items, _cts.Token); } private static async Task RenewAsync(AzureServiceBusBatchConsumer owner, ServiceBusReceiver receiver, IReadOnlyList items, CancellationToken ct) { var lockedUntil = items.Min(m => m.LockedUntil); try { while (!ct.IsCancellationRequested) { var wait = (lockedUntil - DateTimeOffset.UtcNow) / 2; await Task.Delay(wait > TimeSpan.FromSeconds(1) ? wait : TimeSpan.FromSeconds(1), ct).ConfigureAwait(false); var renewed = DateTimeOffset.MaxValue; foreach (var msg in items) { try { await receiver.RenewMessageLockAsync(msg, ct).ConfigureAwait(false); if (msg.LockedUntil < renewed) renewed = msg.LockedUntil; } catch (Exception ex) when (ex is not OperationCanceledException) { owner._logger?.LogWarning(ex, "ASB batch: renewing the lock of messageId={MessageId} failed", msg.MessageId); } } if (renewed != DateTimeOffset.MaxValue) lockedUntil = renewed; } } catch (OperationCanceledException) { // the route returned, or the renewal time is up } } public void Dispose() { _cts.Cancel(); _cts.Dispose(); } } }