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