Path: redb/redb.Core/RedbServiceBase.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/RedbServiceBase.cs ---- #pragma warning disable CS0618 // implements or uses the deprecated object permissions and roles (RedbDeprecation) using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core.Caching; using redb.Core.Data; using redb.Core.Providers; using redb.Core.Query; using redb.Core.Serialization; using redb.Core.Utils; using redb.Core.Models.Enums; using redb.Core.Models.Permissions; using redb.Core.Models.Contracts; using redb.Core.Models.Security; using redb.Core.Models.Entities; using redb.Core.Models.Configuration; using redb.Core.Attributes; using redb.Core.Exceptions; using redb.Core.Models; using redb.Core.Services; using System.Reflection; using System.Threading; using System.Runtime.Loader; namespace redb.Core; /// /// Base abstract class for RedbService implementations. /// Contains all common logic for delegating to providers. /// Provider-specific implementations (Postgres, MSSQL) inherit from this class. /// public abstract partial class RedbServiceBase : IRedbService { private readonly IRedbContext _context; private readonly ISchemeSyncProvider _schemeSync; protected IObjectStorageProvider _objectStorage; protected ITreeProvider _treeProvider; private readonly IPermissionProvider _permissionProvider; protected IQueryableProvider _queryProvider; // The query provider every query goes through. The groupings of its queries read their list item keys through // the list provider (Query.Grouping.ListItemGroupKeys): it is handed over here, on use, because a Pro service // replaces _queryProvider after this constructor. An implementation not derived from QueryableProviderBase has // none, and such a grouping refuses with the reason. private IQueryableProvider Queries { get { if (_queryProvider is Providers.Base.QueryableProviderBase queryables && queryables.ListItems == null) queryables.ListItems = _listProvider; return _queryProvider; } } private readonly IValidationProvider _validationProvider; private readonly IRedbSecurityContext _securityContext; private readonly IUserProvider _userProvider; private readonly IRoleProvider _roleProvider; private readonly IListProvider _listProvider; private readonly IServiceProvider _serviceProvider; // readonly: the providers hold this instance, so it is only ever changed in place (UpdateConfiguration). private readonly RedbServiceConfiguration _configuration; private readonly IRedbObjectSerializer _serializer; private readonly ILogger? _logger; /// /// Cache domain identifier for isolating caches between different database connections. /// protected readonly string _cacheDomain; /// /// Database context for direct data access. /// public IRedbContext Context => _context; public IRedbSecurityContext SecurityContext => _securityContext; public IUserProvider UserProvider => _userProvider; public IRoleProvider RoleProvider => _roleProvider; public IListProvider ListProvider => _listProvider; public RedbServiceConfiguration Configuration => _configuration; /// /// Cache domain identifier for this service instance. /// public string CacheDomain => _cacheDomain; // === ABSTRACT METHODS FOR PROVIDER-SPECIFIC IMPLEMENTATIONS === /// /// Database provider name (e.g., "PostgreSQL", "MSSql"). /// protected abstract string DatabaseTypeName { get; } /// /// SQL query to get database version. /// protected abstract string GetVersionSql { get; } /// /// SQL query to get database size in bytes. /// protected abstract string GetDatabaseSizeSql { get; } /// /// Error message when IRedbContext is not registered. /// protected abstract string ContextNotRegisteredError { get; } /// /// Create scheme sync provider. /// protected abstract ISchemeSyncProvider CreateSchemeSyncProvider( IRedbContext context, RedbServiceConfiguration config, string cacheDomain, ILogger? logger); /// /// Create permission provider. /// protected abstract IPermissionProvider CreatePermissionProvider( IRedbContext context, IRedbSecurityContext securityContext, ILogger? logger); /// /// Create user provider. /// protected abstract IUserProvider CreateUserProvider( IRedbContext context, IRedbSecurityContext securityContext, ILogger? logger); /// /// Create role provider. /// protected abstract IRoleProvider CreateRoleProvider( IRedbContext context, IRedbSecurityContext securityContext, ILogger? logger); /// /// Create list provider. /// protected abstract IListProvider CreateListProvider( IRedbContext context, RedbServiceConfiguration config, ISchemeSyncProvider schemeSync, ILogger? logger); /// /// Save-pipeline interceptors (discussion #12) handed to the storage provider: the DI registrations, resolved /// once, and the run-time subscriptions of the , read on /// every save. Pro services building their own storage call this too. /// protected Interception.RedbSaveInterceptorPipeline ResolveSaveInterceptors() => new( _serviceProvider.GetService(typeof(IEnumerable)) as IEnumerable, _serviceProvider.GetService(typeof(Interception.IRedbSaveInterceptorRegistry)) as Interception.IRedbSaveInterceptorRegistry); /// /// Password hasher for the user provider: a DI registration wins, the fallback is bcrypt. /// Never SimplePasswordHasher - a bare redb deployment must not default to salted SHA256 /// (external security report, 2026-09-08). Legacy SHA256+salt hashes keep validating: /// BcryptPasswordHasher recognizes both formats. /// protected Security.IPasswordHasher ResolvePasswordHasher() => _serviceProvider.GetService(typeof(Security.IPasswordHasher)) as Security.IPasswordHasher ?? new Security.BcryptPasswordHasher(); /// /// Create object storage provider. /// protected abstract IObjectStorageProvider CreateObjectStorageProvider( IRedbContext context, IRedbObjectSerializer serializer, IPermissionProvider permissionProvider, IRedbSecurityContext securityContext, ISchemeSyncProvider schemeSync, RedbServiceConfiguration config, IListProvider listProvider, ILogger? logger, Interception.RedbSaveInterceptorPipeline? saveInterceptors); /// /// Create tree provider. /// protected abstract ITreeProvider CreateTreeProvider( IRedbContext context, IObjectStorageProvider objectStorage, IPermissionProvider permissionProvider, IRedbObjectSerializer serializer, IRedbSecurityContext securityContext, ISchemeSyncProvider schemeSync, RedbServiceConfiguration config, ILogger? logger, Interception.RedbSaveInterceptorPipeline? saveInterceptors); /// /// Create lazy props loader. /// protected abstract ILazyPropsLoader CreateLazyPropsLoader( IRedbContext context, ISchemeSyncProvider schemeSync, IRedbObjectSerializer serializer, RedbServiceConfiguration config, string cacheDomain, IListProvider listProvider, ILogger? logger); /// /// Create queryable provider. /// protected abstract IQueryableProvider CreateQueryableProvider( IRedbContext context, IRedbObjectSerializer serializer, ISchemeSyncProvider schemeSync, IRedbSecurityContext securityContext, ILazyPropsLoader lazyPropsLoader, RedbServiceConfiguration config, string cacheDomain, ILogger? logger); /// /// Create validation provider. /// protected abstract IValidationProvider CreateValidationProvider( IRedbContext context, ILogger? logger); /// /// Factory for the maintenance provider (planner statistics, index health). Lazy: most /// scopes never touch maintenance, so nothing is built until the first access. /// protected abstract IMaintenanceProvider CreateMaintenanceProvider( IRedbContext context, int analysisLimit, ILogger? logger); private IMaintenanceProvider? _maintenance; /// public IMaintenanceProvider Maintenance => _maintenance ??= CreateMaintenanceProvider(_context, _configuration.MaintenanceAnalysisLimit, _logger); /// /// SQL dialect for database-specific queries. /// protected abstract ISqlDialect SqlDialect { get; } /// /// Initialize RedbServiceBase with dependency injection. /// protected RedbServiceBase(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; _context = serviceProvider.GetService() ?? throw new InvalidOperationException(ContextNotRegisteredError); _serializer = serviceProvider.GetService() ?? new SystemTextJsonRedbSerializer(); _logger = serviceProvider.GetService>() as ILogger; // Process-wide caches forget a collectible AssemblyLoadContext (a module) when it unloads. Caching.CollectibleContextCleanup.EnsureWatching(_logger); _configuration = serviceProvider.GetService() ?? new RedbServiceConfiguration(); _securityContext = serviceProvider.GetService() ?? AmbientSecurityContext.GetOrCreateDefault(); // Compute cache domain for this service instance _cacheDomain = _configuration.GetEffectiveCacheDomain(); // Create providers using abstract factory methods (passing cacheDomain) _schemeSync = CreateSchemeSyncProvider(_context, _configuration, _cacheDomain, _logger); // A scheme sync that has to write takes the schema lock of this service (see SchemeSyncProviderBase). if (_schemeSync is Providers.Base.SchemeSyncProviderBase schemeSyncBase) { schemeSyncBase.RunUnderSchemaLock = RunUnderSchemaLockAsync; schemeSyncBase.SchemaProblemFound = ReportSchemaProblem; } _permissionProvider =CreatePermissionProvider(_context, _securityContext, _logger); // Permission cache keys carry the database: ids are per database (review 2026-09-24, C-1). if (_permissionProvider is Providers.Base.PermissionProviderBase permissionBase) permissionBase.CacheDomain = _cacheDomain; _userProvider = CreateUserProvider(_context, _securityContext, _logger); _roleProvider = CreateRoleProvider(_context, _securityContext, _logger); _listProvider = CreateListProvider(_context, _configuration, _schemeSync, _logger); // One interceptor pipeline for the storage and the tree: DeleteSubtreeAsync fires the delete interceptors too. var saveInterceptors = ResolveSaveInterceptors(); _objectStorage = CreateObjectStorageProvider(_context, _serializer, _permissionProvider, _securityContext, _schemeSync, _configuration, _listProvider, _logger, saveInterceptors); _treeProvider = CreateTreeProvider(_context, _objectStorage, _permissionProvider, _serializer, _securityContext, _schemeSync, _configuration, _logger, saveInterceptors); // A data object owns no connection: RedbListItem.Object and the Props of reference stubs load on the live // scope of whoever reads them. This service becomes current for the flow that resolved it, and registers its // database for the loads that find no live scope (refused by default, a fresh scope by explicit option). The // per-item and process-wide loader delegates it installed before opened a fresh scope and pooled connection per // read. _listProvider.LinkedObjectsBatchLoader = LoadLinkedObjectsBatchAsync; ScopeFactory = serviceProvider.GetService(); RedbDomainRegistry.Register(_cacheDomain, ScopeFactory, _configuration, _logger); // A service of the root provider is captive: it lives as long as the process, and the frame it enters below is // inherited by every flow. It lends lazy loads its scope factory, never its one connection (RedbDomainRegistry. // InScopeOf) - parallel lazy loads of shared instances collided on that connection (review after 4.0.0). IsCaptive = ScopeFactory != null && RedbServiceProviders.IsRoot(serviceProvider); LazyPropsLoader = CreateLazyPropsLoader(_context, _schemeSync, _serializer, _configuration, _cacheDomain, _listProvider, _logger); _queryProvider = CreateQueryableProvider(_context, _serializer, _schemeSync, _securityContext, LazyPropsLoader, _configuration, _cacheDomain, _logger); _validationProvider = CreateValidationProvider(_context, _logger); SelfReference = new WeakReference(this); ServicesByContext.AddOrUpdate(_context, this); RedbAmbientScope.Enter(this); } // === Lazy loads on the reader's scope === // Context (one scope, one connection) -> the service of that scope: how a scope-bound loader names the origin of the // instances it materializes. Weak both ways: an ended scope leaves nothing behind. private static readonly System.Runtime.CompilerServices.ConditionalWeakTable ServicesByContext = new(); /// The service whose scope owns ; null for an unknown context. internal static RedbServiceBase? ServiceOf(IRedbContext? context) => context != null && ServicesByContext.TryGetValue(context, out var service) ? service : null; /// A weak reference to this service, shared by every instance it is the origin of. internal WeakReference SelfReference { get; } /// /// This service's own lazy Props loader, bound to its context. Reference stubs never carry it: they carry the /// scope-free loader of this database, which calls the loader of whichever live service reads them. /// protected internal ILazyPropsLoader LazyPropsLoader { get; protected set; } = null!; /// Whether this service's scope has ended (its context is disposed): it no longer answers lazy loads. internal bool IsScopeEnded => _context.IsDisposed; /// The service was resolved from the root provider of its container (see ). internal bool IsCaptive { get; } /// /// Whether a lazy load resolved to this reader runs in a fresh scope of its container instead of on its connection: a /// captive service outside a transaction. Inside its transaction the connection is the transaction, and the load is /// part of it - it reads what the transaction wrote, as it did before. /// internal bool LendsScope => IsCaptive && !_context.IsInTransaction; /// The logger of this service; null when the host registered none. protected internal ILogger? Logger => _logger; /// The scope factory of the container that resolved this service; null outside DI. internal IServiceScopeFactory? ScopeFactory { get; } /// /// The captive service this scope was lent to for one load (); null for a /// scope of its own. /// internal RedbServiceBase? LentTo { get; set; } /// /// The service that instances materialized by this one name as their origin: itself, or the captive service it was lent /// to. A lent scope ends with its load, while what it loaded lives on with the captive reader - the stubs under it /// load through a lent scope of their own. /// internal RedbServiceBase AsOrigin => LentTo ?? this; // === A scope of this service's container (IRedbScopeSource) === /// public bool CanCreateScope => ScopeFactory != null; /// public RedbScope CreateScope() { if (ScopeFactory == null) throw new InvalidOperationException( "This IRedbService was built without a DI container (its provider has no IServiceScopeFactory), so it " + "cannot open a scope of its own. Resolve services from a container to get one per unit of work."); var scope = ScopeFactory.CreateAsyncScope(); RedbScope? opened = null; try { var service = scope.ServiceProvider.GetRequiredService(); if (!string.Equals(service.CacheDomain, CacheDomain, StringComparison.Ordinal)) throw new InvalidOperationException( $"A scope of this service's container resolves IRedbService for database '{service.CacheDomain}', not " + $"'{CacheDomain}': the container registers IRedbService differently per resolution. A scope opened from " + "a service must read that service's database; register one IRedbService per container."); opened = new RedbScope(service, scope); return opened; } finally { if (opened == null) scope.Dispose(); } } /// public IDisposable BeginAccess() => RedbAmbientScope.Push(this); /// public virtual IDisposable WithQueryPlanner(bool enabled) => redb.Core.Query.QueryPlannerScope.Unchanged; /// Opens a query planner block for the calling flow; the tiers that have a planner return it from . protected static IDisposable PushQueryPlanner(bool enabled) => redb.Core.Query.QueryPlannerScope.Push(enabled); /// public async Task> LoadLinkedObjectsAsync( IEnumerable items, CancellationToken cancellationToken = default) { var pending = items.Where(i => !i.IsObjectLoaded && i.IdObject.HasValue).ToList(); if (pending.Count == 0) return new Dictionary(); var byId = await LoadLinkedObjectsBatchAsync(pending.Select(i => i.IdObject!.Value).Distinct().ToList(), cancellationToken); foreach (var item in pending) if (byId.TryGetValue(item.IdObject!.Value, out var obj)) item.Publish(obj, _context); return byId; } /// /// Batch resolver behind the list hand-out preload: one polymorphic load for all linked /// objects of a list. Depth 10 - the SAME depth the lazy getter path uses (LoadTypedAsync), /// so a preloaded extension object is indistinguishable from a lazily loaded one (dictionary /// extension objects are used actively and may carry nested references). Missing ids are /// simply absent from the result - their items keep the lazy path. /// private async Task> LoadLinkedObjectsBatchAsync( IReadOnlyCollection objectIds, CancellationToken cancellationToken) { var loaded = await _objectStorage.LoadAsync(objectIds, depth: 10, cancellationToken: cancellationToken); var byId = new Dictionary(loaded.Count); foreach (var obj in loaded) byId[obj.Id] = obj; return byId; } /// /// The object behind a list item, loaded on this service's connection - the scope of whoever reads the item. A scope /// that tears down meanwhile refuses the command (ObjectDisposedException); nothing falls back to another scope. /// internal Task LoadLinkedObjectAsync(long objectId, CancellationToken cancellationToken) => LoadLinkedObjectCoreAsync(this, objectId, cancellationToken); private static async Task LoadLinkedObjectCoreAsync(IRedbService service, long objectId, CancellationToken cancellationToken) { var dialect = (service as RedbServiceBase)?.SqlDialect; var schemeId = dialect != null ? await service.Context.ExecuteScalarAsync( dialect.ObjectStorage_SelectSchemeIdByObjectId(), new object[] { objectId }, cancellationToken) : 0; if (schemeId == 0) return null; // A scheme this node has never cached (a fresh process, another cluster node) is resolved by // its id; the cache-only lookup fell through to the untyped get_object_json path below. var propsType = await service.Cache.ResolveClrTypeAsync(schemeId, service); if (propsType != null) { // The generic method is our own, so its shape is under our control: the previous // lookup of IObjectStorageProvider.LoadAsync by parameter list silently returned null // (NRE at runtime) the moment that signature grew a CancellationToken. var load = typeof(RedbServiceBase) .GetMethod(nameof(LoadTypedAsync), BindingFlags.NonPublic | BindingFlags.Static)! .MakeGenericMethod(propsType); return await (Task)load.Invoke(null, new object[] { service, objectId, cancellationToken })!; } if (service is not RedbServiceBase typed) return null; var json = await service.Context.ExecuteJsonAsync( typed.SqlDialect.ObjectStorage_GetObjectJson(), new object[] { objectId, 10 }, cancellationToken); return string.IsNullOrEmpty(json) ? null : typed._serializer.DeserializeDynamic(json, typeof(object)); } private static async Task LoadTypedAsync(IObjectStorageProvider storage, long objectId, CancellationToken cancellationToken) where TProps : class, new() => await storage.LoadAsync(objectId, 10, cancellationToken); // === Synchronous twins (thread-pool-free lazy path) === // The sync getter of RedbListItem.Object prefers these: the whole load - scheme lookup, // permission check, get_object_json, deserialization - runs on the calling thread down to // ADO.NET, so a saturated thread pool cannot slow or deadlock a touch of Object. Mirrors of // the async chain above, same depth, same diagnostics. /// Synchronous twin of , on the calling thread down to ADO.NET. internal IRedbObject? LoadLinkedObjectSync(long objectId) => LoadLinkedObjectCoreSync(this, objectId); private static IRedbObject? LoadLinkedObjectCoreSync(IRedbService service, long objectId) { var dialect = (service as RedbServiceBase)?.SqlDialect; var schemeId = dialect != null ? service.Context.ExecuteScalar(dialect.ObjectStorage_SelectSchemeIdByObjectId(), objectId) : 0; if (schemeId == 0) return null; // Same cold resolution as the async twin, on the calling thread. var propsType = service.Cache.ResolveClrType(schemeId, service); if (propsType != null) { // Same reflection shape as the async twin (and the same lesson: our own method, found // by name, never by parameter list). var load = typeof(RedbServiceBase) .GetMethod(nameof(LoadTypedSync), BindingFlags.NonPublic | BindingFlags.Static)! .MakeGenericMethod(propsType); return (IRedbObject?)load.Invoke(null, new object[] { service, objectId }); } if (service is not RedbServiceBase typed) return null; var json = service.Context.ExecuteJson(typed.SqlDialect.ObjectStorage_GetObjectJson(), objectId, 10); return string.IsNullOrEmpty(json) ? null : typed._serializer.DeserializeDynamic(json, typeof(object)); } private static IRedbObject? LoadTypedSync(IObjectStorageProvider storage, long objectId) where TProps : class, new() => storage.Load(objectId, 10); /// /// Get tree provider for extended scenarios. /// public ITreeProvider GetTreeProvider() => _treeProvider; // === DATABASE METADATA === // Sync properties ride the true sync path (calling thread down to ADO.NET) - the previous // .Result over the async form parked a thread on pool-scheduled continuations (debug-era // leftover; same class as the lazy-getter fix). public string dbVersion => _context.ExecuteScalar(GetVersionSql) ?? "unknown"; public string dbType => DatabaseTypeName; public string dbMigration => "ADO.NET"; public long? dbSize => _context.ExecuteScalar(GetDatabaseSizeSql); /// public Task GetDbVersionAsync(CancellationToken cancellationToken = default) => _context.ExecuteScalarAsync(GetVersionSql); // === ISchemeSyncProvider DELEGATION === public Task EnsureSchemeFromTypeAsync(CancellationToken cancellationToken = default) where TProps : class => _schemeSync.EnsureSchemeFromTypeAsync(cancellationToken); public Task> SyncStructuresFromTypeAsync(IRedbScheme scheme, bool strictDeleteExtra = true, CancellationToken cancellationToken = default) where TProps : class => _schemeSync.SyncStructuresFromTypeAsync(scheme, strictDeleteExtra, cancellationToken); public Task SyncSchemeAsync(CancellationToken cancellationToken = default) where TProps : class => _schemeSync.SyncSchemeAsync(cancellationToken); /// public Task DropUnknownStructuresAsync(bool dryRun = true, CancellationToken cancellationToken = default) where TProps : class => _schemeSync.DropUnknownStructuresAsync(dryRun, cancellationToken); public Task GetSchemeByTypeAsync(CancellationToken cancellationToken = default) where TProps : class => _schemeSync.GetSchemeByTypeAsync(cancellationToken); public Task GetSchemeByTypeAsync(Type type, CancellationToken cancellationToken = default) => _schemeSync.GetSchemeByTypeAsync(type, cancellationToken); public IRedbScheme? GetSchemeFromCache() where TProps : class => _schemeSync.GetSchemeFromCache(); public IRedbScheme? GetSchemeFromCache(string schemeName) => _schemeSync.GetSchemeFromCache(schemeName); public Task LoadSchemeByTypeAsync(CancellationToken cancellationToken = default) where TProps : class => _schemeSync.LoadSchemeByTypeAsync(cancellationToken); public Task LoadSchemeByTypeAsync(Type type, CancellationToken cancellationToken = default) => _schemeSync.LoadSchemeByTypeAsync(type, cancellationToken); public Task> GetStructuresByTypeAsync(CancellationToken cancellationToken = default) where TProps : class => _schemeSync.GetStructuresByTypeAsync(cancellationToken); public Task> GetStructuresByTypeAsync(Type type, CancellationToken cancellationToken = default) => _schemeSync.GetStructuresByTypeAsync(type, cancellationToken); public Task SchemeExistsForTypeAsync(CancellationToken cancellationToken = default) where TProps : class => _schemeSync.SchemeExistsForTypeAsync(cancellationToken); public Task SchemeExistsForTypeAsync(Type type, CancellationToken cancellationToken = default) => _schemeSync.SchemeExistsForTypeAsync(type, cancellationToken); public Task SchemeExistsByNameAsync(string schemeName, CancellationToken cancellationToken = default) => _schemeSync.SchemeExistsByNameAsync(schemeName, cancellationToken); public string GetSchemeNameForType() where TProps : class => _schemeSync.GetSchemeNameForType(); public string GetSchemeNameForType(Type type) => _schemeSync.GetSchemeNameForType(type); public string? GetSchemeAliasForType() where TProps : class => _schemeSync.GetSchemeAliasForType(); public string? GetSchemeAliasForType(Type type) => _schemeSync.GetSchemeAliasForType(type); public Task GetSchemeByIdAsync(long schemeId, CancellationToken cancellationToken = default) => _schemeSync.GetSchemeByIdAsync(schemeId, cancellationToken); public IRedbScheme? GetSchemeById(long schemeId) => _schemeSync.GetSchemeById(schemeId); public Task GetSchemeByNameAsync(string schemeName, CancellationToken cancellationToken = default) => _schemeSync.GetSchemeByNameAsync(schemeName, cancellationToken); public Task EnsureObjectSchemeAsync(string name, CancellationToken cancellationToken = default) => _schemeSync.EnsureObjectSchemeAsync(name, cancellationToken); public Task GetObjectSchemeAsync(string name, CancellationToken cancellationToken = default) => _schemeSync.GetObjectSchemeAsync(name, cancellationToken); public Task> GetSchemesAsync(CancellationToken cancellationToken = default) => _schemeSync.GetSchemesAsync(cancellationToken); public GlobalMetadataCache Cache => _schemeSync.Cache; public GlobalListCache ListCache => _schemeSync.ListCache; public GlobalPropsCache PropsCache => _schemeSync.PropsCache; public Task> GetStructuresAsync(IRedbScheme scheme, CancellationToken cancellationToken = default) => _schemeSync.GetStructuresAsync(scheme, cancellationToken); public Task MigrateStructureTypeAsync(long structureId, string oldTypeName, string newTypeName, bool dryRun = false, CancellationToken cancellationToken = default) => _schemeSync.MigrateStructureTypeAsync(structureId, oldTypeName, newTypeName, dryRun, cancellationToken); public Task RecomputeUniqueAsync(string propertyName, CancellationToken cancellationToken = default) where TProps : class => _schemeSync.RecomputeUniqueAsync(propertyName, cancellationToken); public Task> GetStructureTreeAsync(long schemeId, CancellationToken cancellationToken = default) => _schemeSync.GetStructureTreeAsync(schemeId, cancellationToken); public Task> GetSubtreeAsync(long schemeId, long? parentStructureId, CancellationToken cancellationToken = default) => _schemeSync.GetSubtreeAsync(schemeId, parentStructureId, cancellationToken); public void InvalidateStructureTreeCache(long schemeId) => _schemeSync.InvalidateStructureTreeCache(schemeId); public (int TreesCount, int SubtreesCount, long MemoryEstimate) GetStructureTreeCacheStats() => _schemeSync.GetStructureTreeCacheStats(); // === IObjectStorageProvider DELEGATION === public Task?> LoadAsync(long objectId, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() => _objectStorage.LoadAsync(objectId, depth, cancellationToken); // Without this delegation the facade would satisfy IObjectStorageProvider.Load with the // interface DEFAULT - the blocking-over-async fallback - and the sync lazy path would quietly // lose its thread-pool freedom (caught by the starvation stand: 4 capped threads, total // freeze inside ConfiguredTaskAwaiter.GetResult under IObjectStorageProvider.Load). public RedbObject? Load(long objectId, int depth = 10) where TProps : class, new() => _objectStorage.Load(objectId, depth); public Task?> GetByUniqueAsync(System.Linq.Expressions.Expression> keyProperty, object? value, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() => _objectStorage.GetByUniqueAsync(keyProperty, value, depth, cancellationToken); public Task?> GetByUniqueAsync(string propertyName, object? value, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() => _objectStorage.GetByUniqueAsync(propertyName, value, depth, cancellationToken); public Task SaveByUniqueAsync(RedbObject obj, CancellationToken cancellationToken = default) where TProps : class, new() => _objectStorage.SaveByUniqueAsync(obj, cancellationToken); public Task?> LoadAsync(IRedbObject obj, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() => _objectStorage.LoadAsync(obj, depth, cancellationToken); public Task?> LoadAsync(IRedbObject obj, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() => _objectStorage.LoadAsync(obj, user, depth, cancellationToken); public Task SaveAsync(IRedbObject obj, CancellationToken cancellationToken = default) => _objectStorage.SaveAsync(obj, cancellationToken); public Task SaveAsync(IRedbObject obj, CancellationToken cancellationToken = default) where TProps : class, new() => _objectStorage.SaveAsync(obj, cancellationToken); public Task DeleteAsync(IRedbObject obj, CancellationToken cancellationToken = default) => _objectStorage.DeleteAsync(obj, cancellationToken); public Task?> LoadAsync(long objectId, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() => _objectStorage.LoadAsync(objectId, user, depth, cancellationToken); public Task LoadJsonAsync(long objectId, int depth = 10, CancellationToken cancellationToken = default) => _objectStorage.LoadJsonAsync(objectId, depth, cancellationToken); public Task LoadJsonAsync(long objectId, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) => _objectStorage.LoadJsonAsync(objectId, user, depth, cancellationToken); public Task SaveAsync(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) => _objectStorage.SaveAsync(obj, user, cancellationToken); public Task SaveAsync(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) where TProps : class, new() => _objectStorage.SaveAsync(obj, user, cancellationToken); public Task DeleteAsync(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) => _objectStorage.DeleteAsync(obj, user, cancellationToken); public Task DeleteAsync(long objectId, CancellationToken cancellationToken = default) => _objectStorage.DeleteAsync(objectId, cancellationToken); public Task DeleteAsync(long objectId, IRedbUser user, CancellationToken cancellationToken = default) => _objectStorage.DeleteAsync(objectId, user, cancellationToken); public Task> AddNewObjectsAsync(IEnumerable> objects, CancellationToken cancellationToken = default) where TProps : class, new() => _objectStorage.AddNewObjectsAsync(objects, cancellationToken); public Task> AddNewObjectsAsync(IEnumerable> objects, IRedbUser user, CancellationToken cancellationToken = default) where TProps : class, new() => _objectStorage.AddNewObjectsAsync(objects, user, cancellationToken); public Task DeleteAsync(IEnumerable objectIds, CancellationToken cancellationToken = default) => _objectStorage.DeleteAsync(objectIds, cancellationToken); public Task DeleteAsync(IEnumerable objectIds, IRedbUser user, CancellationToken cancellationToken = default) => _objectStorage.DeleteAsync(objectIds, user, cancellationToken); public Task DeleteAsync(IEnumerable objects, CancellationToken cancellationToken = default) => _objectStorage.DeleteAsync(objects, cancellationToken); public Task DeleteAsync(IEnumerable objects, IRedbUser user, CancellationToken cancellationToken = default) => _objectStorage.DeleteAsync(objects, user, cancellationToken); public Task SoftDeleteAsync(IEnumerable objectIds, long? trashParentId = null, CancellationToken cancellationToken = default) => _objectStorage.SoftDeleteAsync(objectIds, trashParentId, cancellationToken); public Task SoftDeleteAsync(IEnumerable objectIds, IRedbUser user, long? trashParentId = null, CancellationToken cancellationToken = default) => _objectStorage.SoftDeleteAsync(objectIds, user, trashParentId, cancellationToken); public Task SoftDeleteAsync(IEnumerable objects, long? trashParentId = null, CancellationToken cancellationToken = default) => _objectStorage.SoftDeleteAsync(objects, trashParentId, cancellationToken); public Task SoftDeleteAsync(IEnumerable objects, IRedbUser user, long? trashParentId = null, CancellationToken cancellationToken = default) => _objectStorage.SoftDeleteAsync(objects, user, trashParentId, cancellationToken); public Task DeleteWithPurgeAsync( IEnumerable objectIds, int batchSize = 10, IProgress? progress = null, CancellationToken cancellationToken = default, long? trashParentId = null) => _objectStorage.DeleteWithPurgeAsync(objectIds, batchSize, progress, cancellationToken, trashParentId); public Task PurgeTrashAsync( long trashId, int totalCount, int batchSize = 10, IProgress? progress = null, CancellationToken cancellationToken = default) => _objectStorage.PurgeTrashAsync(trashId, totalCount, batchSize, progress, cancellationToken); public Task GetDeletionProgressAsync(long trashId, CancellationToken cancellationToken = default) => _objectStorage.GetDeletionProgressAsync(trashId, cancellationToken); public Task> GetUserActiveDeletionsAsync(long userId, CancellationToken cancellationToken = default) => _objectStorage.GetUserActiveDeletionsAsync(userId, cancellationToken); public Task> GetOrphanedDeletionTasksAsync(int timeoutMinutes = 30, CancellationToken cancellationToken = default) => _objectStorage.GetOrphanedDeletionTasksAsync(timeoutMinutes, cancellationToken); public Task TryClaimOrphanedTaskAsync(long trashId, int timeoutMinutes = 30, CancellationToken cancellationToken = default) => _objectStorage.TryClaimOrphanedTaskAsync(trashId, timeoutMinutes, cancellationToken); public Task LockForUpdateAsync(params long[] objectIds) => _objectStorage.LockForUpdateAsync(objectIds); public Task LockForUpdateAsync(long[] objectIds, CancellationToken cancellationToken) => _objectStorage.LockForUpdateAsync(objectIds, cancellationToken); public Task LockForUpdateRequiredAsync(params long[] objectIds) => _objectStorage.LockForUpdateRequiredAsync(objectIds); public Task LockForUpdateRequiredAsync(long[] objectIds, CancellationToken cancellationToken) => _objectStorage.LockForUpdateRequiredAsync(objectIds, cancellationToken); public Task> LoadAsync(IEnumerable objectIds, int depth = 10, CancellationToken cancellationToken = default) => _objectStorage.LoadAsync(objectIds, depth, cancellationToken); public Task> LoadAsync(IEnumerable objectIds, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) => _objectStorage.LoadAsync(objectIds, user, depth, cancellationToken); public Task> SaveAsync(IEnumerable objects, CancellationToken cancellationToken = default) => _objectStorage.SaveAsync(objects, cancellationToken); public Task> SaveAsync(IEnumerable objects, IRedbUser user, CancellationToken cancellationToken = default) => _objectStorage.SaveAsync(objects, user, cancellationToken); // V4 (LAZY Л2 §4.6): batch reload of reference stubs public Task LoadReferencesAsync(RedbObject parent, Func?>?> references, CancellationToken cancellationToken = default) where TProps : class, new() where TRef : class, new() => _objectStorage.LoadReferencesAsync(parent, references, cancellationToken); public Task LoadReferencesAsync(RedbObject parent, Func?> reference, CancellationToken cancellationToken = default) where TProps : class, new() where TRef : class, new() => _objectStorage.LoadReferencesAsync(parent, reference, cancellationToken); // LoadWithParentsAsync - Load with parent chain to root Task?> IObjectStorageProvider.LoadWithParentsAsync(long objectId, int depth, CancellationToken cancellationToken) => _objectStorage.LoadWithParentsAsync(objectId, depth, cancellationToken); Task?> IObjectStorageProvider.LoadWithParentsAsync(IRedbObject obj, int depth, CancellationToken cancellationToken) => _objectStorage.LoadWithParentsAsync(obj, depth, cancellationToken); Task?> IObjectStorageProvider.LoadWithParentsAsync(long objectId, IRedbUser user, int depth, CancellationToken cancellationToken) => _objectStorage.LoadWithParentsAsync(objectId, user, depth, cancellationToken); Task?> IObjectStorageProvider.LoadWithParentsAsync(IRedbObject obj, IRedbUser user, int depth, CancellationToken cancellationToken) => _objectStorage.LoadWithParentsAsync(obj, user, depth, cancellationToken); Task>> IObjectStorageProvider.LoadWithParentsAsync(IEnumerable objectIds, int depth, CancellationToken cancellationToken) => _objectStorage.LoadWithParentsAsync(objectIds, depth, cancellationToken); Task>> IObjectStorageProvider.LoadWithParentsAsync(IEnumerable objectIds, IRedbUser user, int depth, CancellationToken cancellationToken) => _objectStorage.LoadWithParentsAsync(objectIds, user, depth, cancellationToken); Task> IObjectStorageProvider.LoadWithParentsAsync(IEnumerable objectIds, int depth, CancellationToken cancellationToken) => _objectStorage.LoadWithParentsAsync(objectIds, depth, cancellationToken); Task> IObjectStorageProvider.LoadWithParentsAsync(IEnumerable objectIds, IRedbUser user, int depth, CancellationToken cancellationToken) => _objectStorage.LoadWithParentsAsync(objectIds, user, depth, cancellationToken); // === ITreeProvider DELEGATION === public Task DeleteSubtreeAsync(IRedbObject parentObj, CancellationToken cancellationToken = default) => _treeProvider.DeleteSubtreeAsync(parentObj, cancellationToken); public Task DeleteSubtreeAsync(IRedbObject parentObj, IRedbUser user, CancellationToken cancellationToken = default) => _treeProvider.DeleteSubtreeAsync(parentObj, user, cancellationToken); public Task DeleteSubtreeAsync(RedbObject parentObj, CancellationToken cancellationToken = default) => _treeProvider.DeleteSubtreeAsync(parentObj, cancellationToken); public Task DeleteSubtreeAsync(RedbObject parentObj, IRedbUser user, CancellationToken cancellationToken = default) => _treeProvider.DeleteSubtreeAsync(parentObj, user, cancellationToken); public Task> LoadTreeAsync(long rootObjectId, int? maxDepth = null, CancellationToken cancellationToken = default) where TProps : class, new() => _treeProvider.LoadTreeAsync(rootObjectId, maxDepth, cancellationToken); public Task> LoadTreeAsync(IRedbObject rootObj, int? maxDepth = null, CancellationToken cancellationToken = default) where TProps : class, new() => _treeProvider.LoadTreeAsync(rootObj, maxDepth, cancellationToken); public Task>> GetChildrenAsync(IRedbObject parentObj, CancellationToken cancellationToken = default) where TProps : class, new() => _treeProvider.GetChildrenAsync(parentObj, cancellationToken); public Task>> GetPathToRootAsync(IRedbObject obj, CancellationToken cancellationToken = default) where TProps : class, new() => _treeProvider.GetPathToRootAsync(obj, cancellationToken); public Task>> GetDescendantsAsync(IRedbObject parentObj, int? maxDepth = null, CancellationToken cancellationToken = default) where TProps : class, new() => _treeProvider.GetDescendantsAsync(parentObj, maxDepth, cancellationToken); public Task MoveObjectAsync(IRedbObject obj, IRedbObject? newParentObj, CancellationToken cancellationToken = default) => _treeProvider.MoveObjectAsync(obj, newParentObj, cancellationToken); public Task CreateChildAsync(TreeRedbObject obj, IRedbObject parentObj, CancellationToken cancellationToken = default) where TProps : class, new() => _treeProvider.CreateChildAsync(obj, parentObj, cancellationToken); public Task> LoadTreeAsync(long rootObjectId, IRedbUser user, int? maxDepth = null, CancellationToken cancellationToken = default) where TProps : class, new() => _treeProvider.LoadTreeAsync(rootObjectId, user, maxDepth, cancellationToken); public Task> LoadTreeAsync(IRedbObject rootObj, IRedbUser user, int? maxDepth = null, CancellationToken cancellationToken = default) where TProps : class, new() => _treeProvider.LoadTreeAsync(rootObj, user, maxDepth, cancellationToken); public Task>> GetChildrenAsync(IRedbObject parentObj, IRedbUser user, CancellationToken cancellationToken = default) where TProps : class, new() => _treeProvider.GetChildrenAsync(parentObj, user, cancellationToken); public Task>> GetPathToRootAsync(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) where TProps : class, new() => _treeProvider.GetPathToRootAsync(obj, user, cancellationToken); public Task>> GetDescendantsAsync(IRedbObject parentObj, IRedbUser user, int? maxDepth = null, CancellationToken cancellationToken = default) where TProps : class, new() => _treeProvider.GetDescendantsAsync(parentObj, user, maxDepth, cancellationToken); public Task MoveObjectAsync(IRedbObject obj, IRedbObject? newParentObj, IRedbUser user, CancellationToken cancellationToken = default) => _treeProvider.MoveObjectAsync(obj, newParentObj, user, cancellationToken); public Task CreateChildAsync(TreeRedbObject obj, IRedbObject parentObj, IRedbUser user, CancellationToken cancellationToken = default) where TProps : class, new() => _treeProvider.CreateChildAsync(obj, parentObj, user, cancellationToken); public Task LoadPolymorphicTreeAsync(IRedbObject rootObj, int? maxDepth = null, CancellationToken cancellationToken = default) => _treeProvider.LoadPolymorphicTreeAsync(rootObj, maxDepth, cancellationToken); public Task> GetPolymorphicChildrenAsync(IRedbObject parentObj, CancellationToken cancellationToken = default) => _treeProvider.GetPolymorphicChildrenAsync(parentObj, cancellationToken); public Task> GetPolymorphicPathToRootAsync(IRedbObject obj, CancellationToken cancellationToken = default) => _treeProvider.GetPolymorphicPathToRootAsync(obj, cancellationToken); public Task> GetPolymorphicDescendantsAsync(IRedbObject parentObj, int? maxDepth = null, CancellationToken cancellationToken = default) => _treeProvider.GetPolymorphicDescendantsAsync(parentObj, maxDepth, cancellationToken); public Task LoadPolymorphicTreeAsync(IRedbObject rootObj, IRedbUser user, int? maxDepth = null, CancellationToken cancellationToken = default) => _treeProvider.LoadPolymorphicTreeAsync(rootObj, user, maxDepth, cancellationToken); public Task> GetPolymorphicChildrenAsync(IRedbObject parentObj, IRedbUser user, CancellationToken cancellationToken = default) => _treeProvider.GetPolymorphicChildrenAsync(parentObj, user, cancellationToken); public Task> GetPolymorphicPathToRootAsync(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) => _treeProvider.GetPolymorphicPathToRootAsync(obj, user, cancellationToken); public Task> GetPolymorphicDescendantsAsync(IRedbObject parentObj, IRedbUser user, int? maxDepth = null, CancellationToken cancellationToken = default) => _treeProvider.GetPolymorphicDescendantsAsync(parentObj, user, maxDepth, cancellationToken); public Task InitializeTypeRegistryAsync(CancellationToken cancellationToken = default) => _treeProvider.InitializeTypeRegistryAsync(cancellationToken); // === IPermissionProvider DELEGATION === public IQueryable GetReadableObjectIds() => _permissionProvider.GetReadableObjectIds(); public Task CanUserEditObject(IRedbObject obj, CancellationToken cancellationToken = default) => _permissionProvider.CanUserEditObject(obj, cancellationToken); public Task CanUserSelectObject(IRedbObject obj, CancellationToken cancellationToken = default) => _permissionProvider.CanUserSelectObject(obj, cancellationToken); public Task CanUserInsertScheme(IRedbScheme scheme, CancellationToken cancellationToken = default) => _permissionProvider.CanUserInsertScheme(scheme, cancellationToken); public Task CanUserInsertScheme(IRedbScheme scheme, IRedbUser user, CancellationToken cancellationToken = default) => _permissionProvider.CanUserInsertScheme(scheme, user, cancellationToken); public Task CanUserDeleteObject(IRedbObject obj, CancellationToken cancellationToken = default) => _permissionProvider.CanUserDeleteObject(obj, cancellationToken); public IQueryable GetReadableObjectIds(IRedbUser user) => _permissionProvider.GetReadableObjectIds(user); public Task CanUserEditObject(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) => _permissionProvider.CanUserEditObject(obj, user, cancellationToken); public Task CanUserSelectObject(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) => _permissionProvider.CanUserSelectObject(obj, user, cancellationToken); public Task CanUserDeleteObject(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) => _permissionProvider.CanUserDeleteObject(obj, user, cancellationToken); public Task CanUserEditObject(RedbObject obj, CancellationToken cancellationToken = default) => _permissionProvider.CanUserEditObject(obj, cancellationToken); public Task CanUserSelectObject(RedbObject obj, CancellationToken cancellationToken = default) => _permissionProvider.CanUserSelectObject(obj, cancellationToken); public Task CanUserDeleteObject(RedbObject obj, CancellationToken cancellationToken = default) => _permissionProvider.CanUserDeleteObject(obj, cancellationToken); public Task CanUserEditObject(RedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) => _permissionProvider.CanUserEditObject(obj, user, cancellationToken); public Task CanUserSelectObject(RedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) => _permissionProvider.CanUserSelectObject(obj, user, cancellationToken); public Task CanUserDeleteObject(RedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) => _permissionProvider.CanUserDeleteObject(obj, user, cancellationToken); public Task CanUserInsertScheme(RedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) => _permissionProvider.CanUserInsertScheme(obj, user, cancellationToken); public Task CreatePermissionAsync(PermissionRequest request, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) => _permissionProvider.CreatePermissionAsync(request, currentUser, cancellationToken); public Task UpdatePermissionAsync(IRedbPermission permission, PermissionRequest request, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) => _permissionProvider.UpdatePermissionAsync(permission, request, currentUser, cancellationToken); public Task DeletePermissionAsync(IRedbPermission permission, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) => _permissionProvider.DeletePermissionAsync(permission, currentUser, cancellationToken); public Task> GetPermissionsByUserAsync(IRedbUser user, CancellationToken cancellationToken = default) => _permissionProvider.GetPermissionsByUserAsync(user, cancellationToken); public Task> GetPermissionsByRoleAsync(IRedbRole role, CancellationToken cancellationToken = default) => _permissionProvider.GetPermissionsByRoleAsync(role, cancellationToken); public Task> GetPermissionsByObjectAsync(IRedbObject obj, CancellationToken cancellationToken = default) => _permissionProvider.GetPermissionsByObjectAsync(obj, cancellationToken); public Task GetPermissionByIdAsync(long permissionId, CancellationToken cancellationToken = default) => _permissionProvider.GetPermissionByIdAsync(permissionId, cancellationToken); public Task CanUserEditObject(long objectId, long userId, CancellationToken cancellationToken = default) => _permissionProvider.CanUserEditObject(objectId, userId, cancellationToken); public Task CanUserSelectObject(long objectId, long userId, CancellationToken cancellationToken = default) => _permissionProvider.CanUserSelectObject(objectId, userId, cancellationToken); public Task CanUserInsertScheme(long schemeId, long userId, CancellationToken cancellationToken = default) => _permissionProvider.CanUserInsertScheme(schemeId, userId, cancellationToken); public Task CanUserDeleteObject(long objectId, long userId, CancellationToken cancellationToken = default) => _permissionProvider.CanUserDeleteObject(objectId, userId, cancellationToken); public Task GrantPermissionAsync(IRedbUser user, IRedbObject obj, PermissionAction actions, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) => _permissionProvider.GrantPermissionAsync(user, obj, actions, currentUser, cancellationToken); public Task GrantPermissionAsync(IRedbRole role, IRedbObject obj, PermissionAction actions, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) => _permissionProvider.GrantPermissionAsync(role, obj, actions, currentUser, cancellationToken); public Task RevokePermissionAsync(IRedbUser user, IRedbObject obj, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) => _permissionProvider.RevokePermissionAsync(user, obj, currentUser, cancellationToken); public Task RevokePermissionAsync(IRedbRole role, IRedbObject obj, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) => _permissionProvider.RevokePermissionAsync(role, obj, currentUser, cancellationToken); public Task RevokeAllUserPermissionsAsync(IRedbUser user, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) => _permissionProvider.RevokeAllUserPermissionsAsync(user, currentUser, cancellationToken); public Task RevokeAllRolePermissionsAsync(IRedbRole role, IRedbUser? currentUser = null, CancellationToken cancellationToken = default) => _permissionProvider.RevokeAllRolePermissionsAsync(role, currentUser, cancellationToken); public Task GetEffectivePermissionsAsync(IRedbUser user, IRedbObject obj, CancellationToken cancellationToken = default) => _permissionProvider.GetEffectivePermissionsAsync(user, obj, cancellationToken); public Task> GetEffectivePermissionsBatchAsync(IRedbUser user, IRedbObject[] objects, CancellationToken cancellationToken = default) => _permissionProvider.GetEffectivePermissionsBatchAsync(user, objects, cancellationToken); public Task> GetAllEffectivePermissionsAsync(IRedbUser user, CancellationToken cancellationToken = default) => _permissionProvider.GetAllEffectivePermissionsAsync(user, cancellationToken); public Task GetPermissionCountAsync(CancellationToken cancellationToken = default) => _permissionProvider.GetPermissionCountAsync(cancellationToken); public Task GetUserPermissionCountAsync(IRedbUser user, CancellationToken cancellationToken = default) => _permissionProvider.GetUserPermissionCountAsync(user, cancellationToken); public Task GetRolePermissionCountAsync(IRedbRole role, CancellationToken cancellationToken = default) => _permissionProvider.GetRolePermissionCountAsync(role, cancellationToken); // === IQueryableProvider DELEGATION === public IRedbQueryable Query() where TProps : class, new() => Queries.Query(); public IRedbQueryable Query(IRedbUser user) where TProps : class, new() => Queries.Query(user); public IRedbQueryable TreeQuery() where TProps : class, new() => Queries.TreeQuery(); public IRedbQueryable TreeQuery(IRedbUser user) where TProps : class, new() => Queries.TreeQuery(user); public IRedbQueryable TreeQuery(long rootObjectId, int? maxDepth = null) where TProps : class, new() => Queries.TreeQuery(rootObjectId, maxDepth); public IRedbQueryable TreeQuery(IRedbObject? rootObject, int? maxDepth = null) where TProps : class, new() => Queries.TreeQuery(rootObject, maxDepth); public IRedbQueryable TreeQuery(IEnumerable rootObjects, int? maxDepth = null) where TProps : class, new() => Queries.TreeQuery(rootObjects, maxDepth); public IRedbQueryable TreeQuery(IEnumerable rootObjectIds, int? maxDepth = null) where TProps : class, new() => Queries.TreeQuery(rootObjectIds, maxDepth); public IRedbQueryable TreeQuery(long rootObjectId, IRedbUser user, int? maxDepth = null) where TProps : class, new() => Queries.TreeQuery(rootObjectId, user, maxDepth); public IRedbQueryable TreeQuery(IRedbObject? rootObject, IRedbUser user, int? maxDepth = null) where TProps : class, new() => Queries.TreeQuery(rootObject, user, maxDepth); public IRedbQueryable TreeQuery(IEnumerable rootObjects, IRedbUser user, int? maxDepth = null) where TProps : class, new() => Queries.TreeQuery(rootObjects, user, maxDepth); public IRedbQueryable TreeQuery(IEnumerable rootObjectIds, IRedbUser user, int? maxDepth = null) where TProps : class, new() => Queries.TreeQuery(rootObjectIds, user, maxDepth); // === IValidationProvider DELEGATION === public Task> GetSupportedTypesAsync(CancellationToken cancellationToken = default) => _validationProvider.GetSupportedTypesAsync(cancellationToken); public Task ValidateTypeAsync(Type csharpType, string propertyName, CancellationToken cancellationToken = default) => _validationProvider.ValidateTypeAsync(csharpType, propertyName, cancellationToken); public Task ValidateSchemaAsync(string schemeName, bool strictDeleteExtra = true, CancellationToken cancellationToken = default) where TProps : class => _validationProvider.ValidateSchemaAsync(schemeName, strictDeleteExtra, cancellationToken); public ValidationIssue? ValidatePropertyConstraints(Type propertyType, string propertyName, bool isRequired, bool isArray) => _validationProvider.ValidatePropertyConstraints(propertyType, propertyName, isRequired, isArray); public Task ValidateSchemaAsync(IRedbScheme scheme, bool strictDeleteExtra = true, CancellationToken cancellationToken = default) where TProps : class => _validationProvider.ValidateSchemaAsync(scheme, strictDeleteExtra, cancellationToken); public Task AnalyzeSchemaChangesAsync(IRedbScheme scheme, CancellationToken cancellationToken = default) where TProps : class => _validationProvider.AnalyzeSchemaChangesAsync(scheme, cancellationToken); // === SECURITY CONTEXT MANAGEMENT === public void SetCurrentUser(IRedbUser user) => _securityContext.SetCurrentUser(user); public IDisposable CreateSystemContext() => _securityContext.CreateSystemContext(); public long GetEffectiveUserId() => _securityContext.GetEffectiveUserId(); // === CONFIGURATION MANAGEMENT === public void UpdateConfiguration(Action configure) { configure(_configuration); } public void UpdateConfiguration(Action configureBuilder) { // The providers hold this same configuration instance, so it is changed in place and never replaced. // Most builder steps edit the instance they were given, but ForIntegrationTesting starts from a fresh // copy: assigned here, it left this service on the new settings and every provider on the old ones. var builder = new RedbServiceConfigurationBuilder(_configuration); configureBuilder(builder); var built = builder.Build(); if (!ReferenceEquals(built, _configuration)) _configuration.CopyBehaviourFrom(built); } // === INITIALIZATION === /// /// Initialize REDB system at application startup. /// public async Task InitializeAsync(params Assembly[] assemblies) { // An empty database is named as such before any start-up query can fail on it: schema // creation is opt-in (ensureCreated), and without this check the module probe or the // scheme sync below surfaced a raw driver error ("relation _structures does not exist") // that said nothing about how to proceed. if (!await TableExistsAsync("_schemes")) throw new Exceptions.RedbSchemaMissingException(DatabaseTypeName); // 0. Verify v2-pvt SQL module is deployed (only for dialects that ship one). await EnsurePvtModuleDeployedAsync(); // 1. Polymorphic deserialization resolves scheme ids in this domain when no service is current for the flow // (by name: a static closure over this service kept it alive for the life of the process). SystemTextJsonRedbSerializer.SetInitializedDomain(_cacheDomain); // 1a. Problems of the schema that need a person: logged as errors at every start, listed by SchemaProblems. await CheckSchemaCoreAsync(logAll: true, CancellationToken.None); // 1b. Indexes the database lacks or has otherwise than a fresh one: reported, never built at start-up. await ReportIndexesOnStartAsync(); // 2-3. Sync all schemes with RedbSchemeAttribute, then the UserConfigurationProps scheme. Each sync takes the // schema lock itself, and only when it has something to write: a start with nothing changed takes no lock. await AutoSyncSchemesAsync(assemblies); await SyncSchemeAsync(); // 4. Initialize default user configuration // Disabled: config ID=-100 is for cache quotas, not needed for every DB // var configInitializer = new Configuration.DefaultUserConfigurationInitializer(this); // await configInitializer.InitializeAsync(); // 5. Initialize object factory RedbObjectFactory.Initialize(this); // 6. Set global provider for RedbObject RedbObject.SetSchemeSyncProvider(_schemeSync); // 7. Warmup metadata cache await WarmupMetadataCacheAsync(); // 8. Initialize GlobalPropsCache InitializePropsCache(); // 9. Initialize type registry for polymorphic operations await _treeProvider.InitializeTypeRegistryAsync(); } // === v2-pvt MODULE GUARD === /// /// Verifies that the v2-pvt SQL module is deployed at the version this /// dialect's bundle ships. A missing or older module is replaced by the /// embedded bundle automatically — so a simple `git pull` + restart /// upgrades the in-database UDFs without any manual `psql` / `sqlcmd` /// step. A newer module is never replaced: it is used when it serves this /// package (), and /// start-up stops with /// when it does not. Dialects that do not ship v2-pvt opt out by /// returning null from /// and this check becomes a no-op. /// protected virtual async Task EnsurePvtModuleDeployedAsync() { var versionFn = SqlDialect.Query_PvtModuleVersionFunction(); if (string.IsNullOrEmpty(versionFn)) return; var required = SqlDialect.Query_PvtRequiredVersion(); if (string.IsNullOrWhiteSpace(required)) return; string? deployed = null; try { deployed = await _context.ExecuteScalarAsync($"SELECT {versionFn}()"); } catch (Exception ex) when (Data.DbErrorClassifier.IsUndefinedFunction(ex)) { // Module missing entirely — fall through to deploy. } if (!string.IsNullOrWhiteSpace(deployed) && string.Equals(deployed, required, StringComparison.Ordinal)) { return; } if (Data.ModuleCompatibility.IsNewer(deployed, required)) { await AcceptNewerModuleAsync(deployed!, required); return; } // The operator asked that the schema be changed by the DBA only. Say so, with the script to // hand over, and touch nothing. if (!_configuration.AutoApplyDatabaseUpgrades) throw new Exceptions.RedbSchemaOutdatedException(DatabaseTypeName, deployed, required, cause: null); var bundleSql = ReadEmbeddedPvtBundleSql(); if (string.IsNullOrEmpty(bundleSql)) { throw new InvalidOperationException( $"v2-pvt module version mismatch: deployed='{deployed ?? ""}', required='{required}'. " + "The provider does not ship an embedded bundle; redeploy the SQL files manually " + "(redb.Postgres/sql/v2-pvt/*.sql for PostgreSQL or redb.MSSql/sql/v2-pvt/pvt_bundle.sql for SQL Server)."); } // Under the schema lock, and the version asked again under it: another node that met the same old database // may have deployed the bundle while this one waited. await using (await AcquireSchemaLockAsync()) { deployed = await ReadPvtModuleVersionAsync(versionFn); if (string.Equals(deployed, required, StringComparison.Ordinal)) { _logger?.LogInformation("v2-pvt module {Required} was deployed by another process while this one waited.", required); return; } // A node of a newer version deployed its module while this one waited. if (Data.ModuleCompatibility.IsNewer(deployed, required)) { await AcceptNewerModuleAsync(deployed!, required); return; } _logger?.LogInformation( "v2-pvt module {State} (deployed='{Deployed}', required='{Required}'); applying embedded bundle...", string.IsNullOrEmpty(deployed) ? "missing" : "out of date", deployed ?? "", required); try { await ExecuteSchemaScriptAsync(bundleSql); } catch (Exception ex) when (Data.DbErrorClassifier.IsInsufficientPrivilege(ex)) { // The connected role may run the application but not change the schema: the DBA granted // owner rights for the initial installation and took them back. That is a supported // deployment, not a fault, and it deserves an instruction rather than a driver error. // Any other failure of the bundle propagates as is — it is a defect, not a policy. throw new Exceptions.RedbSchemaOutdatedException(DatabaseTypeName, deployed, required, cause: ex); } catch (Exception ex) { // A process that does not take the schema lock (a build before it) finished the same bundle meanwhile. // The database is at the required version, which is all start-up needs. Anything else is a defect. if (!string.Equals(await TryReadPvtModuleVersionAsync(versionFn), required, StringComparison.Ordinal)) throw; _logger?.LogWarning(ex, "v2-pvt module bundle failed, but the database reports the required version {Required}: " + "another process deployed it concurrently. Start-up goes on.", required); return; } _logger?.LogInformation("v2-pvt module bundle applied."); ModuleStep = (true, deployed); // With every module upgrade, under the same lock. await EnsureRootStructureKeyAsync(); } } // The list lives per database (SchemaProblemRegistry), not per instance: the service is scoped, and the instance of // a health check is not the one that ran the start. /// public IReadOnlyList SchemaProblems => SchemaProblemRegistry.Get(_cacheDomain); /// public Task> CheckSchemaAsync(CancellationToken cancellationToken = default) // Asked again (a health check): only problems new to the database are logged. => CheckSchemaCoreAsync(logAll: false, cancellationToken); private async Task> CheckSchemaCoreAsync(bool logAll, CancellationToken cancellationToken) { var found = new List(); if (await IsRootStructureKeyMissingAsync()) found.AddRange(await Data.RootStructureKey.FindDuplicatesAsync(_context, SqlDialect, cancellationToken)); return SchemaProblemRegistry.Replace(_cacheDomain, found, logAll, _logger); } /// A problem met by a scheme sync: logged and listed unless already known for the database. private void ReportSchemaProblem(Models.RedbSchemaProblem problem) => SchemaProblemRegistry.Report(_cacheDomain, problem, _logger); /// /// Whether the engine needs the unique key of root structures () and the /// database lacks it. False on SQL Server, whose structure key holds for root rows already. /// protected async Task IsRootStructureKeyMissingAsync() { var existsSql = SqlDialect.Structures_RootKeyExists(); return existsSql != null && await _context.ExecuteScalarAsync(existsSql) == null; } /// /// Builds the unique key of root structures when it is missing, removing empty duplicates first. Called under the /// schema lock: by the module pass after the bundle (PostgreSQL), by the upgrade pass of the file (SQLite). /// protected async Task EnsureRootStructureKeyAsync() { if (!await IsRootStructureKeyMissingAsync()) return; await Data.RootStructureKey.EnsureAsync(_context, SqlDialect, await TableExistsAsync("_migrations"), _logger); } /// /// The database holds a module newer than this package's: never replaced. Used, with one warning per process, when /// it serves this package; otherwise start-up stops with . A newer /// module without the compatibility function states nothing and is treated as not serving. /// private async Task AcceptNewerModuleAsync(string deployed, string required) { var compatFn = SqlDialect.Query_PvtModuleCompatFunction(); string? compat = null; if (!string.IsNullOrEmpty(compatFn)) { try { compat = await _context.ExecuteScalarAsync($"SELECT {compatFn}()"); } catch (Exception ex) when (Data.DbErrorClassifier.IsUndefinedFunction(ex)) { compat = null; } } if (!Data.ModuleCompatibility.Serves(compat, required, out var fromPackage)) throw new Exceptions.RedbSchemaNewerException(DatabaseTypeName, deployed, required, fromPackage); WarnNewerOnce(DatabaseTypeName, deployed, required, _logger); } private static readonly HashSet NewerWarned = new(StringComparer.Ordinal); /// One warning per process for one newer module: every scoped service runs the start-up check. protected static void WarnNewerOnce(string provider, string deployed, string own, ILogger? logger) { lock (NewerWarned) { if (!NewerWarned.Add(provider + "|" + deployed + "|" + own)) return; } logger?.LogWarning( "The {Provider} database carries the redb module {Deployed}, newer than {Own} of this package; it serves this " + "package and was left as it is. Upgrade the redb packages of this application when convenient.", provider, deployed, own); } private async Task ReadPvtModuleVersionAsync(string versionFn) { try { return await _context.ExecuteScalarAsync($"SELECT {versionFn}()"); } catch (Exception ex) when (Data.DbErrorClassifier.IsUndefinedFunction(ex)) { return null; } } private async Task TryReadPvtModuleVersionAsync(string versionFn) { try { return await ReadPvtModuleVersionAsync(versionFn); } catch { return null; } } // === SCHEMA LOCK === /// /// The schema lock of this database, not yet taken (see ). A provider that has /// no way to lock returns a handle that always succeeds. /// protected abstract Task OpenSchemaLockAsync(CancellationToken cancellationToken); /// /// Takes the schema lock, waiting while another process holds it: one attempt every half second, a line in the log /// when the wait starts and every thirty seconds after, /// past . The work done under it asks its own precondition /// again: the process that held the lock has usually done it already. Disposing releases the lock. /// protected async Task AcquireSchemaLockAsync(CancellationToken cancellationToken = default) { // Asked again inside work already under the lock (RunUnderSchemaLockAsync), the lock is already this flow's: // a second one on a connection of its own would wait for the first. if (_holdsSchemaLock.Value) return Data.SchemaLockHandle.None; var handle = await OpenSchemaLockAsync(cancellationToken); try { var timeout = _configuration.SchemaLockTimeout; var waited = System.Diagnostics.Stopwatch.StartNew(); var nextReport = TimeSpan.Zero; while (!await handle.TryAcquireAsync(cancellationToken)) { if (waited.Elapsed >= timeout) throw new Exceptions.RedbSchemaLockTimeoutException(DatabaseTypeName, handle.Name, waited.Elapsed); if (waited.Elapsed >= nextReport) { _logger?.LogInformation( "The schema lock '{Lock}' is held by another process, most likely upgrading this database; " + "waiting ({Waited:mm\\:ss} of {Timeout}).", handle.Name, waited.Elapsed, timeout); nextReport = waited.Elapsed + TimeSpan.FromSeconds(30); } await Task.Delay(TimeSpan.FromMilliseconds(500), cancellationToken); } if (waited.Elapsed > TimeSpan.FromSeconds(1)) _logger?.LogInformation("The schema lock '{Lock}' taken after {Waited:mm\\:ss}.", handle.Name, waited.Elapsed); return handle; } catch { await handle.DisposeAsync(); throw; } } // True in the flow of work running under RunUnderSchemaLockAsync: the lock is held there, not to be taken again. private readonly AsyncLocal _holdsSchemaLock = new(); /// /// Runs under the schema lock (). Reentrant: called /// again from inside the work, it runs the inner work directly instead of waiting for the lock this flow holds. /// The schema sync of the schemes takes the lock through it when it has something to write. /// protected async Task RunUnderSchemaLockAsync(Func work, CancellationToken cancellationToken = default) { if (_holdsSchemaLock.Value) { await work(); return; } await using (await AcquireSchemaLockAsync(cancellationToken)) { // Set inside this method, the flag reaches the work it awaits and is gone when the method returns. _holdsSchemaLock.Value = true; await work(); } } // === DATABASE SCHEMA MANAGEMENT === /// /// Checks whether the specified table exists in the database. /// protected abstract Task TableExistsAsync(string tableName); /// /// Reads the embedded combined SQL initialization script (redb_init.sql). /// protected abstract string ReadEmbeddedSql(); /// /// Executes the full schema initialization SQL script against the database. /// Provider-specific: e.g. MSSQL splits by GO batch separators. /// protected abstract Task ExecuteSchemaScriptAsync(string sql); /// /// Returns the embedded v2-pvt module bundle (pvt_bundle.sql) or /// null when the provider doesn't ship a standalone bundle. /// Used by to auto-upgrade databases /// that were created before the v2-pvt module was added to /// redb_init.sql (so the full init script is skipped, but the /// module is still missing or outdated). /// protected virtual string? ReadEmbeddedPvtBundleSql() => null; /// public virtual async Task EnsureDatabaseAsync() { // Asked first without the lock: a database already created, nearly every start, takes no lock at all, and a // login that may not take it (a schema deployed by a DBA) starts. Only a missing schema goes to the lock, and // the question is asked again under it: nodes starting together against an empty database would otherwise all // run the creation script, and every one but the first fail on the tables it found. Exception? unreadable = null; bool exists; try { exists = await TableExistsAsync("_schemes"); } catch (Exception ex) when (IsDatabaseClosedForSchemaWork(ex)) { // Another node is creating the schema and holds the database alone for a moment (SQL Server turning on // READ_COMMITTED_SNAPSHOT): the answer comes under the lock, once that node is done. unreadable = ex; exists = false; } if (!exists) { IAsyncDisposable schemaLock; try { schemaLock = await AcquireSchemaLockAsync(); } catch when (unreadable != null) { // The lock could not be reached either: the first error says more (a wrong password fails both). System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(unreadable).Throw(); throw; } await using (schemaLock) { if (!await TableExistsAsync("_schemes")) { _logger?.LogInformation("REDB schema not found. Creating database schema..."); var sql = ReadEmbeddedSql(); await ExecuteSchemaScriptAsync(sql); _logger?.LogInformation("REDB database schema created successfully."); ModuleStep = (true, null); return; } } } // The module pass asks its own question first and takes the lock only when the module is behind. _logger?.LogInformation("REDB schema already exists, skipping creation."); await EnsurePvtModuleDeployedAsync(); } /// /// Whether an error of the first look at the database means that another process holds it alone for schema work, /// so the look is to be repeated under the schema lock. SQL Server refuses logins while /// ALTER DATABASE ... SET READ_COMMITTED_SNAPSHOT of a node creating the schema runs. /// protected virtual bool IsDatabaseClosedForSchemaWork(Exception exception) => false; /// public string GetSchemaScript() => ReadEmbeddedSql(); /// public string? GetUpgradeScript() => ReadEmbeddedPvtBundleSql(); /// public async Task InitializeAsync(bool ensureCreated, params Assembly[] assemblies) { if (ensureCreated) await EnsureDatabaseAsync(); await InitializeAsync(assemblies); } /// /// Warmup metadata cache. Override in derived classes for DB-specific SQL. /// protected virtual async Task WarmupMetadataCacheAsync() { if (!_configuration.WarmupMetadataCacheOnInit) return; try { var sw = System.Diagnostics.Stopwatch.StartNew(); var warmupSql = SqlDialect.Warmup_AllMetadataCaches(); var result = await _context.QueryAsync(warmupSql); sw.Stop(); if (result.Any()) { _logger?.LogInformation( "Metadata cache warmed up: {SchemeCount} schemes, {StructureCount} structures in {ElapsedMs} ms", result.Count, result.Sum(r => r.structures_count), sw.ElapsedMilliseconds); } } catch (Exception ex) { _logger?.LogWarning(ex, "Failed to warmup metadata cache during initialization"); } } /// /// Initialize GlobalPropsCache. /// private void InitializePropsCache() { if (!_configuration.EnablePropsCache) return; // The cache lives for the process: nothing scoped (a user, a configuration service) is captured into it. // Its logger is how a production host learns that the cache is too small or its hits are slow. var cache = new Caching.MemoryRedbObjectCache( maxSize: _configuration.PropsCacheMaxSize, ttl: _configuration.PropsCacheTtl, logger: _serviceProvider.GetService()?.CreateLogger(typeof(Caching.MemoryRedbObjectCache).FullName!)); // A cached graph carries nothing scope-bound: its stubs load on the reader's scope (owner decision 2026-09-15). _schemeSync.PropsCache.Initialize(cache); } /// /// Auto-sync all schemes with RedbSchemeAttribute. /// private async Task AutoSyncSchemesAsync(params Assembly[] assemblies) { IEnumerable assembliesToScan = assemblies.Length > 0 ? assemblies : GetAllLoadedAssemblies(); var typesToSync = assembliesToScan .SelectMany(GetTypesWithRedbSchemeAttribute) .ToList(); if (typesToSync.Count == 0) return; // Pre-flight: validate ALL explicit scheme names up front. A bad name is fatal by design // (a scheme with an invalid name must not boot), but failing on the first offender hides the // rest — the developer fixes one, reruns, hits the next. Reporting the full list in one // AggregateException lets them fix everything in a single pass (H2). var nameErrors = new List(); foreach (var type in typesToSync) { var explicitName = type.GetCustomAttribute()?.Name; if (!string.IsNullOrWhiteSpace(explicitName) && !SchemeNameValidator.IsValid(explicitName, out var reason)) nameErrors.Add(new RedbSchemeNameException(type, explicitName, reason!)); } if (nameErrors.Count == 1) throw nameErrors[0]; if (nameErrors.Count > 1) throw new AggregateException( $"{nameErrors.Count} types declare invalid explicit scheme names — fix all of them:", nameErrors); foreach (var type in typesToSync) { await SyncSchemeForTypeAsync(type); } } private static IEnumerable GetAllLoadedAssemblies() { return AssemblyLoadContext.Default.Assemblies; } private static IEnumerable GetTypesWithRedbSchemeAttribute(Assembly assembly) { try { return assembly.GetTypes() .Where(t => t.GetCustomAttribute() != null); } catch (ReflectionTypeLoadException ex) { return ex.Types .Where(t => t != null && t.GetCustomAttribute() != null)!; } catch { return Enumerable.Empty(); } } private async Task SyncSchemeForTypeAsync(Type type) { try { var method = typeof(ISchemeSyncProvider) .GetMethod(nameof(ISchemeSyncProvider.SyncSchemeAsync)) ?.MakeGenericMethod(type); if (method != null) { var task = method.Invoke(this, new object[] { CancellationToken.None }); // the generic overload takes a token now if (task is Task asyncTask) { await asyncTask; } } } catch (Exception ex) { _logger?.LogError(ex, "Failed to sync scheme for type '{TypeName}'", type.FullName); throw; } } } /// /// Result from warmup_all_metadata_caches() SQL function. /// internal class WarmupCacheResult { public long scheme_id { get; set; } public long structures_count { get; set; } public string? scheme_name { get; set; } }