Bundle: redb-route / redb.Route.RabbitMQ (redb.Route.RabbitMQ.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.RabbitMQ/AssemblyInfo.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/AssemblyInfo.cs ---- // redb_Route_RabbitMQ - placeholder for build Path: redb-route/redb.Route.RabbitMQ/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.RabbitMQ/Extensions/ServiceCollectionExtensions.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Route.Extensions; namespace redb.Route.RabbitMQ; /// /// Extension methods for registering the RabbitMQ transport in a DI container. /// public static class ServiceCollectionExtensions { /// /// Registers the in the route context so that /// rabbitmq:// URIs are resolved. /// /// /// services.AddRedbRoute(route => /// { /// route.Services.AddRedbRouteRabbitMQ(); /// route.AddRouteBuilder<MyRoutes>(); /// }); /// /// /// public static IServiceCollection AddRedbRouteRabbitMQ(this IServiceCollection services) { // IRouteContextConfigurator is applied by RouteHostedService at startup -- // the correct registration hook (a lazy marker singleton never fires). services.AddRouteComponent(); return services; } } Path: redb-route/redb.Route.RabbitMQ/Fluent/Rabbit.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/Fluent/Rabbit.cs ---- using System.Text; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.RabbitMQ; /// /// Fluent API for RabbitMQ endpoints. /// /// .From(Rabbit.Queue("orders").Host("broker1").Exchange("exchange", "topic").RoutingKey("order.*")) /// .To(Rabbit.Queue("notifications").Host("broker1").Declare()) /// /// public static class Rabbit { /// Creates a RabbitMQ endpoint for the given queue name. public static RabbitBuilder Queue(string name) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException( "A queue name is required. For an endpoint on an exchange without a queue name (a producer that publishes " + "to the exchange, a consumer on a temporary queue of its own) use Rabbit.Exchange(name, type).", nameof(name)); return new RabbitBuilder(name); } /// /// Creates a RabbitMQ endpoint on an exchange, without a queue name (rabbitmq:?exchange=...). A producer /// publishes to the exchange with the routing key. A consumer reads a temporary queue of its own (exclusive, /// auto-delete) that the broker names and that is bound to the exchange, so every consumer of a fanout exchange /// gets its copy of each message; it needs , and fails at start without it. /// /// Exchange name (template string, supports ${...}). /// Exchange type: direct, topic, fanout or headers. public static RabbitBuilder Exchange(string name, string? type = null) { ArgumentException.ThrowIfNullOrWhiteSpace(name); return new RabbitBuilder(string.Empty).Exchange(name, type); } } /// /// Fluent builder for RabbitMQ endpoint URIs. /// public sealed class RabbitBuilder { private readonly string _queue; // Connection private string? _host; private string? _port; private string? _username; private string? _password; private string? _virtualHost; private string? _connectionFactory; private string? _clientName; // Exchange private string? _exchange; private string? _exchangeType; private bool? _exchangeDurable; private bool? _exchangeAutoDelete; private bool _declare; // Queue private bool? _durable; private bool _autoDelete; private bool _exclusive; private string? _routingKey; // Message private string? _contentType; private string? _messageTtl; private string? _expires; // Consumer private string? _concurrentConsumers; private string? _prefetchCount; private AckMode? _ackMode; private int? _maximumRetryAttempts; private int? _retryDelay; private bool? _rejectAndDontRequeue; private bool _disableReplyTo; private bool _batching; private int? _maxBatchMessages; private int? _pollTimeoutMs; private int? _batchingIntervalMs; private bool? _transacted; private bool? _mandatory; private bool _publisherConnection; private bool _replyTo; private bool _preserveMessageQos; private string? _timeout; private string? _confirmTimeout; // Queue limits private string? _maxLength; private string? _maxLengthBytes; private string? _overflow; private string? _deadLetterExchange; private string? _deadLetterRoutingKey; private string? _queueType; private string? _maxPriority; // Connection settings private bool? _automaticRecovery; private bool? _topologyRecoveryEnabled; private string? _recoveryInterval; private string? _heartbeat; private string? _connectionTimeout; private string? _socketReadTimeout; private string? _socketWriteTimeout; private string? _continuationTimeout; private string? _consumerDispatchConcurrency; // SSL private bool _ssl; private string? _sslServerName; private string? _sslCertPath; private string? _sslCertPassword; private string? _sslCaCertPath; private System.Security.Authentication.SslProtocols _sslProtocols; private System.Security.Cryptography.X509Certificates.X509RevocationMode _revocationMode; private bool _revocationSoftFail; private RabbitMQAuthMechanism _authMechanism; // The entry points check the name: Rabbit.Queue requires one, Rabbit.Exchange passes none. internal RabbitBuilder(string queue) => _queue = queue; // ── Connection ──────────────────────────────────────────────────── /// Broker hostname. Default "localhost". public RabbitBuilder Host(IExpression host) { _host = host.ToTemplateString(); return this; } /// Broker hostname (template string, supports ${...}). Default "localhost". public RabbitBuilder Host(string host) { _host = host; return this; } /// Broker port. Default 5672. public RabbitBuilder Port(int port) { _port = port.ToString(); return this; } /// Broker port from an expression. public RabbitBuilder Port(IExpression port) { _port = port.ToTemplateString(); return this; } /// Username. Default "guest". public RabbitBuilder Username(IExpression username) { _username = username.ToTemplateString(); return this; } /// Username (template string, supports ${...}). Default "guest". public RabbitBuilder Username(string username) { _username = username; return this; } /// Password. Default "guest". public RabbitBuilder Password(IExpression password) { _password = password.ToTemplateString(); return this; } /// Password (template string, supports ${...}). Default "guest". public RabbitBuilder Password(string password) { _password = password; return this; } /// Virtual host. Default "/". public RabbitBuilder VirtualHost(IExpression vhost) { _virtualHost = vhost.ToTemplateString(); return this; } /// Virtual host (template string, supports ${...}). Default "/". public RabbitBuilder VirtualHost(string vhost) { _virtualHost = vhost; return this; } /// Use a named connection factory registered in DI. public RabbitBuilder ConnectionFactory(IExpression name) { _connectionFactory = name.ToTemplateString(); return this; } /// Use a named connection factory registered in DI (template string, supports ${...}). public RabbitBuilder ConnectionFactory(string name) { _connectionFactory = name; return this; } /// Client connection name. Default "redb.Route". public RabbitBuilder ClientName(IExpression name) { _clientName = name.ToTemplateString(); return this; } /// Client connection name (template string, supports ${...}). Default "redb.Route". public RabbitBuilder ClientName(string name) { _clientName = name; return this; } // ── Exchange ────────────────────────────────────────────────────── /// Exchange name and optionally type (direct, topic, fanout, headers). public RabbitBuilder Exchange(IExpression name, string? type = null) { _exchange = name.ToTemplateString(); if (type != null) _exchangeType = type; return this; } /// Exchange name (template string, supports ${...}) and optionally type. public RabbitBuilder Exchange(string name, string? type = null) { _exchange = name; if (type != null) _exchangeType = type; return this; } /// Exchange durability. Default true. public RabbitBuilder ExchangeDurable(bool durable = true) { _exchangeDurable = durable; return this; } /// Exchange auto-delete when last consumer unsubscribes. public RabbitBuilder ExchangeAutoDelete() { _exchangeAutoDelete = true; return this; } /// Declare exchange and queue on startup. public RabbitBuilder Declare() { _declare = true; return this; } // ── Queue ───────────────────────────────────────────────────────── /// Queue durability. Default true. public RabbitBuilder Durable(bool durable = true) { _durable = durable; return this; } /// Auto-delete queue. public RabbitBuilder AutoDelete() { _autoDelete = true; return this; } /// Exclusive queue (only this connection). public RabbitBuilder Exclusive() { _exclusive = true; return this; } /// Routing key for binding. public RabbitBuilder RoutingKey(IExpression key) { _routingKey = key.ToTemplateString(); return this; } /// Routing key (template string, supports ${...} for a per-message key). public RabbitBuilder RoutingKey(string key) { _routingKey = key; return this; } // ── Message ─────────────────────────────────────────────────────── /// Content type. Default "application/json". public RabbitBuilder ContentType(string type) { _contentType = type; return this; } /// Per-message TTL in milliseconds. public RabbitBuilder MessageTtl(int ms) { _messageTtl = ms.ToString(); return this; } /// Per-message TTL from an expression. public RabbitBuilder MessageTtl(IExpression ms) { _messageTtl = ms.ToTemplateString(); return this; } /// Queue expires (auto-delete) after ms of inactivity. 0 = never. public RabbitBuilder Expires(int ms) { _expires = ms.ToString(); return this; } /// Queue expiry from an expression. public RabbitBuilder Expires(IExpression ms) { _expires = ms.ToTemplateString(); return this; } // ── Consumer ────────────────────────────────────────────────────── /// Number of concurrent consumers. Default 1. public RabbitBuilder ConcurrentConsumers(int count) { _concurrentConsumers = count.ToString(); return this; } /// Consumer parallelism as a string: a number or "auto" (= max(CPU, 2)). public RabbitBuilder ConcurrentConsumers(string count) { _concurrentConsumers = count; return this; } /// Concurrent consumers from an expression. public RabbitBuilder ConcurrentConsumers(IExpression count) { _concurrentConsumers = count.ToTemplateString(); return this; } /// Prefetch count. Default 10. public RabbitBuilder PrefetchCount(ushort count) { _prefetchCount = count.ToString(); return this; } /// Prefetch count from an expression. public RabbitBuilder PrefetchCount(IExpression count) { _prefetchCount = count.ToTemplateString(); return this; } /// /// When the delivery is settled. : the broker settles it on hand-off /// (at-most-once), a failed turn does not requeue it. Default (at-least-once). /// Auto cannot be combined with . /// public RabbitBuilder AckMode(AckMode mode) { _ackMode = mode; return this; } /// Attempts on a failed delivery, the first included (Apache Camel maximumRetryAttempts, default 5). public RabbitBuilder MaximumRetryAttempts(int attempts) { _maximumRetryAttempts = attempts; return this; } /// Milliseconds between two attempts on a failed delivery (Apache Camel retryDelay, default 1000). public RabbitBuilder RetryDelay(int milliseconds) { _retryDelay = milliseconds; return this; } /// /// Whether a delivery that failed every attempt is rejected without requeue, to the dead letter exchange (Apache Camel /// rejectAndDontRequeue, default true), or requeued. /// public RabbitBuilder RejectAndDontRequeue(bool value) { _rejectAndDontRequeue = value; return this; } /// The consumer ignores a delivery's reply-to (Apache Camel disableReplyTo): no reply, and a batch takes it. public RabbitBuilder DisableReplyTo() { _disableReplyTo = true; return this; } /// Batch mode (batching=true): the route gets the deliveries as a List<IMessage>. public RabbitBuilder Batching() { _batching = true; return this; } /// Largest number of deliveries in a batch (maxBatchMessages, default and maximum prefetchCount). public RabbitBuilder MaxBatchMessages(int max) { _maxBatchMessages = max; return this; } /// Idle timeout of a batch in milliseconds (pollTimeoutMs, default 1000). public RabbitBuilder PollTimeoutMs(int ms) { _pollTimeoutMs = ms; return this; } /// Hard limit of a batch in milliseconds from its first delivery (batchingIntervalMs). public RabbitBuilder BatchingIntervalMs(int ms) { _batchingIntervalMs = ms; return this; } /// Enable transacted channel. public RabbitBuilder Transacted() { _transacted = true; return this; } /// /// Sets transacted explicitly. false sends at once even inside a .Transacted() block, outside its /// transaction; left unset, a producer follows the block. /// public RabbitBuilder Transacted(bool value) { _transacted = value; return this; } /// Set mandatory flag on published messages. public RabbitBuilder Mandatory() { _mandatory = true; return this; } /// /// Publish over a connection of its own: this endpoint's sends and its consumer's RPC replies go over a second /// connection with the same settings, so the broker blocking publishers cannot stop consumers from acking. /// public RabbitBuilder PublisherConnection() { _publisherConnection = true; return this; } /// Enable request-reply with temporary reply queue. public RabbitBuilder ReplyTo() { _replyTo = true; return this; } /// /// Keep the ReplyTo header as the reply-to of an ordinary send (Apache Camel preserveMessageQos); without it /// a forwarded sender's reply-to is not carried on. /// public RabbitBuilder PreserveMessageQos() { _preserveMessageQos = true; return this; } /// Consumer/producer timeout in seconds. Default 60. public RabbitBuilder Timeout(int seconds) { _timeout = seconds.ToString(); return this; } /// Timeout from an expression. public RabbitBuilder Timeout(IExpression seconds) { _timeout = seconds.ToTemplateString(); return this; } /// /// How long a send may take until the broker has taken it, in milliseconds. Default 5000. A send to a broker that /// blocks its publishers fails with when it expires. /// public RabbitBuilder ConfirmTimeout(int milliseconds) { _confirmTimeout = milliseconds.ToString(); return this; } /// Confirm timeout from an expression. public RabbitBuilder ConfirmTimeout(IExpression milliseconds) { _confirmTimeout = milliseconds.ToTemplateString(); return this; } // ── Queue limits ────────────────────────────────────────────────── /// Max queue length (number of messages). public RabbitBuilder MaxLength(int max) { _maxLength = max.ToString(); return this; } /// Max queue length from an expression. public RabbitBuilder MaxLength(IExpression max) { _maxLength = max.ToTemplateString(); return this; } /// Max queue size in bytes. public RabbitBuilder MaxLengthBytes(int max) { _maxLengthBytes = max.ToString(); return this; } /// Max queue size from an expression. public RabbitBuilder MaxLengthBytes(IExpression max) { _maxLengthBytes = max.ToTemplateString(); return this; } /// Overflow strategy: "drop-head", "reject-publish", "reject-publish-dlx". public RabbitBuilder Overflow(string policy) { _overflow = policy; return this; } /// Dead letter exchange name. public RabbitBuilder DeadLetterExchange(IExpression exchange) { _deadLetterExchange = exchange.ToTemplateString(); return this; } /// Dead letter exchange name (template string, supports ${...}). public RabbitBuilder DeadLetterExchange(string exchange) { _deadLetterExchange = exchange; return this; } /// Dead letter routing key. public RabbitBuilder DeadLetterRoutingKey(IExpression key) { _deadLetterRoutingKey = key.ToTemplateString(); return this; } /// Dead letter routing key (template string, supports ${...}). public RabbitBuilder DeadLetterRoutingKey(string key) { _deadLetterRoutingKey = key; return this; } /// Queue type: "classic", "quorum", "stream". public RabbitBuilder QueueType(string type) { _queueType = type; return this; } /// Max priority level. Default 0 (disabled). public RabbitBuilder MaxPriority(int priority) { _maxPriority = priority.ToString(); return this; } /// Max priority from an expression. public RabbitBuilder MaxPriority(IExpression priority) { _maxPriority = priority.ToTemplateString(); return this; } // ── Connection settings ─────────────────────────────────────────── /// Enable automatic connection recovery. Default true. public RabbitBuilder AutomaticRecovery(bool enabled = true) { _automaticRecovery = enabled; return this; } /// Enable topology recovery. Default true. public RabbitBuilder TopologyRecoveryEnabled(bool enabled = true) { _topologyRecoveryEnabled = enabled; return this; } /// Recovery interval in seconds. Default 5. public RabbitBuilder RecoveryInterval(int seconds) { _recoveryInterval = seconds.ToString(); return this; } /// Recovery interval from an expression. public RabbitBuilder RecoveryInterval(IExpression seconds) { _recoveryInterval = seconds.ToTemplateString(); return this; } /// Heartbeat interval in seconds. Default 60. public RabbitBuilder Heartbeat(int seconds) { _heartbeat = seconds.ToString(); return this; } /// Heartbeat interval from an expression. public RabbitBuilder Heartbeat(IExpression seconds) { _heartbeat = seconds.ToTemplateString(); return this; } /// Connection timeout in seconds. Default 60. public RabbitBuilder ConnectionTimeout(int seconds) { _connectionTimeout = seconds.ToString(); return this; } /// Connection timeout from an expression. public RabbitBuilder ConnectionTimeout(IExpression seconds) { _connectionTimeout = seconds.ToTemplateString(); return this; } /// Socket read timeout in seconds. Default 30. public RabbitBuilder SocketReadTimeout(int seconds) { _socketReadTimeout = seconds.ToString(); return this; } /// Socket read timeout from an expression. public RabbitBuilder SocketReadTimeout(IExpression seconds) { _socketReadTimeout = seconds.ToTemplateString(); return this; } /// Socket write timeout in seconds. Default 30. public RabbitBuilder SocketWriteTimeout(int seconds) { _socketWriteTimeout = seconds.ToString(); return this; } /// Socket write timeout from an expression. public RabbitBuilder SocketWriteTimeout(IExpression seconds) { _socketWriteTimeout = seconds.ToTemplateString(); return this; } /// Continuation timeout in seconds. Default 30. public RabbitBuilder ContinuationTimeout(int seconds) { _continuationTimeout = seconds.ToString(); return this; } /// Continuation timeout from an expression. public RabbitBuilder ContinuationTimeout(IExpression seconds) { _continuationTimeout = seconds.ToTemplateString(); return this; } /// Consumer dispatch concurrency. Default 1. public RabbitBuilder ConsumerDispatchConcurrency(ushort count) { _consumerDispatchConcurrency = count.ToString(); return this; } /// Consumer dispatch concurrency from an expression. public RabbitBuilder ConsumerDispatchConcurrency(IExpression count) { _consumerDispatchConcurrency = count.ToTemplateString(); return this; } // ── SSL ─────────────────────────────────────────────────────────── /// Enable SSL with optional server name and client certificate. public RabbitBuilder Ssl(IExpression? serverName = null, IExpression? certPath = null, IExpression? certPassphrase = null) { _ssl = true; _sslServerName = serverName?.ToTemplateString(); _sslCertPath = certPath?.ToTemplateString(); _sslCertPassword = certPassphrase?.ToTemplateString(); return this; } /// PEM file with the root certificates the broker certificate must chain to, instead of the system trust store. public RabbitBuilder SslCaCertPath(IExpression path) { _sslCaCertPath = path.ToTemplateString(); return this; } /// Allowed TLS versions: Tls12, Tls13 or both. Unset, the operating system chooses. public RabbitBuilder SslProtocols(System.Security.Authentication.SslProtocols protocols) { _sslProtocols = protocols; return this; } /// Revocation check of the broker certificate; accepts an undeterminable status. public RabbitBuilder RevocationMode(System.Security.Cryptography.X509Certificates.X509RevocationMode mode, bool softFail = false) { _revocationMode = mode; _revocationSoftFail = softFail; return this; } /// Log in with the TLS client certificate () instead of a password. public RabbitBuilder AuthMechanism(RabbitMQAuthMechanism mechanism) { _authMechanism = mechanism; return this; } // ── Build ───────────────────────────────────────────────────────── /// Builds the RabbitMQ endpoint URI string. public string Build() { var sb = new StringBuilder(); sb.Append("rabbitmq:"); sb.Append(_queue); var sep = '?'; void Append(string key, string value) { sb.Append(sep); sb.Append(key); sb.Append('='); sb.Append(Uri.EscapeDataString(value)); sep = '&'; } void AppendIf(string key, string? value) { if (value != null) Append(key, value); } void AppendBool(string key, bool value) { if (value) Append(key, "true"); } void AppendBoolExplicit(string key, bool? value) { if (value.HasValue) Append(key, value.Value.ToString().ToLowerInvariant()); } // Connection AppendIf("host", _host); AppendIf("port", _port); AppendIf("username", _username); AppendIf("password", _password); AppendIf("virtualHost", _virtualHost); AppendIf("connectionFactory", _connectionFactory); AppendIf("clientName", _clientName); // Exchange AppendIf("exchange", _exchange); AppendIf("exchangeType", _exchangeType); AppendBoolExplicit("exchangeDurable", _exchangeDurable); AppendBoolExplicit("exchangeAutoDelete", _exchangeAutoDelete); AppendBool("declare", _declare); // Queue AppendBoolExplicit("durable", _durable); AppendBool("autoDelete", _autoDelete); AppendBool("exclusive", _exclusive); AppendIf("routingKey", _routingKey); // Message AppendIf("contentType", _contentType); AppendIf("messageTtl", _messageTtl); AppendIf("expires", _expires); // Consumer AppendIf("concurrentConsumers", _concurrentConsumers); AppendIf("prefetchCount", _prefetchCount); AppendIf("ackMode", _ackMode?.ToString().ToLowerInvariant()); AppendIf("maximumRetryAttempts", _maximumRetryAttempts?.ToString()); AppendIf("retryDelay", _retryDelay?.ToString()); AppendBoolExplicit("rejectAndDontRequeue", _rejectAndDontRequeue); AppendBool("disableReplyTo", _disableReplyTo); AppendBool("batching", _batching); AppendIf("maxBatchMessages", _maxBatchMessages?.ToString()); AppendIf("pollTimeoutMs", _pollTimeoutMs?.ToString()); AppendIf("batchingIntervalMs", _batchingIntervalMs?.ToString()); if (_transacted is { } transacted) Append("transacted", transacted ? "true" : "false"); AppendBoolExplicit("mandatory", _mandatory); AppendBool("replyTo", _replyTo); AppendBool("preserveMessageQos", _preserveMessageQos); AppendBool("publisherConnection", _publisherConnection); AppendIf("timeout", _timeout); AppendIf("confirmTimeout", _confirmTimeout); // Queue limits AppendIf("maxLength", _maxLength); AppendIf("maxLengthBytes", _maxLengthBytes); AppendIf("overflow", _overflow); AppendIf("deadLetterExchange", _deadLetterExchange); AppendIf("deadLetterRoutingKey", _deadLetterRoutingKey); AppendIf("queueType", _queueType); AppendIf("maxPriority", _maxPriority); // Connection settings AppendBoolExplicit("automaticRecovery", _automaticRecovery); AppendBoolExplicit("topologyRecoveryEnabled", _topologyRecoveryEnabled); AppendIf("recoveryInterval", _recoveryInterval); AppendIf("heartbeat", _heartbeat); AppendIf("connectionTimeout", _connectionTimeout); AppendIf("socketReadTimeout", _socketReadTimeout); AppendIf("socketWriteTimeout", _socketWriteTimeout); AppendIf("continuationTimeout", _continuationTimeout); AppendIf("consumerDispatchConcurrency", _consumerDispatchConcurrency); // SSL AppendBool("ssl", _ssl); AppendIf("sslServerName", _sslServerName); AppendIf("sslCertPath", _sslCertPath); AppendIf("sslCertPassword", _sslCertPassword); AppendIf("sslCaCertPath", _sslCaCertPath); if (_sslProtocols != System.Security.Authentication.SslProtocols.None) Append("sslProtocols", _sslProtocols.ToString().Replace(" ", string.Empty)); if (_revocationMode != System.Security.Cryptography.X509Certificates.X509RevocationMode.NoCheck) Append("revocationMode", _revocationMode.ToString()); AppendBool("revocationSoftFail", _revocationSoftFail); if (_authMechanism != RabbitMQAuthMechanism.Plain) Append("authMechanism", _authMechanism.ToString()); return sb.ToString(); } /// Implicit conversion to URI string. public static implicit operator string(RabbitBuilder b) => b.Build(); /// public override string ToString() => Build(); } Path: redb-route/redb.Route.RabbitMQ/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.RabbitMQ/README.md ---- # redb.Route.RabbitMQ RabbitMQ transport for redb.Route. Consumer and producer with exchanges, queues, dead-letter, priority, TTL, and the official RabbitMQ.Client 7.x. [![NuGet](https://img.shields.io/nuget/v/redb.Route.RabbitMQ?label=NuGet&color=blue)](https://www.nuget.org/packages/redb.Route.RabbitMQ) [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue)](../../LICENSE) ## Installation ```bash dotnet add package redb.Route.RabbitMQ ``` ## Usage ### URI Format ``` rabbitmq://queue-name?host=localhost&exchange=my-exchange&routingKey=order.* ``` ### Fluent DSL ```csharp using redb.Route.RabbitMQ; // Consumer with exchange binding From(Rabbit.Queue("orders") .Host("rabbitmq.local") .Username("guest").Password("guest") .Exchange("order-exchange", "topic") .RoutingKey("order.new") .PrefetchCount(50) .ConcurrentConsumers(4)) .Log("Order received") .To("direct://process"); // Producer with dead-letter From("direct://outbound") .To(Rabbit.Queue("events") .Host("rabbitmq.local") .Durable() .MessageTtl(86400000) .DeadLetterExchange("dlx") .DeadLetterRoutingKey("failed")); ``` ### An exchange without a queue name `Rabbit.Exchange(name, type)` builds an endpoint with no queue name (`rabbitmq:?exchange=...`). A producer publishes to the exchange; a consumer reads a temporary queue of its own (exclusive, auto-delete) that the broker names and that is bound to the exchange, so every instance of a fanout consumer gets its copy of each message. The consumer needs `.Declare()`: without it nothing creates and binds the temporary queue, and it fails at start. ```csharp // Every instance of the application gets each notification From(Rabbit.Exchange("ui-notify", "fanout").ConnectionFactory("rabbit").Declare()) .To("direct://push-to-browsers"); From("direct://notify") .To(Rabbit.Exchange("ui-notify", "fanout").ConnectionFactory("rabbit").Declare()); ``` `Rabbit.Queue("")` is refused and names `Rabbit.Exchange`: an empty queue name is a different endpoint, not a queue. ## Fluent Builder API | Category | Methods | |----------|---------| | **Connection** | `.Host()`, `.Port()`, `.Username()`, `.Password()`, `.VirtualHost()`, `.ConnectionFactory()`, `.ClientName()`, `.PublisherConnection()` | | **TLS and login** | `.Ssl(serverName, certPath, certPassphrase)`, `.SslCaCertPath()`, `.SslProtocols()`, `.RevocationMode(mode, softFail)`, `.AuthMechanism()` | | **Recovery** | `.AutomaticRecovery()`, `.TopologyRecoveryEnabled()`, `.RecoveryInterval()`, `.Heartbeat()`, `.ConnectionTimeout()` | | **Exchange** | `.Exchange(name, type?)`, `.ExchangeDurable()`, `.ExchangeAutoDelete()`, `.Declare()` | | **Queue** | `.Durable()`, `.AutoDelete()`, `.Exclusive()`, `.RoutingKey()`, `.MaxLength()`, `.MaxLengthBytes()`, `.Overflow()`, `.QueueType()`, `.MaxPriority()` | | **Consumer** | `.ConcurrentConsumers()`, `.PrefetchCount()`, `.AckMode()`, `.MaximumRetryAttempts()`, `.RetryDelay()`, `.RejectAndDontRequeue()`, `.DisableReplyTo()`, `.Batching()`, `.MaxBatchMessages()`, `.PollTimeoutMs()`, `.BatchingIntervalMs()`, `.Transacted()`, `.Mandatory()`, `.ReplyTo()`, `.PreserveMessageQos()`, `.Timeout()` | | **Message** | `.ContentType()`, `.MessageTtl()`, `.Expires()` | | **DLX** | `.DeadLetterExchange()`, `.DeadLetterRoutingKey()` | > Most builder methods accept both constant values and `IExpression` for runtime resolution via the expression engine. Queues are durable by default, and a consumer without a queue name gets an exclusive temporary queue. A named queue with `durable=false` must also be `exclusive=true` on RabbitMQ 4.3 and later: the broker refuses transient non-exclusive queues there (541 INTERNAL_ERROR, `transient_nonexcl_queues`) unless its configuration permits that deprecated feature. ## Consumer concurrency & acknowledgement - **`.ConcurrentConsumers(N)`** is the single knob for consumer-side parallelism: it sets both the channel's AMQP consumer-dispatch concurrency and the app-level concurrency semaphore, so up to **N** messages from the queue are processed concurrently. Default `1` (strictly serial — message order preserved). With `N > 1`, ordering is not preserved and your processor must be thread-safe. Keep `.PrefetchCount()` ≥ `N` so the broker keeps the parallel slots fed. - **`.AckMode(AckMode.Auto)`** (`ackMode=auto`) switches the consumer to broker-side auto-acknowledge (**at-most-once**): the broker settles each delivery on hand-off, so a failed turn does **not** requeue. The broker never delivers such a message again, but the consumer still tries it again in the process, up to `maximumRetryAttempts` attempts in all (default 5, the first included; a batch the same way): that is the only second chance the message has. A message that fails every attempt is lost, and so is one in work when the process dies. `maximumRetryAttempts=1` turns the in-process retry off: one attempt, then the message is gone. Default `ackMode=manual` (**at-least-once**: ack after a successful turn; a failed one is settled as in [A failed message](#a-failed-message)). `ackMode=auto` cannot be combined with `.Transacted()`. The same option on every broker consumer. ### A failed message As in Apache Camel's spring-rabbitmq, a delivery on which the route fails is tried again in the consumer: `maximumRetryAttempts` attempts in all, the first included (default 5), `retryDelay` milliseconds apart (default 1000), each on a fresh exchange. A delivery that failed every attempt is then rejected without requeue (`rejectAndDontRequeue=true`, the default): the broker hands it to the queue's dead letter exchange when one is configured (`deadLetterExchange` and `deadLetterRoutingKey` with `declare=true`, or `x-dead-letter-exchange` on the queue), and drops it otherwise. `rejectAndDontRequeue=false` nacks it with requeue instead: the broker delivers it again and the attempts start over. A route error handler that handles the failure (`OnException(...).Handled(true)`, a dead letter channel) ends the attempts at once: the delivery is acknowledged. The consumer's own stop is not a failure: a delivery interrupted by it is requeued. ### Batch mode `batching=true` makes the consumer hand the route one exchange per batch of deliveries, by the batch contract every broker of redb.Route follows: - `maxBatchMessages` caps the batch (default and maximum: `prefetchCount`, as the broker never hands over more unacknowledged deliveries); `pollTimeoutMs` (default 1000) sends a batch on once no delivery came for that long, restarted by every delivery; `batchingIntervalMs` sends it on once that long has passed since its first delivery. A batch option without `batching=true`, a value out of range, `maxBatchMessages` above `prefetchCount` and `batching=true` with `replyTo=true` fail the start. - The body is a `List`, one message per delivery with its own body, headers and `redbRmq.*` metadata, even for a batch of one; the size is `body.Count`. `redbRmq.Exchange` and `redbRmq.RoutingKey` are set on the batch message when every delivery agrees. The exchange is InOnly. `Split` over the body gives each part its delivery. - `concurrentConsumers` workers each collect and run one batch at a time; the deliveries the broker hands over (`prefetchCount` at most) are shared among them. - Every delivery of the batch is acknowledged after the route. A failed batch follows the rule of a failed delivery for every delivery in it: the batch is run again up to `maximumRetryAttempts`, `retryDelay` apart, then every delivery is rejected without requeue, to the dead letter exchange (`rejectAndDontRequeue=false`: requeued). - A delivery with a reply-to cannot be answered from a one-way batch: it is not put into the batch but rejected at once without requeue, with an error in the log and the endpoint statistics. `disableReplyTo=true` (Apache Camel's name, single mode too) ignores senders' reply-to: such deliveries are batched and nobody replies. - A batch half collected when the consumer stops is not run: its deliveries are requeued, as are those still waiting. ### A list body A list of `IMessage` (a batch consumer's body, for one) is sent element by element: each element is its own message with its own body and headers, none of the exchange's, routed by the endpoint's options resolved on that element. Each is this producer's single send, so a failure stops the list and the messages before it stay. A plain list (one whose text would be its type name) is refused, and so is any list at a request-reply producer (`replyTo=true`): split it. ## Transactions - **Consumer.** `.Transacted()` takes deliveries on a transacted channel: every ack, and every reject or nack of a failed delivery, is followed by `tx.commit`, so the broker has applied it before the next delivery is settled. The acknowledgement belongs to the consumer, not to the route's `.Transacted()` block: it comes last, after the database and the deferred sends have committed. This works with `concurrentConsumers` above 1 as well. - **Producer.** Inside a route's `.Transacted()` block a publish **joins the transaction**: it goes out once the database has committed and is dropped if the block rolls back. `.Transacted(false)` publishes at once, outside the transaction; `.Transacted()` requires an enclosing block and fails the step outside one. A request-reply producer (`.ReplyTo()`) always publishes at once and refuses `.Transacted()`: a request held back until the commit would wait for a reply that cannot come. - **Several publishes in one block.** The deferred publishes of one producer in a block are committed in one channel transaction, on a channel of the producer's own (a channel with publisher confirms cannot run transactions): they arrive together, in order, or not at all. The producer's batches take turns on that channel, and a channel transaction is markedly slower than publisher confirms. See the framework-wide **Transactions** guide (`TRANSACTIONS.md` in the [redb.Route repository](https://github.com/redbase-app/redb)). ## Headers Exchange headers become AMQP headers of a published message and of an RPC reply, and the AMQP headers of a delivery or an RPC reply come back as exchange headers. A header named after a basic property (`MessageId`, `CorrelationId`, `ReplyTo`...) goes into that property instead; `redbRmq.*` headers are exchange metadata and stay back. The reply-to of a delivery is not carried on: an ordinary (not request-reply) send leaves the `ReplyTo` header out, so a message consumed with a sender's reply-to and forwarded here does not make another consumer answer into a queue of another system, as in Apache Camel's JMS. `preserveMessageQos=true` (`.PreserveMessageQos()`) keeps it, for a bridge that needs it or a route that names a reply address on an ordinary send. The correlation id is always carried; a request-reply send (`replyTo=true`) sets its own reply-to. `headerFilterStrategy=#name` names an `IHeaderFilterStrategy` in the registry that decides which headers the endpoint carries, as in Apache Camel: outgoing for a published request and a consumer's RPC reply, incoming for a delivery and the reply a request-reply producer receives. It replaces the default, `RabbitMQHeaderFilterStrategy`, entirely; derive from that class to add to it. The basic properties and the consumer's `redbRmq.*` metadata 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 }); // rabbitmq://orders?host=localhost&headerFilterStrategy=#correlationOnly ``` ## Part of [redb.Route](../README.md) — ESB & EIP Framework for .NET ## Named connection factory Keep credentials out of the route URI: register a factory in the context registry and reference it by name. A set-but-unknown name fails loud at startup — a typo can never silently fall back to inline URI parameters. The factory is the whole connection, as in Apache Camel: host, port, credentials, virtual host, TLS, timeouts, recovery and client name all come from it. A URI that names a factory and also gives one of those parameters is refused when the endpoint is created, naming the parameters — it would otherwise go to another broker than the one written. Endpoint parameters (exchange, routing key, queue arguments, prefetch and the like) belong on the URI as usual. Endpoints on the same factory share one connection; two factories are two connections, even with the same settings. Endpoints without a factory share a connection when all their connection parameters are the same, and get a connection of their own when any differs. ## Publishing and consuming connections By default producers and consumers with the same settings share one connection, as in Spring AMQP. The broker's flow control and memory or disk alarms block a *publishing* connection as a whole, and a consumer on it can then no longer acknowledge — RabbitMQ recommends separate connections. Two ways to get them: - two named factories, one for the producers and one for the consumers; - `publisherConnection=true` on an endpoint: its producer's sends, and its consumer's RPC replies, go over a second connection with the same settings, shown as `" (publisher)"` in the management UI. A consumer's replies can be moved off its connection only this way. At most two connections per factory (or per set of URI settings) either way, never one per endpoint. ## When the broker blocks its publishers Under a memory or disk alarm the broker stops reading from publishing connections and sends no publisher confirms until the alarm clears. A consumer that stopped reading and a queue without a length limit filling the disk is the usual way there. A send therefore waits at most `confirmTimeout` milliseconds (5000 by default, as Apache Camel's) for the broker to take it, then fails with `RabbitMQPublishTimeoutException`, a `TimeoutException`: - an ordinary send: the wait for the channel, the publish and the confirm; - a send in a transacted block: the block's publishes and the `tx.commit`; - a request-reply call: the request's publish; `timeout` bounds the wait for the reply. ```csharp .OnException().Handled().To("seda://retry-later").End() .To(Rabbit.Exchange("positions").ConfirmTimeout(2000)) ``` A timed-out message may still reach the queue when the broker resumes, so a route that sends it again can deliver it twice. A queue whose messages may be lost under load (positions, statuses) gets a limit on the broker side: `maxLength` or `maxLengthBytes` with `overflow=drop-head`, or a `messageTtl`, or the same as a broker policy. ## When the broker closes a channel A channel-level error — a publish to an exchange that does not exist (404), a failed precondition — closes the channel and keeps the connection, so connection recovery does not reopen it. - **Producer:** the next send opens a new channel (and a new reply queue for `replyTo=true`); only the send that hit the error fails. - **Consumer:** it opens a new channel and subscribes again; unacknowledged deliveries go back to the queue and are delivered again. The same happens when the broker cancels the subscription (the queue was deleted, or its node left); with `declare=true` the queue is declared anew. - A lost *connection* is restored with its channels and subscriptions by automatic recovery (on by default). With `automaticRecovery=false` the consumer opens a new connection and subscribes again itself. While the subscription is lost the endpoint's health is `Warning`, then `Critical` once an attempt to bring it back failed; a Warning is logged when it is lost and an Information when it is back, and `Reconnects` counts each return. Attempts follow `RedbRoute:Reconnect` (delay, multiplier, cap, attempt timeout). A loss is not counted in `Errors`. ```csharp context.AddToRegistry("prod", new RabbitMQConnectionFactory { Host = "rabbit.internal", Username = "svc", Password = secrets.RabbitPassword, }); // rabbitmq://orders?connectionFactory=prod ``` ## Unroutable messages A publish with `mandatory` set that no queue takes comes back from the broker, and the send fails with `RabbitMQUnroutableException` (exchange, routing key, reply code) instead of the message vanishing. `mandatory` is on by default for `direct` and `headers` exchanges and for the default exchange, off for `topic` and `fanout`, where a message nobody subscribed to is normal; set it with `mandatory=true|false`. The same exception comes from every path: - an immediate send, when the broker returns it; - a request-reply call (`replyTo=true`), at once instead of after the timeout; - the sends of a `.Transacted()` block, when the block commits. The channel transaction has then committed the messages that did route, so a retry of the block sends those again. For production queues consider an alternate exchange on the target exchange as well: the broker then keeps what does not route instead of returning it. ```csharp OnException() .Handled() .Log("No queue for ${header.region}: ${exception.message}") .To("rabbitmq://parking-lot") .EndOnException(); ``` ## TLS and login `ssl=true` (or `Ssl = true` on a factory) encrypts the connection; the broker's TLS listener is usually port **5671**, so set the port too — the default stays 5672. Every TLS setting below needs `ssl=true`: given without it, it would be ignored, so the endpoint is refused instead. | Setting (URI / factory) | What it does | |---|---| | `sslServerName` | The name the broker certificate must carry. Unset, each host of a cluster list is checked against its own name; set it when the certificate names a load balancer or an alias. The name is always checked. | | `sslCaCertPath` / `SslCaCertPath`, `SslCaCertificates` | Trust these roots (PEM file, or the certificates themselves on a factory) for the broker certificate instead of the system store — a private or corporate CA without installing it in the OS. | | `sslCertPath` + `sslCertPassword` / `ClientCertificate` | Client certificate for mutual TLS: a PFX file, or on a factory the `X509Certificate2` itself (from the Windows store, a key vault). It must have its private key and be inside its validity period; both are checked before the handshake, naming the certificate. | | `sslProtocols` | `Tls12`, `Tls13` or `Tls12,Tls13`. Unset, the OS chooses. SSL 3.0, TLS 1.0 and 1.1 are refused. | | `revocationMode` + `revocationSoftFail` | Revocation check of the broker certificate: `NoCheck` (default), `Online` (CRL/OCSP), `Offline` (OS cache). An undeterminable status is refused unless `revocationSoftFail=true`; a certificate that names no CRL or OCSP source passes, as in the AS4 connector. | | `authMechanism=External` | Log in with the client certificate (SASL EXTERNAL) — no password is sent; the broker takes the user from the certificate. Needs the broker's `rabbitmq_auth_mechanism_ssl` plugin. | ```csharp context.AddToRegistry("prod", new RabbitMQConnectionFactory { Host = "rmq1.internal, rmq2.internal", Port = 5671, Ssl = true, SslCaCertPath = "/etc/pki/corp-root.pem", ClientCertificate = certificateFromStore, // mutual TLS AuthMechanism = RabbitMQAuthMechanism.External, // the certificate is the login SslProtocols = SslProtocols.Tls13, }); ``` **OAuth 2.0.** A factory with `OAuth2TokenEndpoint`, `OAuth2ClientId` and `OAuth2ClientSecret` (and optionally `OAuth2Scope`) logs in with an access token from the client credentials grant instead of a password, and renews the token on the open connection before it expires, so the broker never closes the connection for an expired token. The token endpoint must be https (plain http only on the loopback address): the client secret is sent to it. Needs the broker's `rabbitmq_auth_backend_oauth2` plugin. Any other source of credentials plugs in as `CredentialsProvider` (an `ICredentialsProvider`). OAuth2, `CredentialsProvider` and `AuthMechanism=External` are three ways to log in; a factory that sets two of them is refused. ```csharp context.AddToRegistry("prod", new RabbitMQConnectionFactory { Host = "rmq.internal", Port = 5671, Ssl = true, OAuth2TokenEndpoint = "https://login.example.com/oauth2/token", OAuth2ClientId = "billing-service", OAuth2ClientSecret = secrets.BillingClientSecret, OAuth2Scope = "rabbitmq.read:*/* rabbitmq.write:*/*", }); ``` Endpoints that share a pooled connection share its TLS identity and login, so the inline pool key includes every TLS and login setting. The integration tests run against a stand with a private CA, mutual TLS, EXTERNAL and OAuth 2.0 (profile `rabbitmq-tls` of the test stand `docker-compose.tests.yml`, see `RabbitMQTlsBrokerTests`). ## 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: ``` concurrentConsumers=4 # a fixed worker count concurrentConsumers=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. Path: redb-route/redb.Route.RabbitMQ/RabbitMQComponent.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/RabbitMQComponent.cs ---- using System.Collections.Concurrent; using Microsoft.Extensions.Logging; using RabbitMQ.Client; using RabbitMQ.Client.OAuth2; using redb.Route.Abstractions; using redb.Route.Extensions; using redb.Route.Core; namespace redb.Route.RabbitMQ; /// /// RabbitMQ transport component for redb.Route. /// Scheme: rabbitmq. /// /// URI format: rabbitmq://queue-name?host=localhost&exchange=my-exchange&routingKey=key /// /// /// Owns a process-wide pool of instances, shared between endpoints /// according to a deterministic key: /// /// If connectionFactory=name is set on the URI — key is "factory:{name}". /// Two factories with identical parameters but different names produce two distinct /// connections (the factory name is the connection identity). /// Otherwise — key is "inline:{host}:{port}/{vhost}@{user}#ssl:sni={sslServerName}:cert={sslCertPath}" /// (the TLS part only with ssl=true, each of its fields only when set). Endpoints /// with identical inline connection parameters share one connection automatically. /// /// Connections are created lazily on first endpoint use and released only when the component /// itself is disposed by . Channels are cheap and remain /// owned by individual producers/consumers; endpoint.Stop() closes channels but never /// pooled connections (so connections survive Stop/Start cycles). /// /// public sealed partial class RabbitMQComponent : ComponentBase { private readonly ConcurrentDictionary>> _connections = new(StringComparer.Ordinal); /// The connections the broker blocks (connection.blocked, under a memory or disk alarm), with its reason. private readonly ConcurrentDictionary _blocked = new(); /// The broker's reason while it blocks ; null when it does not. internal string? BlockedReason(IConnection connection) => _blocked.TryGetValue(connection, out var reason) ? reason : null; /// public override string Scheme => "rabbitmq"; /// Structured XML form: <rabbitmq queue="orders"/>. public override string? StructuredPathSynonym => "queue"; /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var options = new RabbitMQEndpointOptions(); options.BindFromUri(uri.RawParameters); // A connection parameter next to connectionFactory is refused by the core while binding: the options declare // them ([ConnectionParameter]), as a factory is the whole connection in Camel. options.Validate(); options.ResolveBatch(EndpointUri.Sanitize(uri.BaseKey)); return new RabbitMQEndpoint(uri, this, options); } /// /// Returns the shared for the given endpoint, creating it on first /// request. Self-healing: if the cached connection has been closed (auto-recovery gave up, /// broker permanently rejected, etc.) it is evicted and recreated on the next call. /// internal async Task GetOrCreateConnectionAsync(RabbitMQEndpoint endpoint, RabbitMQConnectionUse use, CancellationToken ct) { // publisherConnection=true: publishing gets a second connection with the same settings, so the broker's flow // control or an alarm on it cannot stop the consumers of the first from acking. var publisher = use == RabbitMQConnectionUse.Publish && endpoint.EndpointOptions.PublisherConnection; var key = ResolveConnectionKey(endpoint.EndpointOptions) + (publisher ? PublisherKeySuffix : string.Empty); var lazy = _connections.GetOrAdd(key, k => new Lazy>(() => CreateConnectionAsync(k, endpoint, publisher, ct))); IConnection conn; try { conn = await lazy.Value.ConfigureAwait(false); } catch { // Failed initialization must not poison the slot — evict so the next caller retries. ((ICollection>>>)_connections) .Remove(new KeyValuePair>>(key, lazy)); StopTokenRenewal(key); throw; } if (!conn.IsOpen) { // Broker terminated the connection beyond auto-recovery's reach. // Evict only if our entry is still the cached one (avoid racing another caller). ((ICollection>>>)_connections) .Remove(new KeyValuePair>>(key, lazy)); StopTokenRenewal(key); try { await conn.DisposeAsync().ConfigureAwait(false); } catch (Exception ex) { Logger?.LogDebug(ex, "RabbitMQ: error disposing dead connection [{Key}]", key); } return await GetOrCreateConnectionAsync(endpoint, use, ct).ConfigureAwait(false); } return conn; } private const string PublisherKeySuffix = "|publisher"; /// Number of currently pooled connections (for diagnostics and tests). internal int PooledConnectionCount => _connections.Count; /// Returns a snapshot of the open pooled connections (for diagnostics and tests). internal async Task> GetPooledConnectionsAsync() { var list = new List(); foreach (var lazy in _connections.Values) { if (!lazy.IsValueCreated) continue; try { list.Add(await lazy.Value.ConfigureAwait(false)); } catch { /* skip failed entries */ } } return list; } /// /// Computes the pool key for the given endpoint options. See class XML doc for the rule set. /// internal static string ResolveConnectionKey(RabbitMQEndpointOptions opts) { if (!string.IsNullOrEmpty(opts.ConnectionFactory)) return "factory:" + opts.ConnectionFactory; // A pooled connection is one TLS identity: another server name or client certificate is another connection. return string.Concat( "inline:", opts.Host, ":", opts.Port.ToString(System.Globalization.CultureInfo.InvariantCulture), "/", opts.VirtualHost, "@", opts.Username, opts.Ssl ? "#ssl" : string.Empty, opts.Ssl && !string.IsNullOrEmpty(opts.SslServerName) ? ":sni=" + opts.SslServerName : string.Empty, opts.Ssl && !string.IsNullOrEmpty(opts.SslCertPath) ? ":cert=" + opts.SslCertPath : string.Empty, ConnectionSettingsSuffix(opts)); } private static readonly RabbitMQEndpointOptions DefaultOptions = new(); /// /// The connection settings that differ from the defaults. A shared connection has one set of them, so an endpoint /// with another heartbeat, timeout, recovery policy, client name or password gets a connection of its own rather than /// the first endpoint's. The password enters only as a short hash: the key is written to the log. /// private static string ConnectionSettingsSuffix(RabbitMQEndpointOptions o) { var d = DefaultOptions; var sb = new System.Text.StringBuilder(); void Add(string name, T value, T fallback) { if (!EqualityComparer.Default.Equals(value, fallback)) sb.Append('|').Append(name).Append('=').Append(Convert.ToString(value, System.Globalization.CultureInfo.InvariantCulture)); } Add("heartbeat", o.Heartbeat, d.Heartbeat); Add("connectionTimeout", o.ConnectionTimeout, d.ConnectionTimeout); Add("socketReadTimeout", o.SocketReadTimeout, d.SocketReadTimeout); Add("socketWriteTimeout", o.SocketWriteTimeout, d.SocketWriteTimeout); Add("continuationTimeout", o.ContinuationTimeout, d.ContinuationTimeout); Add("automaticRecovery", o.AutomaticRecovery, d.AutomaticRecovery); Add("topologyRecoveryEnabled", o.TopologyRecoveryEnabled, d.TopologyRecoveryEnabled); Add("recoveryInterval", o.RecoveryInterval, d.RecoveryInterval); Add("consumerDispatchConcurrency", o.ConsumerDispatchConcurrency, d.ConsumerDispatchConcurrency); Add("clientName", o.ClientName, d.ClientName); Add("sslCaCertPath", o.SslCaCertPath, d.SslCaCertPath); Add("sslProtocols", o.SslProtocols, d.SslProtocols); Add("revocationMode", o.RevocationMode, d.RevocationMode); Add("revocationSoftFail", o.RevocationSoftFail, d.RevocationSoftFail); Add("authMechanism", o.AuthMechanism, d.AuthMechanism); if (o.Password != d.Password) { var hash = System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(o.Password)); sb.Append("|pw=").Append(Convert.ToHexString(hash, 0, 4)); } return sb.ToString(); } /// /// Builds the underlying and opens the physical connection. /// Honours registry lookup; /// supports comma-separated host lists for cluster mode. /// private async Task CreateConnectionAsync(string key, RabbitMQEndpoint endpoint, bool publisher, CancellationToken ct) { var (factory, hosts, oauth2) = ResolveConnectionTarget(endpoint.EndpointOptions); if (publisher) factory.ClientProvidedName = $"{factory.ClientProvidedName} (publisher)"; OAuth2ClientCredentialsProvider? tokens = null; if (oauth2 is not null) { var builder = new OAuth2ClientBuilder(oauth2.OAuth2ClientId!, oauth2.OAuth2ClientSecret!, new Uri(oauth2.OAuth2TokenEndpoint!), null); if (!string.IsNullOrEmpty(oauth2.OAuth2Scope)) builder.SetScope(oauth2.OAuth2Scope); tokens = new OAuth2ClientCredentialsProvider(key, await builder.BuildAsync(ct).ConfigureAwait(false)); factory.CredentialsProvider = tokens; } // Always over the endpoint list, even for one host: that overload takes TLS from each endpoint, // and the same list serves failover on the first connect and on recovery. IConnection connection; try { connection = await factory.CreateConnectionAsync(hosts, ct).ConfigureAwait(false); } catch { tokens?.Dispose(); throw; } endpoint.AttachConnectionLifecycleHandlers(connection); // The connection is shared by every endpoint with these settings, so its blocked state is kept here, where // each of them reads it for its health, and not on the endpoint that happened to open it. connection.ConnectionBlockedAsync += (_, args) => { _blocked[connection] = args.Reason; return Task.CompletedTask; }; connection.ConnectionUnblockedAsync += (_, _) => { _blocked.TryRemove(connection, out _); return Task.CompletedTask; }; connection.ConnectionShutdownAsync += (_, _) => { _blocked.TryRemove(connection, out _); return Task.CompletedTask; }; if (tokens is not null) _tokenRenewals[key] = new TokenRenewal(tokens, new CredentialsRefresher(tokens, (credentials, exception, token) => RenewSecretAsync(key, connection, credentials, exception, token), CancellationToken.None)); Logger?.LogInformation( "RabbitMQ connection opened [{Key}]: host={Host}:{Port}, tls={Tls}, vHost={VHost}, login={Login}", key, connection.Endpoint.HostName, connection.Endpoint.Port, connection.Endpoint.Ssl.Enabled, factory.VirtualHost, LoginOf(factory, oauth2)); return connection; } private static string LoginOf(ConnectionFactory factory, RabbitMQConnectionFactory? oauth2) => oauth2 is not null ? $"oauth2 ({oauth2.OAuth2ClientId})" : factory.AuthMechanisms.Any(m => m is ExternalMechanismFactory) ? "client certificate (EXTERNAL)" : factory.CredentialsProvider is { } provider && provider is not BasicCredentialsProvider ? $"credentials provider ({provider.Name})" : factory.UserName; /// /// Puts a renewed access token on the open connection (connection.update-secret), before the old one expires. /// A failed renewal is logged: the broker closes the connection once the old token expires, and recovery then logs in /// with a fresh token. /// private async Task RenewSecretAsync(string key, IConnection connection, Credentials? credentials, Exception? exception, CancellationToken ct) { if (exception is not null || credentials is null) { Logger?.LogError(exception, "RabbitMQ [{Key}]: the OAuth2 access token could not be renewed", key); return; } if (!connection.IsOpen) return; await connection.UpdateSecretAsync(credentials.Password, "OAuth2 access token renewed", ct).ConfigureAwait(false); Logger?.LogDebug("RabbitMQ [{Key}]: OAuth2 access token renewed on the open connection", key); } /// The token source of an OAuth2 connection and the timer that renews its token. private sealed record TokenRenewal(OAuth2ClientCredentialsProvider Tokens, CredentialsRefresher Refresher) : IDisposable { public void Dispose() { Refresher.Dispose(); Tokens.Dispose(); } } private readonly ConcurrentDictionary _tokenRenewals = new(StringComparer.Ordinal); private void StopTokenRenewal(string key) { if (_tokenRenewals.TryRemove(key, out var renewal)) renewal.Dispose(); } /// /// The factory and the hosts it connects to, from one source: the named factory's own settings and host list, /// or the endpoint URI's. Every host carries the TLS settings. The named factory comes back too when it logs in /// with OAuth2, which is set up asynchronously when the connection opens. /// private (ConnectionFactory Factory, IReadOnlyList Hosts, RabbitMQConnectionFactory? OAuth2) ResolveConnectionTarget(RabbitMQEndpointOptions options) { // Named factory from registry — its settings are authoritative; inline overrides are not // applied (matches the historical contract of RabbitMQConnectionFactory.Build()). if (!string.IsNullOrEmpty(options.ConnectionFactory)) { // A set-but-unknown name fails loud — never a silent fallback to URI params. var registryFactory = Context.GetRequiredFromRegistry(options.ConnectionFactory); registryFactory.Validate(options.ConnectionFactory); Logger?.LogDebug("RabbitMQ: using ConnectionFactory '{Name}' from registry", options.ConnectionFactory); var factoryHosts = registryFactory.GetEndpoints($"RabbitMQ connection factory '{options.ConnectionFactory}'", Logger); return (registryFactory.Build(factoryHosts), factoryHosts, registryFactory.UsesOAuth2 ? registryFactory : null); } var hosts = RabbitMQConnectionFactory.BuildEndpoints( options.Host, options.Port, options.ResolveTls("RabbitMQ endpoint"), Logger); var factory = new ConnectionFactory { UserName = options.Username, Password = options.Password, VirtualHost = options.VirtualHost, AutomaticRecoveryEnabled = options.AutomaticRecovery, TopologyRecoveryEnabled = options.TopologyRecoveryEnabled, NetworkRecoveryInterval = TimeSpan.FromSeconds(options.RecoveryInterval), RequestedHeartbeat = TimeSpan.FromSeconds(options.Heartbeat), RequestedConnectionTimeout = TimeSpan.FromSeconds(options.ConnectionTimeout), SocketReadTimeout = TimeSpan.FromSeconds(options.SocketReadTimeout), SocketWriteTimeout = TimeSpan.FromSeconds(options.SocketWriteTimeout), ContinuationTimeout = TimeSpan.FromSeconds(options.ContinuationTimeout), ConsumerDispatchConcurrency = options.ConsumerDispatchConcurrency, ClientProvidedName = options.ClientName, }; if (options.AuthMechanism == RabbitMQAuthMechanism.External) factory.AuthMechanisms = [new ExternalMechanismFactory()]; // The Endpoint setter also sets factory.Ssl from the endpoint, so TLS is never set apart from the hosts. factory.Endpoint = hosts[0]; return (factory, hosts, null); } /// /// Closes every pooled connection. Called by ; /// individual endpoint Stop calls do not close pooled connections (channels only), /// so connections survive Stop/Start cycles intentionally. /// public override async ValueTask DisposeAsync() { foreach (var key in _tokenRenewals.Keys) StopTokenRenewal(key); foreach (var (key, lazy) in _connections.ToArray()) { if (!lazy.IsValueCreated) continue; IConnection? conn = null; try { conn = await lazy.Value.ConfigureAwait(false); } catch { /* failed initialization — nothing to close */ } if (conn is null) continue; try { if (conn.IsOpen) await conn.CloseAsync().ConfigureAwait(false); } catch (Exception ex) { Logger?.LogWarning(ex, "RabbitMQ: error closing pooled connection [{Key}]", key); } try { await conn.DisposeAsync().ConfigureAwait(false); } catch (Exception ex) { Logger?.LogWarning(ex, "RabbitMQ: error disposing pooled connection [{Key}]", key); } } _connections.Clear(); Logger?.LogInformation("RabbitMQ component disposed: connection pool drained"); } } Path: redb-route/redb.Route.RabbitMQ/RabbitMQConnectionFactory.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/RabbitMQConnectionFactory.cs ---- using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using global::RabbitMQ.Client; using Microsoft.Extensions.Logging; using redb.Route.Core; namespace redb.Route.RabbitMQ; /// /// Connection factory configuration for RabbitMQ. Register in the route registry /// and reference by name in endpoint URIs (connectionFactory=myFactory). /// Supports cluster mode via comma-separated hosts. /// public sealed class RabbitMQConnectionFactory { /// Host name or comma-separated list for cluster mode. public string Host { get; set; } = "localhost"; /// AMQP port (default: 5672; the broker's TLS listener is usually 5671). public int Port { get; set; } = 5672; /// Username (default: guest). Not used with or OAuth2. public string Username { get; set; } = "guest"; /// Password (default: guest). Not used with or OAuth2. [Sensitive] public string Password { get; set; } = "guest"; /// Virtual host (default: /). public string VirtualHost { get; set; } = "/"; /// Enable automatic recovery (default: true). public bool AutomaticRecovery { get; set; } = true; /// Re-declare topology (exchanges, queues, bindings) after recovery (default: true). Critical for cluster. public bool TopologyRecoveryEnabled { get; set; } = true; /// Network recovery interval in seconds (default: 5). public int RecoveryInterval { get; set; } = 5; /// Requested heartbeat in seconds (default: 60). public int Heartbeat { get; set; } = 60; /// Connection timeout in seconds (default: 60). Prevents hangs on unreachable cluster nodes. public int ConnectionTimeout { get; set; } = 60; /// Socket read timeout in seconds (default: 30). Detects dead TCP connections faster than heartbeat alone. public int SocketReadTimeout { get; set; } = 30; /// Socket write timeout in seconds (default: 30). public int SocketWriteTimeout { get; set; } = 30; /// Timeout for AMQP protocol-level continuations in seconds (default: 30). Prevents indefinite hangs on declare/bind. public int ContinuationTimeout { get; set; } = 30; /// Concurrent dispatch limit per connection (default: 1). Controls how many messages the client dispatches concurrently. public ushort ConsumerDispatchConcurrency { get; set; } = 1; // ── TLS ── /// Enable TLS for the connection. 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. /// public string? SslServerName { get; set; } /// Client certificate (PFX) presented for mutual TLS. Or give the certificate itself as . public string? SslCertPath { get; set; } /// Passphrase of . [Sensitive] public string? SslCertPassword { get; set; } /// /// Client certificate for mutual TLS, with its private key — from the Windows certificate store, a key vault or /// anywhere else. Checked for its validity period when the connection opens. /// public X509Certificate2? ClientCertificate { get; set; } /// PEM file with the root certificates the broker certificate must chain to, instead of the system trust store. public string? SslCaCertPath { get; set; } /// The root certificates the broker certificate must chain to, instead of the system trust store. public X509Certificate2Collection? SslCaCertificates { get; set; } /// Allowed TLS versions (Tls12, Tls13). (default): the operating system chooses. public SslProtocols SslProtocols { get; set; } /// /// Revocation check of the broker certificate: (default), /// or . /// public X509RevocationMode RevocationMode { get; set; } /// Accept a broker certificate whose revocation status cannot be determined. Default false: refused. public bool RevocationSoftFail { get; set; } // ── Authentication ── /// /// (default) or : the TLS client /// certificate is the login. /// public RabbitMQAuthMechanism AuthMechanism { get; set; } /// /// OAuth 2.0 token endpoint (client credentials grant). Set with and /// , the connection logs in with an access token instead of a password and renews /// it on the open connection before it expires. HTTPS, except on the loopback address. Needs the broker's /// rabbitmq_auth_backend_oauth2 plugin. /// public string? OAuth2TokenEndpoint { get; set; } /// OAuth 2.0 client id. public string? OAuth2ClientId { get; set; } /// OAuth 2.0 client secret. [Sensitive] public string? OAuth2ClientSecret { get; set; } /// Requested scopes, space-separated (optional; for RabbitMQ usually rabbitmq.read:*/* ...). public string? OAuth2Scope { get; set; } /// /// Your own source of credentials (), in place of and /// — a secret store, a token of another identity provider. Not combined with OAuth2. /// public ICredentialsProvider? CredentialsProvider { get; set; } /// Client-provided connection name for management UI. public string ClientName { get; set; } = "redb.Route"; internal bool UsesOAuth2 => !string.IsNullOrEmpty(OAuth2TokenEndpoint); /// Throws when the factory's settings contradict each other; called when a connection is opened with it. /// The factory's registry name, for the error text. public void Validate(string name) { var owner = $"RabbitMQ connection factory '{name}'"; RabbitMQTls.Validate(new RabbitMQTls.TlsRules( Ssl, SslServerName, SslCertPath, SslCertPassword, ClientCertificate is not null, SslCaCertPath, SslCaCertificates is not null, SslProtocols, RevocationMode, RevocationSoftFail, AuthMechanism), owner); var oauthSet = new[] { OAuth2TokenEndpoint, OAuth2ClientId, OAuth2ClientSecret }.Count(v => !string.IsNullOrEmpty(v)); if (oauthSet is > 0 and < 3) throw new ArgumentException($"{owner}: OAuth2 needs OAuth2TokenEndpoint, OAuth2ClientId and OAuth2ClientSecret together."); if (!string.IsNullOrEmpty(OAuth2Scope) && !UsesOAuth2) throw new ArgumentException($"{owner}: OAuth2Scope is given without OAuth2TokenEndpoint."); var logins = new List(); if (UsesOAuth2) logins.Add("OAuth2"); if (CredentialsProvider is not null) logins.Add("CredentialsProvider"); if (AuthMechanism == RabbitMQAuthMechanism.External) logins.Add("AuthMechanism=External"); if (logins.Count > 1) throw new ArgumentException($"{owner}: {string.Join(" and ", logins)} are two ways to log in; choose one."); if (UsesOAuth2) { if (!Uri.TryCreate(OAuth2TokenEndpoint, UriKind.Absolute, out var endpoint) || (endpoint.Scheme != Uri.UriSchemeHttps && !(endpoint.Scheme == Uri.UriSchemeHttp && endpoint.IsLoopback))) throw new ArgumentException( $"{owner}: OAuth2TokenEndpoint '{OAuth2TokenEndpoint}' must be an absolute https URI (http only on the loopback " + "address): the client secret is sent to it."); } } /// /// Creates a configured pointed at the first host. Open the connection with /// CreateConnectionAsync() to fail over across every host of the cluster. /// OAuth2 credentials are set up by the component when it opens the connection (the token is fetched asynchronously /// and renewed on the open connection). /// public ConnectionFactory Build() => Build(GetEndpoints()); internal ConnectionFactory Build(IReadOnlyList endpoints) { var factory = new ConnectionFactory { UserName = Username, Password = Password, VirtualHost = VirtualHost, AutomaticRecoveryEnabled = AutomaticRecovery, TopologyRecoveryEnabled = TopologyRecoveryEnabled, NetworkRecoveryInterval = TimeSpan.FromSeconds(RecoveryInterval), RequestedHeartbeat = TimeSpan.FromSeconds(Heartbeat), RequestedConnectionTimeout = TimeSpan.FromSeconds(ConnectionTimeout), SocketReadTimeout = TimeSpan.FromSeconds(SocketReadTimeout), SocketWriteTimeout = TimeSpan.FromSeconds(SocketWriteTimeout), ContinuationTimeout = TimeSpan.FromSeconds(ContinuationTimeout), ConsumerDispatchConcurrency = ConsumerDispatchConcurrency, ClientProvidedName = ClientName, }; if (AuthMechanism == RabbitMQAuthMechanism.External) factory.AuthMechanisms = [new ExternalMechanismFactory()]; if (CredentialsProvider is not null) factory.CredentialsProvider = CredentialsProvider; // The Endpoint setter also replaces factory.Ssl with the endpoint's own TLS settings, // so TLS travels with the endpoint and is never set on the factory separately. factory.Endpoint = endpoints[0]; return factory; } /// /// Parses the host list into AMQP endpoints, each carrying the TLS settings: a connection opened over an /// endpoint list takes TLS from the endpoints, not from the . /// public List GetEndpoints() => GetEndpoints("RabbitMQ connection factory", null); internal List GetEndpoints(string owner, ILogger? logger) => BuildEndpoints(Host, Port, ResolveTls(owner), logger); /// The TLS settings of this factory, loading the certificate files it names. internal RabbitMQTlsSettings ResolveTls(string owner) { if (!Ssl) return RabbitMQTlsSettings.Off; var client = ClientCertificate; if (client is not null) RabbitMQTls.EnsureClientCertificateUsable(client, owner); else if (!string.IsNullOrEmpty(SslCertPath)) client = RabbitMQTls.LoadClientCertificate(SslCertPath, SslCertPassword, owner); var roots = SslCaCertificates ?? (string.IsNullOrEmpty(SslCaCertPath) ? null : RabbitMQTls.LoadCaCertificates(SslCaCertPath, owner)); return new RabbitMQTlsSettings(true, SslServerName, client, SslProtocols, roots, RevocationMode, RevocationSoftFail); } /// /// The AMQP endpoints of a comma-separated host list, each with the TLS settings. Without an explicit server name /// each endpoint checks the broker certificate against its own host. /// internal static List BuildEndpoints(string hostList, int port, RabbitMQTlsSettings tls, ILogger? logger) { var hosts = hostList.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); if (hosts.Length == 0) throw new InvalidOperationException("RabbitMQ: no host is configured; set host (a name or a comma-separated list)."); return hosts.Select(h => new AmqpTcpEndpoint(h, port, RabbitMQTls.OptionFor(h, tls, logger))).ToList(); } } Path: redb-route/redb.Route.RabbitMQ/RabbitMQConsumer.Batch.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/RabbitMQConsumer.Batch.cs ---- using System.Threading.Channels; using Microsoft.Extensions.Logging; using RabbitMQ.Client; using RabbitMQ.Client.Events; using redb.Route.Abstractions; using redb.Route.Batching; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.RabbitMQ; /// /// Batch mode of the RabbitMQ consumer (batching=true), on the core batch contract: deliveries are buffered as /// they arrive, concurrentConsumers workers each collect a batch from the buffer and run it through the route, /// one batch per worker at a time, and every delivery of a batch is settled once after the route. A failed batch /// follows the rule of a failed single delivery for every delivery in it: tried again up to /// maximumRetryAttempts, retryDelay apart, then rejected without requeue (or requeued). /// public sealed partial class RabbitMQConsumer { private Channel? _deliveries; private CancellationTokenSource? _batchStop; private Task[] _batchWorkers = []; private void StartBatchWorkers(BatchOptions batch, IChannel channel) { _deliveries = Channel.CreateUnbounded(); _batchStop = new CancellationTokenSource(); var stop = _batchStop.Token; _batchWorkers = Enumerable.Range(0, _options.ResolvedConcurrentConsumers) .Select(_ => Task.Run(() => BatchWorkerAsync(batch, channel, stop))) .ToArray(); } /// /// Stops collecting: a batch half collected goes back to the broker, a batch running finishes (the drain waits for /// it), and the deliveries still buffered are requeued. /// private async Task StopBatchWorkersAsync() { if (_batchStop is null) return; await _batchStop.CancelAsync().ConfigureAwait(false); } private async Task AwaitBatchWorkersAsync(IChannel? channel) { if (_batchStop is null) return; try { await Task.WhenAll(_batchWorkers).ConfigureAwait(false); } catch (Exception ex) { _logger?.LogWarning(ex, "RabbitMQ batch worker ended with an error on queue {Queue}", _actualQueueName); } var left = new List(); while (_deliveries!.Reader.TryRead(out var delivery)) left.Add(delivery); if (left.Count > 0 && channel is { IsOpen: true } && _options.AckMode == AckMode.Manual) await SettleManyAsync(channel, left, Settlement.Requeue).ConfigureAwait(false); _batchStop.Dispose(); _batchStop = null; _batchWorkers = []; _deliveries = null; } /// /// A delivery in batch mode: buffered for the workers, its body copied (the client reuses the buffer once the handler /// returns). A delivery that asks for a reply cannot be answered from a one-way batch: unless disableReplyTo /// says to ignore reply-to, it is rejected without requeue at once, by the poison path, and the rest goes on. /// private async Task OnBatchDeliveryAsync(object sender, BasicDeliverEventArgs ea) { var channel = _channel; if (!_options.DisableReplyTo && !string.IsNullOrEmpty(ea.BasicProperties.ReplyTo)) { var refused = new InvalidOperationException( $"RabbitMQ batch consumer on queue '{_actualQueueName}' received a delivery with reply-to " + $"'{ea.BasicProperties.ReplyTo}': a batch is one-way and nobody would answer it, so it is rejected without " + "requeue (to the dead letter exchange, if the queue has one). Set disableReplyTo=true to batch such " + "deliveries without a reply."); _endpoint.RecordError(refused); _logger?.LogError(refused, "{Message}", refused.Message); if (_options.AckMode == AckMode.Manual && channel is { IsOpen: true }) { try { await SettleAsync(channel, ea.DeliveryTag, Settlement.Reject).ConfigureAwait(false); } catch (Exception ex) { _logger?.LogWarning(ex, "RabbitMQ: rejecting a delivery with a reply-to failed"); } } return; } var copy = new BasicDeliverEventArgs(ea.ConsumerTag, ea.DeliveryTag, ea.Redelivered, ea.Exchange, ea.RoutingKey, ea.BasicProperties, ea.Body.ToArray(), CancellationToken.None); _deliveries?.Writer.TryWrite(copy); } private async Task BatchWorkerAsync(BatchOptions batch, IChannel channel, CancellationToken stop) { var settlement = new RabbitBatchSettlement(this, channel); var dispatcher = new BatchDispatcher(Processor, settlement, ToMessage, _endpoint.ScopeFactory, [RmqHeaders.Exchange, RmqHeaders.RoutingKey]); var collector = new BatchCollector(batch, ReceiveAsync); while (!stop.IsCancellationRequested) { CollectedBatch collected; try { collected = await collector.CollectAsync(stop).ConfigureAwait(false); } catch (Exception ex) { _logger?.LogError(ex, "RabbitMQ batch collection failed on queue {Queue}", _actualQueueName); continue; } if (collected.Items.Count == 0) continue; if (collected.Interrupted) { await settlement.ReturnAsync(collected.Items, CancellationToken.None).ConfigureAwait(false); return; } using var inWork = TrackInflight(); var token = ProcessingToken; try { await RunBatchAsync(dispatcher, settlement, collected.Items, token).ConfigureAwait(false); } catch (OperationCanceledException ex) when (IsOwnStop(ex, token)) { return; } catch (Exception ex) { _endpoint.RecordError(ex); _logger?.LogError(ex, "RabbitMQ batch failed to settle on queue {Queue}", _actualQueueName); } } } /// /// Runs one batch, trying it again on failure by the rule of a failed single delivery: up to /// maximumRetryAttempts in all, retryDelay apart, each attempt on a fresh batch exchange; the last /// failure settles every delivery by rejectAndDontRequeue. /// private async Task RunBatchAsync(BatchDispatcher dispatcher, RabbitBatchSettlement settlement, IReadOnlyList items, CancellationToken token) { using var span = BatchDispatcher.StartSpan( (_endpoint.Component as ComponentBase)?.Context, $"{items[0].Exchange} receive", "rabbitmq", _endpoint.Uri.NormalizedKey, items[0].Exchange, items.Select(i => RouteTelemetryExtensions.ExtractTraceContext(i.BasicProperties.Headers, ReadTraceHeader)), items.Count); for (var attempt = 1; ; attempt++) { settlement.FinalAttempt = attempt >= _options.MaximumRetryAttempts; var outcome = await dispatcher.DispatchAsync(items, span, token).ConfigureAwait(false); if (outcome == BatchOutcome.Accepted) { Interlocked.Add(ref _processedCount, items.Count); return; } if (settlement.FinalAttempt) return; _logger?.LogWarning( "RabbitMQ: attempt {Attempt} of {Max} failed on a batch of {Count} on queue {Queue}; the next in {Delay} ms", attempt, _options.MaximumRetryAttempts, items.Count, _actualQueueName, _options.RetryDelay); try { await RetryPauseAsync(token).ConfigureAwait(false); } catch (OperationCanceledException) { await settlement.ReturnAsync(items, CancellationToken.None).ConfigureAwait(false); throw; } } } /// /// The transport's part of collection: the first buffered delivery within , then whatever else /// is already buffered, up to . /// private async ValueTask ReceiveAsync(List into, int max, TimeSpan wait, CancellationToken ct) { var reader = _deliveries!.Reader; using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); timeout.CancelAfter(wait); BasicDeliverEventArgs first; try { first = await reader.ReadAsync(timeout.Token).ConfigureAwait(false); } catch (OperationCanceledException) when (!ct.IsCancellationRequested) { return 0; } catch (ChannelClosedException) { return 0; } into.Add(first); var added = 1; while (added < max && reader.TryRead(out var more)) { into.Add(more); added++; } return added; } /// One delivery into a message, built as a single delivery's exchange message is. private IMessage ToMessage(BasicDeliverEventArgs ea, IExchange batch) { var message = new Message(ea.Body.ToArray()); Fill(message, ea, _headerFilter, batch); return message; } /// Settles every delivery of the same way, then commits once on a transacted channel. private async Task SettleManyAsync(IChannel channel, IReadOnlyList items, Settlement settlement) { foreach (var item in items) { switch (settlement) { case Settlement.Ack: await channel.BasicAckAsync(item.DeliveryTag, multiple: false).ConfigureAwait(false); break; case Settlement.Requeue: await channel.BasicNackAsync(item.DeliveryTag, multiple: false, requeue: true).ConfigureAwait(false); break; default: await channel.BasicRejectAsync(item.DeliveryTag, requeue: false).ConfigureAwait(false); break; } } if (_options.Transacted == true) await channel.TxCommitAsync().ConfigureAwait(false); _logger?.LogDebug("RabbitMQ {Settle}: {Count} deliveries of a batch", settlement, items.Count); } /// /// RabbitMQ's settlement of a batch: by delivery tag, every delivery the same way. With ackMode=auto the /// broker settled them on hand-off and there is nothing to do. /// private sealed class RabbitBatchSettlement(RabbitMQConsumer owner, IChannel channel) : IBatchSettlement { /// Whether a failure settles the batch (the last attempt) or leaves it for the next attempt. public bool FinalAttempt { get; set; } private bool Manual => owner._options.AckMode == AckMode.Manual; public ValueTask BeforeRouteAsync(IExchange batch, IReadOnlyList items, CancellationToken ct) => ValueTask.FromResult(null); public async ValueTask AcceptAsync(IExchange batch, IReadOnlyList items, CancellationToken ct) { if (Manual) await owner.SettleManyAsync(channel, items, Settlement.Ack).ConfigureAwait(false); } public async ValueTask RejectAsync(IExchange batch, IReadOnlyList items, Exception failure, CancellationToken ct) { owner._logger?.LogError(failure, "RabbitMQ batch of {Count} failed on queue {Queue}", items.Count, owner._actualQueueName); if (!FinalAttempt || !Manual) return; await owner.SettleManyAsync(channel, items, owner._options.RejectAndDontRequeue ? Settlement.Reject : Settlement.Requeue).ConfigureAwait(false); } public async ValueTask ReturnAsync(IReadOnlyList items, CancellationToken ct) { if (Manual && channel.IsOpen) await owner.SettleManyAsync(channel, items, Settlement.Requeue).ConfigureAwait(false); } } } Path: redb-route/redb.Route.RabbitMQ/RabbitMQConsumer.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/RabbitMQConsumer.cs ---- using System.Collections.Concurrent; using System.Diagnostics; using System.Text; using Microsoft.Extensions.Logging; using RabbitMQ.Client; using RabbitMQ.Client.Events; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.RabbitMQ; /// /// RabbitMQ consumer. Event-driven async consumer using , on the core's /// : concurrent processing up to concurrentConsumers, transacted channels (TxSelect, and /// a TxCommit after every ack or nack), and automatic RPC reply when the incoming message has ReplyTo set. /// /// A subscription the broker ends while the route runs comes back on the context's reconnect schedule /// (RedbRoute:Reconnect), with the endpoint's health Warning, then Critical, until it does: a channel the broker /// closed (a channel-level error such as 406 PRECONDITION_FAILED, 403, 404), a consumer the broker cancelled (its queue /// was deleted), and a lost connection when the client does not restore consumers itself (automaticRecovery=false /// or topologyRecoveryEnabled=false). With automatic recovery the client restores the connection and the /// subscription; the consumer's supervisor only follows it for health and the log. /// /// public sealed partial class RabbitMQConsumer : PushConsumer { private readonly RabbitMQEndpoint _endpoint; private readonly RabbitMQEndpointOptions _options; private ILogger? _logger; private IChannel? _channel; // The shutdown handler of the current consume channel. It names its channel itself: under automatic recovery the // client raises the event with its inner channel as the sender, never the channel we hold. private AsyncEventHandler? _channelShutdown; /// /// Dedicated channel for RPC reply publish. Created lazily on the first reply. /// Splitting consume/Ack from reply-publish prevents broker-side write backpressure on /// the reply path from blocking the Ack path — each channel has its own broker-side /// per-channel flow-control state, even though they share the underlying TCP connection. /// Channel-level recovery: if the broker closes _replyChannel, the next reply /// reopens it transparently. /// private IChannel? _replyChannel; private readonly SemaphoreSlim _replyChannelLock = new(1, 1); private AsyncEventingBasicConsumer? _consumer; private string? _consumerTag; private string? _actualQueueName; // The subscription's supervisor (created on the first start) and the connection whose recovery it follows. private ConnectionSupervisor? _subscription; private IConnection? _connection; /// Number of messages successfully processed. public long ProcessedCount => Interlocked.Read(ref _processedCount); private long _processedCount; /// Drain timeout for graceful stop (default 30s). internal new TimeSpan DrainTimeout { get => base.DrainTimeout; set => base.DrainTimeout = value; } /// The channel the subscription runs on now (tests break it on purpose). internal IChannel? ConsumeChannel => _channel; /// Known AMQP basic property names that should not leak into user headers. private static readonly HashSet BasicPropertyNames = new(StringComparer.OrdinalIgnoreCase) { "ContentType", "ContentEncoding", "DeliveryMode", "Priority", "CorrelationId", "ReplyTo", "Expiration", "MessageId", "Timestamp", "Type", "UserId", "AppId", "ClusterId" }; /// Creates a RabbitMQ consumer. public RabbitMQConsumer(RabbitMQEndpoint endpoint, IProcessor processor, RabbitMQEndpointOptions options) : base(processor ?? throw new ArgumentNullException(nameof(processor)), ConcurrencyOf(options)) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _options = options ?? throw new ArgumentNullException(nameof(options)); _logger = endpoint.Logger; _headerFilter = endpoint.HeaderFilterStrategy; } // In batch mode the handler only buffers the delivery for the batch workers, which run concurrentConsumers at a time. private static int? ConcurrencyOf(RabbitMQEndpointOptions? options) => options is null ? null : options.Batch is not null ? null : Math.Max(1, options.ResolvedConcurrentConsumers); private readonly IHeaderFilterStrategy _headerFilter; /// protected override IEndpoint ConsumerEndpoint => _endpoint; /// protected override string ConsumerName => $"rabbitmq:{_actualQueueName ?? _endpoint.QueueName}"; // ── Subscription ── /// protected override async Task SubscribeAsync(CancellationToken ct) { if (!_options.Declare && string.IsNullOrEmpty(_endpoint.QueueName)) throw new InvalidOperationException( $"RabbitMQ consumer '{_endpoint.Uri}': an empty queue name asks for a temporary queue, which only " + "declare=true creates and binds; with declare=false name the queue to read."); _logger ??= (_endpoint.Component as ComponentBase)?.Logger; await OpenAsync(ct).ConfigureAwait(false); _subscription = SuperviseConnection($"{ConsumerName} consumer"); // With automatic recovery the client restores the connection (and, with topology recovery, the subscription): // the supervisor follows it for health and the log. _connection = await _endpoint.GetConnectionAsync(RabbitMQConnectionUse.Consume, ct).ConfigureAwait(false); _connection.RecoverySucceededAsync += OnConnectionRecoveredAsync; _connection.ConnectionRecoveryErrorAsync += OnConnectionRecoveryErrorAsync; _logger?.LogDebug( "RabbitMQ consumer subscribed: queue={Queue}, exchange={Exchange}, routingKey={RoutingKey}, prefetch={Prefetch}, concurrent={Concurrent}", _actualQueueName, _options.Exchange, _options.RoutingKey, _options.PrefetchCount, _options.ResolvedConcurrentConsumers); } /// /// Opens the consume channel and subscribes on it: topology, QoS, the transacted mode, the consumer, the batch workers. /// A failure releases the channel and propagates. /// private async Task OpenAsync(CancellationToken ct) { // Consumer channel: no publisher confirms. // We only Ack/Nack (each followed by TxCommit when transacted) here; RPC replies go on a channel of their own. // Enabling publisher confirms tracking on this channel adds latency to every reply // and creates extra contention in the .NET client's confirm-tracking machinery // (each BasicPublishAsync awaits a broker confirm). For RPC replies we explicitly // do not need delivery guarantees — the client either receives the reply within its // own timeout, or treats the call as failed. // ConcurrentConsumers is the single knob for consumer-side parallelism: it sizes both the // AMQP consumer-dispatch concurrency of THIS channel (how many deliveries the client hands us // in parallel) and the base's concurrency limit (the app-level cap on concurrent Process calls). // Without the explicit dispatch value the channel would pin to 1 (ctor default) and every // message would be handled serially regardless of ConcurrentConsumers — the RabbitMQ.Client // 7.x trap this fixes. // In batch mode the handler only buffers the delivery for the batch workers: one dispatch is enough. var dispatchConcurrency = _options.Batch is not null ? (ushort)1 : (ushort)Math.Clamp(_options.ResolvedConcurrentConsumers, 1, ushort.MaxValue); var channel = await _endpoint.CreateChannelAsync( RabbitMQConnectionUse.Consume, publisherConfirms: false, consumerDispatchConcurrency: dispatchConcurrency, ct: ct).ConfigureAwait(false); try { // Topology declaration (exchange, queue, bindings). A temporary queue is read by the name the broker gave // it on that declaration, the one bound to the exchange. _actualQueueName = await _endpoint.DeclareTopologyAsync(channel, RabbitMQConnectionUse.Consume, ct) .ConfigureAwait(false) ?? _endpoint.QueueName; // QoS await channel.BasicQosAsync( prefetchSize: 0, prefetchCount: _options.PrefetchCount, global: false, cancellationToken: ct).ConfigureAwait(false); // Transacted channel if (_options.Transacted == true) { await channel.TxSelectAsync(ct).ConfigureAwait(false); _logger?.LogDebug("RabbitMQ consumer: transacted channel enabled"); } // Consumer setup var consumer = new AsyncEventingBasicConsumer(channel); if (_options.Batch is { } batch) { consumer.ReceivedAsync += OnBatchDeliveryAsync; StartBatchWorkers(batch, channel); } else { consumer.ReceivedAsync += OnMessageReceivedAsync; } consumer.UnregisteredAsync += OnConsumerUnregisteredAsync; _channelShutdown = (_, args) => OnConsumeChannelShutdownAsync(channel, args); channel.ChannelShutdownAsync += _channelShutdown; _channel = channel; _consumer = consumer; // autoAck:true settles every delivery at the broker on hand-off (at-most-once) — no manual // BasicAck/BasicNack, and a throw in Process does NOT requeue. autoAck:false (default) keeps // the post-process manual ack / nack-requeue path. ackMode=auto with Transacted is rejected in Validate(). _consumerTag = await channel.BasicConsumeAsync( queue: _actualQueueName, autoAck: _options.AckMode == AckMode.Auto, consumer: consumer, cancellationToken: ct).ConfigureAwait(false); } catch (Exception ex) { // Channel was created but subsequent setup failed — release it (close + dispose + unregister // from the endpoint's tracking list) to prevent a leak. _logger?.LogDebug(ex, "RabbitMQ consumer subscribe failed: queue={Queue}, exchange={Exchange}", _actualQueueName, _options.Exchange); DetachShutdown(channel); await StopBatchWorkersAsync().ConfigureAwait(false); await AwaitBatchWorkersAsync(null).ConfigureAwait(false); _channel = null; _consumer = null; _consumerTag = null; await _endpoint.ReleaseChannelAsync(channel, CancellationToken.None).ConfigureAwait(false); throw; } } /// /// Replaces a lost subscription: the old channel (closed by the broker, or left without its consumer) is released /// with what was buffered from it, and a new one is opened and subscribed. /// private async Task ReopenAsync(CancellationToken ct) { var old = _channel; if (old is not null) { DetachShutdown(old); // The broker returned the deliveries of a closed channel to the queue: what the batch workers buffered from // it cannot be settled any more and is dropped with it. await StopBatchWorkersAsync().ConfigureAwait(false); await AwaitBatchWorkersAsync(null).ConfigureAwait(false); _channel = null; _consumer = null; _consumerTag = null; await _endpoint.ReleaseChannelAsync(old, CancellationToken.None).ConfigureAwait(false); } await OpenAsync(ct).ConfigureAwait(false); } /// protected override async Task StopAcceptingAsync(CancellationToken ct) { if (_connection is { } connection) { connection.RecoverySucceededAsync -= OnConnectionRecoveredAsync; connection.ConnectionRecoveryErrorAsync -= OnConnectionRecoveryErrorAsync; _connection = null; } // Stop accepting new messages if (_consumer is not null && _consumerTag is not null && _channel is { IsOpen: true }) { try { await _channel.BasicCancelAsync(_consumerTag, cancellationToken: ct).ConfigureAwait(false); } catch (Exception ex) { _logger?.LogWarning(ex, "Error cancelling RabbitMQ consumer"); } } // Batch mode: stop collecting, so a half-collected batch goes back and no new batch starts. await StopBatchWorkersAsync().ConfigureAwait(false); } /// protected override async Task UnsubscribeAsync(CancellationToken ct) { _consumer = null; _consumerTag = null; _subscription = null; // Release the main consume channel. The consumer OWNS this channel, so the consumer must free // it here — RabbitMQEndpoint.Stop() only runs on full context teardown, NOT on a per-route // Stop/Start, so leaving the channel to the endpoint leaks one open (cancelled, idle) channel // per Stop/Start cycle. ReleaseChannelAsync also unregisters it from the endpoint's list, so a // later endpoint.Stop() won't touch it (and double-close is guarded anyway). await AwaitBatchWorkersAsync(_channel).ConfigureAwait(false); IChannel? consumeChannel = _channel; _channel = null; if (consumeChannel is not null) DetachShutdown(consumeChannel); await _endpoint.ReleaseChannelAsync(consumeChannel, ct).ConfigureAwait(false); // Close the dedicated reply channel (if it was ever opened). IChannel? replyChannel; await _replyChannelLock.WaitAsync(ct).ConfigureAwait(false); try { replyChannel = _replyChannel; _replyChannel = null; } finally { _replyChannelLock.Release(); } if (replyChannel is not null) { try { if (replyChannel.IsOpen) await replyChannel.CloseAsync(ct).ConfigureAwait(false); } catch (Exception ex) { _logger?.LogWarning(ex, "RabbitMQ: error closing RPC reply channel"); } try { replyChannel.Dispose(); } catch (Exception ex) { _logger?.LogDebug(ex, "RabbitMQ: error disposing RPC reply channel"); } } } /// The pause before the next attempt on a failed batch: ended by the processing token and by a stop. private async Task RetryPauseAsync(CancellationToken token) { if (_options.RetryDelay <= 0) return; using var pause = CancellationTokenSource.CreateLinkedTokenSource(token, StopToken); await Task.Delay(_options.RetryDelay, pause.Token).ConfigureAwait(false); } // ── Losing the subscription ── // AMQP channel-level errors (access refused, not found, resource locked, precondition failed): the broker closes the // channel and keeps the connection, so connection recovery never reopens it. private static bool IsChannelLevelError(ushort replyCode) => replyCode is 403 or 404 or 405 or 406; private void DetachShutdown(IChannel channel) { if (_channelShutdown is { } handler) channel.ChannelShutdownAsync -= handler; _channelShutdown = null; } private Task OnConsumeChannelShutdownAsync(IChannel channel, ShutdownEventArgs args) { if (IsStopping || args.Initiator == ShutdownInitiator.Application || !ReferenceEquals(channel, _channel) || _subscription is not { } subscription) return Task.CompletedTask; var cause = new IOException( $"RabbitMQ consumer channel on queue {_actualQueueName} closed by the broker: {args.ReplyCode} {args.ReplyText}"); // A channel-level error keeps the connection: nothing but a new channel brings the subscription back. A lost // connection does the same when the client does not restore consumers; when it does, the supervisor waits for its // recovery events. var lost = subscription.Lost(cause); if (lost && (IsChannelLevelError(args.ReplyCode) || !_endpoint.ClientRestoresConsumers)) _ = ResubscribeAsync(subscription, ReopenAsync); return Task.CompletedTask; } private Task OnConsumerUnregisteredAsync(object sender, ConsumerEventArgs args) { // The broker cancels a subscription whose queue was deleted, on a channel that stays open; without a new // subscription the consumer would just go quiet. A cancel of our own (a stop) and one on a closing channel are not // news here. if (IsStopping || _subscription is not { } subscription || sender is not AsyncEventingBasicConsumer { Channel: { IsOpen: true } channel } || !ReferenceEquals(channel, _channel)) return Task.CompletedTask; if (subscription.Lost(new IOException( $"RabbitMQ consumer on queue {_actualQueueName} was cancelled by the broker (the queue was deleted, or its node left)"))) _ = ResubscribeAsync(subscription, ReopenAsync); return Task.CompletedTask; } private Task OnConnectionRecoveredAsync(object sender, AsyncEventArgs args) { // The client restored the connection, and with it the consumer it restores itself. if (!IsStopping && _endpoint.ClientRestoresConsumers) _subscription?.Restored(); return Task.CompletedTask; } private Task OnConnectionRecoveryErrorAsync(object sender, ConnectionRecoveryErrorEventArgs args) { if (!IsStopping && _endpoint.ClientRestoresConsumers) _subscription?.Failed(args.Exception); return Task.CompletedTask; } // ── Message handling ── private async Task OnMessageReceivedAsync(object sender, BasicDeliverEventArgs ea) { // The channel the delivery came on: its tag is valid only there, also after a resubscribe replaced _channel. var channel = (sender as AsyncEventingBasicConsumer)?.Channel ?? _channel; // In ackMode=auto the broker settled the delivery on hand-off: there is nothing to ack or nack. var settleRequired = _options.AckMode == AckMode.Manual; try { if (channel is not { IsOpen: true }) { _logger?.LogWarning("RabbitMQ: channel closed before message could be processed, deliveryTag={DeliveryTag}", ea.DeliveryTag); return; } var body = ea.Body.ToArray(); using var span = StartConsumerSpan(ea); var replyTo = !_options.DisableReplyTo && !string.IsNullOrEmpty(ea.BasicProperties.ReplyTo) ? ea.BasicProperties.ReplyTo : null; // Apache Camel's spring-rabbitmq: a failed delivery is tried again in the consumer, up to // maximumRetryAttempts in all, retryDelay apart, each attempt on a fresh exchange. The consumer's // own stop is not a failure and ends the attempts. // RPC reply: if incoming message has ReplyTo, send response. SendReplyAsync swallows its own errors so a dead // reply queue does NOT prevent us from acking the original message — we still need to advance past // poison/dead-reply messages. var dispatch = await DispatchAsync( () => CreateExchange(ea, body), span, new PushRetry(_options.MaximumRetryAttempts, TimeSpan.FromMilliseconds(Math.Max(0, _options.RetryDelay))), replyTo is null ? null : (exchange, token) => SendReplyAsync(exchange, replyTo, ea.BasicProperties.CorrelationId, span.Activity, token)) .ConfigureAwait(false); switch (dispatch.Outcome) { case PushOutcome.Accepted: // The acknowledgement belongs to this consumer, not to a route's .Transacted() block: the block owns // the database and the outgoing sends, and has committed them by the time Process returns, so the // ack comes last and only a unit of work that ended well is acknowledged. if (settleRequired) { try { await SettleAsync(channel, ea.DeliveryTag, Settlement.Ack).ConfigureAwait(false); } catch (Exception ex) { // An ack failure after a route that ended well (the channel died at settle) is invisible to // the core: the transport records it. One settle per delivery: a second ack or nack of the // same tag is rejected with PRECONDITION_FAILED (unknown delivery tag), which closes the // whole channel, so nothing else is tried. span.Activity.RecordFailure(ex); _endpoint.RecordError(ex); _logger?.LogError(ex, "RabbitMQ message processing error: deliveryTag={DeliveryTag}", ea.DeliveryTag); return; } } Interlocked.Increment(ref _processedCount); break; case PushOutcome.Rejected: // The route failed every attempt: counted by the core's statistics already. Rejected without // requeue (rejectAndDontRequeue: the dead letter exchange gets it) or requeued. In ackMode=auto the // broker took the delivery on hand-off (at-most-once): there is nothing to settle, the error is the // only signal. _logger?.LogError(dispatch.Failure, "RabbitMQ message processing error: deliveryTag={DeliveryTag}", ea.DeliveryTag); if (settleRequired) await SettleQuietlyAsync(channel, ea.DeliveryTag, _options.RejectAndDontRequeue ? Settlement.Reject : Settlement.Requeue).ConfigureAwait(false); break; default: // Refused (arrived after the stop began) or Returned (the stop ended it): the delivery goes back. if (settleRequired) await SettleQuietlyAsync(channel, ea.DeliveryTag, Settlement.Requeue).ConfigureAwait(false); break; } } catch (Exception ex) { // Transport-level failure outside the pipeline - invisible to the core's statistics wrappers, so the endpoint // records it itself. Pipeline errors are counted by the core's StatisticsProcessor - not here, that would // double. The delivery was not settled: the broker redelivers it when the channel closes. _endpoint.RecordError(ex); _logger?.LogError(ex, "Fatal error in RabbitMQ message handler"); } } /// A nack or reject whose own failure (a channel that died) is only logged. private async Task SettleQuietlyAsync(IChannel channel, ulong deliveryTag, Settlement settlement) { try { await SettleAsync(channel, deliveryTag, settlement).ConfigureAwait(false); } catch (Exception ex) { _logger?.LogWarning(ex, "Error settling a failed RabbitMQ message"); } } /// How a delivery is settled. private enum Settlement { /// Consumed. Ack, /// Given back: the broker delivers it again. Requeue, /// Rejected without requeue: the broker hands it to the queue's dead letter exchange, or drops it. Reject, } /// /// Acks the delivery, nacks it with requeue, or rejects it without requeue. On a transacted channel a settle takes /// effect only at tx.commit, so each is followed by a commit, the nack and the reject too: tx.rollback /// would discard it and leave the delivery unacknowledged until the channel closes (Spring AMQP commits a /// transactional reject the same way). Concurrent deliveries on the channel need no lock: a commit applies every /// settle pending on the channel, each of them already final, and the commit that follows each settle at worst finds /// the transaction empty. /// private async Task SettleAsync(IChannel channel, ulong deliveryTag, Settlement settlement) { switch (settlement) { case Settlement.Ack: await channel.BasicAckAsync(deliveryTag, multiple: false).ConfigureAwait(false); break; case Settlement.Requeue: await channel.BasicNackAsync(deliveryTag, multiple: false, requeue: true).ConfigureAwait(false); break; default: await channel.BasicRejectAsync(deliveryTag, requeue: false).ConfigureAwait(false); break; } if (_options.Transacted == true) await channel.TxCommitAsync().ConfigureAwait(false); _logger?.LogDebug("RabbitMQ {Settle}: deliveryTag={DeliveryTag}", settlement, deliveryTag); } // ── Trace context propagation ── /// /// Opens the receive span through the core's transport contract: the parent comes from the message's W3C headers /// only (without them the span is a root, never a child of the dispatch thread's ambient activity), the sender's /// baggage is put back, the span names its endpoint, and EnableTelemetry=false opens nothing. /// private TransportSpan StartConsumerSpan(BasicDeliverEventArgs ea) { var span = RouteTelemetryExtensions.StartConsumerSpan( (_endpoint.Component as ComponentBase)?.Context, $"{ea.Exchange} receive", ActivityKind.Consumer, "messaging.system", "rabbitmq", _endpoint.Uri.NormalizedKey, ea.BasicProperties.Headers, ReadTraceHeader, destination: ea.Exchange, operation: "receive"); if (span.Activity is { IsAllDataRequested: true } activity) { activity.SetTag("messaging.rabbitmq.destination.routing_key", ea.RoutingKey); activity.SetTag("messaging.message.delivery_tag", ea.DeliveryTag); } return span; } /// A trace header as AMQP carries it: RabbitMQ hands string headers over as UTF-8 bytes. private static string? ReadTraceHeader(IDictionary? headers, string name) => headers is not null && headers.TryGetValue(name, out var raw) ? raw switch { null => null, string s => s, byte[] bytes => Encoding.UTF8.GetString(bytes), _ => raw.ToString(), } : null; // ── Exchange creation ── private Exchange CreateExchange(BasicDeliverEventArgs ea, byte[] body) { var message = new Message(body); var pattern = _options.DisableReplyTo || string.IsNullOrEmpty(ea.BasicProperties.ReplyTo) ? ExchangePattern.InOnly : ExchangePattern.InOut; var exchange = Exchange.Create(message, _endpoint.ScopeFactory); exchange.Pattern = pattern; Fill(message, ea, _headerFilter, exchange); return exchange; } /// /// A delivery into (whose body is the delivery's bytes): the AMQP headers as /// lets them in, the redbRmq.* delivery metadata and the basic properties by /// name. One mapping for every inbound path, a consumed message and an RPC reply alike; /// is the one the headers come into (for an RPC reply, the request's). /// internal static void Fill(Message message, BasicDeliverEventArgs ea, IHeaderFilterStrategy headerFilter, IExchange exchange) { // Transfer AMQP headers if (ea.BasicProperties.Headers is not null) { foreach (var header in ea.BasicProperties.Headers) { object? value = header.Value switch { byte[] bytes => Encoding.UTF8.GetString(bytes), string str => str, _ => header.Value }; if (value is null) continue; if (headerFilter.FilterIncoming(header.Key, value, exchange)) continue; message.Headers[header.Key] = value; } } // AMQP metadata as rabbitmq.* headers message.Headers[RmqHeaders.Exchange] = ea.Exchange; message.Headers[RmqHeaders.RoutingKey] = ea.RoutingKey; message.Headers[RmqHeaders.DeliveryTag] = ea.DeliveryTag; message.Headers[RmqHeaders.Redelivered] = ea.Redelivered; message.Headers[RmqHeaders.ConsumerTag] = ea.ConsumerTag; if (!string.IsNullOrEmpty(ea.BasicProperties.ContentType)) { message.Headers[RmqHeaders.ContentType] = ea.BasicProperties.ContentType; message.ContentType = ea.BasicProperties.ContentType; } // Stamp AMQP basic properties into headers by name (the bare well-known names) via cached // reflection — symmetric with the producer's forwarding, so a consume→produce round-trip // carries them through. Simple string/byte properties go through the loop; Timestamp // (AmqpTimestamp) and persistence (DeliveryMode) are explicit — reflection can't map them. foreach (var prop in _stampableProps) { var val = prop.GetValue(ea.BasicProperties); if (val is string s) { if (!string.IsNullOrEmpty(s)) message.Headers[prop.Name] = s; } else if (val is byte b) { if (b > 0) message.Headers[prop.Name] = b; } } if (ea.BasicProperties.Timestamp.UnixTime != 0) message.Headers[RmqHeaders.Timestamp] = ea.BasicProperties.Timestamp.UnixTime; message.Headers["Persistent"] = ea.BasicProperties.Persistent; } /// /// Readable string/byte stamped into /// headers by name via cached reflection. Excludes Headers (bulk-copied), ContentType (explicit — also /// sets Message.ContentType) and DeliveryMode (persistence handled explicitly as a bool). /// private static readonly System.Reflection.PropertyInfo[] _stampableProps = BuildStampableProps(); private static System.Reflection.PropertyInfo[] BuildStampableProps() { var list = new System.Collections.Generic.List(); foreach (var p in typeof(global::RabbitMQ.Client.IReadOnlyBasicProperties).GetProperties()) { if (!p.CanRead) continue; if (p.Name is "Headers" or "ContentType" or "DeliveryMode") continue; if (p.PropertyType == typeof(string) || p.PropertyType == typeof(byte)) list.Add(p); } return list.ToArray(); } // ── RPC reply ── private async Task SendReplyAsync(IExchange exchange, string replyTo, string? correlationId, Activity? span, CancellationToken token) { IChannel? replyChannel; try { replyChannel = await GetOrCreateReplyChannelAsync(token).ConfigureAwait(false); } catch (Exception ex) { if (!IsOwnStop(ex, token)) span.RecordFailure(ex); _logger?.LogWarning(ex, "RabbitMQ: failed to open reply channel for {ReplyTo} — original message will still be acked", replyTo); return; } if (replyChannel is not { IsOpen: true }) { _logger?.LogWarning("RabbitMQ: cannot send RPC reply — reply channel is closed. replyTo={ReplyTo}", replyTo); return; } try { var response = exchange.HasOut ? exchange.Out! : exchange.In; var responseObj = response.Body; var body = responseObj switch { byte[] bytes => bytes, string str => Encoding.UTF8.GetBytes(str), null => Array.Empty(), var other => Encoding.UTF8.GetBytes(other.ToString() ?? string.Empty) }; var properties = new BasicProperties { // The reply's own type, not the request's: a JSON request may well be answered with a PDF. ContentType = response.ContentType ?? _options.ContentType, Persistent = false }; if (!string.IsNullOrEmpty(correlationId)) properties.CorrelationId = correlationId; // Basic property names never become AMQP headers; the endpoint's strategy decides the rest. var headers = new Dictionary(); foreach (var (key, value) in response.Headers) { if (BasicPropertyNames.Contains(key)) continue; if (value is null) continue; if (_headerFilter.FilterOutgoing(key, value, exchange)) continue; headers[key] = value switch { string s => s, byte[] b => b, _ => value.ToString() }; } if (headers.Count > 0) properties.Headers = headers!; // mandatory:false — RPC reply queues are typically auto-generated, exclusive, // auto-delete (amq.gen-*). If the originating client has timed out and disconnected, // its reply queue is already gone. Setting mandatory:true would cause the broker // to send BasicReturn back, which on a confirm-tracking channel surfaces as a // PublishException — pure noise that would block useful work and inflate logs. // We deliberately fire-and-forget the reply: if the client is still listening, // it gets the reply; if not, we move on and ack the original request. await replyChannel.BasicPublishAsync( exchange: string.Empty, routingKey: replyTo, mandatory: false, basicProperties: properties, body: body, cancellationToken: token).ConfigureAwait(false); _logger?.LogDebug("RabbitMQ RPC reply sent: replyTo={ReplyTo}, correlationId={CorrelationId}", replyTo, correlationId); } catch (Exception ex) { // Swallow: a failed reply must NOT prevent acking the original message. // The client will detect failure via its own RPC timeout. // It is still a failure of this delivery, so its span says so. if (!IsOwnStop(ex, token)) span.RecordFailure(ex); _logger?.LogWarning(ex, "RabbitMQ: failed to send RPC reply to {ReplyTo} (correlationId={CorrelationId}) — original message will still be acked", replyTo, correlationId); } } /// /// Returns the dedicated RPC-reply channel, opening it on first use and transparently /// reopening it if the broker has closed it since the last reply (e.g. after a network /// hiccup or channel-level exception). The reply channel always uses /// publisherConfirms: false — RPC reply is best-effort. /// private async Task GetOrCreateReplyChannelAsync(CancellationToken ct) { var current = _replyChannel; if (current is { IsOpen: true }) return current; await _replyChannelLock.WaitAsync(ct).ConfigureAwait(false); try { if (_replyChannel is { IsOpen: true }) return _replyChannel; // Drop the dead channel handle (will be closed by the connection's tracker on close). var dead = _replyChannel; _replyChannel = null; if (dead is not null) { try { dead.Dispose(); } catch (Exception ex) { _logger?.LogDebug(ex, "RabbitMQ: error disposing closed reply channel"); } } _replyChannel = await _endpoint.CreateChannelAsync(RabbitMQConnectionUse.Publish, publisherConfirms: false, ct: ct).ConfigureAwait(false); _logger?.LogDebug("RabbitMQ: dedicated RPC reply channel opened for queue {Queue}", _actualQueueName); return _replyChannel; } finally { _replyChannelLock.Release(); } } } Path: redb-route/redb.Route.RabbitMQ/RabbitMQEndpoint.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/RabbitMQEndpoint.cs ---- using Microsoft.Extensions.Logging; using RabbitMQ.Client; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Extensions; namespace redb.Route.RabbitMQ; /// /// RabbitMQ endpoint. The queue name comes from . /// Manages connection and channel lifecycle for a single URI. /// Supports publisher confirms, automatic recovery, and transacted channels. /// public sealed class RabbitMQEndpoint : EndpointBase { private readonly RabbitMQComponent _component; private readonly List _channels = new(); /// The connections this endpoint publishes over; its health follows the broker's blocking of them. private readonly System.Collections.Concurrent.ConcurrentDictionary _publishConnections = new(); /// /// while the broker blocks a connection this endpoint publishes over /// (a memory or disk alarm): its sends wait for a confirm that does not come and fail after confirmTimeout. /// The endpoint returns to its computed status when the broker unblocks the connection. /// protected override (EndpointHealthStatus Status, string Reason)? TransportCondition { get { foreach (var connection in _publishConnections.Keys) { if (_component.BlockedReason(connection) is { } reason) return (EndpointHealthStatus.Critical, $"The broker blocks publishing on this endpoint's connection: {reason}"); } return null; } } /// Queue name from the URI path (may be empty for auto-generated queues). public string QueueName { get; } /// Logger from the parent component. internal ILogger? Logger { get; } /// Typed options (exposed for consumer/producer). internal RabbitMQEndpointOptions EndpointOptions => Options; /// /// Whether the client brings a consumer back by itself after a lost connection: automatic recovery with topology /// recovery, from the endpoint's options or from the registry connection factory it names. Otherwise the consumer /// resubscribes on its own. /// internal bool ClientRestoresConsumers { get { if (Options.ConnectionFactory is { } name && _component.Context.GetRequiredFromRegistry(name) is { } factory) return factory.AutomaticRecovery && factory.TopologyRecoveryEnabled; return Options.AutomaticRecovery && Options.TopologyRecoveryEnabled; } } /// The pooled connection a channel of this use runs over (the same one takes). internal Task GetConnectionAsync(RabbitMQConnectionUse use, CancellationToken ct) => _component.GetOrCreateConnectionAsync(this, use, ct); /// Creates a RabbitMQ endpoint. public RabbitMQEndpoint(EndpointUri uri, RabbitMQComponent component, RabbitMQEndpointOptions options) : base(uri, component, options) { _component = component ?? throw new ArgumentNullException(nameof(component)); QueueName = uri.Path; Logger = component.Logger; // Default exchange routes by queue name — if RoutingKey is not explicitly set, // use QueueName so publish is routed correctly. if (string.IsNullOrEmpty(options.Exchange) && string.IsNullOrEmpty(options.RoutingKey) && !string.IsNullOrEmpty(QueueName)) { options.RoutingKey = QueueName; } _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(RabbitMQHeaderFilterStrategy.Default); /// public override IProducer CreateProducer() => new RabbitMQProducer(this, Options); /// public override IConsumer CreateConsumer(IProcessor processor) => new RabbitMQConsumer(this, processor, Options); /// /// Creates a new channel on the shared connection. Thread-safe. /// Each producer/consumer MUST get its own channel to avoid deadlocks /// (e.g. consumer processing a message that publishes on the same channel blocks confirms). /// Publisher confirms are enabled by default but must be disabled for transacted channels /// (RabbitMQ does not allow confirm + tx mode on the same channel). /// /// What the channel is for: with publisherConnection=true publishing goes over a connection of its own. /// Enable publisher confirms (default true). Set to false for transacted channels. /// /// Per-channel consumer dispatch concurrency. When null the channel inherits the value from the /// connection (). /// /// CRITICAL: the constructor parameter defaults to /// (= 1), NOT null — so omitting it /// pins every channel to serial dispatch and silently overrides the connection-level setting. We /// therefore always pass this value explicitly (null = inherit, N = override). /// /// /// Cancellation token. internal async Task CreateChannelAsync( RabbitMQConnectionUse use, bool publisherConfirms = true, ushort? consumerDispatchConcurrency = null, CancellationToken ct = default) { var connection = await _component.GetOrCreateConnectionAsync(this, use, ct).ConfigureAwait(false); if (use == RabbitMQConnectionUse.Publish) { foreach (var closed in _publishConnections.Keys.Where(c => !c.IsOpen)) _publishConnections.TryRemove(closed, out _); _publishConnections.TryAdd(connection, 0); } // For confirm-tracking channels we MUST supply an explicit ThrottlingRateLimiter sized // to MaxOutstandingConfirms. RabbitMQ.Client 7.x defaults to a tiny built-in limiter // that surfaces as "Could not acquire a lease from the rate limiter" under publish bursts. // // We ALSO pass consumerDispatchConcurrency explicitly (even null) because the ctor's 4th // parameter defaults to 1, not null — omitting it clamps the channel to serial dispatch and // clobbers whatever the connection/ConnectionFactory set. Passing null restores "inherit". var channelOpts = publisherConfirms ? new CreateChannelOptions( publisherConfirmationsEnabled: true, publisherConfirmationTrackingEnabled: true, outstandingPublisherConfirmationsRateLimiter: new ThrottlingRateLimiter( Options.MaxOutstandingConfirms > 0 ? Options.MaxOutstandingConfirms : 2048), consumerDispatchConcurrency: consumerDispatchConcurrency) : new CreateChannelOptions( publisherConfirmationsEnabled: false, publisherConfirmationTrackingEnabled: false, outstandingPublisherConfirmationsRateLimiter: null, consumerDispatchConcurrency: consumerDispatchConcurrency); var channel = await connection.CreateChannelAsync(channelOpts, ct).ConfigureAwait(false); AttachChannelLifecycleHandlers(channel); lock (_channels) { _channels.Add(channel); } Logger?.LogDebug("RabbitMQ channel created (confirms={Confirms})", publisherConfirms); return channel; } /// Number of channels currently tracked by this endpoint (open or not). For diagnostics and tests. internal int TrackedChannelCount { get { lock (_channels) { return _channels.Count; } } } /// /// Unregisters a channel from the endpoint's tracking list and closes+disposes it. /// /// The owner of a channel (a consumer or producer) must call this when it stops, so the channel is /// released on a per-route Stop/Start cycle — is only invoked on full context /// teardown, so relying on it leaks one channel per Stop/Start of an individual route. /// /// Safe to call more than once for the same channel: guards on , /// and removal from the list is idempotent. /// internal async Task ReleaseChannelAsync(IChannel? channel, CancellationToken ct = default) { if (channel is null) return; lock (_channels) { _channels.Remove(channel); } if (channel.IsOpen) { try { await channel.CloseAsync(ct).ConfigureAwait(false); } catch (Exception ex) { Logger?.LogWarning(ex, "Error closing RabbitMQ channel"); } } try { channel.Dispose(); } catch (Exception ex) { Logger?.LogDebug(ex, "Error disposing RabbitMQ channel"); } } /// /// Subscribes diagnostic logging to channel-level events. Without these handlers, /// failures like "message not routed" (BasicReturn), broker-side channel shutdown, /// and callback exceptions are silently swallowed by the .NET client. /// /// /// A returned reply whose client is gone: amq.gen-* is an auto-generated exclusive reply queue, and /// amq.rabbitmq.reply-to.* the direct reply-to pseudo-queue. Once the client timed out, its reply address /// is gone and a late reply comes back — normal, not a problem worth a Warning. /// internal static bool IsTransientReplyTo(string? routingKey) => !string.IsNullOrEmpty(routingKey) && (routingKey.StartsWith("amq.gen-", StringComparison.Ordinal) || routingKey.StartsWith("amq.rabbitmq.reply-to", StringComparison.Ordinal)); private void AttachChannelLifecycleHandlers(IChannel channel) { channel.ChannelShutdownAsync += (sender, args) => { if (args.Initiator == ShutdownInitiator.Application) { Logger?.LogDebug("RabbitMQ channel shutdown by application: {Reason}", args.ReplyText); } else { Logger?.LogWarning( "RabbitMQ channel shutdown unexpectedly: initiator={Initiator}, code={Code}, reason={Reason}", args.Initiator, args.ReplyCode, args.ReplyText); } return Task.CompletedTask; }; channel.CallbackExceptionAsync += (sender, args) => { Logger?.LogError(args.Exception, "RabbitMQ channel callback exception in {Detail}", args.Detail); return Task.CompletedTask; }; channel.BasicReturnAsync += (sender, args) => { if (IsTransientReplyTo(args.RoutingKey)) { Logger?.LogDebug( "RabbitMQ BasicReturn (transient reply-to): routingKey={RoutingKey}, code={Code}, reason={Reason}", args.RoutingKey, args.ReplyCode, args.ReplyText); } else { Logger?.LogWarning( "RabbitMQ BasicReturn: exchange={Exchange}, routingKey={RoutingKey}, code={Code}, reason={Reason}, bodySize={Size} — message NOT routed", args.Exchange, args.RoutingKey, args.ReplyCode, args.ReplyText, args.Body.Length); } return Task.CompletedTask; }; channel.BasicNacksAsync += (sender, args) => { Logger?.LogWarning( "RabbitMQ BasicNack from broker: deliveryTag={Tag}, multiple={Multiple} — publish was rejected", args.DeliveryTag, args.Multiple); return Task.CompletedTask; }; } /// /// Subscribes diagnostic logging to connection-level events. Invoked by /// exactly once per pooled connection. /// internal void AttachConnectionLifecycleHandlers(IConnection connection) { connection.ConnectionShutdownAsync += (sender, args) => { if (args.Initiator == ShutdownInitiator.Application) { Logger?.LogInformation("RabbitMQ connection shutdown by application: {Reason}", args.ReplyText); } else { Logger?.LogWarning( "RabbitMQ connection shutdown unexpectedly: initiator={Initiator}, code={Code}, reason={Reason}", args.Initiator, args.ReplyCode, args.ReplyText); } return Task.CompletedTask; }; connection.RecoverySucceededAsync += (sender, args) => { // The host the pooled connection recovered to, not this endpoint's URI host (a connection factory may name another). Logger?.LogInformation("RabbitMQ connection recovery SUCCEEDED: host={Host}:{Port}", connection.Endpoint.HostName, connection.Endpoint.Port); return Task.CompletedTask; }; connection.ConnectionBlockedAsync += (sender, args) => { Logger?.LogWarning("RabbitMQ connection BLOCKED by broker: reason={Reason} — publish paused", args.Reason); return Task.CompletedTask; }; connection.ConnectionUnblockedAsync += (sender, args) => { Logger?.LogInformation("RabbitMQ connection UNBLOCKED — publish resumed"); return Task.CompletedTask; }; connection.CallbackExceptionAsync += (sender, args) => { Logger?.LogError(args.Exception, "RabbitMQ connection callback exception in {Detail}", args.Detail); return Task.CompletedTask; }; } /// /// Declares exchange, queue, and bindings according to endpoint options. /// /// /// Declares the exchange, the queue and its binding when declare=true. An empty queue name is a temporary /// queue that only a consumer has: the broker names it, it is bound and returned, and the consumer reads that /// name. A producer with an empty queue name declares the exchange only, a queue of its own would take copies of /// what it publishes and nobody would read them. /// /// The name of the declared queue, or null when no queue was declared. internal async Task DeclareTopologyAsync(IChannel channel, RabbitMQConnectionUse use, CancellationToken ct = default) { if (!Options.Declare) return null; var exchangeName = Options.Exchange; var queueName = QueueName; var routingKey = Options.RoutingKey; // 1. Declare exchange if named if (!string.IsNullOrEmpty(exchangeName)) { await channel.ExchangeDeclareAsync( exchange: exchangeName, type: Options.ExchangeType, durable: Options.ExchangeDurable, autoDelete: Options.ExchangeAutoDelete, arguments: null, cancellationToken: ct).ConfigureAwait(false); Logger?.LogDebug("RabbitMQ exchange declared: {Exchange} (type={Type})", exchangeName, Options.ExchangeType); } // 2. Declare queue var isTemporary = string.IsNullOrEmpty(queueName); if (isTemporary && use != RabbitMQConnectionUse.Consume) return null; var queueArgs = Options.BuildQueueArguments(); var result = await channel.QueueDeclareAsync( queue: queueName, durable: !isTemporary && Options.Durable, exclusive: isTemporary || Options.Exclusive, autoDelete: isTemporary || Options.AutoDelete, arguments: queueArgs.Count > 0 ? queueArgs! : null, cancellationToken: ct).ConfigureAwait(false); Logger?.LogDebug("RabbitMQ queue declared: {Queue} (durable={Durable})", result.QueueName, Options.Durable); // 3. Bind queue to exchange if (!string.IsNullOrEmpty(exchangeName)) { await channel.QueueBindAsync( queue: result.QueueName, exchange: exchangeName, routingKey: routingKey, arguments: null, cancellationToken: ct).ConfigureAwait(false); Logger?.LogDebug("RabbitMQ queue bound: {Queue} → {Exchange} (routingKey={RoutingKey})", result.QueueName, exchangeName, routingKey); } return result.QueueName; } /// public override async Task Stop(CancellationToken ct = default) { // Close channels owned by this endpoint. The pooled IConnection is owned by // RabbitMQComponent and is NOT closed here — it survives Stop/Start cycles and is // released only on RouteContext.DisposeAsync (which calls Component.DisposeAsync). List channelsCopy; lock (_channels) { channelsCopy = new List(_channels); _channels.Clear(); } foreach (var ch in channelsCopy) { if (ch is { IsOpen: true }) { try { await ch.CloseAsync(ct).ConfigureAwait(false); } catch (Exception ex) { Logger?.LogWarning(ex, "Error closing RabbitMQ channel"); } } try { ch.Dispose(); } catch (Exception ex) { Logger?.LogDebug(ex, "Error disposing RabbitMQ channel"); } } Logger?.LogInformation("RabbitMQ endpoint stopped: {Uri}", EndpointUri.ForLog(Uri.ToString(), Logger)); } } /// What a channel is opened for, which decides its connection when publisherConnection=true. internal enum RabbitMQConnectionUse { /// Consuming and acknowledging. Consume, /// Publishing: producer sends, RPC requests with their reply queue, and a consumer's RPC replies. Publish, } 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; } } Path: redb-route/redb.Route.RabbitMQ/RabbitMQHeaderFilterStrategy.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/RabbitMQHeaderFilterStrategy.cs ---- using redb.Route.Abstractions; namespace redb.Route.RabbitMQ; /// /// The default of the RabbitMQ component, Apache Camel's /// RabbitMQHeaderFilterStrategy. An endpoint's headerFilterStrategy=#name replaces it; derive from it to /// add to it. /// /// A producer's request and a consumer's RPC reply carry every exchange header but the component's own /// redbRmq.* and null values as AMQP headers; a consumed message and an RPC reply bring every AMQP header in. /// Whatever the strategy, a header named after a basic property of the message (MessageId, CorrelationId, /// ReplyTo...) goes into that property, not into the headers, and the delivery metadata /// (redbRmq.*, the basic properties by name) is set by the consumer. /// /// public class RabbitMQHeaderFilterStrategy : IHeaderFilterStrategy { /// The default strategy of a RabbitMQ endpoint. public static RabbitMQHeaderFilterStrategy Default { get; } = new(); /// public virtual bool FilterOutgoing(string name, object? value, IExchange exchange) => value is null || RmqHeaders.IsRedbHeader(name); /// public virtual bool FilterIncoming(string name, object? value, IExchange exchange) => false; } Path: redb-route/redb.Route.RabbitMQ/RabbitMQProducer.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/RabbitMQProducer.cs ---- using System.Collections.Concurrent; using System.Diagnostics; using System.Text; using Microsoft.Extensions.Logging; using RabbitMQ.Client; using RabbitMQ.Client.Events; using redb.Route.Abstractions; using redb.Route.Transactions; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.RabbitMQ; /// /// RabbitMQ producer. Sends messages to an exchange/queue with support for: /// /// Immediate — direct publish via BasicPublishAsync. /// Transactional — deferred publish via . The message is /// captured (cloned) at Process time and only sent on Commit. /// RPC — request/reply pattern with a temporary reply queue and /// correlation-based response routing. /// /// public sealed class RabbitMQProducer : ConnectableProducer { private readonly RabbitMQEndpoint _endpoint; private readonly RabbitMQEndpointOptions _options; private IChannel? _channel; // ── RPC infrastructure ── private readonly ConcurrentDictionary _pendingResponses = new(); private readonly IHeaderFilterStrategy _headerFilter; /// An RPC request waiting for its reply: the reply's headers are filtered against the request exchange. private sealed record PendingReply(TaskCompletionSource Reply, IExchange Request); private string? _replyQueueName; private AsyncEventingBasicConsumer? _responseConsumer; private string? _responseConsumerTag; private readonly SemaphoreSlim _rpcLock = new(1, 1); private volatile bool _rpcSetup; /// /// Serialises /// calls on the producer's single channel. RabbitMQ.Client 7.x is documented as NOT thread-safe /// when multiple concurrent BasicPublishAsync calls run on the same channel with publisher /// confirm tracking enabled — the in-flight delivery-tag bookkeeping races and produces /// PRECONDITION_FAILED on confirm callbacks. /// The lock is per-Producer (each Producer instance owns its own channel), so two routes /// with their own producers publish in parallel; only the same Producer's calls are serialised. /// private readonly SemaphoreSlim _publishLock = new(1, 1); // The deferred publishes of a block go out as one batch per producer, on a channel of its own in tx mode (a channel // with publisher confirms cannot run transactions); the batches take turns on it. private readonly string _batchKey = $"rabbitmq-batch-{Guid.NewGuid():N}"; private readonly SemaphoreSlim _commitLock = new(1, 1); private IChannel? _txChannel; /// Known AMQP basic property names that should not be propagated as custom headers. private static readonly HashSet BasicPropertyNames = new(StringComparer.OrdinalIgnoreCase) { "ContentType", "ContentEncoding", "DeliveryMode", "Persistent", "Priority", "CorrelationId", "ReplyTo", "Expiration", "MessageId", "Timestamp", "Type", "UserId", "AppId", "ClusterId" }; /// protected override IEndpoint ProducerEndpoint => _endpoint; /// protected override string ProducerName => $"rabbitmq:{_options.Exchange}/{_options.RoutingKey}"; /// Creates a RabbitMQ producer. public RabbitMQProducer(RabbitMQEndpoint endpoint, RabbitMQEndpointOptions options) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _options = options ?? throw new ArgumentNullException(nameof(options)); _headerFilter = endpoint.HeaderFilterStrategy; // A request-reply send cannot wait for the commit: the reply it waits for would never come. if (_options.ReplyTo && _options.Transacted == true) throw new InvalidOperationException( $"'{ProducerName}' is a request-reply producer (replyTo=true): the request has to leave at once for its " + "reply to arrive, so it cannot be deferred to the commit of a transaction. Drop transacted=true: a " + "request-reply send always goes out at once, outside the transaction."); } /// protected override async Task ConnectAsync(CancellationToken ct) { _channel = await _endpoint.CreateChannelAsync(RabbitMQConnectionUse.Publish, ct: ct).ConfigureAwait(false); try { // Declare topology if requested await _endpoint.DeclareTopologyAsync(_channel, RabbitMQConnectionUse.Publish, ct).ConfigureAwait(false); // RPC: set up reply queue eagerly if (_options.ReplyTo) await SetupResponseQueueAsync(ct).ConfigureAwait(false); } catch (Exception ex) { Logger?.LogError(ex, "RabbitMQ producer ConnectAsync failed for {Exchange}/{RoutingKey}", _options.Exchange, _options.RoutingKey); try { await _channel.CloseAsync(ct).ConfigureAwait(false); } catch (Exception closeEx) { Logger?.LogWarning(closeEx, "RabbitMQ: error closing channel during ConnectAsync cleanup"); } _channel.Dispose(); _channel = null; throw; } } /// protected override async Task DisconnectAsync(CancellationToken ct) { // Cancel pending RPC responses foreach (var pending in _pendingResponses) { pending.Value.Reply.TrySetCanceled(ct); } _pendingResponses.Clear(); // Shut down response consumer if (_responseConsumer is not null && _responseConsumerTag is not null && _channel is { IsOpen: true }) { try { await _channel.BasicCancelAsync(_responseConsumerTag, cancellationToken: ct).ConfigureAwait(false); } catch (Exception ex) { Logger?.LogDebug(ex, "RabbitMQ: error cancelling response consumer during stop"); } } _responseConsumer = null; _responseConsumerTag = null; _rpcSetup = false; if (_txChannel is not null) { try { await _txChannel.CloseAsync(ct).ConfigureAwait(false); } catch (Exception ex) { Logger?.LogDebug(ex, "RabbitMQ: error closing the transacted channel during stop"); } _txChannel.Dispose(); _txChannel = null; } } /// public override async Task Process(IExchange exchange, CancellationToken ct = default) { EnsureStarted(); // A list of IMessage is sent element by element, each element its own message with its own body, headers and // routing: the send of each is this producer's single send on an exchange of its own, as a Split part's. A // plain list has no wire form here, and one request cannot wait for many replies: both are refused. var inBody = exchange.In.Body; if (ListBody.Messages(inBody) is { } messages) { if (_options.ReplyTo) throw ListBody.RequestReplyRefusal(EndpointUri.Sanitize(_endpoint.Uri.BaseKey), messages.Count); foreach (var message in messages) { var element = ListBody.ElementExchange(exchange, message); try { await Process(element, ct).ConfigureAwait(false); } finally { if (element is IAsyncDisposable disposable) await disposable.DisposeAsync().ConfigureAwait(false); } } return; } if (ListBody.IsPlainList(inBody)) throw ListBody.PlainListRefusal(EndpointUri.Sanitize(_endpoint.Uri.BaseKey), inBody!); // The confirm timeout bounds the send from here until the broker has taken it: a broker that blocks its // publishers sends no confirm, and the send would otherwise wait for as long as the alarm lasts. var confirmTimeout = TimeSpan.FromMilliseconds(_options.ConfirmTimeout); using var deadline = new CancellationTokenSource(confirmTimeout); using var publish = CancellationTokenSource.CreateLinkedTokenSource(ct, deadline.Token); // The send span through the core's transport contract: it names its endpoint and honours EnableTelemetry. using var activity = RouteTelemetryExtensions.StartTransportSpan( (_endpoint.Component as ComponentBase)?.Context, $"{_options.Exchange} publish", ActivityKind.Producer, "messaging.system", "rabbitmq", _endpoint.Uri.NormalizedKey, destination: _options.ResolveOption(_options.Exchange, exchange) ?? _options.Exchange, operation: "publish"); if (activity is { IsAllDataRequested: true }) activity.SetTag("messaging.rabbitmq.destination.routing_key", _options.ResolveOption(_options.RoutingKey, exchange) ?? _options.RoutingKey); var (properties, body) = PrepareMessage(exchange); // The context of this send, over a traceparent copied from the incoming message: that one names the previous hop. RouteTelemetryExtensions.InjectTraceContext(activity, properties, static (p, name, value) => (p.Headers ??= new Dictionary())[name] = value); try { await EnsureChannelAsync(publish.Token).ConfigureAwait(false); if (_options.ReplyTo) { await ProcessRpcAsync(exchange, properties, body, publish.Token, ct).ConfigureAwait(false); } else if (TransactedActions.Defers(exchange, _options.Transacted)) { ProcessTransactional(exchange, properties, body); } else { await ProcessImmediateAsync(exchange, properties, body, publish.Token).ConfigureAwait(false); } } catch (OperationCanceledException canceled) when (deadline.IsCancellationRequested && !ct.IsCancellationRequested) { var timedOut = new RabbitMQPublishTimeoutException( _options.ResolveOption(_options.Exchange, exchange) ?? _options.Exchange, _options.ResolveOption(_options.RoutingKey, exchange) ?? _options.RoutingKey, confirmTimeout, canceled); activity.RecordFailure(timedOut); Logger?.LogWarning("{Message}", timedOut.Message); throw timedOut; } catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested) { // A refused or unconfirmed publish, a returned message, a failed request-reply call. Only a cancellation // through the caller's own token is not a failure; any other one (a client-side timeout) is. activity.RecordFailure(ex); throw; } } // ── Immediate send ── private async Task ProcessImmediateAsync(IExchange exchange, BasicProperties properties, byte[] body, CancellationToken ct) { var resolvedExchange = _options.ResolveOption(_options.Exchange, exchange) ?? _options.Exchange; var resolvedRoutingKey = _options.ResolveOption(_options.RoutingKey, exchange) ?? _options.RoutingKey; try { await _publishLock.WaitAsync(ct).ConfigureAwait(false); try { await _channel!.BasicPublishAsync( exchange: resolvedExchange, routingKey: resolvedRoutingKey, mandatory: _options.ResolveMandatory(), basicProperties: properties, body: body, cancellationToken: ct).ConfigureAwait(false); } finally { _publishLock.Release(); } // Wire-level bytes are the connector's to record: the core's ToProcessor counts // MessagesOut/Errors for a routed producer but has no idea of payload sizes. _endpoint.RecordBytesOut(body.Length); Logger?.LogDebug("RabbitMQ immediate publish: exchange={Exchange}, routingKey={RoutingKey}, bodySize={Size}", resolvedExchange, resolvedRoutingKey, body.Length); } catch (global::RabbitMQ.Client.Exceptions.PublishReturnException returned) { throw RabbitMQUnroutableException.From(returned); } catch (Exception ex) when (ex is not OperationCanceledException) { LogPublishDiagnostics("Immediate", ex, _channel, resolvedExchange, resolvedRoutingKey, _options.ResolveMandatory(), body.Length, properties?.ContentType); throw; } } // ── Transactional deferred send ── private void ProcessTransactional(IExchange exchange, BasicProperties properties, byte[] body) { // Clone everything — the action might execute long after Process returns var capturedExchange = _options.ResolveOption(_options.Exchange, exchange) ?? _options.Exchange; var capturedRoutingKey = _options.ResolveOption(_options.RoutingKey, exchange) ?? _options.RoutingKey; var capturedMandatory = _options.ResolveMandatory(); var capturedBody = new byte[body.Length]; Buffer.BlockCopy(body, 0, capturedBody, 0, body.Length); var capturedProperties = CloneProperties(properties); var batch = TransactedActions.JoinBatch(exchange, _batchKey, () => new RabbitMQSendBatch(TransactedChannelAsync, _commitLock, TimeSpan.FromMilliseconds(_options.ConfirmTimeout), Logger), ProducerName); batch.Add(new RabbitMQDeferredPublish( capturedExchange, capturedRoutingKey, capturedMandatory, capturedProperties, capturedBody)); } /// /// The producer's channel in tx mode, opened for the first batch and again after a failed batch closed it. A batch /// calls it under the commit lock. /// private async Task TransactedChannelAsync(CancellationToken ct) { if (_txChannel is { IsOpen: true } open) return open; _txChannel?.Dispose(); var channel = await _endpoint.CreateChannelAsync(RabbitMQConnectionUse.Publish, publisherConfirms: false, ct: ct).ConfigureAwait(false); // RabbitMQ.Client waits for a method's reply (tx.commit-ok, channel.close-ok) until the channel's continuation // timeout and does not stop for a cancelled token, so the confirm timeout is set as that timeout: a blocked // broker's missing commit-ok then fails the commit in time, and the client itself drops the pending reply. channel.ContinuationTimeout = TimeSpan.FromMilliseconds(_options.ConfirmTimeout); await channel.TxSelectAsync(ct).ConfigureAwait(false); _txChannel = channel; return channel; } // ── RPC (request/reply) ── /// Bounds the request's publish: the confirm timeout and the caller's token. /// The caller's token; with Timeout it bounds the wait for the reply. private async Task ProcessRpcAsync( IExchange exchange, BasicProperties properties, byte[] body, CancellationToken publishCt, CancellationToken ct) { if (!_rpcSetup) await SetupResponseQueueAsync(publishCt).ConfigureAwait(false); // First attempt; if the publish fails because the underlying channel/reply-queue is gone // (cluster failover, broker-side queue eviction, channel exception), recreate the reply // queue once and retry. Without this retry, every RPC after a node loss would hang for // the full RPC timeout (default 60s) before the caller learns of the failure. try { await PublishRpcOnceAsync(exchange, properties, body, publishCt, ct).ConfigureAwait(false); return; } catch (global::RabbitMQ.Client.Exceptions.PublishReturnException returned) { // No queue takes the request, so no reply can come; a new reply queue would not change that. throw RabbitMQUnroutableException.From(returned); } catch (Exception ex) when (IsRecoverableRpcFailure(ex)) { Logger?.LogWarning(ex, "RabbitMQ RPC publish failed on first attempt \u2014 recreating reply queue and retrying"); await RecreateResponseQueueAsync(publishCt).ConfigureAwait(false); // Properties.ReplyTo was set to the OLD queue inside PublishRpcOnceAsync; clear so // the second attempt picks up the NEW _replyQueueName. properties.ReplyTo = null; try { await PublishRpcOnceAsync(exchange, properties, body, publishCt, ct).ConfigureAwait(false); } catch (global::RabbitMQ.Client.Exceptions.PublishReturnException returned) { throw RabbitMQUnroutableException.From(returned); } } } /// /// Heuristic: was the publish failure caused by the broker dropping our channel or our /// auto-deleted reply queue? If so, a single retry against a freshly recreated reply queue /// is the correct enterprise-grade response (failover-style). /// private static bool IsRecoverableRpcFailure(Exception ex) => ex is global::RabbitMQ.Client.Exceptions.AlreadyClosedException or global::RabbitMQ.Client.Exceptions.OperationInterruptedException or global::RabbitMQ.Client.Exceptions.BrokerUnreachableException or global::RabbitMQ.Client.Exceptions.ChannelAllocationException or global::RabbitMQ.Client.Exceptions.PublishException; private async Task PublishRpcOnceAsync( IExchange exchange, BasicProperties properties, byte[] body, CancellationToken publishCt, CancellationToken ct) { var correlationId = Guid.NewGuid().ToString(); properties.CorrelationId = correlationId; properties.ReplyTo = _replyQueueName; var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); _pendingResponses[correlationId] = new PendingReply(tcs, exchange); try { await _publishLock.WaitAsync(publishCt).ConfigureAwait(false); try { await _channel!.BasicPublishAsync( exchange: _options.ResolveOption(_options.Exchange, exchange) ?? _options.Exchange, routingKey: _options.ResolveOption(_options.RoutingKey, exchange) ?? _options.RoutingKey, mandatory: true, basicProperties: properties, body: body, cancellationToken: publishCt).ConfigureAwait(false); } finally { _publishLock.Release(); } Logger?.LogDebug("RabbitMQ RPC request sent: correlationId={CorrelationId}, replyTo={ReplyTo}", correlationId, _replyQueueName); // Wait for response with timeout using var timeoutCts = new CancellationTokenSource(TimeSpan.FromSeconds(_options.Timeout)); using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, timeoutCts.Token); var responseTask = tcs.Task; var completed = await Task.WhenAny(responseTask, Task.Delay(Timeout.Infinite, linked.Token)) .ConfigureAwait(false); if (completed != responseTask) { _pendingResponses.TryRemove(correlationId, out _); throw new TimeoutException( $"RabbitMQ RPC timeout ({_options.Timeout}s): exchange={_options.Exchange}, routingKey={_options.RoutingKey}"); } var response = await responseTask.ConfigureAwait(false); // Set Out message exchange.Out = response; exchange.Pattern = ExchangePattern.InOut; Logger?.LogDebug("RabbitMQ RPC response received: correlationId={CorrelationId}", correlationId); } catch (Exception ex) { _pendingResponses.TryRemove(correlationId, out _); if (ex is not OperationCanceledException and not TimeoutException) { var resolvedExchange = _options.ResolveOption(_options.Exchange, exchange) ?? _options.Exchange; var resolvedRoutingKey = _options.ResolveOption(_options.RoutingKey, exchange) ?? _options.RoutingKey; LogPublishDiagnostics("RPC", ex, _channel, resolvedExchange, resolvedRoutingKey, true, body.Length, properties?.ContentType, correlationId, _replyQueueName, _options.Timeout); } throw; } } // ── RPC response queue setup ── private async Task SetupResponseQueueAsync(CancellationToken ct) { if (_rpcSetup) return; await _rpcLock.WaitAsync(ct).ConfigureAwait(false); try { if (_rpcSetup) return; await DeclareReplyQueueAndConsumerAsync(ct).ConfigureAwait(false); _rpcSetup = true; Logger?.LogDebug("RabbitMQ RPC reply queue created: {Queue}", _replyQueueName); } finally { _rpcLock.Release(); } } /// /// Tears down the previous reply consumer (if any) and re-declares a fresh exclusive /// auto-delete reply queue + consumer on the producer's channel. Used by /// to recover after a cluster failover or broker-side /// queue eviction. Pending RPC TCSes for the old queue are failed so callers see the error /// immediately instead of waiting for the full RPC timeout. /// private async Task RecreateResponseQueueAsync(CancellationToken ct) { await _rpcLock.WaitAsync(ct).ConfigureAwait(false); try { // Cancel the old consumer; ignore errors — the channel is likely already dead. if (_responseConsumerTag is not null && _channel is { IsOpen: true }) { try { await _channel.BasicCancelAsync(_responseConsumerTag, cancellationToken: ct).ConfigureAwait(false); } catch (Exception ex) { Logger?.LogDebug(ex, "RabbitMQ: error cancelling old reply consumer during recreate"); } } // Fail every in-flight RPC tied to the old reply queue — caller learns now, not after timeout. var oldQueue = _replyQueueName; foreach (var pending in _pendingResponses) { pending.Value.Reply.TrySetException(new InvalidOperationException( $"RabbitMQ RPC reply queue '{oldQueue}' was lost (cluster failover); request must be retried")); } _pendingResponses.Clear(); _responseConsumer = null; _responseConsumerTag = null; _rpcSetup = false; _replyQueueName = null; // The publisher channel itself may be closed too — recreate it through the endpoint // (which goes through the connection pool, transparently reconnecting if needed). if (_channel is null || !_channel.IsOpen) { try { _channel?.Dispose(); } catch (Exception ex) { Logger?.LogDebug(ex, "RabbitMQ: error disposing dead producer channel during recreate"); } _channel = await _endpoint.CreateChannelAsync(RabbitMQConnectionUse.Publish, ct: ct).ConfigureAwait(false); Logger?.LogInformation("RabbitMQ producer channel recreated after RPC failure"); } await DeclareReplyQueueAndConsumerAsync(ct).ConfigureAwait(false); _rpcSetup = true; Logger?.LogInformation("RabbitMQ RPC reply queue recreated: {Queue} (was {OldQueue})", _replyQueueName, oldQueue); } finally { _rpcLock.Release(); } } /// /// Declares an exclusive auto-delete reply queue on the producer channel, sets QoS, and /// installs the response consumer. Caller must hold . /// private async Task DeclareReplyQueueAndConsumerAsync(CancellationToken ct) { var result = await _channel!.QueueDeclareAsync( queue: string.Empty, durable: false, exclusive: true, autoDelete: true, cancellationToken: ct).ConfigureAwait(false); _replyQueueName = result.QueueName; await _channel.BasicQosAsync(0, (ushort)(_options.ResolvedConcurrentConsumers * 3), false, ct) .ConfigureAwait(false); _responseConsumer = new AsyncEventingBasicConsumer(_channel); _responseConsumer.ReceivedAsync += OnRpcResponseReceivedAsync; _responseConsumerTag = await _channel.BasicConsumeAsync( queue: _replyQueueName, autoAck: false, consumer: _responseConsumer, cancellationToken: ct).ConfigureAwait(false); } private async Task OnRpcResponseReceivedAsync(object sender, BasicDeliverEventArgs ea) { try { var correlationId = ea.BasicProperties.CorrelationId; if (!string.IsNullOrEmpty(correlationId) && _pendingResponses.TryRemove(correlationId, out var pending)) { try { // The reply is mapped as a consumed message is: the body stays bytes (a binary reply is not // decoded as text), ContentType and the other basic properties come along, and the producer's // strategy decides which AMQP headers come in. var message = new Message(ea.Body.ToArray()); RabbitMQConsumer.Fill(message, ea, _headerFilter, pending.Request); pending.Reply.TrySetResult(message); } catch (Exception ex) { pending.Reply.TrySetException(ex); } } await _channel!.BasicAckAsync(ea.DeliveryTag, multiple: false).ConfigureAwait(false); } catch (Exception ex) { Logger?.LogError(ex, "Error processing RPC response"); try { await _channel!.BasicNackAsync(ea.DeliveryTag, multiple: false, requeue: false).ConfigureAwait(false); } catch (Exception nackEx) { Logger?.LogWarning(nackEx, "RabbitMQ: error nacking RPC response"); } } } // ── Message preparation ── private (BasicProperties Properties, byte[] Body) PrepareMessage(IExchange exchange) { var body = exchange.In.Body switch { byte[] bytes => bytes, string str => Encoding.UTF8.GetBytes(str), null => Array.Empty(), var other => Encoding.UTF8.GetBytes(other.ToString() ?? string.Empty) }; var properties = new BasicProperties { ContentType = exchange.In.ContentType ?? _options.ContentType, Persistent = true }; // Basic property names never become AMQP headers; the endpoint's strategy decides the rest. var headers = new Dictionary(); foreach (var (key, value) in exchange.In.Headers) { if (BasicPropertyNames.Contains(key)) continue; if (value is null) continue; if (_headerFilter.FilterOutgoing(key, value, exchange)) continue; headers[key] = value switch { string s => s, byte[] b => b, int or long or float or double or decimal or bool => value, _ => value.ToString() }; } if (headers.Count > 0) properties.Headers = headers!; // Forward AMQP basic properties from headers, mapped by name (the well-known bare names — // "ReplyTo", "Priority", "MessageId", "Expiration"/TTL, "Type", "AppId", "UserId", …). Simple // string/byte properties go through cached reflection; a `redbRmq.X` prefixed name is also // accepted for the consume→produce round-trip. Header wins over any default. The reply-to only with // preserveMessageQos, as Camel's JMS: a sender's reply-to forwarded here must not make another consumer answer into // it; a request-reply send sets its own reply queue after this. foreach (var prop in _forwardableProps) { if (prop.Name == nameof(BasicProperties.ReplyTo) && !_options.PreserveMessageQos) continue; if (!TryGetHeaderValue(exchange, RmqHeaders.Prefix + prop.Name, prop.Name, out var raw)) continue; try { prop.SetValue(properties, System.Convert.ChangeType(raw, prop.PropertyType, System.Globalization.CultureInfo.InvariantCulture)); } catch { /* malformed header value — ignore, keep default */ } } // Explicit cases reflection/Convert.ChangeType can't handle: // Timestamp is an AmqpTimestamp (not IConvertible), DeliveryMode/persistence is a flag. if (TryGetHeaderValue(exchange, RmqHeaders.Prefix + "Timestamp", "Timestamp", out var tsRaw) && long.TryParse(tsRaw, out var ts)) properties.Timestamp = new global::RabbitMQ.Client.AmqpTimestamp(ts); if (TryGetHeaderValue(exchange, RmqHeaders.Prefix + "Persistent", "Persistent", out var persRaw) && bool.TryParse(persRaw, out var pers)) properties.Persistent = pers; else if (TryGetHeaderValue(exchange, RmqHeaders.Prefix + "DeliveryMode", "DeliveryMode", out var dmRaw) && byte.TryParse(dmRaw, out var dm)) properties.Persistent = dm == 2; // AMQP: 2 = persistent, 1 = transient return (properties, body); } /// /// Settable string/byte mapped from same-named headers via cached /// reflection. Excludes Headers (bulk-copied) and things needing special handling /// (ContentType — from the message field above; Timestamp/DeliveryMode — explicit). /// private static readonly System.Reflection.PropertyInfo[] _forwardableProps = BuildForwardableProps(); private static System.Reflection.PropertyInfo[] BuildForwardableProps() { var list = new List(); foreach (var p in typeof(BasicProperties).GetProperties()) { if (!p.CanWrite) continue; if (p.Name is "Headers" or "ContentType" or "DeliveryMode") continue; if (p.PropertyType == typeof(string) || p.PropertyType == typeof(byte)) list.Add(p); } return list.ToArray(); } /// Reads a header by its prefixed (redbRmq.X) name first, then the bare name; true when found non-empty. private static bool TryGetHeaderValue(IExchange exchange, string prefixedKey, string bareKey, out string value) { if ((exchange.In.Headers.TryGetValue(prefixedKey, out var v) || exchange.In.Headers.TryGetValue(bareKey, out v)) && v is not null) { value = v.ToString() ?? string.Empty; return !string.IsNullOrEmpty(value); } value = string.Empty; return false; } // ── Helpers ── /// /// Reopens the producer's channel when the broker closed it. A channel-level error — a publish to an exchange that /// does not exist (404), a failed precondition — closes the channel but not the connection, so connection recovery /// never reopens it, and every later send would fail until the route was restarted. /// private async Task EnsureChannelAsync(CancellationToken ct) { if (_channel is { IsOpen: true }) return; if (_options.ReplyTo) { // The reply consumer lived on the closed channel: the channel and the reply queue are recreated together. await RecreateResponseQueueAsync(ct).ConfigureAwait(false); return; } await _publishLock.WaitAsync(ct).ConfigureAwait(false); try { if (_channel is { IsOpen: true }) return; var closed = _channel; _channel = await _endpoint.CreateChannelAsync(RabbitMQConnectionUse.Publish, ct: ct).ConfigureAwait(false); await _endpoint.ReleaseChannelAsync(closed, ct).ConfigureAwait(false); await _endpoint.DeclareTopologyAsync(_channel, RabbitMQConnectionUse.Publish, ct).ConfigureAwait(false); Logger?.LogWarning("RabbitMQ producer '{Producer}': the broker had closed its channel ({Reason}); a new one is open", ProducerName, closed?.CloseReason?.ReplyText ?? "unknown reason"); } finally { _publishLock.Release(); } } private static BasicProperties CloneProperties(BasicProperties source) { var clone = new BasicProperties { ContentType = source.ContentType, ContentEncoding = source.ContentEncoding, DeliveryMode = source.DeliveryMode, Priority = source.Priority, CorrelationId = source.CorrelationId, ReplyTo = source.ReplyTo, Expiration = source.Expiration, MessageId = source.MessageId, Timestamp = source.Timestamp, Type = source.Type, UserId = source.UserId, AppId = source.AppId, ClusterId = source.ClusterId, Persistent = source.Persistent }; if (source.Headers is not null) clone.Headers = new Dictionary(source.Headers); return clone; } // ── Publish diagnostics ── private void LogPublishDiagnostics( string mode, Exception ex, IChannel? channel, string? exchangeName, string? routingKey, bool mandatory, int bodySize, string? contentType, string? correlationId = null, string? replyTo = null, int? timeoutSec = null) { if (Logger is null) return; var sb = new StringBuilder(); sb.AppendLine("═══════════════════════════════════════════════════════════"); sb.AppendLine($"RabbitMQ PUBLISH DIAGNOSTICS ({mode})"); sb.AppendLine("═══════════════════════════════════════════════════════════"); sb.AppendLine($"Exception: {ex.GetType().FullName}: {ex.Message}"); if (ex.InnerException != null) sb.AppendLine($"Inner: {ex.InnerException.GetType().FullName}: {ex.InnerException.Message}"); sb.AppendLine("───────────────────────────────────────────────────────────"); sb.AppendLine("CHANNEL STATE:"); try { sb.AppendLine($" IsOpen: {channel?.IsOpen ?? false}"); sb.AppendLine($" CloseReason: {channel?.CloseReason?.ReplyText ?? "N/A"}"); } catch (Exception chEx) { sb.AppendLine($" ERROR reading channel state: {chEx.Message}"); } sb.AppendLine("───────────────────────────────────────────────────────────"); sb.AppendLine("PUBLISH DETAILS:"); sb.AppendLine($" Exchange: {exchangeName ?? "(default)"}"); sb.AppendLine($" RoutingKey: {routingKey}"); sb.AppendLine($" Mandatory: {mandatory}"); sb.AppendLine($" BodySize: {bodySize} bytes"); sb.AppendLine($" ContentType: {contentType ?? "N/A"}"); sb.AppendLine($" Endpoint: {_endpoint.Uri}"); if (correlationId != null) { sb.AppendLine("───────────────────────────────────────────────────────────"); sb.AppendLine("RPC:"); sb.AppendLine($" CorrelationId: {correlationId}"); sb.AppendLine($" ReplyTo: {replyTo}"); sb.AppendLine($" Timeout: {timeoutSec}s"); } sb.AppendLine("───────────────────────────────────────────────────────────"); sb.AppendLine("POSSIBLE CAUSES:"); sb.AppendLine(" 1. Connection closed (NAT timeout / heartbeat missed)"); sb.AppendLine(" 2. Publisher Confirms timeout"); sb.AppendLine(" 3. Network timeout / connection lost"); sb.AppendLine(" 4. RabbitMQ server overloaded / flow control"); if (correlationId != null) sb.AppendLine(" 5. Reply queue deleted (temporary queue autoDelete=true)"); sb.AppendLine("═══════════════════════════════════════════════════════════"); Logger.LogError(ex, "{Diagnostics}", sb.ToString()); } } /// One deferred publish, captured (cloned) when the step ran. internal sealed record RabbitMQDeferredPublish( string Exchange, string RoutingKey, bool Mandatory, BasicProperties Properties, byte[] Body); /// /// The deferred publishes of one producer in one transacted block. On commit they are published on the producer's /// transacted channel and committed with one tx.commit, so the block's messages arrive together or not at all. /// On rollback nothing has been published. /// internal sealed class RabbitMQSendBatch : ITransactedAction { private readonly ConcurrentQueue _publishes = new(); private readonly Func> _transactedChannel; private readonly SemaphoreSlim _commitLock; private readonly TimeSpan _confirmTimeout; private readonly ILogger? _logger; /// The producer's channel in tx mode, opened again when the last one was closed. /// /// The producer's lock: a channel transaction belongs to the channel, so one batch at a time publishes and commits on /// it. Another batch's tx.commit would otherwise commit half of this one. /// /// /// The endpoint's confirm timeout: it bounds the whole commit, from the wait for the channel to commit-ok. /// /// The producer's logger. public RabbitMQSendBatch( Func> transactedChannel, SemaphoreSlim commitLock, TimeSpan confirmTimeout, ILogger? logger) { _transactedChannel = transactedChannel; _commitLock = commitLock; _confirmTimeout = confirmTimeout; _logger = logger; } /// Adds a publish to the batch, after the ones the block deferred before it. public void Add(RabbitMQDeferredPublish publish) => _publishes.Enqueue(publish); public async Task Commit(CancellationToken ct = default) { // A broker that blocks its publishers answers no tx.commit, so the commit is bounded as a confirm is. using var deadline = new CancellationTokenSource(_confirmTimeout); using var commit = CancellationTokenSource.CreateLinkedTokenSource(ct, deadline.Token); try { await CommitWithinAsync(commit.Token).ConfigureAwait(false); } catch (Exception failure) when (failure is OperationCanceledException or TimeoutException && failure is not RabbitMQPublishTimeoutException && !ct.IsCancellationRequested) { // Either this deadline fired, or the client's own continuation timeout (set to the same value on the // transacted channel) gave up on the commit-ok. var first = _publishes.FirstOrDefault(); var timedOut = new RabbitMQPublishTimeoutException( first?.Exchange ?? string.Empty, first?.RoutingKey ?? string.Empty, _confirmTimeout, failure); _logger?.LogWarning("{Message} Transactional batch of {Count} message(s); its channel is closed.", timedOut.Message, _publishes.Count); throw timedOut; } } private async Task CommitWithinAsync(CancellationToken ct) { await _commitLock.WaitAsync(ct).ConfigureAwait(false); try { var channel = await _transactedChannel(ct).ConfigureAwait(false); // A mandatory publish that no queue takes comes back as basic.return, which the broker sends while it // routes the batch at tx.commit, before commit-ok. The batches take turns on this channel, so every return // seen until the commit completes belongs to this batch. var returned = new ConcurrentQueue(); AsyncEventHandler onReturn = (_, args) => { returned.Enqueue(args); return Task.CompletedTask; }; channel.BasicReturnAsync += onReturn; try { foreach (var p in _publishes) { await channel.BasicPublishAsync( exchange: p.Exchange, routingKey: p.RoutingKey, mandatory: p.Mandatory, basicProperties: p.Properties, body: p.Body, cancellationToken: ct).ConfigureAwait(false); } await channel.TxCommitAsync(ct).ConfigureAwait(false); } catch (Exception ex) { // Closing the channel discards its open transaction, so none of the batch is delivered, and the next // batch starts on a fresh channel instead of committing what this one left behind. The handler leaves // the channel first: a closed channel is disposed, and leaving it then would throw over this failure. channel.BasicReturnAsync -= onReturn; await CloseAsync(channel).ConfigureAwait(false); _logger?.LogError(ex, "RabbitMQ transactional batch failed; none of its {Count} messages was published. First target: " + "exchange={Exchange}, routingKey={RoutingKey}", _publishes.Count, _publishes.FirstOrDefault()?.Exchange, _publishes.FirstOrDefault()?.RoutingKey); throw; } channel.BasicReturnAsync -= onReturn; // The transaction is committed: the routed messages are delivered and cannot be taken back. A returned one // is lost unless the route learns of it, so the send fails as an immediate publish of it fails. if (returned.TryPeek(out var first)) { var message = $"RabbitMQ: {returned.Count} of the {_publishes.Count} messages of a transactional batch came back " + $"unroutable (no queue takes them) and were not delivered; the other {_publishes.Count - returned.Count} " + $"were committed. First returned: {first.ReplyCode} {first.ReplyText}, exchange='{first.Exchange}', " + $"routingKey='{first.RoutingKey}'."; _logger?.LogError("{Message}", message); throw new RabbitMQUnroutableException(message, first.Exchange, first.RoutingKey, first.ReplyCode, first.ReplyText); } _logger?.LogDebug("RabbitMQ transactional batch committed: messages={Count}", _publishes.Count); } finally { _commitLock.Release(); } } public Task Rollback(CancellationToken ct = default) { _logger?.LogDebug("RabbitMQ transactional batch rolled back (messages discarded): messages={Count}", _publishes.Count); return Task.CompletedTask; } private async Task CloseAsync(IChannel channel) { // The wait for close-ok is bounded by the channel's continuation timeout, the confirm timeout. try { await channel.CloseAsync(CancellationToken.None).ConfigureAwait(false); } catch (Exception closeEx) { _logger?.LogWarning(closeEx, "RabbitMQ: closing the transacted channel after a failed batch failed; it is dropped and replaced."); } finally { channel.Dispose(); } } } Path: redb-route/redb.Route.RabbitMQ/RabbitMQPublishTimeoutException.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/RabbitMQPublishTimeoutException.cs ---- namespace redb.Route.RabbitMQ; /// /// A send the broker did not take within the endpoint's confirmTimeout: no publisher confirm (or, for a /// transacted block, no commit-ok) came in time, typically because the broker blocks its publishers under a memory /// or disk alarm. Every publish path throws it, so one OnException<RabbitMQPublishTimeoutException> covers /// them all; it is a , so a handler for that type takes it too. /// The message may still reach the queue later, when the broker resumes. /// public sealed class RabbitMQPublishTimeoutException : TimeoutException { /// Creates the exception for a send that timed out. public RabbitMQPublishTimeoutException(string exchange, string routingKey, TimeSpan timeout, Exception? innerException = null) : base( $"RabbitMQ: the broker did not confirm the send within {timeout.TotalMilliseconds:0} ms " + $"(exchange='{exchange}', routingKey='{routingKey}'); a blocked broker (memory or disk alarm) is the usual cause.", innerException) { Exchange = exchange; RoutingKey = routingKey; Timeout = timeout; } /// The exchange the message was published to; empty for the default exchange. public string Exchange { get; } /// The routing key of the send. public string RoutingKey { get; } /// The endpoint's confirm timeout that expired. public TimeSpan Timeout { get; } } Path: redb-route/redb.Route.RabbitMQ/RabbitMQTls.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/RabbitMQTls.cs ---- using System.Net.Security; using System.Security.Authentication; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Microsoft.Extensions.Logging; using RabbitMQ.Client; namespace redb.Route.RabbitMQ; /// How the connection authenticates to the broker. public enum RabbitMQAuthMechanism { /// Username and password (SASL PLAIN), the default. Plain, /// /// The TLS client certificate (SASL EXTERNAL): the broker takes the user from the certificate, and no password is /// sent. Needs TLS and a client certificate, and the broker's rabbitmq_auth_mechanism_ssl plugin. /// External, } /// The TLS settings of one connection, resolved from the endpoint URI or from a named factory. /// TLS on. /// The name the broker certificate must carry; null checks each host against its own name. /// The certificate presented for mutual TLS, loaded and checked for validity. /// Allowed TLS versions; lets the operating system choose. /// Trust only these roots for the broker certificate instead of the system store. /// Revocation check of the broker certificate chain. /// Accept a broker certificate whose revocation status cannot be determined. internal sealed record RabbitMQTlsSettings( bool Enabled, string? ServerName, X509Certificate2? ClientCertificate, SslProtocols Protocols, X509Certificate2Collection? CaCertificates, X509RevocationMode RevocationMode, bool RevocationSoftFail) { /// No TLS. public static readonly RabbitMQTlsSettings Off = new(false, null, null, SslProtocols.None, null, X509RevocationMode.NoCheck, false); } /// Loading and checking the TLS material of a RabbitMQ connection, and the SSL options built from it. internal static class RabbitMQTls { /// The TLS versions a connection may be limited to; older ones are broken and refused. public const SslProtocols AllowedProtocols = SslProtocols.Tls12 | SslProtocols.Tls13; /// /// The TLS and authentication rules, the same for the endpoint URI and a named factory: a TLS setting without TLS /// would be ignored in silence, so it is refused, as are settings that contradict each other. /// public static void Validate(TlsRules r, string owner) { if (!r.Ssl) { var needTls = new List(); if (!string.IsNullOrEmpty(r.ServerName)) needTls.Add("sslServerName"); if (!string.IsNullOrEmpty(r.CertPath)) needTls.Add("sslCertPath"); if (!string.IsNullOrEmpty(r.CertPassphrase)) needTls.Add("sslCertPassword"); if (r.ClientCertificateObject) needTls.Add("ClientCertificate"); if (!string.IsNullOrEmpty(r.CaCertPath)) needTls.Add("sslCaCertPath"); if (r.CaCertificatesObject) needTls.Add("SslCaCertificates"); if (r.Protocols != SslProtocols.None) needTls.Add("sslProtocols"); if (r.Revocation != X509RevocationMode.NoCheck) needTls.Add("revocationMode"); if (r.SoftFail) needTls.Add("revocationSoftFail"); if (needTls.Count > 0) throw new ArgumentException( $"{owner}: {string.Join(", ", needTls)} only take effect over TLS, and ssl is off. Set ssl=true, or remove them."); } #pragma warning disable SYSLIB0039 // named to refuse them if ((r.Protocols & ~AllowedProtocols) != SslProtocols.None) throw new ArgumentException( $"{owner}: sslProtocols '{r.Protocols}' is not allowed: only Tls12 and Tls13 (SSL 3.0, TLS 1.0 and TLS 1.1 are broken)."); #pragma warning restore SYSLIB0039 if (!string.IsNullOrEmpty(r.CertPassphrase) && string.IsNullOrEmpty(r.CertPath)) throw new ArgumentException($"{owner}: sslCertPassword is given without sslCertPath."); if (r.ClientCertificateObject && !string.IsNullOrEmpty(r.CertPath)) throw new ArgumentException($"{owner}: give the client certificate once, as ClientCertificate or as SslCertPath, not both."); if (r.CaCertificatesObject && !string.IsNullOrEmpty(r.CaCertPath)) throw new ArgumentException($"{owner}: give the CA certificates once, as SslCaCertificates or as SslCaCertPath, not both."); if (r.SoftFail && r.Revocation == X509RevocationMode.NoCheck) throw new ArgumentException($"{owner}: revocationSoftFail is set but revocationMode is NoCheck, so nothing is checked."); if (r.Auth == RabbitMQAuthMechanism.External && (!r.Ssl || (string.IsNullOrEmpty(r.CertPath) && !r.ClientCertificateObject))) throw new ArgumentException( $"{owner}: authMechanism=External logs in with the TLS client certificate, so it needs ssl=true and a client certificate."); } /// The settings checks, from either source. internal sealed record TlsRules( bool Ssl, string? ServerName, string? CertPath, string? CertPassphrase, bool ClientCertificateObject, string? CaCertPath, bool CaCertificatesObject, SslProtocols Protocols, X509RevocationMode Revocation, bool SoftFail, RabbitMQAuthMechanism Auth); /// Loads the client certificate (PFX) and refuses one outside its validity period. public static X509Certificate2 LoadClientCertificate(string path, string? passphrase, string owner) { X509Certificate2 certificate; try { certificate = X509CertificateLoader.LoadPkcs12FromFile(path, passphrase); } catch (Exception ex) when (ex is CryptographicException or IOException or UnauthorizedAccessException) { throw new InvalidOperationException($"{owner}: the client certificate '{path}' could not be loaded: {ex.Message}", ex); } EnsureClientCertificateUsable(certificate, owner); return certificate; } /// /// Refuses a client certificate without a private key or outside its validity period: the broker would refuse the /// handshake with a bare "certificate unknown", so the connector says which certificate and why first. /// public static void EnsureClientCertificateUsable(X509Certificate2 certificate, string owner) { var who = $"{owner}: the client certificate {certificate.Subject} ({certificate.Thumbprint})"; if (!certificate.HasPrivateKey) throw new CryptographicException($"{who} has no private key, so it cannot be presented."); var now = DateTime.UtcNow; if (now < certificate.NotBefore.ToUniversalTime()) throw new CryptographicException($"{who} is not yet valid: valid from {certificate.NotBefore.ToUniversalTime():O}."); if (now > certificate.NotAfter.ToUniversalTime()) throw new CryptographicException($"{who} has expired: valid until {certificate.NotAfter.ToUniversalTime():O}."); } /// Loads the trusted root certificates from a PEM file (one or more certificates). public static X509Certificate2Collection LoadCaCertificates(string path, string owner) { var collection = new X509Certificate2Collection(); try { collection.ImportFromPemFile(path); } catch (Exception ex) when (ex is CryptographicException or IOException or UnauthorizedAccessException) { throw new InvalidOperationException($"{owner}: the CA certificates '{path}' could not be loaded: {ex.Message}", ex); } if (collection.Count == 0) throw new InvalidOperationException($"{owner}: '{path}' holds no PEM certificate to trust."); return collection; } /// The SSL options of one host of the connection. public static SslOption OptionFor(string host, RabbitMQTlsSettings tls, ILogger? logger) { if (!tls.Enabled) return new SslOption(); var option = new SslOption { Enabled = true, ServerName = string.IsNullOrEmpty(tls.ServerName) ? host : tls.ServerName, Version = tls.Protocols, }; if (tls.ClientCertificate is { } client) option.Certs = new X509CertificateCollection { client }; if (tls.CaCertificates is { Count: > 0 } || tls.RevocationMode != X509RevocationMode.NoCheck) option.CertificateValidationCallback = BrokerCertificateValidator(tls, logger); return option; } /// /// Checks the broker certificate against the configured roots and revocation policy. The host name is checked as /// always; the chain is built again under the connection's trust rather than the system's. /// private static RemoteCertificateValidationCallback BrokerCertificateValidator(RabbitMQTlsSettings tls, ILogger? logger) => (_, certificate, presented, errors) => { if (certificate is null || (errors & SslPolicyErrors.RemoteCertificateNotAvailable) != 0) { logger?.LogError("RabbitMQ TLS: the broker presented no certificate."); return false; } if ((errors & SslPolicyErrors.RemoteCertificateNameMismatch) != 0) { logger?.LogError("RabbitMQ TLS: the broker certificate {Subject} does not name the server the connection expects.", certificate.Subject); return false; } using var broker = X509CertificateLoader.LoadCertificate(certificate.GetRawCertData()); using var chain = new X509Chain(); chain.ChainPolicy.RevocationMode = tls.RevocationMode; chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot; if (tls.CaCertificates is { Count: > 0 } roots) { chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; chain.ChainPolicy.CustomTrustStore.AddRange(roots); } if (presented is not null) foreach (var element in presented.ChainElements.Skip(1)) chain.ChainPolicy.ExtraStore.Add(element.Certificate); if (chain.Build(broker)) return true; var status = chain.ChainStatus.Aggregate(X509ChainStatusFlags.NoError, (all, s) => all | s.Status); const X509ChainStatusFlags undetermined = X509ChainStatusFlags.RevocationStatusUnknown | X509ChainStatusFlags.OfflineRevocation; if ((status & ~undetermined) == X509ChainStatusFlags.NoError) { // Only the revocation status is missing. A certificate that names no CRL distribution point and no // authority information access cannot be checked at all and passes, as in the AS4 connector (Domibus); // one that names a source it could not reach passes only with soft-fail. var unreachable = chain.ChainElements .Where(e => e.ChainElementStatus.Any(s => (s.Status & undetermined) != 0)) .Where(e => NamesRevocationSources(e.Certificate)) .ToList(); if (unreachable.Count == 0) return true; if (tls.RevocationSoftFail) { logger?.LogWarning("RabbitMQ TLS: the revocation status of the broker certificate {Subject} could not be " + "determined; accepted because revocationSoftFail is set.", broker.Subject); return true; } } logger?.LogError("RabbitMQ TLS: the broker certificate {Subject} ({Thumbprint}) was rejected: {Status}.", broker.Subject, broker.Thumbprint, status); return false; }; private const string CrlDistributionPointsOid = "2.5.29.31"; private const string AuthorityInformationAccessOid = "1.3.6.1.5.5.7.1.1"; private static bool NamesRevocationSources(X509Certificate2 certificate) => certificate.Extensions.Any(e => e.Oid?.Value is CrlDistributionPointsOid or AuthorityInformationAccessOid); } Path: redb-route/redb.Route.RabbitMQ/RabbitMQUnroutableException.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/RabbitMQUnroutableException.cs ---- using RabbitMQ.Client.Exceptions; namespace redb.Route.RabbitMQ; /// /// A mandatory publish came back from the broker (basic.return): no queue takes it for its exchange and routing /// key, so it was not delivered. Every publish path throws it — an immediate send, a request-reply call and the sends /// of a transacted block — so one OnException<RabbitMQUnroutableException> covers all of them. /// public sealed class RabbitMQUnroutableException : Exception { /// Creates the exception for a returned publish. public RabbitMQUnroutableException( string message, string exchange, string routingKey, ushort replyCode, string replyText, Exception? innerException = null) : base(message, innerException) { Exchange = exchange; RoutingKey = routingKey; ReplyCode = replyCode; ReplyText = replyText; } /// The exchange the message was published to; empty for the default exchange. public string Exchange { get; } /// The routing key no queue is bound for. public string RoutingKey { get; } /// The broker's reply code, 312 (NO_ROUTE) for an unroutable message. public ushort ReplyCode { get; } /// The broker's reply text, such as NO_ROUTE. public string ReplyText { get; } /// Wraps the client's exception for a publish the broker returned. internal static RabbitMQUnroutableException From(PublishReturnException returned) => new( $"RabbitMQ: the message came back unroutable and was not delivered: no queue takes it for " + $"exchange='{returned.Exchange}', routingKey='{returned.RoutingKey}' ({returned.ReplyCode} {returned.ReplyText}).", returned.Exchange, returned.RoutingKey, returned.ReplyCode, returned.ReplyText, returned); } Path: redb-route/redb.Route.RabbitMQ/RmqHeaders.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/RmqHeaders.cs ---- namespace redb.Route.RabbitMQ; /// /// Well-known header constants used by the RabbitMQ component. /// public static class RmqHeaders { /// Common prefix for redb-specific RabbitMQ envelope headers (delivery metadata). public const string Prefix = "redbRmq."; // ── Envelope / delivery metadata (no standard AMQP name → redb-prefixed) ───── /// Exchange the message was published to. public const string Exchange = "redbRmq.Exchange"; /// Routing key of the message. public const string RoutingKey = "redbRmq.RoutingKey"; /// Delivery tag for acknowledgement. public const string DeliveryTag = "redbRmq.DeliveryTag"; /// Whether this message was redelivered. public const string Redelivered = "redbRmq.Redelivered"; /// Consumer tag that received the message. public const string ConsumerTag = "redbRmq.ConsumerTag"; // ── Standard AMQP basic properties (well-known names → BARE, self-documenting) ── // These map 1:1 to RabbitMQ BasicProperties. Bare names mean no docs needed and a // consume→produce round-trip carries them through. Caveat: common-word names // (Type/Priority/Timestamp/MessageId) can collide with a business header of the // same name — set a prefixed header instead if that matters. /// AMQP content type (BasicProperties.ContentType). public const string ContentType = "ContentType"; /// Correlation ID (BasicProperties.CorrelationId). public const string CorrelationId = "CorrelationId"; /// Reply-to address (BasicProperties.ReplyTo). public const string ReplyTo = "ReplyTo"; /// Message ID (BasicProperties.MessageId). public const string MessageId = "MessageId"; /// Message priority 0-9 (BasicProperties.Priority). public const string Priority = "Priority"; /// Per-message expiration / TTL in milliseconds, as a string (BasicProperties.Expiration). public const string Expiration = "Expiration"; /// Application message type name (BasicProperties.Type). public const string Type = "Type"; /// Creating application id (BasicProperties.AppId). public const string AppId = "AppId"; /// Creating user id (BasicProperties.UserId). public const string UserId = "UserId"; /// Content encoding (BasicProperties.ContentEncoding). public const string ContentEncoding = "ContentEncoding"; /// Message timestamp, Unix seconds (BasicProperties.Timestamp). public const string Timestamp = "Timestamp"; /// Returns true if the header key belongs to the RabbitMQ component. public static bool IsRedbHeader(string key) => key.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase); } Path: redb-route/redb.Route.RabbitMQ/redb.Route.RabbitMQ.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.RabbitMQ/redb.Route.RabbitMQ.csproj ---- redb.Route.RabbitMQ RabbitMQ transport for redb.Route ESB framework. esb;messaging;rabbitmq;redb README.md