Path: redb-route/redb.Route.AzureServiceBus/AzureServiceBusConsumer.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/AzureServiceBusConsumer.cs
----
using System.Collections.Concurrent;
using Azure.Messaging.ServiceBus;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Telemetry;
namespace redb.Route.AzureServiceBus;
///
/// Event-driven consumer using callback model.
/// Supports PeekLock with manual Complete/Abandon/DeadLetter and ReceiveAndDelete.
///
internal sealed class AzureServiceBusConsumer : IConsumer
{
private readonly AzureServiceBusEndpoint _endpoint;
private readonly IProcessor _pipeline;
private readonly AzureServiceBusEndpointOptions _options;
private readonly IHeaderFilterStrategy _headerFilter;
private readonly InflightDrainGuard _drain = new();
private ServiceBusProcessor? _processor;
private ILogger? _logger;
private AzureServiceBusConnectionWatch? _watch;
public IEndpoint? Endpoint => _endpoint;
internal AzureServiceBusConsumer(AzureServiceBusEndpoint endpoint, IProcessor pipeline,
AzureServiceBusEndpointOptions options)
{
ArgumentNullException.ThrowIfNull(endpoint);
ArgumentNullException.ThrowIfNull(pipeline);
ArgumentNullException.ThrowIfNull(options);
_endpoint = endpoint;
_pipeline = pipeline;
_options = options;
_headerFilter = endpoint.HeaderFilterStrategy;
}
public async Task Start(CancellationToken ct = default)
{
_logger ??= (_endpoint.Component as ComponentBase)?.Logger;
var client = await _endpoint.GetOrCreateClientAsync(ct).ConfigureAwait(false);
var processorOptions = new ServiceBusProcessorOptions
{
ReceiveMode = _options.ParsedReceiveMode,
MaxConcurrentCalls = _options.ResolvedMaxConcurrentCalls,
PrefetchCount = _options.PrefetchCount,
MaxAutoLockRenewalDuration = TimeSpan.FromSeconds(_options.MaxAutoLockRenewalDuration),
AutoCompleteMessages = false
};
if (_options.ParsedSubQueue is not null)
processorOptions.SubQueue = _options.ParsedSubQueue.Value;
_processor = _endpoint.IsTopic
? client.CreateProcessor(_endpoint.EntityName, _options.SubscriptionName, processorOptions)
: client.CreateProcessor(_endpoint.EntityName, processorOptions);
_processor.ProcessMessageAsync += OnMessageAsync;
_processor.ProcessErrorAsync += OnErrorAsync;
_watch = new AzureServiceBusConnectionWatch(_endpoint, client, _options.SubscriptionName, _logger, probe: true);
_drain.Start(ct);
try
{
await _processor.StartProcessingAsync(ct).ConfigureAwait(false);
}
catch
{
// The processor that did not start is let go, so a later Start creates one processor, not a second.
await _processor.DisposeAsync().ConfigureAwait(false);
_processor = null;
_drain.Dispose();
_watch.Stop();
_watch = null;
throw;
}
_logger?.LogInformation("ASB consumer started: entity={Entity}, ackMode={Mode}, concurrent={Concurrent}",
_endpoint.EntityName, _options.AckMode, _options.ResolvedMaxConcurrentCalls);
}
public async Task Stop(CancellationToken ct = default)
{
// First: a probe of a lost connection ends, so it never holds the stop.
_watch?.Stop();
_watch = null;
// The processor stops receiving and waits for the messages in work with no limit of its own, so the drain runs
// next to it: the messages in work end on the route's token, which only the drain timeout cancels, and are
// settled; then the stop returns.
var stopping = _processor?.StopProcessingAsync(ct) ?? Task.CompletedTask;
await _drain.DrainAsync(ct, _logger, $"asb:{_endpoint.EntityName}").ConfigureAwait(false);
await stopping.ConfigureAwait(false);
_drain.Dispose();
if (_processor is not null)
{
await _processor.DisposeAsync().ConfigureAwait(false);
_processor = null;
}
_logger?.LogInformation("ASB consumer stopped: entity={Entity}", _endpoint.EntityName);
}
// ── Message handling ──
private async Task OnMessageAsync(ProcessMessageEventArgs args)
{
_drain.Increment();
_watch?.Traffic();
// The receive span covers the whole unit of work, settlement included; the route's spans sit under it.
using var span = AzureServiceBusTrace.StartReceiveSpan(_endpoint, args.Message);
Exchange? exchange = null;
var pipelineFailed = false;
try
{
exchange = CreateExchange(args.Message);
// The lock is settled by this consumer below, after the whole unit of work ended well; the route
// transaction owns the database and the outgoing sends.
// No RecordMessageIn: the core's StatisticsProcessor around From() owns it (ownership audit).
try
{
await _pipeline.Process(exchange, _drain.ProcessingToken).ConfigureAwait(false);
}
catch
{
pipelineFailed = true;
throw;
}
if (exchange.Exception is { } failure && !exchange.ExceptionHandled)
AzureServiceBusTrace.RecordFailure(span.Activity, failure, _drain.ProcessingToken);
// Acknowledge (PeekLock): complete a unit of work that ended well, abandon or dead-letter one that did not.
if (_options.ParsedReceiveMode == ServiceBusReceiveMode.PeekLock)
{
await AcknowledgeAsync(args, exchange).ConfigureAwait(false);
}
}
catch (Exception ex)
{
AzureServiceBusTrace.RecordFailure(span.Activity, ex, _drain.ProcessingToken);
if (_options.ParsedReceiveMode == ServiceBusReceiveMode.PeekLock)
{
try
{
await args.AbandonMessageAsync(args.Message, cancellationToken: CancellationToken.None)
.ConfigureAwait(false);
}
catch (Exception abandonEx)
{
_logger?.LogWarning(abandonEx, "Failed to abandon ASB message");
}
}
// A pipeline failure is already counted by the core; only what the core cannot see
// (exchange building, settlement) is the transport's to record (ownership audit).
if (!pipelineFailed)
_endpoint.RecordError(ex);
throw;
}
finally
{
if (exchange is not null)
await exchange.DisposeAsync().ConfigureAwait(false);
_drain.Decrement();
}
}
private async Task AcknowledgeAsync(ProcessMessageEventArgs args, Exchange exchange)
{
if (exchange.Exception is not null && !exchange.ExceptionHandled)
{
if (_options.AutoDeadLetter)
{
await args.DeadLetterMessageAsync(args.Message,
_options.DeadLetterReason ?? "ProcessingError",
exchange.Exception.Message,
cancellationToken: CancellationToken.None).ConfigureAwait(false);
}
else
{
await args.AbandonMessageAsync(args.Message, cancellationToken: CancellationToken.None)
.ConfigureAwait(false);
}
}
else if (exchange.IsRollbackOnly())
{
// The route rolled the unit of work back (.RollbackAll()): not an error, the message is delivered again.
await args.AbandonMessageAsync(args.Message, cancellationToken: CancellationToken.None)
.ConfigureAwait(false);
}
else
{
await args.CompleteMessageAsync(args.Message, cancellationToken: CancellationToken.None)
.ConfigureAwait(false);
}
}
private Task OnErrorAsync(ProcessErrorEventArgs args)
{
// The client reconnects by itself and reports each failed receive here: a connection error is the supervisor's
// (health shows the loss), not a failed message.
if (args.ErrorSource != ServiceBusErrorSource.ProcessMessageCallback && _watch?.Report(args.Exception) == true)
{
_logger?.LogDebug(args.Exception, "ASB connection error on {EntityPath}: {Source}", args.EntityPath, args.ErrorSource);
return Task.CompletedTask;
}
_endpoint.RecordError(args.Exception);
_logger?.LogError(args.Exception, "ASB error on {EntityPath}: {Source}",
args.EntityPath, args.ErrorSource);
return Task.CompletedTask;
}
// ── Exchange creation ──
internal Exchange CreateExchange(ServiceBusReceivedMessage msg)
{
var message = new Message();
var exchange = Exchange.Create(message, _endpoint.ScopeFactory);
FillMessage(msg, message, exchange, _options, _headerFilter);
return exchange;
}
///
/// The body and headers of a received message: the Service Bus properties as redbAsb.* headers, the
/// application properties as the strategy lets them in against . One mapping for a single
/// message and for an element of a batch.
///
internal static void FillMessage(ServiceBusReceivedMessage msg, Message message, IExchange exchange,
AzureServiceBusEndpointOptions options, IHeaderFilterStrategy headerFilter)
{
message.Body = msg.Body.ToArray();
// Identity
SetIfNotEmpty(message, AzureServiceBusHeaders.MessageId, msg.MessageId);
SetIfNotEmpty(message, AzureServiceBusHeaders.CorrelationId, msg.CorrelationId);
SetIfNotEmpty(message, AzureServiceBusHeaders.SessionId, msg.SessionId);
SetIfNotEmpty(message, AzureServiceBusHeaders.PartitionKey, msg.PartitionKey);
SetIfNotEmpty(message, AzureServiceBusHeaders.ReplyToSessionId, msg.ReplyToSessionId);
// Metadata
SetIfNotEmpty(message, AzureServiceBusHeaders.Subject, msg.Subject);
SetIfNotEmpty(message, AzureServiceBusHeaders.ContentType, msg.ContentType);
SetIfNotEmpty(message, AzureServiceBusHeaders.ReplyTo, msg.ReplyTo);
SetIfNotEmpty(message, AzureServiceBusHeaders.To, msg.To);
if (msg.ContentType is not null)
message.ContentType = msg.ContentType;
message.Headers[AzureServiceBusHeaders.TimeToLive] = msg.TimeToLive;
// Scheduling
message.Headers[AzureServiceBusHeaders.ScheduledEnqueueTime] = msg.ScheduledEnqueueTime;
message.Headers[AzureServiceBusHeaders.SequenceNumber] = msg.SequenceNumber;
// Consumer metadata
message.Headers[AzureServiceBusHeaders.DeliveryCount] = msg.DeliveryCount;
message.Headers[AzureServiceBusHeaders.EnqueuedTime] = msg.EnqueuedTime;
message.Headers[AzureServiceBusHeaders.ExpiresAt] = msg.ExpiresAt;
if (options.ParsedReceiveMode == ServiceBusReceiveMode.PeekLock)
message.Headers[AzureServiceBusHeaders.LockedUntil] = msg.LockedUntil;
// Dead-letter metadata
SetIfNotEmpty(message, AzureServiceBusHeaders.DeadLetterSource, msg.DeadLetterSource);
SetIfNotEmpty(message, AzureServiceBusHeaders.DeadLetterReason, msg.DeadLetterReason);
SetIfNotEmpty(message, AzureServiceBusHeaders.DeadLetterErrorDescription, msg.DeadLetterErrorDescription);
// Application properties → exchange headers, as the endpoint's strategy lets them in
foreach (var kv in msg.ApplicationProperties)
{
if (kv.Value is null) continue;
if (headerFilter.FilterIncoming(kv.Key, kv.Value, exchange)) continue;
message.Headers[kv.Key] = kv.Value;
}
}
private static void SetIfNotEmpty(IMessage message, string key, string? value)
{
if (!string.IsNullOrEmpty(value))
message.Headers[key] = value;
}
}