Path: redb-route/redb.Route/Processors/WireTapProcessor.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/WireTapProcessor.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; using redb.Route.Telemetry; using redb.Route.Transactions; namespace redb.Route.Processors; /// /// Sends a fire-and-forget clone of the exchange to a tap processor. /// The main exchange continues through the pipeline unchanged. /// Supports an optional onPrepare callback to modify the clone before tapping /// and an optional body replacement for the tapped exchange. /// Errors in the tap are logged (if logger available) but never propagated /// to the main pipeline — this is by-design for fire-and-forget semantics. /// public class WireTapProcessor : IProcessor, IAsyncDisposable, IStopAwareProcessor { private readonly IProcessor _tap; private readonly Action? _onPrepare; private readonly Func? _newBodyFactory; private readonly ILogger? _logger; private readonly DetachedExecutor _executor; /// Creates a wire-tap that sends clones to the specified processor. /// The processor to receive exchange clones. /// Optional callback to modify the cloned exchange before tapping. /// Optional factory to replace the body on the tapped clone. /// Optional logger for tap errors. /// The bounds of the tap's own pool; the default profile when null. /// The profile's name for metrics and logs. /// The route the tap is in, for metrics and logs. public WireTapProcessor( IProcessor tap, Action? onPrepare = null, Func? newBodyFactory = null, ILogger? logger = null, ThreadPoolProfile? profile = null, string? profileName = null, string? routeId = null) { _tap = tap ?? throw new ArgumentNullException(nameof(tap)); _onPrepare = onPrepare; _newBodyFactory = newBodyFactory; _logger = logger; _executor = new DetachedExecutor(profileName ?? "default", profile ?? new ThreadPoolProfile(), "wireTap", routeId, logger); } /// The tap's pool, for tests. internal DetachedExecutor Executor => _executor; /// public async Task Process(IExchange exchange, CancellationToken ct = default) { // As Camel's WireTapProcessor.configureCopyExchange: a correlated copy (an id of its own), and then no // correlation id at all, since a tap is fire-and-forget and not a part of the exchange it copies. var clone = exchange.CorrelatedCopy(); clone.Properties.Remove(ExchangePropertyKeys.CorrelationId); // Ownership of the clone transfers to the tap task once it is dispatched; until then this // method owns it. If preparation (user onPrepare / newBodyFactory) throws before dispatch, // the finally below disposes the clone so its per-exchange DI scope / DB connection is // released — otherwise a throwing callback would strand the clone's scope (a connection leak). var dispatched = false; try { if (_newBodyFactory != null) clone.In.Body = _newBodyFactory(exchange); _onPrepare?.Invoke(clone); // The detached branch must NOT share the originating transaction's deferred transport // actions. TransactedProcessor owns that dictionary (Properties["TRANSACT_ACTION"]) and // commits/rolls it back; Exchange.Clone() copies Properties shallowly, so the tap clone // would otherwise hold the SAME ConcurrentDictionary and could race the main commit. The // tap runs with the ambient transaction suppressed (see DetachedDispatch.Enter), so it has // no part in that set. clone.Properties.Remove(TransactedProcessor.TransactActionPropertyKey); // Capture ambient trace + transaction state on the ORIGINATING thread, before dispatch. var origin = DetachedDispatch.Capture(); // The branch runs on the step's bounded pool; the caller does not wait for it, unless the pool and its // queue are full and the profile has the caller run it. Either way it runs in a detached frame: the // caller's transaction suppressed, the trace re-rooted. The branch must NOT inherit the caller's // CancellationToken — cancelling the main pipeline (an aborted HTTP request) would kill an in-flight // audit mid-write. WireTap semantics per EIP are "InOnly, detached". var routeId = exchange.RouteId ?? "(no-route)"; dispatched = await _executor.Execute(async () => { using var frame = DetachedDispatch.Enter(origin, "redb.route.wiretap"); try { await _tap.Process(clone, CancellationToken.None).ConfigureAwait(false); ProcessorMetrics.WireTapDispatched.Add(1); } catch (OperationCanceledException) { /* expected on host shutdown */ } catch (Exception ex) { ProcessorMetrics.WireTapFailed.Add(1); _logger?.LogWarning(ex, "WireTap processor failed for route '{RouteId}'. Error is non-fatal and will not affect the main pipeline.", routeId); } finally { if (clone is IAsyncDisposable d) await d.DisposeAsync().ConfigureAwait(false); } }).ConfigureAwait(false); } finally { // Not handed over: preparation threw, or the profile dropped (Discard) or refused (Abort) the branch. if (!dispatched && clone is IAsyncDisposable d) await d.DisposeAsync().ConfigureAwait(false); } } /// Task IStopAwareProcessor.OnConsumersStoppedAsync(CancellationToken ct) => _executor.DrainAsync(ct); /// public ValueTask DisposeAsync() => ValueTask.CompletedTask; }