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