Bundle: redb-route / redb.Route.AzureServiceBus (redb.Route.AzureServiceBus.txt), 17 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.AzureServiceBus/AzureServiceBusAckAction.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/AzureServiceBusAckAction.cs ---- using Azure.Messaging.ServiceBus; using redb.Route.Abstractions; namespace redb.Route.AzureServiceBus; /// /// Deferred complete/abandon for non-session transacted consumer. /// Registered via exchange.Properties["TRANSACT_ACTION"]. /// internal sealed class AzureServiceBusAckAction : ITransactedAction { private readonly ProcessMessageEventArgs _args; internal AzureServiceBusAckAction(ProcessMessageEventArgs args) { _args = args; } /// public async Task Commit(CancellationToken ct = default) { await _args.CompleteMessageAsync(_args.Message, ct).ConfigureAwait(false); } /// public async Task Rollback(CancellationToken ct = default) { await _args.AbandonMessageAsync(_args.Message, cancellationToken: ct).ConfigureAwait(false); } } /// /// Deferred complete/abandon for session-aware transacted consumer. /// internal sealed class AzureServiceBusSessionAckAction : ITransactedAction { private readonly ProcessSessionMessageEventArgs _args; internal AzureServiceBusSessionAckAction(ProcessSessionMessageEventArgs args) { _args = args; } /// public async Task Commit(CancellationToken ct = default) { await _args.CompleteMessageAsync(_args.Message, ct).ConfigureAwait(false); } /// public async Task Rollback(CancellationToken ct = default) { await _args.AbandonMessageAsync(_args.Message, cancellationToken: ct).ConfigureAwait(false); } } 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(); } } } Path: redb-route/redb.Route.AzureServiceBus/AzureServiceBusComponent.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/AzureServiceBusComponent.cs ---- using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.AzureServiceBus; /// /// Azure Service Bus component. Scheme: asb. /// /// URI format: asb://queue-name?connectionString=... /// asb://topic-name?connectionString=...&subscriptionName=my-sub /// /// public sealed class AzureServiceBusComponent : ComponentBase { /// public override string Scheme => "asb"; /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var options = new AzureServiceBusEndpointOptions(); options.BindFromUri(uri.RawParameters); options.Validate(); options.ResolveBatch(EndpointUri.Sanitize(uri.BaseKey)); return new AzureServiceBusEndpoint(uri, this, options); } } Path: redb-route/redb.Route.AzureServiceBus/AzureServiceBusConnectionFactory.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/AzureServiceBusConnectionFactory.cs ---- using Azure.Messaging.ServiceBus; using redb.Route.Core; namespace redb.Route.AzureServiceBus; /// /// POCO factory for creating instances. /// Register in the route context registry for shared client configuration: /// context.AddToRegistry("myAsb", new AzureServiceBusConnectionFactory { ... }); /// Reference from URI: asb://queue?connectionFactory=myAsb /// public sealed class AzureServiceBusConnectionFactory { /// Azure Service Bus connection string. [Sensitive] public string ConnectionString { get; set; } = ""; /// Maximum number of retries (default 3). public int MaxRetries { get; set; } = 3; /// Initial retry delay in milliseconds (default 800). public int DelayMs { get; set; } = 800; /// Maximum retry delay in milliseconds (default 60000). public int MaxDelayMs { get; set; } = 60_000; /// Retry mode: Exponential or Fixed (default Exponential). public ServiceBusRetryMode RetryMode { get; set; } = ServiceBusRetryMode.Exponential; /// Per-try timeout in milliseconds (default 60000). public int TryTimeoutMs { get; set; } = 60_000; /// Transport type: AmqpTcp or AmqpWebSockets (default AmqpTcp). public ServiceBusTransportType TransportType { get; set; } = ServiceBusTransportType.AmqpTcp; /// Web proxy address. Forces AmqpWebSockets transport when set. public string? ProxyAddress { get; set; } /// Builds a configured . public ServiceBusClient Build() { var options = new ServiceBusClientOptions { TransportType = TransportType, RetryOptions = new ServiceBusRetryOptions { Mode = RetryMode, MaxRetries = MaxRetries, Delay = TimeSpan.FromMilliseconds(DelayMs), MaxDelay = TimeSpan.FromMilliseconds(MaxDelayMs), TryTimeout = TimeSpan.FromMilliseconds(TryTimeoutMs) } }; if (!string.IsNullOrWhiteSpace(ProxyAddress)) { options.TransportType = ServiceBusTransportType.AmqpWebSockets; options.WebProxy = new System.Net.WebProxy(ProxyAddress); } return new ServiceBusClient(ConnectionString, options); } } Path: redb-route/redb.Route.AzureServiceBus/AzureServiceBusConnectionWatch.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/AzureServiceBusConnectionWatch.cs ---- using System.Net.Sockets; using Azure.Messaging.ServiceBus; using Microsoft.Extensions.Logging; using redb.Route.Core; namespace redb.Route.AzureServiceBus; /// /// The connection of one Service Bus consumer as its endpoint's health sees it. The client reconnects by itself and /// reports each failed receive, but it has no "connection back" event. So an error of the connection goes to a /// (health shows the loss; it is not counted as a failed message), and the recovery /// comes from the next successful receive or from a read-only probe on the supervisor's schedule, whichever is first. The /// probe peeks the entity's dead-letter queue through the consumer's own client: it needs only the Listen right the /// consumer has, locks nothing, and works on a session entity too (its dead-letter queue has no sessions). It runs only /// while the connection is lost. While connected, any other error (an entity that does not exist, a refused claim) is /// recorded on the endpoint as before: it is not a connection being retried. While lost, every error of a receive is the /// loss's and shows as its reason. /// internal sealed class AzureServiceBusConnectionWatch { /// How long one probe waits for the namespace's answer. internal static readonly TimeSpan ProbeTimeout = TimeSpan.FromSeconds(10); private readonly AzureServiceBusEndpoint _endpoint; private readonly ILogger? _logger; private readonly ConnectionSupervisor _supervisor; private readonly Func? _probe; private readonly string? _subscription; private readonly CancellationTokenSource _stop = new(); private int _probing; /// The endpoint whose health shows the connection. /// The consumer's client: the probe peeks through it. /// The subscription a topic consumer reads; null for a queue. /// The consumer's logger. /// /// Whether to probe while lost. A consumer that receives in its own loop (the batch receiver) learns of the /// recovery from that loop and needs none. /// public AzureServiceBusConnectionWatch(AzureServiceBusEndpoint endpoint, ServiceBusClient client, string? subscription, ILogger? logger, bool probe) { _endpoint = endpoint; _logger = logger; _subscription = subscription; _supervisor = endpoint.Supervise($"asb:{endpoint.EntityName} consumer", logger); if (probe) _probe = ct => PeekDeadLetterAsync(client, ct); } /// The supervisor of the connection. public ConnectionSupervisor Supervisor => _supervisor; /// /// Whether is the connection's, not a message's or a refusal: a communication problem the /// client reports, or a socket or I/O failure under it. /// public static bool IsConnectionError(Exception error) { if (error is ServiceBusException { Reason: ServiceBusFailureReason.ServiceCommunicationProblem }) return true; if (error is ServiceBusException) return false; for (var e = error; e is not null; e = e.InnerException) { if (e is SocketException or IOException) return true; } return false; } /// /// Takes an error of the client: a connection error goes to the supervisor (the first shows the loss and starts the /// probe, the later ones are attempts that failed) and true is returned. While the connection is lost, any /// error of a receive belongs to the loss too (a session lock dies with the connection; a namespace that is coming /// back may not serve the entity yet): it becomes the reason health shows, not a failed message. Once connected, any /// other error is left to the caller (false), which records it on the endpoint. A lost session lock is neither: /// the session processor accepts a session again by itself, and a message it cut short is counted where it failed. /// public bool Report(Exception error) { if (error is ServiceBusException { Reason: ServiceBusFailureReason.SessionLockLost }) { if (_supervisor.State != ConnectionState.Connected) _supervisor.Lost(error); return true; } if (!IsConnectionError(error)) { if (_supervisor.State == ConnectionState.Connected) return false; if (_probe is null) _supervisor.Failed(error); else _supervisor.Lost(error); return true; } if (_supervisor.Lost(error)) { StartProbe(); } else if (_probe is null) { // No probe makes the attempts: the client's own failed receive is one. _supervisor.Failed(error); } return true; } /// A receive succeeded, so the connection is there. Cheap while connected. public void Traffic() { if (_supervisor.State != ConnectionState.Connected) _supervisor.Restored(); } /// Ends a running probe and stops reporting to the endpoint. public void Stop() { _stop.Cancel(); _endpoint.Unsupervise(_supervisor); } private void StartProbe() { if (_probe is null || Interlocked.CompareExchange(ref _probing, 1, 0) != 0) return; var stop = _stop.Token; _ = Task.Run(async () => { try { await _supervisor.ReconnectAsync(ProbeAsync, stop).ConfigureAwait(false); } catch (Exception ex) { _logger?.LogDebug(ex, "ASB consumer on {Entity}: the probe ended", _endpoint.EntityName); } finally { Volatile.Write(ref _probing, 0); } }, CancellationToken.None); } // Asks nothing once the connection is back: a receive restored it meanwhile. private Task ProbeAsync(CancellationToken ct) => _supervisor.State == ConnectionState.Connected ? Task.CompletedTask : _supervisor.AttemptAsync(async c => { await _probe!(c).ConfigureAwait(false); return true; }, static _ => { }, ct); private async Task PeekDeadLetterAsync(ServiceBusClient client, CancellationToken ct) { using var bounded = CancellationTokenSource.CreateLinkedTokenSource(ct); bounded.CancelAfter(ProbeTimeout); var options = new ServiceBusReceiverOptions { SubQueue = SubQueue.DeadLetter }; await using var receiver = _endpoint.IsTopic ? client.CreateReceiver(_endpoint.EntityName, _subscription, options) : client.CreateReceiver(_endpoint.EntityName, options); try { await receiver.PeekMessageAsync(cancellationToken: bounded.Token).ConfigureAwait(false); } catch (OperationCanceledException) when (!ct.IsCancellationRequested) { throw new TimeoutException( $"asb:{_endpoint.EntityName}: the namespace did not answer a peek within {ProbeTimeout.TotalSeconds:0} s."); } } } 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; } } Path: redb-route/redb.Route.AzureServiceBus/AzureServiceBusEndpoint.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/AzureServiceBusEndpoint.cs ---- using Azure.Messaging.ServiceBus; using redb.Route.Abstractions; using redb.Route.Extensions; using redb.Route.Core; namespace redb.Route.AzureServiceBus; /// /// Azure Service Bus endpoint. Manages shared lifecycle. /// Queue/topic name comes from . /// internal sealed class AzureServiceBusEndpoint : EndpointBase { private ServiceBusClient? _client; /// /// Creates the client instead of the connection factory or the URI options when set: a test sets a fake here to /// drive a processor that fails to start without a namespace. /// internal Func? ClientSource { get; set; } private readonly SemaphoreSlim _clientLock = new(1, 1); internal AzureServiceBusEndpoint(EndpointUri uri, AzureServiceBusComponent component, AzureServiceBusEndpointOptions options) : base(uri, component, options) { _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(AzureServiceBusHeaderFilterStrategy.Default); /// Queue or topic name resolved from options or URI path. internal string EntityName => Options.QueueName ?? Options.TopicName ?? Uri.Path; /// True when a subscription name is set (topic mode). internal bool IsTopic => !string.IsNullOrEmpty(Options.SubscriptionName); /// /// Returns a shared for this endpoint. /// Thread-safe; ServiceBusClient is designed for long-lived reuse. /// 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 (ClientSource is { } source) { _client = source(); return _client; } if (!string.IsNullOrWhiteSpace(Options.ConnectionFactory)) { // A set-but-unknown name fails loud — a typo must never silently // fall back to URI parameters. var context = (Component as ComponentBase)?.Context; var factory = context.GetRequiredFromRegistry( Options.ConnectionFactory); _client = factory.Build(); return _client; } _client = BuildClientFromOptions(); return _client; } finally { _clientLock.Release(); } } /// public override IProducer CreateProducer() => new AzureServiceBusProducer(this, Options); /// public override IConsumer CreateConsumer(IProcessor processor) { if (Options.Batch is { } batch) return new AzureServiceBusBatchConsumer(this, processor, Options, batch); if (Options.EnableSessions) return new AzureServiceBusSessionConsumer(this, processor, Options); return new AzureServiceBusConsumer(this, processor, Options); } /// public override async Task Stop(CancellationToken ct = default) { if (_client is not null) { await _client.DisposeAsync().ConfigureAwait(false); _client = null; } await base.Stop(ct).ConfigureAwait(false); } private ServiceBusClient BuildClientFromOptions() { var clientOptions = new ServiceBusClientOptions { RetryOptions = new ServiceBusRetryOptions { Mode = Options.ParsedRetryMode, MaxRetries = Options.RetryMaxRetries, Delay = TimeSpan.FromMilliseconds(Options.RetryDelayMs), MaxDelay = TimeSpan.FromMilliseconds(Options.RetryMaxDelayMs) } }; return new ServiceBusClient(Options.ConnectionString, clientOptions); } } Path: redb-route/redb.Route.AzureServiceBus/AzureServiceBusEndpointOptions.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/AzureServiceBusEndpointOptions.cs ---- using Azure.Messaging.ServiceBus; using redb.Route.Abstractions; using redb.Route.Batching; using redb.Route.Core; namespace redb.Route.AzureServiceBus; /// /// Endpoint options for Azure Service Bus. Bound from URI query parameters. /// public sealed class AzureServiceBusEndpointOptions : EndpointOptions { // ── Connection ── /// Azure Service Bus connection string. [Sensitive] public string ConnectionString { get; set; } = ""; /// Named connection factory from route context registry. [RegistryReference(typeof(AzureServiceBusConnectionFactory))] public string? ConnectionFactory { get; set; } /// /// A registry reference (#name) to an that /// decides which headers this endpoint carries between the exchange and a message's application properties, in /// place of . /// [RegistryReference(typeof(IHeaderFilterStrategy))] public string? HeaderFilterStrategy { get; set; } // ── Entity ── /// Explicit queue name (overrides URI path). public string? QueueName { get; set; } /// Explicit topic name (overrides URI path). public string? TopicName { get; set; } /// Topic subscription name. When set, the entity is treated as a topic. public string? SubscriptionName { get; set; } // ── Consumer: Receive mode ── /// /// When a message is settled (). Manual (default): received with PeekLock and /// completed after a turn that ended well, abandoned on failure (at-least-once). Auto: received with /// ReceiveAndDelete, the broker removes it on hand-off (at-most-once). /// public AckMode AckMode { get; set; } = AckMode.Manual; /// protected override string? UnknownParameterHint(string name) => name.Equals("enableBatch", StringComparison.OrdinalIgnoreCase) || name.Equals("batchMaxMessages", StringComparison.OrdinalIgnoreCase) ? $"'{name}' is gone: any list body is sent as one Service Bus batch, one message per element (a list of IMessage " + "with each element's own body and properties), as in Apache Camel; batchMaxSizeBytes bounds it." : name.Equals("receiveMode", StringComparison.OrdinalIgnoreCase) ? "'receiveMode' is replaced by 'ackMode': ackMode=manual (the default) is PeekLock, ackMode=auto is ReceiveAndDelete." : null; /// Maximum concurrent handler invocations: a number or "auto" (= max(CPU, 2)). Default 1. // A string so "auto" binds verbatim instead of silently degrading to the int default. public string? MaxConcurrentCalls { get; set; } /// Resolved handler parallelism (see ). public int ResolvedMaxConcurrentCalls => ConcurrencyOption.Resolve(MaxConcurrentCalls, "maxConcurrentCalls"); /// Number of messages to pre-fetch into local buffer (default 0). public int PrefetchCount { get; set; } /// Maximum auto lock renewal duration in seconds (default 300 = 5 min). public int MaxAutoLockRenewalDuration { get; set; } = 300; /// Sub-queue to consume from: "deadletter" or "transferdeadletter". public string? SubQueue { get; set; } // ── Consumer: Sessions ── /// Enable session-aware consumer (default false). public bool EnableSessions { get; set; } /// Fixed session ID filter. Null = accept any session. public string? SessionId { get; set; } /// Maximum concurrent session handlers (default 1). public int MaxConcurrentSessions { get; set; } = 1; /// Session idle timeout in seconds. 0 = SDK default. public int SessionIdleTimeout { get; set; } // ── Consumer: Error handling ── /// Automatically dead-letter messages on processing error (default false). public bool AutoDeadLetter { get; set; } /// Dead-letter reason string when AutoDeadLetter is enabled. public string? DeadLetterReason { get; set; } // ── Consumer: Batch mode ── /// /// Batch mode (Apache Camel batching, the batch contract of every broker of redb.Route): the route gets one /// InOnly exchange whose body is a List<IMessage> of up to messages, /// received with ReceiveMessagesAsync and settled once after the route: completed on success; on failure each /// is abandoned, or dead-lettered with , as a failed single message is. /// public bool Batching { get; set; } /// Largest number of messages in a batch (default 100). 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 /// message (default 1000). /// 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 batch options, or null outside batch mode. Set by . internal BatchOptions? Batch { get; private set; } /// The default of . internal const int DefaultMaxBatchMessages = 100; /// /// Resolves the batch options. Fails, naming the endpoint, where batch mode cannot work: a batch option without /// batching=true, a value out of range, and a session entity (): its messages are /// received and settled per session, and the batch consumer reads the entity's plain receiver. /// internal void ResolveBatch(string endpoint) { Batch = BatchOptions.Resolve(endpoint, Batching, MaxBatchMessages, PollTimeoutMs, BatchingIntervalMs, DefaultMaxBatchMessages); if (Batch is not null && EnableSessions) throw new InvalidOperationException( $"Endpoint '{endpoint}': batching=true cannot be combined with enableSessions=true: the messages of a session " + "entity are received and settled per session. Consume the session entity message by message."); } // ── Producer: Transacted ── /// /// 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, outside the block's transaction. A consumer always settles the /// delivery itself once the route has finished, so the option does not apply to it. /// public bool? Transacted { get; set; } /// /// Producer: the sends it defers in a .Transacted() block leave as one Service Bus batch when the block /// commits — Service Bus takes a batch to one entity whole or not at all — so they arrive together or not at all. /// The block's messages must fit in one batch (, and the entity's own limit); a block /// whose messages do not fit fails its commit and sends nothing. On a partitioned or session entity the messages of /// one batch must share the partition key or session id. Unset, the deferred sends go out one after the other. /// public bool BatchCommit { get; set; } // ── Producer: Send ── /// Dynamic message ID expression (supports ${...}). public DynamicValue? MessageId { get; set; } /// Dynamic session ID for producer (supports ${...}). public DynamicValue? ProducerSessionId { get; set; } /// Partition key for batching. public string? PartitionKey { get; set; } /// Delayed delivery in seconds (default 0 = immediate). public int ScheduleDelaySeconds { get; set; } /// Message TTL as TimeSpan string (e.g. "00:05:00"). public string? TimeToLive { get; set; } // ── Producer: a list body ── /// /// Maximum size in bytes of the one Service Bus batch a list body or a block is sent as /// (default 256 KB). Messages that do not fit fail the send: nothing is dropped silently. /// public long BatchMaxSizeBytes { get; set; } = 256 * 1024; // ── Client retry settings ── /// Maximum retry count (default 3). public int RetryMaxRetries { get; set; } = 3; /// Initial retry delay in milliseconds (default 800). public int RetryDelayMs { get; set; } = 800; /// Maximum retry delay in milliseconds (default 60000). public int RetryMaxDelayMs { get; set; } = 60_000; /// Retry mode: Exponential (default) or Fixed. public string RetryMode { get; set; } = "Exponential"; // ── Validation ── /// public override void Validate() { if (string.IsNullOrWhiteSpace(ConnectionString) && string.IsNullOrWhiteSpace(ConnectionFactory)) throw new ArgumentOutOfRangeException(nameof(ConnectionString), "ConnectionString or ConnectionFactory is required"); _ = ConcurrencyOption.Resolve(MaxConcurrentCalls, "maxConcurrentCalls"); // loud on garbage if (PrefetchCount < 0) throw new ArgumentOutOfRangeException(nameof(PrefetchCount), "Must be >= 0"); if (MaxAutoLockRenewalDuration < 0) throw new ArgumentOutOfRangeException(nameof(MaxAutoLockRenewalDuration), "Must be >= 0"); if (MaxConcurrentSessions < 1) throw new ArgumentOutOfRangeException(nameof(MaxConcurrentSessions), "Must be >= 1"); if (!string.IsNullOrWhiteSpace(SubQueue) && !SubQueue.Equals("deadletter", StringComparison.OrdinalIgnoreCase) && !SubQueue.Equals("transferdeadletter", StringComparison.OrdinalIgnoreCase)) throw new ArgumentOutOfRangeException(nameof(SubQueue), "Must be deadletter or transferdeadletter"); if (BatchMaxSizeBytes < 1) throw new ArgumentOutOfRangeException(nameof(BatchMaxSizeBytes), "Must be >= 1"); if (BatchCommit && Transacted == false) throw new ArgumentException( "'batchCommit' sends the messages deferred in a .Transacted() block as one batch, and 'transacted=false' " + "sends at once, deferring none. Drop one of the two."); if (!RetryMode.Equals("Exponential", StringComparison.OrdinalIgnoreCase) && !RetryMode.Equals("Fixed", StringComparison.OrdinalIgnoreCase)) throw new ArgumentOutOfRangeException(nameof(RetryMode), "Must be Exponential or Fixed"); } // ── Internal helpers ── /// Parsed receive mode enum. internal ServiceBusReceiveMode ParsedReceiveMode => AckMode == AckMode.Auto ? ServiceBusReceiveMode.ReceiveAndDelete : ServiceBusReceiveMode.PeekLock; /// Parsed sub-queue enum. internal Azure.Messaging.ServiceBus.SubQueue? ParsedSubQueue => SubQueue?.ToLowerInvariant() switch { "deadletter" => Azure.Messaging.ServiceBus.SubQueue.DeadLetter, "transferdeadletter" => Azure.Messaging.ServiceBus.SubQueue.TransferDeadLetter, _ => null }; /// Parsed retry mode enum. internal ServiceBusRetryMode ParsedRetryMode => RetryMode.Equals("Fixed", StringComparison.OrdinalIgnoreCase) ? ServiceBusRetryMode.Fixed : ServiceBusRetryMode.Exponential; } Path: redb-route/redb.Route.AzureServiceBus/AzureServiceBusHeaderFilterStrategy.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/AzureServiceBusHeaderFilterStrategy.cs ---- using redb.Route.Abstractions; namespace redb.Route.AzureServiceBus; /// /// The default of the Azure Service Bus 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 redbAsb.* and null values as application /// properties; a consumer (plain and session alike) brings every application property in. Whatever the strategy, the /// producer reads the message's system properties (MessageId, SessionId, Subject...) from the /// redbAsb.* headers, the consumer sets them and the delivery metadata, and trace context is written by the /// telemetry layer. /// /// public class AzureServiceBusHeaderFilterStrategy : IHeaderFilterStrategy { /// The default strategy of an Azure Service Bus endpoint. public static AzureServiceBusHeaderFilterStrategy Default { get; } = new(); /// public virtual bool FilterOutgoing(string name, object? value, IExchange exchange) => value is null || AzureServiceBusHeaders.IsAsbHeader(name); /// public virtual bool FilterIncoming(string name, object? value, IExchange exchange) => false; } Path: redb-route/redb.Route.AzureServiceBus/AzureServiceBusHeaders.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/AzureServiceBusHeaders.cs ---- namespace redb.Route.AzureServiceBus; /// /// Header constants for Azure Service Bus connector. Prefix: redbAsb. /// Maps to ServiceBusMessage / ServiceBusReceivedMessage properties. /// public static class AzureServiceBusHeaders { /// Header prefix for all Azure Service Bus headers. public const string Prefix = "redbAsb."; // ── Message identity ── /// Unique message identifier. public const string MessageId = "redbAsb.MessageId"; /// Correlation identifier for request-reply. public const string CorrelationId = "redbAsb.CorrelationId"; /// Session identifier (FIFO ordering key). public const string SessionId = "redbAsb.SessionId"; /// Partition key for batching within a partition. public const string PartitionKey = "redbAsb.PartitionKey"; /// Reply-to session identifier for RPC over sessions. public const string ReplyToSessionId = "redbAsb.ReplyToSessionId"; // ── Message metadata ── /// Message subject (label). public const string Subject = "redbAsb.Subject"; /// Content type of the message body. public const string ContentType = "redbAsb.ContentType"; /// Reply-to address for RPC. public const string ReplyTo = "redbAsb.ReplyTo"; /// Destination address (informational). public const string To = "redbAsb.To"; /// Message time-to-live as TimeSpan string. public const string TimeToLive = "redbAsb.TimeToLive"; // ── Scheduling ── /// Scheduled enqueue time (DateTimeOffset). public const string ScheduledEnqueueTime = "redbAsb.ScheduledEnqueueTime"; /// Sequence number assigned by the broker. public const string SequenceNumber = "redbAsb.SequenceNumber"; // ── Consumer-only (received message metadata) ── /// Number of delivery attempts. public const string DeliveryCount = "redbAsb.DeliveryCount"; /// Time the message was enqueued (DateTimeOffset). public const string EnqueuedTime = "redbAsb.EnqueuedTime"; /// Time the message expires (DateTimeOffset). public const string ExpiresAt = "redbAsb.ExpiresAt"; /// Time the lock expires (DateTimeOffset, PeekLock only). public const string LockedUntil = "redbAsb.LockedUntil"; /// Lock token string (PeekLock only). public const string LockToken = "redbAsb.LockToken"; // ── Dead-letter ── /// Original entity that dead-lettered the message. public const string DeadLetterSource = "redbAsb.DeadLetterSource"; /// Reason the message was dead-lettered. public const string DeadLetterReason = "redbAsb.DeadLetterReason"; /// Error description when dead-lettered. public const string DeadLetterErrorDescription = "redbAsb.DeadLetterErrorDescription"; // ── Session state ── /// Session state (BinaryData serialized). public const string SessionState = "redbAsb.SessionState"; // ── Batch producer ── /// Number of messages in a sent batch. public const string BatchMessageCount = "redbAsb.BatchMessageCount"; /// Checks if a header key belongs to the Azure Service Bus connector. public static bool IsAsbHeader(string key) => key.StartsWith(Prefix, StringComparison.Ordinal); } Path: redb-route/redb.Route.AzureServiceBus/AzureServiceBusProducer.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/AzureServiceBusProducer.cs ---- using System.Collections; using System.Diagnostics; using System.Text.Json; using System.Transactions; using Azure.Messaging.ServiceBus; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; using redb.Route.Transactions; namespace redb.Route.AzureServiceBus; /// /// Sends messages to an Azure Service Bus queue or topic. /// Supports single send, batch send, and scheduled delivery. /// internal sealed class AzureServiceBusProducer : ConnectableProducer { private readonly AzureServiceBusEndpoint _endpoint; private readonly AzureServiceBusEndpointOptions _options; private readonly IHeaderFilterStrategy _headerFilter; private readonly string _batchKey = $"asb-batch-{Guid.NewGuid():N}"; private ServiceBusSender? _sender; protected override IEndpoint ProducerEndpoint => _endpoint; protected override string ProducerName => _endpoint.Uri.NormalizedKey; internal AzureServiceBusProducer(AzureServiceBusEndpoint endpoint, AzureServiceBusEndpointOptions options) { _endpoint = endpoint; _options = options; _headerFilter = endpoint.HeaderFilterStrategy; } protected override async Task ConnectAsync(CancellationToken ct) { var client = await _endpoint.GetOrCreateClientAsync(ct).ConfigureAwait(false); _sender = client.CreateSender(_endpoint.EntityName); } protected override async Task DisconnectAsync(CancellationToken ct) { if (_sender is not null) { await _sender.DisposeAsync().ConfigureAwait(false); _sender = null; } } public override async Task Process(IExchange exchange, CancellationToken ct) { EnsureStarted(); using var activity = RouteTelemetryExtensions.StartTransportSpan( (_endpoint.Component as ComponentBase)?.Context, $"{_endpoint.EntityName} send", ActivityKind.Producer, "messaging.system", "azureservicebus", _endpoint.Uri.NormalizedKey, destination: _endpoint.EntityName, operation: "send"); // A list is sent as one Service Bus batch, one message per element, as Camel's azure-servicebus sends an // Iterable body: a list of IMessage with each element's own body and headers, a plain list with each value as // the body under the exchange's headers. var body = exchange.In.Body; var elements = (IEnumerable?)ListBody.Messages(body) ?? (ListBody.IsPlainList(body) ? (IEnumerable)body! : null); var defers = TransactedActions.Defers(exchange, _options.Transacted); if (defers && _options.BatchCommit) { // The block's sends through this producer leave as one Service Bus batch when the block commits. var messages = elements is not null ? await BuildListMessagesAsync(exchange, elements, activity).ConfigureAwait(false) : [BuildSingle(exchange, activity)]; if (elements is not null) exchange.In.Headers[AzureServiceBusHeaders.BatchMessageCount] = messages.Count; TransactedActions.JoinBatch(exchange, _batchKey, () => new AzureServiceBusSendBatch(this), ProducerName) .Add(messages); return; } // The messages 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. var send = elements is not null ? PrepareList(exchange, await BuildListMessagesAsync(exchange, elements, activity).ConfigureAwait(false)) : PrepareSingle(exchange, activity); if (defers) { TransactedActions.RegisterSend(exchange, $"asb-send-{Guid.NewGuid():N}", send, ProducerName); return; } // The Service Bus client enlists a send in the ambient System.Transactions transaction on its own. A send that // goes out at once must not: it would wait for the block's commit, and next to a database in the same block it // would escalate the transaction to a distributed one. using (new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled)) { try { await send(ct).ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested) { activity.RecordFailure(ex); throw; } } } // ── Single send ── private Func PrepareSingle(IExchange exchange, Activity? activity) { var msg = BuildSingle(exchange, activity); return async ct => { await _sender!.SendMessageAsync(msg, ct).ConfigureAwait(false); _endpoint.RecordBytesOut(msg.Body.ToMemory().Length); }; } private ServiceBusMessage BuildSingle(IExchange exchange, Activity? activity) { var msg = BuildMessage(exchange, activity); exchange.In.Headers[AzureServiceBusHeaders.MessageId] = msg.MessageId; return msg; } // ── List send ── private Func PrepareList(IExchange exchange, List messages) => async ct => { await SendAsOneBatchAsync(messages, "this list body", ct).ConfigureAwait(false); exchange.In.Headers[AzureServiceBusHeaders.BatchMessageCount] = messages.Count; }; /// /// One message per element of a list body, each built from its element's exchange (): /// an element with its own body and headers, its own message id when it carries one; a plain /// value with the exchange's headers and a message id of its own, so the entity's duplicate detection does not take /// the elements for one message. /// private async Task> BuildListMessagesAsync(IExchange exchange, IEnumerable elements, Activity? activity) { var messages = new List(); foreach (var element in elements) { var source = ListBody.ElementExchange(exchange, element); try { var msg = BuildMessage(source, activity); if (element is not IMessage) msg.MessageId = Guid.NewGuid().ToString(); messages.Add(msg); } finally { if (source is IAsyncDisposable disposable) await disposable.DisposeAsync().ConfigureAwait(false); } } activity?.SetTag("messaging.batch.message_count", messages.Count); return messages; } /// /// Sends as one Service Bus batch: the entity takes it whole or not at all. Messages that /// do not fit in one batch fail the send before anything leaves: they used to be dropped without a word. /// internal async Task SendAsOneBatchAsync(IReadOnlyList messages, string what, CancellationToken ct) { var sender = _sender ?? throw new InvalidOperationException( $"'{ProducerName}' is stopped: the messages cannot be sent."); using var batch = await sender.CreateMessageBatchAsync( new CreateMessageBatchOptions { MaxSizeInBytes = _options.BatchMaxSizeBytes }, ct).ConfigureAwait(false); foreach (var msg in messages) { if (!batch.TryAddMessage(msg)) throw new InvalidOperationException( $"The {messages.Count} messages of {what} do not fit in one Service Bus batch of {batch.MaxSizeInBytes} " + $"bytes through '{ProducerName}': nothing was sent. Raise batchMaxSizeBytes up to the entity's limit, " + "or send less at once."); } if (batch.Count > 0) { await sender.SendMessagesAsync(batch, ct).ConfigureAwait(false); long sent = 0; foreach (var msg in messages) sent += msg.Body.ToMemory().Length; _endpoint.RecordBytesOut(sent); } } // ── Message building ── private ServiceBusMessage BuildMessage(IExchange exchange, Activity? activity) { var data = ResolveBodyData(exchange.In.Body ?? throw new InvalidOperationException("Body is null; cannot send an empty message.")); var msg = new ServiceBusMessage(data); ApplyProperties(msg, exchange, activity); return msg; } /// /// Maps native Service Bus properties and application properties from exchange headers/options. /// Shared by single and batch send so batched messages carry the same metadata, the trace context of /// included. /// private void ApplyProperties(ServiceBusMessage msg, IExchange exchange, Activity? activity) { // Identity msg.MessageId = ResolveHeader(exchange, AzureServiceBusHeaders.MessageId) ?? _options.MessageId?.Resolve(exchange) ?? Guid.NewGuid().ToString(); msg.CorrelationId = ResolveHeader(exchange, AzureServiceBusHeaders.CorrelationId) ?? ""; msg.SessionId = ResolveHeader(exchange, AzureServiceBusHeaders.SessionId) ?? _options.ProducerSessionId?.Resolve(exchange) ?? ""; var partitionKey = ResolveHeader(exchange, AzureServiceBusHeaders.PartitionKey) ?? _options.PartitionKey; if (!string.IsNullOrEmpty(partitionKey) && string.IsNullOrEmpty(msg.SessionId)) msg.PartitionKey = partitionKey; msg.ReplyToSessionId = ResolveHeader(exchange, AzureServiceBusHeaders.ReplyToSessionId) ?? ""; // Metadata msg.Subject = ResolveHeader(exchange, AzureServiceBusHeaders.Subject) ?? ""; msg.ContentType = ResolveHeader(exchange, AzureServiceBusHeaders.ContentType) ?? exchange.In.ContentType ?? ""; msg.ReplyTo = ResolveHeader(exchange, AzureServiceBusHeaders.ReplyTo) ?? ""; msg.To = ResolveHeader(exchange, AzureServiceBusHeaders.To) ?? ""; // TTL if (!string.IsNullOrEmpty(_options.TimeToLive)) msg.TimeToLive = TimeSpan.Parse(_options.TimeToLive, System.Globalization.CultureInfo.InvariantCulture); if (ResolveHeader(exchange, AzureServiceBusHeaders.TimeToLive) is { } ttlStr && !string.IsNullOrEmpty(ttlStr)) msg.TimeToLive = TimeSpan.Parse(ttlStr, System.Globalization.CultureInfo.InvariantCulture); // Scheduling if (_options.ScheduleDelaySeconds > 0) msg.ScheduledEnqueueTime = DateTimeOffset.UtcNow.AddSeconds(_options.ScheduleDelaySeconds); if (exchange.In.GetHeader(AzureServiceBusHeaders.ScheduledEnqueueTime) is { } scheduled) msg.ScheduledEnqueueTime = scheduled; // Application properties, as the endpoint's strategy lets the exchange headers out foreach (var (key, value) in exchange.In.Headers) { if (value is null) continue; if (_headerFilter.FilterOutgoing(key, value, exchange)) continue; msg.ApplicationProperties[key] = value; } // The context of this send, over a Diagnostic-Id the header bridge copied from a received message: that one // names the previous hop. RouteTelemetryExtensions.InjectTraceContext(activity, msg.ApplicationProperties, AzureServiceBusTrace.Write); } private static BinaryData ResolveBodyData(object? body) { return body switch { byte[] bytes => BinaryData.FromBytes(bytes), BinaryData bd => bd, string str => BinaryData.FromString(str), Stream stream => BinaryData.FromStream(stream), _ => BinaryData.FromObjectAsJson(body) }; } private static T? ResolveHeader(IExchange exchange, string headerKey) where T : class { return exchange.In.GetHeader(headerKey); } } /// /// The messages a Service Bus producer with batchCommit deferred in one .Transacted() block, sent as one /// batch when the block commits. /// internal sealed class AzureServiceBusSendBatch : ITransactedAction { private readonly AzureServiceBusProducer _producer; private readonly System.Collections.Concurrent.ConcurrentQueue _messages = new(); public AzureServiceBusSendBatch(AzureServiceBusProducer producer) => _producer = producer; public void Add(IEnumerable messages) { foreach (var message in messages) _messages.Enqueue(message); } public Task Commit(CancellationToken ct = default) => _producer.SendAsOneBatchAsync(_messages.ToArray(), "this .Transacted() block", ct); // The block rolled back before anything was sent. public Task Rollback(CancellationToken ct = default) => Task.CompletedTask; } Path: redb-route/redb.Route.AzureServiceBus/AzureServiceBusSessionConsumer.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/AzureServiceBusSessionConsumer.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; /// /// Session-aware consumer using . /// Sessions guarantee FIFO ordering per session ID and enable session state. /// internal sealed class AzureServiceBusSessionConsumer : IConsumer { private readonly AzureServiceBusEndpoint _endpoint; private readonly IProcessor _pipeline; private readonly AzureServiceBusEndpointOptions _options; private readonly IHeaderFilterStrategy _headerFilter; private readonly InflightDrainGuard _drain = new(); private ServiceBusSessionProcessor? _processor; private ILogger? _logger; private AzureServiceBusConnectionWatch? _watch; public IEndpoint? Endpoint => _endpoint; internal AzureServiceBusSessionConsumer(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 ServiceBusSessionProcessorOptions { ReceiveMode = _options.ParsedReceiveMode, MaxConcurrentSessions = _options.MaxConcurrentSessions, MaxConcurrentCallsPerSession = _options.ResolvedMaxConcurrentCalls, PrefetchCount = _options.PrefetchCount, MaxAutoLockRenewalDuration = TimeSpan.FromSeconds(_options.MaxAutoLockRenewalDuration), AutoCompleteMessages = false }; if (_options.SessionIdleTimeout > 0) processorOptions.SessionIdleTimeout = TimeSpan.FromSeconds(_options.SessionIdleTimeout); if (!string.IsNullOrEmpty(_options.SessionId)) processorOptions.SessionIds.Add(_options.SessionId); _processor = _endpoint.IsTopic ? client.CreateSessionProcessor(_endpoint.EntityName, _options.SubscriptionName, processorOptions) : client.CreateSessionProcessor(_endpoint.EntityName, processorOptions); _processor.ProcessMessageAsync += OnSessionMessageAsync; _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 session consumer started: entity={Entity}, sessions={MaxSessions}, callsPerSession={Calls}", _endpoint.EntityName, _options.MaxConcurrentSessions, _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-session:{_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 session consumer stopped: entity={Entity}", _endpoint.EntityName); } // ── Session message handling ── private async Task OnSessionMessageAsync(ProcessSessionMessageEventArgs 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, args); // 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); 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 session 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(ProcessSessionMessageEventArgs 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 session connection error on {EntityPath}: {Source}", args.EntityPath, args.ErrorSource); return Task.CompletedTask; } _endpoint.RecordError(args.Exception); _logger?.LogError(args.Exception, "ASB session error on {EntityPath}: {Source}", args.EntityPath, args.ErrorSource); return Task.CompletedTask; } // ── Exchange creation ── private Exchange CreateExchange(ServiceBusReceivedMessage msg, ProcessSessionMessageEventArgs args) { var message = new Message(msg.Body.ToArray()); // Identity SetIfNotEmpty(message, AzureServiceBusHeaders.MessageId, msg.MessageId); SetIfNotEmpty(message, AzureServiceBusHeaders.CorrelationId, msg.CorrelationId); SetIfNotEmpty(message, AzureServiceBusHeaders.PartitionKey, msg.PartitionKey); SetIfNotEmpty(message, AzureServiceBusHeaders.ReplyToSessionId, msg.ReplyToSessionId); // Session — always present for session consumer message.Headers[AzureServiceBusHeaders.SessionId] = args.SessionId; // 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 var exchange = Exchange.Create(message, _endpoint.ScopeFactory); 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; } return exchange; } private static void SetIfNotEmpty(IMessage message, string key, string? value) { if (!string.IsNullOrEmpty(value)) message.Headers[key] = value; } } Path: redb-route/redb.Route.AzureServiceBus/AzureServiceBusTrace.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/AzureServiceBusTrace.cs ---- using System.Diagnostics; using Azure.Messaging.ServiceBus; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.AzureServiceBus; /// /// The trace carrier of a Service Bus message: its application properties. Azure names the W3C /// traceparent field Diagnostic-Id (same value format), so that one name is mapped; tracestate /// and baggage go under their own names. One explicit mapping, read and written the same way. /// internal static class AzureServiceBusTrace { /// The application property Azure keeps the traceparent value in. internal const string DiagnosticId = "Diagnostic-Id"; private const string TraceParent = "traceparent"; private static string PropertyName(string field) => string.Equals(field, TraceParent, StringComparison.Ordinal) ? DiagnosticId : field; /// Reads one trace field from the application properties of a received message. internal static string? Read(IReadOnlyDictionary properties, string field) => properties.TryGetValue(PropertyName(field), out var value) ? value?.ToString() : null; /// Writes one trace field to the application properties of an outgoing message, replacing a copied value. internal static void Write(IDictionary properties, string field, string value) => properties[PropertyName(field)] = value; /// /// Marks failed by , unless it is our own stop: a cancellation /// by (the processor stopping, the caller's token). Any other cancellation, a timeout inside /// the route for one, is a failure. /// internal static void RecordFailure(Activity? span, Exception exception, CancellationToken ours) { if (exception is OperationCanceledException && ours.IsCancellationRequested) return; span.RecordFailure(exception); } /// /// Opens the receive span of : a child of the sender's context, or a root when the /// message carries none. /// internal static TransportSpan StartReceiveSpan(AzureServiceBusEndpoint endpoint, ServiceBusReceivedMessage message) { var span = RouteTelemetryExtensions.StartConsumerSpan( (endpoint.Component as ComponentBase)?.Context, $"{endpoint.EntityName} receive", ActivityKind.Consumer, "messaging.system", "azureservicebus", endpoint.Uri.NormalizedKey, message.ApplicationProperties, Read, destination: endpoint.EntityName, operation: "receive"); if (span.Activity is { IsAllDataRequested: true } activity && !string.IsNullOrEmpty(message.MessageId)) activity.SetTag("messaging.message.id", message.MessageId); return span; } } Path: redb-route/redb.Route.AzureServiceBus/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.AzureServiceBus/Extensions/ServiceCollectionExtensions.cs ---- using Microsoft.Extensions.DependencyInjection; namespace redb.Route.AzureServiceBus.Extensions; /// /// DI registration for the Azure Service Bus component. /// public static class ServiceCollectionExtensions { /// /// Registers as a singleton. /// Use with route.AddComponent<AzureServiceBusComponent>() or resolve from DI. /// public static IServiceCollection AddRedbRouteAzureServiceBus(this IServiceCollection services) { services.AddSingleton(); return services; } } Path: redb-route/redb.Route.AzureServiceBus/Fluent/AzureServiceBusDsl.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/Fluent/AzureServiceBusDsl.cs ---- using redb.Route.Core; namespace redb.Route.AzureServiceBus.Fluent; /// /// Fluent DSL entry point for Azure Service Bus URIs. /// /// /// .From(Asb.Queue("orders").ConnectionString("Endpoint=sb://...").Build()) /// .To(Asb.Topic("events", "my-sub").ConnectionString("...").Build()) /// /// /// public static class Asb { /// Creates a builder targeting a queue. public static AzureServiceBusBuilder Queue(string queueName) => new(queueName, isTopic: false); /// Creates a builder targeting a topic with a subscription. public static AzureServiceBusBuilder Topic(string topicName, string subscriptionName) => new AzureServiceBusBuilder(topicName, isTopic: true) .SubscriptionName(subscriptionName); } /// /// Fluent builder for constructing asb:// endpoint URIs. /// public sealed class AzureServiceBusBuilder { private readonly string _entity; private readonly bool _isTopic; private readonly Dictionary _params = new(StringComparer.OrdinalIgnoreCase); internal AzureServiceBusBuilder(string entity, bool isTopic) { _entity = entity; _isTopic = isTopic; } // ── Connection ── /// Sets the connection string. public AzureServiceBusBuilder ConnectionString(string cs) => Set("connectionString", cs); /// Sets the named connection factory from registry. public AzureServiceBusBuilder ConnectionFactory(string name) => Set("connectionFactory", name); // ── Entity ── /// Sets the topic subscription name. public AzureServiceBusBuilder SubscriptionName(string name) => Set("subscriptionName", name); /// Sets the sub-queue: "deadletter" or "transferdeadletter". public AzureServiceBusBuilder SubQueue(string sq) => Set("subQueue", sq); // ── Consumer ── /// When a message is settled: after the route with PeekLock (, default) or on hand-off with ReceiveAndDelete (). public AzureServiceBusBuilder AckMode(AckMode mode) => Set("ackMode", mode.ToString().ToLowerInvariant()); /// Sets maximum concurrent message handler calls. public AzureServiceBusBuilder MaxConcurrentCalls(int n) => Set("maxConcurrentCalls", n); /// Handler parallelism as a string: a number or "auto" (= max(CPU, 2)). public AzureServiceBusBuilder MaxConcurrentCalls(string n) => Set("maxConcurrentCalls", n); /// Batch mode (batching=true): the route gets the messages as a List<IMessage>. public AzureServiceBusBuilder Batching(bool v = true) => Set("batching", v); /// Largest number of messages in a batch (maxBatchMessages, default 100). public AzureServiceBusBuilder MaxBatchMessages(int n) => Set("maxBatchMessages", n); /// Batch mode: the idle timeout in milliseconds, restarted by every message (pollTimeoutMs, default 1000). public AzureServiceBusBuilder PollTimeoutMs(int ms) => Set("pollTimeoutMs", ms); /// Batch mode: the hard limit in milliseconds since a batch's first message (batchingIntervalMs). public AzureServiceBusBuilder BatchingIntervalMs(int ms) => Set("batchingIntervalMs", ms); /// Sets message pre-fetch count. public AzureServiceBusBuilder PrefetchCount(int n) => Set("prefetchCount", n); /// Sets maximum auto lock renewal duration in seconds. public AzureServiceBusBuilder MaxAutoLockRenewalDuration(int sec) => Set("maxAutoLockRenewalDuration", sec); /// /// 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 AzureServiceBusBuilder Transacted(bool v = true) => Set("transacted", v); /// /// Sets batchCommit: the sends this producer defers in a .Transacted() block leave as one Service Bus /// batch, all or none; the block's messages must fit in one batch. /// public AzureServiceBusBuilder BatchCommit(bool v = true) => Set("batchCommit", v); /// Enables automatic dead-lettering on processing error. public AzureServiceBusBuilder AutoDeadLetter(bool v = true) => Set("autoDeadLetter", v); /// Sets dead-letter reason string. public AzureServiceBusBuilder DeadLetterReason(string reason) => Set("deadLetterReason", reason); // ── Sessions ── /// Enables session-aware consumer. public AzureServiceBusBuilder EnableSessions(bool v = true) => Set("enableSessions", v); /// Sets fixed session ID filter. public AzureServiceBusBuilder SessionId(string id) => Set("sessionId", id); /// Sets maximum concurrent session handlers. public AzureServiceBusBuilder MaxConcurrentSessions(int n) => Set("maxConcurrentSessions", n); /// Sets session idle timeout in seconds. public AzureServiceBusBuilder SessionIdleTimeout(int sec) => Set("sessionIdleTimeout", sec); // ── Producer ── /// Sets dynamic message ID expression. public AzureServiceBusBuilder MessageId(string expr) => Set("messageId", expr); /// Sets dynamic session ID for producer. public AzureServiceBusBuilder ProducerSessionId(string expr) => Set("producerSessionId", expr); /// Sets partition key. public AzureServiceBusBuilder PartitionKey(string key) => Set("partitionKey", key); /// Sets delayed delivery in seconds. public AzureServiceBusBuilder ScheduleDelaySeconds(int sec) => Set("scheduleDelaySeconds", sec); /// Sets message TTL as TimeSpan string (e.g. "00:05:00"). public AzureServiceBusBuilder TimeToLive(string ttl) => Set("timeToLive", ttl); /// Sets maximum batch size in bytes. public AzureServiceBusBuilder BatchMaxSizeBytes(long bytes) => Set("batchMaxSizeBytes", bytes); // ── Retry ── /// Sets maximum retry count. public AzureServiceBusBuilder RetryMaxRetries(int n) => Set("retryMaxRetries", n); /// Sets retry mode: "Exponential" or "Fixed". public AzureServiceBusBuilder RetryMode(string mode) => Set("retryMode", mode); // ── Build ── /// Builds the asb:// endpoint URI string. public string Build() { var qs = string.Join("&", _params.Select(kv => $"{kv.Key}={Uri.EscapeDataString(kv.Value)}")); return qs.Length > 0 ? $"asb://{_entity}?{qs}" : $"asb://{_entity}"; } /// public override string ToString() => Build(); /// Implicit conversion to string (calls ). public static implicit operator string(AzureServiceBusBuilder builder) => builder.Build(); private AzureServiceBusBuilder Set(string key, object value) { _params[key] = value.ToString()!; return this; } } Path: redb-route/redb.Route.AzureServiceBus/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.AzureServiceBus/README.md ---- # redb.Route.AzureServiceBus Azure Service Bus connector for the [redb.Route](../README.md) ESB framework. Provides a full-featured **producer** (single & batch), **consumer** (PeekLock / ReceiveAndDelete), **session consumer** (FIFO per session), and **transacted acknowledgement**. Uses the `asb` URI scheme. [![NuGet](https://img.shields.io/nuget/v/redb.Route.AzureServiceBus?label=NuGet&color=blue)](https://www.nuget.org/packages/redb.Route.AzureServiceBus) [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue)](../../LICENSE) ## Quick Start ```csharp // Consumer: receive from a queue .From(Asb.Queue("orders") .ConnectionString("Endpoint=sb://my-ns.servicebus.windows.net/;SharedAccessKeyName=...;SharedAccessKey=...") .MaxConcurrentCalls(5) .PrefetchCount(10)) // Producer: send to a queue .To(Asb.Queue("orders") .ConnectionString("Endpoint=sb://...")) // Topic/subscription roundtrip .From(Asb.Topic("events", "my-subscription") .ConnectionString("Endpoint=sb://...")) .To(Asb.Topic("events", "ignored-for-producer") .ConnectionString("Endpoint=sb://...")) ``` ## URI Format ``` asb://entity-name?connectionString=...¶m=value ``` Entity detection is automatic: if `subscriptionName` is set, the entity is treated as a **topic**; otherwise as a **queue**. ## Producer The producer sends messages via `ServiceBusSender`. Two modes are supported: ### Single Message (default) ```csharp var exchange = new Exchange(new Message("Hello ASB")); exchange.In.Headers[AzureServiceBusHeaders.CorrelationId] = "corr-123"; exchange.In.Headers[AzureServiceBusHeaders.Subject] = "order.created"; await producer.Process(exchange); // After send, MessageId header is set var id = exchange.In.Headers[AzureServiceBusHeaders.MessageId]; ``` ### A list body A list body is sent as one Service Bus batch, one message per element, as Apache Camel's azure-servicebus sends an `Iterable` body; Service Bus takes the batch whole or not at all. A list of `IMessage` (a batch consumer's body, for one) sends each element with its own body and headers as application properties, none of the exchange's; any other list sends each value as the body under the exchange's headers, each with a message id of its own. Messages that do not fit in `batchMaxSizeBytes` (and the entity's own limit) fail the send and nothing is sent. To send a list as one message, serialize it in the route. ```csharp .To(Asb.Queue("orders") .ConnectionString("...") .BatchMaxSizeBytes(262144)) var items = new[] { "msg-1", "msg-2", "msg-3" }; var exchange = new Exchange(new Message(items)); await producer.Process(exchange); var count = (int)exchange.In.Headers[AzureServiceBusHeaders.BatchMessageCount]!; // 3 ``` > **Note:** `PartitionKey` is only set when `SessionId` is empty (ASB constraint). ## Consumer The consumer uses `ServiceBusProcessor` with callback-based message delivery. ```csharp .From(Asb.Queue("orders") .ConnectionString("...") .AckMode(AckMode.Manual) // default: PeekLock .MaxConcurrentCalls(10) .PrefetchCount(20) .MaxAutoLockRenewalDuration(300)) // 5 min ``` ### Acknowledge Modes | Scenario | `exchange.Exception` | `AutoDeadLetter` | Action | |----------|---------------------|-------------------|--------| | Success | `null` | — | Complete | | Error | set | `false` | Abandon (re-delivery) | | Error | set | `true` | Dead-letter with reason | ```csharp // Auto dead-letter on processing error .From(Asb.Queue("orders") .ConnectionString("...") .AutoDeadLetter(true) .DeadLetterReason("ProcessingFailed")) ``` A stop of the consumer (single or session) receives nothing more and waits up to 30 s for the messages in work; they finish and are settled as above. Only after that time is the route's cancellation token cancelled. ### ReceiveAndDelete Messages are removed from the queue immediately upon receipt. No acknowledgement needed: ```csharp .From(Asb.Queue("orders") .ConnectionString("...") .AckMode(AckMode.Auto)) // ReceiveAndDelete ``` ### Batch mode `batching=true` makes the consumer hand the route one exchange per batch of messages, by the batch contract every broker of redb.Route follows. Apache Camel's azure-servicebus has no batch consumer (it batches only the producer); the contract is redb.Route's own, the same as for Kafka, RabbitMQ, IBM MQ, SQS and AMQP 1.0. - `maxBatchMessages` (default 100) caps the batch; `pollTimeoutMs` (default 1000) sends a batch on once no message came for that long, restarted by every message; `batchingIntervalMs` sends it on once that long has passed since its first message. A batch option without `batching=true`, a value out of range, and `batching=true` with `enableSessions=true` (the messages of a session entity are received and settled per session) fail the start. - Each of `maxConcurrentCalls` workers has a receiver of its own and collects with `ReceiveMessagesAsync`, one batch at a time. - The body is a `List`, one message per Service Bus message with the same body and headers a single message gets, even for a batch of one; the size is `body.Count`. The exchange is InOnly. `Split` over the body gives each part its message. - With `ackMode=manual` (PeekLock) every message is completed after the route. A failed batch follows the rule of a failed message for every message in it: abandoned, delivered again, and moved to the dead letter sub-queue by the entity after its `MaxDeliveryCount`; with `autoDeadLetter=true` dead-lettered at once with `deadLetterReason`. 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 lock; keep `batchingIntervalMs` well below the entity's lock duration, since a lock is not renewed while the batch is still being collected. - With `ackMode=auto` (ReceiveAndDelete) the messages are gone on receipt, and a failure does not bring them back. - A batch half collected when the consumer stops is not run: its messages are abandoned. The stop waits for the receive in progress, at most `pollTimeoutMs`. ### Sub-Queues Read from dead-letter or transfer dead-letter queues: ```csharp .From(Asb.Queue("orders") .ConnectionString("...") .SubQueue("deadletter")) ``` ### Consumer Headers Each received message populates the following exchange headers: | Header | Type | Description | |--------|------|-------------| | `redbAsb.MessageId` | `string` | Message ID | | `redbAsb.CorrelationId` | `string` | Correlation ID | | `redbAsb.SessionId` | `string` | Session ID | | `redbAsb.PartitionKey` | `string` | Partition key | | `redbAsb.ReplyToSessionId` | `string` | Reply-to session ID | | `redbAsb.Subject` | `string` | Message subject / label | | `redbAsb.ContentType` | `string` | Content type | | `redbAsb.ReplyTo` | `string` | Reply-to address | | `redbAsb.To` | `string` | Destination address | | `redbAsb.TimeToLive` | `TimeSpan` | Time to live | | `redbAsb.ScheduledEnqueueTime` | `DateTimeOffset` | Scheduled enqueue time | | `redbAsb.SequenceNumber` | `long` | Sequence number | | `redbAsb.DeliveryCount` | `int` | Number of deliveries | | `redbAsb.EnqueuedTime` | `DateTimeOffset` | When message was enqueued | | `redbAsb.ExpiresAt` | `DateTimeOffset` | When the message expires | | `redbAsb.LockedUntil` | `DateTimeOffset` | Lock expiry (PeekLock only) | | `redbAsb.DeadLetterSource` | `string` | Original entity (dead-letter messages) | | `redbAsb.DeadLetterReason` | `string` | Dead-letter reason | | `redbAsb.DeadLetterErrorDescription` | `string` | Dead-letter error description | All `ApplicationProperties` from the message are also copied to exchange headers. ## Session Consumer Enable session-aware FIFO processing with `enableSessions=true`: ```csharp .From(Asb.Queue("session-queue") .ConnectionString("...") .EnableSessions(true) .MaxConcurrentSessions(5) .SessionIdleTimeout(30)) // Filter by specific session .From(Asb.Queue("session-queue") .ConnectionString("...") .EnableSessions(true) .SessionId("my-session-id")) ``` The session consumer uses `ServiceBusSessionProcessor` and guarantees message ordering within a session. `MaxConcurrentSessions` controls parallelism across sessions; messages within the same session are always processed sequentially. ## Transactions The consumer settles a delivery itself once the route has finished: it completes the message on success and abandons it on failure. Inside `.Transacted()` that comes last, after the database and the deferred sends have committed. A producer inside `.Transacted()` joins the transaction: the message is sent once the database has committed and dropped if the block rolls back. ```csharp From(Asb.Queue("orders.in").ConnectionString("...")) .Transacted() .ProcessWithRedb(async (redb, ex, ct) => await redb.SaveAsync((Order)ex.In.Body!, ct)) .To(Asb.Queue("orders.created").ConnectionString("...")) // sent after the commit .To(Asb.Queue("alerts").ConnectionString("...").Transacted(false)) // sent at once .End(); ``` - `transacted=false` sends at once, outside the transaction, even if the block later rolls back. - `transacted=true` requires an enclosing block; outside one the step fails instead of losing the message. - The Service Bus client would enlist a send in the ambient `System.Transactions` transaction by itself. The connector never lets it: a send that leaves at once runs with the ambient transaction suppressed and a deferred one after the transaction closed, so Service Bus never becomes a second resource next to the database. - By default the sends a producer deferred in a block go out one after the other. With `batchCommit=true` (`.BatchCommit()`) they leave as **one batch** when the block commits: Service Bus takes a batch to one entity whole or not at all. The block's messages must fit in one batch (`batchMaxSizeBytes`, and the entity's limit — 256 KB on Standard); a block whose messages do not fit fails its commit and sends nothing. On a partitioned or session entity the messages of one batch must share the partition key or session id. See the framework-wide **Transactions** guide (`TRANSACTIONS.md` in the [redb.Route repository](https://github.com/redbase-app/redb)) for the commit order and nesting. ## Topic / Subscription ```csharp // Producer sends to the topic .To(Asb.Topic("events", "sub-name") .ConnectionString("...")) // Consumer reads from a subscription .From(Asb.Topic("events", "my-subscription") .ConnectionString("...")) ``` The second argument to `Asb.Topic()` is the subscription name. The producer ignores `subscriptionName` and sends directly to the topic; the consumer uses it to create a `ServiceBusProcessor` for that subscription. ## Connection Factory For complex or shared client configurations, register a named `AzureServiceBusConnectionFactory`: ```csharp var factory = new AzureServiceBusConnectionFactory { ConnectionString = "Endpoint=sb://my-ns.servicebus.windows.net/;...", MaxRetries = 5, RetryMode = ServiceBusRetryMode.Fixed, TransportType = ServiceBusTransportType.AmqpWebSockets, ProxyAddress = "http://proxy:8080", }; context.AddToRegistry("myAsb", factory); // Reference by name in URI Asb.Queue("orders").ConnectionFactory("myAsb") ``` If `ProxyAddress` is set, transport is automatically switched to `AmqpWebSockets` with the configured proxy. ### Factory Properties | Property | Type | Default | Description | |----------|------|---------|-------------| | `ConnectionString` | `string` | `""` | ASB connection string | | `MaxRetries` | `int` | `3` | Max retry count | | `DelayMs` | `int` | `800` | Initial retry delay (ms) | | `MaxDelayMs` | `int` | `60000` | Max retry delay (ms) | | `RetryMode` | `ServiceBusRetryMode` | `Exponential` | `Exponential` or `Fixed` | | `TryTimeoutMs` | `int` | `60000` | Per-try timeout (ms) | | `TransportType` | `ServiceBusTransportType` | `AmqpTcp` | Transport: `AmqpTcp` or `AmqpWebSockets` | | `ProxyAddress` | `string?` | — | HTTP proxy for `AmqpWebSockets` | ## DI Registration ```csharp services.AddRedbRouteAzureServiceBus(); ``` ## Configuration Reference ### Connection | Parameter | Default | Description | |-----------|---------|-------------| | `connectionString` | — | ASB connection string (required if no factory) | | `connectionFactory` | — | Named factory from DI registry | ### Consumer | Parameter | Default | Description | |-----------|---------|-------------| | `ackMode` | `manual` | `manual` (PeekLock: completed after the route) or `auto` (ReceiveAndDelete) | | `maxConcurrentCalls` | `1` | Max concurrent handler invocations | | `prefetchCount` | `0` | Messages to pre-fetch | | `maxAutoLockRenewalDuration` | `300` | Auto lock renewal (seconds) | | `subQueue` | — | `deadletter` or `transferdeadletter` | | `autoDeadLetter` | `false` | Dead-letter on processing error | | `deadLetterReason` | — | Dead-letter reason string | | `batching` | `false` | Batch mode: the route gets a `List` (see [Batch mode](#batch-mode)) | | `maxBatchMessages` | `100` | Batch mode: largest batch | | `pollTimeoutMs` | `1000` | Batch mode: idle timeout, restarted by every message | | `batchingIntervalMs` | — | Batch mode: hard limit since a batch's first message | | `transacted` | unset | Producer: unset follows an enclosing `.Transacted()` block, `false` sends at once, `true` requires a block | ### Sessions | Parameter | Default | Description | |-----------|---------|-------------| | `enableSessions` | `false` | Session-aware consumer | | `sessionId` | — | Fixed session ID filter | | `maxConcurrentSessions` | `1` | Max concurrent session handlers | | `sessionIdleTimeout` | `0` | Session idle timeout (seconds, 0 = SDK default) | ### Producer | Parameter | Default | Description | |-----------|---------|-------------| | `messageId` | — | Dynamic message ID expression (`${...}`) | | `producerSessionId` | — | Dynamic session ID expression | | `partitionKey` | — | Partition key | | `scheduleDelaySeconds` | `0` | Delayed delivery (seconds) | | `timeToLive` | — | Message TTL (`HH:MM:SS` format) | ### Batch | Parameter | Default | Description | |-----------|---------|-------------| | `batchMaxSizeBytes` | `262144` | Max size of the batch a list body or a `batchCommit` block is sent as (bytes, default 256 KB) | ### Retry These are the Service Bus client's retries of a call to the service that failed (`ServiceBusRetryOptions`), not attempts of the route: a message the route fails is not run again in the process. With `ackMode=manual` the entity delivers it again up to its `MaxDeliveryCount`; with `ackMode=auto` it is gone. | Parameter | Default | Description | |-----------|---------|-------------| | `retryMaxRetries` | `3` | Max retry count | | `retryDelayMs` | `800` | Initial retry delay (ms) | | `retryMaxDelayMs` | `60000` | Max retry delay (ms) | | `retryMode` | `Exponential` | `Exponential` or `Fixed` | ## Headers Reference All headers use the `redbAsb.` prefix. | Constant | Value | Direction | Used By | |----------|-------|-----------|---------| | `MessageId` | `redbAsb.MessageId` | In/Out | Producer, Consumer | | `CorrelationId` | `redbAsb.CorrelationId` | In/Out | Producer, Consumer | | `SessionId` | `redbAsb.SessionId` | In/Out | Producer, Consumer | | `PartitionKey` | `redbAsb.PartitionKey` | In/Out | Producer, Consumer | | `ReplyToSessionId` | `redbAsb.ReplyToSessionId` | In/Out | Producer, Consumer | | `Subject` | `redbAsb.Subject` | In/Out | Producer, Consumer | | `ContentType` | `redbAsb.ContentType` | In/Out | Producer, Consumer | | `ReplyTo` | `redbAsb.ReplyTo` | In/Out | Producer, Consumer | | `To` | `redbAsb.To` | In/Out | Producer, Consumer | | `TimeToLive` | `redbAsb.TimeToLive` | In/Out | Producer, Consumer | | `ScheduledEnqueueTime` | `redbAsb.ScheduledEnqueueTime` | In/Out | Producer, Consumer | | `SequenceNumber` | `redbAsb.SequenceNumber` | Out | Consumer | | `DeliveryCount` | `redbAsb.DeliveryCount` | Out | Consumer | | `EnqueuedTime` | `redbAsb.EnqueuedTime` | Out | Consumer | | `ExpiresAt` | `redbAsb.ExpiresAt` | Out | Consumer | | `LockedUntil` | `redbAsb.LockedUntil` | Out | Consumer (PeekLock) | | `LockToken` | `redbAsb.LockToken` | — | Declared, not set | | `DeadLetterSource` | `redbAsb.DeadLetterSource` | Out | Consumer (DLQ) | | `DeadLetterReason` | `redbAsb.DeadLetterReason` | Out | Consumer (DLQ) | | `DeadLetterErrorDescription` | `redbAsb.DeadLetterErrorDescription` | Out | Consumer (DLQ) | | `SessionState` | `redbAsb.SessionState` | — | Declared, not set | | `BatchMessageCount` | `redbAsb.BatchMessageCount` | Out | Producer (batch) | ### Header filter strategy Every other exchange header goes out as an application property, and every application property of a received message comes in. `headerFilterStrategy=#name` names an `IHeaderFilterStrategy` in the registry that decides which headers cross, as in Apache Camel: on a producer, which exchange headers become application properties; on a consumer (plain and session alike), which application properties come in. It replaces the default, `AzureServiceBusHeaderFilterStrategy` (keeps `redbAsb.*` back), entirely; derive from that class to add to it. The system properties above and the trace context are set whatever the strategy says. ```csharp ctx.AddToRegistry("correlationOnly", new DefaultHeaderFilterStrategy { OutFilter = ["Correlation-ID"], FilterOnMatch = false, // a whitelist: only the listed headers go out }); // asb://orders?connectionString=...&headerFilterStrategy=#correlationOnly ``` ## Requirements - **Azure Service Bus** or Azure Service Bus Emulator - .NET 10.0 / 11.0. The 4.7 line stays on .NET 8, 9 and 10 for applications that cannot move yet. - `Azure.Messaging.ServiceBus` 7.x ## 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: ``` maxConcurrentCalls=4 # a fixed worker count maxConcurrentCalls=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. ## A lost connection The Service Bus client reconnects by itself, for the processor, the session processor and the batch receiver alike. While the connection is lost, the endpoint's health is `Warning`, then `Critical` once an attempt failed, and `Healthy` when it is back; a Warning is logged when it is lost and an Information when it is back, and `Reconnects` counts each return. A loss is not counted in `Errors`. The batch receiver learns of the return from its next receive. The processors give no event for it, so while the connection is lost the consumer peeks the entity's dead-letter queue on the `RedbRoute:Reconnect` schedule, through its own client: it needs only the Listen right the consumer has and locks nothing (each peek is bounded to 10 s and ends with the route's stop); the next message restores it too, whichever comes first. Only communication errors start a lost connection. While it is connected, an entity that does not exist, a refused claim and other errors the client reports are counted in `Errors` as before, and health shows them as recent errors, not as a connection being retried. While the connection is lost, every error of a receive belongs to the loss and is the reason health shows (a namespace coming back may refuse the entity for a moment). A lost session lock is neither an error nor a lost connection: the session processor accepts a session again by itself, and a message it cut short is counted where it failed. ## Tracing On the `redb.Route` activity source (`AddSource("redb.Route")`). The trace context travels in the application properties: the `traceparent` value under Azure's own name for it, `Diagnostic-Id`; `tracestate` and `baggage` under their own names. - **Consumer.** One `Consumer` span per message, named `{entity} receive`, over the whole unit of work, settlement included, for the session consumer too. Its parent is the sender's `Diagnostic-Id`; without one it is a root, never a child of whatever activity the processor thread holds. The sender's baggage is back on it, and the route's spans are its children. It carries `redb.route.endpoint` and `messaging.message.id`, and is an error when the route fails. - **Producer.** One `Producer` span per send, named `{entity} send`; an error when the send fails. Every message, each message of a batch included, carries the context of this span: a `Diagnostic-Id` the header bridge copied from a received message is replaced, as it names the previous hop. - `RouteEngineOptions.EnableTelemetry = false` opens neither span. A context that came in still goes out. Path: redb-route/redb.Route.AzureServiceBus/redb.Route.AzureServiceBus.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.AzureServiceBus/redb.Route.AzureServiceBus.csproj ---- redb.Route.AzureServiceBus Azure Service Bus connector for redb.Route ESB framework. Event-driven consumer with PeekLock/ReceiveAndDelete, sessions, dead-letter queues, transacted acknowledge; producer with single/batch send and scheduled delivery. esb;messaging;azure;servicebus;redb README.md