Path: redb-route/redb.Route/Processors/DetachedExecutor.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/DetachedExecutor.cs
----
using System.Collections.Concurrent;
using System.Diagnostics;
using Microsoft.Extensions.Logging;
using redb.Route.Configuration;
using redb.Route.Core;
using redb.Route.Telemetry;
namespace redb.Route.Processors;
///
/// The bounded pool of one detached step (a WireTap, an asynchronous OnCompletion), built from a
/// : at most branches run, at most
/// wait, and a branch that finds both full is handled by the profile's
/// rejected policy. Each step has a pool of its own, as each Camel EIP gets its own executor from the profile.
///
internal sealed class DetachedExecutor
{
private readonly ThreadPoolProfile _profile;
private readonly ILogger? _logger;
private readonly TagList _tags;
private readonly string _description;
private readonly ConcurrentQueue> _queue = new();
private int _active;
private int _queued;
private long _rejected;
private long _callerRuns;
/// The profile's name for metrics and logs: default or the executorService name.
/// The bounds.
/// The step for metrics and logs: wireTap, onCompletion.
/// The route the step is in, when known.
/// Logs a rejected branch and what shutdown left.
public DetachedExecutor(string profileName, ThreadPoolProfile profile, string step, string? routeId, ILogger? logger)
{
_profile = profile;
_logger = logger;
_tags = new TagList { { "profile", profileName }, { "step", step }, { "route", routeId ?? "(unknown)" } };
_description = $"{step} on route '{routeId ?? "(unknown)"}' (thread pool profile '{profileName}': {profile})";
}
/// Branches running now.
internal int Active => Volatile.Read(ref _active);
/// Branches waiting now.
internal int Queued => Volatile.Read(ref _queued);
/// Branches dropped or refused so far.
internal long Rejected => Interlocked.Read(ref _rejected);
/// Branches the caller ran itself so far.
internal long CallerRuns => Interlocked.Read(ref _callerRuns);
///
/// Runs on the pool. Returns once it is handed to the pool or queued, or, when both are
/// full, once the caller ran it (CallerRuns). Returns false when the branch was dropped (Discard); throws
/// when it was refused (Abort). The branch handles its own failures; one
/// that escapes is counted.
///
public async ValueTask Execute(Func branch)
{
if (TryTakeSlot())
{
Start(branch);
return true;
}
if (Interlocked.Increment(ref _queued) <= _profile.MaxQueueSize)
{
_queue.Enqueue(branch);
ProcessorMetrics.PoolQueued.Add(1, _tags);
// A runner that found the queue empty a moment ago may have left: take its slot for what waits.
if (TryTakeSlot())
{
if (TryDequeue() is { } next)
Start(next);
else
ReleaseSlot();
}
return true;
}
Interlocked.Decrement(ref _queued);
switch (_profile.RejectedPolicy)
{
case ThreadPoolRejectedPolicy.CallerRuns:
Interlocked.Increment(ref _callerRuns);
ProcessorMetrics.PoolCallerRuns.Add(1, _tags);
await RunOne(branch).ConfigureAwait(false);
return true;
case ThreadPoolRejectedPolicy.Discard:
Interlocked.Increment(ref _rejected);
ProcessorMetrics.PoolRejected.Add(1, _tags);
_logger?.LogWarning("A branch of {Step} was dropped: its pool and queue are full.", _description);
return false;
default:
Interlocked.Increment(ref _rejected);
ProcessorMetrics.PoolRejected.Add(1, _tags);
throw new RejectedExecutionException($"A branch of {_description} was refused: its pool and queue are full.");
}
}
///
/// Waits until no branch runs or waits, or until ends the wait; what is left then is counted
/// and logged with its number. Branches keep running after that; they are not cancelled.
///
public async Task DrainAsync(CancellationToken ct)
{
try
{
while (Active > 0 || Queued > 0)
await Task.Delay(20, ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
var left = Active + Queued;
if (left > 0)
{
ProcessorMetrics.PoolNotDrained.Add(left, _tags);
_logger?.LogWarning(
"{Count} branch(es) of {Step} were still running or waiting when the shutdown timeout ran out " +
"({Active} running, {Queued} waiting).", left, _description, Active, Queued);
}
}
}
private bool TryTakeSlot()
{
while (true)
{
var active = Volatile.Read(ref _active);
if (active >= _profile.MaxConcurrency)
return false;
if (Interlocked.CompareExchange(ref _active, active + 1, active) == active)
{
ProcessorMetrics.PoolActive.Add(1, _tags);
return true;
}
}
}
private void ReleaseSlot()
{
Interlocked.Decrement(ref _active);
ProcessorMetrics.PoolActive.Add(-1, _tags);
}
private Func? TryDequeue()
{
if (!_queue.TryDequeue(out var branch))
return null;
Interlocked.Decrement(ref _queued);
ProcessorMetrics.PoolQueued.Add(-1, _tags);
return branch;
}
/// Starts a runner on a slot already taken: it runs the branch, then what waits, then gives the slot back.
private void Start(Func first) => _ = Task.Run(async () =>
{
var next = first;
while (true)
{
while (next is not null)
{
await RunOne(next).ConfigureAwait(false);
next = TryDequeue();
}
ReleaseSlot();
// A branch queued between the last empty look and the release would wait for the next Execute: take it.
if (_queue.IsEmpty || !TryTakeSlot())
return;
next = TryDequeue();
if (next is null)
{
ReleaseSlot();
return;
}
}
});
private async Task RunOne(Func branch)
{
try
{
await branch().ConfigureAwait(false);
}
catch (Exception ex)
{
ProcessorMetrics.PoolFailed.Add(1, _tags);
_logger?.LogWarning(ex, "A branch of {Step} failed.", _description);
}
}
}