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).
[](https://www.nuget.org/packages/redb.Route)
[](../../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