Path: redb-route/redb.Route/Batching/BatchDispatcher.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/Batching/BatchDispatcher.cs
----
using System.Diagnostics;
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Telemetry;
namespace redb.Route.Batching;
/// What became of a dispatched batch.
public enum BatchOutcome
{
/// The route succeeded; the batch was accepted.
Accepted,
/// The route failed; the batch was settled by the connector's failure rule.
Rejected,
/// The consumer was cancelled while the route ran; the batch was given back to the broker.
Returned,
}
///
/// Runs a collected batch through the route, one implementation for every broker: it builds the batch exchange
/// (InOnly, body a of , one message per broker message, even for a batch of
/// one), runs the route once, and settles the batch once after the route has returned, through the connector's
/// .
///
public sealed class BatchDispatcher
{
private readonly IProcessor _processor;
private readonly IBatchSettlement _settlement;
private readonly Func _toMessage;
private readonly IServiceScopeFactory? _scopeFactory;
private readonly IReadOnlyCollection _sharedHeaders;
/// Creates a dispatcher for one consumer.
/// The route.
/// How the connector settles a batch.
///
/// One broker message into a message, built as the connector builds a single message's, so a destination gives one
/// message shape in both modes. The exchange is the batch exchange, for header filtering.
///
/// The endpoint's scope factory, for the batch exchange's DI scope.
///
/// Transport headers set on the batch message when every message of the batch carries the same value, as Camel's
/// CamelKafkaTopic on a batch (a topic, a queue, a partition).
///
public BatchDispatcher(IProcessor processor, IBatchSettlement settlement, Func toMessage,
IServiceScopeFactory? scopeFactory, IReadOnlyCollection sharedHeaders)
{
_processor = processor ?? throw new ArgumentNullException(nameof(processor));
_settlement = settlement ?? throw new ArgumentNullException(nameof(settlement));
_toMessage = toMessage ?? throw new ArgumentNullException(nameof(toMessage));
_scopeFactory = scopeFactory;
_sharedHeaders = sharedHeaders ?? throw new ArgumentNullException(nameof(sharedHeaders));
}
///
/// Runs through the route and settles them. A failure of the route is not thrown: it marks
/// , and the batch is settled by the connector's failure rule. Only a cancellation by
/// is thrown, after the batch has been given back.
///
public async Task DispatchAsync(IReadOnlyList items, TransportSpan span, CancellationToken processingCt)
{
ArgumentNullException.ThrowIfNull(items);
if (items.Count == 0)
throw new ArgumentException("A batch has at least one message.", nameof(items));
var exchange = CreateExchange(items);
try
{
Exception? failure;
try
{
var scope = await _settlement.BeforeRouteAsync(exchange, items, processingCt).ConfigureAwait(false);
try
{
await _processor.Process(exchange, processingCt).ConfigureAwait(false);
}
finally
{
scope?.Dispose();
}
failure = ExchangeFailureExtensions.FailureOf(exchange);
}
catch (OperationCanceledException) when (processingCt.IsCancellationRequested)
{
await _settlement.ReturnAsync(items, CancellationToken.None).ConfigureAwait(false);
throw;
}
catch (Exception ex)
{
failure = ex;
}
if (failure is not null)
{
span.Activity.RecordFailure(failure);
await _settlement.RejectAsync(exchange, items, failure, CancellationToken.None).ConfigureAwait(false);
return BatchOutcome.Rejected;
}
await _settlement.AcceptAsync(exchange, items, CancellationToken.None).ConfigureAwait(false);
return BatchOutcome.Accepted;
}
finally
{
await exchange.DisposeAsync().ConfigureAwait(false);
}
}
/// Builds the batch exchange: InOnly, body a list of one message per broker message.
internal Exchange CreateExchange(IReadOnlyList items)
{
var batchMessage = new Message();
var exchange = Exchange.Create(batchMessage, _scopeFactory);
exchange.Pattern = ExchangePattern.InOnly;
var messages = new List(items.Count);
foreach (var item in items)
messages.Add(_toMessage(item, exchange));
batchMessage.Body = messages;
foreach (var header in _sharedHeaders)
{
if (SharedValue(messages, header, out var value))
batchMessage.Headers[header] = value;
}
return exchange;
}
private static bool SharedValue(List messages, string header, out object? value)
{
value = null;
for (var i = 0; i < messages.Count; i++)
{
if (!messages[i].Headers.TryGetValue(header, out var current))
return false;
if (i == 0)
value = current;
else if (!Equals(value, current))
return false;
}
return true;
}
///
/// The receive span of a batch: a root of its own (its messages come from different senders and traces, none of
/// them is its parent), linked to the context of every message that carries one, with the batch size as
/// messaging.batch.message_count.
///
public static TransportSpan StartSpan(IRouteContext? context, string name, string systemValue, string endpointUri,
string? destination, IEnumerable senders, int count)
{
ArgumentNullException.ThrowIfNull(senders);
var links = new List();
foreach (var sender in senders)
{
if (sender != default)
links.Add(new ActivityLink(sender));
}
var span = RouteTelemetryExtensions.StartConsumerSpan