Path: redb-route/redb.Route.Amqp/AmqpConsumer.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.Amqp/AmqpConsumer.cs
----
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Text;
using Amqp;
using Amqp.Framing;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Telemetry;
using AmqpMessage = global::Amqp.Message;
using RouteMessage = redb.Route.Core.Message;
namespace redb.Route.Amqp;
///
/// AMQP 1.0 consumer. Receives messages via with support for:
/// concurrent processing, automatic/manual accept, RPC reply, and batch mode (batching=true, see the
/// AmqpConsumer.Batch.cs part).
///
public sealed partial class AmqpConsumer : IConsumer
{
private readonly AmqpEndpoint _endpoint;
public IEndpoint Endpoint => _endpoint;
private readonly IProcessor _processor;
private readonly AmqpEndpointOptions _options;
private ILogger? _logger;
// ConcurrentConsumers is honoured as N REAL competing consumers: each Worker owns its own AMQP
// session + receiver link and drives a single serial receive loop. AMQPNetLite sessions/links are
// not thread-safe, so concurrency comes from N independent workers, never from sharing one link.
private readonly List _workers = new();
// The node the consumer reads: the URI address, or the name the broker gave a dynamic node.
private string _address;
///
/// The node this consumer reads: the address of the URI, or, with dynamic=true, the name the broker gave
/// the node it created (known once has returned). Senders reach the consumer at this address.
///
public string Address => _address;
private CancellationTokenSource? _cts;
private readonly InflightDrainGuard _drain = new();
private long _processedCount;
/// Number of messages successfully processed (summed across all worker loops).
public long ProcessedCount => Interlocked.Read(ref _processedCount);
///
/// One competing consumer: its own AMQP session, receiver link and receive-loop task, and the supervisor of its link.
/// A link the broker closes (a detach, or the connection under it lost) is attached again on a new session by the
/// worker's loop, so the session and the link change over the worker's life.
///
private sealed class Worker
{
public Worker(int index, ConnectionSupervisor supervisor) { Index = index; Supervisor = supervisor; }
public int Index { get; }
public ConnectionSupervisor Supervisor { get; }
public Session? Session { get; set; }
public ReceiverLink? Receiver { get; set; }
public Task? Loop { get; set; }
}
/// Creates an AMQP consumer.
public AmqpConsumer(AmqpEndpoint endpoint, IProcessor processor, AmqpEndpointOptions options)
{
_endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
_processor = processor ?? throw new ArgumentNullException(nameof(processor));
_options = options ?? throw new ArgumentNullException(nameof(options));
_logger = endpoint.Logger;
_address = endpoint.Address;
_headerFilter = endpoint.HeaderFilterStrategy;
}
private readonly IHeaderFilterStrategy _headerFilter;
///
public async Task Start(CancellationToken ct = default)
{
var workerCount = Math.Max(1, _options.ResolvedConcurrentConsumers);
_logger ??= (_endpoint.Component as ComponentBase)?.Logger;
// Each worker is a receiver link of its own. On a MULTICAST (topic) address every link is a subscription
// that gets a COPY of each message, and every dynamic link gets a node of its own: N workers would not
// share the work, they would process each message N times or read N different nodes. One link, as IBM MQ
// does for a topic.
var multicast = _options.ResolveCapabilities().Contains("topic", StringComparer.OrdinalIgnoreCase);
if (workerCount > 1 && (multicast || _options.Dynamic))
{
_logger?.LogWarning(
"AMQP: ConcurrentConsumers({N}) ignored for {Kind} {Address}: each receiver link would get a copy of "
+ "every message instead of a share of them, so the consumer runs one link",
workerCount, multicast ? "MULTICAST address" : "a dynamic node", _address);
workerCount = 1;
}
_cts = new CancellationTokenSource();
_drain.Start(ct);
try
{
for (var i = 0; i < workerCount; i++)
{
var worker = new Worker(i, _endpoint.Supervise($"amqp:{_endpoint.Address} consumer worker {i}", _logger));
_workers.Add(worker);
await AttachAsync(worker, ct).ConfigureAwait(false);
worker.Loop = _options.Batch is { } batch
? Task.Run(() => BatchLoopAsync(worker, batch, _cts.Token), _cts.Token)
: Task.Run(() => ReceiveLoopAsync(worker, _cts.Token), _cts.Token);
}
}
catch
{
// Partial start — tear down whatever came up so we don't leak sessions/links.
await StopWorkersAsync(ct).ConfigureAwait(false);
_drain.Dispose();
_cts?.Dispose();
_cts = null;
throw;
}
_logger?.LogInformation(
"AMQP consumer started: address={Address}, credit={Credit}, concurrent={Concurrent}, batch={Batch}",
_address, _options.Credit, workerCount, _options.Batch?.MaxMessages);
}
/// The consumer as errors name it: its scheme and the address of its URI.
private string ConsumerName => $"AMQP consumer amqp:{_endpoint.Address}";
///
/// The broker's attach answer. An accepted receiver link comes back with a source (for a dynamic node, the address
/// the broker gave it); a refused one comes back without a source and is detached right after with the reason.
/// Frames of a connection are handled one after another, so the detach cannot pass the handler subscribed here.
///
private void OnLinkAttached(ILink link, Attach remote, TaskCompletionSource attached, string failing)
{
if (remote.Source is Source source)
{
attached.TrySetResult(source.Address);
return;
}
link.Closed += (_, error) => attached.TrySetException(Refused(error, failing));
if (link.IsClosed)
attached.TrySetException(Refused(link.Error, failing));
}
private InvalidOperationException Refused(Error? error, string failing) => new(
$"{ConsumerName} {failing}: the broker refused the receiver link"
+ (error is null ? "." : $" ({error.Condition}: {error.Description})."));
private const string StartFailing = "cannot start";
private const string ReattachFailing = "cannot attach its receiver link again";
///
/// Opens the worker's session and receiver link at start. The link waits for the broker's attach answer before
/// Start returns: without the wait a refused link (an unknown address, no permission) was only logged by the receive
/// loop and the consumer stayed "started" without receiving, and on a topic the subscription did not exist yet when
/// Start returned.
///
private async Task AttachAsync(Worker worker, CancellationToken ct)
{
var (session, receiver, address) = await OpenLinkAsync(worker.Index, StartFailing, ct).ConfigureAwait(false);
worker.Session = session;
worker.Receiver = receiver;
if (_options.Dynamic)
_address = address!;
}
///
/// A session and a receiver link the broker accepted, with the address its answer names. Nothing is left open when it
/// fails: no answer within timeout, a refusal, or a dynamic node the broker did not create.
///
private async Task<(Session Session, ReceiverLink Receiver, string? Address)> OpenLinkAsync(int index, string failing,
CancellationToken ct)
{
var attached = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var (session, receiver) = await _endpoint
.CreateDedicatedReceiverAsync($"receiver-{_endpoint.Address}-{index}-{Guid.NewGuid():N}",
(link, remote) => OnLinkAttached(link, remote, attached, failing), ct)
.ConfigureAwait(false);
try
{
string? address;
try
{
address = await attached.Task.WaitAsync(TimeSpan.FromSeconds(_options.Timeout), ct).ConfigureAwait(false);
}
catch (TimeoutException ex)
{
throw new InvalidOperationException(
$"{ConsumerName} {failing}: the broker did not answer the receiver link within {_options.Timeout} s.", ex);
}
// The broker names the dynamic node in its attach answer; the route reads that node.
if (_options.Dynamic && string.IsNullOrEmpty(address))
throw new InvalidOperationException(
$"{ConsumerName} {failing}: the broker created no dynamic node for the receiver link.");
return (session, receiver, address);
}
catch
{
await CloseLinkQuietlyAsync(session, receiver).ConfigureAwait(false);
throw;
}
}
///
/// Attaches a worker's link again after the broker closed it: reports the loss to the worker's supervisor, closes what
/// is left of the old session, and opens a new session and link on the supervisor's schedule, one bounded attempt at
/// a time (the component replaces a closed connection on the way), until it succeeds or the consumer stops. While it
/// is away the endpoint's health says so. Returns false when the consumer stopped first. A dynamic node is a new
/// node with a new name after the reattach: senders find the consumer at again.
///
private async Task ReattachAsync(Worker worker, CancellationToken ct)
{
// A failed receive can resume on the connection's frame pump; the reattach waits for frames, so it leaves it.
await Task.Yield();
var supervisor = worker.Supervisor;
supervisor.Lost(LinkLost(worker.Receiver));
await CloseLinkQuietlyAsync(worker.Session, worker.Receiver).ConfigureAwait(false);
worker.Receiver = null;
worker.Session = null;
return await supervisor.ReconnectAsync(async c =>
{
var (session, receiver, address) = await supervisor.AttemptAsync(
a => OpenLinkAsync(worker.Index, ReattachFailing, a),
late => _ = CloseLinkQuietlyAsync(late.Session, late.Receiver), c).ConfigureAwait(false);
worker.Session = session;
worker.Receiver = receiver;
if (_options.Dynamic && address != _address)
{
_logger?.LogWarning("AMQP consumer reads the new dynamic node {Address} after its link was attached again "
+ "(it read {Old})", address, _address);
_address = address!;
}
}, ct).ConfigureAwait(false);
}
/// Why the worker's link is gone: the broker's error on it, or a link closed without one.
private Exception LinkLost(ReceiverLink? receiver) => receiver?.Error is { } error
? new AmqpException(error)
: new InvalidOperationException($"the receiver link of amqp:{_address} was closed");
// A close waits for the broker's answer; on a connection that is gone without a TCP close it would wait out the
// client's default, so the reattach does not start before this.
private TimeSpan CloseWait => TimeSpan.FromSeconds(Math.Max(1, _options.Timeout));
private async Task CloseLinkQuietlyAsync(Session? session, ReceiverLink? receiver)
{
if (receiver is { IsClosed: false })
{
try { await receiver.CloseAsync(CloseWait, null).ConfigureAwait(false); }
catch (Exception ex) { _logger?.LogDebug(ex, "Error closing an AMQP receiver link"); }
}
if (session is { IsClosed: false })
{
try { await session.CloseAsync(CloseWait, null).ConfigureAwait(false); }
catch (Exception ex) { _logger?.LogDebug(ex, "Error closing an AMQP session"); }
}
}
///
public async Task Stop(CancellationToken ct = default)
{
// Step 1: stop accepting new messages
_cts?.Cancel();
// Close receivers BEFORE awaiting the loops — this unblocks ReceiveAsync (which doesn't
// accept a CancellationToken). Then drain in-flight processing, then await the loops.
// Batch mode keeps the links open until the batches in flight are settled on them (the drain below), then closes
// them: a link receive cannot be cancelled, and closing the link ends it. The broker gives back the unsettled
// deliveries of a batch still being collected when its link detaches.
if (_options.Batch is null)
{
foreach (var w in _workers)
{
if (w.Receiver is { IsClosed: false })
{
try { await w.Receiver.CloseAsync().ConfigureAwait(false); }
catch (Exception ex) { _logger?.LogWarning(ex, "Error closing AMQP receiver link"); }
}
}
}
// Step 2: drain in-flight processing
await _drain.DrainAsync(ct, _logger, $"amqp:{_address}").ConfigureAwait(false);
// Batch mode: the batches in flight are settled; closing the links now ends a receive that is still waiting.
if (_options.Batch is not null)
{
foreach (var w in _workers)
{
if (w.Receiver is { IsClosed: false })
{
try { await w.Receiver.CloseAsync().ConfigureAwait(false); }
catch (Exception ex) { _logger?.LogWarning(ex, "Error closing AMQP receiver link"); }
}
}
}
await StopWorkersAsync(ct).ConfigureAwait(false);
_cts?.Dispose();
_cts = null;
_drain.Dispose();
_logger ??= (_endpoint.Component as ComponentBase)?.Logger;
_logger?.LogInformation("AMQP consumer stopped: address={Address}", _address);
}
/// Awaits every worker loop and closes its receiver + dedicated session.
private async Task StopWorkersAsync(CancellationToken ct)
{
foreach (var w in _workers)
{
if (w.Loop != null)
{
try { await w.Loop.ConfigureAwait(false); }
catch (OperationCanceledException) { /* expected */ }
catch (Exception ex) { _logger?.LogDebug(ex, "AMQP worker loop faulted during stop"); }
}
if (w.Receiver is { IsClosed: false })
{
try { await w.Receiver.CloseAsync().ConfigureAwait(false); }
catch (Exception ex) { _logger?.LogDebug(ex, "Error closing AMQP receiver link during stop"); }
}
if (w.Session is { IsClosed: false })
{
try { await w.Session.CloseAsync().ConfigureAwait(false); }
catch (Exception ex) { _logger?.LogDebug(ex, "Error closing AMQP worker session during stop"); }
}
_endpoint.Unsupervise(w.Supervisor);
}
_workers.Clear();
}
// ── Receive loop ──
private async Task ReceiveLoopAsync(Worker worker, CancellationToken ct)
{
var receiveTimeout = _options.ReceiveTimeout > 0
? TimeSpan.FromSeconds(_options.ReceiveTimeout)
: TimeSpan.FromSeconds(60);
while (!ct.IsCancellationRequested)
{
// A link the broker closed, or lost with the connection under it, is attached again on the schedule.
var receiver = worker.Receiver;
if (receiver is null or { IsClosed: true })
{
if (!await ReattachAsync(worker, ct).ConfigureAwait(false))
break;
continue;
}
AmqpMessage? msg = null;
try
{
msg = await receiver.ReceiveAsync(receiveTimeout).ConfigureAwait(false);
if (msg == null) continue;
_drain.Increment();
try
{
await ProcessMessageAsync(worker, msg, _drain.ProcessingToken).ConfigureAwait(false);
}
finally
{
_drain.Decrement();
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested) { break; }
catch (AmqpException ex) when (ct.IsCancellationRequested)
{
_logger?.LogDebug(ex, "AMQP receive cancelled during shutdown");
break;
}
catch (Exception ex) when (ex is AmqpException || receiver.IsClosed)
{
// The link went away under the receive: not an error of a message. A detach is thrown while the link is
// still closing (IsClosed is not yet set, and a receive throws again at once), so the loop does not wait
// for IsClosed: it reports the loss to the supervisor and attaches the link again now.
_logger?.LogDebug(ex, "AMQP receive ended with the link closed: address={Address}", _address);
if (!await ReattachAsync(worker, ct).ConfigureAwait(false))
break;
}
catch (Exception ex)
{
// Transport-level failure - invisible to the core's statistics wrappers, so the
// endpoint records it itself. Pipeline errors stay with StatisticsProcessor.
_endpoint.RecordError(ex);
_logger?.LogError(ex, "Error in AMQP receive loop: address={Address}",
_address);
if (msg != null && receiver is { IsClosed: false })
{
try { receiver.Release(msg); }
catch (Exception relEx) { _logger?.LogWarning(relEx, "AMQP: failed to release message after error"); }
}
}
}
}
private async Task ProcessMessageAsync(Worker worker, AmqpMessage msg, CancellationToken ct)
{
using var span = StartConsumerSpan(msg);
var exchange = CreateExchange(msg);
var receiver = worker.Receiver;
var session = worker.Session;
if (receiver is null or { IsClosed: true } || session is null)
{
_logger?.LogWarning("AMQP: receiver closed before message could be processed");
return;
}
// The delivery is settled by this consumer once the whole unit of work ended well, not by the route
// transaction: the transaction owns the database and the outgoing sends.
var ackAction = new AmqpAckAction(receiver, msg, _logger);
// ackMode=auto: settled on receipt, before the route runs; a failure below does not bring it back.
if (_options.AckMode == AckMode.Auto)
await ackAction.Commit(ct).ConfigureAwait(false);
var pipelineFailed = false;
try
{
try
{
await _processor.Process(exchange, ct).ConfigureAwait(false);
exchange.ThrowIfUnhandledFailure();
}
catch
{
pipelineFailed = true;
throw;
}
// RPC reply, unless disableReplyTo
if (!_options.DisableReplyTo && !string.IsNullOrEmpty(msg.Properties?.ReplyTo))
{
await SendReplyAsync(session, exchange, msg.Properties.ReplyTo, msg.Properties.CorrelationId?.ToString())
.ConfigureAwait(false);
}
// Accept (settle) the message
// Settle through the ack action: a route-level .Transacted() may already have accepted it (Settled).
if (_options.AckMode == AckMode.Manual && !ackAction.Settled && receiver is { IsClosed: false })
{
await ackAction.Commit(ct).ConfigureAwait(false);
}
Interlocked.Increment(ref _processedCount);
}
catch (Exception ex)
{
// Our own stop (the processing token) is not a failure; any other cancellation is.
if (ex is not OperationCanceledException || !ct.IsCancellationRequested)
span.Activity.RecordFailure(ex);
// A pipeline failure is already counted by the core's StatisticsProcessor; a settle
// failure AFTER a successful pipeline is invisible to the core, so the transport
// records it.
if (!pipelineFailed)
_endpoint.RecordError(ex);
_logger?.LogError(ex, "AMQP message processing error: address={Address}, messageId={MessageId}",
_address, msg.Properties?.MessageId);
if (receiver is { IsClosed: false })
{
try { await ackAction.Rollback(ct).ConfigureAwait(false); }
catch (Exception releaseEx) { _logger?.LogWarning(releaseEx, "Error releasing AMQP message"); }
}
}
finally
{
await exchange.DisposeAsync().ConfigureAwait(false);
}
}
// ── Trace context propagation ──
private TransportSpan StartConsumerSpan(AmqpMessage msg)
{
var span = RouteTelemetryExtensions.StartConsumerSpan(
(_endpoint.Component as ComponentBase)?.Context,
$"{_address} receive", ActivityKind.Consumer,
"messaging.system", "amqp", _endpoint.Uri.NormalizedKey,
msg.ApplicationProperties?.Map,
static (map, name) => map is not null && map.TryGetValue(name, out var raw) ? raw?.ToString() : null,
destination: _address, operation: "receive");
if (span.Activity is { IsAllDataRequested: true } activity)
{
if (msg.Properties?.MessageId is { } msgId)
activity.SetTag("messaging.message.id", msgId);
if (msg.Properties?.Subject is { } subject)
activity.SetTag("messaging.amqp.subject", subject);
}
return span;
}
// ── Exchange creation ──
private Exchange CreateExchange(AmqpMessage msg)
{
var routeMsg = new RouteMessage();
var exchange = Exchange.Create(routeMsg, _endpoint.ScopeFactory);
FillMessage(msg, routeMsg, exchange);
// A delivery with a reply-to is a request, unless disableReplyTo (Camel's) says to ignore reply-to.
exchange.Pattern = !_options.DisableReplyTo && !string.IsNullOrEmpty(msg.Properties?.ReplyTo)
? ExchangePattern.InOut
: ExchangePattern.InOnly;
return exchange;
}
/// One delivery as an element of a batch, built as a single delivery's message is.
private RouteMessage ToMessage(AmqpMessage msg, IExchange batch)
{
var routeMsg = new RouteMessage();
FillMessage(msg, routeMsg, batch);
return routeMsg;
}
/// The body and headers of a delivery: application properties as the strategy lets them in, the AMQP properties.
private void FillMessage(AmqpMessage msg, RouteMessage routeMsg, IExchange exchange)
{
routeMsg.Body = AmqpMessageHelper.ExtractBody(msg);
AmqpMessageHelper.CopyApplicationProperties(msg, routeMsg, _headerFilter, exchange);
// Standard AMQP properties → bare header names (self-documenting, round-trip via the producer);
// transport metadata (Address/DeliveryCount/FirstAcquirer) → redbAmqp.* (no standard name).
routeMsg.Headers[AmqpHeaders.Address] = _address;
if (msg.Properties != null)
{
if (msg.Properties.MessageId != null)
routeMsg.Headers[AmqpHeaders.MessageId] = msg.Properties.MessageId.ToString()!;
if (msg.Properties.CorrelationId != null)
routeMsg.Headers[AmqpHeaders.CorrelationId] = msg.Properties.CorrelationId.ToString()!;
if (!string.IsNullOrEmpty(msg.Properties.ReplyTo))
routeMsg.Headers[AmqpHeaders.ReplyTo] = msg.Properties.ReplyTo;
if (!string.IsNullOrEmpty(msg.Properties.ContentType))
{
routeMsg.Headers[AmqpHeaders.ContentType] = msg.Properties.ContentType;
routeMsg.ContentType = msg.Properties.ContentType;
}
if (!string.IsNullOrEmpty(msg.Properties.Subject))
routeMsg.Headers[AmqpHeaders.Subject] = msg.Properties.Subject;
if (!string.IsNullOrEmpty(msg.Properties.GroupId))
routeMsg.Headers[AmqpHeaders.GroupId] = msg.Properties.GroupId;
if (msg.Properties.GroupSequence > 0)
routeMsg.Headers[AmqpHeaders.GroupSequence] = msg.Properties.GroupSequence;
if (msg.Properties.CreationTime != default)
routeMsg.Headers[AmqpHeaders.CreationTime] = msg.Properties.CreationTime;
if (msg.Properties.AbsoluteExpiryTime != default)
routeMsg.Headers[AmqpHeaders.AbsoluteExpiryTime] = msg.Properties.AbsoluteExpiryTime;
if (!string.IsNullOrEmpty(msg.Properties.ContentEncoding))
routeMsg.Headers[AmqpHeaders.ContentEncoding] = msg.Properties.ContentEncoding;
if (!string.IsNullOrEmpty(msg.Properties.To))
routeMsg.Headers[AmqpHeaders.To] = msg.Properties.To;
if (!string.IsNullOrEmpty(msg.Properties.ReplyToGroupId))
routeMsg.Headers[AmqpHeaders.ReplyToGroupId] = msg.Properties.ReplyToGroupId;
if (msg.Properties.UserId is { Length: > 0 } userId)
routeMsg.Headers[AmqpHeaders.UserId] = System.Text.Encoding.UTF8.GetString(userId);
}
if (msg.Header != null)
{
routeMsg.Headers[AmqpHeaders.Durable] = msg.Header.Durable;
routeMsg.Headers[AmqpHeaders.Priority] = msg.Header.Priority;
if (msg.Header.Ttl > 0)
routeMsg.Headers[AmqpHeaders.Ttl] = msg.Header.Ttl;
routeMsg.Headers[AmqpHeaders.DeliveryCount] = msg.Header.DeliveryCount;
routeMsg.Headers[AmqpHeaders.FirstAcquirer] = msg.Header.FirstAcquirer;
}
}
// ── RPC reply ──
private async Task SendReplyAsync(Session session, IExchange exchange, string replyTo, string? correlationId)
{
try
{
var responseBody = exchange.HasOut
? exchange.Out!.Body
: exchange.In.Body;
object wireBody = responseBody switch
{
byte[] bytes => (object)bytes,
string str => str,
null => Array.Empty(),
var other => other.ToString() ?? string.Empty
};
var reply = new AmqpMessage(wireBody)
{
Properties = new Properties { ContentType = exchange.In.ContentType ?? _options.ContentType }
};
if (!string.IsNullOrEmpty(correlationId))
reply.Properties.CorrelationId = correlationId;
// Response headers → application-properties, as the endpoint's strategy lets them out
var responseHeaders = exchange.HasOut ? exchange.Out!.Headers : exchange.In.Headers;
var appProps = new ApplicationProperties();
foreach (var (key, value) in responseHeaders)
{
if (value is null) continue;
if (_headerFilter.FilterOutgoing(key, value, exchange)) continue;
appProps[key] = value switch
{
string s => s,
int or long or float or double or bool => value,
_ => value.ToString()!
};
}
if (appProps.Map.Count > 0)
reply.ApplicationProperties = appProps;
// Reply on the WORKER's own session (never the shared endpoint session) — each worker
// runs on its own AMQP session, so concurrent replies never race on a shared session.
var replySender = new SenderLink(
session,
$"reply-sender-{Guid.NewGuid():N}",
replyTo);
// Bounded send timeout: a dead reply address (client gone, queue removed)
// must not block the consumer slot indefinitely. The original message will
// still be accepted by the caller — the client will see its own RPC timeout.
var sendTimeout = TimeSpan.FromSeconds(_options.ReplyTimeout > 0 ? _options.ReplyTimeout : 2);
await replySender.SendAsync(reply, sendTimeout).ConfigureAwait(false);
try { await replySender.CloseAsync(TimeSpan.FromSeconds(2)).ConfigureAwait(false); }
catch (Exception closeEx)
{
_logger?.LogWarning(closeEx, "AMQP: error closing reply sender, forcing close");
replySender.Close(TimeSpan.Zero);
}
_logger?.LogDebug("AMQP RPC reply sent: replyTo={ReplyTo}, correlationId={CorrelationId}",
replyTo, correlationId);
}
catch (Exception ex)
{
// Swallow: failed reply must not prevent accepting the original message.
// Client will detect failure via its own RPC timeout.
_logger?.LogWarning(ex, "AMQP: failed to send RPC reply to {ReplyTo} (correlationId={CorrelationId}) — original message will still be accepted",
replyTo, correlationId);
}
}
}
/// Deferred AMQP acknowledgement action.
internal sealed class AmqpAckAction : ITransactedAction
{
private int _settled;
/// True once the delivery was accepted or released, by either the deferred (transaction) or the inline path.
public bool Settled => Volatile.Read(ref _settled) == 1;
private readonly ReceiverLink _receiver;
private readonly AmqpMessage _msg;
private readonly ILogger? _logger;
public AmqpAckAction(ReceiverLink receiver, AmqpMessage msg, ILogger? logger)
{
_receiver = receiver;
_msg = msg;
_logger = logger;
}
///
public Task Commit(CancellationToken ct = default)
{
if (Interlocked.Exchange(ref _settled, 1) != 0) return Task.CompletedTask;
_receiver.Accept(_msg);
_logger?.LogDebug("AMQP ack committed");
return Task.CompletedTask;
}
///
/// Gives the delivery back as a failed one: the modified outcome with delivery-failed, so the broker
/// counts the attempt and a message that always fails ends at its maximum delivery count (Artemis moves it to the
/// dead letter address). The released outcome is not counted, and such a message would come back without end.
///
public Task Rollback(CancellationToken ct = default)
{
if (Interlocked.Exchange(ref _settled, 1) != 0) return Task.CompletedTask;
_receiver.Modify(_msg, deliveryFailed: true);
_logger?.LogDebug("AMQP nack (modified, delivery-failed)");
return Task.CompletedTask;
}
}