Bundle: redb-route / redb.Route (redb.Route.2.txt), 95 files Snapshot: 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 Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt ==== Path: redb-route/redb.Route/Processors/IdempotentConsumerProcessor.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/IdempotentConsumerProcessor.cs ---- using System.Transactions; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.Processors; /// /// Idempotent consumer processor. Deduplicates exchanges based on a key extracted /// from the exchange. Duplicate exchanges are silently skipped. /// /// Usage: wrap the inner pipeline so that duplicate messages (by key) are not processed twice. /// The key extractor is a function from to string. /// Typical keys: message ID, correlation ID, or a business-specific unique identifier. /// /// public sealed class IdempotentConsumerProcessor : IProcessor { /// /// Well-known exchange property set on duplicates that were skipped. /// public const string DuplicatePropertyKey = ExchangePropertyKeys.DuplicateMessage; private readonly IProcessor _inner; private readonly IIdempotentRepository _repository; private readonly Func _keyExtractor; private readonly bool _skipDuplicate; private readonly ILogger? _logger; /// Creates an idempotent consumer processor. /// Inner processor to delegate to when the message is not a duplicate. /// Repository for tracking processed message keys. /// Function that extracts the unique key from an exchange. /// /// When true, duplicates are silently skipped (default). /// When false, duplicates propagate through the pipeline with CamelDuplicateMessage=true property set. /// /// Optional logger. public IdempotentConsumerProcessor( IProcessor inner, IIdempotentRepository repository, Func keyExtractor, bool skipDuplicate = true, ILogger? logger = null) { _inner = inner ?? throw new ArgumentNullException(nameof(inner)); _repository = repository ?? throw new ArgumentNullException(nameof(repository)); _keyExtractor = keyExtractor ?? throw new ArgumentNullException(nameof(keyExtractor)); _skipDuplicate = skipDuplicate; _logger = logger; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { var key = _keyExtractor(exchange); if (string.IsNullOrEmpty(key)) { _logger?.LogWarning("Idempotent consumer: key extractor returned null/empty. Processing without dedup."); await _inner.Process(exchange, ct).ConfigureAwait(false); return; } // A redelivery of the whole route (OnException) comes back here with the key this exchange claimed on the // previous attempt: it is not a duplicate of itself. var claim = ExchangeResources.FindCompletion(exchange, c => ReferenceEquals(c.Consumer, this) && c.Key == key); var isNew = await _repository.Add(key, ct).ConfigureAwait(false); if (!isNew && claim is { State: ClaimState.Done }) { // The block's work is done and a later step failed. Camel redelivers that step alone; skipping the block // is the same outcome: the work is not done twice. _logger?.LogDebug("Idempotent consumer: key {Key} was processed by this exchange already; the block is skipped on the redelivery.", key); return; } if (!isNew && claim is not { State: ClaimState.Failed }) { // Duplicate detected ProcessorMetrics.IdempotentDuplicate.Add(1); exchange.Properties[DuplicatePropertyKey] = true; _logger?.LogDebug("Duplicate message detected (key={Key}). Skipping.", key); if (_skipDuplicate) { // Tail-consuming wiring: this processor owns the route tail, // so duplicates are skipped simply by returning without invoking _inner. return; } // If not skipping, let it through with the duplicate flag await _inner.Process(exchange, ct).ConfigureAwait(false); return; } // The key is this exchange's: just added, or still held after the block failed on the previous attempt. if (claim is null) { claim = new KeyClaim(this, key); ExchangeResources.OnCompletion(exchange, claim); } if (isNew) claim.Bind(Transaction.Current); claim.State = ClaimState.Running; try { await _inner.Process(exchange, ct).ConfigureAwait(false); } catch { claim.State = ClaimState.Failed; throw; } if (exchange.EndedInFailure()) { claim.State = ClaimState.Failed; return; } claim.State = ClaimState.Done; // A key bound to a transaction is confirmed with the work; otherwise when the exchange completes. if (claim.FollowsTransaction) await _repository.Confirm(key, ct).ConfigureAwait(false); ProcessorMetrics.IdempotentPassed.Add(1); } private enum ClaimState { Running, Done, Failed } /// /// The key this exchange claimed, and what happens to it when the exchange's unit of work ends (Apache Camel's /// idempotent consumer with completionEager=false and removeOnFailure=true, the defaults). /// /// Claimed outside a transaction: the key is confirmed when the exchange completes and removed when it fails, /// wherever the failure happened (inside the block or after it), so the redelivery is processed again. A failure an /// error handler marked handled (OnException with Handled(true)) removes the key too: the handler /// answered the exchange, but the work it guarded did not happen. A failure caught by DoCatch proves nothing /// about the work, so it keeps the key. /// Claimed inside a transaction: the key follows the transaction, not the exchange. It commits with the work /// and stays even if the exchange fails later (a send after the database commit, say), so the redelivery does not /// redo committed work. It goes with a rollback: by itself for a repository that /// , removed by the consumer for one that does not. /// /// private sealed class KeyClaim : IExchangeCompletion { public KeyClaim(IdempotentConsumerProcessor consumer, string key) { Consumer = consumer; Key = key; } public IdempotentConsumerProcessor Consumer { get; } public string Key { get; } public ClaimState State { get; set; } public bool FollowsTransaction { get; private set; } public void Bind(Transaction? transaction) { FollowsTransaction = transaction is not null; if (transaction is not null && !Consumer._repository.JoinsAmbientTransaction) transaction.TransactionCompleted += RemoveUnlessCommitted; } public Task OnComplete(IExchange exchange, CancellationToken ct) { if (FollowsTransaction) return Task.CompletedTask; // Camel's IdempotentOnCompletion: onComplete checks ExchangeHelper.isFailureHandled and, when it is set, // removes the key (removeOnFailure) instead of confirming it. So a message whose failure an OnException // handler marked Handled(true) is reprocessed on its redelivery rather than skipped as a duplicate. A failure // caught by DoCatch is not marked handled, so its key stays confirmed. return exchange.IsFailureHandled() ? Consumer._repository.Remove(Key, ct) : Consumer._repository.Confirm(Key, ct); } public async Task OnFailure(IExchange exchange, CancellationToken ct) { if (FollowsTransaction) return; try { await Consumer._repository.Remove(Key, ct).ConfigureAwait(false); } catch (Exception ex) { throw new InvalidOperationException( $"Idempotent consumer: the exchange failed and removing its key '{Key}' failed too; until the key is " + "removed, the redelivery is skipped as a duplicate.", ex); } } /// /// The repository keeps its keys outside the transaction, so the rollback cannot take the key back: the work it /// guarded did not commit, and a key left behind would make the redelivery look like a duplicate. Runs while the /// transaction completes, before the route returns to the consumer. /// private void RemoveUnlessCommitted(object? sender, TransactionEventArgs e) { var status = e.Transaction?.TransactionInformation.Status; if (status == TransactionStatus.Committed) return; if (status != TransactionStatus.Aborted) { Consumer._logger?.LogError( "Idempotent consumer: the outcome of the transaction holding key '{Key}' is {Status}; the key is kept, " + "check whether the work committed.", Key, status); return; } // A synchronous event: the removal is waited for here, so it lands before the consumer hands the message back. // It runs outside the completed transaction, which a repository opening a connection must not try to join. try { using var noTransaction = new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled); Consumer._repository.Remove(Key, CancellationToken.None).GetAwaiter().GetResult(); } catch (Exception ex) { Consumer._logger?.LogError(ex, "Idempotent consumer: the transaction rolled back and removing key '{Key}' failed; until the key is " + "removed, the redelivery is skipped as a duplicate.", Key); } } } } Path: redb-route/redb.Route/Processors/InMemoryClaimCheckRepository.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/InMemoryClaimCheckRepository.cs ---- using System; using System.Collections.Concurrent; using System.Threading; using System.Threading.Tasks; using redb.Route.Abstractions; namespace redb.Route.Processors; /// /// In-memory implementation of . /// Suitable for single-process scenarios, testing, and push/pop stash patterns. /// Thread-safe via . /// public sealed class InMemoryClaimCheckRepository : IClaimCheckRepository { private readonly ConcurrentDictionary _store = new(StringComparer.Ordinal); private readonly TimeSpan _defaultTtl; /// /// Creates a new in-memory claim check repository. /// /// Default TTL for entries. Zero or null means no expiry. public InMemoryClaimCheckRepository(TimeSpan? defaultTtl = null) { _defaultTtl = defaultTtl ?? TimeSpan.Zero; } /// Number of entries currently in the store (including potentially expired). public int Count => _store.Count; /// public Task Store(ReadOnlyMemory data, TimeSpan? ttl = null, CancellationToken ct = default) { var key = Guid.NewGuid().ToString("N"); StoreInternal(key, data, ttl); return Task.FromResult(key); } /// public Task Store(string key, ReadOnlyMemory data, TimeSpan? ttl = null, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); StoreInternal(key, data, ttl); return Task.CompletedTask; } /// public Task Retrieve(string key, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); if (_store.TryGetValue(key, out var entry)) { if (entry.IsExpired) { _store.TryRemove(key, out _); return Task.FromResult(null); } return Task.FromResult(entry.Data); } return Task.FromResult(null); } /// public Task RetrieveAndRemove(string key, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); if (_store.TryRemove(key, out var entry) && !entry.IsExpired) return Task.FromResult(entry.Data); return Task.FromResult(null); } /// public Task Remove(string key, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); _store.TryRemove(key, out _); return Task.CompletedTask; } private void StoreInternal(string key, ReadOnlyMemory data, TimeSpan? ttl) { var effectiveTtl = ttl ?? _defaultTtl; var expiresAt = effectiveTtl > TimeSpan.Zero ? DateTimeOffset.UtcNow + effectiveTtl : (DateTimeOffset?)null; _store[key] = new Entry(data.ToArray(), expiresAt); } private sealed record Entry(byte[] Data, DateTimeOffset? ExpiresAt) { public bool IsExpired => ExpiresAt.HasValue && DateTimeOffset.UtcNow >= ExpiresAt.Value; } } Path: redb-route/redb.Route/Processors/InMemoryIdempotentRepository.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/InMemoryIdempotentRepository.cs ---- using System.Collections.Concurrent; using redb.Route.Abstractions; namespace redb.Route.Processors; /// /// In-memory implementation of . /// Uses a for thread-safe deduplication. /// Supports optional TTL-based eviction to prevent unbounded memory growth. /// Suitable for single-process scenarios and testing. /// public sealed class InMemoryIdempotentRepository : IIdempotentRepository { // One immutable entry per key: replaced whole (compare-and-swap) on Confirm and on a takeover. // Token: the claim id Lease hands out, a GUID per claim; null for a key taken by Add. private sealed record Entry(DateTimeOffset ClaimedAt, bool Confirmed, string? Token = null); private readonly ConcurrentDictionary _store = new(StringComparer.Ordinal); private readonly TimeSpan? _ttl; /// Creates a repository with optional TTL for automatic key expiration. /// /// Time-to-live for keys. Keys older than this are evicted on next call. /// Null means keys are kept indefinitely (default). /// public InMemoryIdempotentRepository(TimeSpan? ttl = null) { _ttl = ttl; } /// Gets the current number of tracked keys (including potentially expired ones). public int Count => _store.Count; /// public Task Add(string key, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); // Lazy eviction: remove expired entries on each Add if (_ttl.HasValue) EvictExpired(); var added = _store.TryAdd(key, new Entry(DateTimeOffset.UtcNow, Confirmed: false)); return Task.FromResult(added); } /// public Task Confirm(string key, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); while (_store.TryGetValue(key, out var entry) && !entry.Confirmed) { if (_store.TryUpdate(key, entry with { Confirmed = true }, entry)) break; } return Task.CompletedTask; } /// public Task Remove(string key, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); _store.TryRemove(key, out _); return Task.CompletedTask; } /// public Task Contains(string key, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); if (_ttl.HasValue && _store.TryGetValue(key, out var entry)) { if (DateTimeOffset.UtcNow - entry.ClaimedAt > _ttl.Value) { _store.TryRemove(key, out _); return Task.FromResult(false); } } return Task.FromResult(_store.ContainsKey(key)); } /// public Task Clear(CancellationToken ct = default) { _store.Clear(); return Task.CompletedTask; } /// public async Task Claim(string key, TimeSpan? abandonedAfter, CancellationToken ct = default) => (await Lease(key, abandonedAfter, ct).ConfigureAwait(false)).Outcome; /// /// /// The confirmed state, the time of the claim and its id are kept with the key; an abandoned claim is replaced by a /// compare-and-swap of exactly the entry that was read, so of two callers taking it over at once one wins. /// public Task Lease(string key, TimeSpan? abandonedAfter, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); if (_ttl.HasValue) EvictExpired(); while (true) { var now = DateTimeOffset.UtcNow; var claim = new Entry(now, Confirmed: false, Guid.NewGuid().ToString("N")); if (_store.TryAdd(key, claim)) return Task.FromResult(new IdempotentLease(IdempotentClaim.Claimed, claim.Token)); if (!_store.TryGetValue(key, out var held)) continue; // released between the two calls: claim it again if (held.Confirmed) return Task.FromResult(new IdempotentLease(IdempotentClaim.Confirmed, null)); if (abandonedAfter is { } age && now - held.ClaimedAt > age) return Task.FromResult(_store.TryUpdate(key, claim, held) ? new IdempotentLease(IdempotentClaim.TakenOver, claim.Token) : new IdempotentLease(IdempotentClaim.InFlight, null)); return Task.FromResult(new IdempotentLease(IdempotentClaim.InFlight, null)); } } /// public async Task Confirm(string key, string? token, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); if (token is null) { await Confirm(key, ct).ConfigureAwait(false); return true; } while (_store.TryGetValue(key, out var entry) && entry.Token == token) { if (entry.Confirmed || _store.TryUpdate(key, entry with { Confirmed = true }, entry)) return true; } return false; } /// public async Task Release(string key, string? token, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); if (token is null) { await Remove(key, ct).ConfigureAwait(false); return true; } while (_store.TryGetValue(key, out var entry) && entry.Token == token) { if (_store.TryRemove(new KeyValuePair(key, entry))) return true; } return false; } private void EvictExpired() { var cutoff = DateTimeOffset.UtcNow - _ttl!.Value; foreach (var kvp in _store) { if (kvp.Value.ClaimedAt < cutoff) _store.TryRemove(kvp.Key, out _); } } } Path: redb-route/redb.Route/Processors/InboundSpanProcessor.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/InboundSpanProcessor.cs ---- using System.Diagnostics; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.Processors; /// /// Keeps the inbound span of the transport that delivered the exchange on the exchange while its route runs, for /// .SpanTag(..., SpanTarget.Inbound). The consumer opened that span around the route /// (), so on entry it is /// . A route entered through direct: finds one of the caller's internal spans /// there and keeps the caller's inbound span. Restored on exit, as does the context. /// internal sealed class InboundSpanProcessor : IProcessor { private readonly IProcessor _inner; public InboundSpanProcessor(IProcessor inner) => _inner = inner ?? throw new ArgumentNullException(nameof(inner)); public async Task Process(IExchange exchange, CancellationToken ct = default) { if (exchange is not Exchange stampable || Activity.Current is not { } current || !IsInbound(current)) { await _inner.Process(exchange, ct).ConfigureAwait(false); return; } var previous = stampable.InboundSpan; stampable.InboundSpan = current; try { await _inner.Process(exchange, ct).ConfigureAwait(false); } finally { stampable.InboundSpan = previous; } } private static bool IsInbound(Activity span) => span.Source == RouteActivitySource.Source && span.Kind is ActivityKind.Server or ActivityKind.Consumer; } Path: redb-route/redb.Route/Processors/InflightTrackingProcessor.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/InflightTrackingProcessor.cs ---- using redb.Route.Abstractions; namespace redb.Route.Processors; /// /// Outermost pipeline wrapper that registers/unregisters exchanges /// in the . Wraps even StatisticsProcessor. /// Guarantees unregister via finally block. /// internal sealed class InflightTrackingProcessor : IProcessor { private readonly IProcessor _inner; private readonly IInflightRepository _repository; private readonly string _routeId; private readonly string? _fromEndpoint; public InflightTrackingProcessor( IProcessor inner, IInflightRepository repository, string routeId, string? fromEndpoint = null) { _inner = inner ?? throw new ArgumentNullException(nameof(inner)); _repository = repository ?? throw new ArgumentNullException(nameof(repository)); _routeId = routeId; _fromEndpoint = fromEndpoint; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var entry = new InflightExchange( exchange.ExchangeId, _routeId, DateTime.UtcNow, Environment.CurrentManagedThreadId, _fromEndpoint); _repository.Register(entry); try { await _inner.Process(exchange, ct).ConfigureAwait(false); } finally { _repository.Unregister(exchange.ExchangeId); } } } Path: redb-route/redb.Route/Processors/InflightWaits.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/InflightWaits.cs ---- using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Processors; /// /// Marks the planned waits of the engine (redelivery delays, the delay step) in the route context's in-flight /// registry, so a monitor tells an exchange that waits by design from a hung one. /// internal static class InflightWaits { /// Waits with the exchange marked as waiting for that long. public static async Task DelayAsync(IExchange exchange, TimeSpan delay, CancellationToken ct) { using (Begin(exchange, delay)) await Task.Delay(delay, ct).ConfigureAwait(false); } private static IDisposable? Begin(IExchange exchange, TimeSpan delay) => (exchange.Context as RouteContext)?.InflightRepository.BeginWait(exchange.ExchangeId, delay); } Path: redb-route/redb.Route/Processors/InterceptProcessor.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/InterceptProcessor.cs ---- using redb.Route.Abstractions; namespace redb.Route.Processors; /// /// Runs the intercept steps before the intercepted processor (a route step for Intercept(), /// the whole route for InterceptFrom()). A condition that does not hold leaves the step /// untouched; a Stop() inside the intercept stops the exchange. /// internal sealed class InterceptProcessor : IProcessor { private readonly IProcessor _intercept; private readonly IPredicate? _condition; private readonly IProcessor _step; public InterceptProcessor(IProcessor intercept, IPredicate? condition, IProcessor step) { _intercept = intercept ?? throw new ArgumentNullException(nameof(intercept)); _condition = condition; _step = step ?? throw new ArgumentNullException(nameof(step)); } public async Task Process(IExchange exchange, CancellationToken ct = default) { if (_condition is null || await _condition.MatchesAsync(exchange).ConfigureAwait(false)) { await _intercept.Process(exchange, ct).ConfigureAwait(false); if (exchange.IsStopped) return; } await _step.Process(exchange, ct).ConfigureAwait(false); } } Path: redb-route/redb.Route/Processors/InterceptSendProcessor.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/InterceptSendProcessor.cs ---- using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Processors; /// /// Wraps a To / ToD: when the target URI matches the mask, publishes it in the exchange property /// (Camel's CamelToEndpoint), runs the intercept steps, and /// then sends to the original endpoint — unless the intercept asked to skip it (dry run, test double) /// or stopped the exchange. A non-matching URI (dynamic targets) is sent untouched. /// internal sealed class InterceptSendProcessor : IProcessor { private readonly IProcessor _intercept; private readonly IPredicate? _condition; private readonly bool _skipOriginal; private readonly string _uriPattern; private readonly Func _targetUri; private readonly IProcessor _send; private readonly DynamicEndpointResolver? _resolver; /// For a dynamic target: the node's own resolver, so the URI resolved here is the one the send uses (evaluated once per message). public InterceptSendProcessor(IProcessor intercept, IPredicate? condition, bool skipOriginal, string uriPattern, Func targetUri, IProcessor send, DynamicEndpointResolver? resolver = null) { _intercept = intercept ?? throw new ArgumentNullException(nameof(intercept)); _condition = condition; _skipOriginal = skipOriginal; _uriPattern = uriPattern ?? throw new ArgumentNullException(nameof(uriPattern)); _targetUri = targetUri ?? throw new ArgumentNullException(nameof(targetUri)); _send = send ?? throw new ArgumentNullException(nameof(send)); _resolver = resolver; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var parked = false; var uri = _resolver is null ? _targetUri(exchange) : _resolver.ResolveAndPark(exchange, out parked); try { if (!UriMask.IsMatch(_uriPattern, uri)) { await _send.Process(exchange, ct).ConfigureAwait(false); return; } // Exchange properties reach logs, traces and the dashboard: publish the target without its secrets. exchange.Properties[ExchangePropertyKeys.ToEndpoint] = EndpointUri.Sanitize(uri); if (_condition is not null && !await _condition.MatchesAsync(exchange).ConfigureAwait(false)) { await _send.Process(exchange, ct).ConfigureAwait(false); return; } await _intercept.Process(exchange, ct).ConfigureAwait(false); if (exchange.IsStopped || _skipOriginal) return; await _send.Process(exchange, ct).ConfigureAwait(false); } finally { if (parked) _resolver!.Unpark(exchange); } } } Path: redb-route/redb.Route/Processors/KeyedThrottleProcessor.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/KeyedThrottleProcessor.cs ---- using System.Collections.Concurrent; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; namespace redb.Route.Processors; /// /// Throttle per key: each distinct key (customer id, tenant, API key…) gets its own sliding-window gate, /// and the limit is read from the message, so key and limit can come from the exchange /// ("gold customers 100 per second, others 10, each under its own key"). /// /// A key's gate is a — the same arrival-order-fair, /// per-message-limit gate as the plain Throttle, one per key — so both throttles behave /// identically, including the two overflow modes (wait, or reject with 429 + Retry-After). /// Gates idle for two periods are evicted, at most once per period, so a high-cardinality key space /// neither grows without bound nor is scanned on every message. /// /// public sealed class KeyedThrottleProcessor : IProcessor, IDisposable { private readonly IProcessor _next; private readonly Func _keyExtractor; private readonly Func _maxPerPeriod; private readonly TimeSpan _period; private readonly bool _rejectOnOverflow; private readonly ILogger? _logger; private readonly ConcurrentDictionary _gates = new(StringComparer.Ordinal); private long _nextEvictionTicks; private int _disposed; /// Creates a keyed throttle with a fixed limit per key. /// Next processor in the pipeline. /// Function extracting the throttle key from the exchange. /// Maximum exchanges per period per key. /// Time period for the rate limit (default: 1 second). /// When true, exchanges that exceed the rate limit are /// short-circuited with HTTP 429 + Retry-After instead of waiting. /// Optional logger. public KeyedThrottleProcessor( IProcessor next, Func keyExtractor, int maxPerPeriod, TimeSpan? period = null, bool rejectOnOverflow = false, ILogger? logger = null) : this(next, keyExtractor, _ => maxPerPeriod, period, rejectOnOverflow, logger) { if (maxPerPeriod <= 0) throw new ArgumentOutOfRangeException(nameof(maxPerPeriod), "Must be > 0."); } /// Creates a keyed throttle whose limit is evaluated on every message. /// Next processor in the pipeline. /// Function extracting the throttle key from the exchange. /// Per-message limit for the exchange's key; must return a positive number. /// Time period for the rate limit (default: 1 second). /// When true, overflow is rejected with 429 instead of waiting. /// Optional logger. public KeyedThrottleProcessor( IProcessor next, Func keyExtractor, Func maxPerPeriod, TimeSpan? period = null, bool rejectOnOverflow = false, ILogger? logger = null) { _next = next ?? throw new ArgumentNullException(nameof(next)); _keyExtractor = keyExtractor ?? throw new ArgumentNullException(nameof(keyExtractor)); _maxPerPeriod = maxPerPeriod ?? throw new ArgumentNullException(nameof(maxPerPeriod)); _period = period ?? TimeSpan.FromSeconds(1); if (_period <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(period), "Must be positive."); _rejectOnOverflow = rejectOnOverflow; _logger = logger; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { ObjectDisposedException.ThrowIf(_disposed != 0, this); var key = _keyExtractor(exchange) ?? string.Empty; var gate = AcquireGate(key); try { await gate.Throttle.Process(exchange, ct).ConfigureAwait(false); } finally { TryEvictStale(); } } /// /// The live gate for , touched under its own lock. Eviction decides under the /// same lock, so a gate a message is about to enter is never retired underneath it; a gate retired /// between the lookup and the lock is skipped and the lookup repeated. /// private KeyGate AcquireGate(string key) { while (true) { var gate = _gates.GetOrAdd(key, _ => new KeyGate(new ThrottleProcessor(_next, _maxPerPeriod, _period, _rejectOnOverflow, _logger))); lock (gate.Sync) { if (gate.Retired) continue; gate.Touch(); return gate; } } } /// public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) != 0) return; foreach (var gate in _gates.Values) gate.Throttle.Dispose(); _gates.Clear(); } /// Number of keys currently holding a gate (diagnostics / tests). public int ActiveKeyCount => _gates.Count; /// Evicts gates idle for two periods; runs at most once per period, whoever's message triggers it. private void TryEvictStale() { var now = Environment.TickCount64; var next = Volatile.Read(ref _nextEvictionTicks); if (now < next || Interlocked.CompareExchange(ref _nextEvictionTicks, now + (long)_period.TotalMilliseconds, next) != next) return; var threshold = now - (long)(_period.TotalMilliseconds * 2); foreach (var (key, gate) in _gates) { lock (gate.Sync) { if (gate.Retired || gate.LastUsedTicks >= threshold || !gate.Throttle.IsIdle) continue; gate.Retired = true; _gates.TryRemove(new KeyValuePair(key, gate)); gate.Throttle.Dispose(); } } } private sealed class KeyGate(ThrottleProcessor throttle) { private long _lastUsedTicks = Environment.TickCount64; public readonly object Sync = new(); public ThrottleProcessor Throttle { get; } = throttle; /// Set under by eviction; a retired gate is disposed and must not be entered. public bool Retired { get; set; } public long LastUsedTicks => Volatile.Read(ref _lastUsedTicks); public void Touch() => Volatile.Write(ref _lastUsedTicks, Environment.TickCount64); } } Path: redb-route/redb.Route/Processors/LoadBalancer/FailoverStrategy.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/LoadBalancer/FailoverStrategy.cs ---- using System; using System.Collections.Concurrent; using System.Collections.Generic; using redb.Route.Abstractions; namespace redb.Route.Processors.LoadBalancer; /// /// Failover load balancer strategy. /// Selects the first healthy endpoint from an ordered list. /// Tracks failures per endpoint and allows recovery after a configurable timeout. /// Thread-safe via . /// public sealed class FailoverStrategy : ILoadBalancerStrategy { private readonly int _maxFailures; private readonly TimeSpan _recoveryTimeout; private readonly ConcurrentDictionary _failures = new(StringComparer.Ordinal); /// /// Creates a failover strategy. /// /// Number of consecutive failures before an endpoint is considered unhealthy. /// Time after which a failed endpoint is retried (probing). public FailoverStrategy(int maxFailures = 3, TimeSpan? recoveryTimeout = null) { _maxFailures = maxFailures > 0 ? maxFailures : throw new ArgumentOutOfRangeException(nameof(maxFailures)); _recoveryTimeout = recoveryTimeout ?? TimeSpan.FromSeconds(30); if (_recoveryTimeout < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(recoveryTimeout), "Recovery timeout must be non-negative."); } /// public string Select(IExchange exchange, IReadOnlyList endpoints) { if (endpoints.Count == 0) throw new InvalidOperationException("No endpoints configured for load balancer."); foreach (var ep in endpoints) { if (!_failures.TryGetValue(ep, out var record)) return ep; if (record.Count < _maxFailures) return ep; // Recovery probe: if enough time passed since last failure, try again if (DateTimeOffset.UtcNow - record.LastFailure > _recoveryTimeout) return ep; } // All endpoints failed — return first and let it fail with proper exception return endpoints[0]; } /// public void ReportFailure(string endpoint, Exception exception) { _failures.AddOrUpdate( endpoint, _ => new FailureRecord(1, DateTimeOffset.UtcNow), (_, old) => new FailureRecord(old.Count + 1, DateTimeOffset.UtcNow)); } /// public void ReportSuccess(string endpoint) { _failures.TryRemove(endpoint, out _); } private sealed record FailureRecord(int Count, DateTimeOffset LastFailure); } Path: redb-route/redb.Route/Processors/LoadBalancer/LoadBalancerProcessor.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/LoadBalancer/LoadBalancerProcessor.cs ---- using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Processors.LoadBalancer; /// /// Processor for the Load Balancer EIP pattern. /// Selects an endpoint using a pluggable , /// then delegates the exchange to the selected endpoint's producer. /// Producers are lazily created and cached per endpoint URI (thread-safe). /// For , automatically retries with the next healthy endpoint on failure. /// public sealed class LoadBalancerProcessor : IProcessor, IAsyncDisposable { private readonly IRouteContext _context; private readonly IReadOnlyList _endpoints; private readonly ILoadBalancerStrategy _strategy; private readonly ILogger? _logger; private readonly ConcurrentDictionary> _producerCache = new(StringComparer.Ordinal); /// /// Creates a new load balancer processor. /// /// Route context for endpoint resolution. /// List of endpoint URIs to balance across. /// Strategy for selecting the next endpoint. /// Optional logger. public LoadBalancerProcessor( IRouteContext context, IReadOnlyList endpoints, ILoadBalancerStrategy strategy, ILogger? logger = null) { _context = context ?? throw new ArgumentNullException(nameof(context)); _endpoints = endpoints ?? throw new ArgumentNullException(nameof(endpoints)); foreach (var endpoint in endpoints) (context as RouteContext)?.NoteStaticEndpoint(endpoint); _strategy = strategy ?? throw new ArgumentNullException(nameof(strategy)); _logger = logger; if (endpoints.Count == 0) throw new ArgumentException("At least one endpoint is required.", nameof(endpoints)); } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(exchange); if (_strategy is FailoverStrategy) { await ProcessWithFailover(exchange, ct).ConfigureAwait(false); return; } var selected = _strategy.Select(exchange, _endpoints); await SendToEndpoint(selected, exchange, ct).ConfigureAwait(false); } private async Task ProcessWithFailover(IExchange exchange, CancellationToken ct) { // Try up to N endpoints (one per attempt) for (var attempt = 0; attempt < _endpoints.Count; attempt++) { var selected = _strategy.Select(exchange, _endpoints); try { var producer = GetOrCreateProducer(selected); await producer.Process(exchange, ct).ConfigureAwait(false); _strategy.ReportSuccess(selected); _logger?.LogDebug("Load balancer: sent to {Endpoint} (failover attempt {Attempt})", EndpointUri.Sanitize(selected), attempt + 1); return; } catch (OperationCanceledException) { throw; } catch (Exception ex) { _strategy.ReportFailure(selected, ex); _logger?.LogWarning(ex, "Load balancer: endpoint {Endpoint} failed (attempt {Attempt}/{Total})", selected, attempt + 1, _endpoints.Count); // Last attempt — re-throw if (attempt == _endpoints.Count - 1) throw; } } } private async Task SendToEndpoint(string endpoint, IExchange exchange, CancellationToken ct) { try { var producer = GetOrCreateProducer(endpoint); await producer.Process(exchange, ct).ConfigureAwait(false); _strategy.ReportSuccess(endpoint); _logger?.LogDebug("Load balancer: sent to {Endpoint}", EndpointUri.Sanitize(endpoint)); } catch (Exception ex) when (ex is not OperationCanceledException) { _strategy.ReportFailure(endpoint, ex); throw; } } private ToProcessor GetOrCreateProducer(string endpoint) { return _producerCache.GetOrAdd(endpoint, ep => new Lazy(() => new ToProcessor(ep, _context))).Value; } /// /// Stops all cached producers and clears the cache. /// public async ValueTask DisposeAsync() { foreach (var lazy in _producerCache.Values) { if (lazy.IsValueCreated) await lazy.Value.StopProducerAsync().ConfigureAwait(false); } _producerCache.Clear(); } } Path: redb-route/redb.Route/Processors/LoadBalancer/RandomStrategy.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/LoadBalancer/RandomStrategy.cs ---- using System; using System.Collections.Generic; using redb.Route.Abstractions; namespace redb.Route.Processors.LoadBalancer; /// /// Random load balancer strategy. /// Selects a random endpoint for each exchange. Stateless and thread-safe. /// public sealed class RandomStrategy : ILoadBalancerStrategy { /// public string Select(IExchange exchange, IReadOnlyList endpoints) { if (endpoints.Count == 0) throw new InvalidOperationException("No endpoints configured for load balancer."); return endpoints[Random.Shared.Next(endpoints.Count)]; } } Path: redb-route/redb.Route/Processors/LoadBalancer/RoundRobinStrategy.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/LoadBalancer/RoundRobinStrategy.cs ---- using System; using System.Collections.Generic; using System.Threading; using redb.Route.Abstractions; namespace redb.Route.Processors.LoadBalancer; /// /// Round-robin load balancer strategy. /// Cycles through endpoints evenly using a lock-free rotating index. /// public sealed class RoundRobinStrategy : ILoadBalancerStrategy { private int _index = -1; /// public string Select(IExchange exchange, IReadOnlyList endpoints) { if (endpoints.Count == 0) throw new InvalidOperationException("No endpoints configured for load balancer."); var idx = Interlocked.Increment(ref _index); // Handle int overflow: ensure non-negative modulo return endpoints[((idx % endpoints.Count) + endpoints.Count) % endpoints.Count]; } } Path: redb-route/redb.Route/Processors/LoadBalancer/StickyStrategy.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/LoadBalancer/StickyStrategy.cs ---- using System; using System.Collections.Generic; using redb.Route.Abstractions; namespace redb.Route.Processors.LoadBalancer; /// /// Sticky load balancer strategy. /// Routes exchanges with the same key to the same endpoint using hash-based selection. /// Falls back to round-robin when the key extractor returns null/empty. /// Thread-safe. /// public sealed class StickyStrategy : ILoadBalancerStrategy { private readonly Func _keyExtractor; private readonly RoundRobinStrategy _fallback = new(); /// /// Creates a sticky strategy with the given key extractor. /// /// /// Extracts a routing key from the exchange (e.g., tenant ID, correlation ID). /// When the result is null or empty, falls back to round-robin. /// public StickyStrategy(Func keyExtractor) { _keyExtractor = keyExtractor ?? throw new ArgumentNullException(nameof(keyExtractor)); } /// public string Select(IExchange exchange, IReadOnlyList endpoints) { if (endpoints.Count == 0) throw new InvalidOperationException("No endpoints configured for load balancer."); var key = _keyExtractor(exchange); if (string.IsNullOrEmpty(key)) return _fallback.Select(exchange, endpoints); // Stable hash → deterministic endpoint selection var hash = key.GetHashCode(StringComparison.Ordinal); var idx = ((hash % endpoints.Count) + endpoints.Count) % endpoints.Count; return endpoints[idx]; } } Path: redb-route/redb.Route/Processors/LoadBalancer/WeightedStrategy.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/LoadBalancer/WeightedStrategy.cs ---- using System; using System.Collections.Generic; using System.Threading; using redb.Route.Abstractions; namespace redb.Route.Processors.LoadBalancer; /// /// Weighted round-robin load balancer strategy. /// Endpoints with higher weights receive proportionally more traffic. /// Thread-safe via lock-free . /// public sealed class WeightedStrategy : ILoadBalancerStrategy { private readonly string[] _expandedEndpoints; private int _index = -1; /// /// Creates a weighted strategy from endpoint-weight pairs. /// /// Tuples of (uri, weight). Weight must be > 0. public WeightedStrategy(IReadOnlyList<(string Uri, int Weight)> endpointWeights) { ArgumentNullException.ThrowIfNull(endpointWeights); if (endpointWeights.Count == 0) throw new ArgumentException("At least one endpoint is required.", nameof(endpointWeights)); // Expand into weighted array: (A:3, B:1) → [A, A, A, B] var expanded = new List(); foreach (var (uri, weight) in endpointWeights) { if (weight <= 0) throw new ArgumentException($"Weight for '{EndpointUri.Sanitize(uri)}' must be positive, got {weight}.", nameof(endpointWeights)); for (var i = 0; i < weight; i++) expanded.Add(uri); } _expandedEndpoints = expanded.ToArray(); } /// /// Selects the next endpoint using weighted round-robin. /// Note: the parameter is intentionally unused; /// weights and their corresponding URIs are fixed at construction time. /// public string Select(IExchange exchange, IReadOnlyList endpoints) { var idx = Interlocked.Increment(ref _index); return _expandedEndpoints[((idx % _expandedEndpoints.Length) + _expandedEndpoints.Length) % _expandedEndpoints.Length]; } } Path: redb-route/redb.Route/Processors/LogProcessor.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/LogProcessor.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; namespace redb.Route.Processors; /// /// Logs a message for each exchange passing through. /// Supports static messages and dynamic expressions via Func. /// public class LogProcessor : IProcessor { private readonly ILogger _logger; private readonly Func _messageFunc; private readonly LogLevel _level; /// Creates a log processor with a static message. /// Logger instance. /// Static log message. /// Log level (default: Information). public LogProcessor(ILogger logger, string message, LogLevel level = LogLevel.Information) : this(logger, _ => message, level) { } /// Creates a log processor with a dynamic message function. /// Logger instance. /// Function to compute the log message from the exchange. /// Log level (default: Information). public LogProcessor(ILogger logger, Func messageFunc, LogLevel level = LogLevel.Information) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _messageFunc = messageFunc ?? throw new ArgumentNullException(nameof(messageFunc)); _level = level; } /// public Task Process(IExchange exchange, CancellationToken ct = default) { #pragma warning disable CA2254 // Template should be a static expression _logger.Log(_level, "{Message}", _messageFunc(exchange)); #pragma warning restore CA2254 return Task.CompletedTask; } } Path: redb-route/redb.Route/Processors/LoopProcessor.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/LoopProcessor.cs ---- using redb.Route.Abstractions; namespace redb.Route.Processors; /// /// Repeats processing either a fixed number of times or until a predicate returns false. /// Supports both count-based and predicate-based looping with optional exchange copy per iteration. /// public class LoopProcessor : IProcessor { private readonly IProcessor _body; private readonly int? _maxIterations; private readonly IPredicate? _whileCondition; private readonly Func? _countFactory; private readonly bool _copy; private readonly bool _shareScope; /// Creates a count-based loop processor. /// Processor to execute on each iteration. /// Maximum number of iterations. /// If true, each iteration receives a clone of the original exchange. /// If true (default), copy-mode iterations share the parent's DI scope (same DB connection, same TX). If false, each iteration gets its own scope. public LoopProcessor(IProcessor body, int maxIterations, bool copy = false, bool shareScope = true) { _body = body ?? throw new ArgumentNullException(nameof(body)); if (maxIterations < 0) throw new ArgumentOutOfRangeException(nameof(maxIterations), "Must be non-negative."); _maxIterations = maxIterations; _copy = copy; _shareScope = shareScope; } /// Creates a predicate-based loop processor. /// Processor to execute on each iteration. /// Predicate evaluated before each iteration; loop continues while true. /// If true, each iteration receives a clone of the original exchange. /// If true (default), copy-mode iterations share the parent's DI scope (same DB connection, same TX). If false, each iteration gets its own scope. public LoopProcessor(IProcessor body, Func whileCondition, bool copy = false, bool shareScope = true) : this(body, new Predicates.LambdaPredicate(whileCondition ?? throw new ArgumentNullException(nameof(whileCondition))), copy, shareScope) { } /// Creates a predicate-based loop processor whose condition is awaited before each iteration. /// Processor to execute on each iteration. /// Condition evaluated before each iteration; the loop continues while it holds. /// If true, each iteration receives a clone of the original exchange. /// If true (default), copy-mode iterations share the parent's DI scope. public LoopProcessor(IProcessor body, IPredicate whileCondition, bool copy = false, bool shareScope = true) { _body = body ?? throw new ArgumentNullException(nameof(body)); _whileCondition = whileCondition ?? throw new ArgumentNullException(nameof(whileCondition)); _copy = copy; _shareScope = shareScope; } /// Creates a dynamic count-based loop processor where count is resolved from the exchange at runtime. /// Processor to execute on each iteration. /// Function that resolves the loop count from the exchange. /// If true, each iteration receives a clone of the original exchange. /// If true (default), copy-mode iterations share the parent's DI scope (same DB connection, same TX). If false, each iteration gets its own scope. public LoopProcessor(IProcessor body, Func countFactory, bool copy = false, bool shareScope = true) { _body = body ?? throw new ArgumentNullException(nameof(body)); _countFactory = countFactory ?? throw new ArgumentNullException(nameof(countFactory)); _copy = copy; _shareScope = shareScope; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { // Snapshot: shares parent scope by default so iterations participate in parent TX. var snapshot = _copy ? (_shareScope ? exchange.CloneLinked() : exchange.Clone()) : null; try { if (_maxIterations.HasValue) { for (var i = 0; i < _maxIterations.Value; i++) { ct.ThrowIfCancellationRequested(); if (exchange.IsStopped) break; await ProcessIteration(exchange, snapshot, i, _maxIterations.Value, ct).ConfigureAwait(false); } } else if (_countFactory is not null) { var count = _countFactory(exchange); for (var i = 0; i < count; i++) { ct.ThrowIfCancellationRequested(); if (exchange.IsStopped) break; await ProcessIteration(exchange, snapshot, i, count, ct).ConfigureAwait(false); } } else { var index = 0; while (await _whileCondition!.MatchesAsync(exchange).ConfigureAwait(false)) { ct.ThrowIfCancellationRequested(); if (exchange.IsStopped) break; await ProcessIteration(exchange, snapshot, index++, null, ct).ConfigureAwait(false); } } } finally { if (snapshot is IAsyncDisposable d) await d.DisposeAsync().ConfigureAwait(false); } } /// /// Runs one iteration. Its index, and the iteration count of a counted loop, are exchange properties of the /// exchange the iteration runs on, as Camel's CamelLoopIndex and CamelLoopSize. /// private async Task ProcessIteration(IExchange exchange, IExchange? snapshot, int index, int? size, CancellationToken ct) { if (!_copy) { MarkIteration(exchange, index, size); await _body.Process(exchange, ct).ConfigureAwait(false); return; } var target = _shareScope ? snapshot!.CloneLinked() : snapshot!.Clone(); MarkIteration(target, index, size); try { await _body.Process(target, ct).ConfigureAwait(false); MergeBack(exchange, target); } finally { if (target is IAsyncDisposable d) await d.DisposeAsync().ConfigureAwait(false); } } private static void MarkIteration(IExchange exchange, int index, int? size) { exchange.Properties[ExchangePropertyKeys.LoopIndex] = index; if (size is { } count) exchange.Properties[ExchangePropertyKeys.LoopSize] = count; } /// Merges iteration results back into the original exchange (headers, properties, exception state). private static void MergeBack(IExchange original, IExchange iteration) { original.In.Body = iteration.In.Body; foreach (var h in iteration.In.Headers) original.In.Headers[h.Key] = h.Value; foreach (var p in iteration.Properties) { // The clone's own bookkeeping (cached DI scopes, registered resources) stays with the clone, which // releases it right after this merge; copying it here would leave the original a disposed scope. if (ExchangeResources.IsOwnedByExchange(p.Key)) continue; original.Properties[p.Key] = p.Value; } if (iteration.Exception != null) original.Exception = iteration.Exception; } } Path: redb-route/redb.Route/Processors/MessageHistoryProcessor.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/MessageHistoryProcessor.cs ---- using System.Diagnostics; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Processors; /// /// Wraps a single route node so that, as the exchange passes through, a /// (route id, node id, node label, elapsed ms) is appended to the exchange's message history. Applied at /// compile time by when message history is enabled — the runtime /// half of the Apache Camel Message History EIP. /// /// The elapsed time is recorded in a finally, so a node that throws still leaves a history entry — /// which is exactly what the failure dump needs to point at the step that failed. /// /// internal sealed class MessageHistoryProcessor : IProcessor { private readonly IProcessor _inner; private readonly string _routeId; private readonly string _nodeId; private readonly string _label; public MessageHistoryProcessor(IProcessor inner, string routeId, string nodeId, string label) { _inner = inner ?? throw new ArgumentNullException(nameof(inner)); _routeId = routeId; _nodeId = nodeId; _label = label; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { var start = Stopwatch.GetTimestamp(); try { await _inner.Process(exchange, ct).ConfigureAwait(false); } finally { var elapsedMs = Stopwatch.GetElapsedTime(start).TotalMilliseconds; MessageHistory.Append(exchange, new MessageHistoryEntry(_routeId, _nodeId, _label, elapsedMs)); } } } Path: redb-route/redb.Route/Processors/MulticastProcessor.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/MulticastProcessor.cs ---- using redb.Route.Abstractions; using redb.Route.Telemetry; using redb.Route.Transactions; namespace redb.Route.Processors; /// /// Sends the exchange to multiple processors (fan-out). /// Supports parallel/sequential execution, aggregation strategy, stopOnException, /// timeout, and configurable concurrency with deterministic result ordering. /// public class MulticastProcessor : IProcessor { private readonly List _targets = []; private readonly bool _parallelProcessing; private readonly int _maxDegreeOfParallelism; private readonly bool _stopOnException; private readonly TimeSpan _timeout; private readonly Func? _aggregationStrategy; /// Gets the list of target processors. public IReadOnlyList Targets => _targets; /// Creates a multicast processor. /// Whether to process targets in parallel (true) or sequentially (false). /// Optional pair-wise aggregation: (aggregated, current) → merged. /// Whether to stop on the first exception. /// Timeout for the entire multicast operation (TimeSpan.Zero = no timeout). /// Maximum concurrent tasks when parallel (0 = unlimited). public MulticastProcessor( bool parallelProcessing = true, Func? aggregationStrategy = null, bool stopOnException = false, TimeSpan timeout = default, int maxDegreeOfParallelism = 0) { _parallelProcessing = parallelProcessing; _aggregationStrategy = aggregationStrategy; _stopOnException = stopOnException; _timeout = timeout; _maxDegreeOfParallelism = maxDegreeOfParallelism > 0 ? maxDegreeOfParallelism : Environment.ProcessorCount; } /// Adds a target processor to the multicast. /// Target processor. /// This instance for fluent chaining. public MulticastProcessor AddTarget(IProcessor processor) { ArgumentNullException.ThrowIfNull(processor); _targets.Add(processor); return this; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { if (_targets.Count == 0) return; ProcessorMetrics.MulticastBranches.Record(_targets.Count); using var timeoutCts = _timeout > TimeSpan.Zero ? CancellationTokenSource.CreateLinkedTokenSource(ct) : null; if (timeoutCts != null) timeoutCts.CancelAfter(_timeout); var effectiveCt = timeoutCts?.Token ?? ct; try { if (_parallelProcessing) await ProcessParallel(exchange, effectiveCt).ConfigureAwait(false); else await ProcessSequential(exchange, effectiveCt).ConfigureAwait(false); } catch (OperationCanceledException) when (timeoutCts != null && timeoutCts.IsCancellationRequested && !ct.IsCancellationRequested) { throw new TimeoutException($"Multicast processing timed out after {_timeout.TotalMilliseconds} ms."); } } private async Task ProcessSequential(IExchange exchange, CancellationToken ct) { var clones = new IExchange[_targets.Count]; Exception? firstException = null; try { for (var i = 0; i < _targets.Count; i++) { ct.ThrowIfCancellationRequested(); clones[i] = Branch(exchange.CorrelatedCopyLinked(), i); try { await _targets[i].Process(clones[i], ct).ConfigureAwait(false); } catch (OperationCanceledException) { throw; } catch (Exception ex) { clones[i].Exception = ex; firstException ??= ex; ProcessorMetrics.MulticastFailedBranches.Add(1); if (_stopOnException) { exchange.Exception = ex; break; } } } Aggregate(exchange, clones); } finally { // Release the clones' DI scopes only, as Splitter / ScatterGather / RecipientList do. Disposing // a clone would close its body, and the aggregation may have handed exactly that body (or the // clones themselves, GroupedExchange) to the original exchange. foreach (var clone in clones) if (clone is redb.Route.Core.Exchange e) await e.ReleaseScopes().ConfigureAwait(false); } if (firstException != null && _stopOnException) throw firstException; } private async Task ProcessParallel(IExchange exchange, CancellationToken ct) { var clones = new IExchange?[_targets.Count]; var exceptions = new Exception?[_targets.Count]; var shouldStop = 0; using var semaphore = new SemaphoreSlim(_maxDegreeOfParallelism); try { var tasks = new Task[_targets.Count]; for (var i = 0; i < _targets.Count; i++) { var idx = i; tasks[idx] = Task.Run(async () => { if (Volatile.Read(ref shouldStop) == 1) return; await semaphore.WaitAsync(ct).ConfigureAwait(false); try { if (Volatile.Read(ref shouldStop) == 1) return; var clone = Branch(exchange.CorrelatedCopy(), idx); clones[idx] = clone; try { // Isolate this branch under a dependent clone of the ambient transaction so // concurrent branches never share one Transaction.Current (see DependentTransactionBranch). await DependentTransactionBranch.RunAsync(() => _targets[idx].Process(clone, ct)).ConfigureAwait(false); } catch (OperationCanceledException) { throw; } catch (Exception ex) { clone.Exception = ex; exceptions[idx] = ex; ProcessorMetrics.MulticastFailedBranches.Add(1); if (_stopOnException) { Interlocked.Exchange(ref shouldStop, 1); } } finally { // Release DI scopes early; body/headers stay alive for aggregation await clone.ReleaseScopes().ConfigureAwait(false); } } finally { semaphore.Release(); } }, ct); } await Task.WhenAll(tasks).ConfigureAwait(false); // Aggregate in deterministic index order Aggregate(exchange, clones!); var allExceptions = exceptions.Where(e => e != null).Cast().ToArray(); if (allExceptions.Length > 0) { exchange.Exception = allExceptions.Length == 1 ? allExceptions[0] : new AggregateException("Multiple multicast targets failed.", allExceptions); if (_stopOnException) throw allExceptions[0]; } } finally { // Release the clones' DI scopes only, as Splitter / ScatterGather / RecipientList do. Disposing // a clone would close its body, and the aggregation may have handed exactly that body (or the // clones themselves, GroupedExchange) to the original exchange. foreach (var clone in clones) if (clone is redb.Route.Core.Exchange e) await e.ReleaseScopes().ConfigureAwait(false); } } /// /// Marks a branch copy as Camel's multicast does: its index and whether it is the last branch, as exchange /// properties. The copy is a correlated one: its own id, and the original's id as its correlation id. /// private IExchange Branch(IExchange copy, int index) { copy.Properties[ExchangePropertyKeys.MulticastIndex] = index; copy.Properties[ExchangePropertyKeys.MulticastComplete] = index == _targets.Count - 1; return copy; } private void Aggregate(IExchange original, IExchange[] clones) { if (_aggregationStrategy == null) return; IExchange? aggregated = null; foreach (var clone in clones) { if (clone == null) continue; // Skip error clones if stopOnException is set — only aggregate successful results if (_stopOnException && clone.Exception != null) continue; aggregated = aggregated == null ? clone : _aggregationStrategy(aggregated, clone); } if (aggregated != null) { original.In.Body = aggregated.In.Body; foreach (var header in aggregated.In.Headers) original.In.Headers[header.Key] = header.Value; foreach (var prop in aggregated.Properties) { // The clone's own bookkeeping (cached DI scopes, registered resources) stays with the clone, which // releases it right after this merge; copying it here would leave the original a disposed scope. // The branch's correlation id points at the original; the original keeps its own, as in Camel. if (ExchangeResources.IsOwnedByExchange(prop.Key) || prop.Key == ExchangePropertyKeys.CorrelationId) continue; original.Properties[prop.Key] = prop.Value; } } } } 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); } } } Path: redb-route/redb.Route/Processors/OnExceptionProcessor.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/OnExceptionProcessor.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.ErrorHandling; namespace redb.Route.Processors; /// /// The OnException handlers of one scope around a body: handles the failures a per-step /// TryCatchProcessor did not, with redelivery (delay, exponential backoff, max attempts). /// /// The handler is chosen as Apache Camel's DefaultExceptionPolicyStrategy chooses it: the failure is walked /// from its innermost cause up to the exception that was thrown; a handler of exactly that type wins at once; /// otherwise the handler whose type is the nearest ancestor does, the earlier exception of the walk and the earlier /// declared handler winning a tie. The smallest distance over the whole chain wins, as in Camel's source: a cause /// whose nearest handler is further away loses to the thrown exception's nearer one, even a catch-all. A handler /// whose OnWhen is false is passed over. A later handler of the same /// type without OnWhen replaces the earlier one. /// /// /// A route has two such scopes, the route's own handlers inside and the ones shared with other routes (its route /// configurations and its builder) outside. The inner one leaves a failure to the outer one when that has a strictly /// nearer handler; on a tie the route's own handler wins. /// /// public class OnExceptionProcessor : IProcessor { private readonly IProcessor _body; private readonly List _handlers = []; private readonly ILogger? _logger; /// /// The scope around this one. A failure this scope could take is left to it when it has a strictly nearer handler. /// internal OnExceptionProcessor? Outer { get; set; } /// Creates an on-exception processor wrapping the body. /// The main processor pipeline to protect. /// Optional logger for exception diagnostics. public OnExceptionProcessor(IProcessor body, ILogger? logger = null) { _body = body ?? throw new ArgumentNullException(nameof(body)); _logger = logger; } /// Registers a handler for a specific exception type. /// Exception type to handle. /// Handler processor. /// Maximum retry attempts before giving up (default: 0, no retry). /// Delay between retry attempts (default: 1 second). /// Backoff multiplier (default: 1.0 = fixed delay). /// Whether to apply exponential backoff (default: false). /// Whether the exception is marked as handled (default: false). /// Whether to continue the pipeline after the handler runs (default: false). /// Optional guard predicate. /// Log level for retry attempt messages (default: Warning). /// Log level when retries are exhausted (default: Error). /// Optional callback on each exception occurrence. /// Optional predicate — retry continues while true. /// Optional callback before each redelivery. /// Optional callback before handler/DLQ after retries exhausted. /// Restore original message before retries and handler. /// Restore original body only before retries and handler. /// Allow retries during cancellation. /// Include stack trace in retry logs. /// Log when retries are exhausted. /// Log the exhausted failure when the handler handled it (default: false, as in Camel). /// Log the exhausted failure when the handler continued it (default: false, as in Camel). /// This instance for fluent chaining. public OnExceptionProcessor Handle( IProcessor handler, int maxRedeliveries = 0, TimeSpan? redeliveryDelay = null, double backoffMultiplier = 1.0, bool useExponentialBackoff = false, bool handled = false, bool continued = false, Func? onWhenPredicate = null, LogLevel retryAttemptedLogLevel = LogLevel.Warning, LogLevel retriesExhaustedLogLevel = LogLevel.Error, Action? onExceptionOccurred = null, Func? retryWhile = null, Action? onRedelivery = null, Action? onPrepareFailure = null, bool useOriginalMessage = false, bool useOriginalBody = false, bool allowRedeliveryWhileStopping = false, bool logStackTrace = true, bool logExhausted = true, bool logHandled = false, bool logContinued = false) where TException : Exception { return Handle(typeof(TException), handler, maxRedeliveries, redeliveryDelay, backoffMultiplier, useExponentialBackoff, handled, continued, onWhenPredicate, retryAttemptedLogLevel, retriesExhaustedLogLevel, onExceptionOccurred, retryWhile, onRedelivery, onPrepareFailure, useOriginalMessage, useOriginalBody, allowRedeliveryWhileStopping, logStackTrace, logExhausted, logHandled: logHandled, logContinued: logContinued); } /// Registers a handler for a specific exception type (non-generic). public OnExceptionProcessor Handle( Type exceptionType, IProcessor handler, int maxRedeliveries = 0, TimeSpan? redeliveryDelay = null, double backoffMultiplier = 1.0, bool useExponentialBackoff = false, bool handled = false, bool continued = false, Func? onWhenPredicate = null, LogLevel retryAttemptedLogLevel = LogLevel.Warning, LogLevel retriesExhaustedLogLevel = LogLevel.Error, Action? onExceptionOccurred = null, Func? retryWhile = null, Action? onRedelivery = null, Action? onPrepareFailure = null, bool useOriginalMessage = false, bool useOriginalBody = false, bool allowRedeliveryWhileStopping = false, bool logStackTrace = true, bool logExhausted = true, // The processor forms of the three callbacks: the markup can only name a bean, and a bean is an IProcessor. // New parameters go last and optional, and land on init-only properties of the handler record: a new positional // parameter would shift the ones after it and break every caller built against the old order. IProcessor? onExceptionOccurredProcessor = null, IProcessor? onRedeliveryProcessor = null, IProcessor? onPrepareFailureProcessor = null, // Camel's LogHandled / LogContinued: whether the exhausted-failure log entry is written when the handler handled // (or continued) the failure. Both false by default, as in Camel. A rollback-only exchange bypasses both checks. bool logHandled = false, bool logContinued = false) { ArgumentNullException.ThrowIfNull(exceptionType); ArgumentNullException.ThrowIfNull(handler); RetryPolicy? retryPolicy = null; if (maxRedeliveries > 0) { var delay = redeliveryDelay ?? TimeSpan.FromSeconds(1); var multiplier = useExponentialBackoff ? Math.Max(backoffMultiplier, 2.0) : backoffMultiplier; retryPolicy = new RetryPolicy { MaxRetries = maxRedeliveries, InitialDelay = delay, BackoffMultiplier = multiplier, MaxDelay = TimeSpan.FromMinutes(5) }; } var registered = new ExceptionHandler(exceptionType, handler, maxRedeliveries, retryPolicy, handled, continued, onWhenPredicate, retryAttemptedLogLevel, retriesExhaustedLogLevel, onExceptionOccurred, retryWhile, onRedelivery, onPrepareFailure, useOriginalMessage, useOriginalBody, allowRedeliveryWhileStopping, logStackTrace, logExhausted, logHandled, logContinued) { OnExceptionOccurredProcessor = onExceptionOccurredProcessor, OnRedeliveryProcessor = onRedeliveryProcessor, OnPrepareFailureProcessor = onPrepareFailureProcessor, }; // Camel keys its policies by exception type and OnWhen: a later handler of the same type without OnWhen takes // the place of the earlier one (so a route configuration's handler is used instead of the builder's). Handlers // with an OnWhen are each their own entry. var same = onWhenPredicate is null ? _handlers.FindIndex(h => h.ExceptionType == exceptionType && h.OnWhenPredicate is null) : -1; if (same >= 0) _handlers[same] = registered; else _handlers.Add(registered); return this; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { // Snapshot original message/body BEFORE processing (any handler may need it) object? originalBody = null; IDictionary? originalHeaders = null; var needsSnapshot = _handlers.Any(h => h.UseOriginalMessage || h.UseOriginalBody); if (needsSnapshot) { originalBody = exchange.In.Body; if (_handlers.Any(h => h.UseOriginalMessage)) originalHeaders = new Dictionary(exchange.In.Headers); } var attempt = 0; // Set by a Continued handler: the next turn replays the steps after the one that failed instead of the body. Exception? continueAfter = null; while (true) { var resuming = continueAfter is not null; try { if (continueAfter is { } failure) { continueAfter = null; await ResumePoints.ResumeAsync(exchange, failure, ct).ConfigureAwait(false); } else { await _body.Process(exchange, ct).ConfigureAwait(false); } return; // Success — exit } // A downstream timeout is an OperationCanceledException whose token (ours) is still live — not a // cancellation, so it enters here and is named a TimeoutException so OnException // matches it. A genuine cancellation (the caller's token fired) is filtered out, never swallowed. catch (Exception ex) when (!RouteCancellation.IsCancellation(ex, ct)) { ex = RouteCancellation.Normalize(ex, ct); exchange.Exception = ex; var (handler, distance) = FindHandler(ex, exchange); if (handler == null) throw; // No handler — rethrow // The scope around has a strictly nearer handler: the failure is its to take. if (Outer?.FindHandler(ex, exchange) is { Handler: not null } outer && outer.Distance < distance) throw; // Invoke callback if registered handler.OnExceptionOccurred?.Invoke(exchange); if (handler.OnExceptionOccurredProcessor is { } occurred) await occurred.Process(exchange, ct).ConfigureAwait(false); // B10: Set redelivery headers exchange.In.Headers["CamelRedelivered"] = attempt > 0; exchange.In.Headers["CamelRedeliveryCounter"] = attempt; // Check if we should continue retrying. A failure in steps replayed after a continue is not retried: // a redelivery re-runs the route from its first step, which would repeat what already succeeded. var shouldRetry = false; if (resuming) { shouldRetry = false; } else if (handler.RetryWhile != null) { // RetryWhile takes priority — retry as long as predicate returns true shouldRetry = handler.RetryWhile(exchange); } else { shouldRetry = attempt < handler.MaxRedeliveries; } // B7: Check if redelivery is allowed while stopping if (shouldRetry && !handler.AllowRedeliveryWhileStopping && ct.IsCancellationRequested) shouldRetry = false; if (shouldRetry) { attempt++; exchange.In.Headers["CamelRedeliveryCounter"] = attempt; exchange.In.Headers["CamelRedelivered"] = true; if (handler.LogStackTrace) { _logger?.Log(handler.RetryAttemptedLogLevel, ex, "Redelivery attempt {Attempt}/{Max} for {ExceptionType}", attempt, handler.MaxRedeliveries, ex.GetType().Name); } else { _logger?.Log(handler.RetryAttemptedLogLevel, "Redelivery attempt {Attempt}/{Max} for {ExceptionType}: {Message}", attempt, handler.MaxRedeliveries, ex.GetType().Name, EndpointUri.RedactSecrets(ex.Message)); } // Apply redelivery delay if (handler.RetryPolicy != null) { var delay = handler.RetryPolicy.GetDelay(attempt - 1); if (delay > TimeSpan.Zero) await InflightWaits.DelayAsync(exchange, delay, ct).ConfigureAwait(false); } // B6: Restore original message/body before retry RestoreOriginal(exchange, handler, originalBody, originalHeaders); // B4: OnRedelivery callback before each retry handler.OnRedelivery?.Invoke(exchange); if (handler.OnRedeliveryProcessor is { } redelivery) await redelivery.Process(exchange, ct).ConfigureAwait(false); exchange.Exception = null; exchange.ExceptionHandled = false; exchange.ClearFailureHandled(); // a redelivery is not a handled failure yet continue; // Retry } // Retries exhausted — B10: set exhausted flag exchange.In.Headers["CamelRedeliveryExhausted"] = true; exchange.In.Headers["CamelRedeliveryMaxCounter"] = handler.MaxRedeliveries; // B8: Log exhausted. Camel's RedeliveryErrorHandler.logFailedDelivery logs a handled failure only when // LogHandled, a continued one only when LogContinued. Both checks are bypassed for a rollback-only // exchange: its work was rolled back, so the failure is real even if the handler answered a client. var logThisFailure = handler.LogExhausted && (exchange.IsRollbackOnly() || !((handler.Handled && !handler.LogHandled) || (handler.Continued && !handler.LogContinued))); if (logThisFailure) { if (handler.LogStackTrace) { _logger?.Log(handler.RetriesExhaustedLogLevel, ex, "Retries exhausted for {ExceptionType} after {Attempts} attempts", ex.GetType().Name, attempt); } else { _logger?.Log(handler.RetriesExhaustedLogLevel, "Retries exhausted for {ExceptionType} after {Attempts} attempts: {Message}", ex.GetType().Name, attempt, EndpointUri.RedactSecrets(ex.Message)); } // Dump the message-history trail (when recorded) so the failing step is visible. var history = Core.MessageHistory.Format(exchange); if (!string.IsNullOrEmpty(history)) _logger?.Log(handler.RetriesExhaustedLogLevel, "{MessageHistory}", history); } // B6: Restore original message/body before handler RestoreOriginal(exchange, handler, originalBody, originalHeaders); // B5: OnPrepareFailure callback before handler/DLQ handler.OnPrepareFailure?.Invoke(exchange); if (handler.OnPrepareFailureProcessor is { } prepareFailure) await prepareFailure.Process(exchange, ct).ConfigureAwait(false); await handler.Processor.Process(exchange, ct).ConfigureAwait(false); // Apply handled/continued flags. // Handled or Continued suppress the failure — the exception is cleared and the consumer // commits. Otherwise — the // Camel handled(false) default — the failure is NOT suppressed: the onException route ran // (logging / DLQ / etc.), but the exception stays on the exchange with ExceptionHandled=false // so the consumer, which treats `Exception != null && !ExceptionHandled` as a failure, rolls // back and does not ack. Previously this branch set ExceptionHandled=true, silently swallowing // the failure: the transaction rolled back while the message was acknowledged. if (handler.Handled) { // Camel's ExchangeHelper.setFailureHandled: an error handler handled the failure. The exchange // completes successfully (the consumer acknowledges), but the idempotent consumer must not confirm // the key it claimed for the work that failed. exchange.MarkFailureHandled(); exchange.ExceptionHandled = true; exchange.Exception = null; } else if (handler.Continued) { // Camel's prepareExchangeForContinue clears the marker: a continued handler does not count the // failure handled, so a dedup key claimed for the block stays confirmed. exchange.ClearFailureHandled(); exchange.ExceptionHandled = true; exchange.Exception = null; } else { exchange.ClearFailureHandled(); exchange.ExceptionHandled = false; } // Continued: routing picks up at the step after the one that failed (Camel's continued(true)), where // Handled ends the route here. The next turn of the loop replays the steps the pipelines recorded, and // a failure among them is matched against the handlers anew. if (handler.Continued && !exchange.IsStopped) { continueAfter = ex; continue; } return; } } } private static void RestoreOriginal(IExchange exchange, ExceptionHandler handler, object? originalBody, IDictionary? originalHeaders) { if (handler.UseOriginalMessage && originalHeaders != null) { exchange.In.Body = originalBody; exchange.In.Headers.Clear(); foreach (var kvp in originalHeaders) exchange.In.Headers[kvp.Key] = kvp.Value; } else if (handler.UseOriginalBody) { exchange.In.Body = originalBody; } } /// /// The handler of this scope for and how far its type is from the exception it matched /// (0 — exactly that type), or no handler. See the class remarks for the rule. /// internal (ExceptionHandler? Handler, int Distance) FindHandler(Exception ex, IExchange exchange) { ExceptionHandler? best = null; var bestDistance = int.MaxValue; foreach (var failure in InnermostFirst(ex)) { var failureType = failure.GetType(); ExceptionHandler? candidate = null; var candidateDistance = int.MaxValue; foreach (var h in _handlers) { if (!h.ExceptionType.IsInstanceOfType(failure)) continue; if (h.OnWhenPredicate != null && !h.OnWhenPredicate(exchange)) continue; var distance = Distance(failureType, h.ExceptionType); if (distance < candidateDistance) { candidate = h; candidateDistance = distance; if (distance == 0) break; } } // The earlier exception of the walk keeps a tie. if (candidate is not null && candidateDistance < bestDistance) { best = candidate; bestDistance = candidateDistance; } if (bestDistance == 0) break; } return (best, bestDistance); } /// The failure and its causes, the innermost cause first, the thrown exception last. private static List InnermostFirst(Exception ex) { var chain = new List(); for (Exception? current = ex; current is not null; current = current.InnerException) chain.Add(current); chain.Reverse(); return chain; } /// How many base-type steps separate from . private static int Distance(Type failureType, Type handlerType) { var distance = 0; for (var type = failureType; type is not null && type != handlerType; type = type.BaseType) distance++; return distance; } /// Gets the registered handlers. public IReadOnlyList Handlers => _handlers; /// Describes a registered exception handler. /// Exception type to match. /// Handler processor to execute. /// Maximum redelivery attempts before handler fires. /// Optional retry policy for controlling delays between redeliveries. /// Whether the exception is marked as handled (clears Exception on exchange). /// Whether to continue the pipeline after handler. /// Guard predicate — handler fires only when this returns true. /// Log level for retry attempts. /// Log level when retries are exhausted. /// Callback invoked each time exception occurs. /// Predicate evaluated before each retry — continues retrying while true, regardless of max count. /// Callback invoked before each redelivery attempt (after delay). /// Callback invoked before the exchange is sent to the handler/DLQ after all retries are exhausted. /// When true, restore the original message (body + headers) before each retry and before executing the handler. /// When true, restore only the original body (not headers) before each retry and before executing the handler. /// When false (default), redelivery stops immediately if cancellation is requested. /// Whether to include the full stack trace in retry log messages (default: true). /// Whether to log when all retries are exhausted (default: true). /// Whether to log the exhausted failure when the handler handled it (default: false, as in Camel). /// Whether to log the exhausted failure when the handler continued it (default: false, as in Camel). public record ExceptionHandler( Type ExceptionType, IProcessor Processor, int MaxRedeliveries, RetryPolicy? RetryPolicy = null, bool Handled = false, bool Continued = false, Func? OnWhenPredicate = null, LogLevel RetryAttemptedLogLevel = LogLevel.Warning, LogLevel RetriesExhaustedLogLevel = LogLevel.Error, Action? OnExceptionOccurred = null, Func? RetryWhile = null, Action? OnRedelivery = null, Action? OnPrepareFailure = null, bool UseOriginalMessage = false, bool UseOriginalBody = false, bool AllowRedeliveryWhileStopping = false, bool LogStackTrace = true, bool LogExhausted = true, bool LogHandled = false, bool LogContinued = false) { /// Processor invoked every time the exception occurs, before any retry. public IProcessor? OnExceptionOccurredProcessor { get; init; } /// Processor invoked before each redelivery attempt. public IProcessor? OnRedeliveryProcessor { get; init; } /// Processor invoked before the handler runs, once the redeliveries are exhausted. public IProcessor? OnPrepareFailureProcessor { get; init; } } } Path: redb-route/redb.Route/Processors/PipelineProcessor.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/PipelineProcessor.cs ---- using redb.Route.Abstractions; namespace redb.Route.Processors; /// /// Executes a list of processors sequentially. The backbone of route processing. /// Stops early if exchange.IsStopped or cancellation is requested. /// public class PipelineProcessor : IProcessor { private readonly List _processors = []; /// Gets the list of processors in this pipeline. public IReadOnlyList Processors => _processors; /// Adds a processor to the end of the pipeline. /// Processor to add. public void Add(IProcessor processor) { ArgumentNullException.ThrowIfNull(processor); _processors.Add(processor); } /// Adds multiple processors to the pipeline. /// Processors to add. public void AddRange(IEnumerable processors) { ArgumentNullException.ThrowIfNull(processors); _processors.AddRange(processors); } /// public Task Process(IExchange exchange, CancellationToken ct = default) => ProcessFrom(exchange, 0, ct); /// /// Runs the pipeline from . A failure records where the pipeline stopped /// (), so an OnException ... Continued() handler can pick the route up at the next /// step, as Apache Camel does. /// internal async Task ProcessFrom(IExchange exchange, int startIndex, CancellationToken ct) { // Pipeline EIP semantics: // - Intermediate steps that produce Out are merged (Out → In, Out := null) so the // next step sees the result as its input. // - The final step's Out (if any) is left intact so InOut callers (direct-vm, // replyTo, RPC) get the reply via exchange.Out. // - If the final step does NOT produce Out, we do not synthesize one from earlier // steps: any subsequent step that modified In is the authoritative final result. for (var i = startIndex; i < _processors.Count; i++) { ct.ThrowIfCancellationRequested(); if (exchange.IsStopped) break; try { await _processors[i].Process(exchange, ct).ConfigureAwait(false); } catch (Exception failure) when (failure is not OperationCanceledException) { ResumePoints.Record(exchange, failure, this, i + 1); throw; } // Pipeline EIP: propagate Out body/headers → In so the next processor sees the result. // ContentType is merged like a header, not taken wholesale: a step that writes an Out body // without setting a content type leaves the In content type in place (it used to be nulled, // which lost the format for a body that had not declared its own). if (exchange.HasOut && i < _processors.Count - 1) { var outMsg = exchange.Out!; exchange.In.Body = outMsg.Body; if (outMsg.ContentType is not null) exchange.In.ContentType = outMsg.ContentType; foreach (var (key, value) in outMsg.Headers) exchange.In.Headers[key] = value; // Attachments follow the content type rule: an Out that carries some replaces those of In, an Out that // carries none (a producer's reply) leaves the In ones for the next step. Core.MessageAttachments.ReplaceWhenPresent(outMsg, exchange.In); exchange.Out = null; // prevent stale Out from re-merging on next step } } } } Path: redb-route/redb.Route/Processors/RecipientListProcessor.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/RecipientListProcessor.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.Processors; /// /// Sends the exchange to a dynamic list of endpoints determined at runtime. /// Unlike Multicast (static URI list), RecipientList computes URIs from the exchange. /// Supports parallel/sequential processing and configurable aggregation. /// Producers are cached per URI for the lifetime of this processor. /// internal sealed class RecipientListProcessor : IProcessor, IAsyncDisposable { private readonly IRouteContext _context; private readonly Func> _recipientListFactory; private readonly bool _parallelProcessing; private readonly bool _stopOnException; private readonly Func? _aggregationStrategy; private readonly Dictionary _producerCache = new(StringComparer.Ordinal); private readonly object _cacheLock = new(); /// Creates a recipient list processor. /// Route context for resolving endpoints. /// Function that returns target URIs from the exchange. /// Whether to send to recipients in parallel. /// Whether to stop on the first exception. /// Optional pair-wise aggregation of results. public RecipientListProcessor( IRouteContext context, Func> recipientListFactory, bool parallelProcessing = false, bool stopOnException = false, Func? aggregationStrategy = null) { _context = context ?? throw new ArgumentNullException(nameof(context)); _recipientListFactory = recipientListFactory ?? throw new ArgumentNullException(nameof(recipientListFactory)); _parallelProcessing = parallelProcessing; _stopOnException = stopOnException; _aggregationStrategy = aggregationStrategy; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { var uris = _recipientListFactory(exchange).ToList(); if (uris.Count == 0) return; ProcessorMetrics.RecipientListRecipients.Record(uris.Count); if (_parallelProcessing) await ProcessParallel(exchange, uris, ct).ConfigureAwait(false); else await ProcessSequential(exchange, uris, ct).ConfigureAwait(false); } private async Task ProcessSequential(IExchange exchange, List uris, CancellationToken ct) { IExchange? aggregated = null; var copies = new List(uris.Count); try { foreach (var uri in uris) { ct.ThrowIfCancellationRequested(); var copy = exchange.CorrelatedCopyLinked(); copies.Add(copy); var (endpoint, producer) = GetOrCreateProducer(uri); copy.Properties[ExchangePropertyKeys.RecipientListEndpoint] = uri; try { await Core.CountedSend.Process(endpoint, producer, copy, ct).ConfigureAwait(false); if (copy.Exception != null && _stopOnException) { exchange.Exception = copy.Exception; return; } if (_aggregationStrategy != null) aggregated = aggregated is null ? copy : _aggregationStrategy(aggregated, copy); } catch when (_stopOnException) { throw; } catch (Exception ex) { copy.Exception = ex; if (_aggregationStrategy != null) aggregated = aggregated is null ? copy : _aggregationStrategy(aggregated, copy); } } if (aggregated != null && _aggregationStrategy != null) { exchange.In.Body = aggregated.In.Body; foreach (var header in aggregated.In.Headers) exchange.In.Headers[header.Key] = header.Value; } } finally { foreach (var copy in copies) if (copy is IAsyncDisposable d) await d.DisposeAsync().ConfigureAwait(false); } } private async Task ProcessParallel(IExchange exchange, List uris, CancellationToken ct) { var copies = new List(uris.Count); try { var tasks = uris.Select(async uri => { var copy = exchange.CorrelatedCopy(); lock (copies) copies.Add(copy); var (endpoint, producer) = GetOrCreateProducer(uri); copy.Properties[ExchangePropertyKeys.RecipientListEndpoint] = uri; try { // Concurrent branches never share one Transaction.Current: each runs under a dependent clone of the // route's transaction, as a parallel Multicast or Split does (see DependentTransactionBranch). await Transactions.DependentTransactionBranch.RunAsync( () => Core.CountedSend.Process(endpoint, producer, copy, ct)).ConfigureAwait(false); } finally { // Release DI scopes early; body/headers stay alive for aggregation await copy.ReleaseScopes().ConfigureAwait(false); } return copy; }).ToList(); IExchange[] results; if (_stopOnException) { results = await Task.WhenAll(tasks).ConfigureAwait(false); } else { var settled = await Task.WhenAll(tasks.Select(async t => { try { return await t.ConfigureAwait(false); } catch (Exception ex) { var errExchange = exchange.CorrelatedCopy(); lock (copies) copies.Add(errExchange); errExchange.Exception = ex; await errExchange.ReleaseScopes().ConfigureAwait(false); return errExchange; } })).ConfigureAwait(false); results = settled.Where(r => r != null).ToArray(); } if (_aggregationStrategy != null && results.Length > 0) { var aggregated = results[0]; for (int i = 1; i < results.Length; i++) aggregated = _aggregationStrategy(aggregated, results[i]); exchange.In.Body = aggregated.In.Body; foreach (var header in aggregated.In.Headers) exchange.In.Headers[header.Key] = header.Value; } } finally { foreach (var copy in copies) if (copy is IAsyncDisposable d) await d.DisposeAsync().ConfigureAwait(false); } } private (IEndpoint Endpoint, IProducer Producer) GetOrCreateProducer(string uri) { lock (_cacheLock) { if (_producerCache.TryGetValue(uri, out var cached)) return cached; var endpoint = _context.GetEndpoint(uri); var producer = endpoint.CreateProducerOnItsSide(); _producerCache[uri] = (endpoint, producer); return (endpoint, producer); } } /// Stops all cached producers. public async ValueTask DisposeAsync() { KeyValuePair[] snapshot; lock (_cacheLock) { snapshot = _producerCache.ToArray(); _producerCache.Clear(); } foreach (var kvp in snapshot) { try { await kvp.Value.Producer.Stop().ConfigureAwait(false); } catch { // Best-effort cleanup during disposal } } } } Path: redb-route/redb.Route/Processors/ResequencerProcessor.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/ResequencerProcessor.cs ---- using redb.Route.Abstractions; namespace redb.Route.Processors; /// /// Resequences exchanges based on a sequence key, delivering them in order. /// Uses batch mode: collects exchanges until a batch is complete (by size or timeout), /// then sorts and delivers them. An active timer ensures buffered messages are flushed /// even when no new messages arrive. /// Thread-safe for concurrent pipeline usage. Implements /// to release the timer and semaphore. /// public sealed class ResequencerProcessor : IProcessor, IAsyncDisposable { private readonly IProcessor _next; private readonly Func _keySelector; private readonly int _batchSize; private readonly TimeSpan _timeout; private readonly List<(long Key, IExchange Exchange)> _buffer = []; private readonly SemaphoreSlim _bufferLock = new(1, 1); private readonly CancellationTokenSource _disposeCts = new(); private Timer? _timer; private int _disposed; /// Creates a resequencer processor. /// Next processor in the pipeline (receives ordered exchanges). /// Function to extract the sequence key (lower = earlier). /// Max exchanges before flushing the batch. /// Max time to wait for a complete batch. public ResequencerProcessor( IProcessor next, Func keySelector, int batchSize = 100, TimeSpan? timeout = null) { _next = next ?? throw new ArgumentNullException(nameof(next)); _keySelector = keySelector ?? throw new ArgumentNullException(nameof(keySelector)); if (batchSize <= 0) throw new ArgumentOutOfRangeException(nameof(batchSize)); _batchSize = batchSize; _timeout = timeout ?? TimeSpan.FromSeconds(5); } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { ObjectDisposedException.ThrowIf(_disposed != 0, this); List<(long Key, IExchange Exchange)>? toFlush = null; await _bufferLock.WaitAsync(ct).ConfigureAwait(false); try { var key = _keySelector(exchange); _buffer.Add((key, exchange)); if (_buffer.Count >= _batchSize) { toFlush = [.. _buffer]; _buffer.Clear(); StopTimer(); } else if (_buffer.Count == 1) { // First item in a new batch — start the active timer StartTimer(); } } finally { _bufferLock.Release(); } if (toFlush is not null) { await FlushBatch(toFlush, ct).ConfigureAwait(false); } } /// /// Forces a flush of any buffered exchanges. Call this when shutting down /// to process remaining exchanges. /// /// Cancellation token. public async Task Flush(CancellationToken ct = default) { List<(long Key, IExchange Exchange)>? toFlush = null; await _bufferLock.WaitAsync(ct).ConfigureAwait(false); try { if (_buffer.Count > 0) { toFlush = [.. _buffer]; _buffer.Clear(); StopTimer(); } } finally { _bufferLock.Release(); } if (toFlush is not null) { await FlushBatch(toFlush, ct).ConfigureAwait(false); } } /// Gets the number of currently buffered exchanges. public async Task GetBufferedCount(CancellationToken ct = default) { await _bufferLock.WaitAsync(ct).ConfigureAwait(false); try { return _buffer.Count; } finally { _bufferLock.Release(); } } /// public async ValueTask DisposeAsync() { if (Interlocked.Exchange(ref _disposed, 1) != 0) return; await _disposeCts.CancelAsync().ConfigureAwait(false); if (_timer is not null) await _timer.DisposeAsync().ConfigureAwait(false); _disposeCts.Dispose(); _bufferLock.Dispose(); } private void StartTimer() { // One-shot timer that fires after timeout _timer?.Change(Timeout.Infinite, Timeout.Infinite); // stop previous if any _timer ??= new Timer(OnTimerFired, null, Timeout.Infinite, Timeout.Infinite); _timer.Change(_timeout, Timeout.InfiniteTimeSpan); } private void StopTimer() { _timer?.Change(Timeout.Infinite, Timeout.Infinite); } private void OnTimerFired(object? state) { // Timer callback — flush on the thread pool. Fire-and-forget is acceptable here // because the timer is a best-effort mechanism. Exceptions from _next.Process // are set on individual exchanges. _ = Flush(_disposeCts.Token); } private async Task FlushBatch(List<(long Key, IExchange Exchange)> batch, CancellationToken ct) { // Sort by key ascending (sequence order) batch.Sort((a, b) => a.Key.CompareTo(b.Key)); foreach (var (_, exchange) in batch) { ct.ThrowIfCancellationRequested(); try { await _next.Process(exchange, ct).ConfigureAwait(false); } catch (Exception ex) { exchange.Exception = ex; } if (exchange.IsStopped) break; } } } Path: redb-route/redb.Route/Processors/ResumePoints.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/ResumePoints.cs ---- using redb.Route.Abstractions; namespace redb.Route.Processors; /// /// Where routing picks up after a failure an OnException ... Continued() handler suppressed (Apache Camel's /// continued(true)). /// /// Camel attaches its error handler to every step, so a continued failure returns to the pipeline that was running it /// and the pipeline moves on to the next step by itself. Here the handler wraps the whole route, and by the time it runs /// the stack that knew where the failure happened is gone: every pipeline the exception unwinds through records the step /// it stopped at — innermost first — and the handler replays the rest of them in that order. /// /// /// The points belong to one failure: another failure starts its own list, so a set nobody replayed cannot be taken for /// somebody else's. Work that must not be replayed — a transacted block that rolled back, a DoTry body whose /// failure was caught — is forgotten by the step that swallowed it. /// /// internal sealed class ResumePoints { /// Exchange property holding the points. Owned by the exchange: copies do not inherit it. internal const string PropertyKey = "__redb_resume"; private readonly List<(PipelineProcessor Pipeline, int NextIndex)> _points = []; private ResumePoints(Exception failure) => Failure = failure; private Exception Failure { get; } /// Remembers that stopped at minus one. internal static void Record(IExchange exchange, Exception failure, PipelineProcessor pipeline, int nextIndex) { var points = Of(exchange, failure); if (points is null) { points = new ResumePoints(failure); exchange.Properties[PropertyKey] = points; } points._points.Add((pipeline, nextIndex)); } /// /// Forgets what has been recorded for this failure so far: the steps it covers are not to be replayed. A transacted /// block that rolled back and a caught DoTry body use it — what they did is undone or deliberately abandoned. /// internal static void Forget(IExchange exchange, Exception failure) => Of(exchange, failure)?._points.Clear(); /// /// Replays the remaining steps of every pipeline the failure unwound through, innermost first. A step that fails /// again throws from here, and the caller — the route's exception handler — matches it against its handlers anew. /// internal static async Task ResumeAsync(IExchange exchange, Exception failure, CancellationToken ct) { if (Of(exchange, failure) is not { } points) return; exchange.Properties.Remove(PropertyKey); foreach (var (pipeline, nextIndex) in points._points) { if (exchange.IsStopped) break; await pipeline.ProcessFrom(exchange, nextIndex, ct).ConfigureAwait(false); } } private static ResumePoints? Of(IExchange exchange, Exception failure) => exchange.Properties.TryGetValue(PropertyKey, out var value) && value is ResumePoints points && ReferenceEquals(points.Failure, failure) ? points : null; } Path: redb-route/redb.Route/Processors/RichLogProcessor.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/RichLogProcessor.cs ---- using System.Text; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Expressions; namespace redb.Route.Processors; /// /// Rich log processor that outputs multiple messages, selected headers and properties /// in a structured format. Built by the Log(level) scope DSL. /// public class RichLogProcessor : IProcessor { private readonly ILogger _logger; private readonly LogLevel _level; private readonly IReadOnlyList _messages; private readonly IReadOnlyList> _messageFuncs; private readonly IReadOnlyList _headerNames; private readonly IReadOnlyList _propertyNames; private readonly bool _showRouteId; public RichLogProcessor( ILogger logger, LogLevel level, IReadOnlyList messages, IReadOnlyList> messageFuncs, IReadOnlyList headerNames, IReadOnlyList propertyNames, bool showRouteId) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _level = level; _messages = messages; _messageFuncs = messageFuncs; _headerNames = headerNames; _propertyNames = propertyNames; _showRouteId = showRouteId; } /// public Task Process(IExchange exchange, CancellationToken ct = default) { if (!_logger.IsEnabled(_level)) return Task.CompletedTask; var sb = new StringBuilder(); // Route ID prefix if (_showRouteId) { var routeId = exchange.RouteId; if (!string.IsNullOrEmpty(routeId)) sb.Append("[rId:").Append(routeId).Append("] "); } // Properties foreach (var name in _propertyNames) { if (exchange.Properties.TryGetValue(name, out var val)) sb.Append("[p:").Append(name).Append('=').Append(val).Append("] "); } // Headers foreach (var name in _headerNames) { if (exchange.In.Headers.TryGetValue(name, out var val)) sb.Append("[h:").Append(name).Append('=').Append(val).Append("] "); } // Static/template messages — each on its own line (like original LogProcessor) foreach (var msg in _messages) { if (msg.Contains("${", StringComparison.Ordinal)) sb.AppendLine(ExpressionResolver.ProcessTemplate(msg, exchange)); else sb.AppendLine(msg); } // Dynamic messages foreach (var func in _messageFuncs) { sb.AppendLine(func(exchange)); } // Remove trailing newline var logStr = sb.ToString(); if (logStr.EndsWith(Environment.NewLine)) logStr = logStr[..^Environment.NewLine.Length]; #pragma warning disable CA2254 _logger.Log(_level, "{Message}", logStr); #pragma warning restore CA2254 return Task.CompletedTask; } } Path: redb-route/redb.Route/Processors/RoutePolicyProcessor.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/RoutePolicyProcessor.cs ---- using redb.Route.Abstractions; namespace redb.Route.Processors; /// /// Wraps a pipeline processor with / /// calls. Only created for routes that have a policy. /// internal sealed class RoutePolicyProcessor : IProcessor { private readonly IProcessor _next; private readonly IRoutePolicy _policy; private readonly IRouteContext _context; public RoutePolicyProcessor(IProcessor next, IRoutePolicy policy, IRouteContext context) { _next = next; _policy = policy; _context = context; } public async Task Process(IExchange exchange, CancellationToken ct = default) { await _policy.OnExchangeBegin(_context, exchange, ct).ConfigureAwait(false); try { await _next.Process(exchange, ct).ConfigureAwait(false); } finally { await _policy.OnExchangeDone(_context, exchange, ct).ConfigureAwait(false); } } } Path: redb-route/redb.Route/Processors/RoutingSlipProcessor.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/RoutingSlipProcessor.cs ---- using System.Collections.Concurrent; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Processors; /// /// Routing Slip EIP: routes the exchange through a list of endpoints that is computed once /// up front (the "slip"), then piped through sequentially. This is the static counterpart of the /// Dynamic Router (), which recomputes the next hop after every /// step — mirroring Apache Camel, where "the Routing Slip will compute the slip beforehand … only /// computed once". /// /// Between hops the exchange is threaded with Pipeline semantics (the Out of one hop becomes /// the In of the next), exactly like ; the final hop's /// Out is left intact so an InOut caller / RPC reply still receives it. Producers are cached /// per resolved URI and registered with the context for graceful shutdown. /// /// internal sealed class RoutingSlipProcessor : IProcessor, IAsyncDisposable { /// /// Exchange property carrying the endpoint currently being processed as the slip advances /// (Camel parity: CamelSlipEndpoint). /// public const string SlipEndpointProperty = ExchangePropertyKeys.SlipEndpoint; private readonly IRouteContext _context; private readonly Func> _slipFactory; private readonly bool _ignoreInvalidEndpoints; private readonly ILogger? _logger; private readonly ConcurrentDictionary _producerCache = new(StringComparer.Ordinal); public RoutingSlipProcessor( IRouteContext context, Func> slipFactory, bool ignoreInvalidEndpoints = false, ILogger? logger = null) { _context = context ?? throw new ArgumentNullException(nameof(context)); _slipFactory = slipFactory ?? throw new ArgumentNullException(nameof(slipFactory)); _ignoreInvalidEndpoints = ignoreInvalidEndpoints; _logger = logger; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { // The slip is evaluated ONCE (Routing Slip, not Dynamic Router). var uris = _slipFactory(exchange).ToList(); if (uris.Count == 0) return; for (var i = 0; i < uris.Count; i++) { ct.ThrowIfCancellationRequested(); if (exchange.IsStopped) break; var uri = uris[i]; (IEndpoint Endpoint, IProducer Producer) pair; try { pair = await GetOrCreatePairAsync(uri, ct).ConfigureAwait(false); } catch (Exception ex) when (_ignoreInvalidEndpoints) { _logger?.LogWarning(ex, "Routing Slip: ignoring invalid endpoint '{Uri}'", EndpointUri.Sanitize(uri)); continue; } exchange.Properties[SlipEndpointProperty] = uri; _logger?.LogDebug("Routing Slip: hop {Hop}/{Total} → {Uri}", i + 1, uris.Count, EndpointUri.Sanitize(uri)); await Core.CountedSend.Process(pair.Endpoint, pair.Producer, exchange, ct).ConfigureAwait(false); // Pipeline EIP: the Out of an intermediate hop becomes the In of the next; the final // hop's Out is left intact for an InOut caller (direct-vm / replyTo / RPC). if (exchange.HasOut && i < uris.Count - 1) { var outMsg = exchange.Out!; exchange.In.Body = outMsg.Body; exchange.In.ContentType = outMsg.ContentType; foreach (var (key, value) in outMsg.Headers) exchange.In.Headers[key] = value; exchange.Out = null; // prevent a stale Out from re-merging on the next hop } } } private async Task<(IEndpoint Endpoint, IProducer Producer)> GetOrCreatePairAsync(string uri, CancellationToken ct) { if (_producerCache.TryGetValue(uri, out var cached)) return cached; var endpoint = _context.GetEndpoint(uri); var producer = endpoint.CreateProducerOnItsSide(); await producer.Start(ct).ConfigureAwait(false); (_context as RouteContext)?.TrackProducer(producer); if (!_producerCache.TryAdd(uri, (endpoint, producer))) { // Lost the race — stop our duplicate and use the one already cached. await producer.Stop(ct).ConfigureAwait(false); return _producerCache[uri]; } return (endpoint, producer); } /// Stops all cached producers (best-effort). public async ValueTask DisposeAsync() { foreach (var kvp in _producerCache) { try { await kvp.Value.Producer.Stop().ConfigureAwait(false); } catch { /* best-effort cleanup during disposal */ } } _producerCache.Clear(); } } Path: redb-route/redb.Route/Processors/SagaProcessor.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/SagaProcessor.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Definitions; using redb.Route.Telemetry; namespace redb.Route.Processors; /// /// Executes saga steps sequentially. On failure, runs compensations in reverse order /// for all completed steps. Compensation failures are logged but do not interrupt rollback. /// After all steps succeed, invokes the optional completion callback. /// internal sealed class SagaProcessor : IProcessor { private readonly SagaStepEntry[] _steps; private readonly Func? _onCompletion; private readonly ILogger? _logger; public SagaProcessor( SagaStepEntry[] steps, Func? onCompletion = null, ILogger? logger = null) { _steps = steps; _onCompletion = onCompletion; _logger = logger; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { var completedCount = 0; var compensationFailed = false; try { for (var i = 0; i < _steps.Length; i++) { ct.ThrowIfCancellationRequested(); await _steps[i].Action(exchange, ct).ConfigureAwait(false); completedCount++; } } catch (Exception ex) when (ex is not OperationCanceledException) { _logger?.LogWarning(ex, "Saga step {StepIndex} failed, compensating {CompletedCount} step(s)", completedCount, completedCount); // Run compensations in reverse order for all completed steps for (var i = completedCount - 1; i >= 0; i--) { var compensate = _steps[i].Compensate; if (compensate is null) continue; try { await compensate(exchange, ct).ConfigureAwait(false); } catch (Exception compEx) { compensationFailed = true; _logger?.LogError(compEx, "Saga compensation for step {StepIndex} failed", i); } } if (compensationFailed) ProcessorMetrics.SagaFailed.Add(1); else ProcessorMetrics.SagaCompensated.Add(1); throw; } ProcessorMetrics.SagaCompleted.Add(1); // All steps succeeded — invoke completion callback if present if (_onCompletion is not null) await _onCompletion(exchange, ct).ConfigureAwait(false); } } Path: redb-route/redb.Route/Processors/SamplingProcessor.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/SamplingProcessor.cs ---- using redb.Route.Abstractions; namespace redb.Route.Processors; /// /// Samples messages from the stream, allowing only a subset to pass through. /// Supports two modes: count-based (every Nth message) and time-based (at most one per period). /// Non-sampled messages are stopped via . /// Thread-safe via lock-free atomic operations. /// public class SamplingProcessor : IProcessor { private readonly long _messageFrequency; private readonly long _periodTicks; private long _counter; private long _lastSampledTicks; /// Creates a count-based sampler that passes every Nth message. /// Pass every Nth message (1 = all, 5 = every 5th). public SamplingProcessor(long messageFrequency) { if (messageFrequency < 1) throw new ArgumentOutOfRangeException(nameof(messageFrequency), "Must be >= 1."); _messageFrequency = messageFrequency; } /// Creates a time-based sampler that passes at most one message per period. /// Minimum interval between sampled messages. public SamplingProcessor(TimeSpan period) { if (period <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(period), "Must be positive."); _periodTicks = period.Ticks; } /// public Task Process(IExchange exchange, CancellationToken ct = default) { if (_messageFrequency > 0) ProcessCountBased(exchange); else ProcessTimeBased(exchange); return Task.CompletedTask; } private void ProcessCountBased(IExchange exchange) { var count = Interlocked.Increment(ref _counter); // Pass first message and every Nth after that: 1, 1+N, 1+2N, ... if ((count - 1) % _messageFrequency != 0) exchange.Stop(); } private void ProcessTimeBased(IExchange exchange) { var now = DateTime.UtcNow.Ticks; var last = Interlocked.Read(ref _lastSampledTicks); if (now - last < _periodTicks) { exchange.Stop(); return; } // CAS: only one thread wins the race to sample if (Interlocked.CompareExchange(ref _lastSampledTicks, now, last) != last) exchange.Stop(); } } Path: redb-route/redb.Route/Processors/ScatterGatherProcessor.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/ScatterGatherProcessor.cs ---- using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Processors; /// /// Processor for the Scatter-Gather EIP pattern. /// Sends the exchange to multiple endpoints (scatter phase), collects all responses, /// and aggregates them using a mandatory pair-wise strategy (gather phase). /// Supports static and dynamic recipient lists, parallel/sequential processing, /// timeout with partial-result aggregation, and configurable error handling. /// public sealed class ScatterGatherProcessor : IProcessor, IAsyncDisposable { private readonly IRouteContext _context; private readonly IReadOnlyList? _staticRecipients; private readonly Func>? _dynamicRecipients; private readonly Func _aggregationStrategy; private readonly TimeSpan _timeout; private readonly bool _parallelProcessing; private readonly bool _stopOnException; private readonly int _maxDegreeOfParallelism; private readonly ILogger? _logger; private readonly ConcurrentDictionary> _producerCache = new(StringComparer.Ordinal); /// /// Creates a scatter-gather processor with static recipients. /// /// Route context for endpoint resolution. /// Fixed list of endpoint URIs to scatter to. /// Pair-wise aggregation: (accumulated, current) → merged. /// Whether to send to all recipients in parallel. /// Max concurrent sends (0 = processor count). /// Whether to stop on the first error (true) or aggregate partial results (false). /// Timeout for the entire operation (TimeSpan.Zero = no timeout). /// Optional logger. public ScatterGatherProcessor( IRouteContext context, IReadOnlyList recipients, Func aggregationStrategy, bool parallelProcessing = true, int maxDegreeOfParallelism = 0, bool stopOnException = false, TimeSpan timeout = default, ILogger? logger = null) { _context = context ?? throw new ArgumentNullException(nameof(context)); ArgumentNullException.ThrowIfNull(recipients); if (recipients.Count == 0) throw new ArgumentException("At least one recipient is required.", nameof(recipients)); _staticRecipients = recipients; foreach (var recipient in recipients) (context as RouteContext)?.NoteStaticEndpoint(recipient); _dynamicRecipients = null; _aggregationStrategy = aggregationStrategy ?? throw new ArgumentNullException(nameof(aggregationStrategy)); _parallelProcessing = parallelProcessing; _maxDegreeOfParallelism = maxDegreeOfParallelism; _stopOnException = stopOnException; _timeout = timeout >= TimeSpan.Zero ? timeout : throw new ArgumentOutOfRangeException(nameof(timeout)); _logger = logger; } /// /// Creates a scatter-gather processor with dynamic recipients resolved at runtime. /// /// Route context for endpoint resolution. /// Function that returns target URIs from the exchange. /// Pair-wise aggregation: (accumulated, current) → merged. /// Whether to send to all recipients in parallel. /// Max concurrent sends (0 = processor count). /// Whether to stop on the first error (true) or aggregate partial results (false). /// Timeout for the entire operation (TimeSpan.Zero = no timeout). /// Optional logger. public ScatterGatherProcessor( IRouteContext context, Func> recipientFactory, Func aggregationStrategy, bool parallelProcessing = true, int maxDegreeOfParallelism = 0, bool stopOnException = false, TimeSpan timeout = default, ILogger? logger = null) { _context = context ?? throw new ArgumentNullException(nameof(context)); _staticRecipients = null; _dynamicRecipients = recipientFactory ?? throw new ArgumentNullException(nameof(recipientFactory)); _aggregationStrategy = aggregationStrategy ?? throw new ArgumentNullException(nameof(aggregationStrategy)); _parallelProcessing = parallelProcessing; _maxDegreeOfParallelism = maxDegreeOfParallelism; _stopOnException = stopOnException; _timeout = timeout >= TimeSpan.Zero ? timeout : throw new ArgumentOutOfRangeException(nameof(timeout)); _logger = logger; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(exchange); IReadOnlyList recipients = _staticRecipients ?? (IReadOnlyList)_dynamicRecipients!(exchange).ToList(); if (recipients.Count == 0) throw new InvalidOperationException("Scatter-gather requires at least one recipient."); _logger?.LogDebug("Scatter-gather: dispatching to {Count} recipients", recipients.Count); using var timeoutCts = _timeout > TimeSpan.Zero ? CancellationTokenSource.CreateLinkedTokenSource(ct) : null; timeoutCts?.CancelAfter(_timeout); var effectiveCt = timeoutCts?.Token ?? ct; try { if (_parallelProcessing) await ProcessParallel(exchange, recipients, effectiveCt, ct).ConfigureAwait(false); else await ProcessSequential(exchange, recipients, effectiveCt, ct).ConfigureAwait(false); } // Wraps timeout-only OCE into TimeoutException. // In best-effort mode, timeout is handled internally (partial results aggregated) // so this catch only fires in stopOnException mode. catch (OperationCanceledException) when (_timeout > TimeSpan.Zero && !ct.IsCancellationRequested) { // Timeout reached with stopOnException — wrap in TimeoutException throw new TimeoutException($"Scatter-gather timed out after {_timeout}."); } } private async Task ProcessSequential( IExchange exchange, IReadOnlyList recipients, CancellationToken ct, CancellationToken callerCt) { IExchange? aggregated = null; var clones = new List(recipients.Count); try { foreach (var uri in recipients) { ct.ThrowIfCancellationRequested(); var clone = exchange.CorrelatedCopyLinked(); clones.Add(clone); try { var producer = GetOrCreateProducer(uri); await producer.Process(clone, ct).ConfigureAwait(false); aggregated = aggregated is null ? clone : _aggregationStrategy(aggregated, clone); _logger?.LogDebug("Scatter-gather: received response from {Endpoint}", EndpointUri.Sanitize(uri)); } catch (OperationCanceledException) when (!callerCt.IsCancellationRequested && !_stopOnException) { // Timeout in best-effort mode — aggregate partial results collected so far _logger?.LogWarning( "Scatter-gather: timed out, aggregating partial results"); break; } catch (OperationCanceledException) { throw; } catch (Exception ex) { if (_stopOnException) throw; clone.Exception = ex; _logger?.LogWarning(ex, "Scatter-gather: endpoint {Endpoint} failed", EndpointUri.Sanitize(uri)); aggregated = aggregated is null ? clone : _aggregationStrategy(aggregated, clone); } } ApplyAggregation(exchange, aggregated); } finally { foreach (var clone in clones) if (clone is IAsyncDisposable d) await d.DisposeAsync().ConfigureAwait(false); } } private async Task ProcessParallel( IExchange exchange, IReadOnlyList recipients, CancellationToken ct, CancellationToken callerCt) { var clones = new IExchange?[recipients.Count]; try { var maxDop = _maxDegreeOfParallelism > 0 ? _maxDegreeOfParallelism : Environment.ProcessorCount; using var semaphore = new SemaphoreSlim(maxDop); async Task SendToRecipient(int index) { await semaphore.WaitAsync(ct).ConfigureAwait(false); try { var clone = exchange.CorrelatedCopy(); clones[index] = clone; var producer = GetOrCreateProducer(recipients[index]); // Concurrent branches never share one Transaction.Current: each runs under a dependent clone of the // route's transaction, as a parallel Multicast or Split does (see DependentTransactionBranch). await Transactions.DependentTransactionBranch.RunAsync(() => producer.Process(clone, ct)).ConfigureAwait(false); _logger?.LogDebug("Scatter-gather: received response from {Endpoint}", EndpointUri.Sanitize(recipients[index])); return clone; } finally { // Release DI scopes early; body/headers stay alive for aggregation if (clones[index] != null) await clones[index]!.ReleaseScopes().ConfigureAwait(false); semaphore.Release(); } } var tasks = Enumerable.Range(0, recipients.Count) .Select(SendToRecipient) .ToList(); IExchange?[] results; if (_stopOnException) { results = await Task.WhenAll(tasks).ConfigureAwait(false); } else { // Best-effort: collect completed results, handle failures/timeouts gracefully results = await Task.WhenAll(tasks.Select(async (t, index) => { try { return await t.ConfigureAwait(false); } catch (OperationCanceledException) when (!callerCt.IsCancellationRequested) { // Timeout — skip this result _logger?.LogWarning("Scatter-gather: endpoint {Endpoint} timed out", EndpointUri.Sanitize(recipients[index])); return null; } catch (OperationCanceledException) { throw; } catch (Exception ex) when (ex is not OutOfMemoryException) { var clone = clones[index] ?? exchange.CorrelatedCopy(); clones[index] = clone; clone.Exception = ex; _logger?.LogWarning(ex, "Scatter-gather: endpoint {Endpoint} failed", EndpointUri.Sanitize(recipients[index])); return clone; } })).ConfigureAwait(false); } // Aggregate in deterministic index order IExchange? aggregated = null; foreach (var result in results) { if (result == null) continue; aggregated = aggregated is null ? result : _aggregationStrategy(aggregated, result); } ApplyAggregation(exchange, aggregated); } finally { foreach (var clone in clones) if (clone is IAsyncDisposable d) await d.DisposeAsync().ConfigureAwait(false); } } /// /// Copies aggregated body, headers, and properties back to the original exchange. /// private static void ApplyAggregation(IExchange original, IExchange? aggregated) { if (aggregated == null) return; original.In.Body = aggregated.In.Body; foreach (var header in aggregated.In.Headers) original.In.Headers[header.Key] = header.Value; foreach (var prop in aggregated.Properties) { // The clone's own bookkeeping (cached DI scopes, registered resources) stays with the clone, which // releases it right after this merge; copying it here would leave the original a disposed scope. // The branch's correlation id points at the original; the original keeps its own, as in Camel. if (ExchangeResources.IsOwnedByExchange(prop.Key) || prop.Key == ExchangePropertyKeys.CorrelationId) continue; original.Properties[prop.Key] = prop.Value; } } private ToProcessor GetOrCreateProducer(string endpoint) { return _producerCache.GetOrAdd(endpoint, ep => new Lazy(() => new ToProcessor(ep, _context))).Value; } /// /// Stops all cached producers and clears the cache. /// public async ValueTask DisposeAsync() { List? errors = null; foreach (var lazy in _producerCache.Values) { if (lazy.IsValueCreated) { try { await lazy.Value.StopProducerAsync().ConfigureAwait(false); } catch (Exception ex) { errors ??= []; errors.Add(ex); } } } _producerCache.Clear(); if (errors != null) throw new AggregateException("One or more producers failed to stop.", errors); } } Path: redb-route/redb.Route/Processors/SplitterProcessor.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/SplitterProcessor.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; using redb.Route.Transactions; namespace redb.Route.Processors; /// /// Splits a single exchange into multiple exchanges based on a splitter function. /// Each resulting part is processed individually by the inner processor. /// Supports parallel processing, aggregation strategy, stopOnException, timeout, /// and configurable concurrency — matching the full feature set of lt.Core.Route. /// public class SplitterProcessor : IProcessor { private readonly Func> _splitter; private readonly IProcessor _target; private readonly bool _parallelProcessing; private readonly int _maxDegreeOfParallelism; private readonly Func? _aggregationStrategy; private readonly bool _stopOnException; private readonly TimeSpan _timeout; private readonly bool _parallelAggregate; private readonly bool _aggregateOnException; /// Creates a splitter processor. /// Function that splits the exchange body into parts. /// Processor to handle each split exchange. /// Whether to process parts in parallel. /// Maximum concurrent tasks when parallel (0 = unlimited). /// /// Optional pair-wise aggregation: (oldExchange, newExchange) → merged. /// /// Camel-compatible contract: for the first part is invoked /// with oldExchange == null, so the strategy can perform a seed/wrap (e.g. wrap into a list, set a marker header). /// Strategies must explicitly handle the null-old case — there is no implicit assign-first fallback. /// /// /// Whether to stop on the first exception. /// Timeout for the entire split operation (TimeSpan.Zero = no timeout). /// /// When true together with , the aggregation strategy is invoked /// inline from each worker task under an internal lock instead of by a single deterministic post-pass. /// The strategy MUST be thread-safe. Order of pair-wise calls is non-deterministic. /// /// /// When true, split exchanges that failed (target threw) are still fed into the aggregation /// strategy. Useful for collecting error info into the aggregated result. Default false /// preserves Camel default (failed parts excluded from aggregate). /// public SplitterProcessor( Func> splitter, IProcessor target, bool parallelProcessing = false, int maxDegreeOfParallelism = 0, Func? aggregationStrategy = null, bool stopOnException = true, TimeSpan timeout = default, bool parallelAggregate = false, bool aggregateOnException = false) { _splitter = splitter ?? throw new ArgumentNullException(nameof(splitter)); _target = target ?? throw new ArgumentNullException(nameof(target)); _parallelProcessing = parallelProcessing; _maxDegreeOfParallelism = maxDegreeOfParallelism > 0 ? maxDegreeOfParallelism : Environment.ProcessorCount; _aggregationStrategy = aggregationStrategy; _stopOnException = stopOnException; _timeout = timeout; _parallelAggregate = parallelAggregate; _aggregateOnException = aggregateOnException; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { var parts = _splitter(exchange).ToArray(); if (parts.Length == 0) return; ProcessorMetrics.SplitterParts.Add(parts.Length); using var timeoutCts = _timeout > TimeSpan.Zero ? CancellationTokenSource.CreateLinkedTokenSource(ct) : null; if (timeoutCts != null) timeoutCts.CancelAfter(_timeout); var effectiveCt = timeoutCts?.Token ?? ct; try { if (_parallelProcessing) await ProcessParallel(exchange, parts, effectiveCt).ConfigureAwait(false); else await ProcessSequential(exchange, parts, effectiveCt).ConfigureAwait(false); } catch (OperationCanceledException) when (timeoutCts != null && timeoutCts.IsCancellationRequested && !ct.IsCancellationRequested) { throw new TimeoutException($"Split processing timed out after {_timeout.TotalMilliseconds} ms."); } } private async Task ProcessSequential(IExchange exchange, object?[] parts, CancellationToken ct) { IExchange? aggregated = null; Exception? firstException = null; var splitExchanges = new List(parts.Length); try { for (var i = 0; i < parts.Length; i++) { ct.ThrowIfCancellationRequested(); if (exchange.IsStopped) break; var splitExchange = CreateSplitExchange(exchange, parts[i], i, parts.Length, i == parts.Length - 1, linked: true); splitExchanges.Add(splitExchange); try { await _target.Process(splitExchange, ct).ConfigureAwait(false); if (_aggregationStrategy != null) { // S1: Camel-compatible — strategy is invoked even for the first part // with oldExchange == null so it can perform a seed/wrap. aggregated = _aggregationStrategy(aggregated, splitExchange); } } catch (OperationCanceledException) { throw; } catch (Exception ex) { firstException ??= ex; // The branch's own record of its failure, as Multicast and RecipientList keep it: its unit of work // ends with the branch and reads the outcome from it. splitExchange.Exception = ex; // S4: aggregateOnException — include failed split exchange into aggregate if (_aggregateOnException && _aggregationStrategy != null) { aggregated = _aggregationStrategy(aggregated, splitExchange); } if (_stopOnException) { exchange.Exception = ex; break; } } } // S2: when stopOnException fired, do NOT publish the partial aggregate to parent if (!(_stopOnException && firstException != null)) ApplyAggregation(exchange, aggregated); } finally { foreach (var se in splitExchanges) if (se is IAsyncDisposable d) await d.DisposeAsync().ConfigureAwait(false); } if (firstException != null && _stopOnException) throw firstException; } private async Task ProcessParallel(IExchange exchange, object?[] parts, CancellationToken ct) { var results = new IExchange?[parts.Length]; var exceptions = new Exception?[parts.Length]; var shouldStop = 0; // Interlocked flag // S3: state for in-task ("parallel") aggregation under lock var aggLock = new object(); IExchange? parallelAggregated = null; using var semaphore = new SemaphoreSlim(_maxDegreeOfParallelism); var splitExchanges = new IExchange?[parts.Length]; var tasks = new Task[parts.Length]; for (var i = 0; i < parts.Length; i++) { var idx = i; tasks[idx] = Task.Run(async () => { if (Volatile.Read(ref shouldStop) == 1) return; await semaphore.WaitAsync(ct).ConfigureAwait(false); try { if (Volatile.Read(ref shouldStop) == 1) return; var splitExchange = CreateSplitExchange(exchange, parts[idx], idx, parts.Length, idx == parts.Length - 1, linked: false); splitExchanges[idx] = splitExchange; var succeeded = false; try { // Isolate this branch under a dependent clone of the ambient transaction so // concurrent branches never share one Transaction.Current (see DependentTransactionBranch). await DependentTransactionBranch.RunAsync(() => _target.Process(splitExchange, ct)).ConfigureAwait(false); results[idx] = splitExchange; succeeded = true; } catch (OperationCanceledException) { throw; } catch (Exception ex) { exceptions[idx] = ex; splitExchange.Exception = ex; if (_stopOnException) { Interlocked.Exchange(ref shouldStop, 1); } } finally { // S3 + S4: when parallelAggregate is enabled, aggregate inline under lock if (_parallelAggregate && _aggregationStrategy != null && (succeeded || _aggregateOnException)) { lock (aggLock) { parallelAggregated = _aggregationStrategy(parallelAggregated, splitExchange); } } // Release DI scopes early; body/headers stay alive for aggregation await splitExchange.ReleaseScopes().ConfigureAwait(false); } } finally { semaphore.Release(); } }, ct); } try { await Task.WhenAll(tasks).ConfigureAwait(false); var allExceptions = exceptions.Where(e => e != null).Cast().ToArray(); var hasErrors = allExceptions.Length > 0; // S2: do not apply partial aggregate when stopOnException fired if (_aggregationStrategy != null && !(_stopOnException && hasErrors)) { if (_parallelAggregate) { ApplyAggregation(exchange, parallelAggregated); } else { // Deterministic post-pass aggregation (in index order) IExchange? aggregated = null; for (var i = 0; i < results.Length; i++) { var part = results[i]; if (part == null) { // S4: include failed split exchanges if requested if (_aggregateOnException && exceptions[i] != null && splitExchanges[i] != null) part = splitExchanges[i]; else continue; } // S1: strategy invoked for the first part with oldExchange == null aggregated = _aggregationStrategy(aggregated, part); } ApplyAggregation(exchange, aggregated); } } if (hasErrors) { exchange.Exception = allExceptions.Length == 1 ? allExceptions[0] : new AggregateException("Multiple split targets failed.", allExceptions); if (_stopOnException) throw allExceptions[0]; } } finally { foreach (var se in splitExchanges) if (se is IAsyncDisposable d) await d.DisposeAsync().ConfigureAwait(false); } } /// /// Builds the exchange of one part, as Camel's Splitter: an element becomes the part's message /// (a copy, so the parent's collection stays as it was) without the parent's headers; any other element becomes the /// body under the parent's headers and attachments. Index, size and completion are exchange properties of the part, /// and the part's correlation id is the parent's exchange id. total is null when a streaming split does not /// know it yet. /// internal static IExchange CreateSplitExchange( IExchange original, object? part, int index, int? total, bool complete, bool linked) { IMessage splitMessage; if (part is IMessage element) { splitMessage = element.Clone(); } else { splitMessage = new Message(part); foreach (var header in original.In.Headers) splitMessage.Headers[header.Key] = header.Value; // and the attachments, as Camel's split copies the exchange: every part carries them, content shared. MessageAttachments.CopyInto(original.In, splitMessage); } var splitExchange = linked ? original.CreateLinkedChild(splitMessage) : original.CreateChild(splitMessage); splitExchange.Properties[ExchangePropertyKeys.SplitIndex] = index; if (total is { } size) splitExchange.Properties[ExchangePropertyKeys.SplitSize] = size; else splitExchange.Properties.Remove(ExchangePropertyKeys.SplitSize); // an enclosing split's size is not ours splitExchange.Properties[ExchangePropertyKeys.SplitComplete] = complete; splitExchange.Properties[ExchangePropertyKeys.CorrelationId] = original.ExchangeId; return splitExchange; } private static void ApplyAggregation(IExchange original, IExchange? aggregated) { if (aggregated == null) return; original.In.Body = aggregated.In.Body; // Copy headers from aggregated result foreach (var header in aggregated.In.Headers) original.In.Headers[header.Key] = header.Value; // Copy properties from aggregated result foreach (var prop in aggregated.Properties) { // The clone's own bookkeeping (cached DI scopes, registered resources) stays with the clone, which // releases it right after this merge; copying it here would leave the original a disposed scope. // The part's correlation id points at the original; the original keeps its own, as in Camel. if (ExchangeResources.IsOwnedByExchange(prop.Key) || prop.Key == ExchangePropertyKeys.CorrelationId) continue; original.Properties[prop.Key] = prop.Value; } } } Path: redb-route/redb.Route/Processors/StreamCachingProcessor.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/StreamCachingProcessor.cs ---- using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; namespace redb.Route.Processors; /// /// Wraps a forward-only Stream body with a seekable , /// allowing downstream processors to re-read the body multiple times. /// Non-Stream bodies pass through unchanged. /// internal sealed class StreamCachingProcessor : IProcessor { private readonly IProcessor _next; private readonly StreamCacheOptions _options; /// Creates a stream caching processor. /// The next processor in the pipeline. /// Stream cache options (spool threshold, temp directory). internal StreamCachingProcessor(IProcessor next, StreamCacheOptions options) { ArgumentNullException.ThrowIfNull(next); ArgumentNullException.ThrowIfNull(options); _next = next; _options = options; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { await StreamCacheBody.CacheAsync(exchange, _options, ct).ConfigureAwait(false); await _next.Process(exchange, ct).ConfigureAwait(false); } } /// /// Standalone (no-next) variant of stream caching, suitable for use as a /// leaf inside a . /// Wraps a forward-only body with a seekable ; /// the pipeline advances to the next step automatically. /// Non-Stream bodies pass through unchanged. /// internal sealed class StreamCachingTransformer : IProcessor { private readonly StreamCacheOptions _options; internal StreamCachingTransformer(StreamCacheOptions options) { ArgumentNullException.ThrowIfNull(options); _options = options; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { await StreamCacheBody.CacheAsync(exchange, _options, ct).ConfigureAwait(false); } } /// The one place a stream body is replaced by its cache. internal static class StreamCacheBody { /// /// Replaces a forward-only stream body with a and closes the source: the exchange owns its /// body and disposes only what the body is, so a replaced stream nobody closes would hold its file or connection /// until the garbage collector ran (a streamed file the consumer then fails to delete). Camel closes the source too. /// public static async Task CacheAsync(IExchange exchange, StreamCacheOptions options, CancellationToken ct) { if (exchange.In.Body is not Stream stream || stream is StreamCache) return; var cache = new StreamCache(options); try { await cache.CacheFromSourceAsync(stream, ct).ConfigureAwait(false); } catch { // Not cached: the body stays the source, and the half-written cache goes. await cache.DisposeAsync().ConfigureAwait(false); throw; } exchange.In.Body = cache; await stream.DisposeAsync().ConfigureAwait(false); } } 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; } } 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(); } } Path: redb-route/redb.Route/Processors/ThrottleProcessor.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/ThrottleProcessor.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Telemetry; namespace redb.Route.Processors; /// /// Limits the rate of exchange processing using a fixed-rate token release. /// Thread-safe for concurrent pipeline usage. Disposable — call /// to cancel pending slot-release timers on shutdown. /// /// Two overflow modes (selected via the rejectOnOverflow constructor flag): /// /// /// false (default, legacy) — semaphore-wait until a slot frees; the calling /// exchange is blocked but eventually proceeds. Preserves backward compatibility. /// true (RFC 6585) — reject overflow exchanges immediately with HTTP 429 /// Too Many Requests and a Retry-After header (RFC 7231 §7.1.3) set to the /// current rate-limit period. Strongly recommended for any HTTP-facing endpoint so /// the client can back off explicitly instead of seeing what looks like a hung server. /// /// public sealed class ThrottleProcessor : IProcessor, IDisposable { private readonly IProcessor _next; private readonly Func _maxPerPeriod; private readonly TimeSpan _period; private readonly bool _rejectOnOverflow; private readonly CancellationTokenSource _disposeCts = new(); private readonly ILogger? _logger; private int _disposed; // The gate. A semaphore cannot change capacity per exchange, so the window is tracked by // hand: how many slots are occupied, and who is waiting for one. Waiters are served in // arrival order; each carries the limit its own exchange evaluated to. private readonly object _gate = new(); private int _occupied; private readonly Queue<(int Limit, TaskCompletionSource Slot)> _waiters = new(); /// No slot occupied and nobody waiting — a per-key gate in this state can be evicted. internal bool IsIdle { get { lock (_gate) return _occupied == 0 && _waiters.Count == 0; } } /// Creates a throttle processor with a fixed limit. /// Next processor in the pipeline. /// Maximum number of exchanges allowed in the time period. /// Time period for the rate limit (default: 1 second). /// When true, exchanges that exceed the rate limit are /// short-circuited with HTTP 429 + Retry-After instead of waiting. /// Optional logger. public ThrottleProcessor( IProcessor next, int maxPerPeriod, TimeSpan? period = null, bool rejectOnOverflow = false, ILogger? logger = null) : this(next, _ => maxPerPeriod, period, rejectOnOverflow, logger) { if (maxPerPeriod <= 0) throw new ArgumentOutOfRangeException(nameof(maxPerPeriod), "Must be > 0."); } /// /// Creates a throttle processor whose limit is computed per exchange. The factory runs on /// every message, so the limit can come from a header, a property or an expression and change /// between messages, as the Apache Camel throttler does with a dynamic expression. /// /// Next processor in the pipeline. /// Computes the maximum number of exchanges allowed in the period /// for the given exchange. Must return a positive number; anything else fails that exchange /// loudly rather than silently letting everything through. /// Time period for the rate limit (default: 1 second). /// When true, exchanges that exceed the rate limit are /// short-circuited with HTTP 429 + Retry-After instead of waiting. /// Optional logger. public ThrottleProcessor( IProcessor next, Func maxPerPeriod, TimeSpan? period = null, bool rejectOnOverflow = false, ILogger? logger = null) { _next = next ?? throw new ArgumentNullException(nameof(next)); _maxPerPeriod = maxPerPeriod ?? throw new ArgumentNullException(nameof(maxPerPeriod)); _period = period ?? TimeSpan.FromSeconds(1); _rejectOnOverflow = rejectOnOverflow; _logger = logger; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { ObjectDisposedException.ThrowIf(_disposed != 0, this); var limit = _maxPerPeriod(exchange); if (limit <= 0) throw new InvalidOperationException( $"Throttle limit evaluated to {limit} for this exchange; it must be a positive number."); // Non-blocking probe so we can choose between rejection and waiting without // holding a slot speculatively. if (!TryAcquire(limit)) { ProcessorMetrics.ThrottleDelayed.Add(1); if (_rejectOnOverflow) { _logger?.LogDebug("Throttle: rejecting overflow with 429 (RFC 6585)."); ThrottleRejection.Apply(exchange, _period); return; } _logger?.LogDebug("Throttle: exchange delayed (all {Max} slots occupied).", limit); await WaitForSlotAsync(limit, ct).ConfigureAwait(false); } try { await _next.Process(exchange, ct).ConfigureAwait(false); } finally { ScheduleSlotRelease(); } } /// Cancels pending slot-release timers and wakes every waiter with a cancellation. public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) != 0) return; _disposeCts.Cancel(); _disposeCts.Dispose(); lock (_gate) { while (_waiters.Count > 0) _waiters.Dequeue().Slot.TrySetCanceled(); } } private bool TryAcquire(int limit) { lock (_gate) { // Arrival order is honoured: a newcomer does not overtake a queued exchange even if // its own limit would allow it in right now. if (_waiters.Count == 0 && _occupied < limit) { _occupied++; return true; } return false; } } private async Task WaitForSlotAsync(int limit, CancellationToken ct) { var slot = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); lock (_gate) { _waiters.Enqueue((limit, slot)); } using var registration = ct.Register(static state => ((TaskCompletionSource)state!).TrySetCanceled(), slot); try { await slot.Task.ConfigureAwait(false); } catch (OperationCanceledException) { // The slot may have been granted just before cancellation won the race; give it back. lock (_gate) { if (slot.Task.IsCompletedSuccessfully) _occupied--; } throw; } } private void ScheduleSlotRelease() { // Disposed while a message was in flight (a keyed gate evicted, a route stopped): there is no // window left to release into, and the token source is gone. if (Volatile.Read(ref _disposed) != 0) return; CancellationToken token; try { token = _disposeCts.Token; } catch (ObjectDisposedException) { return; } _ = Task.Delay(_period, token).ContinueWith(_ => ReleaseSlot(), CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default); } private void ReleaseSlot() { lock (_gate) { _occupied--; // Hand the freed capacity to the head of the queue, and keep going while the next // waiter's own limit still has room: after a larger limit arrives several may fit. while (_waiters.Count > 0 && _occupied < _waiters.Peek().Limit) { var (_, slot) = _waiters.Dequeue(); if (slot.TrySetResult(true)) _occupied++; } } } } Path: redb-route/redb.Route/Processors/ThrottleRejection.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/ThrottleRejection.cs ---- using System.Globalization; using System.Text; using System.Text.Json; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Processors; /// /// Applies an RFC 6585 §4 "429 Too Many Requests" short-circuit to an exchange. Shared /// by and when their /// rejectOnOverflow flag is set. /// /// Writes a small OAuth-style JSON body (error / error_description / /// retry_after), a Retry-After response header (RFC 7231 §7.1.3 delta-seconds /// form), and the redbHttp.ResponseCode bridge header used by the redb.Route HTTP /// consumer. The exchange is stopped via so no downstream /// processor runs (no WireTap, no tx commit, no idempotency capture). /// /// internal static class ThrottleRejection { /// Constant error code returned in the 429 body. public const string ErrorCode = "rate_limit_exceeded"; /// /// Writes the 429 short-circuit on . The retry-after value /// is the configured throttle period rounded up to whole seconds (per RFC 7231 §7.1.3 /// delta-seconds), clamped to a minimum of 1 second so the header is never absent or /// degenerate when the period is sub-second. /// public static void Apply(IExchange exchange, TimeSpan period) { var retryAfter = (int)Math.Max(1, Math.Ceiling(period.TotalSeconds)); var retryAfterStr = retryAfter.ToString(CultureInfo.InvariantCulture); var body = JsonSerializer.SerializeToUtf8Bytes(new Dictionary { ["error"] = ErrorCode, ["error_description"] = $"Rate limit exceeded. Retry after {retryAfterStr} second(s).", ["retry_after"] = retryAfter, }); var msg = new Message(body) { ContentType = "application/json", }; msg.Headers["redbHttp.ResponseCode"] = 429; msg.Headers["redbHttp.ResponseContentType"] = "application/json"; msg.Headers["Retry-After"] = retryAfterStr; exchange.Out = msg; exchange.ExceptionHandled = true; exchange.Stop(); } } Path: redb-route/redb.Route/Processors/TimeoutProcessor.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/TimeoutProcessor.cs ---- using System.Diagnostics; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.Processors; /// /// Wraps an inner processor with a per-exchange processing timeout. /// If the timeout fires, throws /// which can be caught by route-level exception handlers. /// internal sealed class TimeoutProcessor : IProcessor { private readonly IProcessor _inner; private readonly TimeSpan _timeout; private readonly string _routeId; private readonly RouteContext? _context; private readonly ILogger? _logger; public TimeoutProcessor(IProcessor inner, TimeSpan timeout, string routeId, RouteContext? context = null, ILogger? logger = null) { _inner = inner; _timeout = timeout; _routeId = routeId; _context = context; _logger = logger; } public async Task Process(IExchange exchange, CancellationToken ct) { using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(ct); timeoutCts.CancelAfter(_timeout); var sw = Stopwatch.StartNew(); try { await _inner.Process(exchange, timeoutCts.Token).ConfigureAwait(false); } catch (OperationCanceledException) when (timeoutCts.IsCancellationRequested && !ct.IsCancellationRequested) { sw.Stop(); var elapsed = sw.Elapsed; var ex = new ExchangeTimedOutException(_routeId, _timeout, elapsed); exchange.Exception = ex; exchange.Properties["ExchangeTimedOut"] = true; ProcessorMetrics.TimeoutExpired.Add(1); _logger?.LogWarning("Exchange {ExchangeId} timed out after {Elapsed}ms on route '{RouteId}'.", exchange.ExchangeId, elapsed.TotalMilliseconds, _routeId); if (_context != null) { await _context.NotifyExchangeTimedOut( _routeId, exchange.ExchangeId, elapsed, ct).ConfigureAwait(false); } throw ex; } } } Path: redb-route/redb.Route/Processors/ToDynamicProcessor.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/ToDynamicProcessor.cs ---- using redb.Route.Abstractions; namespace redb.Route.Processors; /// /// Camel-style toD(): sends the exchange to an endpoint whose URI is /// computed per message from a ${...} template, an , /// or a factory delegate. Producers are cached per resolved URI and reused. /// public sealed class ToDynamicProcessor : IProcessor { private readonly DynamicEndpointResolver _resolver; /// Creates a dynamic-to processor with the given resolver. public ToDynamicProcessor(DynamicEndpointResolver resolver) { _resolver = resolver ?? throw new ArgumentNullException(nameof(resolver)); } /// The resolver this node sends through; shared with an interception wrapper so the target is evaluated once per message. internal DynamicEndpointResolver Resolver => _resolver; /// public async Task Process(IExchange exchange, CancellationToken ct = default) { var (endpoint, producer) = await _resolver.ResolvePairAsync(exchange, ct).ConfigureAwait(false); await Core.CountedSend.Process(endpoint, producer, exchange, ct).ConfigureAwait(false); } } Path: redb-route/redb.Route/Processors/ToProcessor.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/ToProcessor.cs ---- using System.Diagnostics; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Processors; /// /// Sends the exchange to a target endpoint via its producer. /// Resolves the endpoint from IRouteContext by URI, creates a producer, and delegates Process. /// The producer is started on first use and can be stopped via . /// public class ToProcessor : IProcessor { private readonly string _endpointUri; private readonly IRouteContext _context; private readonly object _producerLock = new(); private Task? _producerTask; private IProducer? _producer; private IEndpoint? _endpoint; /// Gets the target endpoint URI. public string EndpointUri => _endpointUri; /// Creates a ToProcessor that sends exchanges to the given endpoint URI. /// Target endpoint URI (e.g., "kafka://orders"). /// Route context used to resolve endpoints. public ToProcessor(string endpointUri, IRouteContext context) { _endpointUri = endpointUri ?? throw new ArgumentNullException(nameof(endpointUri)); _context = context ?? throw new ArgumentNullException(nameof(context)); (context as RouteContext)?.NoteStaticEndpoint(endpointUri); } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { var producer = await GetOrCreateProducerAsync(ct).ConfigureAwait(false); await CountedSend.Process(_endpoint!, producer, exchange, ct).ConfigureAwait(false); } /// Stops the producer if one was created and started. public async Task StopProducerAsync(CancellationToken ct = default) { Task? task; lock (_producerLock) { task = _producerTask; _producerTask = null; } if (task is null) return; IProducer producer; try { producer = await task.ConfigureAwait(false); } catch { return; } // start failed — nothing to stop await producer.Stop(ct).ConfigureAwait(false); } private Task GetOrCreateProducerAsync(CancellationToken ct) { // Single-flight: the first exchange creates + starts the producer; concurrent exchanges await // the SAME task and only receive the producer AFTER Start() (and its ConnectAsync) has fully // completed. Previously this returned _producer as soon as it was assigned — before Start() // finished — so under concurrent processing (e.g. RabbitMQ ConcurrentConsumers(N)) a second // thread could Process() a half-initialised producer (Redis _db still null → NRE). lock (_producerLock) { return _producerTask ??= CreateAndStartProducerAsync(); } } private async Task CreateAndStartProducerAsync() { var endpoint = _context.GetEndpoint(_endpointUri); var producer = endpoint.CreateProducerOnItsSide(); try { // Producer lifecycle is independent of any single exchange — do NOT tie startup to one // message's cancellation token (it would cancel startup for every concurrent caller). await producer.Start(CancellationToken.None).ConfigureAwait(false); } catch { // Allow a later exchange to retry a failed cold start instead of caching the failure. lock (_producerLock) { _producerTask = null; } throw; } _endpoint = endpoint; _producer = producer; (_context as RouteContext)?.TrackProducer(producer); return producer; } } Path: redb-route/redb.Route/Processors/TryCatchProcessor.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/TryCatchProcessor.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Processors; /// /// A catch clause used by . /// Matches exceptions by type and executes a handler processor. /// public class CatchClause { /// The exception type to catch. public Type ExceptionType { get; } /// Optional predicate for additional filtering. public Func? When { get; } /// Processor to execute when the exception is caught. public IProcessor Handler { get; } /// Creates a catch clause. /// Exception type to match. /// Handler processor. /// Optional additional predicate. public CatchClause(Type exceptionType, IProcessor handler, Func? when = null) { ExceptionType = exceptionType ?? throw new ArgumentNullException(nameof(exceptionType)); Handler = handler ?? throw new ArgumentNullException(nameof(handler)); if (!typeof(Exception).IsAssignableFrom(exceptionType)) throw new ArgumentException($"Type must be an Exception, got {exceptionType.Name}", nameof(exceptionType)); When = when; } /// Creates a typed catch clause. /// Exception type to match. /// Handler processor. /// Optional additional predicate. /// A new catch clause for the specified type. public static CatchClause For(IProcessor handler, Func? when = null) where TException : Exception { Func? wrappedWhen = when != null ? ex => ex is TException typed && when(typed) : null; return new CatchClause(typeof(TException), handler, wrappedWhen); } /// Checks whether this clause matches the given exception. /// The exception to match. /// True if this clause handles the exception. public bool Matches(Exception exception) { if (!ExceptionType.IsInstanceOfType(exception)) return false; return When == null || When(exception); } } /// /// Try-catch error handling processor. Wraps a body processor and catches /// exceptions using ordered catch clauses. Optionally runs a finally block. /// public class TryCatchProcessor : IProcessor { private readonly IProcessor _body; private readonly List _catchClauses = []; private readonly ILogger? _logger; private IProcessor? _finally; /// Gets the catch clauses. public IReadOnlyList CatchClauses => _catchClauses; /// Gets the finally processor. public IProcessor? Finally => _finally; /// Creates a try-catch processor wrapping the specified body. /// The processor to wrap in try-catch. /// Optional logger. public TryCatchProcessor(IProcessor body, ILogger? logger = null) { _body = body ?? throw new ArgumentNullException(nameof(body)); _logger = logger; } /// Adds a catch clause. /// The catch clause to add. /// This instance for fluent chaining. public TryCatchProcessor Catch(CatchClause clause) { ArgumentNullException.ThrowIfNull(clause); _catchClauses.Add(clause); return this; } /// Adds a typed catch clause. /// Exception type to catch. /// Handler processor. /// This instance for fluent chaining. public TryCatchProcessor Catch(IProcessor handler) where TException : Exception { _catchClauses.Add(CatchClause.For(handler)); return this; } /// Sets the finally processor. /// Processor to run after try/catch regardless of outcome. /// This instance for fluent chaining. public TryCatchProcessor SetFinally(IProcessor processor) { _finally = processor ?? throw new ArgumentNullException(nameof(processor)); return this; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { try { await _body.Process(exchange, ct).ConfigureAwait(false); } // A downstream timeout is an OperationCanceledException whose token (ours) is still live — not a // cancellation, so it enters here. Name it a TimeoutException so Catch sees it; // a genuine cancellation (the caller's token fired) is filtered out and never handled. catch (Exception ex) when (!RouteCancellation.IsCancellation(ex, ct)) { var failure = RouteCancellation.Normalize(ex, ct); exchange.Exception = failure; var matched = false; foreach (var clause in _catchClauses) { if (clause.Matches(failure)) { _logger?.LogWarning(failure, "TryCatch: caught {ExceptionType}: {Message}", failure.GetType().Name, failure.Message); await clause.Handler.Process(exchange, ct).ConfigureAwait(false); exchange.ExceptionHandled = true; // The catch clause is where this failure ends; the steps left in the try body are deliberately // abandoned, so nothing replays them later (OnException ... Continued()). ResumePoints.Forget(exchange, failure); matched = true; break; } } if (!matched) throw; } finally { if (_finally != null) { await _finally.Process(exchange, ct).ConfigureAwait(false); } } } } Path: redb-route/redb.Route/Processors/UnitOfWorkProcessor.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/UnitOfWorkProcessor.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Processors; /// /// Opens the exchange's unit of work when it enters its first route and ends it before that route returns to its consumer /// (Apache Camel: the UnitOfWork of the consumer's route, done before the consumer acknowledges). The completions /// registered with have therefore run before the message is acknowledged or /// handed back to the broker, so a redelivery cannot overtake them. /// /// Sits outside every error handler and the route's OnCompletion blocks, and reaches the consumer's verdict: an /// escaping exception is a failure, and so is a normal return with an unhandled failure left on the exchange /// (OnException without Handled) or a rollback-only mark (.RollbackAll()) — /// . A handled failure is a success. A route called with an exchange /// whose unit of work is already open (direct:) passes through. /// /// internal sealed class UnitOfWorkProcessor : IProcessor { private readonly IProcessor _inner; private readonly ILogger? _logger; public UnitOfWorkProcessor(IProcessor inner, ILogger? logger) { _inner = inner ?? throw new ArgumentNullException(nameof(inner)); _logger = logger; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var unitOfWork = ExchangeResources.OpenUnitOfWork(exchange); if (unitOfWork is null) { await _inner.Process(exchange, ct).ConfigureAwait(false); return; } try { await _inner.Process(exchange, ct).ConfigureAwait(false); } catch { await unitOfWork.End(exchange, failed: true, _logger).ConfigureAwait(false); throw; } await unitOfWork.End(exchange, exchange.EndedInFailure(), _logger).ConfigureAwait(false); } } 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; } Path: redb-route/redb.Route/README.md 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/README.md ---- # redb.Route > Documentation and articles: Core ESB engine — async-first message routing with fluent C# DSL, 30+ EIP processors, unified expression engine with 17 predicates, OpenTelemetry telemetry, and built-in components (Direct, SEDA, Timer, Mock, Log). [![NuGet](https://img.shields.io/nuget/v/redb.Route?label=NuGet&color=blue)](https://www.nuget.org/packages/redb.Route) [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue)](../../LICENSE) ## Installation ```bash dotnet add package redb.Route ``` ## Quick Start ```csharp using redb.Route.Extensions; builder.Services.AddRedbRoute(route => { // Inline routes route.AddRoutes(r => { r.From("timer://heartbeat?period=5000") .SetBody("ping") .Log("Heartbeat: ${body}") .To("direct://monitor"); }); // Or RouteBuilder classes route.AddRouteBuilder(); // Or every public, non-abstract RouteBuilder of an assembly (constructor injection works); // the filter is optional and leaves builders out route.AddRouteBuilders([typeof(MyRoutes).Assembly], type => type != typeof(DebugRoutes)); }); ``` Without a host, `context.AddRoutes(typeof(MyRoutes).Assembly)` adds the builders that have a public parameterless constructor. A builder that cannot be created, or a type already added, is an error naming it — never skipped. ### RouteBuilder — Full DSL ```csharp public class OrderRoutes : RouteBuilder { protected override void Configure() { From("direct://orders") .RouteId("order-pipeline") // Expression predicates — typed, composable .Filter(Header("status").isEqualTo("new")) // JsonPath extraction .SetBody(JPath("$.order")) .SetHeader("total", JPath("$.order.total")) // Content-Based Router — chain style .Choice() .When(Header("total").isGreaterThan(10000)) .To("direct://large-orders") .When(Header("total").isBetween(1000, 10000)) .To("direct://medium-orders") .Otherwise() .To("direct://small-orders") .EndChoice() .Log("Order routed: ${header.orderId}"); // Exception handling with redelivery — for the routes of this builder only OnException() .MaximumRedeliveries(3) .RedeliveryDelay(TimeSpan.FromSeconds(2)) .UseExponentialBackOff() .BackOffMultiplier(2.0) .Handled() .Log("HTTP error: ${exception.message}") .To("seda://dead-letter") .EndOnException(); } } ``` ## Built-in Components | Component | Scheme | Direction | Description | |-----------|--------|-----------|-------------| | **Direct** | `direct:name` | In-process | Synchronous in-process messaging | | **SEDA** | `seda:name` | In-process | Async queue with configurable concurrency | | **Timer** | `timer:name` | Consumer | Periodic message generation | | **Mock** | `mock:name` | Producer | Testing endpoint with expectations | | **Log** | `log:name` | Producer | Logging sink at configurable levels | ### Fluent Builders ```csharp using redb.Route; // Direct — sync in-process From(Direct.Endpoint("orders")) .To(Direct.Endpoint("processor")); // SEDA — async queue From(Seda.Consume("incoming").ConcurrentConsumers(4).Size(1000)) .To(Seda.Send("outgoing")); // Timer — periodic From(TimerDsl.Every("poll").Period(5000).Delay(1000)) .To("direct://check"); // Mock — testing From("direct://test") .To(MockDsl.Endpoint("result").ExpectedMessageCount(3)); // Log — sink From("direct://data") .To(LogDsl.Info("audit").ShowHeaders().ShowBody()); ``` ## Expression Engine Two expression systems — **unified through `IExpression`** interface: ### Typed Expressions (RouteBuilder helpers) `protected static` helpers in `RouteBuilder` — use directly in `Configure()`: ```csharp // Message accessors Body() // message body Header("name") // header value Property("key") // exchange property Constant(42) // constant value Exchange(e => e.RouteId) // delegate over IExchange // Structured data extraction JPath("$.order.total") // JsonPath JPath("$.order.total") // typed JsonPath XPath("/order/status/text()") // XPath 1.0 XPath("count(//item)") // typed XPath // String template bridge — wraps ${...} as IExpression Expr("${header.orderId}") // single value Expr("${header.prefix}-${body}") // template interpolation ``` ### 17 Predicate Methods Every expression supports predicate chaining — for `Filter()`, `When()`, `Validate()`: ```csharp Header("status").isEqualTo("active") // equality Header("status").isNotEqualTo("cancelled") // inequality Header("amount").isGreaterThan(1000) // comparison Header("amount").isLessThan(500) Header("amount").isGreaterThanOrEqualTo(100) Header("amount").isLessThanOrEqualTo(9999) Header("amount").isBetween(100, 5000) // range (inclusive) Header("name").contains("Corp") // substring / collection Header("name").startsWith("Order-") Header("name").endsWith(".pdf") Header("email").regex(@"^[\w.]+@[\w.]+$") // regex match Header("type").In("order", "payment") // set membership Header("optional").isNull() Header("required").isNotNull() // Also works with Expr — string expression + predicates: Expr("${header.amount}").isGreaterThan(1000) ``` ### String Expression Resolver AST-based compiled expression language with caching (used in `Log`, `Filter(string)`, `When(string)`, `Expr()`): ```csharp // Templates — ${...} placeholder interpolation .Log("Processing: ${header.orderId}") .SetBody(Expr("${header.prefix}-${body}")) // Boolean expressions — in Filter/When .Filter("header.amount > 1000") .Filter("header.status == 'active' AND header.amount > 0") // Supports: header.*, body.*, property.*, exception.* // Operators: ==, !=, >, <, >=, <=, AND, OR, XOR, ! // Functions: contains(), startsWith(), endsWith(), jpath(), xpath() // Arithmetic: +, -, *, / ``` ### Every DSL Method — Multiple Input Styles | Method | Static | Lambda | IExpression | String `${...}` | |--------|--------|--------|-------------|------------------| | `SetBody` | `SetBody("hi")` | `SetBody(e => ...)` | `SetBody(Header("x"))` | `SetBody(Expr("${header.x}"))` | | `SetHeader` | `SetHeader("k","v")` | `SetHeader("k", e => ...)` | `SetHeader("k", JPath("$.x"))` | `SetHeader("k", Expr("${body}"))` | | `SetProperty` | `SetProperty("k",1)` | `SetProperty("k", e => ...)` | `SetProperty("k", Body())` | `SetProperty("k", Expr("${header.x}"))` | | `Filter` | — | `Filter(e => ...)` | `Filter(Header("x").isEqualTo("y"))` | `Filter("header.x == 'y'")` | | `Transform` | — | `Transform(e => ...)` | `Transform(JPath("$.data"))` | — | | `Process` | — | `Process(e => ...)` | `Process(myProcessor)` | — | ## Processors (30+ EIP Patterns) | Processor | DSL | Pattern | |-----------|-----|---------| | `PipelineProcessor` | (implicit) | Pipeline | | `FilterProcessor` | `.Filter(...)` | Message Filter | | `ChoiceProcessor` | `.Choice()` | Content-Based Router | | `MulticastProcessor` | `.Multicast(...)` | Multicast | | `RecipientListProcessor` | `.RecipientList(...)` | Recipient List | | `SplitterProcessor` | `.Split(...)` | Splitter | | `AggregatorProcessor` | `.Aggregate(...)` | Aggregator | | `ResequencerProcessor` | `.Resequence(...)` | Resequencer | | `DynamicRouterProcessor` | `.DynamicRouter(...)` | Dynamic Router | | `RoutingSlipProcessor` | `.RoutingSlip(...)` | Routing Slip | | `WireTapProcessor` | `.WireTap(...)` | Wire Tap | | `EnrichProcessor` | `.Enrich(...)` | Content Enricher | | `XsltProcessor` | `.Xslt(...)` / `xslt:` | Message Translator (XSLT) | | `ToProcessor` | `.To(...)` | Message Endpoint | | `DelegateProcessor` | `.Process(...)` | Custom Processor | | `LogProcessor` | `.Log(...)` | Logging | | `RichLogProcessor` | `.Log().Message(...)` | Structured Logging | | `MessageHistoryProcessor` | `.MessageHistory()` / `EnableMessageHistory` | Message History | | `ControlBusProducer` | `.ControlBus(...)` / `controlbus:` | Control Bus | | `DelayProcessor` | `.Delay(...)` | Delayer | | `LoopProcessor` | `.Loop(...)` | Loop | | `ThrottleProcessor` | `.Throttle(...)` | Throttler | | `CircuitBreakerProcessor` | `.CircuitBreaker(...)` | Circuit Breaker | | `RetryProcessor` | `.Transacted().Retry(...)` | Retry (transaction scope) | | `DeadLetterProcessor` | `.Transacted().DeadLetterChannel(...)` | Dead Letter Channel (transaction scope) | | `OnExceptionProcessor` | `.OnException()` | Exception Handler | | `TryCatchProcessor` | `.DoTry()` | Try-Catch | | `IdempotentConsumerProcessor` | `.IdempotentConsumer(...)` | Idempotent Consumer | | `SagaProcessor` | `.Saga()` | Saga (compensating steps) | | `ScatterGatherProcessor` | `.ScatterGather(...)` | Scatter-Gather | | `ClaimCheckProcessor` | claim-check definition | Claim Check | | `ThreadsProcessor` | `.Threads(n)` | Threads (async handoff) | | `DebounceProcessor` | `.Debounce(...)` | Debounce | | `KeyedThrottleProcessor` | keyed throttle definition | Throttler (per key) | | `LoadBalancerProcessor` | `.LoadBalance(...)` | Load Balancer | | `ChoiceProcessor` (composed) | `.Normalize(...)` | Normalizer | | `PollEnrichProcessor` | `.PollEnrich(...)` | Polling Consumer / Enricher | | `SamplingProcessor` | `.Sample(...)` | Sampling | | `TimeoutProcessor` | `.ProcessingTimeout(...)` | Processing timeout | | `ToDynamicProcessor` | `.ToD(...)` | Dynamic Endpoint | | `CheckpointProcessor` | `.Replayable(...)` | Replay checkpoint | | `RoutePolicyProcessor` | `.RoutePolicy(...)` | Route Policy | | `StreamCachingProcessor` | `.StreamCaching()` | Stream Caching | | `StreamingSplitterProcessor` | `.Split(...)` (streaming) | Splitter (streaming) | > Counts in this file are derived from `Processors/` and `IRouteDefinition` — 37 `*Processor` > implementations behind 30+ named EIPs. Keep them in step with the repository README and the > package description when adding a pattern. ## Error Handling ```csharp // Retry + Dead Letter Channel live on the transaction scope (.Transacted() / .Transaction()) .Transacted() .Retry(attempts: 3, delay: TimeSpan.FromSeconds(1)) .DeadLetterChannel("seda://failed") .To("http://api/submit") .End() // Try-Catch-Finally scope .DoTry() .To("http://api/submit") .DoCatch() .Log("API failed: ${exception.message}") .To("seda://retry") .DoFinally() .Log("Attempt done") .End() ``` ## Transactions One primitive: `.Transacted()` (alias `.Transaction()`). Inside it all `redb` work shares one connection per (transaction, database) and commits or rolls back with the block; put `.IdempotentConsumer(...)` **inside** `.Transacted()` so the dedup key is written in the same transaction as the work. ```csharp .Transacted() .Process(async ex => await redb.SaveAsync(order)) // enlists in the ambient transaction .To("kafka://orders.created") .End() ``` Keep a transacted route to one database (a second durable connection escalates to MSDTC, unsupported on .NET/Linux), don't do database work in parallel branches inside a transaction (open a transaction inside each sub-route instead; a parallel fan-out in a transaction runs each branch under a dependent clone, and one failed branch rolls the whole block back), and note `BeginRedbTransaction()` is `[Obsolete]` — `.Transacted()` enlists `redb` on its own. **See the full guide: [TRANSACTIONS.md](../TRANSACTIONS.md)** — placement, per-mode idempotency semantics, the at-most-once loss window without a transaction, parallelism, and migration off `BeginRedbTransaction()`. ## Content-Based Routing ```csharp // Chain style — Camel-like .Choice() .When(Header("type").isEqualTo("order")) .To("direct://orders") .When(Header("type").isEqualTo("payment")) .To("direct://payments") .Otherwise() .To("seda://unknown") .EndChoice() // Lambda style — callback sub-routes .Choice(c => c .When(Header("type").isEqualTo("order"), r => r.To("direct://orders")) .When(Header("type").isEqualTo("payment"), r => r.To("direct://payments")) .Otherwise(r => r.To("seda://unknown"))) // String expression style .Choice() .When("header.type == 'order'") .To("direct://orders") .Otherwise() .To("seda://unknown") .EndChoice() ``` ## Processing ```csharp // Async delegate with CancellationToken .Process(async (exchange, ct) => { var order = exchange.In.Body as Order; exchange.In.Body = await EnrichOrder(order, ct); }) // Sync delegate .Process(exchange => { exchange.In.Headers["processed"] = true; }) // Custom IProcessor class .Process(new OrderValidationProcessor()) ``` ## Configuration ```csharp builder.Services.Configure(o => { o.EnableTelemetry = true; // OpenTelemetry Activities o.EnableMetrics = true; // Meters & Counters o.ShutdownTimeout = TimeSpan.FromSeconds(30); o.ThrowOnCompilationError = true; // Fail-fast on invalid routes }); ``` ### Property Placeholders Endpoint URIs can externalise their configuration with Camel-style `{{key}}` / `{{key:default}}` placeholders, resolved **once at route-compile time** — from `IConfiguration` (environment, appsettings, user-secrets), then context properties (`SetProperty`) as a container-free fallback. A URI without `{{` is untouched, and an unresolved placeholder without a default fails fast. ```csharp From("{{orders.source}}") // amqp://broker/orders — from appsettings/env .To("http://api/{{tenant}}/pay"); From("amqp://broker:{{amqp.port:5672}}/orders"); // default used when the key is not configured ``` Because `IConfiguration` already layers environment, files and secrets, no `env:`/`sys:` prefix functions are needed. Keeps secrets out of source and lets one route run unchanged across environments. ### Named connection factories Every transport that opens a connection accepts `connectionFactory=` on the endpoint URI, resolved from the context registry — the canonical way to keep credentials out of URIs: ```csharp context.AddToRegistry("prod-kafka", new KafkaConnectionFactory { Brokers = "b1:9092,b2:9092" }); // kafka://orders?connectionFactory=prod-kafka ``` The resolution contract, uniform across connectors: 1. **Explicit name** — resolved from the registry; a set-but-unknown name FAILS LOUD at startup (never a silent fallback: a typo and a working configuration must be distinguishable). Resolution happens BEFORE option validation, so the factory may be the only source of required values (brokers, tokens, credentials). 2. **URI options** — inline parameters when no name is set. 3. **Component/provider defaults** — where the connector has them (e.g. Firebase's `DefaultProjectId`/`DefaultCredentialPath`). 4. **Environment** — provider chains such as `GOOGLE_APPLICATION_CREDENTIALS` or the AWS default credentials chain. ### When endpoints and producers are created A static target's endpoint — `To`, `WireTap`, `Enrich`, a load balancer's targets, a Scatter-Gather's fixed recipients — is created when its route starts, as Camel resolves a static `to(...)` at startup: an unknown scheme, an unknown URI parameter or a missing `{{key}}` stops the start (or skips the route, with `ThrowOnCompilationError = false`) instead of failing the first message. A dynamic target (`ToD`, a recipient list, a routing slip) is resolved per message. Producers are made when a message first needs one — unlike Camel, which starts them with the route — so starting a context opens no connection to a broker a route has not used yet. A static target matched by an intercept with `SkipSendToOriginalEndpoint()` is not created up front: the original may never be sent to (a dry run whose real component is absent). ## Telemetry Built-in OpenTelemetry — distributed tracing + metrics per route and step: ```csharp // Scope style — wrap block of steps .Traced("order-processing") .SetBody(JPath("$.order")) .Process(async (e, ct) => await Enrich(e, ct)) .EndTraced() // Inline style — wrap single step .Traced("validate", async (e, ct) => await Validate(e, ct)) .Metered("throughput", e => { e.In.Body = Transform(e); }) ``` `RouteEngineOptions.EnableTelemetry` is on for the whole context. A single route can opt out with `.Tracing(false)` (or `` in Route-XML), so a service route such as a health check or a metric summary opens no span of its own. To find a trace by a business key, put it on a span with `.SpanTag(key, value)` — a literal or an expression, as in `SetHeader` (`` or `expr="..."` in Route-XML). Jaeger and Tempo find a trace by an attribute on any of its spans: ```csharp .SpanTag("sap.order.id", XPath("/Ack/OrderNo")) // nearest Traced scope, else the route span .SpanTag("sap.order.id", Header("orderNo"), SpanTarget.Inbound) // the request's / message's own span ``` The key is checked when the route is built (lowercase, dot-separated, outside `redb.`, `http.`, `messaging.` and the other reserved namespaces, never a secret's name). Nothing is set without a listener, on an unsampled span, with `.Tracing(false)` (no fallback to the transport span), or on a span that has ended; a value that fails to evaluate is skipped. The host's own span (ASP.NET Core) is never written. **The value is exported unfiltered** — no personal data, no credentials; and a business key goes on a span, not in baggage, which travels to every next service. ## Batch consumers A broker consumer in batch mode follows one contract, in `redb.Route.Batching`, with Apache Camel's option names: `batching=true` switches it on (no other option does), `maxBatchMessages` caps the batch, `pollTimeoutMs` sends a batch on once no message came for that long (restarted by every message), `batchingIntervalMs` sends it on once that long has passed since its first message. The route gets one InOnly exchange whose body is a `List`, one message per broker message with its own body and headers, even for a batch of one; the size is `body.Count` (`${body.size}`). Transport headers every message agrees on (a topic, a queue) are set on the batch message. The batch is settled once, after the route has returned; a failed batch is settled by the connector's rule for a failed single message, applied to every message. A batch half collected when the consumer stops is not run: its messages go back to the broker. `Split` over the body gives each part its record's body and headers, the split metadata as exchange properties. A connector of your own supplies a `BatchReceive` delegate to `BatchCollector`, an `IBatchSettlement` (accept, reject, give back) and the message mapping to `BatchDispatcher`. ## Behaviour Guarantees A few behaviours are easy to get wrong from reading a single method, so they are stated here. - **A body a producer has no wire form for.** It is sent as its own text (`ToString()` overridden: a number, a record, a JSON node). A list or an object whose text would only be its type name is refused, naming the endpoint (`BodyText`). A list of `IMessage` is sent element by element where the connector supports it (`ListBody`). - **A stopped exchange.** `exchange.Stop()` stops the pipeline from running its remaining steps; it is not an exception. A `DoFinally()` block still runs, because it is the C# `finally` of `TryCatchProcessor`. A failure and a cancellation behave the same way. - **A stop in a route called over `direct-vm:`.** A plain `direct-vm:` call runs the called route on the caller's own exchange, so a `Stop()` there ends the caller's route too, and an HTTP consumer up the chain answers with what the called route left (body, `redbHttp.ResponseCode`, headers). A check after `.To`, a `DoTry` / `DoCatch` when the called route marked its exception handled (nothing is thrown), and `headerFilterStrategy=#name` (the linked copy hands the stop back) do not let the caller continue. `Enrich` does: it calls on a linked copy, the stop stays on the copy, and the merge decides what comes back (the body, the headers and the exception of the exchange it returns). Return the original from the merge: ```csharp .Enrich("direct-vm:auth.check", (original, call) => { var reply = call.HasOut ? call.Out! : call.In; if (reply.Headers.TryGetValue("redbHttp.ResponseCode", out var code) && Convert.ToInt32(code) >= 400) { original.In.Body = "{\"code\":\"parties.not_allowed\"}"; original.In.Headers["redbHttp.ResponseCode"] = 403; original.In.Headers["redbHttp.ResponseContentType"] = "application/json"; } else original.In.Body = reply.Body; return original; }) ``` - **The Out → In merge.** When a step writes `exchange.Out`, the pipeline merges it into `In` before the next step: the body and every header of `Out` are copied over, `ContentType` is copied only when `Out` carries one, and `Out` is cleared. The last step's `Out` is left in place for an InOut caller. - **A Split branch.** A part that is an `IMessage` becomes the branch's message (a copy, its own headers, none of the parent's); any other part becomes the body under a copy of the parent's In headers. `CamelSplitIndex`, `CamelSplitSize`, `CamelSplitComplete` and `CamelCorrelationId` are exchange properties of the branch, as in Apache Camel (`${property.CamelSplitIndex}`). The branch inherits the parent's properties (the dictionary is inherited, the values are shared). Writing a property on a branch does not reach the parent. - **EIP properties.** As Apache Camel's `ExchangePropertyKey`, the EIPs publish exchange properties, named in `ExchangePropertyKeys`: `CamelToEndpoint` (interceptSendToEndpoint), `CamelLoopIndex` and `CamelLoopSize` (Loop), `CamelMulticastIndex`, `CamelMulticastComplete` and `CamelCorrelationId` (Multicast), `CamelAggregatedSize`, `CamelAggregatedCompletedBy` and `CamelAggregatedCorrelationKey` (Aggregate), `CamelRecipientListEndpoint` (RecipientList), `CamelSlipEndpoint` (RoutingSlip), `CamelDuplicateMessage` (IdempotentConsumer). - **`now()` and `delay`.** `now()` returns a `DateTime` with `DateTimeKind.Utc`. `delay` accepts a `TimeSpan`, an `int` / `long` / `double` meaning milliseconds, a string that parses as a number of milliseconds, or a string that parses as `hh:mm:ss`. ## Validation ```csharp // JSON Schema .ValidateJsonSchema("""{"type":"object","required":["orderId"]}""") // XSD .ValidateXsd(xsdContent) // XSD from a file: its imports and includes are read relative to it, from under schemaRoot only .ValidateXsdFile("schemas/order.xsd", schemaRoot: "..") // Predicate .Validate(e => e.In.Body is Order { Amount: > 0 }, "Amount must be positive") ``` ## Part of [redb.Route](../README.md) — ESB & EIP Framework for .NET ## Header filter strategy Apache Camel's `HeaderFilterStrategy`. A transport carried headers by a rule of its own, fixed in code: HTTP sent every exchange header but a fixed list, or none (`bridgeHeaders`); the brokers sent every one. There was no way to send one header, such as `Correlation-ID`, and keep the rest at home. - `redb.Route.Abstractions.IHeaderFilterStrategy`: `FilterOutgoing` (an exchange header about to go into an outgoing message: a producer's request, a consumer's reply) and `FilterIncoming` (a header of an incoming message about to come into the exchange); `true` drops the header, as in Camel. - `DefaultHeaderFilterStrategy`: per direction a list of names, a regular expression (the whole name) and name prefixes; `FilterOnMatch=false` turns it into a whitelist; `CaseInsensitive` (on by default, as in Camel), `LowerCase`, `AllowNullValues`. Declared as a bean in C# or in markup. - An endpoint names its strategy with `headerFilterStrategy=#name`; it replaces the transport's default on every point of the endpoint. A name the registry does not hold fails when the producer or consumer is built. - Every transport keeps its behaviour by default: its rule became its default strategy. The fields a transport sets itself (trace context, content type, the native properties of a message) and its protocol fields do not go through a strategy. - Transports with the option: HTTP, Kafka, RabbitMQ, AMQP 1.0, Azure Service Bus, IBM MQ, gRPC, SQS/SNS, AS2. Each default is a public class (`KafkaHeaderFilterStrategy`, `RabbitMQHeaderFilterStrategy`, ...) to derive from. On a request-reply (RabbitMQ, AMQP, IBM MQ, gRPC) the strategy is asked about the reply too: a producer's strategy for the headers that come back, a consumer's for the headers it answers with. - A transport's own guards stay outside every strategy: gRPC refuses a caller's header with a transport-reserved prefix unless `allowClientReservedHeaders=true`; AS2 never forwards another hop's credentials; an SQS `redbSqs.attr.X` header is an explicit request and is sent as attribute `X`. - `direct-vm:` and `vm:`, the calls between contexts, take the option on the calling side (`.To`), as Apache Camel 3's `direct-vm` does; a consumer URI with it is refused. `direct-vm:` with a strategy runs the called context on a copy that shares the caller's DI scope and unit of work: the callee sees the headers the strategy lets out, and the caller keeps its own headers and takes the reply's body, the reply headers the strategy lets in, the properties, the exception and a stop. Unlike Camel, which replaces the caller's message with the reply, the caller's own headers survive the call. Without the option nothing changes: the callee works on the caller's own exchange. `vm:` filters the copy it hands over; Camel's `vm` has no such option. - The markup package gate (`redb-route-xml check --bin`) holds a `headerFilterStrategy=#name` bean against `IHeaderFilterStrategy`, as it holds `repository=#name` against the repository interfaces. - Transports that send only what a route names with a prefix (SOAP, S3, AS4, FCM, Mail, LLM, Redis Streams, MQTT) do not take a strategy: nothing crosses there without that consent. characterization tests that pin what every transport carried before (`*HeaderMappingCharacterizationTests`). Path: redb-route/redb.Route/Serialization/Base64MessageSerializer.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/Serialization/Base64MessageSerializer.cs ---- using System.Text; namespace redb.Route.Serialization; /// Base64 as a data format: Marshal("application/base64") encodes the body, Unmarshal<byte[]>("application/base64") decodes it. public sealed class Base64MessageSerializer : BinaryWrapperSerializer { /// Content type the format is registered under by default. public const string DefaultContentType = "application/base64"; /// public override string ContentType => DefaultContentType; /// protected override string FormatName => "Base64"; /// protected override byte[] Encode(byte[] payload) => Encoding.ASCII.GetBytes(Convert.ToBase64String(payload)); /// protected override byte[] Decode(byte[] data) => Base64Text.Decode(Encoding.ASCII.GetString(data).Trim()); } Path: redb-route/redb.Route/Serialization/Base64Text.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/Serialization/Base64Text.cs ---- namespace redb.Route.Serialization; /// /// Base64 decoding that reads a value the same way on every runtime. .NET 11 refuses a value whose last character /// carries non-zero unused bits (YR== where an encoder writes YQ==); .NET 10 ignores those bits and /// decodes both to the same bytes. RFC 4648 §3.5 allows a decoder either behaviour, so each place picks one: /// accepts such a value on every runtime (data and digests from a partner, as .NET 10 read /// them), refuses it on every runtime (credentials and tokens: one value, one /// spelling). Everything else (alphabet, padding, whitespace, errors) is that of /// . /// public static class Base64Text { private const string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// with the unused bits of the last character read as zero. /// is not base64. public static byte[] Decode(string value) => Convert.FromBase64String(ClearUnusedBits(value)); /// with the unused bits of the last character read as zero. public static bool TryDecode(string value, Span bytes, out int bytesWritten) => Convert.TryFromBase64String(ClearUnusedBits(value), bytes, out bytesWritten); /// /// that refuses a value whose last character has non-zero unused bits on /// every runtime, as .NET 11 does. /// public static bool TryDecodeCanonical(string value, Span bytes, out int bytesWritten) { if (HasUnusedBitsSet(value)) { bytesWritten = 0; return false; } return Convert.TryFromBase64String(value, bytes, out bytesWritten); } /// /// Whether the last character of carries non-zero unused bits: the spelling XML Schema /// base64Binary and .NET 11 refuse. It says nothing else about whether the value is base64. /// public static bool HasUnusedBitsSet(string value) => UnusedBitsOfLast(value, out _, out _, out _); private static string ClearUnusedBits(string value) { if (!UnusedBitsOfLast(value, out var last, out var index, out var unused)) return value; var chars = value.ToCharArray(); chars[last] = Alphabet[index & ~unused]; return new string(chars); } /// True when the last character before the padding has some of its unused bits set. private static bool UnusedBitsOfLast(string value, out int last, out int index, out int unused) { ArgumentNullException.ThrowIfNull(value); index = -1; unused = 0; var pads = 0; last = value.Length - 1; for (; last >= 0; last--) { var c = value[last]; if (c == '=') pads++; else if (c is not (' ' or '\t' or '\r' or '\n')) break; } if (last < 0 || pads is < 1 or > 2) return false; index = Alphabet.IndexOf(value[last], StringComparison.Ordinal); // One '=' leaves 2 unused bits in the last character, two leave 4. unused = pads == 1 ? 0b11 : 0b1111; return index >= 0 && (index & unused) != 0; } } Path: redb-route/redb.Route/Serialization/BinaryWrapperSerializer.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/Serialization/BinaryWrapperSerializer.cs ---- using System.Text; using redb.Route.Abstractions; namespace redb.Route.Serialization; /// /// Base for data formats that wrap bytes rather than serialize an object model (Base64, GZip, Zip). /// Marshal accepts a byte[], a string (UTF-8) or a ; /// Unmarshal yields byte[], string, or object (bytes). /// Anything else is an error that names the format, not a NullReferenceException later. /// public abstract class BinaryWrapperSerializer : IMessageSerializer { /// public abstract string ContentType { get; } /// public virtual IReadOnlyCollection MediaTypes => [ContentType]; /// public bool WrapsBytes => true; /// /// Default cap on the unwrapped size, 128 MB. A body that expands past the cap is refused, so a small /// compressed message cannot exhaust the process memory; raise it per format instance when a bigger /// payload is expected (new GZipMessageSerializer(maxDecodedBytes: …)). /// public const long DefaultMaxDecodedBytes = 128L * 1024 * 1024; /// Wraps the payload (encode / compress). protected abstract byte[] Encode(byte[] payload); /// Unwraps the data (decode / decompress). protected abstract byte[] Decode(byte[] data); /// Short format name for error messages (GZip). protected abstract string FormatName { get; } /// public byte[] Serialize(T value) => Encode(ToBytes(value)); /// public T? Deserialize(byte[] data) => (T?)Deserialize(data, typeof(T)); /// public object? Deserialize(byte[] data, Type type) { ArgumentNullException.ThrowIfNull(data); ArgumentNullException.ThrowIfNull(type); byte[] raw; try { raw = Decode(data); } catch (Exception ex) when (ex is FormatException or IOException or InvalidDataException) { throw new InvalidOperationException($"{FormatName} data format: the body is not valid {FormatName} data ({ex.Message}).", ex); } if (type == typeof(byte[]) || type == typeof(object)) return raw; if (type == typeof(string)) return Encoding.UTF8.GetString(raw); if (type == typeof(Stream) || type == typeof(MemoryStream)) return new MemoryStream(raw, writable: false); if (type == typeof(ReadOnlyMemory)) return new ReadOnlyMemory(raw); throw new InvalidOperationException( $"{FormatName} data format wraps bytes: unmarshal to byte[], string or Stream, not {type.Name}."); } private byte[] ToBytes(object? value) => value switch { null => [], byte[] bytes => bytes, string text => Encoding.UTF8.GetBytes(text), ReadOnlyMemory memory => memory.ToArray(), Stream stream => ReadAll(stream), _ => throw new InvalidOperationException( $"{FormatName} data format wraps bytes: the body must be byte[], string or Stream, not {value.GetType().Name}."), }; /// /// Copies the decoded into a buffer, refusing to grow past /// bytes. Thrown as on purpose: it is /// not "invalid data" (the stream may be perfectly valid), it is a body the format refuses to unwrap. /// protected static byte[] ReadBounded(Stream source, long limit, string formatName) { using var output = new MemoryStream(); var buffer = new byte[81920]; long total = 0; int read; while ((read = source.Read(buffer, 0, buffer.Length)) > 0) { total += read; if (total > limit) throw new InvalidOperationException( $"{formatName} data format: the decoded body exceeds the limit of {limit} bytes; raise maxDecodedBytes on the {formatName} format if a body this large is expected."); output.Write(buffer, 0, read); } return output.ToArray(); } private static byte[] ReadAll(Stream stream) { if (stream is MemoryStream ms) return ms.ToArray(); using var buffer = new MemoryStream(); stream.CopyTo(buffer); return buffer.ToArray(); } } Path: redb-route/redb.Route/Serialization/ConvertBodyProcessor.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/Serialization/ConvertBodyProcessor.cs ---- using System.Text; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Serialization; /// /// Processor that converts the exchange body to the specified target type. /// Uses ContentType to determine encoding for byte[]/string conversions. /// Supports Stream ↔ byte[] ↔ string conversions. /// public sealed class ConvertBodyProcessor : IProcessor { private readonly Type _targetType; private readonly IDataFormatRegistry? _registry; /// Creates a body converter processor. /// Target type to convert body to. /// Optional data format registry for ContentType-based deserialization. public ConvertBodyProcessor(Type targetType, IDataFormatRegistry? registry = null) { _targetType = targetType ?? throw new ArgumentNullException(nameof(targetType)); _registry = registry; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { var body = exchange.In.Body; if (body is null) return; if (_targetType.IsInstanceOfType(body)) return; // A model type through a message format registered for the content type: the format reads the body as it came // (a Stream included) with the content type parameters. Plain text and byte conversions stay below. if (_targetType != typeof(string) && _targetType != typeof(byte[]) && _targetType != typeof(Stream) && exchange.In.ContentType is { } contentType && _registry?.GetSerializer(contentType) is IMessageDataFormat messageFormat) { await messageFormat.UnmarshalAsync(exchange, _targetType, ct).ConfigureAwait(false); return; } exchange.In.Body = body is Stream ? await ConvertStreamAsync(body, exchange.In.ContentType, ct).ConfigureAwait(false) : Convert(body, exchange.In.ContentType); } private object Convert(object body, string? contentType) { // byte[] → string if (_targetType == typeof(string) && body is byte[] bytes) { var encoding = GetEncoding(contentType); return encoding.GetString(bytes); } // string → byte[] if (_targetType == typeof(byte[]) && body is string str) { var encoding = GetEncoding(contentType); return encoding.GetBytes(str); } // byte[] → Stream if (_targetType == typeof(Stream) && body is byte[] b) return new MemoryStream(b, writable: false); // string → Stream if (_targetType == typeof(Stream) && body is string s) return new MemoryStream(GetEncoding(contentType).GetBytes(s)); // string/byte[] → T via registered serializer when ContentType is known if (contentType is not null) { var serializer = _registry?.GetSerializer(contentType); if (serializer is not null) { var data = body switch { byte[] raw => raw, string txt => Encoding.UTF8.GetBytes(txt), _ => null }; if (data is not null) return serializer.Deserialize(data, _targetType) ?? throw new InvalidOperationException( $"Serializer for '{contentType}' returned null for type '{_targetType.Name}'."); } } // Fallback: try System.Convert try { return RouteDecimal.ChangeType(body, _targetType); } catch (Exception ex) { throw new InvalidOperationException( $"Cannot convert body of type '{body.GetType().Name}' to '{_targetType.Name}'." + (contentType != null ? $" ContentType: '{contentType}'." : ""), ex); } } private async Task ConvertStreamAsync(object body, string? contentType, CancellationToken ct) { var stream = (Stream)body; // Stream → byte[] if (_targetType == typeof(byte[])) { using var ms = new MemoryStream(); await stream.CopyToAsync(ms, ct).ConfigureAwait(false); return ms.ToArray(); } // Stream → string if (_targetType == typeof(string)) { using var reader = new StreamReader(stream, GetEncoding(contentType), leaveOpen: true); return await reader.ReadToEndAsync(ct).ConfigureAwait(false); } throw new InvalidOperationException( $"Cannot convert body of type 'Stream' to '{_targetType.Name}'."); } private static Encoding GetEncoding(string? contentType) { if (contentType is null) return Encoding.UTF8; // Parse charset from ContentType, e.g. "text/plain; charset=iso-8859-1" var charsetIndex = contentType.IndexOf("charset=", StringComparison.OrdinalIgnoreCase); if (charsetIndex >= 0) { var charset = contentType[(charsetIndex + 8)..].Trim().TrimEnd(';').Trim(); try { return Encoding.GetEncoding(charset); } catch { // Unknown charset — fall back to UTF-8 } } return Encoding.UTF8; } } Path: redb-route/redb.Route/Serialization/DataFormatRegistry.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/Serialization/DataFormatRegistry.cs ---- using redb.Route.Abstractions; namespace redb.Route.Serialization; /// /// Default registry mapping content types to instances. /// Pre-registers JSON and XML serializers. Thread-safe: a format may be registered while routes /// are already resolving serializers (a hot-loaded module adding its own). /// public sealed class DataFormatRegistry : IDataFormatRegistry { private readonly System.Collections.Concurrent.ConcurrentDictionary _serializers = new(StringComparer.OrdinalIgnoreCase); private readonly System.Collections.Concurrent.ConcurrentDictionary _profiles = new(StringComparer.OrdinalIgnoreCase); /// Creates a registry with JSON and XML serializers pre-registered. public DataFormatRegistry() { var json = new JsonMessageSerializer(); _serializers["application/json"] = json; var xml = new XmlMessageSerializer(); _serializers["application/xml"] = xml; _serializers["text/xml"] = xml; // Byte wrappers shipped with the core (no dependencies): Marshal("application/gzip") etc. Register(Base64MessageSerializer.DefaultContentType, new Base64MessageSerializer()); Register(GZipMessageSerializer.DefaultContentType, new GZipMessageSerializer()); Register(ZipMessageSerializer.DefaultContentType, new ZipMessageSerializer()); // HTML form data, also without dependencies: ConvertBody() right after an HTTP consumer. Register(FormUrlEncodedMessageSerializer.DefaultContentType, new FormUrlEncodedMessageSerializer()); } /// public IMessageSerializer? GetSerializer(string contentType) { ArgumentNullException.ThrowIfNull(contentType); // Exact match if (_serializers.TryGetValue(contentType, out var s)) return s; // Strip parameters (e.g. "application/json; charset=utf-8" → "application/json") var semi = contentType.IndexOf(';'); if (semi > 0) { var baseType = contentType[..semi].Trim(); if (_serializers.TryGetValue(baseType, out s)) return s; } // Structured suffix: "application/vnd.api+json" → try "application/json" if (contentType.Contains("+json", StringComparison.OrdinalIgnoreCase)) return _serializers.GetValueOrDefault("application/json"); if (contentType.Contains("+xml", StringComparison.OrdinalIgnoreCase)) return _serializers.GetValueOrDefault("application/xml"); return null; } /// public void Register(string contentType, IMessageSerializer serializer) { ArgumentException.ThrowIfNullOrEmpty(contentType); ArgumentNullException.ThrowIfNull(serializer); // Primary registration by the caller-specified content type. _serializers[contentType] = serializer; // Also fan out to all media-type aliases the serializer declares, so a single // Register(...) call covers structured-suffix variants (e.g. "application/json" // + "application/problem+json" if both are claimed by the instance). foreach (var alias in serializer.MediaTypes) { if (!string.IsNullOrEmpty(alias) && !string.Equals(alias, contentType, StringComparison.OrdinalIgnoreCase)) { _serializers.TryAdd(alias, serializer); } } } /// public IMessageSerializer? ResolveProfile(string profileName) { ArgumentException.ThrowIfNullOrEmpty(profileName); return _profiles.GetValueOrDefault(profileName); } /// public void RegisterProfile(string profileName, IMessageSerializer serializer) { ArgumentException.ThrowIfNullOrEmpty(profileName); ArgumentNullException.ThrowIfNull(serializer); _profiles[profileName] = serializer; } } Path: redb-route/redb.Route/Serialization/FormBody.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/Serialization/FormBody.cs ---- using System.Collections; namespace redb.Route.Serialization; /// /// The fields of an application/x-www-form-urlencoded body, in order. A name may repeat (checkboxes, a list /// field), so the form is a list of pairs; answers the first value of a name and /// every one. Names compare ordinally, as HTML forms send them. /// public sealed class FormBody : IReadOnlyList>, ICloneable { private readonly List> _fields; /// An empty form. public FormBody() => _fields = []; /// A form with the given fields, in order. public FormBody(IEnumerable> fields) { ArgumentNullException.ThrowIfNull(fields); _fields = []; foreach (var (name, value) in fields) Add(name, value); } /// public int Count => _fields.Count; /// public KeyValuePair this[int index] => _fields[index]; /// Appends a field; a field with the same name may already be there. public FormBody Add(string name, string value) { ArgumentNullException.ThrowIfNull(name); ArgumentNullException.ThrowIfNull(value); _fields.Add(new(name, value)); return this; } /// The first value of , or null. public string? Get(string name) { ArgumentNullException.ThrowIfNull(name); foreach (var (key, value) in _fields) if (string.Equals(key, name, StringComparison.Ordinal)) return value; return null; } /// Every value of , in order; empty when the field is absent. public IReadOnlyList GetAll(string name) { ArgumentNullException.ThrowIfNull(name); return _fields.Where(f => string.Equals(f.Key, name, StringComparison.Ordinal)).Select(f => f.Value).ToArray(); } /// Whether the form has a field named . public bool Contains(string name) => Get(name) is not null; /// The fields as a dictionary of the first value of each name (later repeats are left out). public Dictionary ToDictionary() { var map = new Dictionary(StringComparer.Ordinal); foreach (var (key, value) in _fields) map.TryAdd(key, value); return map; } /// A copy with its own field list (names and values are immutable strings). public object Clone() => new FormBody(_fields); /// public IEnumerator> GetEnumerator() => _fields.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); /// The form in its wire form, UTF-8 (for logs and tests). public override string ToString() => FormUrlEncoding.Encode(this, System.Text.Encoding.UTF8); } Path: redb-route/redb.Route/Serialization/FormUrlEncodedMessageSerializer.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/Serialization/FormUrlEncodedMessageSerializer.cs ---- namespace redb.Route.Serialization; /// /// HTML form data as a data format, registered by default: /// Unmarshal<FormBody>("application/x-www-form-urlencoded") or ConvertBody<FormBody>() after an /// HTTP consumer reads the posted fields, Marshal("application/x-www-form-urlencoded") writes a /// or a dictionary of strings. Parsing and encoding follow the WHATWG URL standard. /// /// /// Unmarshal targets: (every field, in order) and Dictionary<string, string> /// (the first value of each name). Marshal sources: and any sequence of string pairs, such as /// IDictionary<string, string>. /// public sealed class FormUrlEncodedMessageSerializer : Abstractions.IMessageSerializer { /// Content type the format is registered under by default. public const string DefaultContentType = "application/x-www-form-urlencoded"; private readonly FormUrlEncodedOptions _options; /// A format with the default options (UTF-8, ASP.NET Core limits). public FormUrlEncodedMessageSerializer() : this(new FormUrlEncodedOptions()) { } /// A format with the given options. public FormUrlEncodedMessageSerializer(FormUrlEncodedOptions options) { _options = options ?? throw new ArgumentNullException(nameof(options)); ArgumentNullException.ThrowIfNull(options.Encoding, nameof(options.Encoding)); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(options.MaxFields, nameof(options.MaxFields)); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(options.MaxNameLength, nameof(options.MaxNameLength)); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(options.MaxValueLength, nameof(options.MaxValueLength)); } /// A format configured in place. public FormUrlEncodedMessageSerializer(Action configure) : this(Configure(configure)) { } /// public string ContentType => DefaultContentType; /// public byte[] Serialize(T value) => value switch { null => [], IEnumerable> fields => _options.Encoding.GetBytes(FormUrlEncoding.Encode(fields, _options.Encoding)), _ => throw new NotSupportedException( $"Form data cannot be written from '{value.GetType().FullName}': use FormBody or a sequence of string pairs (IDictionary).") }; /// public T? Deserialize(byte[] data) => (T?)Deserialize(data, typeof(T)); /// public object? Deserialize(byte[] data, Type type) { ArgumentNullException.ThrowIfNull(data); ArgumentNullException.ThrowIfNull(type); var form = FormUrlEncoding.Decode(data, _options.Encoding, _options); if (type.IsAssignableFrom(typeof(FormBody))) return form; if (type.IsAssignableFrom(typeof(Dictionary))) return form.ToDictionary(); throw new NotSupportedException( $"Form data cannot be read as '{type.FullName}': use FormBody (every field) or Dictionary (the first value of each name)."); } private static FormUrlEncodedOptions Configure(Action configure) { ArgumentNullException.ThrowIfNull(configure); var options = new FormUrlEncodedOptions(); configure(options); return options; } } Path: redb-route/redb.Route/Serialization/FormUrlEncodedOptions.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/Serialization/FormUrlEncodedOptions.cs ---- using System.Text; namespace redb.Route.Serialization; /// /// Options of . The limits apply wherever the form comes from (HTTP, a file, /// a queue), not only behind a web server; the defaults are those of ASP.NET Core's FormOptions. /// public sealed class FormUrlEncodedOptions { /// /// Character encoding of the decoded bytes. Default UTF-8, what browsers send from a UTF-8 page; the /// charset parameter is not part of this content type, so a sender with another encoding needs its own /// format instance. /// public Encoding Encoding { get; set; } = Encoding.UTF8; /// Most fields one form may have. Default 1024. public int MaxFields { get; set; } = 1024; /// Longest field name, in characters after decoding. Default 2048. public int MaxNameLength { get; set; } = 2048; /// Longest field value, in characters after decoding. Default 4 194 304 (4 M). public int MaxValueLength { get; set; } = 4 * 1024 * 1024; } Path: redb-route/redb.Route/Serialization/FormUrlEncoding.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/Serialization/FormUrlEncoding.cs ---- using System.Text; namespace redb.Route.Serialization; /// /// The application/x-www-form-urlencoded parser and serializer of the WHATWG URL standard, the one browsers and /// ASP.NET follow: pairs split on & and the first =, + is a space, %XX is a byte, a /// % not followed by two hex digits stays as it is. /// internal static class FormUrlEncoding { public static FormBody Decode(ReadOnlySpan data, Encoding encoding, FormUrlEncodedOptions limits) { var form = new FormBody(); var bytes = new List(); while (!data.IsEmpty) { var amp = data.IndexOf((byte)'&'); var pair = amp < 0 ? data : data[..amp]; data = amp < 0 ? [] : data[(amp + 1)..]; if (pair.IsEmpty) continue; if (form.Count == limits.MaxFields) throw new InvalidDataException($"Form data has more than {limits.MaxFields} fields (FormUrlEncodedOptions.MaxFields)."); var eq = pair.IndexOf((byte)'='); var name = DecodeComponent(eq < 0 ? pair : pair[..eq], encoding, bytes); var value = eq < 0 ? string.Empty : DecodeComponent(pair[(eq + 1)..], encoding, bytes); if (name.Length > limits.MaxNameLength) throw new InvalidDataException($"Form data has a field name longer than {limits.MaxNameLength} characters (FormUrlEncodedOptions.MaxNameLength)."); if (value.Length > limits.MaxValueLength) throw new InvalidDataException($"Form data has a field value longer than {limits.MaxValueLength} characters (FormUrlEncodedOptions.MaxValueLength)."); form.Add(name, value); } return form; } private static string DecodeComponent(ReadOnlySpan text, Encoding encoding, List buffer) { buffer.Clear(); for (var i = 0; i < text.Length; i++) { var b = text[i]; if (b == (byte)'+') { buffer.Add((byte)' '); } else if (b == (byte)'%' && i + 2 < text.Length && IsHex(text[i + 1]) && IsHex(text[i + 2])) { buffer.Add((byte)((HexValue(text[i + 1]) << 4) | HexValue(text[i + 2]))); i += 2; } else { buffer.Add(b); } } return encoding.GetString(System.Runtime.InteropServices.CollectionsMarshal.AsSpan(buffer)); } public static string Encode(IEnumerable> fields, Encoding encoding) { var sb = new StringBuilder(); foreach (var (name, value) in fields) { if (sb.Length > 0) sb.Append('&'); EncodeComponent(sb, name, encoding); sb.Append('='); EncodeComponent(sb, value, encoding); } return sb.ToString(); } // The application/x-www-form-urlencoded percent-encode set: everything but ASCII alphanumerics and *-._ is // encoded, and a space becomes '+'. private static void EncodeComponent(StringBuilder sb, string text, Encoding encoding) { foreach (var b in encoding.GetBytes(text)) { if (b == (byte)' ') sb.Append('+'); else if (b is >= (byte)'a' and <= (byte)'z' or >= (byte)'A' and <= (byte)'Z' or >= (byte)'0' and <= (byte)'9' or (byte)'*' or (byte)'-' or (byte)'.' or (byte)'_') sb.Append((char)b); else sb.Append('%').Append("0123456789ABCDEF"[b >> 4]).Append("0123456789ABCDEF"[b & 0xF]); } } private static bool IsHex(byte b) => b is >= (byte)'0' and <= (byte)'9' or >= (byte)'a' and <= (byte)'f' or >= (byte)'A' and <= (byte)'F'; private static int HexValue(byte b) => b <= (byte)'9' ? b - '0' : (b | 0x20) - 'a' + 10; } Path: redb-route/redb.Route/Serialization/GZipMessageSerializer.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/Serialization/GZipMessageSerializer.cs ---- using System.IO.Compression; namespace redb.Route.Serialization; /// GZip as a data format: Marshal("application/gzip") compresses the body, Unmarshal<string>("application/gzip") decompresses it. public sealed class GZipMessageSerializer : BinaryWrapperSerializer { /// Content type the format is registered under by default. public const string DefaultContentType = "application/gzip"; private readonly CompressionLevel _level; private readonly long _maxDecodedBytes; /// Creates the format. /// Compression level (default ). /// Cap on the decompressed size (default , 128 MB); a body that expands past it is refused. public GZipMessageSerializer(CompressionLevel level = CompressionLevel.Optimal, long maxDecodedBytes = DefaultMaxDecodedBytes) { ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxDecodedBytes); _level = level; _maxDecodedBytes = maxDecodedBytes; } /// public override string ContentType => DefaultContentType; /// public override IReadOnlyCollection MediaTypes => [DefaultContentType, "application/x-gzip"]; /// protected override string FormatName => "GZip"; /// protected override byte[] Encode(byte[] payload) { using var output = new MemoryStream(); using (var gzip = new GZipStream(output, _level, leaveOpen: true)) gzip.Write(payload); return output.ToArray(); } /// protected override byte[] Decode(byte[] data) { using var input = new MemoryStream(data, writable: false); using var gzip = new GZipStream(input, CompressionMode.Decompress); return ReadBounded(gzip, _maxDecodedBytes, FormatName); } } Path: redb-route/redb.Route/Serialization/JsonMessageSerializer.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/Serialization/JsonMessageSerializer.cs ---- using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Serialization; using redb.Route.Abstractions; namespace redb.Route.Serialization; /// /// JSON message serializer using System.Text.Json. /// Thread-safe, singleton-friendly. Configurable via . /// public sealed class JsonMessageSerializer : IMessageSerializer { private readonly JsonSerializerOptions _options; private readonly string _contentType; private readonly IReadOnlyCollection _mediaTypes; /// /// Default options: camelCase, case-insensitive, ignore null values on write, UTF-8. /// Uses so non-ASCII /// (Cyrillic, emoji, diacritics) and ASCII punctuation like " are emitted /// as-is in UTF-8 instead of being escaped to \u0022/\u0410. /// This is safe for HTTP API responses; only unsafe when embedding JSON inside /// HTML/JS inline — which message-serializer output never does. /// Exotic transports (e.g. JSONP, HTML-inline) can override via constructor. /// public static readonly JsonSerializerOptions DefaultOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, PropertyNameCaseInsensitive = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, WriteIndented = false, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; // The static options build metadata over every message type; a module's type in them is let go on unload. static JsonMessageSerializer() => Core.CollectibleContextCleanup.EnsureWatching(); /// Creates a JSON serializer with default options. public JsonMessageSerializer() : this(DefaultOptions, contentType: "application/json", mediaTypes: null) { } /// Creates a JSON serializer with custom options. /// JSON serializer options. public JsonMessageSerializer(JsonSerializerOptions options) : this(options, contentType: "application/json", mediaTypes: null) { } /// /// Creates a JSON serializer with custom options, a specific primary content type, /// and an optional extended list of media-type aliases the instance also handles. /// /// JSON serializer options. /// Primary content type reported by /// (e.g. application/scim+json). /// Optional alias list reported by /// . If null, defaults to [contentType]. /// /// Used to ship profile serializers (SCIM, Problem Details, …) that own their own /// and declare non-application/json /// media types without subclassing. /// public JsonMessageSerializer( JsonSerializerOptions options, string contentType, IReadOnlyCollection? mediaTypes) { _options = options ?? throw new ArgumentNullException(nameof(options)); _contentType = !string.IsNullOrEmpty(contentType) ? contentType : throw new ArgumentException("Content type must not be empty.", nameof(contentType)); _mediaTypes = mediaTypes is { Count: > 0 } ? mediaTypes : new[] { _contentType }; } /// public string ContentType => _contentType; /// public IReadOnlyCollection MediaTypes => _mediaTypes; /// public byte[] Serialize(T value) { return JsonSerializer.SerializeToUtf8Bytes(value, _options); } /// public T? Deserialize(byte[] data) { ArgumentNullException.ThrowIfNull(data); return JsonSerializer.Deserialize(data, _options); } /// public object? Deserialize(byte[] data, Type type) { ArgumentNullException.ThrowIfNull(data); ArgumentNullException.ThrowIfNull(type); return JsonSerializer.Deserialize(data, type, _options); } } Path: redb-route/redb.Route/Serialization/MarshalProcessor.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/Serialization/MarshalProcessor.cs ---- using redb.Route.Abstractions; using redb.Route.Processors; namespace redb.Route.Serialization; /// /// Processor that marshals the exchange body to/from bytes using an . /// Use in a pipeline to serialize before sending or deserialize after receiving. /// public sealed class MarshalProcessor : IProcessor { private readonly IMessageSerializer _serializer; /// Creates a marshal (serialize) processor. /// Serializer to use. public MarshalProcessor(IMessageSerializer serializer) { _serializer = serializer ?? throw new ArgumentNullException(nameof(serializer)); } /// public Task Process(IExchange exchange, CancellationToken ct = default) { // A message format sees the whole message (a body may be empty when the attachments are the payload). if (_serializer is IMessageDataFormat messageFormat) return messageFormat.MarshalAsync(exchange, ct).AsTask(); var body = exchange.In.Body; if (body is null) return Task.CompletedTask; // For an object-model format (JSON, XML, Avro, ...) a byte[] body is an already-marshalled result // and passes through; for a byte wrapper (GZip, Zip, Base64) the bytes are the payload itself. if (body is byte[] && !_serializer.WrapsBytes) return Task.CompletedTask; var bytes = SerializeBody(body); exchange.In.Body = bytes; exchange.In.ContentType = _serializer.ContentType; exchange.In.Headers["Content-Type"] = _serializer.ContentType; return Task.CompletedTask; } private byte[] SerializeBody(object body) { // Use reflection to call Serialize with the actual runtime type var method = typeof(IMessageSerializer) .GetMethod(nameof(IMessageSerializer.Serialize))! .MakeGenericMethod(body.GetType()); return (byte[])method.Invoke(_serializer, [body])!; } } /// /// Processor that unmarshals the exchange body from bytes to a typed object /// using an . /// public sealed class UnmarshalProcessor : IProcessor { private readonly IMessageSerializer _serializer; private readonly Type _targetType; /// Creates an unmarshal (deserialize) processor. /// Serializer to use. /// Type to deserialize to. public UnmarshalProcessor(IMessageSerializer serializer, Type targetType) { _serializer = serializer ?? throw new ArgumentNullException(nameof(serializer)); _targetType = targetType ?? throw new ArgumentNullException(nameof(targetType)); } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { // A message format reads the body as it came, with the content type parameters. if (_serializer is IMessageDataFormat messageFormat) { await messageFormat.UnmarshalAsync(exchange, _targetType, ct).ConfigureAwait(false); return; } // Text formats (CSV, YAML, JSON) usually arrive as a string; a Stream is common after an // HTTP or file consumer. All three are the same bytes to a serializer. var bytes = exchange.In.Body switch { byte[] b => b, string s => System.Text.Encoding.UTF8.GetBytes(s), Stream stream => await ReadAllAsync(stream, ct).ConfigureAwait(false), _ => null, }; if (bytes is null) return; exchange.In.Body = _serializer.Deserialize(bytes, _targetType); } private static async Task ReadAllAsync(Stream stream, CancellationToken ct) { // The buffer shortcut only when the stream is at its start; a positioned stream (an earlier step // consumed framing) is read from its position like any other, never from byte zero. if (stream is MemoryStream ms && ms.Position == 0 && ms.TryGetBuffer(out var segment) && segment.Offset == 0 && segment.Count == ms.Length) return segment.Array!.Length == segment.Count ? segment.Array : segment.ToArray(); using var buffer = new MemoryStream(); await stream.CopyToAsync(buffer, ct).ConfigureAwait(false); return buffer.ToArray(); } } Path: redb-route/redb.Route/Serialization/XmlMessageSerializer.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/Serialization/XmlMessageSerializer.cs ---- using System; using System.Collections.Concurrent; using System.IO; using System.Text; using System.Xml; using System.Xml.Serialization; using redb.Route.Abstractions; namespace redb.Route.Serialization; /// /// XML message serializer using . /// Thread-safe, caches instances per type. /// public sealed class XmlMessageSerializer : IMessageSerializer { // Weak per type: a type of an unloadable module (collectible load context) does not stay alive in this cache, // and the serializer .NET generates for it lives in that same load context. private static readonly System.Runtime.CompilerServices.ConditionalWeakTable SerializerCache = new(); private readonly XmlWriterSettings _writerSettings; private readonly XmlReaderSettings _readerSettings; /// Default writer settings: UTF-8 without BOM, no XML declaration, no indentation. public static readonly XmlWriterSettings DefaultWriterSettings = new() { Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), OmitXmlDeclaration = true, Indent = false, CloseOutput = false }; /// Default reader settings. public static readonly XmlReaderSettings DefaultReaderSettings = new() { CloseInput = false, IgnoreWhitespace = true }; /// Creates an XML serializer with default settings. public XmlMessageSerializer() : this(DefaultWriterSettings, DefaultReaderSettings) { } /// Creates an XML serializer with custom writer and reader settings. /// Settings for XML output. /// Settings for XML input. public XmlMessageSerializer(XmlWriterSettings writerSettings, XmlReaderSettings readerSettings) { _writerSettings = writerSettings ?? throw new ArgumentNullException(nameof(writerSettings)); _readerSettings = readerSettings ?? throw new ArgumentNullException(nameof(readerSettings)); } /// public string ContentType => "application/xml"; /// public byte[] Serialize(T value) { var serializer = GetOrCreateSerializer(typeof(T)); using var ms = new MemoryStream(); using (var xw = XmlWriter.Create(ms, _writerSettings)) { serializer.Serialize(xw, value); } return ms.ToArray(); } /// public T? Deserialize(byte[] data) { ArgumentNullException.ThrowIfNull(data); var serializer = GetOrCreateSerializer(typeof(T)); using var ms = new MemoryStream(data); using var xr = XmlReader.Create(ms, _readerSettings); return (T?)serializer.Deserialize(xr); } /// public object? Deserialize(byte[] data, Type type) { ArgumentNullException.ThrowIfNull(data); ArgumentNullException.ThrowIfNull(type); var serializer = GetOrCreateSerializer(type); using var ms = new MemoryStream(data); using var xr = XmlReader.Create(ms, _readerSettings); return serializer.Deserialize(xr); } private static XmlSerializer GetOrCreateSerializer(Type type) => SerializerCache.GetValue(type, static t => new XmlSerializer(t)); } Path: redb-route/redb.Route/Serialization/ZipMessageSerializer.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/Serialization/ZipMessageSerializer.cs ---- using System.IO.Compression; namespace redb.Route.Serialization; /// /// Zip as a data format: Marshal("application/zip") packs the body into a single-entry archive /// (entry name from the constructor, default body); Unmarshal reads the first entry. /// public sealed class ZipMessageSerializer : BinaryWrapperSerializer { /// Content type the format is registered under by default. public const string DefaultContentType = "application/zip"; private readonly string _entryName; private readonly CompressionLevel _level; private readonly long _maxDecodedBytes; /// Creates the format. /// Name of the single archive entry written by Marshal. /// Compression level (default ). /// Cap on the decompressed size (default , 128 MB); an entry that expands past it is refused. public ZipMessageSerializer(string entryName = "body", CompressionLevel level = CompressionLevel.Optimal, long maxDecodedBytes = DefaultMaxDecodedBytes) { ArgumentException.ThrowIfNullOrWhiteSpace(entryName); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxDecodedBytes); _entryName = entryName; _level = level; _maxDecodedBytes = maxDecodedBytes; } /// public override string ContentType => DefaultContentType; /// public override IReadOnlyCollection MediaTypes => [DefaultContentType, "application/x-zip-compressed"]; /// protected override string FormatName => "Zip"; /// protected override byte[] Encode(byte[] payload) { using var output = new MemoryStream(); using (var archive = new ZipArchive(output, ZipArchiveMode.Create, leaveOpen: true)) { using var entry = archive.CreateEntry(_entryName, _level).Open(); entry.Write(payload); } return output.ToArray(); } /// protected override byte[] Decode(byte[] data) { using var input = new MemoryStream(data, writable: false); using var archive = new ZipArchive(input, ZipArchiveMode.Read); // Directory entries (empty Name) carry no data; the format reads exactly one file entry — a // multi-entry archive is refused rather than silently reduced to whichever entry came first. var files = archive.Entries.Where(e => !string.IsNullOrEmpty(e.Name)).ToList(); if (files.Count == 0) throw new InvalidDataException("the archive has no file entries"); if (files.Count > 1) throw new InvalidDataException($"the archive has {files.Count} entries; Unmarshal reads a single-entry archive"); using var stream = files[0].Open(); return ReadBounded(stream, _maxDecodedBytes, FormatName); } } Path: redb-route/redb.Route/Telemetry/DetachedDispatch.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/Telemetry/DetachedDispatch.cs ---- using System.Diagnostics; using System.Transactions; namespace redb.Route.Telemetry; /// /// Support for "detached" background dispatch — pipeline work that keeps running after the /// originating Process call has already returned (WireTap fire-and-forget, Debounce flush). /// /// A detached branch runs on a thread-pool continuation that, by default, inherits the caller's /// . That flow leaks two ambient values that are /// unsafe once the originating call has unwound: /// /// /// — an ambient that has /// very likely already completed/disposed by the time the branch runs (the route uses /// , so the ambient transaction flows). Producer/DB /// code in the branch would auto-enlist and throw "the current TransactionScope is already /// complete". /// — the originating span, also already stopped, so telemetry /// the branch emits would be parented to a span that has ended (a child that post-dates its /// parent). /// /// /// is called on the originating thread; is called at the /// top of the branch body. Together they suppress the leaked transaction and re-root the trace as a /// fresh span linked to the originator — correlation is preserved without the broken parent /// lifecycle. Non-transaction AsyncLocal state (user/auth context) is intentionally left flowing, /// since a detached branch such as an audit usually needs it. /// /// internal static class DetachedDispatch { /// Trace + transaction state captured on the originating thread at dispatch time. internal readonly struct Origin { /// Trace context of the span active at dispatch time (default if tracing is off). internal ActivityContext TraceLink { get; } /// Whether an ambient was present at dispatch time. internal bool HadAmbientTransaction { get; } internal Origin(ActivityContext traceLink, bool hadAmbientTransaction) { TraceLink = traceLink; HadAmbientTransaction = hadAmbientTransaction; } } /// /// Captures the ambient trace context and transaction presence. Call this on the ORIGINATING /// thread, before the Task.Run / ContinueWith that starts the detached branch. /// internal static Origin Capture() => new(Activity.Current?.Context ?? default, Transaction.Current is not null); /// /// Opens a detached execution frame INSIDE the branch body: suppresses any leaked ambient /// transaction and starts a root span linked to the originator. Dispose at the end of the branch. /// /// State captured via on the originating thread. /// Span name for the detached branch (e.g. "redb.route.wiretap"). internal static Frame Enter(Origin origin, string operationName) { // Suppress the leaked ambient transaction (only pay for the scope when one actually leaked): // the detached branch's producer/DB code must not enlist in a TransactionScope that has // already completed on the originating thread. TransactionScope? suppress = origin.HadAmbientTransaction ? new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled) : null; // Re-root the trace as a NEW root span linked to the originating trace, so the branch is not // an implicit child of an already-stopped parent while correlation is still preserved. // NOTE: StartActivity falls back to Activity.Current when parentContext is default(ActivityContext) // — passing `default` does NOT force a root. So null out the leaked ambient Activity first; the // started span then has no parent and carries the originating trace only via the ActivityLink. // When there is no captured context (tracing disabled, or no listener) this is a no-op. Activity? activity = null; if (origin.TraceLink != default) { var savedCurrent = Activity.Current; Activity.Current = null; activity = RouteActivitySource.Source.StartActivity( operationName, ActivityKind.Internal, parentContext: default, tags: null, links: new[] { new ActivityLink(origin.TraceLink) }); // No listener sampled it → restore the ambient we cleared (nothing to re-root anyway). if (activity is null) Activity.Current = savedCurrent; } return new Frame(suppress, activity); } /// Disposable frame returned by . Restores ambient state at branch end. internal readonly struct Frame : IDisposable { private readonly TransactionScope? _suppress; private readonly Activity? _activity; internal Frame(TransactionScope? suppress, Activity? activity) { _suppress = suppress; _activity = activity; } /// public void Dispose() { _activity?.Dispose(); if (_suppress is not null) { _suppress.Complete(); _suppress.Dispose(); } } } } Path: redb-route/redb.Route/Telemetry/InstrumentedProcessor.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/Telemetry/InstrumentedProcessor.cs ---- using System.Diagnostics; using redb.Route.Abstractions; using redb.Route.Expressions; namespace redb.Route.Telemetry; /// /// Wraps an with OpenTelemetry tracing. /// Creates an span per call, /// recording exceptions and enriching tags from exchange metadata. /// public sealed class InstrumentedProcessor : IProcessor { private readonly IProcessor _inner; private readonly string _operationName; private readonly Func? _nameTemplate; /// Creates an instrumented processor wrapper. /// The processor to instrument. /// Operation name for the activity span (e.g., "route.process", "direct://output send"). Supports ${...} templates resolved at runtime. public InstrumentedProcessor(IProcessor inner, string operationName) { _inner = inner ?? throw new ArgumentNullException(nameof(inner)); _operationName = operationName ?? throw new ArgumentNullException(nameof(operationName)); if (operationName.Contains("${")) _nameTemplate = ExpressionResolver.GetCompiledTemplate(operationName); } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { var name = _nameTemplate != null ? _nameTemplate(exchange) : _operationName; using var activity = RouteActivitySource.Source.StartActivity(name, ActivityKind.Internal); if (activity is { IsAllDataRequested: true }) { activity.SetTag("redb.route.id", exchange.RouteId); activity.SetTag("redb.exchange.pattern", exchange.Pattern.ToString()); if (exchange.Properties.TryGetValue(ExchangePropertyKeys.CorrelationId, out var correlationId)) activity.SetTag("redb.correlation.id", correlationId?.ToString()); } try { await _inner.Process(exchange, ct).ConfigureAwait(false); // The route id is stamped by the first step of the route pipeline, which this span already // wraps, so at start it was still null and the tag was empty on every route span. Set it // again now that it is known — the span is open until this method returns. if (activity is { IsAllDataRequested: true } && !string.IsNullOrEmpty(exchange.RouteId)) activity.SetTag("redb.route.id", exchange.RouteId); if (activity != null && exchange.Exception != null && !exchange.ExceptionHandled) { activity.SetStatus(ActivityStatusCode.Error, exchange.Exception.Message); activity.RecordException(exchange.Exception); } } catch (Exception ex) when (ex is not OperationCanceledException) { // Same late stamp as the success path, and this is where attribution matters most: a failing // span with no route id is the one an operator is actually looking for. if (activity is { IsAllDataRequested: true } && !string.IsNullOrEmpty(exchange.RouteId)) activity.SetTag("redb.route.id", exchange.RouteId); activity?.SetStatus(ActivityStatusCode.Error, ex.Message); activity?.RecordException(ex); throw; } } } /// /// Extension methods for OpenTelemetry activity enrichment. /// internal static class ActivityExtensions { /// /// Records an exception event on the activity. Uses the framework-built-in /// Activity.AddException (OTel semconv 1.6+). The resulting span event is interoperable with /// Jaeger / Tempo / OTLP collectors. /// internal static void RecordException(this Activity activity, Exception ex) { activity.AddException(ex); } } Path: redb-route/redb.Route/Telemetry/MeteredProcessor.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/Telemetry/MeteredProcessor.cs ---- using System.Diagnostics; using redb.Route.Abstractions; namespace redb.Route.Telemetry; /// /// Wraps a pipeline processor to collect metrics: exchange count, duration, failures, inflight. /// Designed to wrap the top-level pipeline of a compiled route. /// public sealed class MeteredProcessor : IProcessor { private readonly IProcessor _inner; private readonly string _routeId; private readonly KeyValuePair[] _tags; /// Creates a metered processor wrapper. /// Inner processor (typically the route pipeline). /// Route identifier for metric tags. /// Optional From endpoint URI; emitted as redb.route.endpoint. /// Optional endpoint scheme (e.g. kafka, http); emitted as redb.route.scheme. public MeteredProcessor(IProcessor inner, string routeId, string? endpointUri = null, string? endpointScheme = null) { _inner = inner ?? throw new ArgumentNullException(nameof(inner)); _routeId = routeId ?? throw new ArgumentNullException(nameof(routeId)); var tagList = new List>(3) { new("redb.route.id", _routeId) }; if (!string.IsNullOrEmpty(endpointUri)) tagList.Add(new KeyValuePair("redb.route.endpoint", endpointUri)); if (!string.IsNullOrEmpty(endpointScheme)) tagList.Add(new KeyValuePair("redb.route.scheme", endpointScheme)); _tags = tagList.ToArray(); } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { // `ReadOnlySpan<>` is a ref struct and cannot live across `await`. The // instrument overloads also accept `ReadOnlySpan>` // implicitly created from the array, so passing the array argument // directly preserves the same zero-copy semantics without violating // span-safety rules. RouteMetrics.ExchangesInflight.Add(1, _tags); var sw = Stopwatch.StartNew(); try { await _inner.Process(exchange, ct).ConfigureAwait(false); // An error handler that gives up leaves the failure on the exchange rather than throwing it. if (exchange.Exception is not null && !exchange.ExceptionHandled) RouteMetrics.ExchangesFailed.Add(1, _tags); else RouteMetrics.ExchangesProcessed.Add(1, _tags); } catch (OperationCanceledException) { throw; } catch { RouteMetrics.ExchangesFailed.Add(1, _tags); throw; } finally { sw.Stop(); RouteMetrics.ExchangeDuration.Record(sw.Elapsed.TotalMilliseconds, _tags); RouteMetrics.ExchangesInflight.Add(-1, _tags); } } } Path: redb-route/redb.Route/Telemetry/MeteredStepProcessor.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/Telemetry/MeteredStepProcessor.cs ---- using System.Diagnostics; using redb.Route.Abstractions; namespace redb.Route.Telemetry; /// /// Wraps a processor pipeline to collect per-step metrics: count, duration, failures. /// Unlike (route-level), this tags metrics with /// both redb.route.id and redb.route.step. /// public sealed class MeteredStepProcessor : IProcessor { private readonly IProcessor _inner; private readonly string _stepName; private readonly IReadOnlyList<(string Name, Func Resolver)>? _tagProviders; /// Creates a per-step metered processor wrapper. /// Inner processor (the metered sub-pipeline). /// Static step name for metric tags. public MeteredStepProcessor(IProcessor inner, string stepName) : this(inner, stepName, null) { } /// Creates a per-step metered processor wrapper with dynamic tag providers. /// Inner processor (the metered sub-pipeline). /// Static step name for metric tags. /// Optional providers evaluated per message for additional metric dimensions. public MeteredStepProcessor(IProcessor inner, string stepName, IReadOnlyList<(string Name, Func Resolver)>? tagProviders) { _inner = inner ?? throw new ArgumentNullException(nameof(inner)); _stepName = stepName ?? throw new ArgumentNullException(nameof(stepName)); _tagProviders = tagProviders; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { var tags = new TagList { { "redb.route.id", exchange.RouteId }, { "redb.route.step", _stepName } }; if (_tagProviders != null) { for (int i = 0; i < _tagProviders.Count; i++) { var (name, resolver) = _tagProviders[i]; object? value; try { value = resolver(exchange); } catch { value = null; } tags.Add(name, value); } } var sw = Stopwatch.StartNew(); try { await _inner.Process(exchange, ct).ConfigureAwait(false); StepMetrics.StepProcessed.Add(1, tags); } catch (OperationCanceledException) { throw; } catch { StepMetrics.StepFailed.Add(1, tags); throw; } finally { sw.Stop(); StepMetrics.StepDuration.Record(sw.Elapsed.TotalMilliseconds, tags); } } } Path: redb-route/redb.Route/Telemetry/MetricsSnapshot.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/Telemetry/MetricsSnapshot.cs ---- using System.Collections.Concurrent; using System.Diagnostics.Metrics; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using redb.Route.Abstractions; namespace redb.Route.Telemetry; /// /// One reading of one instrument: how many measurements, their sum, the extremes, and the last /// value. For a counter the measurements are deltas, so is the running total; /// for a histogram they are recorded values, so all five fields are meaningful. /// public readonly record struct MetricSnapshotPoint(long Count, double Sum, double Min, double Max, double Last); /// /// Read access to the OpenTelemetry layer from inside the process. /// /// /// /// The "redb.Route" meter is push-only, as every .NET is: the EIP /// counters (throttle.delayed, circuitbreaker.tripped, …) and the .Metered() /// step durations go to a subscriber or nowhere. This service is that subscriber, kept in-process: /// current values only — no windows, no percentiles, no history. Whoever needs those plugs in an /// OpenTelemetry backend; a bus should not carry a small Prometheus inside. /// /// /// Deliberately opt-in (context.UseMetricsSnapshot()): a /// receives a callback for every measurement of every instrument, /// which is a tax all routes would pay for a feature few ask for. /// /// public interface IMetricsSnapshot { /// /// The current point of an instrument, keyed exactly by its tags: /// matches the redb.route.id tag, the redb.route.step /// tag; null means the measurement carried no such tag. No aggregation across keys — /// a point either was recorded with these tags or there is nothing to return. /// /// Instrument name, e.g. redb.route.step.duration. /// Value of the redb.route.id tag, or null for untagged. /// Value of the redb.route.step tag, or null for untagged. /// The point, or null when nothing was recorded under this key. MetricSnapshotPoint? Point(string instrument, string? routeId = null, string? step = null); /// /// Convenience reading: the — a counter's running /// total, a histogram's sum of values. /// double? Value(string instrument, string? routeId = null, string? step = null); } /// /// The in-process subscriber behind : a /// on the "redb.Route" meter, accumulating per (instrument, route id, step). /// internal sealed class MetricsSnapshotListener : IMetricsSnapshot, IDisposable { private sealed class Accumulator { private readonly object _gate = new(); private long _count; private double _sum; private double _min = double.PositiveInfinity; private double _max = double.NegativeInfinity; private double _last; public void Add(double value) { lock (_gate) { _count++; _sum += value; if (value < _min) _min = value; if (value > _max) _max = value; _last = value; } } public MetricSnapshotPoint Read() { lock (_gate) { return new MetricSnapshotPoint(_count, _sum, _min, _max, _last); } } } private readonly ConcurrentDictionary<(string Instrument, string RouteId, string Step), Accumulator> _points = new(); private readonly MeterListener _listener; private int _disposed; public MetricsSnapshotListener() { _listener = new MeterListener { InstrumentPublished = (instrument, listener) => { if (instrument.Meter.Name == RouteMetrics.MeterName) listener.EnableMeasurementEvents(instrument); } }; _listener.SetMeasurementEventCallback((instrument, value, tags, _) => Record(instrument.Name, value, tags)); _listener.SetMeasurementEventCallback((instrument, value, tags, _) => Record(instrument.Name, value, tags)); _listener.Start(); } private void Record(string instrument, double value, ReadOnlySpan> tags) { string routeId = "", step = ""; foreach (var tag in tags) { if (tag.Key == "redb.route.id") routeId = tag.Value?.ToString() ?? ""; else if (tag.Key == "redb.route.step") step = tag.Value?.ToString() ?? ""; } _points.GetOrAdd((instrument, routeId, step), static _ => new Accumulator()).Add(value); } /// public MetricSnapshotPoint? Point(string instrument, string? routeId = null, string? step = null) => _points.TryGetValue((instrument, routeId ?? "", step ?? ""), out var acc) ? acc.Read() : null; /// public double? Value(string instrument, string? routeId = null, string? step = null) => Point(instrument, routeId, step)?.Sum; /// /// Stops listening. Collected points stay readable — an operator inspecting a stopped context /// still sees what it measured. /// public void Dispose() { if (Interlocked.CompareExchange(ref _disposed, 1, 0) != 0) return; _listener.Dispose(); } } /// /// Registration for , following the same order as every other /// pluggable service here: what the context was told, then the DI container — and no default, /// because the whole point is that nobody pays for the listener without asking for it. /// public static class MetricsSnapshotRegistration { /// /// Starts an in-process subscriber to the "redb.Route" meter on this context. The /// listener is disposed when the context stops; calling twice keeps the first subscriber. /// public static IRouteContext UseMetricsSnapshot(this IRouteContext context) { ArgumentNullException.ThrowIfNull(context); if (context.GetService() is not null) return context; var listener = new MetricsSnapshotListener(); context.AddService(typeof(IMetricsSnapshot), listener); context.AddLifecycleListener(new DisposeOnStop(listener)); return context; } /// DI registration: services.AddMetricsSnapshot(). public static IServiceCollection AddMetricsSnapshot(this IServiceCollection services) { ArgumentNullException.ThrowIfNull(services); services.TryAddSingleton(_ => new MetricsSnapshotListener()); return services; } /// /// Resolves the snapshot, or null when none was registered — there is deliberately no /// always-on default. /// public static IMetricsSnapshot? GetMetricsSnapshot(this IRouteContext? context) => context?.GetService() ?? context?.GetServiceProvider()?.GetService(typeof(IMetricsSnapshot)) as IMetricsSnapshot; private sealed class DisposeOnStop(IDisposable listener) : IRouteLifecycleListener { public Task OnContextStopped(IRouteContext context, CancellationToken ct) { listener.Dispose(); return Task.CompletedTask; } } } Path: redb-route/redb.Route/Telemetry/ProcessorMetrics.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/Telemetry/ProcessorMetrics.cs ---- using System.Diagnostics.Metrics; namespace redb.Route.Telemetry; /// /// Metrics instruments for EIP processors (CircuitBreaker, Throttle, Filter, Debounce, etc.). /// Subscribe to meter ("redb.Route") to capture these. /// public static class ProcessorMetrics { // ── Circuit Breaker ───────────────────────────────────────── /// Number of times a circuit breaker tripped to Open state. public static readonly Counter CircuitBreakerTripped = RouteMetrics.Meter.CreateCounter("redb.route.circuitbreaker.tripped", "times", "Circuit breaker state transitions to Open."); /// Exchanges rejected while circuit is Open. public static readonly Counter CircuitBreakerRejected = RouteMetrics.Meter.CreateCounter("redb.route.circuitbreaker.rejected", "exchanges", "Exchanges rejected by an open circuit breaker."); // ── Throttle ──────────────────────────────────────────────── /// Exchanges delayed by throttle (rate limiter). public static readonly Counter ThrottleDelayed = RouteMetrics.Meter.CreateCounter("redb.route.throttle.delayed", "exchanges", "Exchanges delayed due to rate limiting."); // ── Filter ────────────────────────────────────────────────── /// Exchanges dropped by filter predicates. public static readonly Counter FilterDropped = RouteMetrics.Meter.CreateCounter("redb.route.filter.dropped", "exchanges", "Exchanges dropped by a filter predicate."); // ── Debounce ──────────────────────────────────────────────── /// Exchanges discarded (superseded by a newer message for the same key). public static readonly Counter DebounceDiscarded = RouteMetrics.Meter.CreateCounter("redb.route.debounce.discarded", "exchanges", "Exchanges replaced before the quiet period elapsed."); /// Exchanges flushed (forwarded after quiet period). public static readonly Counter DebounceFlushed = RouteMetrics.Meter.CreateCounter("redb.route.debounce.flushed", "exchanges", "Exchanges forwarded after the debounce quiet period."); // ── Splitter ──────────────────────────────────────────────── /// Total parts produced by splitter processors. public static readonly Counter SplitterParts = RouteMetrics.Meter.CreateCounter("redb.route.splitter.parts", "parts", "Total parts produced by splitter processors."); // ── Timeout ───────────────────────────────────────────────── /// Exchanges that exceeded the configured timeout. public static readonly Counter TimeoutExpired = RouteMetrics.Meter.CreateCounter("redb.route.timeout.expired", "exchanges", "Exchanges that exceeded their processing timeout."); // ── WireTap ───────────────────────────────────────────────── /// Clones successfully dispatched to a wire-tap branch (fire-and-forget). public static readonly Counter WireTapDispatched = RouteMetrics.Meter.CreateCounter("redb.route.wiretap.dispatched", "exchanges", "Clones successfully handed off to a wire-tap branch."); /// Wire-tap branch failures. Logged but never propagated to the main pipeline. public static readonly Counter WireTapFailed = RouteMetrics.Meter.CreateCounter("redb.route.wiretap.failed", "exchanges", "Wire-tap branches that failed in background. Never affects the main pipeline."); // ── OnCompletion ──────────────────────────────────────────── /// OnCompletion blocks that failed; logged, never the route's outcome. public static readonly Counter OnCompletionFailed = RouteMetrics.Meter.CreateCounter("redb.route.oncompletion.failed", "blocks", "OnCompletion blocks that failed. Never changes the route's outcome."); // ── Detached pools (WireTap, asynchronous OnCompletion) ───── // Tagged with the profile ("default" or the executorService name), the step ("wireTap", "onCompletion") and the // route, so an operator sees which pool fills up and when request threads start paying for a tap. /// Branches running on a detached step's pool. public static readonly UpDownCounter PoolActive = RouteMetrics.Meter.CreateUpDownCounter("redb.route.pool.active", "branches", "Branches running on a detached step's pool."); /// Branches waiting in a detached step's pool queue. public static readonly UpDownCounter PoolQueued = RouteMetrics.Meter.CreateUpDownCounter("redb.route.pool.queued", "branches", "Branches waiting in a detached step's pool queue."); /// Branches the caller ran itself because the pool and its queue were full (CallerRuns). public static readonly Counter PoolCallerRuns = RouteMetrics.Meter.CreateCounter("redb.route.pool.caller_runs", "branches", "Branches the caller ran itself because the pool and its queue were full."); /// Branches dropped or refused because the pool and its queue were full (Discard, Abort). public static readonly Counter PoolRejected = RouteMetrics.Meter.CreateCounter("redb.route.pool.rejected", "branches", "Branches dropped or refused because the pool and its queue were full."); /// Branches that failed on a detached step's pool. public static readonly Counter PoolFailed = RouteMetrics.Meter.CreateCounter("redb.route.pool.failed", "branches", "Branches that failed on a detached step's pool."); /// Branches still running or waiting when the context's shutdown timeout ran out. public static readonly Counter PoolNotDrained = RouteMetrics.Meter.CreateCounter("redb.route.pool.not_drained", "branches", "Branches still running or waiting when the shutdown timeout ran out."); // ── Multicast ─────────────────────────────────────────────── /// Number of branches dispatched per multicast invocation (histogram). public static readonly Histogram MulticastBranches = RouteMetrics.Meter.CreateHistogram("redb.route.multicast.branches", "branches", "Number of target branches dispatched per multicast invocation."); /// Multicast branches that failed with an unhandled exception. public static readonly Counter MulticastFailedBranches = RouteMetrics.Meter.CreateCounter("redb.route.multicast.failed_branches", "branches", "Multicast target branches that failed with an unhandled exception."); // ── Recipient List ────────────────────────────────────────── /// Number of recipients resolved per recipient-list invocation (histogram). public static readonly Histogram RecipientListRecipients = RouteMetrics.Meter.CreateHistogram("redb.route.recipientlist.recipients", "recipients", "Number of recipients resolved per recipient-list invocation."); // ── Aggregator ────────────────────────────────────────────── /// Aggregation groups completed by the completion predicate. public static readonly Counter AggregatorCompleted = RouteMetrics.Meter.CreateCounter("redb.route.aggregator.completed", "groups", "Aggregation groups closed by the completion predicate."); /// Aggregation groups closed by inactivity / completion timeout. public static readonly Counter AggregatorTimedOut = RouteMetrics.Meter.CreateCounter("redb.route.aggregator.timed_out", "groups", "Aggregation groups closed because their timeout elapsed before completion."); /// Aggregation groups currently kept in memory waiting for completion (up/down). public static readonly UpDownCounter AggregatorInflightGroups = RouteMetrics.Meter.CreateUpDownCounter("redb.route.aggregator.inflight_groups", "groups", "Aggregation groups currently buffered in memory waiting for completion or timeout."); // ── Idempotent Consumer ───────────────────────────────────── /// Exchanges identified as duplicates by the idempotent consumer. public static readonly Counter IdempotentDuplicate = RouteMetrics.Meter.CreateCounter("redb.route.idempotent.duplicate", "exchanges", "Exchanges suppressed by the idempotent consumer as duplicates."); /// Exchanges accepted (first occurrence) by the idempotent consumer. public static readonly Counter IdempotentPassed = RouteMetrics.Meter.CreateCounter("redb.route.idempotent.passed", "exchanges", "Exchanges that passed the idempotent consumer for the first time."); // ── Retry / Redelivery ────────────────────────────────────── /// Total retry attempts performed by RetryProcessor / OnException redelivery. public static readonly Counter RetryAttempts = RouteMetrics.Meter.CreateCounter("redb.route.retry.attempts", "attempts", "Total retry attempts performed before final success or give-up."); /// Exchanges that succeeded only after one or more retries. public static readonly Counter RetrySuccess = RouteMetrics.Meter.CreateCounter("redb.route.retry.success", "exchanges", "Exchanges that ultimately succeeded after at least one retry."); /// Exchanges that exhausted all retries and failed. public static readonly Counter RetryExhausted = RouteMetrics.Meter.CreateCounter("redb.route.retry.exhausted", "exchanges", "Exchanges that exhausted all retry attempts without success."); // ── Saga ──────────────────────────────────────────────────── /// Sagas that completed successfully end-to-end. public static readonly Counter SagaCompleted = RouteMetrics.Meter.CreateCounter("redb.route.saga.completed", "sagas", "Sagas that completed all forward steps successfully."); /// Sagas that ran compensation after a forward-step failure. public static readonly Counter SagaCompensated = RouteMetrics.Meter.CreateCounter("redb.route.saga.compensated", "sagas", "Sagas that triggered compensation actions after a forward-step failure."); /// Sagas where both a forward step and compensation failed. public static readonly Counter SagaFailed = RouteMetrics.Meter.CreateCounter("redb.route.saga.failed", "sagas", "Sagas that failed and could not fully compensate."); // ── Dead-Letter Channel ───────────────────────────────────── /// Exchanges routed to a dead-letter channel after retries were exhausted. public static readonly Counter DeadLetterSent = RouteMetrics.Meter.CreateCounter("redb.route.deadletter.sent", "exchanges", "Exchanges routed to a dead-letter channel after exhausting retries."); } Path: redb-route/redb.Route/Telemetry/RouteActivitySource.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/Telemetry/RouteActivitySource.cs ---- using System.Diagnostics; namespace redb.Route.Telemetry; /// /// Centralized telemetry identifiers and the shared /// for the route engine. Consumers of OpenTelemetry subscribe with /// .AddSource(RouteActivitySource.SourceName) for traces and /// .AddMeter(RouteMetrics.MeterName) for metrics; both use the same /// canonical name ("redb.Route"). /// public static class RouteActivitySource { /// Canonical telemetry name shared by the meter and the activity source. public const string TelemetryName = "redb.Route"; /// Source name used for OpenTelemetry tracing instrumentation. public const string SourceName = TelemetryName; /// The shared activity source instance. public static readonly ActivitySource Source = new(SourceName, GetVersion()); private static string GetVersion() { return typeof(RouteActivitySource).Assembly.GetName().Version?.ToString() ?? "0.0.0"; } } Path: redb-route/redb.Route/Telemetry/RouteMetrics.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/Telemetry/RouteMetrics.cs ---- using System.Diagnostics.Metrics; namespace redb.Route.Telemetry; /// /// Provides and standard counters/histograms for route engine metrics. /// Consumers subscribe to meter name via OpenTelemetry. /// public static class RouteMetrics { /// Meter name for OpenTelemetry subscription. Same canonical name as the activity source. public const string MeterName = RouteActivitySource.TelemetryName; internal static readonly Meter Meter = new(MeterName, GetVersion()); /// Total exchanges processed (counter). public static readonly Counter ExchangesProcessed = Meter.CreateCounter("redb.route.exchanges.processed", "exchanges", "Total exchanges processed by all routes."); /// Exchanges that failed with an unhandled exception (counter). public static readonly Counter ExchangesFailed = Meter.CreateCounter("redb.route.exchanges.failed", "exchanges", "Exchanges that resulted in an unhandled exception."); /// Exchange processing duration (histogram). public static readonly Histogram ExchangeDuration = Meter.CreateHistogram("redb.route.exchange.duration", "ms", "Duration of exchange processing in milliseconds."); /// Currently active exchanges being processed (up-down counter). public static readonly UpDownCounter ExchangesInflight = Meter.CreateUpDownCounter("redb.route.exchanges.inflight", "exchanges", "Number of exchanges currently being processed."); private static string GetVersion() { return typeof(RouteMetrics).Assembly.GetName().Version?.ToString() ?? "0.0.0"; } } Path: redb-route/redb.Route/Telemetry/RouteTelemetryExtensions.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/Telemetry/RouteTelemetryExtensions.cs ---- using System.Diagnostics; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Telemetry; /// Reads one trace field (traceparent, tracestate, baggage) from a transport carrier; /// null when the carrier does not hold it. Header names are compared the way the transport compares them. /// Headers, message properties, attributes — whatever the transport carries. public delegate string? TraceHeaderReader(TCarrier carrier, string name); /// Writes one trace field to a transport carrier, replacing a value already there: a header copied /// from the incoming message names the previous hop, not this one. /// Headers, message properties, attributes — whatever the transport carries. public delegate void TraceHeaderWriter(TCarrier carrier, string name, string value); /// Where an inbound span takes its parent from. public enum InboundParent { /// /// From the trace fields of the message itself. Without them the span is a root: the thread's ambient activity /// (a poll loop, a host span of some other work) is never the parent of a message it did not send. /// Carrier, /// /// The host's span for this same request, when there is one — an ASP.NET Core server span has already taken the /// caller's context from the request headers. Without one the carrier is read, as with . /// HostRequest, } /// /// An inbound transport span opened by . Disposing /// it ends the span and gives the thread back the ambient activity it had before. /// public readonly struct TransportSpan : IDisposable { private readonly Activity? _ambient; internal TransportSpan(Activity? activity, Activity? ambient) { Activity = activity; _ambient = ambient; } /// The span; null when nobody listens or tracing is off for the context. public Activity? Activity { get; } /// public void Dispose() { if (Activity is null) return; Activity.Dispose(); // A span with a remote parent or none stops into a null current; the thread had its own before. System.Diagnostics.Activity.Current = _ambient; } } /// /// The tracing contract of a transport, on the shared : open the span /// ( /// outbound, inbound), carry the context to the next hop /// () and mark a failed call (). Every span /// carries redb.route.endpoint, sanitized, and honours RouteEngineOptions.EnableTelemetry of the context. /// A connector supplies only the carrier and its names; the W3C and baggage handling lives here once. /// public static class RouteTelemetryExtensions { /// /// Whether spans are opened for : its RouteEngineOptions.EnableTelemetry. /// true without a context — a component used on its own traces as before. /// public static bool IsTracingEnabled(this IRouteContext? context) => (context as RouteContext)?.TelemetryEnabled ?? true; /// /// Starts a messaging / RPC / I/O span for a transport operation. /// Tags are emitted following the OpenTelemetry semantic conventions for the /// supplied namespace. Does not read EnableTelemetry; a connector passes its /// context to the overload that does. /// /// Span name, e.g. "queue.name publish" or "GET /users/{id}". /// Activity kind (Producer / Consumer / Client / Server). /// /// Semantic-convention attribute name. Use "messaging.system" for brokers, /// "db.system" for databases, "rpc.system" for gRPC, /// "http.method" for plain HTTP or "file.system" for file transports. /// /// Value of the (e.g. "rabbitmq"). /// The full redb.route endpoint URI; always emitted as redb.route.endpoint. /// Optional destination (queue/topic/path) emitted as messaging.destination.name. /// Optional verb emitted as messaging.operation when relevant. /// The opened activity, or null when no listener is active. public static Activity? StartTransportSpan( string name, ActivityKind kind, string systemAttribute, string systemValue, string endpointUri, string? destination = null, string? operation = null) { var activity = RouteActivitySource.Source.StartActivity(name, kind); Tag(activity, systemAttribute, systemValue, endpointUri, destination, operation); return activity; } /// /// for an /// endpoint of : null when the context has tracing off. /// /// The route context of the endpoint (ComponentBase.Context). /// Span name. /// Activity kind (Producer / Client). /// Semantic-convention attribute name. /// Value of the . /// The endpoint URI, emitted sanitized as redb.route.endpoint. /// Optional destination, emitted sanitized as messaging.destination.name. /// Optional verb emitted as messaging.operation. public static Activity? StartTransportSpan( IRouteContext? context, string name, ActivityKind kind, string systemAttribute, string systemValue, string endpointUri, string? destination = null, string? operation = null) => context.IsTracingEnabled() ? StartTransportSpan(name, kind, systemAttribute, systemValue, endpointUri, destination, operation) : null; /// /// Opens the span of an inbound message or request. Its parent is chosen by ; with /// the W3C fields are read from and, when absent, /// the span is a root — never a child of whatever activity the receiving thread happens to hold. The baggage /// the sender put on its activity is put back on this one, so the route's own spans and sends carry it on. /// /// The route context of the endpoint; tracing off opens nothing. /// Span name, e.g. "orders receive". /// for a message, for a request. /// Semantic-convention attribute name. /// Value of the . /// The endpoint URI, emitted sanitized as redb.route.endpoint. /// The incoming message's headers or properties. /// Reads one field from . /// Where the parent comes from. /// Optional destination, emitted sanitized as messaging.destination.name. /// Optional verb emitted as messaging.operation. /// Links to other contexts, e.g. every message of a batch (). public static TransportSpan StartConsumerSpan( IRouteContext? context, string name, ActivityKind kind, string systemAttribute, string systemValue, string endpointUri, TCarrier carrier, TraceHeaderReader readHeader, InboundParent parent = InboundParent.Carrier, string? destination = null, string? operation = null, IEnumerable? links = null) { ArgumentNullException.ThrowIfNull(readHeader); if (!context.IsTracingEnabled()) return default; var ambient = Activity.Current; Activity? activity; if (parent == InboundParent.HostRequest && ambient is not null) { activity = RouteActivitySource.Source.StartActivity(name, kind, parentContext: default, tags: null, links); } else { var fields = new CarrierReader(carrier, readHeader); var remote = Extract(fields); // StartActivity with a default parent context falls back to Activity.Current rather than starting a root // (the house pattern, see DetachedDispatch.Enter): clear it for the start, give it back on dispose. Activity.Current = null; activity = RouteActivitySource.Source.StartActivity(name, kind, remote, tags: null, links); if (activity is null) { Activity.Current = ambient; } else if (DistributedContextPropagator.Current.ExtractBaggage(fields, Getter) is { } baggage) { // AddBaggage puts an item first; adding in reverse keeps the sender's order. foreach (var (key, value) in baggage.Reverse()) activity.AddBaggage(key, value); } } Tag(activity, systemAttribute, systemValue, endpointUri, destination, operation); return new TransportSpan(activity, ambient); } /// /// The W3C context holds, or default when it holds none or an invalid one. For /// links: a batch span links the context of every message it carries. /// /// The message's headers or properties. /// Reads one field from . public static ActivityContext ExtractTraceContext(TCarrier carrier, TraceHeaderReader readHeader) { ArgumentNullException.ThrowIfNull(readHeader); return Extract(new CarrierReader(carrier, readHeader)); } /// /// Writes the trace context of — or, without one, of the ambient activity — to an /// outgoing message: traceparent, tracestate and the baggage, through the process's /// . A context the route received is passed on even with tracing off, /// so a redb hop does not cut the trace of the systems around it. Writes nothing when there is no context. /// /// The send span; null falls back to . /// The outgoing message's headers or properties. /// Writes one field, replacing a value already there. public static void InjectTraceContext(Activity? activity, TCarrier carrier, TraceHeaderWriter writeHeader) { ArgumentNullException.ThrowIfNull(writeHeader); activity ??= Activity.Current; if (activity is null) return; DistributedContextPropagator.Current.Inject(activity, new CarrierWriter(carrier, writeHeader), Setter); } /// /// Marks the span failed by : status and an /// OpenTelemetry exception event — the shape the route spans use, so a failed call shows red on the /// transport span, not only on the route above it. /// /// The span; null does nothing. /// What failed. public static void RecordFailure(this Activity? activity, Exception exception) { ArgumentNullException.ThrowIfNull(exception); if (activity is null) return; activity.SetStatus(ActivityStatusCode.Error, exception.Message); if (activity.IsAllDataRequested) activity.RecordException(exception); } private static void Tag(Activity? activity, string systemAttribute, string systemValue, string endpointUri, string? destination, string? operation) { if (activity is not { IsAllDataRequested: true }) return; activity.SetTag(systemAttribute, systemValue); activity.SetTag("redb.route.endpoint", EndpointUri.Sanitize(endpointUri)); // The destination is often a full URL and may carry a userinfo password or a // sensitive query value; Sanitize is format-preserving and leaves plain names // (queues, topics) byte-for-byte. if (!string.IsNullOrEmpty(destination)) activity.SetTag("messaging.destination.name", EndpointUri.Sanitize(destination)); if (!string.IsNullOrEmpty(operation)) activity.SetTag("messaging.operation", operation); } private static ActivityContext Extract(ICarrierReader fields) { DistributedContextPropagator.Current.ExtractTraceIdAndState(fields, Getter, out var traceParent, out var traceState); return !string.IsNullOrEmpty(traceParent) && ActivityContext.TryParse(traceParent, traceState, out var parsed) ? parsed : default; } private interface ICarrierReader { string? Read(string name); } private sealed class CarrierReader(TCarrier carrier, TraceHeaderReader read) : ICarrierReader { public string? Read(string name) => read(carrier, name); } private interface ICarrierWriter { void Write(string name, string value); } private sealed class CarrierWriter(TCarrier carrier, TraceHeaderWriter write) : ICarrierWriter { public void Write(string name, string value) => write(carrier, name, value); } private static readonly DistributedContextPropagator.PropagatorGetterCallback Getter = static (object? carrier, string name, out string? value, out IEnumerable? values) => { values = null; value = (carrier as ICarrierReader)?.Read(name); }; private static readonly DistributedContextPropagator.PropagatorSetterCallback Setter = static (carrier, name, value) => (carrier as ICarrierWriter)?.Write(name, value); } Path: redb-route/redb.Route/Telemetry/SpanTagPolicy.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/Telemetry/SpanTagPolicy.cs ---- using System.Globalization; using System.Text.RegularExpressions; using redb.Route.Abstractions; namespace redb.Route.Telemetry; /// /// The one place that decides what a .SpanTag(...) step may write: the key, checked when the route is built, /// and the value, normalized per message. The length of a value is left to the OpenTelemetry SDK /// (OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT), as for every other attribute of the engine. /// internal static class SpanTagPolicy { // The namespaces of the engine's own attributes and of the semantic conventions it emits: a step must not // overwrite them (the route span stamps redb.route.id again after its pipeline, so a step's value would not even // survive) or pass a business value off as a convention. private static readonly string[] ReservedPrefixes = ["redb.", "messaging.", "http.", "rpc.", "db.", "exception.", "otel."]; // OpenTelemetry attribute naming: lowercase, dot-separated namespaces. private static readonly Regex KeyPattern = new(@"^[a-z0-9_]+(\.[a-z0-9_]+)*$", RegexOptions.Compiled | RegexOptions.CultureInvariant); /// Refuses a key the step must not write; called when the route is built. /// The attribute name. /// The key is empty, templated, malformed, reserved or names a secret. internal static void ValidateKey(string key) { ArgumentException.ThrowIfNullOrWhiteSpace(key); if (key.Contains("${", StringComparison.Ordinal)) throw new ArgumentException( $"SpanTag key must be a constant (got template '{key}'); the value is where the message goes.", nameof(key)); if (!KeyPattern.IsMatch(key)) throw new ArgumentException( $"SpanTag key '{key}' is not an OpenTelemetry attribute name: lowercase letters, digits and '_', " + "in dot-separated segments (e.g. 'sap.order.id').", nameof(key)); foreach (var prefix in ReservedPrefixes) { if (key.StartsWith(prefix, StringComparison.Ordinal)) throw new ArgumentException( $"SpanTag key '{key}' is in the reserved namespace '{prefix}' of the engine and the semantic " + "conventions; use a namespace of your own (e.g. 'sap.order.id').", nameof(key)); } if (EndpointUri.IsSensitiveKey(key)) throw new ArgumentException( $"SpanTag key '{key}' names a secret; an attribute is exported unfiltered and must not carry one.", nameof(key)); } /// /// The attribute value for an evaluated : strings, booleans, integers and doubles as they /// are, a date in ISO 8601, anything else as invariant text; null when there is nothing to set. /// internal static object? ToAttributeValue(object? value) => value switch { null => null, string s => s.Length == 0 ? null : s, bool or int or long or double => value, DateTimeOffset d => d.ToString("O", CultureInfo.InvariantCulture), DateTime d => d.ToString("O", CultureInfo.InvariantCulture), IFormattable f => NonEmpty(f.ToString(null, CultureInfo.InvariantCulture)), _ => NonEmpty(value.ToString()), }; private static string? NonEmpty(string? text) => string.IsNullOrEmpty(text) ? null : text; } Path: redb-route/redb.Route/Telemetry/SpanTagProcessor.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/Telemetry/SpanTagProcessor.cs ---- using System.Diagnostics; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Telemetry; /// /// The processor of .SpanTag(key, value, target): puts one attribute on a span of the engine. The exchange is /// not touched. Nothing happens when there is no such span, when it records no data (no listener, not sampled) — the /// value is then not even evaluated — or when it has already ended. A value that fails to evaluate is skipped and /// logged at Debug: telemetry does not change the outcome of the message. /// internal sealed class SpanTagProcessor : IProcessor { private readonly string _key; private readonly IExpression _value; private readonly SpanTarget _target; private readonly ILogger? _logger; internal SpanTagProcessor(string key, IExpression value, SpanTarget target, ILogger? logger) { _key = key; _value = value; _target = target; _logger = logger; } /// public Task Process(IExchange exchange, CancellationToken ct = default) { var span = _target == SpanTarget.Inbound ? (exchange as Exchange)?.InboundSpan : EnclosingSpan(); if (span is not { IsAllDataRequested: true } || span.IsStopped) return Task.CompletedTask; object? value; try { value = SpanTagPolicy.ToAttributeValue(_value.Evaluate(exchange)); } catch (Exception ex) when (ex is not OperationCanceledException) { _logger?.LogDebug(ex, "SpanTag '{Key}': the value could not be evaluated; the attribute is not set.", _key); return Task.CompletedTask; } if (value is not null) span.SetTag(_key, value); return Task.CompletedTask; } /// /// The nearest span of the engine from up: an internal one (a Traced scope, the /// route span, a detached branch) or nothing. A transport span reached first means route tracing is off — no /// attribute then — and a span of another source is passed over, never written. /// private static Activity? EnclosingSpan() { for (var span = Activity.Current; span is not null; span = span.Parent) { if (span.Source == RouteActivitySource.Source) return span.Kind == ActivityKind.Internal ? span : null; } return null; } } Path: redb-route/redb.Route/Telemetry/SpanTarget.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/Telemetry/SpanTarget.cs ---- namespace redb.Route.Telemetry; /// Which span a .SpanTag(...) step puts its attribute on. public enum SpanTarget { /// /// The nearest span of redb.Route around the step: the enclosing Traced(...) scope, else the route span. /// With route tracing off (.Tracing(false)) there is none and no attribute is set — never on a transport /// span or on a span of the host. /// Enclosing, /// /// The inbound span of the transport that received the exchange — the server span of an HTTP, SOAP or gRPC request, /// the consumer span of a broker message or a scheduler fire. A route called through direct: keeps the /// caller's. Not the host's own span (ASP.NET Core): that one belongs to the host. /// Inbound, } Path: redb-route/redb.Route/Telemetry/StepMetrics.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/Telemetry/StepMetrics.cs ---- using System.Diagnostics.Metrics; namespace redb.Route.Telemetry; /// /// Per-step metric instruments for the .Metered() DSL. /// Uses the same as to allow a single /// .AddMeter("redb.Route") subscription in OpenTelemetry configuration. /// public static class StepMetrics { private static readonly Meter _meter = RouteMetrics.Meter; /// Total step executions completed successfully. public static readonly Counter StepProcessed = _meter.CreateCounter("redb.route.step.processed", "exchanges", "Total exchanges processed by a named step."); /// Step executions that failed with an unhandled exception. public static readonly Counter StepFailed = _meter.CreateCounter("redb.route.step.failed", "exchanges", "Exchanges that failed at a named step."); /// Step execution duration histogram. public static readonly Histogram StepDuration = _meter.CreateHistogram("redb.route.step.duration", "ms", "Duration of a named step execution in milliseconds."); } Path: redb-route/redb.Route/Transactions/BeginTransactionProcessor.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/Transactions/BeginTransactionProcessor.cs ---- using System.Collections.Concurrent; using System.Transactions; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; namespace redb.Route.Transactions; /// /// Imperative transaction processor that opens a /// and stores it on the exchange for later commit/rollback. /// /// Use or /// to explicitly close the scope. If neither is called, the scope will be /// disposed (rolled back) when the exchange completes. /// /// public sealed class BeginTransactionProcessor : IProcessor { /// Well-known exchange property key for the active . internal const string ScopePropertyKey = "TRANSACTION_SCOPE"; /// /// Set when the block is a unit of work of its own: holds the enclosing block's set of deferred actions (or a marker /// for none), which its commit or rollback puts back. Absent when the block joined an enclosing one. /// internal const string EnclosingActionsPropertyKey = "TRANSACTION_ENCLOSING_ACTIONS"; private static readonly object NoEnclosingActions = new(); private readonly TransactionPolicy _policy; private readonly ILogger? _logger; /// Creates a begin-transaction processor. /// Transaction policy (scope option, timeout, isolation level). /// Optional logger. public BeginTransactionProcessor(TransactionPolicy? policy = null, ILogger? logger = null) { _policy = policy ?? TransactionPolicy.Default; _logger = logger; } /// public Task Process(IExchange exchange, CancellationToken ct = default) { // The same rules as .Transacted(): a Required block inside a running transaction joins it and leaves its sends to // the enclosing block; otherwise the block keeps a set of its own until CommitTransaction or // RollbackTransaction, which puts the enclosing set back, so a transacted send after the block is refused // instead of deferred into a set nobody commits. var joins = TransactedActions.JoinsEnclosingBlock(exchange, _policy); var scope = _policy.CreateScope(); exchange.Properties[ScopePropertyKey] = scope; if (!joins) exchange.Properties[EnclosingActionsPropertyKey] = (object?)TransactedActions.Open(exchange) ?? NoEnclosingActions; _logger?.LogDebug( "Transaction started imperatively (ScopeOption={ScopeOption}, IsolationLevel={IsolationLevel}, Joined={Joined}).", _policy.ScopeOption, _policy.IsolationLevel, joins); return Task.CompletedTask; } /// /// Takes the block's own set off the exchange. Returns true, with the enclosing block's set or null, /// when the block was a unit of work of its own; false when it joined an enclosing block. /// internal static bool TryTakeOwnActions(IExchange exchange, out ConcurrentDictionary? enclosing) { enclosing = null; if (!exchange.Properties.TryGetValue(EnclosingActionsPropertyKey, out var raw)) return false; exchange.Properties.Remove(EnclosingActionsPropertyKey); enclosing = raw as ConcurrentDictionary; return true; } } Path: redb-route/redb.Route/Transactions/CommitTransactionProcessor.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/Transactions/CommitTransactionProcessor.cs ---- using System.Transactions; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Transactions; /// /// Imperative transaction processor that commits the /// previously opened by . /// Commits the database first and the deferred instances after it, in the order /// .Transacted() uses. Joined to an enclosing block, it leaves both to that block. /// public sealed class CommitTransactionProcessor : IProcessor { private readonly ILogger? _logger; /// Creates a commit-transaction processor. /// Optional logger. public CommitTransactionProcessor(ILogger? logger = null) { _logger = logger; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { if (!exchange.Properties.TryGetValue(BeginTransactionProcessor.ScopePropertyKey, out var raw) || raw is not TransactionScope scope) { _logger?.LogWarning("CommitTransaction called but no active transaction scope found on exchange."); return; } if (exchange.IsRollbackOnly()) { // The route marked the unit of work for rollback: committing it would undo the mark. await new RollbackTransactionProcessor(_logger).Process(exchange, ct).ConfigureAwait(false); return; } exchange.Properties.Remove(BeginTransactionProcessor.ScopePropertyKey); var ownsActions = BeginTransactionProcessor.TryTakeOwnActions(exchange, out var enclosing); try { try { // The database first. Joined to an enclosing block, this only votes for the commit: the enclosing block // commits the database and the sends. try { scope.Complete(); } finally { scope.Dispose(); } } catch (Exception ex) when (ownsActions) { // The database did not commit, so no broker hears about the work. await TransactedActions.RollbackAll(exchange, _logger, ct).ConfigureAwait(false); _logger?.LogError(ex, "Transaction rolled back: the database commit failed: {Message}", ex.Message); throw; } if (!ownsActions) { _logger?.LogDebug("Joined transaction completed imperatively; the enclosing block commits it."); return; } try { await TransactedActions.CommitAll(exchange, ct).ConfigureAwait(false); } catch (Exception ex) { // The work is in the database and cannot be taken back; what is left unsent is rolled back and the // failure propagates, so the incoming message is not acknowledged and is redelivered. await TransactedActions.RollbackAll(exchange, _logger, ct).ConfigureAwait(false); _logger?.LogError(ex, "The database transaction committed, then a deferred transport action failed: {Message}. The work " + "is stored; the message is not acknowledged, so the broker will redeliver it.", ex.Message); throw; } _logger?.LogDebug("Transaction committed imperatively."); } finally { if (ownsActions) TransactedActions.Close(exchange, enclosing); } } } Path: redb-route/redb.Route/Transactions/DependentTransactionBranch.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/Transactions/DependentTransactionBranch.cs ---- using System.Transactions; namespace redb.Route.Transactions; /// /// Runs one branch of a parallel fan-out (Splitter / Multicast in parallel mode) under its own /// clone of the ambient transaction. /// /// Parallel branches are dispatched with Task.Run, which flows the caller's /// . Because the route's /// is created with , every branch would /// otherwise observe — and concurrently enlist resources in — the same /// . does not allow concurrent /// use of a single transaction across threads: a second concurrent enlistment promotes to MSDTC or /// throws "transaction context in use by another thread". /// /// /// Each branch instead gets a private via /// . /// makes the parent transaction's commit wait until every branch has signalled completion, so the /// parent never commits work a branch is still writing. Broker transports that defer via /// TRANSACT_ACTION (Kafka/Rabbit/Redis/ASB/AMQP) do not enlist and are unaffected either way; /// this matters for resources that DO enlist (SQL/ADO.NET, redb DB work). /// /// No-op when there is no ambient transaction — the overwhelmingly common, non-transacted case. /// internal static class DependentTransactionBranch { /// /// Executes isolated under a dependent clone of the ambient transaction. /// When no ambient transaction is present the branch runs directly with zero overhead. /// internal static async Task RunAsync(Func branch) { var ambient = Transaction.Current; if (ambient is null) { await branch().ConfigureAwait(false); return; } // Fork a dependent clone so this branch's resource enlistment is private to this thread. var dependent = ambient.DependentClone(DependentCloneOption.BlockCommitUntilComplete); // New ambient for this branch is the dependent; resources opened inside branch() enlist in it. using (var scope = new TransactionScope(dependent, TransactionScopeAsyncFlowOption.Enabled)) { await branch().ConfigureAwait(false); scope.Complete(); } // Signal the dependent is finished so the parent's BlockCommitUntilComplete commit can proceed. // Reached only on the success path: if branch() throws, the scope above disposes without // Complete(), which aborts the (whole) transaction — the parent is then released by the abort, // not by this signal, so there is no deadlock. dependent.Complete(); } } Path: redb-route/redb.Route/Transactions/RollbackTransactionProcessor.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/Transactions/RollbackTransactionProcessor.cs ---- using System.Transactions; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; namespace redb.Route.Transactions; /// /// Imperative transaction processor that rolls back the /// previously opened by . /// Rolls back all deferred instances, then disposes the scope /// without calling . Joined to an enclosing block, it marks the enclosing /// transaction for rollback, and the enclosing block rolls back the database and every send. /// public sealed class RollbackTransactionProcessor : IProcessor { private readonly ILogger? _logger; /// Creates a rollback-transaction processor. /// Optional logger. public RollbackTransactionProcessor(ILogger? logger = null) { _logger = logger; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { if (!exchange.Properties.TryGetValue(BeginTransactionProcessor.ScopePropertyKey, out var raw) || raw is not TransactionScope scope) { _logger?.LogWarning("RollbackTransaction called but no active transaction scope found on exchange."); return; } exchange.Properties.Remove(BeginTransactionProcessor.ScopePropertyKey); var ownsActions = BeginTransactionProcessor.TryTakeOwnActions(exchange, out var enclosing); try { if (ownsActions) await TransactedActions.RollbackAll(exchange, _logger, ct).ConfigureAwait(false); // Dispose without Complete → automatic rollback scope.Dispose(); } finally { if (ownsActions) TransactedActions.Close(exchange, enclosing); } _logger?.LogDebug("Transaction rolled back imperatively."); } } Path: redb-route/redb.Route/Transactions/TransactedActions.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/Transactions/TransactedActions.cs ---- using System.Collections.Concurrent; using System.Transactions; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; namespace redb.Route.Transactions; /// /// Registration of deferred transport actions: an outgoing send or write that a transacted endpoint /// (transacted=true) postpones until the enclosing .Transacted() block has committed the database. /// /// An action is accepted only inside an active block. Outside one — a transacted step on a route without /// .Transacted(), or after the block has ended — nothing would ever commit it and the write would silently /// disappear, so registration fails instead. /// /// public static class TransactedActions { /// Whether is inside an active transacted block. public static bool IsActive(IExchange exchange) { ArgumentNullException.ThrowIfNull(exchange); return Find(exchange) is not null; } /// /// Whether a producer defers its send to the enclosing transacted block, by its transacted parameter. /// Unset, the send follows the block, as in Camel: deferred inside .Transacted(), sent at once outside it. /// false sends at once even inside a block. true always defers, so outside a block /// refuses the send instead of losing it. /// /// The exchange the producer is processing. /// The producer's transacted parameter; null when the route did not set it. public static bool Defers(IExchange exchange, bool? transacted) => transacted ?? IsActive(exchange); /// /// Defers to the enclosing transacted block, which commits it after the database or rolls /// it back on failure. Throws when the exchange is not inside one. /// /// The exchange the step is processing. /// A key unique within the block. /// The deferred action. /// A short, secret-free description of the endpoint for the error message. public static void Register(IExchange exchange, string key, ITransactedAction action, string endpoint) { ArgumentNullException.ThrowIfNull(exchange); ArgumentException.ThrowIfNullOrEmpty(key); ArgumentNullException.ThrowIfNull(action); if (Find(exchange) is not { } actions) throw NotInBlock(endpoint); if (actions is BlockActions block) block.Put(key, action); else actions[key] = action; } /// /// Defers a prepared send to the enclosing transacted block: runs once the database has /// committed and is dropped on rollback. Build everything the send needs from the exchange before registering it; /// the delegate runs after the rest of the block. Throws, as does, outside a block. /// /// The exchange the step is processing. /// A key unique within the block. /// The send, run on commit. /// A short, secret-free description of the endpoint for the error message. public static void RegisterSend(IExchange exchange, string key, Func send, string endpoint) { ArgumentNullException.ThrowIfNull(send); Register(exchange, key, new DeferredSend(send), endpoint); } /// /// The batch a producer keeps in the enclosing block under : the one it registered earlier in the /// block, or a new one from . A producer that commits all its deferred sends of a block in one /// native transaction of its broker collects them in such a batch, which keeps the place of the first send in the /// block's commit order. Throws, as does, outside a block. /// /// The exchange the step is processing. /// The producer's key, the same for every send it defers in a block. /// Creates the batch for the first send of the block. /// A short, secret-free description of the endpoint for the error message. public static TBatch JoinBatch(IExchange exchange, string key, Func create, string endpoint) where TBatch : class, ITransactedAction { ArgumentNullException.ThrowIfNull(exchange); ArgumentException.ThrowIfNullOrEmpty(key); ArgumentNullException.ThrowIfNull(create); if (Find(exchange) is not { } actions) throw NotInBlock(endpoint); var action = actions is BlockActions block ? block.GetOrPut(key, create) : actions.GetOrAdd(key, _ => create()); return action as TBatch ?? throw new InvalidOperationException($"'{key}' holds a {action.GetType().Name}, not the batch of '{endpoint}'."); } private static InvalidOperationException NotInBlock(string endpoint) => new( $"'{endpoint}' is transacted: its write is deferred until the enclosing .Transacted() block commits, " + "and this step is not inside one, so nothing would ever commit the write. Put the step inside " + ".Transacted() ... .End(), or drop transacted=true to write at once."); private sealed class DeferredSend(Func send) : ITransactedAction { public Task Commit(CancellationToken ct = default) => send(ct); public Task Rollback(CancellationToken ct = default) => Task.CompletedTask; } /// /// Whether a block with joins the block it runs in: a Required or Mandatory block inside a /// running transaction is part of that unit of work, and its sends leave with the enclosing commit. /// internal static bool JoinsEnclosingBlock(IExchange exchange, TransactionPolicy policy) => policy.JoinsRunningTransaction && Transaction.Current is not null && IsActive(exchange); /// /// The set of the block the exchange is in, or null outside a block. A set whose block has ended does not /// count: a copy of the exchange (a clone kept by an aggregator, a resequencer, a late hand-off) still holds it, and /// a send registered there would be committed by nobody. /// internal static ConcurrentDictionary? Find(IExchange exchange) => exchange.Properties.TryGetValue(TransactedProcessor.TransactActionPropertyKey, out var raw) && raw is ConcurrentDictionary set && set is not BlockActions { IsClosed: true } ? set : null; /// Opens an empty set for a block of its own and returns the enclosing block's set, if any. internal static ConcurrentDictionary? Open(IExchange exchange) { var enclosing = Find(exchange); exchange.Properties[TransactedProcessor.TransactActionPropertyKey] = new BlockActions(); return enclosing; } /// Closes the block's set for good and puts back the enclosing block's set, if there was one. internal static void Close(IExchange exchange, ConcurrentDictionary? enclosing) { if (exchange.Properties.TryGetValue(TransactedProcessor.TransactActionPropertyKey, out var raw) && raw is BlockActions own) { own.Close(); } if (enclosing is null) exchange.Properties.Remove(TransactedProcessor.TransactActionPropertyKey); else exchange.Properties[TransactedProcessor.TransactActionPropertyKey] = enclosing; } /// /// Detaches a copy of the exchange that is handed over asynchronously (seda:, vm:, an InOnly /// .Threads() worker) from the sending block. The copy runs later, on another flow, as a unit of work of its /// own, as it does in Camel, where a transaction belongs to the thread that opened it. /// internal static void DetachFromBlock(IExchange copy) => copy.Properties.Remove(TransactedProcessor.TransactActionPropertyKey); /// /// The deferred actions of one block, in the order the route registered them (two sends to one queue must not /// arrive swapped); closed for good when the block ends. /// private sealed class BlockActions() : ConcurrentDictionary(StringComparer.OrdinalIgnoreCase) { private readonly ConcurrentQueue _order = new(); private volatile bool _closed; public bool IsClosed => _closed; public void Close() => _closed = true; /// Registers under ; a key seen before keeps its place. public void Put(string key, ITransactedAction action) { if (TryAdd(key, action)) _order.Enqueue(key); else this[key] = action; } /// The action under , registered by the first time. public ITransactedAction GetOrPut(string key, Func create) { if (TryGetValue(key, out var existing)) return existing; var created = create(); Put(key, created); return created; } /// /// The actions still in the set, in registration order. An action put straight into the dictionary (code that /// writes the TRANSACT_ACTION property itself) has no recorded place and follows the others, so none is skipped. /// public IEnumerable> InOrder() { var seen = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (var key in _order) { if (seen.Add(key) && TryGetValue(key, out var action)) yield return new KeyValuePair(key, action); } foreach (var kvp in this) { if (!seen.Contains(kvp.Key)) yield return kvp; } } } /// The set's actions in registration order (a set the block did not create has none to keep). private static IEnumerable> InOrder(ConcurrentDictionary actions) => actions is BlockActions block ? block.InOrder() : actions; /// /// Commits the block's deferred actions. Called once the database transaction has closed. A committed action is /// taken out of the set, so a later attempt (Retry outside the transaction) never commits it a second time. /// internal static async Task CommitAll(IExchange exchange, CancellationToken ct) { var actions = Find(exchange); if (actions is null || actions.IsEmpty) return; // The block's own transaction is closed, but an enclosing block's may still be current (a RequiresNew block // inside a Required one). A deferred send belongs to no transaction, and a client that enlists in the ambient // one on its own (AMQP, Azure Service Bus) must not join the enclosing block's. using var noTransaction = new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled); foreach (var kvp in InOrder(actions).ToList()) { await kvp.Value.Commit(ct).ConfigureAwait(false); actions.TryRemove(kvp.Key, out _); } } /// /// Rolls back the block's deferred actions. A failed rollback is logged and does not hide the failure that caused /// it; rolled back or not, every action leaves the set with the attempt that registered it. /// internal static async Task RollbackAll(IExchange exchange, ILogger? logger, CancellationToken ct) { var actions = Find(exchange); if (actions is null || actions.IsEmpty) return; foreach (var kvp in InOrder(actions).ToList()) { try { await kvp.Value.Rollback(ct).ConfigureAwait(false); } catch (Exception rollbackEx) { logger?.LogWarning(rollbackEx, "Rollback failed for transacted action '{ActionKey}'. Suppressing to preserve original exception.", kvp.Key); } finally { actions.TryRemove(kvp.Key, out _); } } } } Path: redb-route/redb.Route/Transactions/TransactedProcessor.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/Transactions/TransactedProcessor.cs ---- using System.Collections.Concurrent; using System.Transactions; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Transactions; /// /// Wraps an inner processor in a and manages /// deferred commit/rollback. /// /// The block owns a of deferred actions in /// exchange.Properties["TRANSACT_ACTION"] for as long as it runs. Producers inside the block (Kafka, RabbitMQ, /// etc.) add their sends through , keyed by a per-message-unique /// name (e.g. kafka-send-{guid}, never the endpoint URI, so parallel fan-out branches to the same endpoint /// never collide). After the database commits all actions are committed; on failure they are rolled back. /// /// /// Blocks nest as in Camel: a Required or Mandatory block inside a running transaction is part of that unit of work /// and leaves its sends to the enclosing block; a RequiresNew or Suppress block is a unit of work of its own and /// settles only its own sends. /// /// public sealed class TransactedProcessor : IProcessor { /// /// Well-known exchange property key where transports store their instances. /// public const string TransactActionPropertyKey = "TRANSACT_ACTION"; private readonly IProcessor _inner; private readonly TransactionPolicy _policy; private readonly ILogger? _logger; /// Creates a transacted processor. /// Inner pipeline to wrap in a transaction. /// Transaction policy (scope option, timeout, isolation level). /// Optional logger. public TransactedProcessor(IProcessor inner, TransactionPolicy policy, ILogger? logger = null) { _inner = inner ?? throw new ArgumentNullException(nameof(inner)); _policy = policy ?? throw new ArgumentNullException(nameof(policy)); _logger = logger; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { if (TransactedActions.JoinsEnclosingBlock(exchange, _policy)) { await ProcessJoined(exchange, ct).ConfigureAwait(false); return; } // A unit of work of its own keeps its own set of deferred actions for as long as it runs and puts the enclosing // block's set back when it ends. A transacted step after the block, or on a route with no block at all, then // finds no set and fails (TransactedActions.Register) instead of deferring a write that nobody would commit. var enclosing = TransactedActions.Open(exchange); try { await ProcessUnitOfWork(exchange, ct).ConfigureAwait(false); } finally { TransactedActions.Close(exchange, enclosing); } } /// /// A Required or Mandatory block inside a running transaction: the database work joins the enclosing transaction /// and the sends stay in the enclosing set, so both commit with the enclosing block and in its order. /// private async Task ProcessJoined(IExchange exchange, CancellationToken ct) { using var scope = _policy.CreateScope(); await _inner.Process(exchange, ct).ConfigureAwait(false); if (exchange.IsRollbackOnly()) { // .RollbackAll(): leaving without Complete marks the enclosing transaction for rollback, and the enclosing // block, which sees the same mark, rolls everything back. _logger?.LogDebug("Joined transaction marked for rollback: the route marked the exchange rollback-only."); return; } if (exchange.Exception is { } failure && !exchange.ExceptionHandled) { // Leaving the scope without Complete marks the enclosing transaction for rollback: the enclosing block rolls // back the database and every deferred send with it. _logger?.LogError(failure, "Joined transaction marked for rollback: the exchange completed with an unhandled exception: {Message}", failure.Message); return; } scope.Complete(); } private async Task ProcessUnitOfWork(IExchange exchange, CancellationToken ct) { _logger?.LogDebug( "Transaction started (ScopeOption={ScopeOption}, IsolationLevel={IsolationLevel}, Timeout={Timeout}).", _policy.ScopeOption, _policy.IsolationLevel, _policy.Timeout); // The database commits first and the brokers after it, because that is the order the next service reads the // work in: a message tells it something happened and it then looks the work up by id. The failure window is // therefore "written but not announced" — the broker redelivers and the idempotent consumer absorbs the // duplicate — never "announced but not written", which would point a message at rows nobody can see. try { using (var scope = _policy.CreateScope()) { await _inner.Process(exchange, ct).ConfigureAwait(false); if (exchange.IsRollbackOnly()) { // .RollbackAll(), Camel's markRollbackOnly(): a rollback without an exception. The scope is disposed // without Complete; the consumer sees the mark and does not acknowledge the message. await TransactedActions.RollbackAll(exchange, _logger, ct).ConfigureAwait(false); _logger?.LogInformation("Transaction rolled back: the route marked the exchange rollback-only."); return; } if (exchange.Exception is { } failure && !exchange.ExceptionHandled) { // The route left an unhandled failure on the exchange (OnException without Handled(true)) and // returned normally, e.g. from a sub-route: that is a failed unit of work, not a commit. The scope // is disposed without Complete, so the database rolls back together with the brokers. await TransactedActions.RollbackAll(exchange, _logger, ct).ConfigureAwait(false); _logger?.LogError(failure, "Transaction rolled back: the exchange completed with an unhandled exception: {Message}", failure.Message); return; } scope.Complete(); } // the database transaction ends here, on dispose } catch (OperationCanceledException) { // Cancelled before the database committed: nothing was sent, roll the deferred actions back and re-throw. await TransactedActions.RollbackAll(exchange, _logger, ct).ConfigureAwait(false); _logger?.LogWarning("Transaction rolled back due to cancellation."); throw; } catch (Exception ex) { // The database did not commit, so no broker hears about the work: roll the deferred actions back. await TransactedActions.RollbackAll(exchange, _logger, ct).ConfigureAwait(false); // The block's work is undone, so an OnException ... Continued() handler must not replay the steps left in // it: routing picks up after the block, not inside it. Processors.ResumePoints.Forget(exchange, ex); _logger?.LogError(ex, "Transaction rolled back due to exception: {Message}", ex.Message); throw; } try { await TransactedActions.CommitAll(exchange, ct).ConfigureAwait(false); _logger?.LogDebug("Transaction committed successfully."); } catch (Exception ex) { // The work is in the database and cannot be taken back. Whatever is left unsent is rolled back and the // failure propagates, so the consumer does not acknowledge the message: the broker redelivers it and the // idempotent consumer keeps the second pass from doing the work twice. await TransactedActions.RollbackAll(exchange, _logger, ct).ConfigureAwait(false); _logger?.LogError(ex, "The database transaction committed, then a deferred transport action failed: {Message}. The work is " + "stored; the message is not acknowledged, so the broker will redeliver it.", ex.Message); throw; } } } Path: redb-route/redb.Route/Transactions/TransactionPolicy.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/Transactions/TransactionPolicy.cs ---- using System.Transactions; namespace redb.Route.Transactions; /// /// Defines the transactional behavior for a route or a segment of a route. /// Wraps and with sensible defaults. /// public sealed class TransactionPolicy { /// Default policy: , 30-second timeout. public static readonly TransactionPolicy Default = new(); /// /// Policy that always creates a new transaction, suspending any ambient one. /// public static readonly TransactionPolicy RequiresNew = new() { ScopeOption = TransactionScopeOption.RequiresNew }; /// /// Policy that suppresses the ambient transaction so that the inner code runs /// without any transaction context. /// public static readonly TransactionPolicy Suppress = new() { ScopeOption = TransactionScopeOption.Suppress }; /// /// Policy that requires an ambient transaction to already exist; throws /// at scope creation time if there is none. /// Use this to enforce that a route segment can never run outside of a transaction. /// public static readonly TransactionPolicy Mandatory = new() { // System.Transactions has no Mandatory option directly; emulated via a custom // ScopeOption marker checked in CreateScope (see implementation below). ScopeOption = MandatoryScopeMarker }; // Sentinel value outside the defined enum range used to mark Mandatory policies. // System.Transactions.TransactionScopeOption only defines Required, RequiresNew, Suppress. private const TransactionScopeOption MandatoryScopeMarker = (TransactionScopeOption)1000; /// /// Determines whether to join an existing ambient transaction, create a new one, /// or suppress it entirely. Default is . /// public TransactionScopeOption ScopeOption { get; init; } = TransactionScopeOption.Required; /// /// Transaction timeout. Default is 30 seconds. Use /// for long-running scenarios (not recommended for production). /// public TimeSpan Timeout { get; init; } = TimeSpan.FromSeconds(30); /// /// Transaction isolation level. Default is . /// public IsolationLevel IsolationLevel { get; init; } = IsolationLevel.ReadCommitted; /// /// Whether a block with this policy joins a transaction that is already running (Required, Mandatory) rather than /// running a unit of work of its own (RequiresNew, Suppress). /// internal bool JoinsRunningTransaction => ScopeOption == TransactionScopeOption.Required || ScopeOption == MandatoryScopeMarker; /// /// Creates a based on this policy with . /// /// A configured transaction scope. /// /// Thrown when is the Mandatory marker and no ambient /// is present. /// internal TransactionScope CreateScope() { if (ScopeOption == MandatoryScopeMarker) { if (Transaction.Current is null) { throw new InvalidOperationException( "TransactionPolicy.Mandatory requires an ambient System.Transactions.Transaction " + "to be present, but Transaction.Current was null."); } // Join the existing ambient transaction. We deliberately omit TransactionOptions // here because System.Transactions throws ArgumentException when the requested // IsolationLevel differs from the ambient transaction's level. Mandatory honors // the ambient transaction's isolation level by definition. return new TransactionScope( TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled); } var options = new TransactionOptions { Timeout = Timeout, IsolationLevel = IsolationLevel }; return new TransactionScope( ScopeOption, options, TransactionScopeAsyncFlowOption.Enabled); } /// /// Parses a well-known policy name into a instance. /// Supported values: "Required", "RequiresNew", "Suppress", "Mandatory". /// /// Case-insensitive policy name. /// Matching policy. /// Thrown when the name is not recognized. public static TransactionPolicy FromName(string name) => name?.Trim().ToUpperInvariant() switch { "REQUIRED" => Default, "REQUIRESNEW" => RequiresNew, "SUPPRESS" => Suppress, "MANDATORY" => Mandatory, _ => throw new ArgumentException($"Unknown transaction policy name: '{name}'. Expected: Required, RequiresNew, Suppress, Mandatory.", nameof(name)) }; } Path: redb-route/redb.Route/Validation/IMessageValidator.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/Validation/IMessageValidator.cs ---- using redb.Route.Abstractions; namespace redb.Route.Validation; /// /// Result of a message validation operation. /// public sealed class ValidationResult { /// Whether the validation passed. public bool IsValid { get; } /// Human-readable error messages (empty when valid). public IReadOnlyList Errors { get; } /// /// Severity for failures. Defaults to for backward /// compatibility. Adapters that produce non-blocking diagnostics may set /// . /// public ValidationSeverity Severity { get; } private ValidationResult(bool isValid, IReadOnlyList errors, ValidationSeverity severity) { IsValid = isValid; Errors = errors; Severity = severity; } /// Creates a successful validation result. public static ValidationResult Success() => new(true, Array.Empty(), ValidationSeverity.Error); /// Creates a failed validation result with one or more errors. /// Validation error messages. public static ValidationResult Failure(IReadOnlyList errors) => new(false, errors, ValidationSeverity.Error); /// Creates a failed validation result with a single error message. /// Validation error message. public static ValidationResult Failure(string error) => new(false, new[] { error }, ValidationSeverity.Error); /// Creates a failed validation result with explicit severity. /// Validation error messages. /// Severity classification. public static ValidationResult Failure(IReadOnlyList errors, ValidationSeverity severity) => new(false, errors, severity); } /// /// Contract for message validators. Validates the exchange body (or a specific part of it) /// and returns a structured . /// /// Implementations include JSON Schema validation, XSD validation, and custom predicate-based validation. /// /// public interface IMessageValidator { /// /// Validates the exchange asynchronously. The default forwards to ; /// a validator that has to consult a store or a service overrides this one, and the /// processor awaits it. /// /// The exchange to validate. /// A task yielding the validation result. Task ValidateAsync(IExchange exchange) => Task.FromResult(Validate(exchange)); /// /// Validates the exchange and returns a result indicating success or failure with error details. /// /// The exchange to validate. /// A with validation outcome and any errors. ValidationResult Validate(IExchange exchange); } Path: redb-route/redb.Route/Validation/JsonSchemaValidator.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/Validation/JsonSchemaValidator.cs ---- using System.Text.Json; using Json.Schema; using redb.Route.Abstractions; namespace redb.Route.Validation; /// /// Validates JSON message bodies against a JSON Schema (draft 2020-12 and earlier). /// Uses the JsonSchema.Net library internally. /// /// The validator extracts the body as a string and parses it, or takes a /// / body directly. /// /// public sealed class JsonSchemaValidator : IMessageValidator { private readonly JsonSchema _schema; private readonly EvaluationOptions _options; /// Creates a validator from a pre-parsed . /// The JSON Schema to validate against. public JsonSchemaValidator(JsonSchema schema) { _schema = schema ?? throw new ArgumentNullException(nameof(schema)); _options = new EvaluationOptions { OutputFormat = OutputFormat.List, RequireFormatValidation = true }; } /// Creates a validator from a JSON Schema string. /// JSON Schema as a string. public JsonSchemaValidator(string schemaJson) : this(JsonSchema.FromText(schemaJson ?? throw new ArgumentNullException(nameof(schemaJson)))) { } /// public ValidationResult Validate(IExchange exchange) { ArgumentNullException.ThrowIfNull(exchange, nameof(exchange)); JsonDocument doc; var body = exchange.In.Body; if (body is null) return ValidationResult.Failure("Message body is null"); if (body is JsonDocument jdoc) { doc = jdoc; } else if (body is JsonElement jel) { // Wrap JsonElement into JsonDocument via serialization round-trip doc = JsonDocument.Parse(jel.GetRawText()); } else if (body is string str) { try { doc = JsonDocument.Parse(str); } catch (JsonException ex) { return ValidationResult.Failure($"Invalid JSON: {ex.Message}"); } } else { // Serialize POCO to JSON first try { var json = JsonSerializer.Serialize(body, body.GetType()); doc = JsonDocument.Parse(json); } catch (Exception ex) { return ValidationResult.Failure($"Cannot serialize body to JSON: {ex.Message}"); } } var result = _schema.Evaluate(doc, _options); if (result.IsValid) return ValidationResult.Success(); var errors = new List(); if (result.Details != null) { foreach (var detail in result.Details) { if (detail.HasErrors && detail.Errors != null) { foreach (var error in detail.Errors) { errors.Add($"{detail.InstanceLocation}: {error.Value}"); } } } } if (errors.Count == 0) errors.Add("JSON Schema validation failed"); return ValidationResult.Failure(errors); } } Path: redb-route/redb.Route/Validation/PredicateValidator.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/Validation/PredicateValidator.cs ---- using redb.Route.Abstractions; using redb.Route.Predicates; namespace redb.Route.Validation; /// /// Validator that checks an against the exchange. The predicate is /// awaited through when the processor validates /// asynchronously, so a predicate that consults a store or a service does not block. A plain /// delegate is wrapped in a at the boundary. /// public sealed class PredicateValidator : IMessageValidator { private readonly IPredicate _predicate; private readonly Func? _errorFactory; private readonly string _defaultError; /// Creates a validator from a predicate instance and a fixed error message. /// The condition that must hold. /// The error reported when it does not. public PredicateValidator(IPredicate predicate, string errorMessage = "Validation failed") { _predicate = predicate ?? throw new ArgumentNullException(nameof(predicate)); _defaultError = errorMessage; } /// Creates a validator from a predicate instance and an error factory. /// The condition that must hold. /// Builds the error message from the failing exchange. public PredicateValidator(IPredicate predicate, Func errorFactory) { _predicate = predicate ?? throw new ArgumentNullException(nameof(predicate)); _errorFactory = errorFactory ?? throw new ArgumentNullException(nameof(errorFactory)); _defaultError = "Validation failed"; } /// Creates a validator from a delegate and a fixed error message. /// The condition that must hold. /// The error reported when it does not. public PredicateValidator(Func predicate, string errorMessage = "Validation failed") : this(new LambdaPredicate(predicate ?? throw new ArgumentNullException(nameof(predicate))), errorMessage) { } /// Creates a validator from a delegate and an error factory. /// The condition that must hold. /// Builds the error message from the failing exchange. public PredicateValidator(Func predicate, Func errorFactory) : this(new LambdaPredicate(predicate ?? throw new ArgumentNullException(nameof(predicate))), errorFactory) { } /// public ValidationResult Validate(IExchange exchange) { ArgumentNullException.ThrowIfNull(exchange, nameof(exchange)); return ToResult(_predicate.Matches(exchange), exchange); } /// public async Task ValidateAsync(IExchange exchange) { ArgumentNullException.ThrowIfNull(exchange, nameof(exchange)); return ToResult(await _predicate.MatchesAsync(exchange).ConfigureAwait(false), exchange); } private ValidationResult ToResult(bool holds, IExchange exchange) { if (holds) return ValidationResult.Success(); var error = _errorFactory != null ? _errorFactory(exchange) : _defaultError; return ValidationResult.Failure(error); } } Path: redb-route/redb.Route/Validation/RouteDefinitionValidator.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/Validation/RouteDefinitionValidator.cs ---- using System; using System.Collections.Generic; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; namespace redb.Route.Validation; /// /// Validates a v2 tree before compilation. Walks /// recursively and applies two kinds of rule: /// /// Per-node self-validation (e.g. ScatterGather requires recipients). /// Generic scope-nesting rules: any node implementing is /// evaluated against each enclosing scope (a node implementing ). A /// becomes a build error, a a /// warning. This is declarative — new constraints ship on the definitions, not here. /// /// Catches structural errors early rather than producing cryptic runtime failures. /// internal static class RouteDefinitionValidator { /// /// Validates a route definition. Throws if any errors are /// found; returns the (possibly empty) list of non-fatal warnings for the caller to log. /// public static IReadOnlyList Validate(IRouteDefinition definition) { var errors = new List(); var warnings = new List(); if (definition is IProcessorDefinition root) ValidateTree(root, errors, warnings, new List(), new HashSet(StringComparer.OrdinalIgnoreCase)); if (errors.Count > 0) throw new RouteValidationException(definition.GetRouteId() ?? "", errors); return warnings; } private static void ValidateTree( IProcessorDefinition node, List errors, List warnings, List enclosingScopes, HashSet stepIds) { // 0. Step ids must be unique within the route: WeaveById resolves them case-insensitively, // and a message-history node id shared by two steps makes traces unattributable. if (node is ProcessorDefinition { StepId: { } stepId } && !stepIds.Add(stepId)) errors.Add($"Duplicate step id '{stepId}': Id(\"...\") must be unique within a route."); // 1. Per-node self-validation. switch (node) { case ScatterGatherDefinition sg: if ((sg.StaticRecipients is null || sg.StaticRecipients.Length == 0) && sg.DynamicRecipients is null) errors.Add("ScatterGather: at least one recipient (static or dynamic) is required."); if (sg.AggregationStrategy is null) errors.Add("ScatterGather: AggregationStrategy is required."); if (sg.MaxDegreeOfParallelism < 0) errors.Add("ScatterGather: MaxDegreeOfParallelism must be >= 0."); break; case TryCatchDefinition tryCatch: foreach (var clause in tryCatch.Catches) { if (CancellationHandlerWarning(clause.ExceptionType) is { } warning) warnings.Add(warning); } break; } // 2. Generic scope-nesting rules — the node declares its own policy against each enclosing scope. if (node is IScopeNestingRule rule) { foreach (var ancestor in enclosingScopes) { var verdict = rule.CheckAncestor(ancestor); switch (verdict.Policy) { case NestingPolicy.Forbid: errors.Add(verdict.Message!); break; case NestingPolicy.Warn: warnings.Add(verdict.Message!); break; } } } // 3. Descend, tracking scope-openers as enclosing scopes for nested nodes. Recurse into // Outputs AND any branches a definition keeps outside Outputs (e.g. Choice When/Otherwise). var isScope = node is IRouteScope; if (isScope) enclosingScopes.Add(node); foreach (var child in node.Outputs) ValidateTree(child, errors, warnings, enclosingScopes, stepIds); if (node is IBranchingDefinition branching) foreach (var branch in branching.Branches) ValidateTree(branch, errors, warnings, enclosingScopes, stepIds); if (isScope) enclosingScopes.RemoveAt(enclosingScopes.Count - 1); } /// /// The warning to log for an error handler registered on that can never /// fire — a or a subtype (a genuine cancellation is never /// handled, and a timeout arrives as ) — or null when the type is /// fine. Kept next to the validation rules so the fluent DSL, the Route-XML loader and the route-level /// OnException all report the same thing. /// internal static string? CancellationHandlerWarning(Type exceptionType) => RouteCancellation.IsCancellationType(exceptionType) ? $"An error handler for {exceptionType.Name} can never fire: a genuine cancellation is never " + "handled, and a timeout (an OperationCanceledException raised while the caller's token is still " + "live) arrives as System.TimeoutException. Handle System.TimeoutException instead." : null; } Path: redb-route/redb.Route/Validation/RouteValidationException.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/Validation/RouteValidationException.cs ---- using System; using System.Collections.Generic; namespace redb.Route.Validation; /// /// Thrown when a route definition fails structural validation before compilation. /// Contains all detected issues in . /// public sealed class RouteValidationException : InvalidOperationException { /// Route identifier, or null if unnamed. public string? RouteId { get; } /// All validation errors detected. public IReadOnlyList Errors { get; } /// Creates a route validation exception. /// Route identifier. /// List of validation errors. public RouteValidationException(string? routeId, IReadOnlyList errors) : base($"Route '{routeId ?? "(unnamed)"}' validation failed:\n - " + string.Join("\n - ", errors)) { RouteId = routeId; Errors = errors; } } Path: redb-route/redb.Route/Validation/SchemaResolver.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/Validation/SchemaResolver.cs ---- using System.Xml; using System.Xml.Schema; namespace redb.Route.Validation; /// /// Resolves the imports and includes of a schema to files under one directory, the package: never the network, /// never a file outside it. A reference that leaves is an error naming it. One resolver for every caller that reads a /// schema file (validateXsd, the xmljson data format); the callers differ only by the name in the messages. /// internal sealed class SchemaResolver(string caller, string root) : XmlUrlResolver { private readonly string _root = Path.GetFullPath(root).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar; /// /// The first reference refused. reports a failed import only as a warning, so the refusal /// is kept here and raised once the set is compiled. /// public XmlSchemaException? Refusal { get; private set; } public override object? GetEntity(Uri absoluteUri, string? role, Type? ofObjectToReturn) { if (!absoluteUri.IsFile) throw Refuse($"{caller}: the schema refers to '{absoluteUri}'; a schema and its imports are read from the package only, not the network."); var path = Path.GetFullPath(absoluteUri.LocalPath); var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; if (!path.StartsWith(_root, comparison)) throw Refuse($"{caller}: the schema refers to '{path}', outside '{_root}'; imports and includes stay inside the package."); return base.GetEntity(absoluteUri, role, ofObjectToReturn); } private XmlSchemaException Refuse(string message) { var refusal = new XmlSchemaException(message); Refusal ??= refusal; return refusal; } /// /// Reads and compiles the schema at , its imports resolved under /// (relative to the schema's directory; the directory itself when null). Any problem the compiler reports, an /// unresolved import included, is an error: a schema read in part would validate or convert the wrong way without /// saying so. /// /// A schema's own DOCTYPE is skipped (W3C's xmldsig-core-schema.xsd, imported by WS-Security, starts with one): /// nothing in it is expanded or fetched, so an entity reference in a schema's content fails as undeclared. Message /// documents stay strict: one with a DTD is refused (). /// /// /// The name the messages start with (xmljson, validateXsd). /// The schema file. /// The directory imports and includes must stay under, relative to the schema's directory. /// The schema's target namespace; null takes the schema's own. public static XmlSchemaSet Load(string caller, string path, string? root, string? targetNamespace = null) { var full = Path.GetFullPath(path); var directory = Path.GetDirectoryName(full)!; var resolver = new SchemaResolver(caller, root is null ? directory : Path.GetFullPath(Path.Combine(directory, root))); var set = new XmlSchemaSet { XmlResolver = resolver }; set.ValidationEventHandler += (_, e) => { if (resolver.Refusal is { } refusal) throw refusal; throw new XmlSchemaException($"{caller}: schema '{full}': {e.Message}", e.Exception); }; var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore, XmlResolver = resolver }; using (var reader = XmlReader.Create(full, settings)) set.Add(targetNamespace, reader); set.Compile(); if (resolver.Refusal is { } late) throw late; return set; } } Path: redb-route/redb.Route/Validation/ValidateProcessor.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/Validation/ValidateProcessor.cs ---- using redb.Route.Abstractions; namespace redb.Route.Validation; /// /// Pipeline processor that validates the exchange using an . /// /// By default, a failed validation sets the ValidationErrors property on the exchange /// and throws a . If is false, /// the processor only sets the property without throwing — giving the developer freedom to handle /// errors downstream via .Choice() or .Filter(). /// /// public sealed class ValidateProcessor : IProcessor { /// Well-known property key for validation error messages. public const string ValidationErrorsProperty = "ValidationErrors"; /// Well-known property key for the boolean validation result. public const string ValidationResultProperty = "ValidationResult"; /// /// Well-known message-header key receiving warning-severity validation messages. /// Multiple warnings are appended as a semicolon-joined string. /// public const string ValidationWarningsHeader = "redb.validation.warnings"; private readonly IMessageValidator _validator; /// /// Whether to throw on failure. /// Default is true. Set to false for soft validation that only sets properties. /// Ignored when is . /// public bool ThrowOnFailure { get; } /// Creates a validate processor that wraps the specified validator. /// Validator to apply. /// Whether to throw on validation failure (default: true). public ValidateProcessor(IMessageValidator validator, bool throwOnFailure = true) { _validator = validator ?? throw new ArgumentNullException(nameof(validator)); ThrowOnFailure = throwOnFailure; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { var result = await _validator.ValidateAsync(exchange).ConfigureAwait(false); // Always set properties so downstream steps can inspect them exchange.Properties[ValidationResultProperty] = result.IsValid; exchange.Properties[ValidationErrorsProperty] = result.IsValid ? null : string.Join("; ", result.Errors); if (!result.IsValid) { if (result.Severity == ValidationSeverity.Warning) { // Soft path: append to warnings header, never throw. var newMessages = string.Join("; ", result.Errors); if (exchange.In.Headers.TryGetValue(ValidationWarningsHeader, out var existing) && existing is string s && !string.IsNullOrEmpty(s)) { exchange.In.Headers[ValidationWarningsHeader] = s + "; " + newMessages; } else { exchange.In.Headers[ValidationWarningsHeader] = newMessages; } } else if (ThrowOnFailure) { throw new ValidationException(result.Errors); } } } } /// /// Exception thrown when message validation fails and is true. /// public sealed class ValidationException : Exception { /// Individual validation error messages. public IReadOnlyList Errors { get; } /// Creates a validation exception with the specified errors. /// Validation error messages. public ValidationException(IReadOnlyList errors) : base($"Validation failed: {string.Join("; ", errors)}") { Errors = errors; } } Path: redb-route/redb.Route/Validation/ValidationSeverity.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/Validation/ValidationSeverity.cs ---- namespace redb.Route.Validation; /// /// Severity classification for a . /// Lets a single contract distinguish soft warnings /// (route continues, header set) from hard errors (route may throw). /// public enum ValidationSeverity { /// /// Validation failed but processing should continue. /// appends the errors to the redb.validation.warnings in-header (semicolon-joined), /// and never throws. /// Warning = 0, /// /// Validation failed and is treated as an error. Honours the existing /// flag — throws /// when set, otherwise sets properties only. /// Error = 1 } Path: redb-route/redb.Route/Validation/ValidatorComponent.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/Validation/ValidatorComponent.cs ---- using System.Collections.Concurrent; using System.Xml; using System.Xml.Schema; using Json.Schema; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Validation; // ── Component ──────────────────────────────────────────────────────────────── /// /// Component for schema-based message validation. /// /// URI format: validator:path/to/schema.json or validator:path/to/schema.xsd. /// The schema format is auto-detected from the file extension (.xsd → XSD, otherwise JSON Schema). /// /// /// Parameters: /// /// format — Force format: json or xml (overrides auto-detection). /// throwOnFailure — Whether to throw on failure (true by default). /// targetNamespace — Target namespace for XSD schemas (optional). /// schemaRoot — For XSD: the directory imports and includes stay under, relative to the schema's directory (optional). /// /// /// [EndpointRole(EndpointRole.Producer, Hint = "Use .To(\"validator:...\").")] public sealed class ValidatorComponent : ComponentBase { /// public override string Scheme => "validator"; /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var options = new ValidatorEndpointOptions(); options.BindFromUri(uri.RawParameters); // The schema path resolves through the context's resource resolver // (absolute → ResourceRoot → AppContext.BaseDirectory → working directory), so a schema // inside an unpacked package is found wherever the worker process happens to run from. options.SchemaPath = string.IsNullOrWhiteSpace(uri.Path) ? uri.Path : ResourceResolution.Resolve(Context, uri.Path, "Schema file"); options.Validate(); return new ValidatorEndpoint(uri, this, options); } } // ── Options ────────────────────────────────────────────────────────────────── /// Options for the validator endpoint. public sealed class ValidatorEndpointOptions : EndpointOptions { /// Path to the schema file (JSON Schema or XSD). public string SchemaPath { get; set; } = string.Empty; /// /// Explicit format override: json or xml. If not set, auto-detected from file extension. /// public string? Format { get; set; } /// Whether to throw on validation failure. Default: true. public bool ThrowOnFailure { get; set; } = true; /// Target namespace for XSD schemas (optional). public string? TargetNamespace { get; set; } /// /// For XSD: the directory the schema's imports and includes stay under, relative to the schema's directory /// (.. for UBL's maindoc/ next to common/). Not set: the schema's directory itself. /// public string? SchemaRoot { get; set; } /// public override void Validate() { if (string.IsNullOrWhiteSpace(SchemaPath)) throw new ArgumentException("Schema path is required for the validator component."); if (!File.Exists(SchemaPath)) throw new FileNotFoundException($"Schema file not found: {SchemaPath}"); if (Format != null && !Format.Equals("json", StringComparison.OrdinalIgnoreCase) && !Format.Equals("xml", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException($"Invalid format '{Format}'. Supported: json, xml."); } } } // ── Endpoint ───────────────────────────────────────────────────────────────── /// Endpoint that performs schema validation (JSON Schema or XSD). public sealed class ValidatorEndpoint : EndpointBase { private readonly IMessageValidator _validator; private readonly bool _throwOnFailure; internal ValidatorEndpoint(EndpointUri uri, ValidatorComponent component, ValidatorEndpointOptions options) : base(uri, component, options) { _throwOnFailure = options.ThrowOnFailure; _validator = BuildValidator(options); } /// public override IProducer CreateProducer() => new ValidatorProducer(this); /// public override IConsumer CreateConsumer(IProcessor processor) => throw new NotSupportedException("Validator component does not support consuming (from). Use .To(\"validator:...\") instead."); internal IMessageValidator Validator => _validator; internal bool ThrowOnFailure => _throwOnFailure; private static IMessageValidator BuildValidator(ValidatorEndpointOptions options) { // An XSD is read from its file, so its imports and includes resolve relative to it. if (IsXsdSchema(options)) return XsdValidator.FromFile("validator", options.SchemaPath, string.IsNullOrEmpty(options.TargetNamespace) ? null : options.TargetNamespace, options.SchemaRoot); if (options.SchemaRoot is not null) throw new ArgumentException($"schemaRoot applies to XSD schemas; '{options.SchemaPath}' is read as a JSON Schema."); return new JsonSchemaValidator(File.ReadAllText(options.SchemaPath)); } private static bool IsXsdSchema(ValidatorEndpointOptions options) { if (options.Format != null) return options.Format.Equals("xml", StringComparison.OrdinalIgnoreCase); // Auto-detect from file extension var ext = Path.GetExtension(options.SchemaPath); return ext.Equals(".xsd", StringComparison.OrdinalIgnoreCase); } } // ── Producer ───────────────────────────────────────────────────────────────── /// Producer that triggers validation when the route sends to this endpoint. public sealed class ValidatorProducer : IProducer { private readonly ValidatorEndpoint _endpoint; internal ValidatorProducer(ValidatorEndpoint endpoint) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); } /// public Task Process(IExchange exchange, CancellationToken ct = default) { var result = _endpoint.Validator.Validate(exchange); exchange.Properties[ValidateProcessor.ValidationResultProperty] = result.IsValid; exchange.Properties[ValidateProcessor.ValidationErrorsProperty] = result.IsValid ? null : string.Join("; ", result.Errors); if (!result.IsValid && _endpoint.ThrowOnFailure) throw new ValidationException(result.Errors); return Task.CompletedTask; } /// public Task Start(CancellationToken ct = default) => Task.CompletedTask; /// public Task Stop(CancellationToken ct = default) => Task.CompletedTask; } Path: redb-route/redb.Route/Validation/XsdValidator.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/Validation/XsdValidator.cs ---- using System.Xml; using System.Xml.Linq; using System.Xml.Schema; using System.Xml.Serialization; using redb.Route.Abstractions; namespace redb.Route.Validation; /// /// Validates XML message bodies against an XSD (XML Schema Definition). /// Uses the built-in and validation — /// no external NuGet packages required. /// /// The validator accepts body as , , /// (raw XML), or a POCO (auto-serialized via ). /// /// public sealed class XsdValidator : IMessageValidator { private readonly XmlSchemaSet _schemaSet; private readonly XmlReaderSettings _readerSettings; /// Creates a validator from a pre-built . /// A compiled XML Schema set to validate against. public XsdValidator(XmlSchemaSet schemaSet) { _schemaSet = schemaSet ?? throw new ArgumentNullException(nameof(schemaSet)); if (!_schemaSet.IsCompiled) _schemaSet.Compile(); _readerSettings = new XmlReaderSettings { ValidationType = ValidationType.Schema, Schemas = _schemaSet }; } /// Creates a validator from an XSD string (target namespace auto-detected). /// XSD schema as a string. public XsdValidator(string xsdContent) : this(BuildSchemaSet(xsdContent ?? throw new ArgumentNullException(nameof(xsdContent)))) { } /// Creates a validator from an XSD string with an explicit target namespace. /// /// Target namespace URI; null takes the schema's own target namespace, as the one-argument form does, and an /// empty string demands a schema without one. /// /// XSD schema as a string. public XsdValidator(string? targetNamespace, string xsdContent) : this(BuildSchemaSet(targetNamespace, xsdContent ?? throw new ArgumentNullException(nameof(xsdContent)))) { } /// /// Creates a validator from an XSD file, with its xs:import and xs:include read relative to the /// file. Imports and includes are read only from under : one that is not found, lies /// outside it or points to the network (http://...) is an error naming it, as is any problem the schema /// compiler reports. A DOCTYPE in the schema or an imported file is skipped, never fetched. /// /// The XSD file. /// /// Target namespace URI; null takes the schema's own, and an empty string demands a schema without one. /// /// /// The directory imports and includes stay under, relative to the schema's directory (.. for UBL's /// maindoc/ next to common/); null is the schema's directory itself. /// /// The schema or one of its imports does not load or compile. public static XsdValidator FromFile(string path, string? targetNamespace = null, string? schemaRoot = null) => FromFile("validateXsd", path, targetNamespace, schemaRoot); internal static XsdValidator FromFile(string caller, string path, string? targetNamespace, string? schemaRoot) { ArgumentException.ThrowIfNullOrWhiteSpace(path); return new XsdValidator(SchemaResolver.Load(caller, path, schemaRoot, targetNamespace)); } /// public ValidationResult Validate(IExchange exchange) { ArgumentNullException.ThrowIfNull(exchange, nameof(exchange)); var body = exchange.In.Body; if (body is null) return ValidationResult.Failure("Message body is null"); string xml; if (body is XDocument xdoc) { xml = xdoc.ToString(SaveOptions.DisableFormatting); } else if (body is XElement xel) { xml = xel.ToString(SaveOptions.DisableFormatting); } else if (body is string str) { xml = str; } else { // POCO → serialize to XML string try { var serializer = new XmlSerializer(body.GetType()); using var sw = new StringWriter(); using var xw = XmlWriter.Create(sw, new XmlWriterSettings { OmitXmlDeclaration = true, Indent = false }); serializer.Serialize(xw, body); xml = sw.ToString(); } catch (Exception ex) { return ValidationResult.Failure($"Cannot serialize body to XML: {ex.Message}"); } } return ValidateXml(xml); } private ValidationResult ValidateXml(string xml) { // The document's root must be a global element of the schema. The .NET schema processor // reports an element it has no declaration for as a *warning* ("Could not find schema // information for the element 'x'") and skips its subtree; warnings are not delivered to the // handler unless ReportValidationWarnings is set, so an unknown-namespace, foreign-namespace // or no-namespace root passed validation and only failed later, when the body was parsed. // Apache Camel rejects it (its JAXP/Xerces parser raises cvc-elt.1.a), and so does this check. // Enabling ReportValidationWarnings instead was rejected: it would also turn legitimate // warnings (an xs:any processContents="lax" element with no schema for it) fatal. XDocument document; try { document = XDocument.Parse(xml); } catch (XmlException ex) { return ValidationResult.Failure($"XML parsing error: {ex.Message}"); } var root = document.Root; if (root is null) return ValidationResult.Failure("XML document has no root element"); var rootName = new XmlQualifiedName(root.Name.LocalName, root.Name.NamespaceName); if (!_schemaSet.GlobalElements.Contains(rootName)) { var shown = string.IsNullOrEmpty(root.Name.NamespaceName) ? root.Name.LocalName : $"{{{root.Name.NamespaceName}}}{root.Name.LocalName}"; return ValidationResult.Failure( $"Root element '{shown}' is not declared in the schema (cvc-elt.1.a)"); } var errors = new List(); var settings = _readerSettings.Clone(); settings.ValidationEventHandler += (_, e) => { var location = e.Exception != null ? $"Line {e.Exception.LineNumber}, Position {e.Exception.LinePosition}" : "Unknown location"; errors.Add($"{location}: {e.Message}"); }; try { using var stringReader = new StringReader(xml); using var reader = XmlReader.Create(stringReader, settings); while (reader.Read()) { } // Force full read to trigger all validation events } catch (XmlSchemaValidationException ex) { errors.Add($"Line {ex.LineNumber}, Position {ex.LinePosition}: {ex.Message}"); } catch (XmlException ex) { errors.Add($"XML parsing error: {ex.Message}"); } return errors.Count == 0 ? ValidationResult.Success() : ValidationResult.Failure(errors); } private static XmlSchemaSet BuildSchemaSet(string xsdContent) { return BuildSchemaSet(null, xsdContent); } private static XmlSchemaSet BuildSchemaSet(string? targetNamespace, string xsdContent) { var schemaSet = new XmlSchemaSet(); using var reader = new StringReader(xsdContent); // A schema's own DOCTYPE is skipped (W3C's xmldsig schema starts with one): nothing in it is expanded or // fetched, so an entity reference in the schema's content fails as undeclared. The message is read strictly. // No namespace given: null makes XmlSchemaSet take the schema's own targetNamespace ("" would demand none). schemaSet.Add(targetNamespace, XmlReader.Create(reader, new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore })); schemaSet.Compile(); return schemaSet; } } Path: redb-route/redb.Route/Xslt/IXsltEngine.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/Xslt/IXsltEngine.cs ---- namespace redb.Route.Xslt; /// /// The form the XSLT result is materialised into (Apache Camel xslt output option). /// public enum XsltOutput { /// A (default). String, /// A array, encoded per the stylesheet's xsl:output encoding. Bytes, /// An (Camel's DOM). Dom, } /// /// Pluggable XSLT transformation engine — the transformation counterpart of /// . An instance is compiled from a single /// stylesheet and reused (the compiled template is the expensive part, so it is cached in the engine). /// /// The built-in uses the BCL (System.Xml.Xsl, /// XSLT 1.0) with zero external dependencies — matching Apache Camel's default JAXP engine. /// /// /// To substitute a different processor — Saxon for XSLT 2.0/3.0, say — implement /// and register it with context.UseXsltEngine(...) or /// services.AddXsltEngine(...). Implementing this interface alone is not enough and never /// was: until 2026-09-03 every construction site named the built-in engine directly, so the /// substitution this paragraph promised could not actually be made. /// /// public interface IXsltEngine { /// /// Transforms through the compiled stylesheet and materialises the result /// as . /// /// /// The input document: a , array, , /// , or . /// /// The result form (string / bytes / DOM). /// Optional stylesheet parameters (xsl:param), by name. /// The transformed result as a , array, or DOM. object Transform(object? body, XsltOutput output, IReadOnlyDictionary? parameters); } Path: redb-route/redb.Route/Xslt/IXsltEngineFactory.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/Xslt/IXsltEngineFactory.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using redb.Route.Abstractions; namespace redb.Route.Xslt; /// /// Compiles stylesheets into instances — the point at which a different /// XSLT processor is substituted for the built-in one. /// /// /// /// has always been an interface, and its documentation has always said a /// Saxon-backed engine could be added later in an adapter package. It could not: every construction /// site named directly, so there was nothing to substitute. /// An interface with no seam behind it is documentation that lies. /// /// /// Both methods are here rather than in because the engine is a compiled /// stylesheet, and compiling is exactly what a replacement processor does differently. A route that /// allows a per-message stylesheet needs to compile again at runtime, which is why the processor /// holds the factory and not just the engine. /// /// /// The default stays the BCL, XSLT 1.0, no dependencies — the same behaviour a route gets today. /// XSLT 2.0/3.0 needs a processor we cannot ship: every .NET /// implementation is commercial. What we can give is the contract, so someone who has bought one /// registers it in their own project, under their own licence. /// /// public interface IXsltEngineFactory { /// /// Compiles a stylesheet from a file path or URL, which also becomes the base URI for /// xsl:import and xsl:include. /// IXsltEngine FromFile(string stylesheetPath); /// /// Compiles a self-contained stylesheet document. There is no base URI, so /// xsl:import/xsl:include have nothing to resolve against. /// IXsltEngine FromContent(string stylesheetXml); } /// /// The built-in factory: BCL , XSLT 1.0, no /// external dependencies. Used whenever a route has registered nothing else. /// public sealed class XslCompiledTransformEngineFactory : IXsltEngineFactory { /// The shared instance. The factory holds no state; the compiled stylesheets do. public static readonly XslCompiledTransformEngineFactory Instance = new(); /// public IXsltEngine FromFile(string stylesheetPath) => XslCompiledTransformEngine.FromFile(stylesheetPath); /// public IXsltEngine FromContent(string stylesheetXml) => XslCompiledTransformEngine.FromContent(stylesheetXml); } /// /// Registration and resolution of the XSLT engine factory, following the same order as every other /// pluggable service here: what the context was told, then the DI container, then the default. /// public static class XsltEngineRegistration { /// /// Registers an XSLT engine factory on a context built without DI: /// context.UseXsltEngine(new SaxonXsltEngineFactory()). /// public static IRouteContext UseXsltEngine(this IRouteContext context, IXsltEngineFactory factory) { ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(factory); context.AddService(typeof(IXsltEngineFactory), factory); return context; } /// /// DI registration: services.AddXsltEngine(new SaxonXsltEngineFactory()). /// public static IServiceCollection AddXsltEngine(this IServiceCollection services, IXsltEngineFactory factory) { ArgumentNullException.ThrowIfNull(services); ArgumentNullException.ThrowIfNull(factory); services.TryAddSingleton(factory); return services; } /// /// Resolves the factory a route should compile its stylesheets with. /// /// /// A null context is not an error: definitions are built in tests and tools without one, and /// the answer there is the built-in engine, which is also the answer when nothing is registered. /// public static IXsltEngineFactory GetXsltEngineFactory(this IRouteContext? context) => context?.GetService() ?? context?.GetServiceProvider()?.GetService(typeof(IXsltEngineFactory)) as IXsltEngineFactory ?? XslCompiledTransformEngineFactory.Instance; } Path: redb-route/redb.Route/Xslt/XslCompiledTransformEngine.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/Xslt/XslCompiledTransformEngine.cs ---- using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using System.Xml.Xsl; namespace redb.Route.Xslt; /// /// Built-in backed by the BCL /// (System.Xml.Xsl) — zero external dependencies, XSLT 1.0 (like Apache Camel's default /// JAXP engine; use a Saxon-backed engine for 2.0/3.0). The stylesheet is compiled once at construction /// and the compiled template is reused for every transform (the compilation is the expensive part). /// /// The compiled transform is loaded with — inline script and /// the document() function are disabled, which is the safe default for stylesheets coming from /// outside the application. /// /// public sealed class XslCompiledTransformEngine : IXsltEngine { private readonly XslCompiledTransform _compiled; private XslCompiledTransformEngine(XslCompiledTransform compiled) => _compiled = compiled; /// /// Compiles the engine from a stylesheet file (or URL). The path is used as the base URI, so /// xsl:import / xsl:include resolve relative to the stylesheet. /// public static XslCompiledTransformEngine FromFile(string stylesheetPath) { ArgumentException.ThrowIfNullOrWhiteSpace(stylesheetPath); var xslt = new XslCompiledTransform(); xslt.Load(stylesheetPath); return new XslCompiledTransformEngine(xslt); } /// /// Compiles the engine from an inline stylesheet document. Self-contained stylesheets only — /// xsl:import/xsl:include have no base URI to resolve against. /// public static XslCompiledTransformEngine FromContent(string stylesheetXml) { ArgumentException.ThrowIfNullOrWhiteSpace(stylesheetXml); var xslt = new XslCompiledTransform(); using var reader = XmlReader.Create(new StringReader(stylesheetXml)); xslt.Load(reader); return new XslCompiledTransformEngine(xslt); } /// public object Transform(object? body, XsltOutput output, IReadOnlyDictionary? parameters) { using var input = CreateInputReader(body); var args = new XsltArgumentList(); if (parameters is not null) { foreach (var (name, value) in parameters) { if (value is null) continue; // Names that aren't valid XSLT parameter identifiers (e.g. a header like "Content-Type" // is fine, but arbitrary keys may not be) are skipped rather than failing the transform — // matching Camel, which silently ignores headers that aren't declared/usable as params. try { args.AddParam(name, string.Empty, value); } catch (ArgumentException) { /* not a usable parameter name — skip */ } } } // Using the TextWriter / Stream overloads lets XslCompiledTransform honour the stylesheet's // xsl:output method (xml / html / text) and encoding automatically. switch (output) { case XsltOutput.Bytes: { using var ms = new MemoryStream(); _compiled.Transform(input, args, ms); return ms.ToArray(); } case XsltOutput.Dom: { var doc = new XmlDocument(); using var writer = doc.CreateNavigator()!.AppendChild(); _compiled.Transform(input, args, writer); writer.Close(); return doc; } default: // String { using var sw = new StringWriter(); _compiled.Transform(input, args, sw); return sw.ToString(); } } } private static XmlReader CreateInputReader(object? body) => body switch { XmlReader reader => reader, string s => XmlReader.Create(new StringReader(s)), byte[] bytes => XmlReader.Create(new MemoryStream(bytes)), Stream stream => XmlReader.Create(stream), XNode node => node.CreateReader(), // XDocument / XElement (System.Xml.Linq) IXPathNavigable navigable => navigable.CreateNavigator()!.ReadSubtree(), _ => throw new NotSupportedException( $"XSLT input body type '{body?.GetType().Name ?? "null"}' is not supported. " + "Provide XML as string, byte[], Stream, XmlReader, XDocument/XElement, or IXPathNavigable."), }; } Path: redb-route/redb.Route/Xslt/XsltComponent.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/Xslt/XsltComponent.cs ---- using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Xslt; // ── Component ──────────────────────────────────────────────────────────────── /// /// Component for XSLT transformation (Apache Camel xslt: parity). Producer-only — you send /// to it. Mirrors . /// /// URI format: xslt:path/to/stylesheet.xsl. Parameters: /// /// output — result form: string (default) / bytes / dom. /// failOnNullBody — throw when the input body is null (default true). /// allowTemplateFromHeader — allow a per-message stylesheet from headers (default false). /// /// /// /// Registered out of the box under the xslt scheme, so .To("xslt:...") works without any /// setup. All headers and exchange properties are passed to the stylesheet as parameters (Camel parity). /// /// [EndpointRole(EndpointRole.Producer, Hint = "Use .To(\"xslt:...\") or the .Xslt(...) DSL.")] public sealed class XsltComponent : ComponentBase { /// public override string Scheme => "xslt"; /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var options = new XsltEndpointOptions(); options.BindFromUri(uri.RawParameters); // The stylesheet path resolves through the context's resource resolver // (absolute → ResourceRoot → AppContext.BaseDirectory → working directory), so a stylesheet // inside an unpacked package is found wherever the worker process happens to run from. options.StylesheetPath = string.IsNullOrWhiteSpace(uri.Path) ? uri.Path : ResourceResolution.Resolve(Context, uri.Path, "XSLT stylesheet"); options.Validate(); // Resolved here, where the component still has its context: the endpoint compiles the // stylesheet in its constructor and would otherwise have no way to ask. return new XsltEndpoint(uri, this, options, Context.GetXsltEngineFactory()); } } // ── Options ────────────────────────────────────────────────────────────────── /// Options for the XSLT endpoint. public sealed class XsltEndpointOptions : EndpointOptions { /// Path to the stylesheet file (from the URI path). public string StylesheetPath { get; set; } = string.Empty; /// Result form: string (default) / bytes / dom. public XsltOutput Output { get; set; } = XsltOutput.String; /// Throw when the input body is null. Default: true. public bool FailOnNullBody { get; set; } = true; /// Allow a per-message stylesheet from the CamelXsltResourceUri/CamelXsltStylesheet /// headers to override the compiled default. Default: false. public bool AllowTemplateFromHeader { get; set; } /// public override void Validate() { if (string.IsNullOrWhiteSpace(StylesheetPath)) throw new ArgumentException("Stylesheet path is required for the xslt component."); if (!File.Exists(StylesheetPath)) throw new FileNotFoundException($"XSLT stylesheet not found: {StylesheetPath}"); } } // ── Endpoint ───────────────────────────────────────────────────────────────── /// Endpoint that transforms the body through a compiled XSLT stylesheet. public sealed class XsltEndpoint : EndpointBase { private readonly XsltProcessor _processor; internal XsltEndpoint( EndpointUri uri, XsltComponent component, XsltEndpointOptions options, IXsltEngineFactory engines) : base(uri, component, options) { ArgumentNullException.ThrowIfNull(engines); // Reuse XsltProcessor so the component gets parameters + dynamic-from-header behaviour for free. // The stylesheet is compiled once when the endpoint is created (Camel contentCache=true). _processor = new XsltProcessor( engines.FromFile(options.StylesheetPath), options.Output, options.FailOnNullBody, passHeadersAsParameters: true, allowTemplateFromHeader: options.AllowTemplateFromHeader, fileEngineFactory: engines.FromFile, contentEngineFactory: engines.FromContent); } internal XsltProcessor Processor => _processor; /// public override IProducer CreateProducer() => new XsltProducer(this); /// public override IConsumer CreateConsumer(IProcessor processor) => throw new NotSupportedException( "XSLT component does not support consuming (from). Use .To(\"xslt:...\") or the .Xslt(...) DSL."); } // ── Producer ───────────────────────────────────────────────────────────────── /// Producer that runs the XSLT transform when the route sends to this endpoint. public sealed class XsltProducer : IProducer { private readonly XsltEndpoint _endpoint; internal XsltProducer(XsltEndpoint endpoint) => _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); /// public Task Process(IExchange exchange, CancellationToken ct = default) => _endpoint.Processor.Process(exchange, ct); /// public Task Start(CancellationToken ct = default) => Task.CompletedTask; /// public Task Stop(CancellationToken ct = default) => Task.CompletedTask; } Path: redb-route/redb.Route/Xslt/XsltProcessor.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/Xslt/XsltProcessor.cs ---- using System.Collections.Concurrent; using redb.Route.Abstractions; namespace redb.Route.Xslt; /// /// Pipeline processor that transforms the exchange body through an — the /// transformation counterpart of . The result /// (string / bytes / DOM, per ) replaces In.Body. The /// Content-Type header is left unchanged (matching Apache Camel). /// /// By default all message headers and exchange properties are passed as stylesheet parameters /// (xsl:param), like Camel. When allowTemplateFromHeader is enabled a per-message /// stylesheet from / /// overrides the compiled default; those dynamic stylesheets are compiled once and cached. /// /// public sealed class XsltProcessor : IProcessor { private readonly IXsltEngine _defaultEngine; private readonly XsltOutput _output; private readonly bool _failOnNullBody; private readonly bool _passHeadersAsParameters; private readonly bool _allowTemplateFromHeader; private readonly Func? _fileEngineFactory; private readonly Func? _contentEngineFactory; private readonly ConcurrentDictionary _dynamicEngines = new(StringComparer.Ordinal); /// Creates an XSLT processor around a compiled engine. /// The default (compile-once) transformation engine. /// The result form (default ). /// Throw when the input body is null (Camel default: true). /// Pass headers/properties as stylesheet parameters (default: true). /// Allow a per-message stylesheet from headers (default: false). /// Compiles an engine from a stylesheet path (for the dynamic path). /// Compiles an engine from inline stylesheet content (for the dynamic path). public XsltProcessor( IXsltEngine engine, XsltOutput output = XsltOutput.String, bool failOnNullBody = true, bool passHeadersAsParameters = true, bool allowTemplateFromHeader = false, Func? fileEngineFactory = null, Func? contentEngineFactory = null) { _defaultEngine = engine ?? throw new ArgumentNullException(nameof(engine)); _output = output; _failOnNullBody = failOnNullBody; _passHeadersAsParameters = passHeadersAsParameters; _allowTemplateFromHeader = allowTemplateFromHeader; _fileEngineFactory = fileEngineFactory; _contentEngineFactory = contentEngineFactory; } /// public Task Process(IExchange exchange, CancellationToken ct = default) { var body = exchange.In.Body; if (body is null) { if (_failOnNullBody) throw new InvalidOperationException("XSLT: the input body is null (failOnNullBody=true)."); return Task.CompletedTask; } var engine = ResolveEngine(exchange); var parameters = _passHeadersAsParameters ? XsltParameters.FromExchange(exchange) : null; exchange.In.Body = engine.Transform(body, _output, parameters); return Task.CompletedTask; } private IXsltEngine ResolveEngine(IExchange exchange) { if (!_allowTemplateFromHeader) return _defaultEngine; if (_fileEngineFactory is not null && exchange.In.Headers.TryGetValue(XsltHeaders.ResourceUri, out var uriObj) && uriObj is string uri && !string.IsNullOrWhiteSpace(uri)) { return _dynamicEngines.GetOrAdd("uri:" + uri, _ => _fileEngineFactory(uri)); } if (_contentEngineFactory is not null && exchange.In.Headers.TryGetValue(XsltHeaders.Stylesheet, out var xmlObj) && xmlObj is string xml && !string.IsNullOrWhiteSpace(xml)) { return _dynamicEngines.GetOrAdd("xml:" + xml, _ => _contentEngineFactory(xml)); } return _defaultEngine; } } Path: redb-route/redb.Route/Xslt/XsltSupport.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/Xslt/XsltSupport.cs ---- using redb.Route.Abstractions; namespace redb.Route.Xslt; /// Well-known message headers for the XSLT transform (Apache Camel names). public static class XsltHeaders { /// Header carrying a stylesheet file path / URI to use for this message /// (honoured only when allowTemplateFromHeader is enabled). public const string ResourceUri = "CamelXsltResourceUri"; /// Header carrying an inline stylesheet document to use for this message /// (honoured only when allowTemplateFromHeader is enabled). public const string Stylesheet = "CamelXsltStylesheet"; } /// /// Collects XSLT stylesheet parameters from the exchange. Mirrors Apache Camel, which makes all /// message headers (and exchange variables/properties) available as xsl:param — a stylesheet /// only sees the ones it declares. Values are passed as strings; the transform silently ignores keys /// that are not usable parameter names. /// public static class XsltParameters { /// Builds the parameter map (headers first, then properties without overwriting). public static IReadOnlyDictionary FromExchange(IExchange exchange) { var parameters = new Dictionary(StringComparer.Ordinal); foreach (var (key, value) in exchange.In.Headers) if (value is not null) parameters[key] = value.ToString(); foreach (var (key, value) in exchange.Properties) if (value is not null && !parameters.ContainsKey(key)) parameters[key] = value.ToString(); return parameters; } } Path: redb-route/redb.Route/redb.Route.csproj 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/redb.Route.csproj ---- redb.Route Lightweight, async-first ESB framework inspired by Apache Camel. Define message routes with fluent C# DSL, connect Kafka, RabbitMQ, Redis and more. esb;messaging;routing;kafka;rabbitmq;camel;pipeline;async README.md