Path: redb-route/redb.Route.RabbitMQ/RabbitMQEndpointOptions.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.RabbitMQ/RabbitMQEndpointOptions.cs
----
using redb.Route.Abstractions;
using redb.Route.Batching;
using redb.Route.Core;
namespace redb.Route.RabbitMQ;
///
/// Typed options for . Bound from URI query parameters.
///
public sealed class RabbitMQEndpointOptions : EndpointOptions
{
// ── Connection ──
/// RabbitMQ host name (default: localhost).
[ConnectionParameter]
public string Host { get; set; } = "localhost";
///
/// A registry reference (#name) to an that
/// decides which headers this endpoint carries between the exchange and an AMQP message (a request, a consumed
/// message, an RPC reply both ways), in place of .
///
[RegistryReference(typeof(IHeaderFilterStrategy))]
public string? HeaderFilterStrategy { get; set; }
/// RabbitMQ port (default: 5672).
[ConnectionParameter]
public int Port { get; set; } = 5672;
/// RabbitMQ username (default: guest).
[ConnectionParameter]
public string Username { get; set; } = "guest";
/// RabbitMQ password (default: guest).
[Sensitive]
[ConnectionParameter]
public string Password { get; set; } = "guest";
/// Virtual host (default: /).
[ConnectionParameter]
public string VirtualHost { get; set; } = "/";
/// Name of in the route registry.
[ConnectionFactoryReference(typeof(RabbitMQConnectionFactory))]
public string? ConnectionFactory { get; set; }
/// Client-provided name for RabbitMQ connections.
[ConnectionParameter]
public string ClientName { get; set; } = "redb.Route";
// ── Exchange ──
/// Exchange name (empty = default exchange).
public string Exchange { get; set; } = string.Empty;
/// Exchange type: direct, topic, fanout, headers (default: direct), or an x-prefixed plugin type such as x-delayed-message.
public string ExchangeType { get; set; } = "direct";
/// Whether exchange survives broker restart.
public bool ExchangeDurable { get; set; } = true;
/// Auto-delete exchange when no longer in use.
public bool ExchangeAutoDelete { get; set; }
/// Declare exchange and queue on startup.
public bool Declare { get; set; }
// ── Queue ──
///
/// Queue name. Empty on a consumer: a temporary queue of its own (exclusive, auto-delete), named by the broker,
/// bound to the exchange and read under that name; it needs declare=true. Empty on a producer: no queue is
/// declared, the message goes to the exchange.
///
public string Queue { get; set; } = string.Empty;
/// Whether queue survives broker restart.
public bool Durable { get; set; } = true;
/// Auto-delete queue when last consumer disconnects.
public bool AutoDelete { get; set; }
/// Only one consumer allowed on this queue.
public bool Exclusive { get; set; }
// ── Routing ──
/// Routing key for publish and bind operations.
public string RoutingKey { get; set; } = string.Empty;
/// Content type for published messages (default: application/json).
public string ContentType { get; set; } = "application/json";
// ── Consumer ──
///
/// Consumer parallelism. Sizes both the channel's AMQP consumer-dispatch concurrency (how many
/// deliveries the client hands to the processor in parallel) and the app-level concurrency
/// semaphore. This is the single knob for consumer-side parallelism: ConcurrentConsumers(N)
/// yields up to N messages processed concurrently on the queue. Default: 1 (serial).
///
// A string so that "auto" binds verbatim instead of silently degrading to the int default;
// resolved once via ConcurrencyOption.Resolve.
public string? ConcurrentConsumers { get; set; }
/// Resolved consumer parallelism: 1 by default, N, or auto = max(CPU, 2).
public int ResolvedConcurrentConsumers => ConcurrencyOption.Resolve(ConcurrentConsumers, "concurrentConsumers");
/// Prefetch count per consumer (default: 10). Should be >=
/// so the broker can keep the parallel slots fed.
public ushort PrefetchCount { get; set; } = 10;
///
/// When the delivery is settled (). Manual (default): the consumer acks after a
/// turn that ended well and settles a failed one by once its attempts are used up
/// (at-least-once). Auto: the consumer subscribes with autoAck: true and the broker settles every
/// delivery on hand-off (at-most-once); a failure in the route does not requeue it. Auto cannot be combined
/// with .
///
public AckMode AckMode { get; set; } = AckMode.Manual;
///
/// Apache Camel maximumRetryAttempts: how many times the consumer runs the route on a delivery that fails,
/// the first attempt included (default 5). The attempts run in the consumer, one after the other, each on a fresh
/// exchange, apart.
///
public int MaximumRetryAttempts { get; set; } = 5;
/// Apache Camel retryDelay: milliseconds between two attempts on a failed delivery (default 1000).
public int RetryDelay { get; set; } = 1000;
///
/// Apache Camel rejectAndDontRequeue: a delivery that failed every attempt is rejected without requeue
/// (default true), so the broker hands it to the queue's dead letter exchange when one is configured, and drops
/// it otherwise. false nacks it with requeue: the broker delivers it again, and the attempts start over.
///
public bool RejectAndDontRequeue { get; set; } = true;
///
/// Apache Camel disableReplyTo: the consumer does not act on a delivery's reply-to. It sends no reply, and a
/// batch consumer takes such a delivery into its batch instead of rejecting it.
///
public bool DisableReplyTo { get; set; }
// ── Batch mode ──
///
/// Batch mode (Apache Camel batching): the route gets one InOnly exchange whose body is a
/// List<IMessage> of up to deliveries, settled once after the route.
///
public bool Batching { get; set; }
/// Largest number of deliveries in a batch (default ). At most .
public int? MaxBatchMessages { get; set; }
///
/// Batch mode: a batch with deliveries is sent on once no delivery came for this many milliseconds, restarted by
/// every delivery (default 1000).
///
public int PollTimeoutMs { get; set; } = 1000;
/// Batch mode: a batch is sent on once this many milliseconds have passed since its first delivery.
public int? BatchingIntervalMs { get; set; }
/// The batch options, or null outside batch mode. Set by .
internal BatchOptions? Batch { get; private set; }
///
/// Resolves the batch options. Fails, naming the endpoint, where batch mode cannot work: a batch option without
/// batching=true, a value out of range, a batch larger than (the broker never
/// hands over more unacknowledged deliveries), and an endpoint configured for request-reply (a batch is InOnly).
///
internal void ResolveBatch(string endpoint)
{
Batch = BatchOptions.Resolve(endpoint, Batching, MaxBatchMessages, PollTimeoutMs, BatchingIntervalMs, PrefetchCount);
if (Batch is null)
return;
if (Batch.MaxMessages > PrefetchCount)
throw new InvalidOperationException(
$"Endpoint '{endpoint}': maxBatchMessages={Batch.MaxMessages} is larger than prefetchCount={PrefetchCount}; " +
"the broker never hands over more unacknowledged deliveries than prefetchCount, so such a batch would " +
"only ever close by its timeout. Raise prefetchCount, or lower maxBatchMessages.");
if (ReplyTo)
throw new InvalidOperationException(
$"Endpoint '{endpoint}': batching=true cannot be combined with replyTo=true: a batch is one-way (InOnly) " +
"and nobody would answer a request in it.");
}
// ── Transactions ──
///
/// Consumer: true takes the delivery on a transacted channel. 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.
/// A request-reply producer () always sends at once and refuses true.
///
public bool? Transacted { get; set; }
///
/// Publish over a connection of its own (default: false, one connection for everything with the same settings, as in
/// Spring AMQP). The broker's flow control and resource alarms block a publishing connection as a whole, so a
/// consumer on it can no longer ack. With true, the sends of this endpoint's producer and the RPC replies of
/// its consumer go over a second connection with the same settings (named "... (publisher)"), and the consumer keeps
/// the first one to itself. Two named connection factories separate the connections just as well; only a consumer's
/// replies need this option.
///
public bool PublisherConnection { get; set; }
/// Use mandatory flag. Null = auto-detect by exchange type.
public bool? Mandatory { get; set; }
// ── RPC ──
///
/// Request-reply (RPC): the producer publishes the request and waits for the reply on a reply queue of its own. The
/// request's AMQP reply-to is always that queue, overriding a ReplyTo header, since the producer is the
/// one waiting. To send a message that names another reply address without waiting, set the ReplyTo header on
/// an ordinary send with .
///
public bool ReplyTo { get; set; }
///
/// Apache Camel preserveMessageQos: an ordinary (not request-reply) send keeps the ReplyTo header as the
/// message's AMQP reply-to. Off by default, as in Camel's JMS: a message consumed with a sender's reply-to
/// and forwarded to this endpoint does not carry that reply-to on, so no consumer answers into a queue of another
/// system. The correlation id is always carried.
///
public bool PreserveMessageQos { get; set; }
/// RPC timeout in seconds (default: 60).
public int Timeout { get; set; } = 60;
///
/// Maximum number of unconfirmed (in-flight) publishes allowed on a producer channel
/// before
/// awaits broker confirmation. Default: 2048.
///
/// Bound to a ThrottlingRateLimiter wired into CreateChannelOptions.outstandingPublisherConfirmationsRateLimiter.
/// Without this limit, RabbitMQ.Client 7.x falls back to its default rate limiter that returns
/// "Could not acquire a lease from the rate limiter" under sustained publish bursts.
///
///
public int MaxOutstandingConfirms { get; set; } = 2048;
///
/// How long a send may take until the broker has taken it, in milliseconds (default 5000, as Apache Camel's
/// confirmTimeout). It covers the wait for the producer's channel, the publish and the broker's confirm (for a
/// transacted block: its publishes and the tx.commit); for a request-reply call it covers the request's
/// publish, and the wait for the reply.
///
/// A broker that blocks its publishers (a memory or disk alarm) sends no confirm, so without this bound the send would
/// wait for as long as the alarm lasts. On expiry the send fails with ;
/// the message may still reach the queue later, when the broker resumes.
///
///
public int ConfirmTimeout { get; set; } = 5000;
// ── Queue arguments ──
/// Message TTL in milliseconds (x-message-ttl). 0 = disabled.
public int MessageTtl { get; set; }
/// Queue expiry in milliseconds (x-expires). 0 = disabled.
public int Expires { get; set; }
/// Maximum queue length in messages (x-max-length). 0 = unlimited.
public int MaxLength { get; set; }
/// Maximum queue size in bytes (x-max-length-bytes). 0 = unlimited.
public int MaxLengthBytes { get; set; }
/// Overflow strategy: drop-head, reject-publish, reject-publish-dlx (x-overflow).
public string? Overflow { get; set; }
/// Dead-letter exchange name (x-dead-letter-exchange). Critical for error handling.
public string? DeadLetterExchange { get; set; }
/// Dead-letter routing key (x-dead-letter-routing-key).
public string? DeadLetterRoutingKey { get; set; }
/// Queue type: classic, quorum, stream (x-queue-type). Quorum and stream queues are replicated across cluster nodes.
public string? QueueType { get; set; }
/// Maximum priority level for priority queues (x-max-priority). 0 = disabled.
public int MaxPriority { get; set; }
// ── Connection resilience ──
/// Enable automatic recovery (default: true).
[ConnectionParameter]
public bool AutomaticRecovery { get; set; } = true;
/// Re-declare topology after recovery (default: true). Critical for cluster.
[ConnectionParameter]
public bool TopologyRecoveryEnabled { get; set; } = true;
/// Network recovery interval in seconds (default: 5).
[ConnectionParameter]
public int RecoveryInterval { get; set; } = 5;
/// Requested heartbeat interval in seconds (default: 60).
[ConnectionParameter]
public int Heartbeat { get; set; } = 60;
/// Connection timeout in seconds (default: 60). Prevents hangs on unreachable nodes.
[ConnectionParameter]
public int ConnectionTimeout { get; set; } = 60;
/// Socket read timeout in seconds (default: 30).
[ConnectionParameter]
public int SocketReadTimeout { get; set; } = 30;
/// Socket write timeout in seconds (default: 30).
[ConnectionParameter]
public int SocketWriteTimeout { get; set; } = 30;
/// AMQP continuation timeout in seconds (default: 30).
[ConnectionParameter]
public int ContinuationTimeout { get; set; } = 30;
/// Concurrent dispatch limit per connection (default: 1).
[ConnectionParameter]
public ushort ConsumerDispatchConcurrency { get; set; } = 1;
// ── SSL ──
/// Enable SSL/TLS for the connection.
[ConnectionParameter]
public bool Ssl { get; set; }
///
/// The name the broker certificate must carry. Unset, each host of the list is checked against its own name; set it
/// when the certificate names a load balancer or an alias.
///
[ConnectionParameter]
public string? SslServerName { get; set; }
/// Client certificate (PFX) presented for mutual TLS; checked for its validity period at startup.
[ConnectionParameter]
public string? SslCertPath { get; set; }
/// Passphrase of .
[Sensitive]
[ConnectionParameter]
public string? SslCertPassword { get; set; }
///
/// PEM file with the root certificates the broker certificate must chain to, instead of the system trust store — a
/// corporate or private CA without installing it in the operating system.
///
[ConnectionParameter]
public string? SslCaCertPath { get; set; }
///
/// Allowed TLS versions, Tls12, Tls13 or Tls12,Tls13. Unset (None), the operating system
/// chooses. Older versions are refused.
///
[ConnectionParameter]
public System.Security.Authentication.SslProtocols SslProtocols { get; set; }
///
/// Revocation check of the broker certificate: NoCheck (default), Online (CRL and OCSP the
/// certificate points at) or Offline (the operating system's cache only).
///
[ConnectionParameter]
public System.Security.Cryptography.X509Certificates.X509RevocationMode RevocationMode { get; set; }
/// Accept a broker certificate whose revocation status cannot be determined. Default false: refused.
[ConnectionParameter]
public bool RevocationSoftFail { get; set; }
///
/// Plain (default, username and password) or External: the TLS client certificate is the login, no
/// password is sent. External needs ssl=true and sslCertPath.
///
[ConnectionParameter]
public RabbitMQAuthMechanism AuthMechanism { get; set; }
/// The TLS settings of this endpoint's connection, loading the certificate files it names.
internal RabbitMQTlsSettings ResolveTls(string owner) => !Ssl
? RabbitMQTlsSettings.Off
: new RabbitMQTlsSettings(
true,
SslServerName,
string.IsNullOrEmpty(SslCertPath) ? null : RabbitMQTls.LoadClientCertificate(SslCertPath, SslCertPassword, owner),
SslProtocols,
string.IsNullOrEmpty(SslCaCertPath) ? null : RabbitMQTls.LoadCaCertificates(SslCaCertPath, owner),
RevocationMode,
RevocationSoftFail);
///
protected override string? UnknownParameterHint(string name)
=> name.Equals("autoAck", StringComparison.OrdinalIgnoreCase)
? "'autoAck' is replaced by 'ackMode': ackMode=auto for autoAck=true, ackMode=manual (the default) for autoAck=false."
: name.Equals("sslCertPassphrase", StringComparison.OrdinalIgnoreCase)
? "'sslCertPassphrase' is renamed 'sslCertPassword', the name every other connector uses."
: null;
///
public override void Validate()
{
if (PrefetchCount == 0)
throw new ArgumentOutOfRangeException(nameof(PrefetchCount), "PrefetchCount must be greater than 0.");
_ = ConcurrencyOption.Resolve(ConcurrentConsumers, "concurrentConsumers"); // loud on garbage/zero
if (Timeout <= 0)
throw new ArgumentOutOfRangeException(nameof(Timeout), "Timeout must be greater than 0.");
if (ConfirmTimeout <= 0)
throw new ArgumentOutOfRangeException(nameof(ConfirmTimeout), "confirmTimeout must be greater than 0 milliseconds.");
if (MaximumRetryAttempts < 1)
throw new ArgumentOutOfRangeException(nameof(MaximumRetryAttempts),
"maximumRetryAttempts counts the first attempt too and must be at least 1.");
if (RetryDelay < 0)
throw new ArgumentOutOfRangeException(nameof(RetryDelay), "retryDelay cannot be negative.");
if (AckMode == AckMode.Auto && Transacted == true)
throw new ArgumentException(
"ackMode=auto cannot be combined with Transacted: an auto-acked delivery is settled by the broker on hand-off and cannot be transactionally committed or rolled back.");
// A value the broker does not know fails here, naming the option, instead of as a channel error at declare.
// Exchange types beyond the built-in four come from plugins and are x-prefixed (x-delayed-message,
// x-consistent-hash); the built-in names are written the way the broker names them, which is case-sensitive.
var builtInExchangeType = BuiltInExchangeTypes.FirstOrDefault(t => t.Equals(ExchangeType, StringComparison.OrdinalIgnoreCase));
if (builtInExchangeType is not null)
ExchangeType = builtInExchangeType;
else if (!ExchangeType.StartsWith("x-", StringComparison.Ordinal))
throw new ArgumentException(
$"Unknown 'exchangeType' value '{ExchangeType}'. Allowed: {string.Join(", ", BuiltInExchangeTypes)}, or a plugin type starting with 'x-'.");
if (!string.IsNullOrEmpty(QueueType) && !QueueTypes.Contains(QueueType, StringComparer.Ordinal))
throw new ArgumentException($"Unknown 'queueType' value '{QueueType}'. Allowed: {string.Join(", ", QueueTypes)}.");
if (!string.IsNullOrEmpty(Overflow) && !OverflowStrategies.Contains(Overflow, StringComparer.Ordinal))
throw new ArgumentException($"Unknown 'overflow' value '{Overflow}'. Allowed: {string.Join(", ", OverflowStrategies)}.");
// The connection settings of a named factory are checked on the factory; on the URI they are refused next to it.
if (string.IsNullOrEmpty(ConnectionFactory))
RabbitMQTls.Validate(new RabbitMQTls.TlsRules(
Ssl, SslServerName, SslCertPath, SslCertPassword, ClientCertificateObject: false,
SslCaCertPath, CaCertificatesObject: false, SslProtocols, RevocationMode, RevocationSoftFail, AuthMechanism),
"RabbitMQ endpoint");
}
private static readonly string[] BuiltInExchangeTypes = ["direct", "topic", "fanout", "headers"];
private static readonly string[] QueueTypes = ["classic", "quorum", "stream"];
private static readonly string[] OverflowStrategies = ["drop-head", "reject-publish", "reject-publish-dlx"];
///
/// Resolves the mandatory flag. If not explicitly set, uses sensible defaults
/// based on exchange type.
///
internal bool ResolveMandatory()
{
if (Mandatory.HasValue) return Mandatory.Value;
return ExchangeType.ToLowerInvariant() switch
{
"topic" or "fanout" => false,
_ => true
};
}
/// Builds queue arguments dictionary.
internal Dictionary BuildQueueArguments()
{
var args = new Dictionary();
if (MessageTtl > 0) args["x-message-ttl"] = MessageTtl;
if (Expires > 0) args["x-expires"] = Expires;
if (MaxLength > 0) args["x-max-length"] = MaxLength;
if (MaxLengthBytes > 0) args["x-max-length-bytes"] = MaxLengthBytes;
if (!string.IsNullOrEmpty(Overflow)) args["x-overflow"] = Overflow;
if (!string.IsNullOrEmpty(DeadLetterExchange)) args["x-dead-letter-exchange"] = DeadLetterExchange;
if (!string.IsNullOrEmpty(DeadLetterRoutingKey)) args["x-dead-letter-routing-key"] = DeadLetterRoutingKey;
if (!string.IsNullOrEmpty(QueueType)) args["x-queue-type"] = QueueType;
if (MaxPriority > 0) args["x-max-priority"] = MaxPriority;
return args;
}
}