Path: redb-route/redb.Route/Processors/LoopProcessor.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/LoopProcessor.cs
----
using redb.Route.Abstractions;
namespace redb.Route.Processors;
///
/// Repeats processing either a fixed number of times or until a predicate returns false.
/// Supports both count-based and predicate-based looping with optional exchange copy per iteration.
///
public class LoopProcessor : IProcessor
{
private readonly IProcessor _body;
private readonly int? _maxIterations;
private readonly IPredicate? _whileCondition;
private readonly Func? _countFactory;
private readonly bool _copy;
private readonly bool _shareScope;
/// Creates a count-based loop processor.
/// Processor to execute on each iteration.
/// Maximum number of iterations.
/// If true, each iteration receives a clone of the original exchange.
/// If true (default), copy-mode iterations share the parent's DI scope (same DB connection, same TX). If false, each iteration gets its own scope.
public LoopProcessor(IProcessor body, int maxIterations, bool copy = false, bool shareScope = true)
{
_body = body ?? throw new ArgumentNullException(nameof(body));
if (maxIterations < 0)
throw new ArgumentOutOfRangeException(nameof(maxIterations), "Must be non-negative.");
_maxIterations = maxIterations;
_copy = copy;
_shareScope = shareScope;
}
/// Creates a predicate-based loop processor.
/// Processor to execute on each iteration.
/// Predicate evaluated before each iteration; loop continues while true.
/// If true, each iteration receives a clone of the original exchange.
/// If true (default), copy-mode iterations share the parent's DI scope (same DB connection, same TX). If false, each iteration gets its own scope.
public LoopProcessor(IProcessor body, Func whileCondition, bool copy = false, bool shareScope = true)
: this(body, new Predicates.LambdaPredicate(whileCondition ?? throw new ArgumentNullException(nameof(whileCondition))), copy, shareScope)
{
}
/// Creates a predicate-based loop processor whose condition is awaited before each iteration.
/// Processor to execute on each iteration.
/// Condition evaluated before each iteration; the loop continues while it holds.
/// If true, each iteration receives a clone of the original exchange.
/// If true (default), copy-mode iterations share the parent's DI scope.
public LoopProcessor(IProcessor body, IPredicate whileCondition, bool copy = false, bool shareScope = true)
{
_body = body ?? throw new ArgumentNullException(nameof(body));
_whileCondition = whileCondition ?? throw new ArgumentNullException(nameof(whileCondition));
_copy = copy;
_shareScope = shareScope;
}
/// Creates a dynamic count-based loop processor where count is resolved from the exchange at runtime.
/// Processor to execute on each iteration.
/// Function that resolves the loop count from the exchange.
/// If true, each iteration receives a clone of the original exchange.
/// If true (default), copy-mode iterations share the parent's DI scope (same DB connection, same TX). If false, each iteration gets its own scope.
public LoopProcessor(IProcessor body, Func countFactory, bool copy = false, bool shareScope = true)
{
_body = body ?? throw new ArgumentNullException(nameof(body));
_countFactory = countFactory ?? throw new ArgumentNullException(nameof(countFactory));
_copy = copy;
_shareScope = shareScope;
}
///
public async Task Process(IExchange exchange, CancellationToken ct = default)
{
// Snapshot: shares parent scope by default so iterations participate in parent TX.
var snapshot = _copy
? (_shareScope ? exchange.CloneLinked() : exchange.Clone())
: null;
try
{
if (_maxIterations.HasValue)
{
for (var i = 0; i < _maxIterations.Value; i++)
{
ct.ThrowIfCancellationRequested();
if (exchange.IsStopped) break;
await ProcessIteration(exchange, snapshot, i, _maxIterations.Value, ct).ConfigureAwait(false);
}
}
else if (_countFactory is not null)
{
var count = _countFactory(exchange);
for (var i = 0; i < count; i++)
{
ct.ThrowIfCancellationRequested();
if (exchange.IsStopped) break;
await ProcessIteration(exchange, snapshot, i, count, ct).ConfigureAwait(false);
}
}
else
{
var index = 0;
while (await _whileCondition!.MatchesAsync(exchange).ConfigureAwait(false))
{
ct.ThrowIfCancellationRequested();
if (exchange.IsStopped) break;
await ProcessIteration(exchange, snapshot, index++, null, ct).ConfigureAwait(false);
}
}
}
finally
{
if (snapshot is IAsyncDisposable d)
await d.DisposeAsync().ConfigureAwait(false);
}
}
///
/// Runs one iteration. Its index, and the iteration count of a counted loop, are exchange properties of the
/// exchange the iteration runs on, as Camel's CamelLoopIndex and CamelLoopSize.
///
private async Task ProcessIteration(IExchange exchange, IExchange? snapshot, int index, int? size, CancellationToken ct)
{
if (!_copy)
{
MarkIteration(exchange, index, size);
await _body.Process(exchange, ct).ConfigureAwait(false);
return;
}
var target = _shareScope ? snapshot!.CloneLinked() : snapshot!.Clone();
MarkIteration(target, index, size);
try
{
await _body.Process(target, ct).ConfigureAwait(false);
MergeBack(exchange, target);
}
finally
{
if (target is IAsyncDisposable d)
await d.DisposeAsync().ConfigureAwait(false);
}
}
private static void MarkIteration(IExchange exchange, int index, int? size)
{
exchange.Properties[ExchangePropertyKeys.LoopIndex] = index;
if (size is { } count)
exchange.Properties[ExchangePropertyKeys.LoopSize] = count;
}
/// Merges iteration results back into the original exchange (headers, properties, exception state).
private static void MergeBack(IExchange original, IExchange iteration)
{
original.In.Body = iteration.In.Body;
foreach (var h in iteration.In.Headers)
original.In.Headers[h.Key] = h.Value;
foreach (var p in iteration.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.
if (ExchangeResources.IsOwnedByExchange(p.Key))
continue;
original.Properties[p.Key] = p.Value;
}
if (iteration.Exception != null)
original.Exception = iteration.Exception;
}
}