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();
}
}