Path: redb-route/redb.Route.RabbitMQ/RabbitMQConsumer.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.RabbitMQ/RabbitMQConsumer.Batch.cs
----
using System.Threading.Channels;
using Microsoft.Extensions.Logging;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using redb.Route.Abstractions;
using redb.Route.Batching;
using redb.Route.Core;
using redb.Route.Telemetry;
namespace redb.Route.RabbitMQ;
///
/// Batch mode of the RabbitMQ consumer (batching=true), on the core batch contract: deliveries are buffered as
/// they arrive, concurrentConsumers workers each collect a batch from the buffer and run it through the route,
/// one batch per worker at a time, and every delivery of a batch is settled once after the route. A failed batch
/// follows the rule of a failed single delivery for every delivery in it: tried again up to
/// maximumRetryAttempts, retryDelay apart, then rejected without requeue (or requeued).
///
public sealed partial class RabbitMQConsumer
{
private Channel? _deliveries;
private CancellationTokenSource? _batchStop;
private Task[] _batchWorkers = [];
private void StartBatchWorkers(BatchOptions batch, IChannel channel)
{
_deliveries = Channel.CreateUnbounded();
_batchStop = new CancellationTokenSource();
var stop = _batchStop.Token;
_batchWorkers = Enumerable.Range(0, _options.ResolvedConcurrentConsumers)
.Select(_ => Task.Run(() => BatchWorkerAsync(batch, channel, stop)))
.ToArray();
}
///
/// Stops collecting: a batch half collected goes back to the broker, a batch running finishes (the drain waits for
/// it), and the deliveries still buffered are requeued.
///
private async Task StopBatchWorkersAsync()
{
if (_batchStop is null)
return;
await _batchStop.CancelAsync().ConfigureAwait(false);
}
private async Task AwaitBatchWorkersAsync(IChannel? channel)
{
if (_batchStop is null)
return;
try
{
await Task.WhenAll(_batchWorkers).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger?.LogWarning(ex, "RabbitMQ batch worker ended with an error on queue {Queue}", _actualQueueName);
}
var left = new List();
while (_deliveries!.Reader.TryRead(out var delivery))
left.Add(delivery);
if (left.Count > 0 && channel is { IsOpen: true } && _options.AckMode == AckMode.Manual)
await SettleManyAsync(channel, left, Settlement.Requeue).ConfigureAwait(false);
_batchStop.Dispose();
_batchStop = null;
_batchWorkers = [];
_deliveries = null;
}
///
/// A delivery in batch mode: buffered for the workers, its body copied (the client reuses the buffer once the handler
/// returns). A delivery that asks for a reply cannot be answered from a one-way batch: unless disableReplyTo
/// says to ignore reply-to, it is rejected without requeue at once, by the poison path, and the rest goes on.
///
private async Task OnBatchDeliveryAsync(object sender, BasicDeliverEventArgs ea)
{
var channel = _channel;
if (!_options.DisableReplyTo && !string.IsNullOrEmpty(ea.BasicProperties.ReplyTo))
{
var refused = new InvalidOperationException(
$"RabbitMQ batch consumer on queue '{_actualQueueName}' received a delivery with reply-to " +
$"'{ea.BasicProperties.ReplyTo}': a batch is one-way and nobody would answer it, so it is rejected without " +
"requeue (to the dead letter exchange, if the queue 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.Manual && channel is { IsOpen: true })
{
try { await SettleAsync(channel, ea.DeliveryTag, Settlement.Reject).ConfigureAwait(false); }
catch (Exception ex) { _logger?.LogWarning(ex, "RabbitMQ: rejecting a delivery with a reply-to failed"); }
}
return;
}
var copy = new BasicDeliverEventArgs(ea.ConsumerTag, ea.DeliveryTag, ea.Redelivered, ea.Exchange, ea.RoutingKey,
ea.BasicProperties, ea.Body.ToArray(), CancellationToken.None);
_deliveries?.Writer.TryWrite(copy);
}
private async Task BatchWorkerAsync(BatchOptions batch, IChannel channel, CancellationToken stop)
{
var settlement = new RabbitBatchSettlement(this, channel);
var dispatcher = new BatchDispatcher(Processor, settlement, ToMessage,
_endpoint.ScopeFactory, [RmqHeaders.Exchange, RmqHeaders.RoutingKey]);
var collector = new BatchCollector(batch, ReceiveAsync);
while (!stop.IsCancellationRequested)
{
CollectedBatch collected;
try
{
collected = await collector.CollectAsync(stop).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger?.LogError(ex, "RabbitMQ batch collection failed on queue {Queue}", _actualQueueName);
continue;
}
if (collected.Items.Count == 0)
continue;
if (collected.Interrupted)
{
await settlement.ReturnAsync(collected.Items, CancellationToken.None).ConfigureAwait(false);
return;
}
using var inWork = TrackInflight();
var token = ProcessingToken;
try
{
await RunBatchAsync(dispatcher, settlement, collected.Items, token).ConfigureAwait(false);
}
catch (OperationCanceledException ex) when (IsOwnStop(ex, token))
{
return;
}
catch (Exception ex)
{
_endpoint.RecordError(ex);
_logger?.LogError(ex, "RabbitMQ batch failed to settle on queue {Queue}", _actualQueueName);
}
}
}
///
/// Runs one batch, trying it again on failure by the rule of a failed single delivery: up to
/// maximumRetryAttempts in all, retryDelay apart, each attempt on a fresh batch exchange; the last
/// failure settles every delivery by rejectAndDontRequeue.
///
private async Task RunBatchAsync(BatchDispatcher dispatcher, RabbitBatchSettlement settlement,
IReadOnlyList items, CancellationToken token)
{
using var span = BatchDispatcher.StartSpan(
(_endpoint.Component as ComponentBase)?.Context, $"{items[0].Exchange} receive", "rabbitmq",
_endpoint.Uri.NormalizedKey, items[0].Exchange,
items.Select(i => RouteTelemetryExtensions.ExtractTraceContext(i.BasicProperties.Headers, ReadTraceHeader)),
items.Count);
for (var attempt = 1; ; attempt++)
{
settlement.FinalAttempt = attempt >= _options.MaximumRetryAttempts;
var outcome = await dispatcher.DispatchAsync(items, span, token).ConfigureAwait(false);
if (outcome == BatchOutcome.Accepted)
{
Interlocked.Add(ref _processedCount, items.Count);
return;
}
if (settlement.FinalAttempt)
return;
_logger?.LogWarning(
"RabbitMQ: attempt {Attempt} of {Max} failed on a batch of {Count} on queue {Queue}; the next in {Delay} ms",
attempt, _options.MaximumRetryAttempts, items.Count, _actualQueueName, _options.RetryDelay);
try
{
await RetryPauseAsync(token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
await settlement.ReturnAsync(items, CancellationToken.None).ConfigureAwait(false);
throw;
}
}
}
///
/// The transport's part of collection: the first buffered delivery within , then whatever else
/// is already buffered, up to .
///
private async ValueTask ReceiveAsync(List into, int max, TimeSpan wait, CancellationToken ct)
{
var reader = _deliveries!.Reader;
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(wait);
BasicDeliverEventArgs first;
try
{
first = await reader.ReadAsync(timeout.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
return 0;
}
catch (ChannelClosedException)
{
return 0;
}
into.Add(first);
var added = 1;
while (added < max && reader.TryRead(out var more))
{
into.Add(more);
added++;
}
return added;
}
/// One delivery into a message, built as a single delivery's exchange message is.
private IMessage ToMessage(BasicDeliverEventArgs ea, IExchange batch)
{
var message = new Message(ea.Body.ToArray());
Fill(message, ea, _headerFilter, batch);
return message;
}
/// Settles every delivery of the same way, then commits once on a transacted channel.
private async Task SettleManyAsync(IChannel channel, IReadOnlyList items, Settlement settlement)
{
foreach (var item in items)
{
switch (settlement)
{
case Settlement.Ack:
await channel.BasicAckAsync(item.DeliveryTag, multiple: false).ConfigureAwait(false);
break;
case Settlement.Requeue:
await channel.BasicNackAsync(item.DeliveryTag, multiple: false, requeue: true).ConfigureAwait(false);
break;
default:
await channel.BasicRejectAsync(item.DeliveryTag, requeue: false).ConfigureAwait(false);
break;
}
}
if (_options.Transacted == true)
await channel.TxCommitAsync().ConfigureAwait(false);
_logger?.LogDebug("RabbitMQ {Settle}: {Count} deliveries of a batch", settlement, items.Count);
}
///
/// RabbitMQ's settlement of a batch: by delivery tag, every delivery the same way. With ackMode=auto the
/// broker settled them on hand-off and there is nothing to do.
///
private sealed class RabbitBatchSettlement(RabbitMQConsumer owner, IChannel channel) : IBatchSettlement
{
/// Whether a failure settles the batch (the last attempt) or leaves it for the next attempt.
public bool FinalAttempt { get; set; }
private bool Manual => owner._options.AckMode == AckMode.Manual;
public ValueTask BeforeRouteAsync(IExchange batch, IReadOnlyList items,
CancellationToken ct) => ValueTask.FromResult(null);
public async ValueTask AcceptAsync(IExchange batch, IReadOnlyList items, CancellationToken ct)
{
if (Manual)
await owner.SettleManyAsync(channel, items, Settlement.Ack).ConfigureAwait(false);
}
public async ValueTask RejectAsync(IExchange batch, IReadOnlyList items, Exception failure,
CancellationToken ct)
{
owner._logger?.LogError(failure, "RabbitMQ batch of {Count} failed on queue {Queue}", items.Count, owner._actualQueueName);
if (!FinalAttempt || !Manual)
return;
await owner.SettleManyAsync(channel, items,
owner._options.RejectAndDontRequeue ? Settlement.Reject : Settlement.Requeue).ConfigureAwait(false);
}
public async ValueTask ReturnAsync(IReadOnlyList items, CancellationToken ct)
{
if (Manual && channel.IsOpen)
await owner.SettleManyAsync(channel, items, Settlement.Requeue).ConfigureAwait(false);
}
}
}