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