Path: redb-route/redb.Route/Processors/StreamingSplitterProcessor.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/StreamingSplitterProcessor.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Telemetry;
namespace redb.Route.Processors;
///
/// Splits a single exchange into multiple exchanges using an async enumerable (streaming).
/// Each part is processed one at a time without buffering the entire collection.
/// No parallel mode or aggregation — streaming and buffering are opposing strategies.
///
internal sealed class StreamingSplitterProcessor : IProcessor
{
private readonly Func> _splitter;
private readonly IProcessor _target;
private readonly bool _stopOnException;
/// Creates a streaming splitter processor.
/// Function that produces an async enumerable of body parts.
/// Processor to handle each split exchange.
/// Whether to stop on the first exception.
internal StreamingSplitterProcessor(
Func> splitter,
IProcessor target,
bool stopOnException = true)
{
ArgumentNullException.ThrowIfNull(splitter);
ArgumentNullException.ThrowIfNull(target);
_splitter = splitter;
_target = target;
_stopOnException = stopOnException;
}
///
public async Task Process(IExchange exchange, CancellationToken ct = default)
{
var index = 0;
Exception? firstException = null;
// One part is read ahead: whether a part is the last one (CamelSplitComplete) is known only once the next
// read finds nothing, as Camel's streaming split asks its iterator.
await using var parts = _splitter(exchange).WithCancellation(ct).ConfigureAwait(false).GetAsyncEnumerator();
var hasPart = await parts.MoveNextAsync();
while (hasPart)
{
if (exchange.IsStopped) break;
var part = parts.Current;
hasPart = await parts.MoveNextAsync();
var complete = !hasPart;
var splitExchange = SplitterProcessor.CreateSplitExchange(
exchange, part, index, complete ? index + 1 : null, complete, linked: true);
try
{
await _target.Process(splitExchange, ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
firstException ??= ex;
if (_stopOnException)
{
exchange.Exception = ex;
break;
}
}
finally
{
if (splitExchange is IAsyncDisposable d)
await d.DisposeAsync().ConfigureAwait(false);
}
index++;
}
exchange.Properties[ExchangePropertyKeys.SplitSize] = index;
ProcessorMetrics.SplitterParts.Add(index);
if (firstException != null && _stopOnException)
throw firstException;
}
}