Bundle: redb / redb.Core (redb.Core.txt), 233 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
Index: https://redbase.app/src/dev-2026-12-06/redb/_index.txt
====
Path: redb/redb.Core/Attributes/RedbAliasAttribute.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/Attributes/RedbAliasAttribute.cs
----
using System;
namespace redb.Core.Attributes
{
///
/// Attribute for specifying a human-readable alias
/// Applied to enum values (ListItem.Alias) and Props properties (Structure.Alias)
///
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public class RedbAliasAttribute : Attribute
{
public string Alias { get; }
public RedbAliasAttribute(string alias)
{
Alias = alias ?? throw new ArgumentNullException(nameof(alias));
}
}
}
Path: redb/redb.Core/Attributes/RedbIgnoreAttribute.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/Attributes/RedbIgnoreAttribute.cs
----
using System;
namespace redb.Core.Attributes
{
///
/// Excludes a property from the REDB schema (but not from JSON serialization)
///
[AttributeUsage(AttributeTargets.Property)]
public class RedbIgnoreAttribute : Attribute
{
}
}
Path: redb/redb.Core/Attributes/RedbRenameAttribute.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/Attributes/RedbRenameAttribute.cs
----
using System;
namespace redb.Core.Attributes
{
///
/// Declares a previous name of a Props property, so that the scheme sync renames the stored property instead of
/// adding a new one and deleting the old one with its values.
///
/// On the sync, a property whose name is not in the database but whose previous name is gets the stored structure
/// renamed in place: the structure id stays, and with it every stored value. The next sync finds the property under
/// its name and does nothing. When both the name and a previous name are in the database, the sync stops with
/// and changes nothing: choosing one of them would lose the
/// values of the other.
///
///
/// The attribute is repeated for a chain of renames (A to B to C: two attributes on
/// C), so that a database that missed a version is renamed too. The previous names are kept in the
/// database (_structures._renamed_from): a node that still runs a class with the previous name stops at
/// its sync with instead of adding the property again and
/// deleting the renamed one.
///
///
/// The attribute stays on the property for good, in the order of the chain, the first name first: the first name
/// orders the property in the object hash, so the hashes stored before the rename stay valid after it. The sync
/// checks the first attribute against the history the database keeps and stops with
/// when they disagree or the attributes are gone. A database
/// created directly with the renamed class has no history yet, so there the check cannot fire.
///
///
/// A freed previous name may be taken by a new property of the same class once the rename is applied. While the
/// database still stores the previous name and not the current one, the sync stops with an error: the stored
/// structure could belong to either property.
///
///
/// Two properties whose last attributes (the attribute declared last) name each other's current name swap the
/// names in one step, which the sync refuses from the class alone: swap through a temporary name, one deployment
/// per rename.
///
///
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public sealed class RedbRenameAttribute : Attribute
{
/// The previous name of the property.
public string OldName { get; }
/// The previous name of the property.
public RedbRenameAttribute(string oldName)
{
if (string.IsNullOrWhiteSpace(oldName))
throw new ArgumentException("The previous name of a property cannot be empty", nameof(oldName));
OldName = oldName;
}
}
}
Path: redb/redb.Core/Attributes/RedbSchemeAttribute.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/Attributes/RedbSchemeAttribute.cs
----
using System;
namespace redb.Core.Attributes
{
///
/// Attribute for configuring the REDB schema for a properties class.
///
/// By default the schema is named after the CLR type's . Set
/// to pin an explicit name instead, decoupling the database identity of the
/// schema from C# namespace/class refactoring.
///
///
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class RedbSchemeAttribute : Attribute
{
///
/// Explicit schema name in the database. When null or empty, the schema is named after the
/// CLR type's — the legacy default.
///
/// Setting this on an existing project renames the schema in the database on the next
/// sync: the scheme row is looked up by the explicit name, then by FullName, then by the short
/// type name, and the first match is renamed in place (the scheme id, and therefore all objects
/// and structures, are untouched). Because an older binary would not find the scheme under its
/// new name and would create a second one, every consumer of the database must be updated
/// together.
///
///
/// Must follow C# identifier rules — Latin letters, digits, _, . and +,
/// no reserved words, 128 characters max. Validated before any SQL is issued; use
/// for human-readable titles.
///
///
/// Multi-node note. The name (and alias) live in this attribute — in code — so changing
/// them means a redeploy, which restarts every node and rebuilds each process's static scheme
/// caches fresh. Cross-node consistency is achieved by that restart; there is no online rename
/// on live nodes without restart, and it is not supported.
///
///
public string? Name { get; set; }
///
/// Schema alias (human-readable name). Never used as the schema name — it is free-form and may
/// contain spaces, punctuation and non-Latin letters. Synchronised from this attribute on every
/// sync: changing it updates the database, removing it sets the alias back to null.
///
public string? Alias { get; set; }
///
/// Previous names of the schema, oldest first, so that the sync renames the stored schema instead of creating a
/// new one and leaving every object under the old one.
///
/// The sync looks the schema up by its name first; when it is not there, by these names, and renames the first
/// one found in place (the schema id, and with it every object and structure, stays). Use it when an explicit
/// changes (RenamedFrom = ["orders"]), or when a class without an explicit name is
/// renamed or moved to another namespace (its previous FullName). When the schema name and a previous one are
/// both stored, the sync stops with .
///
///
/// The previous names are kept in the database (_schemes._renamed_from): a node that still runs a class
/// with a previous name stops at its sync with instead of
/// creating the old schema again.
///
///
public string[]? RenamedFrom { get; set; }
///
/// The version of this Props class, raised by the programmer with a change that takes data away: a property
/// removed, or a property's type changed (and with a change inside a nested class of the scheme, which belongs
/// to it). A class without the attribute, or without this value, has version 0.
///
/// The sync records the version in the database (_schemes._version) and deletes a structure or
/// changes its type only for a class whose version is higher than the recorded one. A class of the same
/// version adds what it lacks and leaves the rest as it is, with a warning; a class of a lower version (an
/// older build of the application next to a newer one) changes nothing. So a node that still runs an older
/// build cannot take the fields or the types of a newer build away. The version recorded never goes down.
///
///
/// Adding a property needs no new version.
/// (on in the Development profile) lets a class of the same version delete and change too, for a local
/// database during development.
///
///
public int Version { get; set; }
///
/// Parameterless constructor
///
public RedbSchemeAttribute()
{
}
///
/// Constructor with alias. The positional argument is always the alias, never the schema
/// name — an explicit name can only be set through the named parameter, so
/// existing declarations cannot change meaning by accident.
///
/// Schema alias
public RedbSchemeAttribute(string alias)
{
Alias = alias ?? throw new ArgumentNullException(nameof(alias));
}
///
/// Get the schema name for the type: the explicit when set, otherwise the
/// full class name (namespace.class).
///
/// Class type
/// Schema name
///
/// Deliberately does no validation — this sits on hot paths (assembly rescan, cache warm-up,
/// every sync). Explicit names are validated by
/// at the points that write to the database.
///
public string GetSchemeName(Type type)
{
return !string.IsNullOrWhiteSpace(Name)
? Name!
: type.FullName ?? type.Name;
}
}
}
Path: redb/redb.Core/Attributes/RedbTagsAttribute.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/Attributes/RedbTagsAttribute.cs
----
using System;
namespace redb.Core.Attributes
{
///
/// Writes the free-form _tags marker of a scheme (on the Props class) or of a
/// structure (on a property) at synchronisation. The column is a reserved slot for future
/// and custom extensions: 450 characters, indexed on _structures, no semantics
/// imposed by redb. WITHOUT the attribute synchronisation leaves the column untouched, so
/// values written directly by applications and extensions survive every sync.
///
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class RedbTagsAttribute : Attribute
{
/// The marker text, up to 450 characters (enforced in C# for provider parity).
public string Tags { get; }
public RedbTagsAttribute(string tags) => Tags = tags;
}
}
Path: redb/redb.Core/Attributes/RedbUniqueAttribute.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/Attributes/RedbUniqueAttribute.cs
----
using System;
namespace redb.Core.Attributes
{
///
/// Declares a Props property a unique key within its scheme: no two objects of the scheme may
/// hold the same value in it. Enforced by the database — a unique index over
/// _values (_id_structure, _unique), where _unique is the 128-bit hash of the
/// value's canonical form () — and surfaced as
/// .
///
///
/// Allowed on: a scalar property — string, integers, Guid, bool,
/// double/float, decimal, DateTime/DateTimeOffset/
/// DateOnly, byte[] and their nullable forms — of the Props class or of a nested
/// class reached without crossing a collection (S2); and on a whole nested class, array or
/// dictionary property, where the key is the SUBTREE content (S1). Not on enums (stored as their
/// name in text, not a key type), single RedbObject references, or
/// members of collection ELEMENTS — element rows share one structure across every element of
/// every object. Scheme synchronisation rejects a misplaced attribute with
/// .
///
///
///
/// null never participates: any number of objects may leave the key empty.
///
///
///
/// The value is compared exactly, after Unicode NFC normalisation for strings: no trimming, no
/// case folding. A key is a notion of the application; an application that wants
/// case-insensitive or trimmed keys normalises them before saving — the same contract as a unique
/// index in any database, and what EF Core and Hibernate do.
///
///
///
/// Putting the attribute on a property of a scheme that already has data recomputes the column
/// for every existing object at the next synchronisation and reports duplicates
/// () instead of failing start-up: duplicate rows stay
/// outside the index until they are resolved.
///
///
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class RedbUniqueAttribute : Attribute
{
///
/// On a COLLECTION property switches from the subtree-content key (the default) to
/// ELEMENT keys: - no duplicate elements inside one
/// collection; - element values unique across the whole
/// scheme. Meaningless (and rejected at synchronisation) on scalars and nested classes,
/// whose bare attribute already carries the strongest reading.
///
public UniqueScope Scope { get; set; } = UniqueScope.Default;
}
}
Path: redb/redb.Core/Attributes/SchemeNameValidator.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/Attributes/SchemeNameValidator.cs
----
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using redb.Core.Exceptions;
namespace redb.Core.Attributes
{
///
/// Single source of truth for explicit scheme name rules.
///
/// The rules mirror the database-level triggers one-for-one (PostgreSQL
/// validate_scheme_name, and the MSSql/SQLite equivalents). Validation lives here
/// because it must behave identically on every provider and must fail before any SQL is
/// issued — a raw 23505/2627 surfacing from the driver tells the developer nothing about
/// which type is at fault.
///
///
/// Only explicit names () are validated. Names
/// derived from are valid by construction, and checking them
/// would break existing projects that never asked for this feature.
///
///
public static class SchemeNameValidator
{
/// Names starting with this prefix are reserved for internal schemes and skip validation.
public const string SystemPrefix = "@@";
/// Maximum length accepted by the database triggers.
public const int MaxLength = 128;
private static readonly Regex AllowedShape =
new(@"^[a-zA-Z_][a-zA-Z0-9_.+]*$", RegexOptions.Compiled | RegexOptions.CultureInvariant);
private static readonly Regex ValidPart =
new(@"^[a-zA-Z_][a-zA-Z0-9_]*$", RegexOptions.Compiled | RegexOptions.CultureInvariant);
// Same list as the database triggers. Kept verbatim so the three providers and this
// validator can never disagree about what a reserved word is.
private static readonly HashSet ReservedWords = new(StringComparer.Ordinal)
{
"abstract", "as", "bool", "break", "byte", "case", "catch", "char", "checked",
"class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else",
"enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for",
"foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock",
"long", "namespace", "new", "null", "object", "operator", "out", "override", "params",
"private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed",
"short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this",
"throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort",
"using", "virtual", "void", "volatile", "while"
};
///
/// Validates an explicit scheme name and throws when it
/// breaks a rule. The declaring type is carried into the message so the developer knows
/// exactly which class to fix.
///
public static void Validate(string? name, Type declaringType)
{
if (!IsValid(name, out var error))
throw new RedbSchemeNameException(declaringType, name, error!);
}
///
/// Non-throwing form. Returns false and fills with a
/// human-readable reason.
///
public static bool IsValid(string? name, out string? error)
{
error = null;
// Rule 5: not empty / not whitespace-only.
if (string.IsNullOrWhiteSpace(name))
{
error = "the name is empty";
return false;
}
// Rule 0: system schemes bypass every other rule.
if (name!.StartsWith(SystemPrefix, StringComparison.Ordinal))
return true;
// Rule 6: length.
if (name.Length > MaxLength)
{
error = $"the name is longer than {MaxLength} characters (got {name.Length})";
return false;
}
// Rule 1: must not start with a digit. Checked before the shape rule so the message is specific.
if (name[0] >= '0' && name[0] <= '9')
{
error = "the name starts with a digit; it must start with a letter or underscore";
return false;
}
// Rule 2: allowed character set.
if (!AllowedShape.IsMatch(name))
{
error = "the name contains characters outside [a-zA-Z0-9_.+]; " +
"spaces, punctuation and non-Latin letters are not allowed";
return false;
}
// Rule 3: must not end with a dot.
if (name.EndsWith(".", StringComparison.Ordinal))
{
error = "the name ends with a dot";
return false;
}
// Rule 4: no two consecutive dots.
if (name.Contains(".."))
{
error = "the name contains two consecutive dots";
return false;
}
// Rules 7 and 8: every part between dots/pluses must be a valid identifier and
// must not be a C# reserved word.
foreach (var part in name.Split('.', '+'))
{
if (!ValidPart.IsMatch(part))
{
error = $"namespace part '{part}' is not a valid identifier";
return false;
}
if (ReservedWords.Contains(part.ToLowerInvariant()))
{
error = $"namespace part '{part}' is a C# reserved word";
return false;
}
}
return true;
}
}
}
Path: redb/redb.Core/Attributes/UniqueScope.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/Attributes/UniqueScope.cs
----
namespace redb.Core.Attributes;
///
/// Scope of a key on a COLLECTION property (S3 of the
/// subtree-unique plan). On scalars and nested classes the scope is not configurable - the
/// bare attribute already means the strongest sensible reading (value unique per scheme,
/// subtree content unique per scheme).
///
public enum UniqueScope
{
///
/// The default reading of the bare attribute: for a scalar - the value canon; for a class,
/// array or dictionary - the SUBTREE content key (no two objects hold this exact content).
///
Default = 0,
///
/// Element scope, scheme-wide: every ELEMENT value of the collection is unique across all
/// objects of the scheme ("this email appears in one object only, whichever array it sits
/// in"). References canonicalise by target id: "this object is attached at most once in
/// the whole scheme".
///
Scheme = 1,
///
/// Element scope, per collection: no duplicate element values INSIDE one object's
/// collection; different objects may repeat each other freely. The classic "unique set" -
/// for references: "no duplicate links in this collection".
///
Collection = 2,
}
Path: redb/redb.Core/Caching/CacheDelegates.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/CacheDelegates.cs
----
using System;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using redb.Core.Models.Contracts;
using redb.Core.Utils;
namespace redb.Core.Caching
{
///
/// Typed cache calls for an object type met at run time. A batch load and a graph write used to run
/// GetMethod + MakeGenericMethod + Invoke on every object; here the call is built once per type
/// and kept in a : a type unloaded with its collectible load context
/// takes its delegate with it, so Tsak hot reload releases the assembly.
///
internal static class CacheDelegates
{
private static readonly ConditionalWeakTable> _set = new();
private static readonly ConditionalWeakTable> _setGraph = new();
private static readonly ConditionalWeakTable> _get = new();
/// Write the object by its own id (the Set of the cache interface). A non-generic RedbObject carries
/// no Props and was never an entry of its own.
public static void Set(IRedbObjectCache cache, IRedbObject obj)
{
if (RedbObjectTypes.GenericOf(obj.GetType()) == null) return;
_set.GetValue(obj.GetType(), CreateSet)(cache, obj);
}
/// Write the object and every loaded object under it in one walk.
public static void SetGraph(GlobalPropsCache cache, IRedbObject obj)
{
if (RedbObjectTypes.GenericOf(obj.GetType()) == null) return;
_setGraph.GetValue(obj.GetType(), CreateSetGraph)(cache, obj);
}
/// Read the object by id and hash; null when the cache has no current entry.
public static IRedbObject? Get(GlobalPropsCache cache, Type propsType, long objectId, Guid hash)
=> _get.GetValue(propsType, CreateGet)(cache, objectId, hash);
private static Action CreateSet(Type objectType)
{
var redbType = RedbObjectTypes.GenericOf(objectType)!;
var set = typeof(IRedbObjectCache).GetMethod(nameof(IRedbObjectCache.Set))!
.MakeGenericMethod(redbType.GetGenericArguments()[0]);
var cache = Expression.Parameter(typeof(IRedbObjectCache), "cache");
var obj = Expression.Parameter(typeof(IRedbObject), "obj");
var call = Expression.Call(cache, set, Expression.Convert(obj, redbType));
return Expression.Lambda>(call, cache, obj).Compile();
}
private static Action CreateSetGraph(Type objectType)
{
var redbType = RedbObjectTypes.GenericOf(objectType)!;
var setGraph = typeof(GlobalPropsCache).GetMethod(nameof(GlobalPropsCache.SetGraph))!
.MakeGenericMethod(redbType.GetGenericArguments()[0]);
var cache = Expression.Parameter(typeof(GlobalPropsCache), "cache");
var obj = Expression.Parameter(typeof(IRedbObject), "obj");
var call = Expression.Call(cache, setGraph, Expression.Convert(obj, redbType));
return Expression.Lambda>(call, cache, obj).Compile();
}
private static Func CreateGet(Type propsType)
{
var get = typeof(GlobalPropsCache).GetMethod(nameof(GlobalPropsCache.Get))!
.MakeGenericMethod(propsType);
var cache = Expression.Parameter(typeof(GlobalPropsCache), "cache");
var objectId = Expression.Parameter(typeof(long), "objectId");
var hash = Expression.Parameter(typeof(Guid), "hash");
var call = Expression.Call(cache, get, objectId, hash);
var body = Expression.Convert(call, typeof(IRedbObject));
return Expression.Lambda>(body, cache, objectId, hash)
.Compile();
}
}
}
Path: redb/redb.Core/Caching/CacheDiagnosticInfo.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/CacheDiagnosticInfo.cs
----
using System.Collections.Generic;
namespace redb.Core.Caching
{
///
/// Cache diagnostic information, returned by
/// .
///
///
/// These four types used to live in ICompositeMetadataCache.cs, alongside a layer of cache
/// interfaces that was never implemented and never consumed. That layer was removed; these
/// carried on being part of a live public contract, so they moved here unchanged.
///
public class CacheDiagnosticInfo
{
///
/// Cache health status.
///
public CacheHealthStatus HealthStatus { get; set; }
///
/// Potential issues.
///
public List Issues { get; set; } = new();
///
/// Optimization recommendations.
///
public List Recommendations { get; set; } = new();
///
/// Memory information.
///
public MemoryUsageInfo MemoryInfo { get; set; } = new();
///
/// Performance information.
///
public PerformanceInfo PerformanceInfo { get; set; } = new();
}
///
/// Cache health status enumeration.
///
public enum CacheHealthStatus
{
/// Cache is healthy.
Healthy,
/// Cache has warnings.
Warning,
/// Cache is in critical state.
Critical,
/// Cache status is unknown.
Unknown
}
///
/// Cache memory usage information.
///
public class MemoryUsageInfo
{
///
/// Used memory in bytes.
///
public long UsedBytes { get; set; }
///
/// Maximum memory in bytes (if limited).
///
public long? MaxBytes { get; set; }
///
/// Memory usage percentage.
///
public double UsagePercentage { get; set; }
///
/// Memory fragmentation percentage (if available).
///
public double? FragmentationPercentage { get; set; }
}
///
/// Cache performance information.
///
public class PerformanceInfo
{
///
/// Average cache access time in milliseconds.
///
public double AverageAccessTimeMs { get; set; }
///
/// Average data source load time in milliseconds.
///
public double AverageLoadTimeMs { get; set; }
///
/// Operations per second.
///
public double OperationsPerSecond { get; set; }
///
/// Peak access time in milliseconds.
///
public double PeakAccessTimeMs { get; set; }
}
}
Path: redb/redb.Core/Caching/CachePublication.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/CachePublication.cs
----
using System;
using redb.Core.Data;
namespace redb.Core.Caching
{
///
/// The caches publish committed state only (review after 4.0.0). A cache Set marks the graph shared, and a shared
/// instance does not keep what one transaction saw (owner decision 2026-09-15) - so a Set inside a transaction made
/// the writer's own loaded object forget its lazy references: an edit of root.Props.Next.Props followed by a
/// save of root.Props.Next saved a fresh reload, and every read of a list item's object was a query. A Set
/// inside a transaction now waits for its commit; until then the instance is the reader's own, and what a
/// rolled-back transaction loaded never reaches the cache.
///
public static class CachePublication
{
///
/// Runs now, or once the transaction takes part in has
/// committed - the explicit redb transaction of the context, else the ambient .
///
public static void AfterCommit(IRedbContext context, Action publish)
{
ArgumentNullException.ThrowIfNull(context);
ArgumentNullException.ThrowIfNull(publish);
if (!TransactionHooks.OnCompleted(context, committed => { if (committed) publish(); }))
publish();
}
}
}
Path: redb/redb.Core/Caching/CacheStatistics.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/CacheStatistics.cs
----
namespace redb.Core.Caching;
///
/// Cache statistics.
///
public class CacheStatistics
{
public int SchemeHits { get; set; }
public int SchemeMisses { get; set; }
public int StructureHits { get; set; }
public int StructureMisses { get; set; }
public int TypeHits { get; set; }
public int TypeMisses { get; set; }
public double SchemeHitRatio => SchemeHits + SchemeMisses > 0 ? (double)SchemeHits / (SchemeHits + SchemeMisses) : 0;
public double StructureHitRatio => StructureHits + StructureMisses > 0 ? (double)StructureHits / (StructureHits + StructureMisses) : 0;
public double TypeHitRatio => TypeHits + TypeMisses > 0 ? (double)TypeHits / (TypeHits + TypeMisses) : 0;
public double OverallHitRatio
{
get
{
var totalHits = SchemeHits + StructureHits + TypeHits;
var totalRequests = SchemeHits + SchemeMisses + StructureHits + StructureMisses + TypeHits + TypeMisses;
return totalRequests > 0 ? (double)totalHits / totalRequests : 0;
}
}
}
Path: redb/redb.Core/Caching/ClrSchemeTypeIndex.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/ClrSchemeTypeIndex.cs
----
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using redb.Core.Attributes;
using redb.Core.Exceptions;
namespace redb.Core.Caching;
///
/// Process-global registry of schemeName → CLR Type, derived from .
///
/// This mapping is a database-independent fact: a type's scheme name comes from its attribute
/// and is identical regardless of which database/connection it is used against. Therefore it lives
/// once per process and is shared by every cache domain — unlike the per-domain
/// scheme_id → Type projection in , where scheme_id is a
/// per-database fact that must stay isolated per connection.
///
/// It is self-healing: assembly loads (including into plugin AssemblyLoadContexts) bump a
/// generation counter, and the index is rebuilt lazily on the next lookup. This removes the old
/// one-shot, per-domain snapshot that went stale whenever modules loaded after initialization.
///
///
/// Collectible ALC safety. Entries hold to , never
/// a strong reference. A strong Type keeps its AssemblyLoadContext alive, so a static index
/// that held one would pin every hot-reloaded plugin module in memory forever. Dead entries are pruned
/// lazily on lookup.
///
///
public static class ClrSchemeTypeIndex
{
private static readonly ConcurrentDictionary> _nameToType = new();
// Explicit [RedbScheme(Name = "...")] values claimed by more than one DISTINCT type (different
// FullName). Two instances of the SAME FullName from different ALCs are a reload, not a conflict
// (see Rescan). Recorded during the scan (best-effort, must not throw) and turned into a hard
// failure by ThrowIfNameConflict at the deterministic point where the type is actually synced.
private static readonly ConcurrentDictionary Existing, WeakReference Conflicting)> _nameConflicts = new();
private static readonly object _scanLock = new();
private static long _assemblyGeneration; // bumped on every assembly load in the process
private static long _scannedGeneration = -1; // generation captured at the last completed scan
static ClrSchemeTypeIndex()
{
// Fires for assemblies loaded into ANY load context (default + plugin ALCs) in .NET Core.
AppDomain.CurrentDomain.AssemblyLoad += static (_, _) => Interlocked.Increment(ref _assemblyGeneration);
}
///
/// Resolve a scheme name (or alias) to its CLR type, or null if no
/// type carries that name (a legitimately non-generic scheme). Prunes the entry if the type's ALC
/// has been unloaded.
///
public static Type? Resolve(string schemeName)
{
if (string.IsNullOrEmpty(schemeName)) return null;
EnsureFresh();
var type = TryResolveLive(schemeName, out var dead);
if (type != null || !dead)
return type;
// The entry pointed at a type whose ALC has unloaded. The same name may still belong to a live type: the
// scan writes the last type that carries a name, and a module that loaded a copy of the host's own
// assembly took the host's names; once it unloaded they resolved to null, and no assembly load came to
// bring a rescan. Unloading is no load event, so the rescan is made here, once.
lock (_scanLock)
{
var gen = Interlocked.Read(ref _assemblyGeneration);
Rescan();
Volatile.Write(ref _scannedGeneration, gen);
}
return TryResolveLive(schemeName, out _);
}
private static Type? TryResolveLive(string schemeName, out bool dead)
{
dead = false;
if (!_nameToType.TryGetValue(schemeName, out var weak))
return null;
if (weak.TryGetTarget(out var type))
return type;
// The type's ALC was unloaded — drop the dead entry (but only if it is still THIS weak ref;
// a concurrent Register may have replaced it with a live one).
((System.Collections.Generic.ICollection>>)_nameToType)
.Remove(new KeyValuePair>(schemeName, weak));
dead = true;
return null;
}
///
/// Explicitly register a name → type mapping (e.g. from an authoritative scheme sync). Idempotent;
/// last write wins. Lets types resolve even before/without an assembly scan.
///
public static void Register(string schemeName, Type type)
{
if (!string.IsNullOrEmpty(schemeName) && type != null)
_nameToType[schemeName] = new WeakReference(type);
}
/// Rescan loaded assemblies if any have loaded since the last scan. Cheap no-op when unchanged.
public static void EnsureFresh()
{
if (Interlocked.Read(ref _scannedGeneration) == Interlocked.Read(ref _assemblyGeneration))
return;
lock (_scanLock)
{
var gen = Interlocked.Read(ref _assemblyGeneration);
if (_scannedGeneration == gen) return; // another thread already rescanned
Rescan();
// If an assembly loaded mid-scan, gen < newest → next EnsureFresh rescans again (no lost update).
Volatile.Write(ref _scannedGeneration, gen);
}
}
private static void Rescan()
{
foreach (var type in EnumerateSchemeTypes())
{
var attr = type.GetCustomAttribute();
if (attr == null) continue;
var name = attr.GetSchemeName(type);
if (!string.IsNullOrEmpty(name))
{
// Only explicit names are policed. Alias collisions have always been last-write-wins
// (e.g. "Product" is declared in two unrelated projects) and tightening them would
// break projects that never opted into explicit naming.
if (!string.IsNullOrWhiteSpace(attr.Name) && TryGetLiveOwner(name, out var owner) && owner != type)
{
// Same FullName from a different ALC = the SAME logical type reloaded (Tsak hot-swap),
// NOT a name conflict. Only distinct FullNames sharing one explicit Name are a real clash.
if (owner.FullName == type.FullName)
{
_nameConflicts.TryRemove(name, out _); // clear a stale conflict left by the old instance
}
else if (owner.GetCustomAttribute()?.Name == attr.Name)
{
_nameConflicts[name] = (new WeakReference(owner), new WeakReference(type));
}
}
_nameToType[name] = new WeakReference(type); // upsert; never Clear (readers stay safe)
}
if (!string.IsNullOrEmpty(attr.Alias)) _nameToType[attr.Alias!] = new WeakReference(type);
}
}
private static bool TryGetLiveOwner(string name, out Type owner)
{
owner = null!;
return _nameToType.TryGetValue(name, out var weak) && weak.TryGetTarget(out owner!);
}
///
/// Throws when another distinct type has claimed the same explicit scheme name. Called from
/// the sync path rather than from the scan itself: the scan is a best-effort warm-up that must not
/// throw, but a duplicate name is fatal and has to surface deterministically, before anything is
/// written. A conflict whose other party has since been unloaded (dead weak ref) is not reported —
/// there is nothing to clash with anymore.
///
public static void ThrowIfNameConflict(string schemeName, Type type)
{
EnsureFresh();
if (!_nameConflicts.TryGetValue(schemeName, out var pair))
return;
// Both parties must still be alive AND one of them must be the type being synced.
if (!pair.Existing.TryGetTarget(out var existing) || !pair.Conflicting.TryGetTarget(out var conflicting))
{
_nameConflicts.TryRemove(schemeName, out _); // one side unloaded → no live conflict
return;
}
if (existing == type || conflicting == type)
throw new RedbSchemeNameConflictException(schemeName, existing, conflicting);
}
///
/// Single source of truth for assembly enumeration: broad (every load context), reflection-load-safe.
/// Used by the index and reusable by auto-sync so both see the same set.
///
public static IEnumerable EnumerateSchemeTypes()
{
foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
{
Type?[] types;
try
{
types = asm.GetTypes();
}
catch (ReflectionTypeLoadException ex)
{
types = ex.Types;
}
catch
{
continue;
}
foreach (var t in types)
{
if (t != null && t.GetCustomAttribute() != null)
yield return t;
}
}
}
/// Diagnostics: number of live registered name keys (dead weak refs excluded).
public static int Count
{
get
{
var n = 0;
foreach (var weak in _nameToType.Values)
if (weak.TryGetTarget(out _)) n++;
return n;
}
}
/// Test/reset hook — clears the index and forces a rescan on next lookup.
public static void Clear()
{
lock (_scanLock)
{
_nameToType.Clear();
_nameConflicts.Clear();
Interlocked.Exchange(ref _scannedGeneration, -1);
}
}
}
Path: redb/redb.Core/Caching/CollectibleContextCleanup.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/CollectibleContextCleanup.cs
----
using System;
using System.Reflection;
using System.Reflection.Metadata;
using System.Runtime.CompilerServices;
using System.Runtime.Loader;
using System.Threading;
using Microsoft.Extensions.Logging;
namespace redb.Core.Caching;
///
/// Forgets a collectible when it unloads (a module of Tsak, for instance): the
/// process-wide caches that hold INSTANCES of the module's types, or metadata built for them, drop those, so nothing
/// keeps the context alive. Caches of redb keyed by type alone hold their key weakly instead and need nothing here.
///
/// Every collectible context is watched from the moment one of its assemblies loads (and the ones that existed before
/// this class first ran are picked up then), so the hot path pays nothing: the work happens once per unload, in
/// , which Unload() raises before the context can be collected.
///
///
internal static class CollectibleContextCleanup
{
private static readonly ConditionalWeakTable Watched = new();
private static readonly object Marker = new();
private static int _started;
private static int _noHandlersReported;
private static ILogger? _logger;
///
/// Starts watching collectible contexts; called by every cache that can hold a module's instances and by every
/// redb service. The first logger handed over reports the cleanup.
///
public static void EnsureWatching(ILogger? logger = null)
{
if (logger != null)
Interlocked.CompareExchange(ref _logger, logger, null);
if (Interlocked.Exchange(ref _started, 1) == 1)
return;
AppDomain.CurrentDomain.AssemblyLoad += static (_, e) => Watch(e.LoadedAssembly);
foreach (var context in AssemblyLoadContext.All)
if (context.IsCollectible)
Watch(context);
}
private static void Watch(Assembly assembly)
{
if (assembly.IsCollectible && AssemblyLoadContext.GetLoadContext(assembly) is { } context)
Watch(context);
}
private static void Watch(AssemblyLoadContext context)
{
if (Watched.TryAdd(context, Marker))
context.Unloading += OnUnloading;
}
private static void OnUnloading(AssemblyLoadContext context)
{
context.Unloading -= OnUnloading;
bool Unloading(Type type) => BelongsTo(type, context);
GlobalPropsCache.RemoveObjectsOfTypes(Unloading);
GlobalListCache.RemoveObjectsOfTypes(Unloading);
ClearMetadataUpdateCaches(context);
}
///
/// The libraries of .NET keep process-wide caches built over the types they handled, and do not let a collectible
/// context go while one of its types is in them: System.Text.Json above all (metadata in every options instance,
/// the static SystemTextJsonRedbSerializer.Options of redb included, in contexts shared by equal options and
/// in emitted member accessors), TypeDescriptor and others. They declare a handler for hot reload
/// () whose ClearCache empties those caches; redb calls
/// ClearCache(null) of every handler declared by a loaded assembly, as dotnet watch does, once per
/// unload. The assemblies of the unloading context are left out. Unloadable assemblies are not supported by
/// System.Text.Json otherwise: https://github.com/dotnet/runtime/issues/65323. Costs cold caches in those libraries
/// for what follows, once per unload.
///
private static void ClearMetadataUpdateCaches(AssemblyLoadContext unloading)
{
var found = 0;
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
if (assembly.IsDynamic || AssemblyLoadContext.GetLoadContext(assembly) == unloading)
continue;
MetadataUpdateHandlerAttribute[] handlers;
try
{
handlers = (MetadataUpdateHandlerAttribute[])assembly.GetCustomAttributes(typeof(MetadataUpdateHandlerAttribute), false);
}
catch (Exception ex)
{
_logger?.LogWarning(ex, "Unloading context {Context}: cannot read the hot reload handlers of {Assembly}",
unloading.Name, assembly.FullName);
continue;
}
foreach (var handler in handlers)
{
var clearCache = handler.HandlerType.GetMethod("ClearCache",
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static, [typeof(Type[])]);
if (clearCache == null)
continue;
found++;
try
{
clearCache.Invoke(null, [null]);
}
catch (Exception ex)
{
_logger?.LogWarning(ex, "Unloading context {Context}: ClearCache of {Handler} failed, the other caches are cleared",
unloading.Name, handler.HandlerType.FullName);
}
}
}
if (found == 0 && Interlocked.Exchange(ref _noHandlersReported, 1) == 0)
_logger?.LogWarning(
"Unloading context {Context}: no loaded assembly declares a hot reload cache handler; caches of the .NET " +
"libraries (System.Text.Json among them) may keep the context alive", unloading.Name);
}
///
/// Whether needs : declared in one of its assemblies, or built
/// over such a type (RedbObject<ModuleProps>, an array or list of one).
///
internal static bool BelongsTo(Type type, AssemblyLoadContext context)
{
if (type.HasElementType)
return BelongsTo(type.GetElementType()!, context);
if (AssemblyLoadContext.GetLoadContext(type.Assembly) == context)
return true;
if (type.IsConstructedGenericType)
foreach (var argument in type.GetGenericArguments())
if (BelongsTo(argument, context))
return true;
return false;
}
}
Path: redb/redb.Core/Caching/GlobalListCache.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/GlobalListCache.cs
----
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using redb.Core.Models.Contracts;
using redb.Core.Models.Entities;
namespace redb.Core.Caching
{
///
/// Cache entry with TTL.
///
internal class ListCacheEntry
{
public T Value { get; set; } = default!;
public DateTime ExpiresAt { get; set; }
public bool IsExpired => DateTime.UtcNow > ExpiresAt;
}
///
/// Domain-isolated cache data for lists.
///
internal class ListCacheDomain
{
public bool Enabled = true;
public TimeSpan Ttl = TimeSpan.FromMinutes(5);
// Lists cache
public readonly ConcurrentDictionary> ListsById = new();
public readonly ConcurrentDictionary> ListsByName = new();
// Items cache
public readonly ConcurrentDictionary>> ItemsByListId = new();
public readonly ConcurrentDictionary> ItemsById = new();
public void Clear()
{
ListsById.Clear();
ListsByName.Clear();
ItemsByListId.Clear();
ItemsById.Clear();
}
}
///
/// Domain-isolated cache for lists and their items.
/// Hybrid model: TTL for eventual consistency + local invalidation on changes.
/// Instance is bound to specific domain, static data is shared.
///
public sealed class GlobalListCache
{
private static readonly ConcurrentDictionary _domains = new();
private readonly string _domain;
///
/// Domain identifier for this cache instance.
///
public string Domain => _domain;
///
/// Create cache instance for specific domain.
///
public GlobalListCache(string? domain = null, bool? enabled = null)
{
CollectibleContextCleanup.EnsureWatching();
_domain = domain ?? "default";
var cache = GetCache();
if (enabled.HasValue)
cache.Enabled = enabled.Value;
}
private ListCacheDomain GetCache() => _domains.GetOrAdd(_domain, _ => new ListCacheDomain());
///
/// Drops, in every domain, the cached items whose loaded object is of a type
/// answers true for, and the item lists that hold one: the types of a collectible AssemblyLoadContext that
/// unloads (). Such an item comes back from the database on next read.
///
internal static void RemoveObjectsOfTypes(Func unloading)
{
bool Holds(RedbListItem item) => item.LoadedObject is { } loaded && unloading(loaded.GetType());
foreach (var domain in _domains.Values)
{
foreach (var entry in domain.ItemsById)
if (Holds(entry.Value.Value))
domain.ItemsById.TryRemove(entry);
foreach (var entry in domain.ItemsByListId)
if (entry.Value.Value.Any(Holds))
domain.ItemsByListId.TryRemove(entry);
}
}
///
/// Enable or disable cache for this domain.
///
public void SetEnabled(bool enabled)
{
var cache = GetCache();
cache.Enabled = enabled;
if (!enabled)
cache.Clear();
}
///
/// Check if cache is enabled.
///
public bool IsEnabled => GetCache().Enabled;
///
/// Set TTL for the cache.
///
public void SetTtl(TimeSpan ttl)
{
if (ttl <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(ttl), "TTL must be greater than 0");
GetCache().Ttl = ttl;
}
// ===== LISTS =====
///
/// Get list by ID.
///
public RedbList? GetList(long id)
{
var cache = GetCache();
if (!cache.Enabled) return null;
if (cache.ListsById.TryGetValue(id, out var entry))
{
if (!entry.IsExpired)
return entry.Value;
cache.ListsById.TryRemove(id, out _);
}
return null;
}
///
/// Get list by name.
///
public RedbList? GetListByName(string name)
{
var cache = GetCache();
if (!cache.Enabled) return null;
if (cache.ListsByName.TryGetValue(name, out var entry))
{
if (!entry.IsExpired)
return entry.Value;
cache.ListsByName.TryRemove(name, out _);
}
return null;
}
///
/// Cache list.
///
public void CacheList(RedbList list)
{
var cache = GetCache();
if (!cache.Enabled) return;
var entry = new ListCacheEntry
{
Value = list,
ExpiresAt = DateTime.UtcNow.Add(cache.Ttl)
};
cache.ListsById[list.Id] = entry;
cache.ListsByName[list.Name] = entry;
}
// ===== ITEMS =====
///
/// Get list items by list ID.
///
public List? GetListItems(long listId)
{
var cache = GetCache();
if (!cache.Enabled) return null;
if (cache.ItemsByListId.TryGetValue(listId, out var entry))
{
if (!entry.IsExpired)
return entry.Value;
cache.ItemsByListId.TryRemove(listId, out _);
}
return null;
}
///
/// Get list item by ID.
///
public RedbListItem? GetListItem(long itemId)
{
var cache = GetCache();
if (!cache.Enabled) return null;
if (cache.ItemsById.TryGetValue(itemId, out var entry))
{
if (!entry.IsExpired)
return entry.Value;
cache.ItemsById.TryRemove(itemId, out _);
}
return null;
}
///
/// Cache list items.
///
public void CacheListItems(long listId, List items)
{
var cache = GetCache();
if (!cache.Enabled) return;
var itemsEntry = new ListCacheEntry>
{
Value = items,
ExpiresAt = DateTime.UtcNow.Add(cache.Ttl)
};
cache.ItemsByListId[listId] = itemsEntry;
foreach (var item in items)
{
// Shared by every scope from now on, with the object it may already carry: Object loads on the reader's
// scope and, inside the reader's transaction, keeps nothing (owner decision 2026-09-15).
Utils.LazyReferenceInstaller.MarkShared(item);
item._cacheDomain ??= _domain;
var itemEntry = new ListCacheEntry
{
Value = item,
ExpiresAt = DateTime.UtcNow.Add(cache.Ttl)
};
cache.ItemsById[item.Id] = itemEntry;
}
}
// ===== INVALIDATION =====
///
/// Invalidate list and its items.
///
public void InvalidateList(long listId)
{
var cache = GetCache();
if (cache.ListsById.TryRemove(listId, out var listEntry))
{
cache.ListsByName.TryRemove(listEntry.Value.Name, out _);
}
InvalidateListItems(listId);
}
///
/// Invalidate list items.
///
public void InvalidateListItems(long listId)
{
var cache = GetCache();
if (cache.ItemsByListId.TryRemove(listId, out var itemsEntry))
{
foreach (var item in itemsEntry.Value)
{
cache.ItemsById.TryRemove(item.Id, out _);
}
}
}
///
/// Invalidate single list item.
///
public void InvalidateListItem(long itemId)
{
GetCache().ItemsById.TryRemove(itemId, out _);
}
///
/// Clear cache for this domain.
///
public void Clear()
{
GetCache().Clear();
}
///
/// Get cache size statistics.
///
public (int Lists, int Items) GetCacheSize()
{
var cache = GetCache();
return (cache.ListsById.Count, cache.ItemsById.Count);
}
}
}
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);
}
}
}
}
Path: redb/redb.Core/Caching/GlobalPropsCache.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/GlobalPropsCache.cs
----
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using redb.Core.Models.Contracts;
using redb.Core.Models.Entities;
namespace redb.Core.Caching
{
///
/// Domain-isolated cache data for props/objects.
///
internal class PropsCacheDomain
{
public IRedbObjectCache? Cache { get; set; }
}
///
/// Domain-isolated cache for WHOLE RedbObject (not just Props!).
/// Transparent to business code: if disabled (Cache == null), everything goes through DB.
/// Instance is bound to specific domain, static data is shared.
///
///
/// A cached graph is one instance shared by every scope. It carries nothing scope-bound, since a data object owns no
/// connection: its reference stubs hold the scope-free loader of their database and load on the live scope of whoever
/// reads them; only marks the graph shared, so a lazy load inside the reader's transaction
/// keeps nothing. The detached loader swapped in on hand-out, and the dead-scope
/// fallback installed on Set, are gone with the scope-bound loaders they compensated for.
///
public sealed class GlobalPropsCache
{
private static readonly ConcurrentDictionary _domains = new();
private static readonly object _lock = new();
private readonly string _domain;
///
/// Domain identifier for this cache instance.
///
public string Domain => _domain;
///
/// Create cache instance for specific domain.
///
public GlobalPropsCache(string? domain = null)
{
_domain = domain ?? "default";
}
private PropsCacheDomain GetCache() => _domains.GetOrAdd(_domain, _ => new PropsCacheDomain());
///
/// Get underlying cache instance for this domain.
/// If null - cache is disabled, everything goes through DB.
///
public IRedbObjectCache? Instance => GetCache().Cache;
///
/// Initialize cache for this domain (called once at application startup per domain).
///
public void Initialize(IRedbObjectCache cache)
{
CollectibleContextCleanup.EnsureWatching();
lock (_lock)
{
GetCache().Cache = cache;
}
}
///
/// Get WHOLE RedbObject with hash validation.
///
public RedbObject? Get(long objectId, Guid hash) where TProps : class, new()
=> Instance?.Get(objectId, hash);
///
/// Get WHOLE RedbObject WITHOUT hash validation (for monolithic applications).
///
public RedbObject? GetWithoutHashValidation(long objectId) where TProps : class, new()
=> Instance?.GetWithoutHashValidation(objectId);
///
/// Save WHOLE RedbObject to cache. From here on the graph is shared by every scope.
///
public void Set(RedbObject obj) where TProps : class, new()
{
var cache = Instance;
if (cache == null || !obj.hash.HasValue) return;
cache.Set(obj);
Utils.LazyReferenceInstaller.MarkShared(obj);
}
///
/// Save WHOLE RedbObject and every loaded object under it. One walk marks the graph shared and collects the
/// nested entries, where a Set followed by walked the same Props twice.
///
public void SetGraph(RedbObject obj) where TProps : class, new()
{
var cache = Instance;
if (cache == null || !obj.hash.HasValue) return;
cache.Set(obj);
foreach (var nested in Utils.LazyReferenceInstaller.MarkSharedAndCollect(obj))
{
if (ReferenceEquals(nested, obj)) continue;
CacheDelegates.Set(cache, nested);
}
}
///
/// Caches every loaded RedbObject found under by its own id, so a nested object is
/// served directly by id as well; the entries only (the Set of the root marked the graph shared already).
/// Stubs are neither cached nor walked.
///
public void SetNested(object props)
{
var cache = Instance;
if (cache == null || props == null) return;
CacheNestedObjectsInternal(cache, props, new HashSet