Path: redb/redb.Core/Caching/GlobalMetadataCache.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Caching/GlobalMetadataCache.cs ---- using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using redb.Core.Attributes; using redb.Core.Models.Contracts; using redb.Core.Models.Configuration; using redb.Core.Models.Entities; using redb.Core.Providers; namespace redb.Core.Caching; /// /// Type information for caching (DB types, not CLR types). /// public class RedbTypeInfo { public long Id { get; set; } public string Name { get; set; } = ""; public string? DbType { get; set; } public string? Type1 { get; set; } } /// /// Domain-isolated cache data. /// internal class DomainCache { // Cache enabled flag (per-domain) public bool Enabled = true; // Scheme caching public readonly ConcurrentDictionary SchemeByName = new(); public readonly ConcurrentDictionary SchemeById = new(); // Structure trees built from the cached schemes (whole tree, and the children of a parent structure; null parent = // the root nodes). They live and die with the scheme: every invalidation of a scheme drops its trees, so no caller // can read a scheme again and keep building rows from the tree of its previous version. public readonly ConcurrentDictionary> StructureTrees = new(); public readonly ConcurrentDictionary<(long SchemeId, long? ParentId), List> Subtrees = new(); public void ForgetTrees(long schemeId) { StructureTrees.TryRemove(schemeId, out _); foreach (var key in Subtrees.Keys) if (key.SchemeId == schemeId) Subtrees.TryRemove(key, out _); } // DB Type caching (redb types table) public readonly ConcurrentDictionary TypeCache = new(); public readonly ConcurrentDictionary TypeById = new(); // Per-domain CLR type projection. scheme_id is a per-database fact, so this must stay isolated // per connection/domain. The database-independent schemeName↔Type mapping lives process-globally // in ClrSchemeTypeIndex (one scan serves all domains; self-healing on assembly load). // Both directions hold the type weakly, as ClrSchemeTypeIndex does: the type of a module loaded into a // collectible AssemblyLoadContext must not keep that context alive. A dead entry reads as a miss and is // re-derived lazily; a type of the default context never dies, so its entry behaves as a strong one. public readonly ConcurrentDictionary> SchemeIdToClrType = new(); public readonly ConditionalWeakTable> ClrTypeToSchemeId = new(); public void MapClrType(long schemeId, Type type) { SchemeIdToClrType[schemeId] = new WeakReference(type); ClrTypeToSchemeId.AddOrUpdate(type, new StrongBox(schemeId)); } public bool TryGetClrType(long schemeId, [NotNullWhen(true)] out Type? type) { if (SchemeIdToClrType.TryGetValue(schemeId, out var weak)) { if (weak.TryGetTarget(out type)) return true; SchemeIdToClrType.TryRemove(new KeyValuePair>(schemeId, weak)); } type = null; return false; } public bool ClrTypeRegistryInitialized = false; // per-domain warm-up done (optimization only; resolution is lazy) // Statistics public long SchemeHits; public long SchemeMisses; public long TypeHits; public long TypeMisses; /// /// Clear scheme cache only (does NOT clear CLR Type Registry). /// Use this when disabling cache - system will work slower but correctly. /// public void Clear() { // Clear only scheme/type cache, NOT CLR Type Registry SchemeByName.Clear(); SchemeById.Clear(); StructureTrees.Clear(); Subtrees.Clear(); TypeCache.Clear(); TypeById.Clear(); // DO NOT clear CLR Type Registry - it's required for polymorphic deserialization // SchemeIdToClrType, ClrTypeToSchemeId stay intact (name↔Type lives in ClrSchemeTypeIndex) Interlocked.Exchange(ref SchemeHits, 0); Interlocked.Exchange(ref SchemeMisses, 0); Interlocked.Exchange(ref TypeHits, 0); Interlocked.Exchange(ref TypeMisses, 0); } /// /// Clear everything including CLR Type Registry (full reset). /// Use only for complete reinitialization or testing. /// public void ClearAll() { SchemeByName.Clear(); SchemeById.Clear(); StructureTrees.Clear(); Subtrees.Clear(); TypeCache.Clear(); TypeById.Clear(); SchemeIdToClrType.Clear(); ClrTypeToSchemeId.Clear(); ClrTypeRegistryInitialized = false; Interlocked.Exchange(ref SchemeHits, 0); Interlocked.Exchange(ref SchemeMisses, 0); Interlocked.Exchange(ref TypeHits, 0); Interlocked.Exchange(ref TypeMisses, 0); } public void ResetStatistics() { Interlocked.Exchange(ref SchemeHits, 0); Interlocked.Exchange(ref SchemeMisses, 0); Interlocked.Exchange(ref TypeHits, 0); Interlocked.Exchange(ref TypeMisses, 0); } } /// /// Metadata cache with domain isolation. /// Combines scheme caching and CLR type registry (former AutomaticTypeRegistry). /// Instance is bound to specific domain, static data is shared. /// Each domain (typically one per database connection) has isolated cache. /// public class GlobalMetadataCache { // ===== STATIC: shared data across all instances ===== private static readonly ConcurrentDictionary _domains = new(); private static readonly object _lock = new(); // ===== INSTANCE: domain binding ===== private readonly string _domain; /// /// Cache domain this instance is bound to. /// public string Domain => _domain; /// /// Creates cache instance bound to specific domain. /// public GlobalMetadataCache(string? domain = null) { _domain = domain ?? "default"; } /// /// Creates cache instance with domain from configuration. /// public GlobalMetadataCache(RedbServiceConfiguration configuration) { _domain = configuration?.GetEffectiveCacheDomain() ?? "default"; } private DomainCache GetCache() => _domains.GetOrAdd(_domain, _ => new DomainCache()); // ===== SCHEME CACHING ===== /// /// Get scheme by name from cache. /// public IRedbScheme? GetScheme(string schemeName) { if (!GetCache().Enabled) return null; var cache = GetCache(); if (cache.SchemeByName.TryGetValue(schemeName, out var scheme)) { Interlocked.Increment(ref cache.SchemeHits); return scheme; } Interlocked.Increment(ref cache.SchemeMisses); return null; } /// /// Get scheme by ID from cache. /// public IRedbScheme? GetScheme(long schemeId) { if (!GetCache().Enabled) return null; var cache = GetCache(); if (cache.SchemeById.TryGetValue(schemeId, out var scheme)) { Interlocked.Increment(ref cache.SchemeHits); return scheme; } Interlocked.Increment(ref cache.SchemeMisses); return null; } /// /// Cache scheme. /// public void CacheScheme(IRedbScheme scheme) { if (!GetCache().Enabled || scheme == null) return; var cache = GetCache(); // A scheme put over another version of itself (or over none) takes the place of the one its cached trees were // built from: they go. The same version cached again keeps them. if (!cache.SchemeById.TryGetValue(scheme.Id, out var previous) || previous.StructureHash != scheme.StructureHash) cache.ForgetTrees(scheme.Id); cache.SchemeByName[scheme.Name] = scheme; cache.SchemeById[scheme.Id] = scheme; } /// /// Invalidate scheme by ID, with its structure trees. /// public void InvalidateScheme(long schemeId) { var cache = GetCache(); // The trees go even when the scheme itself is no longer cached: a tree kept past its scheme is the stale // tree a save would build rows from after reading the scheme again. cache.ForgetTrees(schemeId); if (cache.SchemeById.TryGetValue(schemeId, out var scheme)) { cache.SchemeByName.TryRemove(scheme.Name, out _); cache.SchemeById.TryRemove(schemeId, out _); // Drop the per-domain scheme_id→Type projection (it can be lazily re-derived). The global // name↔Type (ClrSchemeTypeIndex) is a code fact and is NOT touched by per-domain invalidation. cache.SchemeIdToClrType.TryRemove(schemeId, out _); } } /// /// Invalidate scheme by name, with its structure trees. /// public void InvalidateScheme(string schemeName) { var cache = GetCache(); if (cache.SchemeByName.TryGetValue(schemeName, out var scheme)) { cache.ForgetTrees(scheme.Id); cache.SchemeByName.TryRemove(schemeName, out _); cache.SchemeById.TryRemove(scheme.Id, out _); // Drop the per-domain scheme_id→Type projection (lazily re-derivable). Global name↔Type // (ClrSchemeTypeIndex) is a code fact and is NOT touched by per-domain invalidation. cache.SchemeIdToClrType.TryRemove(scheme.Id, out _); } } // ===== STRUCTURE TREES ===== /// Cached structure tree of a scheme; null when absent or the cache is disabled. internal List? GetStructureTree(long schemeId) { var cache = GetCache(); return cache.Enabled && cache.StructureTrees.TryGetValue(schemeId, out var tree) ? tree : null; } internal void CacheStructureTree(long schemeId, List tree) { var cache = GetCache(); if (cache.Enabled) cache.StructureTrees.TryAdd(schemeId, tree); } /// Cached children of a parent structure (null parent = the root nodes); null when absent. internal List? GetSubtree(long schemeId, long? parentStructureId) { var cache = GetCache(); return cache.Enabled && cache.Subtrees.TryGetValue((schemeId, parentStructureId), out var subtree) ? subtree : null; } internal void CacheSubtree(long schemeId, long? parentStructureId, List subtree) { var cache = GetCache(); if (cache.Enabled) cache.Subtrees.TryAdd((schemeId, parentStructureId), subtree); } /// Drops the structure trees of a scheme and keeps the scheme. internal void InvalidateStructureTrees(long schemeId) => GetCache().ForgetTrees(schemeId); internal (int Trees, int Subtrees) StructureTreeCounts() { var cache = GetCache(); return (cache.StructureTrees.Count, cache.Subtrees.Count); } // ===== DB TYPE CACHING ===== /// /// Get type ID from cache. /// public long? GetTypeId(string typeName) { if (!GetCache().Enabled) return null; var cache = GetCache(); if (cache.TypeCache.TryGetValue(typeName, out var typeId)) { Interlocked.Increment(ref cache.TypeHits); return typeId; } Interlocked.Increment(ref cache.TypeMisses); return null; } /// /// Cache type ID. /// public void CacheType(string typeName, long typeId) { if (!GetCache().Enabled) return; GetCache().TypeCache[typeName] = typeId; } /// /// Get type info by ID. /// public RedbTypeInfo? GetTypeById(long typeId) { if (!GetCache().Enabled) return null; var cache = GetCache(); if (cache.TypeById.TryGetValue(typeId, out var typeInfo)) { Interlocked.Increment(ref cache.TypeHits); return typeInfo; } Interlocked.Increment(ref cache.TypeMisses); return null; } /// /// Bulk cache types by ID. /// public void CacheTypesById(IEnumerable types) { if (!GetCache().Enabled) return; var cache = GetCache(); foreach (var t in types) { cache.TypeById[t.Id] = t; } } /// /// Check if types by ID cache has data. /// public bool HasTypesByIdCache => !GetCache().TypeById.IsEmpty; /// /// The _types table of this domain by id, once has stored it (every caller /// stores the whole table), or null when nothing is cached or the cache is off. Cleared with the rest of the /// domain cache (). /// public IReadOnlyDictionary? GetTypesById() { var cache = GetCache(); if (!cache.Enabled || cache.TypeById.IsEmpty) return null; return cache.TypeById; } // ===== CLR TYPE REGISTRY (former AutomaticTypeRegistry) ===== /// /// Check if CLR type registry is initialized for this domain. /// public bool IsClrTypeRegistryInitialized => GetCache().ClrTypeRegistryInitialized; /// /// Best-effort warm-up of CLR type resolution for this domain: /// (1) refreshes the process-global schemeName↔Type index (), and /// (2) pre-populates this domain's scheme_id→Type projection for schemes already present in the DB. /// This is an OPTIMIZATION only — it is never a precondition for resolution, which is lazy and /// self-healing (see / ). The /// per-domain warm pass runs once; the global index stays self-healing regardless. /// /// Provider for scheme metadata /// Optional logger for diagnostics public async Task InitializeClrTypeRegistryAsync(ISchemeSyncProvider schemeProvider, ILogger? logger = null) { // Global, database-independent name↔Type layer — cheap no-op when no new assemblies loaded. ClrSchemeTypeIndex.EnsureFresh(); var cache = GetCache(); lock (_lock) { if (cache.ClrTypeRegistryInitialized) return; } // Pre-pop the per-domain scheme_id→Type for types whose scheme already exists in THIS domain's DB. foreach (var type in ClrSchemeTypeIndex.EnumerateSchemeTypes()) { try { var attr = type.GetCustomAttribute(); if (attr == null) continue; var schemeName = attr.GetSchemeName(type); ClrSchemeTypeIndex.Register(schemeName, type); if (!string.IsNullOrEmpty(attr.Alias)) ClrSchemeTypeIndex.Register(attr.Alias!, type); var scheme = await schemeProvider.GetSchemeByNameAsync(schemeName); if (scheme != null) cache.MapClrType(scheme.Id, type); } catch (Exception ex) { logger?.LogDebug(ex, "Skipping type {Type} during CLR registry warm-up", type.FullName); } } lock (_lock) { cache.ClrTypeRegistryInitialized = true; } logger?.LogInformation( "CLR type registry warmed for domain '{Domain}': {NameCount} global names, {SchemeIdCount} scheme_id mappings", _domain, ClrSchemeTypeIndex.Count, cache.SchemeIdToClrType.Count); } /// /// Get C# type by scheme ID (this domain). Fast path is the per-domain cache; on a miss it lazily /// self-heals by deriving the type from this domain's cached scheme name + the global /// , then backfills. Returns null if the scheme is not cached in this /// domain or genuinely has no CLR type. For the cold case (scheme not cached here) use /// , which can load the scheme by id. /// public Type? GetClrType(long schemeId) { var cache = GetCache(); if (cache.TryGetClrType(schemeId, out var type)) return type; // Lazy derive: scheme_id → (this domain's cached scheme name) → (global name↔Type). if (cache.SchemeById.TryGetValue(schemeId, out var scheme)) { var t = ClrSchemeTypeIndex.Resolve(scheme.Name); if (t != null) { cache.MapClrType(schemeId, t); return t; } } return null; } /// /// Get C# type by scheme name — served from the process-global /// (database-independent, self-healing on assembly load). /// public Type? GetClrType(string schemeName) => ClrSchemeTypeIndex.Resolve(schemeName); /// /// Resolve scheme_id → Type with a cold fallback. Tries the sync path first (per-domain cache + /// cached scheme); if the scheme is not cached in this domain, loads it by id and resolves via the /// global index, caching both for next time. Covers the cross-domain case (scheme synced under a /// different connection-hash domain, or created by another cluster node) with no per-call-site logic. /// Returns null only when the scheme genuinely has no CLR type (a legitimately non-generic scheme). /// public async Task ResolveClrTypeAsync(long schemeId, ISchemeSyncProvider schemeProvider) { var type = GetClrType(schemeId); if (type != null || IsSchemeKnown(schemeId)) return type; return RememberClrType(schemeId, await schemeProvider.GetSchemeByIdAsync(schemeId)); } /// /// Synchronous for the thread-pool-free load path: the cold lookup loads the /// scheme through on the calling thread. /// public Type? ResolveClrType(long schemeId, ISchemeSyncProvider schemeProvider) { var type = GetClrType(schemeId); if (type != null || IsSchemeKnown(schemeId)) return type; return RememberClrType(schemeId, schemeProvider.GetSchemeById(schemeId)); } // A scheme this domain holds and the type index does not answer to is a scheme with no CLR type: the index is // asked again on every lookup and heals itself when an assembly loads, so the provider is not asked again. // Asking it loaded the scheme on every read of a list item's object of such a scheme. private bool IsSchemeKnown(long schemeId) => GetCache().SchemeById.ContainsKey(schemeId); // The cold half of both forms: cache the loaded scheme in this domain and map its CLR type. private Type? RememberClrType(long schemeId, IRedbScheme? scheme) { if (scheme == null) return null; CacheScheme(scheme); // populate this domain's scheme cache so future sync lookups hit var type = ClrSchemeTypeIndex.Resolve(scheme.Name); if (type != null) GetCache().MapClrType(schemeId, type); return type; } /// /// Register CLR type mapping authoritatively: the database-independent name↔Type goes to the global /// , the per-database scheme_id↔Type goes to this domain. /// public void RegisterClrType(string schemeName, long schemeId, Type type) { ClrSchemeTypeIndex.Register(schemeName, type); // global (shared across domains/connections) GetCache().MapClrType(schemeId, type); // per-domain (scheme_id is per-database) } /// /// Get scheme_id by C# type. /// public long? GetSchemeIdByClrType(Type type) { return GetCache().ClrTypeToSchemeId.TryGetValue(type, out var schemeId) ? schemeId.Value : null; } /// /// Get CLR type registry statistics. /// public (int SchemeNames, int SchemeIds) GetClrTypeStatistics() { return (ClrSchemeTypeIndex.Count, GetCache().SchemeIdToClrType.Count); } // ===== STATISTICS & DIAGNOSTICS ===== /// /// Get cache statistics for this domain. /// public CacheStatistics GetStatistics() { var cache = GetCache(); return new CacheStatistics { SchemeHits = (int)cache.SchemeHits, SchemeMisses = (int)cache.SchemeMisses, TypeHits = (int)cache.TypeHits, TypeMisses = (int)cache.TypeMisses, StructureHits = 0, StructureMisses = 0 }; } /// /// Clear cache for this domain. /// public void Clear() { lock (_lock) { GetCache().Clear(); } } /// /// Clears this domain's schemes, types and scheme id to CLR type mappings: everything a scheme sync inside a /// transaction that rolled back may have cached from rows that no longer exist. Resolution refills it lazily. /// public void ClearDomainIncludingClrTypes() { lock (_lock) { GetCache().ClearAll(); } } /// /// Get diagnostic information. /// public string GetDiagnosticInfo() { var cache = GetCache(); var stats = GetStatistics(); return $"Domain: {_domain}, " + $"Schemes: {cache.SchemeByName.Count}, " + $"DbTypes: {cache.TypeCache.Count}, " + $"ClrTypes: {cache.SchemeIdToClrType.Count}, " + $"Hit Rate: {stats.OverallHitRatio:P1}, " + $"Total Domains: {_domains.Count}"; } // ===== STATIC METHODS: global operations ===== // ===== INSTANCE METHODS FOR CACHE CONTROL ===== /// /// Is caching enabled for this domain. /// public bool IsEnabled => GetCache().Enabled; /// /// Enable/disable caching for this domain. /// public void SetEnabled(bool enabled) { var cache = GetCache(); cache.Enabled = enabled; if (!enabled) cache.Clear(); } /// /// Initialize cache settings from configuration. /// public void Initialize(RedbServiceConfiguration configuration) { var cache = GetCache(); cache.Enabled = configuration.EnableMetadataCache; if (!cache.Enabled) cache.Clear(); } /// /// Reset statistics for this domain. /// public void ResetStatistics() { GetCache().ResetStatistics(); } // ===== STATIC UTILITY METHODS ===== /// /// Clear all domain caches. /// public static void ClearAll() { lock (_lock) { foreach (var cache in _domains.Values) { cache.Clear(); } _domains.Clear(); } } /// /// Clear cache for specific domain. /// public static void ClearDomain(string domain) { lock (_lock) { if (_domains.TryGetValue(domain, out var cache)) { cache.Clear(); } } } /// /// Get list of all registered domains. /// public static IReadOnlyCollection GetAllDomains() { return _domains.Keys.ToList(); } /// /// Reset statistics for all domains (static utility). /// public static void ResetAllStatistics() { lock (_lock) { foreach (var cache in _domains.Values) { Interlocked.Exchange(ref cache.SchemeHits, 0); Interlocked.Exchange(ref cache.SchemeMisses, 0); Interlocked.Exchange(ref cache.TypeHits, 0); Interlocked.Exchange(ref cache.TypeMisses, 0); } } } }