Path: redb-route/redb.Route/Processors/DynamicRouterProcessor.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/DynamicRouterProcessor.cs
----
using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.Processors;
///
/// Dynamic Router: evaluates a routing function on each exchange to determine the next endpoint.
/// The exchange is sent to the returned URI, then the routing function is called again.
/// Routing continues until the function returns null (slip routing).
/// Implements the Dynamic Router / Routing Slip EIP pattern.
/// Producers are cached per URI to avoid repeated creation for hot paths.
///
internal sealed class DynamicRouterProcessor : IProcessor, IAsyncDisposable
{
private readonly IRouteContext _context;
private readonly Func _routingFunction;
private readonly ConcurrentDictionary _producerCache = new(StringComparer.Ordinal);
private readonly ILogger? _logger;
/// Creates a dynamic router processor.
/// Route context for resolving endpoints.
///
/// Function that returns the next URI to route to, or null to stop routing.
/// The function is called after each hop, so the exchange state may change between calls.
///
public DynamicRouterProcessor(
IRouteContext context,
Func routingFunction,
ILogger? logger = null)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
_routingFunction = routingFunction ?? throw new ArgumentNullException(nameof(routingFunction));
_logger = logger;
}
///
public async Task Process(IExchange exchange, CancellationToken ct = default)
{
const int maxHops = 1000; // Safety guard against infinite loops
int hops = 0;
while (!ct.IsCancellationRequested && !exchange.IsStopped)
{
var nextUri = _routingFunction(exchange);
if (nextUri is null)
break;
_logger?.LogDebug("DynamicRouter: hop {Hop} → {Uri}", hops + 1, EndpointUri.Sanitize(nextUri));
if (++hops > maxHops)
throw new InvalidOperationException(
$"DynamicRouter exceeded maximum hop count ({maxHops}). " +
"Possible infinite routing loop detected.");
var (endpoint, producer) = await GetOrCreatePairAsync(nextUri, ct).ConfigureAwait(false);
await Core.CountedSend.Process(endpoint, producer, exchange, ct).ConfigureAwait(false);
}
}
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);
// Use TryAdd to avoid overwriting if another thread added concurrently
if (!_producerCache.TryAdd(uri, (endpoint, producer)))
{
// Another thread won the race — stop our duplicate and use theirs
await producer.Stop(ct).ConfigureAwait(false);
return _producerCache[uri];
}
return (endpoint, producer);
}
/// Stops all cached producers.
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();
}
}