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