Path: redb-route/redb.Route/Processors/MulticastProcessor.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/Processors/MulticastProcessor.cs
----
using redb.Route.Abstractions;
using redb.Route.Telemetry;
using redb.Route.Transactions;
namespace redb.Route.Processors;
///
/// Sends the exchange to multiple processors (fan-out).
/// Supports parallel/sequential execution, aggregation strategy, stopOnException,
/// timeout, and configurable concurrency with deterministic result ordering.
///
public class MulticastProcessor : IProcessor
{
private readonly List _targets = [];
private readonly bool _parallelProcessing;
private readonly int _maxDegreeOfParallelism;
private readonly bool _stopOnException;
private readonly TimeSpan _timeout;
private readonly Func? _aggregationStrategy;
/// Gets the list of target processors.
public IReadOnlyList Targets => _targets;
/// Creates a multicast processor.
/// Whether to process targets in parallel (true) or sequentially (false).
/// Optional pair-wise aggregation: (aggregated, current) → merged.
/// Whether to stop on the first exception.
/// Timeout for the entire multicast operation (TimeSpan.Zero = no timeout).
/// Maximum concurrent tasks when parallel (0 = unlimited).
public MulticastProcessor(
bool parallelProcessing = true,
Func? aggregationStrategy = null,
bool stopOnException = false,
TimeSpan timeout = default,
int maxDegreeOfParallelism = 0)
{
_parallelProcessing = parallelProcessing;
_aggregationStrategy = aggregationStrategy;
_stopOnException = stopOnException;
_timeout = timeout;
_maxDegreeOfParallelism = maxDegreeOfParallelism > 0 ? maxDegreeOfParallelism : Environment.ProcessorCount;
}
/// Adds a target processor to the multicast.
/// Target processor.
/// This instance for fluent chaining.
public MulticastProcessor AddTarget(IProcessor processor)
{
ArgumentNullException.ThrowIfNull(processor);
_targets.Add(processor);
return this;
}
///
public async Task Process(IExchange exchange, CancellationToken ct = default)
{
if (_targets.Count == 0) return;
ProcessorMetrics.MulticastBranches.Record(_targets.Count);
using var timeoutCts = _timeout > TimeSpan.Zero
? CancellationTokenSource.CreateLinkedTokenSource(ct)
: null;
if (timeoutCts != null)
timeoutCts.CancelAfter(_timeout);
var effectiveCt = timeoutCts?.Token ?? ct;
try
{
if (_parallelProcessing)
await ProcessParallel(exchange, effectiveCt).ConfigureAwait(false);
else
await ProcessSequential(exchange, effectiveCt).ConfigureAwait(false);
}
catch (OperationCanceledException) when (timeoutCts != null && timeoutCts.IsCancellationRequested && !ct.IsCancellationRequested)
{
throw new TimeoutException($"Multicast processing timed out after {_timeout.TotalMilliseconds} ms.");
}
}
private async Task ProcessSequential(IExchange exchange, CancellationToken ct)
{
var clones = new IExchange[_targets.Count];
Exception? firstException = null;
try
{
for (var i = 0; i < _targets.Count; i++)
{
ct.ThrowIfCancellationRequested();
clones[i] = Branch(exchange.CorrelatedCopyLinked(), i);
try
{
await _targets[i].Process(clones[i], ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
clones[i].Exception = ex;
firstException ??= ex;
ProcessorMetrics.MulticastFailedBranches.Add(1);
if (_stopOnException)
{
exchange.Exception = ex;
break;
}
}
}
Aggregate(exchange, clones);
}
finally
{
// Release the clones' DI scopes only, as Splitter / ScatterGather / RecipientList do. Disposing
// a clone would close its body, and the aggregation may have handed exactly that body (or the
// clones themselves, GroupedExchange) to the original exchange.
foreach (var clone in clones)
if (clone is redb.Route.Core.Exchange e) await e.ReleaseScopes().ConfigureAwait(false);
}
if (firstException != null && _stopOnException)
throw firstException;
}
private async Task ProcessParallel(IExchange exchange, CancellationToken ct)
{
var clones = new IExchange?[_targets.Count];
var exceptions = new Exception?[_targets.Count];
var shouldStop = 0;
using var semaphore = new SemaphoreSlim(_maxDegreeOfParallelism);
try
{
var tasks = new Task[_targets.Count];
for (var i = 0; i < _targets.Count; i++)
{
var idx = i;
tasks[idx] = Task.Run(async () =>
{
if (Volatile.Read(ref shouldStop) == 1) return;
await semaphore.WaitAsync(ct).ConfigureAwait(false);
try
{
if (Volatile.Read(ref shouldStop) == 1) return;
var clone = Branch(exchange.CorrelatedCopy(), idx);
clones[idx] = clone;
try
{
// Isolate this branch under a dependent clone of the ambient transaction so
// concurrent branches never share one Transaction.Current (see DependentTransactionBranch).
await DependentTransactionBranch.RunAsync(() => _targets[idx].Process(clone, ct)).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
clone.Exception = ex;
exceptions[idx] = ex;
ProcessorMetrics.MulticastFailedBranches.Add(1);
if (_stopOnException)
{
Interlocked.Exchange(ref shouldStop, 1);
}
}
finally
{
// Release DI scopes early; body/headers stay alive for aggregation
await clone.ReleaseScopes().ConfigureAwait(false);
}
}
finally
{
semaphore.Release();
}
}, ct);
}
await Task.WhenAll(tasks).ConfigureAwait(false);
// Aggregate in deterministic index order
Aggregate(exchange, clones!);
var allExceptions = exceptions.Where(e => e != null).Cast().ToArray();
if (allExceptions.Length > 0)
{
exchange.Exception = allExceptions.Length == 1
? allExceptions[0]
: new AggregateException("Multiple multicast targets failed.", allExceptions);
if (_stopOnException)
throw allExceptions[0];
}
}
finally
{
// Release the clones' DI scopes only, as Splitter / ScatterGather / RecipientList do. Disposing
// a clone would close its body, and the aggregation may have handed exactly that body (or the
// clones themselves, GroupedExchange) to the original exchange.
foreach (var clone in clones)
if (clone is redb.Route.Core.Exchange e) await e.ReleaseScopes().ConfigureAwait(false);
}
}
///
/// Marks a branch copy as Camel's multicast does: its index and whether it is the last branch, as exchange
/// properties. The copy is a correlated one: its own id, and the original's id as its correlation id.
///
private IExchange Branch(IExchange copy, int index)
{
copy.Properties[ExchangePropertyKeys.MulticastIndex] = index;
copy.Properties[ExchangePropertyKeys.MulticastComplete] = index == _targets.Count - 1;
return copy;
}
private void Aggregate(IExchange original, IExchange[] clones)
{
if (_aggregationStrategy == null) return;
IExchange? aggregated = null;
foreach (var clone in clones)
{
if (clone == null) continue;
// Skip error clones if stopOnException is set — only aggregate successful results
if (_stopOnException && clone.Exception != null) continue;
aggregated = aggregated == null
? clone
: _aggregationStrategy(aggregated, clone);
}
if (aggregated != null)
{
original.In.Body = aggregated.In.Body;
foreach (var header in aggregated.In.Headers)
original.In.Headers[header.Key] = header.Value;
foreach (var prop in aggregated.Properties)
{
// The clone's own bookkeeping (cached DI scopes, registered resources) stays with the clone, which
// releases it right after this merge; copying it here would leave the original a disposed scope.
// The branch's correlation id points at the original; the original keeps its own, as in Camel.
if (ExchangeResources.IsOwnedByExchange(prop.Key) || prop.Key == ExchangePropertyKeys.CorrelationId)
continue;
original.Properties[prop.Key] = prop.Value;
}
}
}
}