Bundle: redb-route / redb.Route.Cache (redb.Route.Cache.txt), 19 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.Cache/CacheComponent.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.Cache/CacheComponent.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.Cache;
/// The cache: component: explicit get / put / remove / clear as endpoints (Camel cache-component analog).
[EndpointRole(EndpointRole.Producer, Hint = "Use it as To(\"cache:...\").")]
public sealed class CacheComponent : ComponentBase
{
///
public override string Scheme => "cache";
///
public override IEndpoint CreateEndpoint(EndpointUri uri)
{
ArgumentNullException.ThrowIfNull(uri);
var options = new CacheEndpointOptions();
options.BindFromUri(uri.RawParameters);
options.Validate();
return new CacheEndpoint(uri, this, options);
}
}
/// A cache:<region> endpoint; producer only.
public sealed class CacheEndpoint : EndpointBase
{
internal CacheEndpoint(EndpointUri uri, CacheComponent component, CacheEndpointOptions options)
: base(uri, component, options)
{
Region = string.IsNullOrWhiteSpace(uri.Path) ? "default" : uri.Path.Trim('/');
}
/// Region taken from the URI path (cache:customers → customers ).
public string Region { get; }
///
public override IProducer CreateProducer() => new CacheProducer(this, Options);
///
public override IConsumer CreateConsumer(IProcessor processor)
=> throw new NotSupportedException("cache: endpoints are producers only (To(\"cache:...\")).");
}
Path: redb-route/redb.Route.Cache/CacheDefinition.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.Cache/CacheDefinition.cs
----
using System.Security.Cryptography;
using System.Text;
using redb.Route.Abstractions;
using redb.Route.Definitions;
using redb.Route.Expressions;
namespace redb.Route.Cache;
///
/// The caching scope (WSO2 Cache mediator analog): on a hit the body (and optionally the headers)
/// comes from the cache and the inner steps are skipped; on a miss they run and the result is stored.
/// Header cache.hit says which. Close with .
///
public sealed class CacheDefinition : RouteDefinitionBase, IRouteScope
{
private readonly Func _key;
private bool _keyFromBody;
private TimeSpan? _ttl;
private TimeSpan? _sliding;
private string _region = "default";
private bool _cacheHeaders;
private CacheProvider? _provider;
internal CacheDefinition(Func key, TimeSpan? ttl)
{
_key = key ?? throw new ArgumentNullException(nameof(key));
_ttl = ttl;
}
/// Key namespace; clear on the component empties one region. Default default .
public CacheDefinition Region(string region)
{
ArgumentException.ThrowIfNullOrWhiteSpace(region);
_region = region;
return this;
}
/// Absolute lifetime of an entry.
public CacheDefinition Ttl(TimeSpan ttl) { _ttl = ttl; return this; }
/// Lifetime renewed on every hit.
public CacheDefinition SlidingExpiration(TimeSpan sliding) { _sliding = sliding; return this; }
/// Store and restore the headers together with the body.
public CacheDefinition CacheHeaders(bool value = true) { _cacheHeaders = value; return this; }
/// Use the IDistributedCache registered in DI or on the context.
public CacheDefinition Distributed() { _provider = CacheProvider.Distributed; return this; }
/// Use the in-process cache (default).
public CacheDefinition InMemory() { _provider = CacheProvider.Memory; return this; }
///
/// Key = SHA-256 of the body instead of the explicit key (WSO2 "hash of the request" mode). Only the
/// body is hashed: the content type and the headers are not part of the key. A stream body is read
/// to the end for it, and the message continues with its bytes; an object goes through the context's
/// data format, the way the distributed cache stores it.
///
public CacheDefinition KeyFromBody()
{
_keyFromBody = true;
return this;
}
/// Closes the scope and returns to the enclosing route.
public IRouteDefinition EndCache()
=> (IRouteDefinition)(Parent ?? throw new InvalidOperationException("EndCache() called without a parent route."));
///
public IRouteDefinition End() => EndCache();
///
public override IProcessor CreateProcessor(IRouteContext context)
{
var options = CacheStores.Options(context);
var provider = _provider ?? options.DefaultProvider;
var store = CacheStores.Resolve(context, provider);
var flights = CacheStores.Flights(context, provider);
var inner = NodePipeline.Body(context, Outputs);
var region = _region;
var registry = context.GetService();
Func key = _keyFromBody ? exchange => BodyHash(exchange.In, registry) : _key;
var ttl = _ttl ?? options.DefaultTtl;
if (ttl is { } t && t <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(ttl), t, "Cache: the TTL must be positive.");
if (_sliding is { } s && s <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException("sliding", s, "Cache: the sliding expiration must be positive.");
return new CacheScopeProcessor(store, flights, e => CacheKeys.For(region, key(e)), ttl, _sliding, _cacheHeaders, inner);
}
internal static Func KeyFromTemplate(string keyTemplate)
{
ArgumentException.ThrowIfNullOrWhiteSpace(keyTemplate);
// A key without ${...} that starts with no root of the exchange is the key as written ("orders-all", "k-out"):
// the cache key is a template, and bare text with a dash is not arithmetic here (ExpressionResolver.IsConstantKey).
if (ExpressionResolver.IsConstantKey(keyTemplate))
return _ => keyTemplate;
var expression = new StringExpression(keyTemplate);
// Invariant text: a decimal or a date key must spell the same on every machine sharing one Redis.
return exchange => expression.Evaluate(exchange) switch
{
null => throw new InvalidOperationException($"Cache key '{keyTemplate}' evaluated to null."),
string text => text,
IFormattable formattable => formattable.ToString(null, System.Globalization.CultureInfo.InvariantCulture),
var other => other.ToString() ?? throw new InvalidOperationException($"Cache key '{keyTemplate}' evaluated to null."),
};
}
///
/// SHA-256 of the message body. A stream can be read once and the inner steps still need the body,
/// so its bytes replace it on the message, as they do when a miss is stored.
///
internal static string BodyHash(IMessage message, IDataFormatRegistry? registry)
{
byte[] bytes;
switch (message.Body)
{
case null:
bytes = [];
break;
case byte[] raw:
bytes = raw;
break;
case string text:
bytes = Encoding.UTF8.GetBytes(text);
break;
case Stream stream:
bytes = CacheEntry.ReadToEnd(stream);
message.Body = bytes;
break;
case var body:
try
{
bytes = CacheSerialization.Serialize(registry, body, message.ContentType).Bytes;
}
catch (Exception ex)
{
throw new InvalidOperationException($"Cache: KeyFromBody cannot hash a {body.GetType().Name} body: {ex.Message}", ex);
}
break;
}
return Convert.ToHexString(SHA256.HashData(bytes));
}
}
Path: redb-route/redb.Route.Cache/CacheEndpointOptions.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.Cache/CacheEndpointOptions.cs
----
using redb.Route.Core;
namespace redb.Route.Cache;
///
/// Options of a cache: endpoint:
/// cache:<region>?action=get|put|remove|clear&key=${header.id}&ttl=5m&sliding=1m&provider=memory|distributed&headers=X-Rate,Content-Language .
///
public sealed class CacheEndpointOptions : EndpointOptions
{
/// get (default), put , remove or clear .
public string Action { get; set; } = "get";
/// Entry key; ${...} resolved per message. Required except for clear .
public DynamicValue? Key { get; set; }
/// Absolute lifetime for put (5m , 30s , hh:mm:ss ).
public string? Ttl { get; set; }
/// Sliding lifetime for put .
public string? Sliding { get; set; }
/// memory (default) or distributed .
public string? Provider { get; set; }
///
/// put only: the headers stored with the body, by name, comma-separated. A put sees the
/// message as a whole and cannot tell the headers of the value from the headers of the request, so
/// it stores none unless named; a credential (Authorization , Cookie , …) cannot be named.
///
public string? Headers { get; set; }
/// Parsed action.
public CacheAction ParsedAction => Action.ToLowerInvariant() switch
{
"get" => CacheAction.Get,
"put" => CacheAction.Put,
"remove" => CacheAction.Remove,
"clear" => CacheAction.Clear,
_ => throw new ArgumentException($"Cache endpoint: unknown action '{Action}' (get, put, remove, clear)."),
};
/// Parsed provider; null = package default.
public CacheProvider? ParsedProvider => Provider?.ToLowerInvariant() switch
{
null or "" => null,
"memory" => CacheProvider.Memory,
"distributed" => CacheProvider.Distributed,
_ => throw new ArgumentException($"Cache endpoint: unknown provider '{Provider}' (memory, distributed)."),
};
/// The header names of ; null when none were given.
public IReadOnlyCollection? ParsedHeaders
{
get
{
if (string.IsNullOrWhiteSpace(Headers)) return null;
var names = Headers.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (names.Length == 0)
throw new ArgumentException("Cache endpoint: headers= names no header.");
foreach (var name in names)
if (CacheHeaderPolicy.IsCredential(name))
throw new ArgumentException($"Cache endpoint: '{name}' is a credential and cannot be cached: a hit would hand it to another exchange.");
return names;
}
}
///
public override void Validate()
{
_ = ParsedAction;
_ = ParsedProvider;
_ = CacheDuration.Parse(Ttl);
_ = CacheDuration.Parse(Sliding);
if (ParsedAction != CacheAction.Clear && Key is null)
throw new ArgumentException($"Cache endpoint: action '{Action}' needs key=...");
if (ParsedHeaders is not null && ParsedAction != CacheAction.Put)
throw new ArgumentException($"Cache endpoint: headers= belongs to action=put; action '{Action}' takes the entry as it was stored.");
}
///
protected override string? UnknownParameterHint(string name)
=> string.Equals(name, "cacheHeaders", StringComparison.OrdinalIgnoreCase)
? "A put stores no headers unless they are named: headers=X-Rate,Content-Language. It cannot tell the headers of the value from the headers of the request, and a hit hands what it stores to another exchange."
: null;
}
/// Operations of the cache: component.
public enum CacheAction
{
/// Read the entry into the message, or into Out when it was cached as a reply; sets cache.hit .
Get,
/// Store the message under the key.
Put,
/// Remove the key.
Remove,
/// Remove every key of the region.
Clear,
}
Path: redb-route/redb.Route.Cache/CacheEntry.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.Cache/CacheEntry.cs
----
using System.Text.Json.Nodes;
using redb.Route.Abstractions;
namespace redb.Route.Cache;
///
/// What the cache stores for one key: the body, its content type and the headers the entry may carry.
/// A hit hands the entry to another exchange, so the headers are what the miss produced (the scope) or
/// what a put named, never what an exchange came in with and never a credential
/// ( ).
///
public sealed class CacheEntry
{
/// Cached body (a CLR object in the in-process cache; restored to its type from a distributed cache when possible).
public object? Body { get; init; }
/// Content type of the body.
public string? ContentType { get; init; }
/// Headers of the result message: set on In on a hit, or on the reply when .
public IReadOnlyDictionary? Headers { get; init; }
///
/// The miss left its result in exchange.Out (a request-reply producer such as HTTP replies
/// there), so a hit restores it there too — a consumer that answers only when Out is present
/// must see a hit exactly as it saw the miss.
///
public bool FromOut { get; init; }
/// With : the headers the inner steps produced on In while replying in Out ; a hit sets them on In .
public IReadOnlyDictionary? InHeaders { get; init; }
/// Names of the headers the inner steps removed from In ; a hit removes them as well.
public IReadOnlyCollection? RemovedHeaders { get; init; }
///
/// Captures the message with its headers as they are, credentials excluded. The scope and the
/// component keep less: the scope the headers the miss produced ( ), the
/// component the ones a put named.
///
public static CacheEntry From(IMessage message, bool includeHeaders, bool fromOut = false)
{
Dictionary? headers = null;
if (includeHeaders)
{
headers = new Dictionary(StringComparer.OrdinalIgnoreCase);
foreach (var (name, value) in message.Headers)
if (!CacheHeaderPolicy.IsCredential(name))
headers[name] = value;
}
return new()
{
Body = Capture(message),
ContentType = message.ContentType,
Headers = headers,
FromOut = fromOut,
};
}
///
/// Captures what the inner steps of a scope produced: the result message (Out when they
/// replied there, else In ) and, with , the headers they added,
/// changed or removed, compared by instance with the ones the exchange came in with. A header that
/// arrived with the request is never stored; a reply that copied the request's headers keeps only
/// its own.
///
internal static CacheEntry FromResult(IExchange exchange, IReadOnlyDictionary? before)
{
var fromOut = exchange.Out is not null;
var result = fromOut ? exchange.Out! : exchange.In;
var body = Capture(result);
if (before is null)
return new() { Body = body, ContentType = result.ContentType, FromOut = fromOut };
var produced = CacheHeaderPolicy.Produced(exchange.In, before);
var removed = CacheHeaderPolicy.Removed(exchange.In, before);
return fromOut
? new()
{
Body = body,
ContentType = result.ContentType,
FromOut = true,
Headers = CacheHeaderPolicy.Produced(exchange.Out!, before),
InHeaders = produced,
RemovedHeaders = removed,
}
: new()
{
Body = body,
ContentType = result.ContentType,
Headers = produced,
RemovedHeaders = removed,
};
}
/// Captures the message for a put : the body, and of the headers only the ones named.
internal static CacheEntry FromMessage(IMessage message, IReadOnlyCollection? headerNames)
{
Dictionary? headers = null;
if (headerNames is { Count: > 0 })
{
headers = new Dictionary(StringComparer.OrdinalIgnoreCase);
foreach (var name in headerNames)
if (message.Headers.TryGetValue(name, out var value))
headers[name] = value;
}
return new() { Body = Capture(message), ContentType = message.ContentType, Headers = headers };
}
///
/// The body as the cache keeps it. A body can be read once, so its bytes are
/// kept and the live message continues with those bytes; a has one parent and
/// is mutable, so the cache keeps its own copy. Any other body is kept by reference — text and byte
/// arrays are treated as immutable, and a mutable object (a POCO, a list) is shared by every hit: do
/// not mutate what a cache scope handed you, or clone it first.
///
private static object? Capture(IMessage message)
{
switch (message.Body)
{
case Stream stream:
var bytes = ReadToEnd(stream);
message.Body = bytes;
return bytes;
case JsonNode node:
return node.DeepClone();
case var body:
return body;
}
}
internal static byte[] ReadToEnd(Stream stream)
{
using (stream)
{
using var buffer = new MemoryStream();
stream.CopyTo(buffer);
return buffer.ToArray();
}
}
///
/// Writes the entry into the message. Cached headers overwrite the current ones: that is what the
/// inner steps did on the miss, and a hit must leave the message the way the miss did.
///
public void ApplyTo(IMessage message)
{
message.Body = Body is JsonNode node ? node.DeepClone() : Body;
if (ContentType is not null) message.ContentType = ContentType;
if (Headers is null) return;
foreach (var (key, value) in Headers)
message.Headers[key] = value;
}
///
/// Writes the entry where the miss left it: a fresh Out when the inner steps replied there,
/// otherwise In . What the steps did to the headers of In is done again either way.
///
public void ApplyTo(IExchange exchange)
{
if (!FromOut)
{
ApplyTo(exchange.In);
RemoveFrom(exchange.In);
return;
}
if (InHeaders is not null)
foreach (var (key, value) in InHeaders)
exchange.In.Headers[key] = value;
RemoveFrom(exchange.In);
var reply = new redb.Route.Core.Message(Body);
ApplyTo(reply);
exchange.Out = reply;
}
private void RemoveFrom(IMessage message)
{
if (RemovedHeaders is null) return;
foreach (var name in RemovedHeaders)
message.Headers.Remove(name);
}
}
Path: redb-route/redb.Route.Cache/CacheFlights.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.Cache/CacheFlights.cs
----
using System.Collections.Concurrent;
namespace redb.Route.Cache;
///
/// The computations in progress, one per store key: while one exchange computes a missing entry, the
/// others arriving for the same key wait for its result instead of each running the inner steps.
/// One instance per context, with a map per provider, so every cache node that shares a store shares
/// its flights as well. Other processes (and other contexts) compute on their own.
///
internal sealed class CacheFlights
{
private readonly ConcurrentDictionary> _memory = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary> _distributed = new(StringComparer.Ordinal);
/// The flights of the store that serves in this context.
public ConcurrentDictionary> For(CacheProvider provider)
=> provider == CacheProvider.Distributed ? _distributed : _memory;
}
Path: redb-route/redb.Route.Cache/CacheHeaderPolicy.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.Cache/CacheHeaderPolicy.cs
----
using redb.Route.Abstractions;
namespace redb.Route.Cache;
///
/// Which headers a cache entry may carry. A hit hands one exchange's headers to another, so an entry
/// keeps what the miss produced, never what the exchange came in with, and never a credential: an
/// Authorization , Proxy-Authorization (RFC 9110), Cookie or Set-Cookie
/// (RFC 6265) belongs to the exchange it arrived on. The HTTP consumer drops Authorization after
/// its own check for the same reason; the cache is the other place a header crosses exchanges.
///
internal static class CacheHeaderPolicy
{
private static readonly HashSet Credentials = new(StringComparer.OrdinalIgnoreCase)
{
"Authorization", "Proxy-Authorization", "Cookie", "Set-Cookie",
};
/// A header a cache entry never carries, whichever form named it.
public static bool IsCredential(string name) => Credentials.Contains(name);
/// The header values an exchange came in with, by name, taken before the inner steps run.
public static Dictionary Snapshot(IMessage message)
=> new(message.Headers, StringComparer.OrdinalIgnoreCase);
///
/// The headers of the inner steps produced: added, or set to another
/// instance than the one in . A header the steps did not touch is the same
/// instance afterwards, which is how the HTTP consumer tells a route's response header from an
/// echoed request header. Credentials and cache.hit are never part of it.
///
public static Dictionary Produced(IMessage message, IReadOnlyDictionary before)
{
var produced = new Dictionary(StringComparer.OrdinalIgnoreCase);
foreach (var (name, value) in message.Headers)
{
if (IsCredential(name) || string.Equals(name, CacheScopeProcessor.HitHeader, StringComparison.OrdinalIgnoreCase)) continue;
if (before.TryGetValue(name, out var arrived) && ReferenceEquals(arrived, value)) continue;
produced[name] = value;
}
return produced;
}
/// The names in the inner steps removed from .
public static List Removed(IMessage message, IReadOnlyDictionary before)
{
var removed = new List();
foreach (var name in before.Keys)
if (!message.Headers.ContainsKey(name))
removed.Add(name);
return removed;
}
}
Path: redb-route/redb.Route.Cache/CacheKeys.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.Cache/CacheKeys.cs
----
namespace redb.Route.Cache;
///
/// How a region and a key become one store key. The region is length-prefixed, so region a
/// with key b:c and region a:b with key c never share an entry, and clearing a
/// region never reaches a neighbour whose name merely starts the same way.
///
internal static class CacheKeys
{
/// The store key of in .
public static string For(string region, string key) => $"{region.Length}:{region}:{key}";
/// The prefix every key of starts with (region-wide clear).
public static string Prefix(string region) => $"{region.Length}:{region}:";
}
Path: redb-route/redb.Route.Cache/CacheProducer.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.Cache/CacheProducer.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.Cache;
/// Executes the endpoint's action against the resolved store.
internal sealed class CacheProducer : IProducer
{
private readonly CacheEndpoint _endpoint;
private readonly CacheEndpointOptions _options;
private ICacheStore? _store;
private TimeSpan? _ttl;
private TimeSpan? _sliding;
public CacheProducer(CacheEndpoint endpoint, CacheEndpointOptions options)
{
_endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
_options = options ?? throw new ArgumentNullException(nameof(options));
}
private readonly object _startLock = new();
private volatile bool _started;
public Task Start(CancellationToken ct = default)
{
// Idempotent and atomic: two first messages racing into a lazily started producer must not see
// the store set while the TTL is still missing (an entry stored without expiry).
lock (_startLock)
{
if (_started) return Task.CompletedTask;
var context = (_endpoint.Component as ComponentBase)?.Context
?? throw new InvalidOperationException("cache: component is not attached to a route context.");
var options = CacheStores.Options(context);
_ttl = CacheDuration.Parse(_options.Ttl) ?? options.DefaultTtl;
_sliding = CacheDuration.Parse(_options.Sliding);
_store = CacheStores.Resolve(context, _options.ParsedProvider ?? options.DefaultProvider);
_started = true;
}
return Task.CompletedTask;
}
public Task Stop(CancellationToken ct = default) => Task.CompletedTask;
public async Task Process(IExchange exchange, CancellationToken ct = default)
{
if (!_started) await Start(ct).ConfigureAwait(false);
var store = _store!;
if (_options.ParsedAction == CacheAction.Clear)
{
await store.ClearAsync(_endpoint.Region, ct).ConfigureAwait(false);
return;
}
var rawKey = _options.Key!.Value.Resolve(exchange);
if (string.IsNullOrEmpty(rawKey))
throw new InvalidOperationException("cache: key resolved to an empty value.");
var key = CacheKeys.For(_endpoint.Region, rawKey);
switch (_options.ParsedAction)
{
case CacheAction.Get:
// Where the entry came from is part of it: a reply the scope cached out of Out goes back to
// Out, so a request-reply consumer answers with it and not with the request body.
var hit = await store.GetAsync(key, ct).ConfigureAwait(false);
hit?.ApplyTo(exchange);
exchange.In.Headers[CacheScopeProcessor.HitHeader] = hit is not null;
break;
case CacheAction.Put:
// The message as it reached this step: the pipeline has folded the previous step's reply
// into In by now, so there is no Out to store.
await store.SetAsync(key, CacheEntry.FromMessage(exchange.In, _options.ParsedHeaders), _ttl, _sliding, ct).ConfigureAwait(false);
break;
case CacheAction.Remove:
await store.RemoveAsync(key, ct).ConfigureAwait(false);
break;
}
}
}
Path: redb-route/redb.Route.Cache/CacheRouteDefinitionExtensions.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.Cache/CacheRouteDefinitionExtensions.cs
----
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using redb.Route.Abstractions;
using redb.Route.Extensions;
namespace redb.Route.Cache;
/// DSL entry points and registration of the cache EIP.
public static class CacheRouteDefinitionExtensions
{
///
/// Opens a caching scope keyed by a route-language template ("customer-${header.customerId}" ).
/// On a hit the inner steps are skipped and the cached body is the message; on a miss they run and
/// the result is stored for . Close with EndCache() .
///
public static CacheDefinition Cache(this IRouteDefinition route, string keyTemplate, TimeSpan? ttl = null)
=> Cache(route, CacheDefinition.KeyFromTemplate(keyTemplate), ttl);
/// Opens a caching scope with a key computed by .
public static CacheDefinition Cache(this IRouteDefinition route, Func key, TimeSpan? ttl = null)
{
ArgumentNullException.ThrowIfNull(route);
var definition = new CacheDefinition(key, ttl) { Parent = route };
route.Outputs.Add(definition); // the public tree API, identical to ProcessorDefinition.AddOutput
return definition;
}
/// Registers options and the cache: component on a context built without DI.
public static IRouteContext UseCache(this IRouteContext context, Action? configure = null)
{
ArgumentNullException.ThrowIfNull(context);
var options = new RouteCacheOptions();
configure?.Invoke(options);
context.AddService(typeof(RouteCacheOptions), options);
if (!context.GetComponentNames().Contains("cache", StringComparer.OrdinalIgnoreCase))
context.AddComponent(new CacheComponent());
return context;
}
/// DI registration: options plus the cache: component on the hosted context.
public static IServiceCollection AddRedbRouteCache(this IServiceCollection services, Action? configure = null)
{
ArgumentNullException.ThrowIfNull(services);
var options = new RouteCacheOptions();
configure?.Invoke(options);
services.TryAddSingleton(options);
// IRouteContextConfigurator is applied by RouteHostedService at startup --
// the correct registration hook (a lazy marker singleton never fires).
services.AddRouteComponent();
return services;
}
}
Path: redb-route/redb.Route.Cache/CacheScopeProcessor.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.Cache/CacheScopeProcessor.cs
----
using System.Collections.Concurrent;
using redb.Route.Abstractions;
namespace redb.Route.Cache;
/// Runtime side of .
internal sealed class CacheScopeProcessor : IProcessor
{
/// Header set on every exchange passing a cache node: true on a hit, false on a miss.
public const string HitHeader = "cache.hit";
private readonly ICacheStore _store;
// Single flight per key: while one exchange computes a missing entry, the others arriving for the
// same key wait for its result instead of each running the inner steps (a stampede on a hot key
// the moment it expires is exactly what a cache is there to prevent). The map belongs to the
// store's context, not to this node: two nodes on one region and key are one flight.
private readonly ConcurrentDictionary> _inFlight;
private readonly Func _key;
private readonly TimeSpan? _ttl;
private readonly TimeSpan? _sliding;
private readonly bool _cacheHeaders;
private readonly IProcessor _inner;
public CacheScopeProcessor(
ICacheStore store,
ConcurrentDictionary> inFlight,
Func key,
TimeSpan? ttl,
TimeSpan? sliding,
bool cacheHeaders,
IProcessor inner)
{
_store = store;
_inFlight = inFlight;
_key = key;
_ttl = ttl;
_sliding = sliding;
_cacheHeaders = cacheHeaders;
_inner = inner;
}
public async Task Process(IExchange exchange, CancellationToken ct = default)
{
var key = _key(exchange);
while (true)
{
var hit = await _store.GetAsync(key, ct).ConfigureAwait(false);
if (hit is not null)
{
Apply(exchange, hit);
return;
}
var mine = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var owner = _inFlight.GetOrAdd(key, mine);
if (!ReferenceEquals(owner, mine))
{
// Somebody else is computing this key: take its result. Null means it failed or stopped
// without caching; then look again, and compute here if nobody else has taken over.
var computed = await owner.Task.WaitAsync(ct).ConfigureAwait(false);
if (computed is not null)
{
Apply(exchange, computed);
return;
}
continue;
}
try
{
var entry = await ComputeAsync(exchange, key, ct).ConfigureAwait(false);
mine.TrySetResult(entry);
return;
}
catch
{
mine.TrySetResult(null);
throw;
}
finally
{
_inFlight.TryRemove(new KeyValuePair>(key, mine));
}
}
}
private static void Apply(IExchange exchange, CacheEntry entry)
{
entry.ApplyTo(exchange);
exchange.In.Headers[HitHeader] = true;
}
/// Runs the inner steps and stores the result; null when the exchange stopped or failed (nothing cached).
private async Task ComputeAsync(IExchange exchange, string key, CancellationToken ct)
{
exchange.In.Headers[HitHeader] = false;
// With CacheHeaders(): the headers the exchange came in with, so the entry can keep what the
// inner steps did to them and nothing of what arrived (another exchange gets the entry on a hit).
var before = _cacheHeaders ? CacheHeaderPolicy.Snapshot(exchange.In) : null;
await _inner.Process(exchange, ct).ConfigureAwait(false);
if (exchange.IsStopped || exchange.Exception is not null)
return null;
var entry = CacheEntry.FromResult(exchange, before);
await _store.SetAsync(key, entry, _ttl, _sliding, ct).ConfigureAwait(false);
return entry;
}
}
Path: redb-route/redb.Route.Cache/CacheSerialization.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.Cache/CacheSerialization.cs
----
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using redb.Route.Abstractions;
namespace redb.Route.Cache;
///
/// How a body that is neither text nor bytes becomes bytes: through the context's data format for the
/// message's content type (JSON when the message names none, or names one without a serializer). One
/// rule for the distributed store and for KeyFromBody() , so what is hashed is what is stored.
///
internal static class CacheSerialization
{
private static readonly MethodInfo SerializeDefinition =
typeof(IMessageSerializer).GetMethod(nameof(IMessageSerializer.Serialize))!;
// IMessageSerializer.Serialize is generic, so the call is closed over the body type once, not on
// every write. The table holds its keys weakly: a type from an unloaded plugin is not kept alive here.
private static readonly ConditionalWeakTable SerializeMethods = new();
/// Serializes ; the serializer's own exception comes out, not the reflection wrapper.
public static (byte[] Bytes, IMessageSerializer Serializer) Serialize(IDataFormatRegistry? registry, object body, string? contentType)
{
var type = body.GetType();
var wanted = contentType ?? "application/json";
var serializer = registry?.GetSerializer(wanted) ?? registry?.GetSerializer("application/json")
?? throw new InvalidOperationException($"Cache: no data format for '{wanted}' to serialize a {type.Name} body.");
var method = SerializeMethods.GetValue(type, static t => SerializeDefinition.MakeGenericMethod(t));
try
{
return ((byte[])method.Invoke(serializer, [body])!, serializer);
}
catch (TargetInvocationException ex) when (ex.InnerException is not null)
{
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
throw;
}
}
}
Path: redb-route/redb.Route.Cache/CacheStores.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.Cache/CacheStores.cs
----
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Abstractions;
namespace redb.Route.Cache;
///
/// Resolves the store for a node: options and caches come from the context services first
/// (UseCache , AddService ), then from DI, then — for the in-process cache — a
/// is created once per context and shared by every cache node.
///
internal static class CacheStores
{
private static readonly object Sync = new();
public static RouteCacheOptions Options(IRouteContext context)
=> context.GetService()
?? context.GetServiceProvider()?.GetService()
?? new RouteCacheOptions();
public static ICacheStore Resolve(IRouteContext context, CacheProvider provider)
{
lock (Sync)
{
return provider == CacheProvider.Distributed ? Distributed(context) : Memory(context);
}
}
/// The computations in progress on the store returns for the same provider.
public static System.Collections.Concurrent.ConcurrentDictionary> Flights(IRouteContext context, CacheProvider provider)
{
lock (Sync)
{
if (context.GetService() is not { } flights)
{
flights = new CacheFlights();
context.AddService(typeof(CacheFlights), flights);
}
return flights.For(provider);
}
}
private static ICacheStore Memory(IRouteContext context)
{
if (context.GetService() is { } existing) return existing;
var hostCache = context.GetService() ?? context.GetServiceProvider()?.GetService();
if (hostCache is null)
{
var options = Options(context);
hostCache = new MemoryCache(new MemoryCacheOptions { SizeLimit = options.MaxEntries });
context.AddService(typeof(IMemoryCache), hostCache);
}
var store = new MemoryCacheStore(hostCache);
context.AddService(typeof(MemoryCacheStore), store);
return store;
}
private static ICacheStore Distributed(IRouteContext context)
{
if (context.GetService() is { } existing) return existing;
var cache = context.GetService() ?? context.GetServiceProvider()?.GetService()
?? throw new InvalidOperationException(
"Cache: no IDistributedCache is registered. Add one in DI (services.AddStackExchangeRedisCache(...), " +
"AddDistributedMemoryCache()) or on the context (context.AddService(typeof(IDistributedCache), cache)).");
var store = new DistributedCacheStore(cache, context.GetService());
context.AddService(typeof(DistributedCacheStore), store);
return store;
}
}
Path: redb-route/redb.Route.Cache/CacheXmlContribution.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.Cache/CacheXmlContribution.cs
----
using System.Xml.Linq;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Xml;
namespace redb.Route.Cache;
///
/// The <cache> element: the
/// contribution this package registers via —
/// parse, schema shape and C# printing in one place, so the loader, the XSD and the generator
/// see the element together or not at all.
///
public sealed class CacheXmlContribution : IXmlElementContribution
{
///
public string Name => "cache";
///
public XmlElementKind Kind => XmlElementKind.Scope;
///
public ElementSpec Spec => new(Name, Kind,
[
new AttributeSpec("key", AttributeType.Expression) { ConstantKey = true },
new AttributeSpec("keyFromBody", AttributeType.Bool),
new AttributeSpec("ttl", AttributeType.Duration),
new AttributeSpec("sliding", AttributeType.Duration),
new AttributeSpec("region", AttributeType.String),
new AttributeSpec("cacheHeaders", AttributeType.Bool),
new AttributeSpec("provider", AttributeType.Enum, EnumValues: ["memory", "distributed"]),
],
[], AllowsSteps: true);
///
public IRouteDefinition Apply(XElement element, IRouteDefinition current, XmlParseContext context)
{
var pick = context.ExactlyOneOf(element, "key", "keyFromBody");
if (pick is null)
return current;
var ttl = context.Convert(element, "ttl");
var scope = pick.Value.Name == "key"
? current.Cache(pick.Value.Value, ttl)
: current.Cache(static _ => string.Empty, ttl).KeyFromBody();
if (context.Convert(element, "sliding") is { } sliding) scope.SlidingExpiration(sliding);
if (context.Attr(element, "region") is { } region) scope.Region(region);
if (context.Convert(element, "cacheHeaders") == true) scope.CacheHeaders();
switch (context.Attr(element, "provider"))
{
case "distributed": scope.Distributed(); break;
case "memory": scope.InMemory(); break;
case null: break;
case { } other:
context.AddError(element, $"'{other}' is not a cache provider (memory, distributed).");
return current;
}
context.ParseSteps(element, scope);
return scope.EndCache();
}
///
public void Print(XElement element, XmlCodeWriter code)
{
var key = element.Attribute("key")?.Value;
var ttl = element.Attribute("ttl")?.Value is { } t
? XmlCodeWriter.Ts(TimeSpan.Parse(t, System.Globalization.CultureInfo.InvariantCulture))
: null;
var first = key is not null ? XmlCodeWriter.Str(key) : "static _ => string.Empty";
string[] args = ttl is null ? [first] : [first, ttl];
code.Scope(element, "Cache", args, "EndCache", body: w =>
{
if (key is null) w.Config("KeyFromBody()");
if (element.Attribute("sliding")?.Value is { } sliding)
w.Config($"SlidingExpiration({XmlCodeWriter.Ts(TimeSpan.Parse(sliding, System.Globalization.CultureInfo.InvariantCulture))})");
if (element.Attribute("region")?.Value is { } region) w.Config($"Region({XmlCodeWriter.Str(region)})");
if (element.Attribute("cacheHeaders")?.Value == "true") w.Config("CacheHeaders()");
switch (element.Attribute("provider")?.Value)
{
case "distributed": w.Config("Distributed()"); break;
case "memory": w.Config("InMemory()"); break;
}
w.PrintSteps(element);
});
}
}
Path: redb-route/redb.Route.Cache/DistributedCacheStore.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.Cache/DistributedCacheStore.cs
----
using System.Collections.Concurrent;
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.Caching.Distributed;
using redb.Route.Abstractions;
namespace redb.Route.Cache;
///
/// Store over . Entries travel as a JSON envelope: text and bytes as
/// they are, any other body through the data-format registry (JSON by default) with its CLR type
/// name, so it comes back as the same type when that type is resolvable on the reading side.
/// Header values that are JSON primitives are kept; others are dropped. The envelope carries a
/// marker and a version: a value under our key without them is an error, never a hit or a miss.
///
internal sealed class DistributedCacheStore : ICacheStore
{
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
private readonly IDistributedCache _cache;
private readonly IDataFormatRegistry? _registry;
// Keys this process wrote, each with the moment it stops mattering: the abstraction cannot enumerate,
// so region-wide clear works from this list, and expired leases are swept periodically so the list
// does not grow forever. A sliding entry lives on with every read, so a hit renews its lease too.
private readonly ConcurrentDictionary _writtenKeys = new(StringComparer.Ordinal);
private int _writes;
// Body types already resolved by name, so a hit does not walk the loaded assemblies again. Only
// what resolved is remembered (a type may load later), and only for this store's context.
private readonly ConcurrentDictionary _resolvedTypes = new(StringComparer.Ordinal);
private readonly record struct KeyLease(DateTime Expires, DateTime? Absolute, TimeSpan? Sliding)
{
public static KeyLease Start(DateTime now, TimeSpan? ttl, TimeSpan? sliding)
{
DateTime? absolute = ttl is { } t ? now + t : null;
return new KeyLease(Until(now, absolute, sliding), absolute, sliding);
}
public KeyLease Renewed(DateTime now) => this with { Expires = Until(now, Absolute, Sliding) };
private static DateTime Until(DateTime now, DateTime? absolute, TimeSpan? sliding)
{
if (sliding is not { } s) return absolute ?? DateTime.MaxValue;
var slid = now + s;
return absolute is { } a && a < slid ? a : slid;
}
}
public DistributedCacheStore(IDistributedCache cache, IDataFormatRegistry? registry)
{
_cache = cache ?? throw new ArgumentNullException(nameof(cache));
_registry = registry;
}
public async ValueTask GetAsync(string key, CancellationToken ct)
{
var bytes = await _cache.GetAsync(key, ct).ConfigureAwait(false);
if (bytes is null) return null;
if (_writtenKeys.TryGetValue(key, out var lease) && lease.Sliding is not null)
_writtenKeys[key] = lease.Renewed(DateTime.UtcNow);
// A value under our key that we did not write is neither a hit nor a miss: a hit would hand the
// route a body that is not one, a miss would overwrite somebody else's data. It is a shared key
// space (or an entry from before the marker), and that is for the operator to sort out.
Envelope? envelope;
try
{
envelope = JsonSerializer.Deserialize(bytes, JsonOptions);
}
catch (JsonException ex)
{
throw NotOurs(key, "the value is not JSON", ex);
}
if (envelope is null || envelope.Format != Format)
throw NotOurs(key, "the value carries no redb.Route envelope marker", null);
if (envelope.Version != FormatVersion)
throw NotOurs(key, $"the envelope is version {envelope.Version}; this build reads version {FormatVersion}", null);
return Unwrap(envelope);
}
private static InvalidOperationException NotOurs(string key, string reason, Exception? inner)
=> new($"Cache: the value under key '{key}' in the distributed cache is not a redb.Route cache entry ({reason}). " +
"Another writer shares this key space (give this cache its own key prefix, e.g. RedisCacheOptions.InstanceName, " +
"or another region), or the entry predates the envelope marker (clear the region or let it expire).", inner);
public async ValueTask SetAsync(string key, CacheEntry entry, TimeSpan? ttl, TimeSpan? sliding, CancellationToken ct)
{
var envelope = Wrap(entry);
var options = new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = ttl, SlidingExpiration = sliding };
await _cache.SetAsync(key, JsonSerializer.SerializeToUtf8Bytes(envelope, JsonOptions), options, ct).ConfigureAwait(false);
var now = DateTime.UtcNow;
_writtenKeys[key] = KeyLease.Start(now, ttl, sliding);
if (Interlocked.Increment(ref _writes) % 256 == 0)
SweepExpired(now);
}
public async ValueTask RemoveAsync(string key, CancellationToken ct)
{
await _cache.RemoveAsync(key, ct).ConfigureAwait(false);
_writtenKeys.TryRemove(key, out _);
}
/// Best effort: cannot enumerate, so only keys written by this process are removed.
public async ValueTask ClearAsync(string region, CancellationToken ct)
{
var prefix = CacheKeys.Prefix(region);
foreach (var key in _writtenKeys.Keys.Where(k => k.StartsWith(prefix, StringComparison.Ordinal)).ToList())
await RemoveAsync(key, ct).ConfigureAwait(false);
}
private void SweepExpired(DateTime now)
{
foreach (var (key, lease) in _writtenKeys)
if (lease.Expires < now)
_writtenKeys.TryRemove(new KeyValuePair(key, lease));
}
///
/// Resolves a body type name read out of the cache against the assemblies already loaded: a name
/// written by another process (or by anyone who can write to the cache) must never make this
/// process load an assembly from disk.
///
private Type? ResolveLoadedType(string name)
{
if (_resolvedTypes.TryGetValue(name, out var known)) return known;
var type = Type.GetType(name,
assemblyName => AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => string.Equals(a.GetName().Name, assemblyName.Name, StringComparison.OrdinalIgnoreCase)),
typeResolver: null,
throwOnError: false);
if (type is not null) _resolvedTypes[name] = type;
return type;
}
private Envelope Wrap(CacheEntry entry)
{
var envelope = new Envelope { Format = Format, Version = FormatVersion, ContentType = entry.ContentType, FromOut = entry.FromOut };
switch (entry.Body)
{
case null: break;
case string text: envelope.Text = text; break;
case byte[] bytes: envelope.Bytes = bytes; break;
default:
var (serialized, serializer) = CacheSerialization.Serialize(_registry, entry.Body, entry.ContentType);
envelope.Bytes = serialized;
envelope.BodyType = entry.Body.GetType().AssemblyQualifiedName;
envelope.ContentType ??= serializer.ContentType;
break;
}
envelope.Headers = WrapHeaders(entry.Headers);
envelope.InHeaders = WrapHeaders(entry.InHeaders);
envelope.Removed = entry.RemovedHeaders is { Count: > 0 } removed ? removed.ToArray() : null;
return envelope;
}
/// Header values that are JSON primitives travel; any other value is dropped.
private static Dictionary? WrapHeaders(IReadOnlyDictionary? headers)
{
if (headers is null) return null;
var wrapped = new Dictionary(StringComparer.OrdinalIgnoreCase);
foreach (var (name, value) in headers)
if (value is null or string or bool or sbyte or byte or short or ushort or int or uint or long or ulong or float or double or decimal)
wrapped[name] = JsonSerializer.SerializeToElement(value, JsonOptions);
return wrapped;
}
private static Dictionary? UnwrapHeaders(Dictionary? headers)
{
if (headers is null) return null;
var unwrapped = new Dictionary(StringComparer.OrdinalIgnoreCase);
foreach (var (name, element) in headers)
unwrapped[name] = element.ValueKind switch
{
JsonValueKind.String => element.GetString(),
JsonValueKind.True => true,
JsonValueKind.False => false,
JsonValueKind.Number => element.TryGetInt64(out var l) ? l : element.GetDecimal(),
JsonValueKind.Null => null,
_ => element.GetRawText(),
};
return unwrapped;
}
private CacheEntry? Unwrap(Envelope envelope)
{
object? body = null;
if (envelope.Text is not null) body = envelope.Text;
else if (envelope.Bytes is not null)
{
body = envelope.Bytes;
if (envelope.BodyType is not null)
{
// An object was cached under a type this process cannot resolve (a different deployment
// wrote it, or the type is gone): handing raw bytes to a step that expects the object would
// only fail later and further away, so the entry counts as a miss and is recomputed.
var type = ResolveLoadedType(envelope.BodyType);
var serializer = type is null ? null : _registry?.GetSerializer(envelope.ContentType ?? "application/json");
if (type is null || serializer is null)
return null;
body = serializer.Deserialize(envelope.Bytes, type);
}
}
return new CacheEntry
{
Body = body,
ContentType = envelope.ContentType,
Headers = UnwrapHeaders(envelope.Headers),
InHeaders = UnwrapHeaders(envelope.InHeaders),
RemovedHeaders = envelope.Removed,
FromOut = envelope.FromOut,
};
}
/// Marker every envelope carries; a value without it was not written by this store.
private const string Format = "redb.route.cache";
/// Shape of the envelope; a reader accepts exactly the version it writes.
private const int FormatVersion = 1;
private sealed class Envelope
{
public string? Format { get; set; }
public int Version { get; set; }
public string? ContentType { get; set; }
public string? BodyType { get; set; }
public string? Text { get; set; }
public byte[]? Bytes { get; set; }
public Dictionary? Headers { get; set; }
public Dictionary? InHeaders { get; set; }
public string[]? Removed { get; set; }
public bool FromOut { get; set; }
}
}
Path: redb-route/redb.Route.Cache/ICacheStore.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.Cache/ICacheStore.cs
----
namespace redb.Route.Cache;
/// One provider behind both forms of the EIP (scope and component).
internal interface ICacheStore
{
ValueTask GetAsync(string key, CancellationToken ct);
ValueTask SetAsync(string key, CacheEntry entry, TimeSpan? ttl, TimeSpan? sliding, CancellationToken ct);
ValueTask RemoveAsync(string key, CancellationToken ct);
/// Removes every key of a region (keys are region:key ).
ValueTask ClearAsync(string region, CancellationToken ct);
}
Path: redb-route/redb.Route.Cache/MemoryCacheStore.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.Cache/MemoryCacheStore.cs
----
using System.Collections.Concurrent;
using Microsoft.Extensions.Caching.Memory;
namespace redb.Route.Cache;
/// In-process store over : entries are kept as objects, no serialization.
internal sealed class MemoryCacheStore : ICacheStore
{
private readonly IMemoryCache _cache;
// The keys this store wrote, each with the token of its latest write: IMemoryCache cannot enumerate,
// so a region-wide clear works from this list. An entry's eviction callback takes the key off the
// list only while the list still holds that entry's own token, and never for a replacement:
// MemoryCache fires the callback of the entry it replaces too (EvictionReason.Replaced), on the
// thread pool, after the new entry is in, and a plain remove there dropped the live key.
private readonly ConcurrentDictionary _keys = new(StringComparer.Ordinal);
public MemoryCacheStore(IMemoryCache cache)
{
_cache = cache ?? throw new ArgumentNullException(nameof(cache));
}
public ValueTask GetAsync(string key, CancellationToken ct)
=> ValueTask.FromResult(_cache.TryGetValue(key, out CacheEntry? entry) ? entry : null);
public ValueTask SetAsync(string key, CacheEntry entry, TimeSpan? ttl, TimeSpan? sliding, CancellationToken ct)
{
// Registered before the entry is committed (the Dispose of the using): a cache that rejects the
// entry at once (SizeLimit) fires its callback then, and finds the token to take off.
var token = new object();
_keys[key] = token;
using var cacheEntry = _cache.CreateEntry(key);
cacheEntry.Value = entry;
if (ttl is not null) cacheEntry.AbsoluteExpirationRelativeToNow = ttl;
if (sliding is not null) cacheEntry.SlidingExpiration = sliding;
// Always sized: a cache with a SizeLimit (ours via MaxEntries, or the host's own) rejects an
// entry without a Size on every write; a cache without a limit ignores the value.
cacheEntry.Size = 1;
cacheEntry.RegisterPostEvictionCallback(static (k, _, reason, state) =>
{
if (reason == EvictionReason.Replaced) return;
var (keys, ownToken) = ((ConcurrentDictionary Keys, object Token))state!;
keys.TryRemove(new KeyValuePair((string)k, ownToken));
}, (_keys, token));
return ValueTask.CompletedTask;
}
public ValueTask RemoveAsync(string key, CancellationToken ct)
{
_cache.Remove(key);
_keys.TryRemove(key, out _);
return ValueTask.CompletedTask;
}
public ValueTask ClearAsync(string region, CancellationToken ct)
{
var prefix = CacheKeys.Prefix(region);
foreach (var key in _keys.Keys.Where(k => k.StartsWith(prefix, StringComparison.Ordinal)).ToList())
{
_cache.Remove(key);
_keys.TryRemove(key, out _);
}
return ValueTask.CompletedTask;
}
}
Path: redb-route/redb.Route.Cache/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.Cache/README.md
----
# redb.Route.Cache
> Documentation and articles:
Cache as an EIP (WSO2 `Cache` mediator / Camel `caffeine-cache` analog) over the .NET caching
abstractions: `IMemoryCache` in-process (default, created on demand) or `IDistributedCache`
(Redis, SQL Server, anything registered in DI).
## Caching scope
```csharp
.Cache("customer-${header.customerId}", TimeSpan.FromMinutes(5))
.Enrich("http://crm/customers/${header.customerId}")
.EndCache()
```
On a hit the body (and, with `.CacheHeaders()`, the headers) comes from the cache and the inner
steps are skipped; on a miss they run and the result is stored. Header `cache.hit` tells which.
Options: `.Region("customers")`, `.SlidingExpiration(...)`, `.CacheHeaders()`, `.Distributed()`,
`.KeyFromBody()`.
The key, in C# and in ``, is a template: `${...}` holes are evaluated, and a key without one that starts with
no root of the message (`header.`, `property.`, `body`, `exception.`, `bean:`, `ref:`, `env:`, a function call) is the key
as written, so `orders-all` and `reports/daily` are constants. A key that starts with a root is an expression
(`header.customerId`), and one that does not compile (`header.a+b`) fails when the route is built. A constant that
begins with a root word (`body-cache`, `header.txt`) is written in quotes: `'body-cache'`.
`.KeyFromBody()` takes the SHA-256 of the body instead of an explicit key. Only the body is hashed: the
content type and the headers are not part of the key. A `Stream` body is read to the end for it and the
message continues with its bytes; an object goes through the context's data format for the message's
content type, the way the distributed cache stores it. A body that cannot be serialized fails the
exchange with an error that names `KeyFromBody` and the type.
## Component
```csharp
.To("cache:customers?action=get&key=${header.customerId}")
.Filter("header.cache.hit == false")
.Enrich("http://crm/...")
.To("cache:customers?action=put&key=${header.customerId}&ttl=5m")
.EndFilter()
```
`cache:?action=get|put|remove|clear&key=...&ttl=5m&sliding=1m&provider=memory|distributed&headers=X-Rate,Content-Language`.
Durations: `500ms`, `30s`, `5m`, `2h`, `1d` or `hh:mm:ss` (a bare number is refused: `5` would be five
days to `TimeSpan`; a number `TimeSpan` cannot hold is refused the same way). Region and key are joined
with a length-prefixed separator, so region `a` / key `b:c` and region `a:b` / key `c` are two entries.
- `get` sets `cache.hit` and restores the entry where it was cached from: a reply the scope stored out
of `Out` comes back as `Out`, anything else as `In`.
- `put` stores the message as it reaches the step. The pipeline has folded the previous step's reply
into `In` by then. Of the headers it stores only the ones named with `headers=` (see Headers).
- `clear` empties the region (see Boundaries for what it can see).
- The options are checked when the endpoint is created, and `To` creates it on the first message.
## What a hit hands back
A miss is computed once per key at a time, across every cache node of the context that shares the
store: concurrent exchanges for the same key wait for the first one's result instead of each running
the inner steps. A failed computation is not cached, so the waiters retry one at a time. A `Stream`
body is buffered on the miss (the live message continues with the bytes) so a hit can replay it; a
`JsonNode` body is copied into and out of the cache. Text and byte arrays are treated as immutable.
**Any other object (a POCO, a list) is shared by every hit by design**: do not mutate what a cache
scope handed you, or clone it first.
## Headers
A hit hands the entry to another exchange, so an entry never carries what an exchange came in with,
and never a credential.
- **Scope, `.CacheHeaders()`.** The entry keeps what the inner steps did to the headers, compared by
instance with the ones the exchange came in with: the headers added or changed, and the names
removed. A hit does the same to the current exchange and leaves its other headers alone,
`Authorization`, `Cookie` and the `redbHttp.*` request metadata included. With the reply in `Out`, the
reply's own headers and what the steps did to `In` are both kept. A header a step set to the very
instance it arrived as counts as untouched.
- **Component, `put`.** Only the headers named with `headers=Name1,Name2`; a name the message does not
carry is skipped. `cacheHeaders=true` is refused: a `put` sees the message as a whole and cannot tell
the headers of the value from the headers of the request.
- **Never, in either form:** `Authorization`, `Proxy-Authorization`, `Cookie`, `Set-Cookie`. Naming one
on a `put` is an error.
## Setup
Nothing for the in-process cache. `context.UseCache(o => o.MaxEntries = 10_000)` / `services.AddRedbRouteCache(o => ...)`
register options (and the `cache:` component in DI). For `Distributed`, register an `IDistributedCache`
(`services.AddStackExchangeRedisCache(...)`, `AddDistributedMemoryCache()`, or
`context.AddService(typeof(IDistributedCache), cache)`). A POCO body goes through the distributed cache
as JSON and comes back as the same CLR type wherever that type's assembly is loaded; where it is not,
the entry counts as a miss.
## Boundaries
- **`clear` works from a list of written keys**, because neither abstraction can enumerate. On a
distributed cache it removes the keys this process has written; a sliding key stays on the list for
as long as it is read. On the in-process cache it removes the keys this context has written: two
contexts sharing one host `IMemoryCache` keep a list each.
- **A value under a cache key that this package did not write is an error** naming the key, not a hit
and not a miss: no envelope marker, not JSON, or an envelope version this build does not read. Give
the cache its own key prefix (`RedisCacheOptions.InstanceName`) or another region. Entries written
before the marker existed are refused the same way, so clear the regions of a distributed cache
after upgrading.
- **One computation per key holds inside a context.** Other processes, and other contexts in the same
process, compute on their own: there is no distributed lock.
- **Headers go through a distributed cache as JSON primitives**; other values are dropped.
- **`MaxEntries` bounds the cache the package creates**; a cache registered by the host keeps its own
settings.
- **No spans or metrics.** A cache node is a call inside the process, not a transport. `cache.hit` is
the signal, inside the route.
Path: redb-route/redb.Route.Cache/RouteCacheOptions.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.Cache/RouteCacheOptions.cs
----
using System.Globalization;
namespace redb.Route.Cache;
/// Which cache backs a node.
public enum CacheProvider
{
/// In-process IMemoryCache (created on demand when none is registered).
Memory,
/// IDistributedCache registered in DI or on the context (Redis, SQL Server, …).
Distributed,
}
/// Package-wide settings: context.UseCache(o => …) / services.AddRedbRouteCache(o => …) .
public sealed class RouteCacheOptions
{
/// Upper bound on entries of the package-created in-process cache (one unit per entry); null = unbounded. Ignored for a cache registered by the host.
public long? MaxEntries { get; set; }
/// TTL applied when a node does not give one; null = no expiration.
public TimeSpan? DefaultTtl { get; set; }
/// Provider used when a node does not choose one. Default .
public CacheProvider DefaultProvider { get; set; } = CacheProvider.Memory;
}
/// Durations as people write them in URIs: 500ms , 30s , 5m , 2h , 1d , or hh:mm:ss .
public static class CacheDuration
{
/// Parses a duration; null / empty → null . Anything unusable is a .
public static TimeSpan? Parse(string? text)
{
if (string.IsNullOrWhiteSpace(text)) return null;
var value = text.Trim();
TimeSpan? parsed = null;
foreach (var (suffix, millisecondsPerUnit) in Units)
{
if (!value.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)) continue;
var number = value[..^suffix.Length].Trim();
if (double.TryParse(number, NumberStyles.Float, CultureInfo.InvariantCulture, out var amount))
{
// A number TimeSpan cannot hold (too large, NaN, infinity) is a typo like any other, so it
// is the same FormatException, not the OverflowException / ArgumentException of TimeSpan.
var milliseconds = amount * millisecondsPerUnit;
if (!(Math.Abs(milliseconds) <= TimeSpan.MaxValue.TotalMilliseconds))
throw new FormatException($"'{text}' is not a duration a TimeSpan can hold (at most {TimeSpan.MaxValue.TotalDays:F0} days).");
parsed = TimeSpan.FromMilliseconds(milliseconds);
break;
}
}
// A bare number is ambiguous — TimeSpan would read "5" as five days — so a unit is required.
if (parsed is null && double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out _))
throw new FormatException($"'{text}' has no unit: write 5s, 5m, 2h, 1d or hh:mm:ss.");
if (parsed is null && TimeSpan.TryParse(value, CultureInfo.InvariantCulture, out var span))
parsed = span;
if (parsed is null)
throw new FormatException($"'{text}' is not a duration (use 500ms, 30s, 5m, 2h, 1d or hh:mm:ss).");
if (parsed.Value <= TimeSpan.Zero)
throw new FormatException($"'{text}' is not a positive duration.");
return parsed;
}
private static readonly (string Suffix, double MillisecondsPerUnit)[] Units =
[
("ms", 1),
("s", 1_000),
("m", 60_000),
("h", 3_600_000),
("d", 86_400_000),
];
}
Path: redb-route/redb.Route.Cache/redb.Route.Cache.csproj
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Cache/redb.Route.Cache.csproj
----
redb.Route.Cache
Cache as an EIP for redb.Route: a caching scope (.Cache(key, ttl) ... .EndCache()) and a cache: component (get/put/remove/clear) over IMemoryCache or IDistributedCache.
esb;messaging;cache;eip;redb
README.md