Path: redb-route/redb.Route/Processors/RecipientListProcessor.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/RecipientListProcessor.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Telemetry;
namespace redb.Route.Processors;
///
/// Sends the exchange to a dynamic list of endpoints determined at runtime.
/// Unlike Multicast (static URI list), RecipientList computes URIs from the exchange.
/// Supports parallel/sequential processing and configurable aggregation.
/// Producers are cached per URI for the lifetime of this processor.
///
internal sealed class RecipientListProcessor : IProcessor, IAsyncDisposable
{
private readonly IRouteContext _context;
private readonly Func> _recipientListFactory;
private readonly bool _parallelProcessing;
private readonly bool _stopOnException;
private readonly Func? _aggregationStrategy;
private readonly Dictionary _producerCache = new(StringComparer.Ordinal);
private readonly object _cacheLock = new();
/// Creates a recipient list processor.
/// Route context for resolving endpoints.
/// Function that returns target URIs from the exchange.
/// Whether to send to recipients in parallel.
/// Whether to stop on the first exception.
/// Optional pair-wise aggregation of results.
public RecipientListProcessor(
IRouteContext context,
Func> recipientListFactory,
bool parallelProcessing = false,
bool stopOnException = false,
Func? aggregationStrategy = null)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
_recipientListFactory = recipientListFactory ?? throw new ArgumentNullException(nameof(recipientListFactory));
_parallelProcessing = parallelProcessing;
_stopOnException = stopOnException;
_aggregationStrategy = aggregationStrategy;
}
///
public async Task Process(IExchange exchange, CancellationToken ct = default)
{
var uris = _recipientListFactory(exchange).ToList();
if (uris.Count == 0) return;
ProcessorMetrics.RecipientListRecipients.Record(uris.Count);
if (_parallelProcessing)
await ProcessParallel(exchange, uris, ct).ConfigureAwait(false);
else
await ProcessSequential(exchange, uris, ct).ConfigureAwait(false);
}
private async Task ProcessSequential(IExchange exchange, List uris, CancellationToken ct)
{
IExchange? aggregated = null;
var copies = new List(uris.Count);
try
{
foreach (var uri in uris)
{
ct.ThrowIfCancellationRequested();
var copy = exchange.CorrelatedCopyLinked();
copies.Add(copy);
var (endpoint, producer) = GetOrCreateProducer(uri);
copy.Properties[ExchangePropertyKeys.RecipientListEndpoint] = uri;
try
{
await Core.CountedSend.Process(endpoint, producer, copy, ct).ConfigureAwait(false);
if (copy.Exception != null && _stopOnException)
{
exchange.Exception = copy.Exception;
return;
}
if (_aggregationStrategy != null)
aggregated = aggregated is null ? copy : _aggregationStrategy(aggregated, copy);
}
catch when (_stopOnException)
{
throw;
}
catch (Exception ex)
{
copy.Exception = ex;
if (_aggregationStrategy != null)
aggregated = aggregated is null ? copy : _aggregationStrategy(aggregated, copy);
}
}
if (aggregated != null && _aggregationStrategy != null)
{
exchange.In.Body = aggregated.In.Body;
foreach (var header in aggregated.In.Headers)
exchange.In.Headers[header.Key] = header.Value;
}
}
finally
{
foreach (var copy in copies)
if (copy is IAsyncDisposable d) await d.DisposeAsync().ConfigureAwait(false);
}
}
private async Task ProcessParallel(IExchange exchange, List uris, CancellationToken ct)
{
var copies = new List(uris.Count);
try
{
var tasks = uris.Select(async uri =>
{
var copy = exchange.CorrelatedCopy();
lock (copies) copies.Add(copy);
var (endpoint, producer) = GetOrCreateProducer(uri);
copy.Properties[ExchangePropertyKeys.RecipientListEndpoint] = uri;
try
{
// Concurrent branches never share one Transaction.Current: each runs under a dependent clone of the
// route's transaction, as a parallel Multicast or Split does (see DependentTransactionBranch).
await Transactions.DependentTransactionBranch.RunAsync(
() => Core.CountedSend.Process(endpoint, producer, copy, ct)).ConfigureAwait(false);
}
finally
{
// Release DI scopes early; body/headers stay alive for aggregation
await copy.ReleaseScopes().ConfigureAwait(false);
}
return copy;
}).ToList();
IExchange[] results;
if (_stopOnException)
{
results = await Task.WhenAll(tasks).ConfigureAwait(false);
}
else
{
var settled = await Task.WhenAll(tasks.Select(async t =>
{
try { return await t.ConfigureAwait(false); }
catch (Exception ex)
{
var errExchange = exchange.CorrelatedCopy();
lock (copies) copies.Add(errExchange);
errExchange.Exception = ex;
await errExchange.ReleaseScopes().ConfigureAwait(false);
return errExchange;
}
})).ConfigureAwait(false);
results = settled.Where(r => r != null).ToArray();
}
if (_aggregationStrategy != null && results.Length > 0)
{
var aggregated = results[0];
for (int i = 1; i < results.Length; i++)
aggregated = _aggregationStrategy(aggregated, results[i]);
exchange.In.Body = aggregated.In.Body;
foreach (var header in aggregated.In.Headers)
exchange.In.Headers[header.Key] = header.Value;
}
}
finally
{
foreach (var copy in copies)
if (copy is IAsyncDisposable d) await d.DisposeAsync().ConfigureAwait(false);
}
}
private (IEndpoint Endpoint, IProducer Producer) GetOrCreateProducer(string uri)
{
lock (_cacheLock)
{
if (_producerCache.TryGetValue(uri, out var cached))
return cached;
var endpoint = _context.GetEndpoint(uri);
var producer = endpoint.CreateProducerOnItsSide();
_producerCache[uri] = (endpoint, producer);
return (endpoint, producer);
}
}
/// Stops all cached producers.
public async ValueTask DisposeAsync()
{
KeyValuePair[] snapshot;
lock (_cacheLock)
{
snapshot = _producerCache.ToArray();
_producerCache.Clear();
}
foreach (var kvp in snapshot)
{
try
{
await kvp.Value.Producer.Stop().ConfigureAwait(false);
}
catch
{
// Best-effort cleanup during disposal
}
}
}
}