API reference — Caching

Nuvora.Nexus.Relay.Cache

Core caching abstractions for Nuvora Nexus Relay

dotnet add package Nuvora.Nexus.Relay.Cache

Nuvora.Nexus.Relay.Cache

CacheKeyGenerator

public static class CacheKeyGenerator

Produces stable, deterministic cache keys. The previous approach used String.GetHashCode, which is randomized per process (and not stable across runs/instances). That makes a shared cache (e.g. Redis) effectively never hit and risks collisions. This generator hashes a canonical (recursively property-sorted) JSON representation with SHA-256 so the same logical query always maps to the same key, on every process and machine.

Methods

static string Canonicalize(string json)

Re-emits the supplied JSON with all object properties sorted by ordinal name, recursively, so semantically equal payloads with differing property order produce identical text. Invalid JSON is hashed verbatim (best-effort) rather than throwing.

static string ForQuery(string queryType, string payloadJson, string? prefix = null)

Builds a deterministic cache key for a query from its type name and a JSON payload. The payload is canonicalized (object properties sorted recursively) before hashing.

static string ForQueryType(string queryType, string? prefix = null)

The shared key prefix of every entry produced by CacheKeyGenerator.ForQuery for a given query type. Pass this to ICachingStrategy.RemoveByPrefixAsync to invalidate all cached results of that query type. queryType must match the name used when the key was written — the framework uses the query’s full type name (Type.FullName), so two query types with identical short names in different namespaces have distinct prefixes and never invalidate each other.

CacheResult<T>

public readonly struct CacheResult<T>

Explicit cache lookup outcome. Distinguishes a genuine miss from a hit on a null or default value-type payload (which null/default sentinels cannot).

Properties

T? Value { get; }

The cached value when CacheResult.Found is true; otherwise default.

bool Found { get; }

True when the key was present in the cache.

Methods

static CacheResult<T> Hit(T? value)
static CacheResult<T> Miss()

CacheSerialization

public static class CacheSerialization

Single source of truth for JSON serialization across the caching stack. The canonical query-payload serialization used for cache-key generation (see the query caching behavior) and the value serialization used by distributed cache strategies (e.g. Redis) share these options, so every node computes identical keys and reads/writes payloads in one consistent format.

Fields

static readonly JsonSerializerOptions Options

JsonSerializerDefaults.Web semantics: camelCase property names, case-insensitive property matching on read, and numbers readable from strings. Treat as immutable — these options are shared framework-wide; mutating them at runtime would silently change cache keys and stored payload formats.

CachingOptions

public class CachingOptions

Configuration options for caching strategies

Properties

TimeSpan DefaultExpiration { get; set; }

Default cache expiration time

int MaxCacheSize { get; set; }

Maximum cache size for in-memory caching

ICachingStrategy

public interface ICachingStrategy

Interface for caching strategies

Methods

Task RemoveAsync(string key, CancellationToken cancellationToken = default(CancellationToken))

Removes a value from cache

Task SetAsync<T>(string key, T value, TimeSpan expiration, CancellationToken cancellationToken = default(CancellationToken))

Sets a value in cache with expiration

Task<CacheResult<T>> TryGetAsync<T>(string key, CancellationToken cancellationToken = default(CancellationToken))

Gets a cached value with an explicit hit/miss outcome, so a cached null or default value-type payload is not mistaken for a miss.

Task<T?> GetAsync<T>(string key, CancellationToken cancellationToken = default(CancellationToken))

Gets a cached value by key

Task<bool> ExistsAsync(string key, CancellationToken cancellationToken = default(CancellationToken))

Checks if a key exists in cache

Task<int> RemoveByPrefixAsync(string keyPrefix, CancellationToken cancellationToken = default(CancellationToken))

Removes every cached entry whose key starts with keyPrefix. Used to invalidate a logical group of entries (e.g. all cached results of one query type) without knowing each individual key. The prefix is matched against the same logical keys passed to ICachingStrategy.SetAsync/ICachingStrategy.RemoveAsync; implementations apply any storage-level namespace themselves.

IQueryCacheInvalidator

public interface IQueryCacheInvalidator

Invalidates cached query results by query type, so a command handler can drop stale entries after it mutates the data a query reads — e.g. await invalidator.InvalidateQueryAsync<GetCartQuery>() after a cart is updated. Matches the key scheme produced by CacheKeyGenerator, so it clears every cached parameter combination of that query type, not just one.

Methods

Task<int> InvalidateQueryAsync(string queryTypeName, CancellationToken cancellationToken = default(CancellationToken))

Invalidates all cached results for the given query type.

Task<int> InvalidateQueryAsync<TQuery>(CancellationToken cancellationToken = default(CancellationToken))

Invalidates all cached results for TQuery. Uses the type’s full name (Type.FullName), so it only removes entries for this exact type — never for a same-named query type in another namespace.

ITenantCacheKeyProvider

public interface ITenantCacheKeyProvider

Soft-dependency that contributes the ambient tenant to query cache keys, so a shared cache (e.g. Redis) cannot serve tenant A’s cached query result to tenant B. The caching behavior and the invalidator pass ITenantCacheKeyProvider.TenantCachePrefix to CacheKeyGenerator as the key prefix.

SECURITY-CRITICAL: without a tenant prefix, two tenants issuing the same query share one cache entry and read each other’s data. The default returns null (single-tenant: no prefix); the tenancy package replaces it with a bridge to the ambient tenant.

Properties

string? TenantCachePrefix { get; }

The ambient tenant’s cache-key prefix, or null when no tenant is in scope (global).

NullTenantCacheKeyProvider

public sealed class NullTenantCacheKeyProvider : ITenantCacheKeyProvider

Default single-tenant provider: no prefix, so behaviour is unchanged without tenancy.

Properties

string? TenantCachePrefix { get; }

The ambient tenant’s cache-key prefix, or null when no tenant is in scope (global).

QueryCacheInvalidator

public sealed class QueryCacheInvalidator : IQueryCacheInvalidator

Default IQueryCacheInvalidator. Derives the query type’s key prefix via CacheKeyGenerator.ForQueryType — the same scheme the caching behavior uses to write keys — and removes the whole group through ICachingStrategy.RemoveByPrefixAsync.

Constructors

QueryCacheInvalidator(ICachingStrategy cache, ITenantCacheKeyProvider? tenantCacheKey = null)

Methods

Task<int> InvalidateQueryAsync(string queryTypeName, CancellationToken cancellationToken = default(CancellationToken))

Invalidates all cached results for the given query type.

Task<int> InvalidateQueryAsync<TQuery>(CancellationToken cancellationToken = default(CancellationToken))

Invalidates all cached results for TQuery. Uses the type’s full name (Type.FullName), so it only removes entries for this exact type — never for a same-named query type in another namespace.