Path: redb-route/redb.Route/Processors/OnCompletionProcessor.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/OnCompletionProcessor.cs
----
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Definitions;
using redb.Route.Telemetry;
using redb.Route.Transactions;
namespace redb.Route.Processors;
/// One compiled OnCompletion block.
/// The block's own pool (parallelProcessing / executorService); null runs it in the caller.
internal sealed record CompletionHandler(
IProcessor Body, CompletionMode Mode, IPredicate? Condition, bool BeforeConsumer, DetachedExecutor? Pool);
///
/// Runs OnCompletion blocks after the route finished with an exchange — on a copy, outside the
/// route's error handlers and transaction, never changing the route's outcome. Placement in the route
/// wrapper stack is outside every error handler, and "failure" is the consumer's verdict: an exception
/// escaping the route, a failure left unhandled on the exchange, or a rollback-only mark; a handled
/// error is a completion. As in Camel, a block runs in the caller (who waits for it) unless it has a pool
/// of its own; a block after the consumer runs detached from the caller's transaction and token. A failing
/// block is logged and counted, never thrown.
///
internal sealed class OnCompletionProcessor : IProcessor, IAsyncDisposable, IStopAwareProcessor
{
private readonly IProcessor _route;
private readonly IReadOnlyList _handlers;
private readonly string _routeId;
private readonly ILogger? _logger;
public OnCompletionProcessor(IProcessor route, IReadOnlyList handlers, string routeId, ILogger? logger)
{
_route = route ?? throw new ArgumentNullException(nameof(route));
_handlers = handlers ?? throw new ArgumentNullException(nameof(handlers));
_routeId = routeId;
_logger = logger;
}
public async Task Process(IExchange exchange, CancellationToken ct = default)
{
try
{
await _route.Process(exchange, ct).ConfigureAwait(false);
}
catch (Exception ex)
{
await RunHandlers(exchange, ex, ct).ConfigureAwait(false);
throw;
}
// A normal return is not always a completion: a failure left unhandled on the exchange (OnException without
// Handled) or a rollback-only mark (.RollbackAll()) is one the consumer does not acknowledge.
await RunHandlers(exchange, ExchangeFailureExtensions.FailureOf(exchange), ct).ConfigureAwait(false);
}
private async Task RunHandlers(IExchange exchange, Exception? failure, CancellationToken ct)
{
foreach (var handler in _handlers)
{
var applies = handler.Mode switch
{
CompletionMode.OnCompleteOnly => failure is null,
CompletionMode.OnFailureOnly => failure is not null,
_ => true,
};
if (!applies) continue;
// Nothing in here may change the route's own outcome: a copy that cannot be made or a
// condition that throws is the block's problem — logged and skipped, never the caller's.
IExchange? copy = null;
try
{
copy = exchange.CorrelatedCopy();
if (failure is not null) copy.Exception = failure;
// The copy runs outside the route's transaction and must not share its deferred
// transport actions (same reasoning as WireTap): the original commits or rolls them back.
copy.Properties.Remove(TransactedProcessor.TransactActionPropertyKey);
if (handler.Condition is not null && !await handler.Condition.MatchesAsync(copy).ConfigureAwait(false))
{
await Release(copy).ConfigureAwait(false);
continue;
}
}
catch (Exception ex)
{
_logger?.LogError(ex, "OnCompletion condition failed for route '{RouteId}'; the block is skipped", _routeId);
if (copy is not null) await Release(copy).ConfigureAwait(false);
continue;
}
if (handler.BeforeConsumer && handler.Pool is null)
{
await Execute(handler, copy, ct).ConfigureAwait(false);
continue;
}
// Detached, like WireTap: the caller's ambient transaction may still be open when the block
// starts and will complete underneath it, so it is suppressed in the block; telemetry is
// re-rooted as a span linked to the originating trace. The block never gets the caller's token:
// an aborted request does not cut an audit or a cleanup half way. Captured here, entered in the block.
var origin = DetachedDispatch.Capture();
var block = copy;
async Task Detached()
{
using var frame = DetachedDispatch.Enter(origin, "redb.route.oncompletion");
await Execute(handler, block, CancellationToken.None).ConfigureAwait(false);
}
if (handler.Pool is null)
{
// Camel's default: the caller runs the block once the route has finished, and waits for it.
await Detached().ConfigureAwait(false);
continue;
}
// parallelProcessing / executorService: the block's own bounded pool.
bool handedOver;
try
{
handedOver = await handler.Pool.Execute(Detached).ConfigureAwait(false);
}
catch (RejectedExecutionException ex)
{
// Abort under a full pool: the block did not run. It is the block's problem, never the route's.
_logger?.LogError(ex, "OnCompletion block refused for route '{RouteId}'", _routeId);
handedOver = false;
}
if (!handedOver)
await Release(block).ConfigureAwait(false);
}
}
///
async Task IStopAwareProcessor.OnConsumersStoppedAsync(CancellationToken ct)
{
foreach (var handler in _handlers)
if (handler.Pool is { } pool)
await pool.DrainAsync(ct).ConfigureAwait(false);
}
///
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
private async Task Execute(CompletionHandler handler, IExchange copy, CancellationToken ct)
{
try
{
await handler.Body.Process(copy, ct).ConfigureAwait(false);
}
catch (Exception ex)
{
ProcessorMetrics.OnCompletionFailed.Add(1, new KeyValuePair("route", _routeId));
_logger?.LogError(ex, "OnCompletion block failed for route '{RouteId}'", _routeId);
}
finally
{
await Release(copy).ConfigureAwait(false);
}
}
///
/// The copy shares its body with the live exchange (Message.Clone copies the reference), so
/// only the copy's DI scopes are released — never DisposeAsync, which would close the live
/// body under the consumer. Same teardown as the Multicast / Splitter branch clones.
///
private async ValueTask Release(IExchange copy)
{
try
{
if (copy is Exchange exchange) await exchange.ReleaseScopes().ConfigureAwait(false);
}
catch (Exception ex)
{
_logger?.LogError(ex, "OnCompletion copy release failed for route '{RouteId}'", _routeId);
}
}
}