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