Path: redb-route/redb.Route/Processors/ThreadsProcessor.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/ThreadsProcessor.cs
----
using System.Threading.Channels;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Transactions;
namespace redb.Route.Processors;
///
/// Threads EIP — Camel-style concurrency stage. Hands each incoming exchange to a bounded pool
/// of poolSize persistent workers that run the child pipeline (the body), capping the
/// section's concurrency at poolSize.
///
/// Adaptive by exchange pattern (one API, transparent the way Camel's threads() is):
///
/// - InOnly — fire-and-forget hand-off: the caller returns as soon as the exchange is
/// accepted, so a strictly serial polling consumer (file / sql / imap / …) can dispatch the next
/// item while the pool processes the current one — up to poolSize in parallel. This is the
/// general-purpose alternative to .To("seda://x").ConcurrentConsumers(N), without a named
/// endpoint. The exchange is cloned (own DI scope), enqueued to the worker pool, and the
/// worker (started under — a transaction boundary,
/// like .To("seda://")) owns and disposes the clone.
/// - InOut — request/reply: the body runs inline on the SAME exchange under a
/// gate (≤ poolSize concurrent; the rest wait for a permit).
/// Nothing is cloned or copied, so In / Out / headers / properties and the reply are
/// preserved exactly — lossless regardless of whether the route writes its response to
/// Out or to In (redb.Route's HTTP consumer falls back to In when Out is
/// unset). This is not a transaction boundary — the ambient TransactionScope flows into
/// the body, which is correct for request/reply (the caller awaits the result anyway). Exceptions
/// propagate up to the route's outer OnException wrapper exactly as an un-threaded inline route, so
/// error handling / Handled() is unchanged.
///
///
///
/// Backpressure: InOnly waits on the bounded hand-off queue; InOut waits on the gate. Both honour
/// — bound the wait for a free slot instead of waiting indefinitely
/// (on timeout, ; for InOut that surfaces to the awaiting caller).
///
///
/// Drain-on-stop: the processor registers itself as an ;
/// on context stop it stops accepting, completes the queue, awaits the workers (bounded by
/// ) and force-cancels only if that window is exceeded. A straggler exchange
/// that arrives after the queue is completed is run inline so it is never dropped.
///
/// Ordering is not preserved when poolSize > 1 (documented, same as brokers).
///
public sealed class ThreadsProcessor : IProcessor, IRouteLifecycleListener
{
private readonly IProcessor _body; // InOut: inline, inside the route's error handlers
private readonly IProcessor _detachedBody; // InOnly workers: wrapped by the route's error scope
private readonly int _poolSize;
private readonly IRouteContext _context;
private readonly ILogger? _logger;
private readonly Channel _queue; // InOnly hand-off queue (worker pool)
private readonly SemaphoreSlim _gate; // InOut concurrency gate (inline, capped at poolSize)
private readonly CancellationTokenSource _workerCts = new();
private Task[]? _workers;
private int _started;
private volatile bool _shuttingDown;
private long _processedCount;
/// Graceful-drain window on stop before workers are force-cancelled (default 30s).
public TimeSpan DrainTimeout { get; init; } = TimeSpan.FromSeconds(30);
///
/// Optional cap on how long a caller waits for a free worker slot when the pool + queue are
/// saturated. null (default) = wait indefinitely (backpressure). When set and the window
/// elapses, the enqueue fails with — surfaced to the caller
/// (for InOut/RPC that becomes the reply fault instead of an unbounded hang).
///
public TimeSpan? EnqueueTimeout { get; init; }
/// Total number of exchanges processed across all workers.
public long ProcessedCount => Interlocked.Read(ref _processedCount);
/// Number of concurrent workers (the effective max degree of parallelism).
public int PoolSize => _poolSize;
/// Creates a Threads processor.
/// Compiled child pipeline run by each worker.
/// Number of concurrent workers (must be >= 1).
/// Bounded hand-off queue capacity (backpressure). 0 = default (== poolSize).
/// Route context (used for error routing + lifecycle/drain registration).
/// Optional logger.
public ThreadsProcessor(IProcessor body, int poolSize, int maxQueueSize, IRouteContext context, ILogger? logger = null)
: this(body, body, poolSize, maxQueueSize, context, logger)
{
}
///
/// Creates a Threads processor whose in-only workers run — the body wrapped by the
/// route's error scope, since a worker runs after the caller and its error handlers have returned.
///
internal ThreadsProcessor(IProcessor body, IProcessor detachedBody, int poolSize, int maxQueueSize, IRouteContext context,
ILogger? logger)
{
_body = body ?? throw new ArgumentNullException(nameof(body));
_detachedBody = detachedBody ?? throw new ArgumentNullException(nameof(detachedBody));
if (poolSize < 1)
throw new ArgumentOutOfRangeException(nameof(poolSize), poolSize, "poolSize must be at least 1.");
if (maxQueueSize < 0)
throw new ArgumentOutOfRangeException(nameof(maxQueueSize), maxQueueSize, "maxQueueSize cannot be negative.");
_poolSize = poolSize;
_context = context ?? throw new ArgumentNullException(nameof(context));
_logger = logger;
var capacity = maxQueueSize > 0 ? maxQueueSize : poolSize;
_queue = Channel.CreateBounded(new BoundedChannelOptions(capacity)
{
// Backpressure: when the pool + queue are saturated the producer (the caller's Process)
// asynchronously waits, throttling a fast poll loop to the pool's capacity.
FullMode = BoundedChannelFullMode.Wait,
SingleReader = false,
SingleWriter = false
});
// InOut path runs the body inline under this gate — at most poolSize bodies concurrently.
_gate = new SemaphoreSlim(poolSize, poolSize);
_context.AddLifecycleListener(this);
}
///
public async Task Process(IExchange exchange, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(exchange);
// Adaptive by exchange pattern, so .Threads() is transparent the way Camel's threads() is —
// one API, no separate primitive:
// • InOut → request/reply. Runs the body INLINE on the SAME exchange under a semaphore gate:
// at most poolSize bodies at once, the rest wait for a permit. Nothing is cloned or
// copied, so In / Out / headers / properties / the reply are preserved exactly
// (lossless regardless of whether the route writes its response to Out or In). This
// is NOT a transaction boundary — the ambient TransactionScope flows into the body,
// which is correct for request/reply (the caller awaits the result anyway). Errors
// propagate up the pipeline to the outer OnException wrapper, exactly as without
// .Threads(), so RPC error handling is unchanged.
// • InOnly → fire-and-forget hand-off: clone (own DI scope), enqueue and return so a serial
// polling consumer keeps pumping up to poolSize exchanges concurrently. The worker
// runs the body under ExecutionContext.SuppressFlow (a transaction boundary, like
// .To("seda://")) and owns + disposes the clone.
if (exchange.Pattern == ExchangePattern.InOut)
await ProcessInOut(exchange, ct).ConfigureAwait(false);
else
await ProcessInOnly(exchange, ct).ConfigureAwait(false);
}
private async Task ProcessInOut(IExchange exchange, CancellationToken ct)
{
// Concurrency gate: acquire a permit (≤ poolSize in flight), run the body inline on the SAME
// exchange, release. No clone / no copy-back → the reply is whatever the body produced, in place.
if (!await AcquireAsync(ct).ConfigureAwait(false))
throw new TimeoutException(
$"Threads gate: no free slot within {EnqueueTimeout} (poolSize={_poolSize}).");
try
{
// Exceptions propagate up to the route's outer OnException wrapper (see RouteContext) — the
// same path as an un-threaded inline route, so error handling / Handled() is unchanged.
await _body.Process(exchange, ct).ConfigureAwait(false);
}
finally
{
Interlocked.Increment(ref _processedCount);
_gate.Release();
}
}
private async Task ProcessInOnly(IExchange exchange, CancellationToken ct)
{
EnsureStarted();
// Clone (own DI scope, owned by the worker) and enqueue; the caller returns immediately and its
// poll loop can dispatch the next exchange. The bounded queue applies backpressure at capacity.
var copy = exchange.Clone();
// The worker is a transaction boundary: the copy must not see the sending .Transacted() block as its own.
TransactedActions.DetachFromBlock(copy);
// The caller is done with its exchange as soon as this returns, the worker is not: the copy owns the bodies from
// here, or the caller's disposal would close a stream the worker still reads.
var original = exchange as Core.Exchange;
var successor = copy as Core.Exchange;
if (original is not null && successor is not null)
original.HandOverBodiesTo(successor);
if (_shuttingDown)
{
// Queue is being torn down — do not lose this straggler; run it inline on the caller.
await RunBody(copy, ct).ConfigureAwait(false);
return;
}
try
{
await EnqueueAsync(copy, ct).ConfigureAwait(false);
}
catch (ChannelClosedException)
{
// Raced with shutdown between the _shuttingDown check and the write — run inline, don't drop.
// RunBody's finally disposes the copy (releasing its per-exchange DI scope / DB connection).
await RunBody(copy, ct).ConfigureAwait(false);
}
catch
{
// Enqueue failed (cancellation under backpressure / EnqueueTimeout) and the copy was neither
// enqueued nor run inline — dispose it here so its per-exchange DI scope / DB connection is
// released, then rethrow so the caller still observes the cancellation/fault. The bodies go back to the
// caller's exchange first: the caller still has it.
if (original is not null && successor is not null)
successor.HandOverBodiesTo(original);
await copy.DisposeAsync().ConfigureAwait(false);
throw;
}
}
private async Task EnqueueAsync(IExchange item, CancellationToken ct)
{
if (EnqueueTimeout is not { } timeout)
{
await _queue.Writer.WriteAsync(item, ct).ConfigureAwait(false);
return;
}
using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeoutCts.CancelAfter(timeout);
try
{
await _queue.Writer.WriteAsync(item, timeoutCts.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (timeoutCts.IsCancellationRequested && !ct.IsCancellationRequested)
{
throw new TimeoutException(
$"Threads pool: no free worker slot within {timeout} (poolSize={_poolSize}, queue saturated).");
}
}
private async Task AcquireAsync(CancellationToken ct)
{
if (EnqueueTimeout is not { } timeout)
{
await _gate.WaitAsync(ct).ConfigureAwait(false);
return true;
}
// Returns false on timeout (throws only on cancellation) — the caller maps false to TimeoutException.
return await _gate.WaitAsync(timeout, ct).ConfigureAwait(false);
}
private void EnsureStarted()
{
if (Interlocked.CompareExchange(ref _started, 1, 0) != 0) return;
_workers = new Task[_poolSize];
// Suppress ExecutionContext flow so the persistent workers never capture the first caller's
// ambient TransactionScope / AsyncLocal state — .Threads() is a clean async boundary.
using (ExecutionContext.SuppressFlow())
{
for (var i = 0; i < _poolSize; i++)
_workers[i] = Task.Run(() => WorkerLoop(_workerCts.Token));
}
}
private async Task WorkerLoop(CancellationToken ct)
{
try
{
await foreach (var exchange in _queue.Reader.ReadAllAsync(ct).ConfigureAwait(false))
await RunBody(exchange, ct).ConfigureAwait(false);
}
catch (OperationCanceledException) { }
catch (ChannelClosedException) { }
}
private async Task RunBody(IExchange exchange, CancellationToken ct)
{
try
{
await _detachedBody.Process(exchange, ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// Shutting down / cancelled — not a business error, do not route to OnException.
}
catch (Exception ex) when (!ReferenceEquals(_detachedBody, _body))
{
// The route's whole error scope has run around the body (its OnException, its builder's, the context's
// handlers) and none took the failure: it ends here, with nobody left to give it to.
exchange.Exception = ex;
_logger?.LogError(ex, "Threads pool: exchange {ExchangeId} failed and no error handler took it.",
exchange.ExchangeId);
}
catch (Exception ex)
{
// Built outside a route compiler, with no error scope around the body: the context's handlers, explicitly.
exchange.Exception = ex;
try
{
await _context.HandleException(exchange, ex, ct).ConfigureAwait(false);
}
catch (Exception handlerEx)
{
_logger?.LogError(handlerEx,
"Threads pool: exception handler failed for exchange {ExchangeId}.", exchange.ExchangeId);
}
}
finally
{
Interlocked.Increment(ref _processedCount);
await exchange.DisposeAsync().ConfigureAwait(false);
}
}
// ── IRouteLifecycleListener — graceful drain on stop ─────────────────────────
///
public async Task OnContextStopping(IRouteContext context, CancellationToken ct)
{
if (Volatile.Read(ref _started) == 0) return; // never processed anything
_shuttingDown = true;
_queue.Writer.TryComplete(); // stop accepting; workers finish the backlog then exit their loop
var workers = _workers;
if (workers == null) return;
var all = Task.WhenAll(workers);
using var drainCts = new CancellationTokenSource();
var timer = Task.Delay(DrainTimeout, drainCts.Token);
if (await Task.WhenAny(all, timer).ConfigureAwait(false) == all)
{
drainCts.Cancel(); // drained in time — cancel the timer
}
else
{
_logger?.LogWarning(
"Threads pool drain exceeded {Timeout}; force-cancelling {N} worker(s).", DrainTimeout, _poolSize);
await _workerCts.CancelAsync().ConfigureAwait(false);
try { await all.ConfigureAwait(false); } catch { /* observed on shutdown */ }
}
_workerCts.Dispose();
}
}