Path: redb-route/redb.Route.Amqp/AmqpConsumer.Batch.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Amqp/AmqpConsumer.Batch.cs
----
using Amqp;
using Amqp.Framing;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Batching;
using redb.Route.Core;
using redb.Route.Telemetry;
using AmqpMessage = global::Amqp.Message;
namespace redb.Route.Amqp;
///
/// Batch mode of the AMQP 1.0 consumer (batching=true), on the core batch contract: each worker collects up to
/// maxBatchMessages deliveries of its receiver link, runs them through the route once and settles them once.
/// Success accepts every delivery; a failure applies the rule of a failed single delivery to each of them: released,
/// so the broker delivers it again. A batch the consumer stops on is given back: released, or, once the stop has closed
/// the link, returned by the broker on detach. A delivery that asks for a reply cannot
/// be answered from a one-way batch: unless disableReplyTo=true, it is rejected at once (the broker moves a
/// rejected delivery to its dead letter address, where it has one) and the rest goes on.
///
public sealed partial class AmqpConsumer
{
private async Task BatchLoopAsync(Worker worker, BatchOptions batch, CancellationToken stop)
{
// One pass per link: a link the broker closed, or lost with the connection under it, is attached again on the
// schedule, and the deliveries it held unsettled come back from the broker.
while (!stop.IsCancellationRequested)
{
// A link that ends its pass is attached again at once: a detached link is not IsClosed until it has closed.
if (worker.Receiver is { IsClosed: false } receiver
&& !await BatchLinkLoopAsync(receiver, batch, stop).ConfigureAwait(false))
return;
if (!await ReattachAsync(worker, stop).ConfigureAwait(false))
return;
}
}
///
/// Collects and runs batches on one link until the link closes (returns true: the caller attaches it again) or
/// the consumer stops (returns false).
///
private async Task BatchLinkLoopAsync(ReceiverLink receiver, BatchOptions batch, CancellationToken stop)
{
var settlement = new AmqpBatchSettlement(this, receiver);
var dispatcher = new BatchDispatcher(_processor, settlement, ToMessage, _endpoint.ScopeFactory,
[AmqpHeaders.Address]);
var collector = new BatchCollector(batch,
(into, max, wait, ct) => ReceiveIntoBatchAsync(receiver, into, max, wait, ct));
while (!stop.IsCancellationRequested && !receiver.IsClosed)
{
CollectedBatch collected;
try
{
collected = await collector.CollectAsync(stop).ConfigureAwait(false);
}
catch (Exception ex) when (!stop.IsCancellationRequested && (ex is AmqpException || receiver.IsClosed))
{
// The link went away under the collection (a detach throws while the link is still closing): not an error
// of a message; the caller attaches it again.
_logger?.LogDebug(ex, "AMQP batch receive ended with the link closed: address={Address}", _address);
return true;
}
catch (Exception ex) when (!stop.IsCancellationRequested)
{
_endpoint.RecordError(ex);
_logger?.LogError(ex, "Error in AMQP batch receive: address={Address}", _address);
continue;
}
catch (Exception ex)
{
_logger?.LogDebug(ex, "AMQP batch receive ended by the stop");
return false;
}
if (collected.Items.Count == 0)
continue;
if (collected.Interrupted)
{
await settlement.ReturnAsync(collected.Items, CancellationToken.None).ConfigureAwait(false);
return false;
}
var items = collected.Items;
using var span = BatchDispatcher.StartSpan(
(_endpoint.Component as ComponentBase)?.Context, $"{_address} receive", "amqp",
_endpoint.Uri.NormalizedKey, _address,
items.Select(m => RouteTelemetryExtensions.ExtractTraceContext(m.ApplicationProperties?.Map,
static (map, name) => map is not null && map.TryGetValue(name, out var raw) ? raw?.ToString() : null)),
items.Count);
_drain.Increment();
try
{
if (await dispatcher.DispatchAsync(items, span, _drain.ProcessingToken).ConfigureAwait(false)
== BatchOutcome.Accepted)
Interlocked.Add(ref _processedCount, items.Count);
}
catch (OperationCanceledException) when (_drain.ProcessingToken.IsCancellationRequested)
{
return false;
}
catch (Exception ex)
{
_endpoint.RecordError(ex);
_logger?.LogError(ex, "AMQP batch failed to settle: address={Address}", _address);
}
finally
{
_drain.Decrement();
}
}
return !stop.IsCancellationRequested;
}
///
/// The transport's part of collection: one delivery from the link, waiting at most . The link
/// has no cancellable receive: a stop is seen when the wait ends, or when the stop closes the link.
///
internal async ValueTask ReceiveIntoBatchAsync(ReceiverLink receiver, List into, int max,
TimeSpan wait, CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
var msg = await receiver.ReceiveAsync(WholeMilliseconds(wait)).ConfigureAwait(false);
if (msg is null)
{
ct.ThrowIfCancellationRequested();
return 0;
}
if (!_options.DisableReplyTo && !string.IsNullOrEmpty(msg.Properties?.ReplyTo))
{
RejectRequest(receiver, msg);
ct.ThrowIfCancellationRequested();
return 0;
}
into.Add(msg);
ct.ThrowIfCancellationRequested();
return 1;
}
///
/// The wait rounded up to whole milliseconds, at least one. AMQPNetLite's ReceiveAsync(TimeSpan) counts whole
/// milliseconds and drops the rest, and a receive of 0 ms with no delivery at hand creates no waiter: its task never
/// completes. The collector's last wait before the idle or hard deadline can be under a millisecond, and the worker
/// then waited forever, receiving nothing and holding the consumer's stop.
///
internal static TimeSpan WholeMilliseconds(TimeSpan wait)
=> TimeSpan.FromMilliseconds(Math.Max(1, Math.Ceiling(wait.TotalMilliseconds)));
/// A delivery with a reply-to in batch mode: rejected at once, recorded, and the batch goes on.
private void RejectRequest(ReceiverLink receiver, AmqpMessage msg)
{
var refused = new InvalidOperationException(
$"AMQP batch consumer on '{_address}' received a delivery with reply-to '{msg.Properties!.ReplyTo}': a batch is " +
"one-way and nobody would answer it, so it is rejected (to the dead letter address, if the broker has one). " +
"Set disableReplyTo=true to batch such deliveries without a reply.");
_endpoint.RecordError(refused);
_logger?.LogError(refused, "{Message}", refused.Message);
if (_options.AckMode == AckMode.Auto)
{
// ackMode=auto settles on receipt, as a single delivery: accepted, gone.
receiver.Accept(msg);
return;
}
try
{
receiver.Reject(msg, new Error(new global::Amqp.Types.Symbol("amqp:not-implemented"))
{
Description = "a batch consumer does not answer requests",
});
}
catch (Exception ex)
{
_logger?.LogWarning(ex, "AMQP: rejecting a delivery with a reply-to failed");
}
}
///
/// AMQP's settlement of a batch: each delivery on the link it came on. One instance per worker, used by one batch at
/// a time.
///
private sealed class AmqpBatchSettlement(AmqpConsumer owner, ReceiverLink receiver) : IBatchSettlement
{
/// The batch in flight was accepted on receipt (ackMode=auto): there is nothing to give back.
private bool _acceptedOnReceipt;
public ValueTask BeforeRouteAsync(IExchange batch, IReadOnlyList items, CancellationToken ct)
{
// ackMode=auto: accepted on receipt, before the route runs (at-most-once), as a single delivery is.
if (owner._options.AckMode == AckMode.Auto)
{
Settle(items, receiver.Accept, "accept");
_acceptedOnReceipt = true;
}
return ValueTask.FromResult(null);
}
public ValueTask AcceptAsync(IExchange batch, IReadOnlyList items, CancellationToken ct)
{
if (!_acceptedOnReceipt)
Settle(items, receiver.Accept, "accept");
_acceptedOnReceipt = false;
return ValueTask.CompletedTask;
}
public ValueTask RejectAsync(IExchange batch, IReadOnlyList items, Exception failure, CancellationToken ct)
{
owner._logger?.LogError(failure, "AMQP batch of {Count} failed: address={Address}; given back as failed for redelivery",
items.Count, owner._address);
if (!_acceptedOnReceipt)
Settle(items, m => receiver.Modify(m, deliveryFailed: true), "modify");
_acceptedOnReceipt = false;
return ValueTask.CompletedTask;
}
public ValueTask ReturnAsync(IReadOnlyList items, CancellationToken ct)
{
// A closed link gave its unsettled deliveries back to the broker when it detached.
if (!_acceptedOnReceipt && !receiver.IsClosed)
Settle(items, receiver.Release, "release");
_acceptedOnReceipt = false;
return ValueTask.CompletedTask;
}
/// Settles each delivery; one that fails (a link closed under it) is logged and the broker gives it back.
private void Settle(IReadOnlyList items, Action settle, string operation)
{
foreach (var msg in items)
{
try
{
settle(msg);
}
catch (Exception ex)
{
owner._endpoint.RecordError(ex);
owner._logger?.LogWarning(ex, "AMQP batch {Operation} failed for messageId={MessageId} on {Address}",
operation, msg.Properties?.MessageId, owner._address);
}
}
}
}
}