Path: redb/redb.Core/Providers/Base/ObjectStorageProviderBase.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/Providers/Base/ObjectStorageProviderBase.cs ---- #pragma warning disable CS0618 // implements or uses the deprecated object permissions and roles (RedbDeprecation) using redb.Core.Providers; using redb.Core.Data; using redb.Core.Utils; using redb.Core.Extensions; using redb.Core.Serialization; using redb.Core.Query; using redb.Core.Services; using System.Text.Json; using System.Text.Json.Serialization; using System.Text.Encodings.Web; using System.Threading; using System.Threading.Tasks; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Models.Configuration; using System.Reflection; using System.Collections.Generic; using System.Linq; using redb.Core.Exceptions; using System; using redb.Core.Caching; using Microsoft.Extensions.Logging; namespace redb.Core.Providers.Base { /// /// Base abstract class for ObjectStorageProvider with database-agnostic business logic. /// SQL queries are abstracted via ISqlDialect for PostgreSQL/MSSQL/etc support. /// public abstract partial class ObjectStorageProviderBase : IObjectStorageProvider { protected readonly IRedbContext _context; private readonly IRedbObjectSerializer _serializer; private readonly IPermissionProvider _permissionProvider; private readonly IRedbSecurityContext _securityContext; private readonly ISchemeSyncProvider _schemeSync; private readonly RedbServiceConfiguration _configuration; private readonly IListProvider? _listProvider; private readonly ISqlDialect _sql; private readonly ILogger? _logger; /// /// Domain-bound metadata cache for this provider. /// protected GlobalMetadataCache Cache => _schemeSync.Cache; /// /// Domain-bound props cache for this provider. /// protected GlobalPropsCache PropsCache => _schemeSync.PropsCache; /// /// Creates a new ObjectStorageProviderBase instance. /// protected ObjectStorageProviderBase( IRedbContext context, IRedbObjectSerializer serializer, IPermissionProvider permissionProvider, IRedbSecurityContext securityContext, ISchemeSyncProvider schemeSync, RedbServiceConfiguration configuration, ISqlDialect sql, IListProvider? listProvider = null, ILogger? logger = null, Interception.RedbSaveInterceptorPipeline? saveInterceptors = null) { _context = context; _serializer = serializer; _permissionProvider = permissionProvider; _securityContext = securityContext; _schemeSync = schemeSync; _configuration = configuration ?? new RedbServiceConfiguration(); _sql = sql; _listProvider = listProvider; _logger = logger; _saveInterceptors = saveInterceptors ?? Interception.RedbSaveInterceptorPipeline.Empty; } /// /// Save-pipeline interceptors (discussion #12, п.3-4): DI registrations plus run-time subscriptions. Every save /// and delete takes ONE snapshot at its start and uses it for both of its hooks, so a subscription that comes /// or goes meanwhile never gets a Saved without its Saving. An empty snapshot = zero cost: nothing is collected. /// private readonly Interception.RedbSaveInterceptorPipeline _saveInterceptors; /// The interceptors of the operation that starts now. Empty when nobody listens. protected IReadOnlyList SnapshotSaveInterceptors() => _saveInterceptors.Snapshot(); /// /// The change feed for the current save, or null when nobody listens. The base opens it /// before the strategy runs (ChangeTracking only); the Pro diff fills it; the base hands /// it to . Single-threaded by the /// one-scope-one-save contract (CT-4). /// protected List? InterceptorChangeSink; protected static async Task InvokeSavingInterceptorsAsync( IReadOnlyList interceptors, Interception.RedbSavingContext ctx, CancellationToken cancellationToken) { foreach (var interceptor in interceptors) await interceptor.SavingAsync(ctx, cancellationToken); } protected static async Task InvokeSavedInterceptorsAsync( IReadOnlyList interceptors, Interception.RedbSavedContext ctx, CancellationToken cancellationToken) { foreach (var interceptor in interceptors) await interceptor.SavedAsync(ctx, cancellationToken); } private static async Task InvokeDeletingInterceptorsAsync( IReadOnlyList interceptors, Interception.RedbDeletingContext ctx, CancellationToken cancellationToken) { foreach (var interceptor in interceptors) await interceptor.DeletingAsync(ctx, cancellationToken); } private static async Task InvokeDeletedInterceptorsAsync( IReadOnlyList interceptors, Interception.RedbDeletedContext ctx, CancellationToken cancellationToken) { foreach (var interceptor in interceptors) await interceptor.DeletedAsync(ctx, cancellationToken); } // Protected properties for derived classes protected IRedbContext Context => _context; protected IRedbObjectSerializer Serializer => _serializer; protected ISchemeSyncProvider SchemeSyncProvider => _schemeSync; protected RedbServiceConfiguration Configuration => _configuration; protected IListProvider? ListProvider => _listProvider; protected ISqlDialect Sql => _sql; protected IPermissionProvider PermissionProvider => _permissionProvider; protected IRedbSecurityContext SecurityContext => _securityContext; protected ILogger? Logger => _logger; /// /// Creates a LazyPropsLoader instance. Override in derived classes for custom implementations (e.g., ProLazyPropsLoader). /// protected abstract ILazyPropsLoader CreateLazyPropsLoader(); // ===== BASIC METHODS (use _securityContext and configuration) ===== /// /// Load object from EAV by ID (uses _securityContext and config.DefaultCheckPermissionsOnLoad) /// Returns null if object not found and config.ThrowOnObjectNotFound = false /// public async Task?> LoadAsync(long objectId, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() { var effectiveUser = _securityContext.GetEffectiveUser(); return await LoadAsync(objectId, effectiveUser, depth, cancellationToken); } /// /// Load object from EAV (uses _securityContext and config.DefaultCheckPermissionsOnLoad) /// Returns null if object not found and config.ThrowOnObjectNotFound = false /// public async Task?> LoadAsync(IRedbObject obj, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() { var effectiveUser = _securityContext.GetEffectiveUser(); return await LoadAsync(obj.Id, effectiveUser, depth, cancellationToken); } /// /// Load object from EAV with explicitly specified user (uses config.DefaultCheckPermissionsOnLoad) /// Returns null if object not found and config.ThrowOnObjectNotFound = false /// public async Task?> LoadAsync(IRedbObject obj, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() { return await LoadAsync(obj.Id, user, depth, cancellationToken); } // ===== OVERLOADS WITH EXPLICIT USER ===== /// /// MAIN loading method - all other LoadAsync methods call it /// Returns null if object not found and config.ThrowOnObjectNotFound = false /// /// /// Checks whether a loaded object's scheme matches the scheme maps to. /// Returns true when it matches (or when the type has no known scheme yet — nothing to compare /// against). On a mismatch the behaviour depends on ThrowOnSchemeMismatch: by default returns /// false so the caller returns null (a soft-deleted object, scheme -10, reads as /// null); when the flag is set, throws . /// Either way garbage never reaches the cache — the check runs before any caching. /// private async Task IsSchemeValidForLoadAsync(long objectId, long actualSchemeId) where TProps : class, new() { // Expected scheme_id for TProps: fast per-domain projection first, then a lazy resolve that // also warms the projection. Null → the type has no scheme yet; accept rather than block loads. var expected = Cache.GetSchemeIdByClrType(typeof(TProps)); if (expected == null) { var scheme = await _schemeSync.GetSchemeByTypeAsync(); expected = scheme?.Id; } if (!expected.HasValue || expected.Value == actualSchemeId) return true; if (_configuration.ThrowOnSchemeMismatch) throw new Exceptions.RedbSchemeMismatchException(objectId, typeof(TProps), expected.Value, actualSchemeId); return false; // soft default: caller returns null instead of garbage } public async Task?> LoadAsync(long objectId, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() { // Permission check according to configuration if (_configuration.DefaultCheckPermissionsOnLoad) { var canRead = await _permissionProvider.CanUserSelectObject(objectId, user.Id); if (!canRead) { throw new UnauthorizedAccessException($"User {user.Id} has no read permission for object {objectId}"); } } // === EAGER LOADING: Full loading via get_object_json with cache === // OPTIMIZATION for SkipHashValidationOnCacheCheck: check cache first without DB query. // NEVER inside an active transaction (explicit or ambient): a load there is the read of // a read-modify-write - the caller has just taken LockForUpdateAsync and expects the // database's current row, and a pre-lock cached copy is exactly the lost update the // lock exists to prevent (bug report п.1, 2026-09-02). Inside a transaction the load // falls through to the hash-validated path: one indexed SELECT _id,_hash under the lock. if (_configuration.EnablePropsCache && _configuration.SkipHashValidationOnCacheCheck && PropsCache.Instance != null && !_context.IsInTransaction) { var cachedObj = PropsCache.GetWithoutHashValidation(objectId); if (cachedObj != null) { // Cache HIT WITHOUT DB query - return cached object return cachedObj; } } // Cache MISS or hash check enabled - query ID + Hash (+ scheme, for the scheme-match guard // below) to distinguish "object not found" and "hash=null". The probe stays this narrow // on purpose: _hash covers the whole row (header included, see RedbHash), so a match // vouches for the cached object as a whole - no need to read _note/_value_bytes here. var eagerBaseObj = await _context.QueryFirstOrDefaultAsync( Sql.ObjectStorage_SelectIdHashScheme(), new object[] { objectId }, cancellationToken); if (eagerBaseObj == null) { if (_configuration.ThrowOnObjectNotFound) throw new InvalidOperationException($"Object with ID {objectId} not found"); return null; } // Guard against loading an object under the wrong Props type (garbage + cache poisoning). // Mismatch → null by default (soft-deleted scheme -10 reads as null), or throws under the flag. if (!await IsSchemeValidForLoadAsync(objectId, eagerBaseObj.IdScheme)) return null; // Object found, but hash may be null var objectHash = eagerBaseObj.Hash; // Check cache only if hash is NOT null AND validation is not skipped if (_configuration.EnablePropsCache && !_configuration.SkipHashValidationOnCacheCheck && PropsCache.Instance != null && objectHash.HasValue) { var cachedObj = PropsCache.Get(objectId, objectHash.Value); if (cachedObj != null && !await IsCachedGraphCurrentAsync(cachedObj, sync: false, cancellationToken)) { PropsCache.Remove(objectId); cachedObj = null; } if (cachedObj != null) { // Cache HIT - the hash vouches for header and Props alike (cluster review, // 2026-09-11: a save on another node moves _hash whichever part it touched) return cachedObj; } } // Cache MISS - load via get_object_json return await LoadEagerAsync(objectId, depth, cancellationToken); } public Task LoadJsonAsync(long objectId, int depth = 10, CancellationToken cancellationToken = default) => LoadJsonAsync(objectId, _securityContext.GetEffectiveUser(), depth, cancellationToken); public async Task LoadJsonAsync(long objectId, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) { if (_configuration.DefaultCheckPermissionsOnLoad) { var canRead = await _permissionProvider.CanUserSelectObject(objectId, user.Id); if (!canRead) throw new UnauthorizedAccessException($"User {user.Id} has no read permission for object {objectId}"); } // Straight to the in-database materializer. No PropsCache (it is keyed by CLR type, // and there is none here) and no scheme guard (nothing to compare a scheme against); // Pro keeps this path too - _values stays the source of truth on every tier. var json = await _context.ExecuteJsonAsync(Sql.ObjectStorage_GetObjectJson(), new object[] { objectId, depth }, cancellationToken); if (string.IsNullOrEmpty(json)) { if (_configuration.ThrowOnObjectNotFound) throw new InvalidOperationException($"Object with ID {objectId} not found"); return null; } return json; } /// /// Virtual method for EAGER loading of Props. /// Open Source: uses get_object_json /// Pro: overrides for PVT approach /// protected virtual async Task?> LoadEagerAsync(long objectId, int depth, CancellationToken cancellationToken) where TProps : class, new() { var json = await _context.ExecuteJsonAsync( Sql.ObjectStorage_GetObjectJson(), new object[] { objectId, depth }, cancellationToken); return MaterializeLoadedJson(objectId, json); } /// /// Synchronous twin of for the thread-pool-free . /// Open Source: get_object_json. Pro: overrides with its materializer run synchronously. /// protected virtual RedbObject? LoadEager(long objectId, int depth) where TProps : class, new() { var json = _context.ExecuteJson(Sql.ObjectStorage_GetObjectJson(), objectId, depth); return MaterializeLoadedJson(objectId, json); } /// /// The CPU half of an eager load, shared by the async path and the sync (thread-pool-free) /// path: deserialize, install lazy loaders, cache. /// private RedbObject? MaterializeLoadedJson(long objectId, string? json) where TProps : class, new() { if (string.IsNullOrEmpty(json)) { if (_configuration.ThrowOnObjectNotFound) throw new InvalidOperationException($"Object with ID {objectId} not found"); return null; } // Deserialize JSON into RedbObject var loadedObj = _serializer.Deserialize(json); // V4 (L.3): boundary stubs get their loader - BEFORE the cache Set, so the Set marks // every stub of the now shared graph and drops its origin: a shared instance loads on // the reader's scope only (owner decision 2026-09-15). Utils.LazyReferenceInstaller.Install(loadedObj, CreateLazyPropsLoader()); // Put main object + ALL nested RedbObject into cache - once the transaction commits: until then the // graph is the reader's own (CachePublication). if (_configuration.EnablePropsCache && PropsCache.Instance != null && loadedObj.hash.HasValue) { Caching.CachePublication.AfterCommit(_context, () => { // One walk: the graph is marked shared and every nested RedbObject is cached by its own id // (they are already in memory after deserialization). PropsCache.SetGraph(loadedObj); }); } return loadedObj; } /// /// Synchronous eager load for the thread-pool-free lazy path (the sync getter of /// RedbListItem.Object): the same sequence as the main LoadAsync - permission check, /// props-cache probes, id/hash/scheme row, get_object_json - but every database call runs /// on the calling thread down to ADO.NET, so a saturated thread pool cannot slow or /// deadlock the load. /// public virtual RedbObject? Load(long objectId, int depth = 10) where TProps : class, new() { var user = _securityContext.GetEffectiveUser(); if (_configuration.DefaultCheckPermissionsOnLoad) { if (!_permissionProvider.CanUserSelectObjectSync(objectId, user.Id)) throw new UnauthorizedAccessException($"User {user.Id} has no read permission for object {objectId}"); } // Same cache discipline as the async path, including the in-transaction bypass. if (_configuration.EnablePropsCache && _configuration.SkipHashValidationOnCacheCheck && PropsCache.Instance != null && !_context.IsInTransaction) { var cachedObj = PropsCache.GetWithoutHashValidation(objectId); if (cachedObj != null) return cachedObj; } var eagerBaseObj = _context.QueryFirstOrDefault( Sql.ObjectStorage_SelectIdHashScheme(), objectId); if (eagerBaseObj == null) { if (_configuration.ThrowOnObjectNotFound) throw new InvalidOperationException($"Object with ID {objectId} not found"); return null; } // Scheme guard, cache-only: the async path would resolve a cold CLR-type projection // through the scheme-sync provider; here the only caller is the linked-object loader, // which picked TProps FROM the object's scheme id, so on a cold projection the pair // matches by construction and the load is accepted. var expected = Cache.GetSchemeIdByClrType(typeof(TProps)); if (expected.HasValue && expected.Value != eagerBaseObj.IdScheme) { if (_configuration.ThrowOnSchemeMismatch) throw new Exceptions.RedbSchemeMismatchException(objectId, typeof(TProps), expected.Value, eagerBaseObj.IdScheme); return null; } var objectHash = eagerBaseObj.Hash; if (_configuration.EnablePropsCache && !_configuration.SkipHashValidationOnCacheCheck && PropsCache.Instance != null && objectHash.HasValue) { var cachedObj = PropsCache.Get(objectId, objectHash.Value); if (cachedObj != null && !IsCachedGraphCurrentAsync(cachedObj, sync: true, CancellationToken.None).GetAwaiter().GetResult()) { PropsCache.Remove(objectId); cachedObj = null; } if (cachedObj != null) return cachedObj; } return LoadEager(objectId, depth); } /// /// Whether a cached object whose own hash matched its row may be served with the graph it holds. Its hash does /// not move when an object it references changes or leaves for the trash, on this node or any other, so the /// loaded references are checked against their rows: a missing row, a row of the trash scheme and a moved /// hash all make the graph stale. With every database call runs on the calling thread /// and the task is complete on return. /// protected virtual Task IsCachedGraphCurrentAsync(IRedbObject cached, bool sync, CancellationToken cancellationToken) { // Only the references matter: the caller has already compared this object's own hash with its row. var references = GetLoadedReferences(cached); references.Remove(cached.Id); if (references.Count == 0) return Task.FromResult(true); var ids = references.Keys.ToArray(); var sql = Sql.ObjectStorage_SelectObjectsByIds(); if (sync) return Task.FromResult(IsGraphCurrent(references, _context.Query(sql, new object[] { ids }))); return IsGraphCurrentAsync(sql, ids, references, cancellationToken); } private async Task IsGraphCurrentAsync(string sql, long[] ids, Dictionary references, CancellationToken cancellationToken) { var rows = await _context.QueryAsync(sql, new object[] { ids }, cancellationToken); return IsGraphCurrent(references, rows); } private static bool IsGraphCurrent(Dictionary references, List rows) { var byId = new Dictionary(rows.Count); foreach (var row in rows) byId[row.Id] = row; return IsGraphCurrent(references, byId); } private static bool IsGraphCurrent(Dictionary references, Dictionary byId) { foreach (var (id, hash) in references) { if (!byId.TryGetValue(id, out var row)) return false; // the target is gone if (row.IdScheme == RedbTypeIds.DeletedScheme) return false; // the target left for the trash if (row.Hash != hash) return false; // the target changed } return true; } /// /// The ids of the cached graphs that hold at least one stale reference. All graphs are checked in one query: /// the bulk load hands over every object a cache hit returned, and one statement per object would be the /// price of every list read under the props cache. /// private async Task> FindStaleCachedGraphsAsync(IEnumerable cachedObjects, CancellationToken cancellationToken) { var perRoot = new Dictionary>(); var all = new Dictionary(); foreach (var obj in cachedObjects) { var references = GetLoadedReferences(obj); references.Remove(obj.Id); if (references.Count == 0) continue; perRoot[obj.Id] = references; foreach (var (id, hash) in references) all[id] = hash; } var stale = new HashSet(); if (all.Count == 0) return stale; var ids = all.Keys.ToArray(); var rows = await _context.QueryAsync( Sql.ObjectStorage_SelectObjectsByIds(), new object[] { ids }, cancellationToken); var byId = new Dictionary(rows.Count); foreach (var row in rows) byId[row.Id] = row; foreach (var (rootId, references) in perRoot) if (!IsGraphCurrent(references, byId)) stale.Add(rootId); return stale; } /// /// The loaded objects a cached graph vouches for beyond its root, by id with the hash each was loaded with. /// The walk comes from : it visits the loaded part of Props, never a stub and /// never a leaf getter (a list item's Object getter would load its target on read). /// private static Dictionary GetLoadedReferences(IRedbObject root) => LoadedGraphInspector.CollectLoadedReferences( root.GetType().GetMethod("GetPropsDirectly", Type.EmptyTypes)?.Invoke(root, null)); /// /// Save single object via interface. Type determined internally. /// public async Task SaveAsync(IRedbObject obj, CancellationToken cancellationToken = default) { var effectiveUser = _securityContext.GetEffectiveUser(); return await SaveAsync(obj, effectiveUser, cancellationToken); } /// /// Save single object via interface with explicit user. /// public async Task SaveAsync(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) { var results = await SaveAsync(new[] { obj }, user, cancellationToken); return results.FirstOrDefault(); } public async Task SaveAsync(IRedbObject obj, CancellationToken cancellationToken = default) where TProps : class, new() { var effectiveUser = _securityContext.GetEffectiveUser(); return await SaveAsync(obj, effectiveUser, cancellationToken); } public async Task DeleteAsync(IRedbObject obj, CancellationToken cancellationToken = default) { var effectiveUser = _securityContext.GetEffectiveUser(); return await DeleteAsync(obj, effectiveUser, cancellationToken); } /// /// Deletes an object from the database using atomic ExecuteDeleteAsync. /// Thread-safe and handles concurrent delete attempts gracefully. /// public async Task DeleteAsync(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) { // Permission check according to configuration if (_configuration.DefaultCheckPermissionsOnDelete) { var canDelete = await _permissionProvider.CanUserDeleteObject(obj, user); if (!canDelete) { throw new UnauthorizedAccessException($"User {user.Id} has no delete permission for object {obj.Id}"); } } // Interceptors (owner decision: deletes are covered too). Deleting before the SQL - // an exception cancels the delete; Deleted after it, only when a row actually went. var interceptors = SnapshotSaveInterceptors(); if (interceptors.Count > 0) { await InvokeDeletingInterceptorsAsync(interceptors, new Interception.RedbDeletingContext { ObjectIds = [obj.Id], KnownObjects = [obj], EffectiveUser = user, }, cancellationToken); } // Atomic delete via SQL - single query, no race condition var deletedCount = await _context.ExecuteAsync( Sql.ObjectStorage_DeleteById(), new object[] { obj.Id }, cancellationToken); if (deletedCount == 0) { return false; // Object did not exist or was already deleted } if (interceptors.Count > 0) { await InvokeDeletedInterceptorsAsync(interceptors, new Interception.RedbDeletedContext { ObjectIds = [obj.Id], KnownObjects = [obj], EffectiveUser = user, DeletedCount = deletedCount, }, CancellationToken.None); // the row is gone - cancelling the notification would lie (s3.3) } // === CACHE INVALIDATION === if (_configuration.EnablePropsCache && PropsCache.Instance != null) { PropsCache.Remove(obj.Id); } // === ID RESET STRATEGY === if (_configuration.IdResetStrategy == redb.Core.Models.Configuration.ObjectIdResetStrategy.AutoResetOnDelete) { obj.ResetId(); // Automatically reset ID } return true; } // ===== DELETION BY ID ===== /// /// Delete object by ID (uses _securityContext) /// public async Task DeleteAsync(long objectId, CancellationToken cancellationToken = default) { var effectiveUser = _securityContext.GetEffectiveUser(); return await DeleteAsync(objectId, effectiveUser, cancellationToken); } /// /// Delete object by ID with explicit user /// public async Task DeleteAsync(long objectId, IRedbUser user, CancellationToken cancellationToken = default) { var deletedCount = await DeleteAsync(new[] { objectId }, user, cancellationToken); return deletedCount > 0; } // ===== BULK DELETION BY ID ===== /// /// Bulk deletion of objects by ID (uses _securityContext) /// public async Task DeleteAsync(IEnumerable objectIds, CancellationToken cancellationToken = default) { var effectiveUser = _securityContext.GetEffectiveUser(); return await DeleteAsync(objectIds, effectiveUser, cancellationToken); } /// /// Bulk deletion of objects by ID with explicit user /// public async Task DeleteAsync(IEnumerable objectIds, IRedbUser user, CancellationToken cancellationToken = default) => await DeleteByIdsCoreAsync(objectIds.ToList(), user, knownObjects: [], cancellationToken); /// /// The id-batch funnel. carries the instances when the /// caller had them (the delete-by-object overload), so interceptors see more than ids. /// private async Task DeleteByIdsCoreAsync(List ids, IRedbUser user, IReadOnlyList knownObjects, CancellationToken cancellationToken) { if (ids.Count == 0) return 0; // Permission check according to configuration if (_configuration.DefaultCheckPermissionsOnDelete) { foreach (var id in ids) { var canDelete = await _permissionProvider.CanUserDeleteObject(id, user.Id); if (!canDelete) { throw new UnauthorizedAccessException($"User {user.Id} has no delete permission for object {id}"); } } } var interceptors = SnapshotSaveInterceptors(); if (interceptors.Count > 0) { await InvokeDeletingInterceptorsAsync(interceptors, new Interception.RedbDeletingContext { ObjectIds = ids, KnownObjects = knownObjects, EffectiveUser = user, }, cancellationToken); } // Bulk delete via SQL (single query with ANY), counting every object of the batch it deleted. var deletedCount = await ObjectDeleteByIds.RunAsync(_context, Sql, ids.ToArray(), cancellationToken); // === CACHE INVALIDATION (ALWAYS) === if (PropsCache.Instance != null) { foreach (var id in ids) { PropsCache.Remove(id); } } if (interceptors.Count > 0 && deletedCount > 0) { await InvokeDeletedInterceptorsAsync(interceptors, new Interception.RedbDeletedContext { ObjectIds = ids, KnownObjects = knownObjects, EffectiveUser = user, DeletedCount = deletedCount, }, CancellationToken.None); // rows are gone - cancelling the notification would lie (s3.3) } return deletedCount; } // ===== BULK DELETION BY INTERFACE ===== /// /// Bulk deletion of objects by interface (uses _securityContext) /// public async Task DeleteAsync(IEnumerable objects, CancellationToken cancellationToken = default) { var effectiveUser = _securityContext.GetEffectiveUser(); return await DeleteAsync(objects, effectiveUser, cancellationToken); } /// /// Bulk deletion of objects by interface with explicit user /// public async Task DeleteAsync(IEnumerable objects, IRedbUser user, CancellationToken cancellationToken = default) { var objList = objects.ToList(); if (objList.Count == 0) return 0; var ids = objList.Select(o => o.Id).ToList(); // The id funnel, with the instances handed through so interceptors see the objects. var deletedCount = await DeleteByIdsCoreAsync(ids, user, objList, cancellationToken); // === ID RESET STRATEGY === if (_configuration.IdResetStrategy == redb.Core.Models.Configuration.ObjectIdResetStrategy.AutoResetOnDelete) { foreach (var obj in objList) { obj.ResetId(); } } return deletedCount; } // ===== SOFT DELETE (BACKGROUND DELETION) ===== /// /// Mark objects for soft-deletion (uses _securityContext). /// Creates a trash container and moves objects and their descendants under it. /// public async Task SoftDeleteAsync(IEnumerable objectIds, long? trashParentId = null, CancellationToken cancellationToken = default) { var effectiveUser = _securityContext.GetEffectiveUser(); return await SoftDeleteAsync(objectIds, effectiveUser, trashParentId, cancellationToken); } /// /// Mark objects for soft-deletion with explicit user. /// Creates a trash container and moves objects and their descendants under it. /// public async Task SoftDeleteAsync(IEnumerable objectIds, IRedbUser user, long? trashParentId = null, CancellationToken cancellationToken = default) { var ids = objectIds.ToArray(); // mark_for_deletion writes behind a query: an outer transaction has written from here on. Data.TransactionWrites.Mark(_context); if (ids.Length == 0) return new DeletionMark(0, 0); // Check permissions if configured if (_configuration.DefaultCheckPermissionsOnDelete) { foreach (var id in ids) { var canDelete = await _permissionProvider.CanUserDeleteObject(id, user.Id); if (!canDelete) { throw new UnauthorizedAccessException($"User {user.Id} does not have permission to delete object {id}"); } } } // Call the SQL function to mark objects for deletion. One transaction around it, joining // the caller's when there is one: the SQLite mark is several statements, and a failure // between them is rolled back by the transaction's owner, never left open on the handle. // Run again on a deadlock when this transaction is our own (DeadlockRetryHelper). var results = await DeadlockRetryHelper.ExecuteWithRetryAsync(_context, () => _context.ExecuteAtomicAsync( () => _context.QueryAsync( Sql.SoftDelete_MarkForDeletion(), new object[] { ids, user.Id, trashParentId! }, cancellationToken), cancellationToken), cancellationToken: cancellationToken); var result = results.FirstOrDefault() ?? throw new InvalidOperationException("mark_for_deletion function returned no result"); // Invalidate cache for all marked objects if (_configuration.EnablePropsCache && PropsCache.Instance != null) { foreach (var id in ids) { PropsCache.Remove(id); } } _logger?.LogInformation( "Soft-deleted {Count} objects (including descendants). TrashId={TrashId}, User={UserId}", result.marked_count, result.trash_id, user.Id); return new DeletionMark(result.trash_id, (int)result.marked_count); } /// /// Mark objects for soft-deletion (uses _securityContext). /// Creates a trash container and moves objects and their descendants under it. /// public Task SoftDeleteAsync(IEnumerable objects, long? trashParentId = null, CancellationToken cancellationToken = default) { return SoftDeleteAsync(objects.Select(o => o.Id), trashParentId, cancellationToken); } /// /// Mark objects for soft-deletion with explicit user. /// Creates a trash container and moves objects and their descendants under it. /// public Task SoftDeleteAsync(IEnumerable objects, IRedbUser user, long? trashParentId = null, CancellationToken cancellationToken = default) { return SoftDeleteAsync(objects.Select(o => o.Id), user, trashParentId, cancellationToken); } /// /// Delete objects with background purge and progress reporting. /// Marks objects for deletion, then purges them in batches with progress callback. /// public async Task DeleteWithPurgeAsync( IEnumerable objectIds, int batchSize = 10, IProgress? progress = null, CancellationToken cancellationToken = default, long? trashParentId = null) { // Step 1: Mark for deletion (fast, atomic) var mark = await SoftDeleteAsync(objectIds, trashParentId, cancellationToken); if (mark.MarkedCount == 0) return; // Step 2: Purge in batches with progress await PurgeTrashAsync(mark.TrashId, mark.MarkedCount, batchSize, progress, cancellationToken); } /// /// Purge a trash container created by SoftDeleteAsync. /// Physically deletes objects in batches with progress callback. /// public async Task PurgeTrashAsync( long trashId, int totalCount, int batchSize = 10, IProgress? progress = null, CancellationToken cancellationToken = default) { var effectiveUser = _securityContext.GetEffectiveUser(); var deleted = 0; var startedAt = DateTimeOffset.UtcNow; // The purge function writes behind a query: an outer transaction has written from here on. Data.TransactionWrites.Mark(_context); // Unified cancellation semantics (owner decision, 2026-09-08): cancellation is OCE // here like everywhere else - the historical soft return is gone. The token gates // every batch boundary and rides into the purge command itself; a farewell progress // report with PurgeStatus.Cancelled still fires so a UI shows where the purge // stopped. Each purge_trash batch commits on its own, so nothing is lost - the // remainder stays queued in the database and the background worker (or a retry) // picks it up. try { while (true) { cancellationToken.ThrowIfCancellationRequested(); // Call purge_trash SQL function - one transaction per batch (see SoftDeleteAsync), run again on a // deadlock when the batch's transaction is our own (DeadlockRetryHelper). var results = await DeadlockRetryHelper.ExecuteWithRetryAsync(_context, () => _context.ExecuteAtomicAsync( () => _context.QueryAsync( Sql.SoftDelete_PurgeTrash(), new object[] { trashId, batchSize }, cancellationToken), cancellationToken), cancellationToken: cancellationToken); var result = results.FirstOrDefault(); if (result == null) break; if (result.deleted_count == 0) { if (result.remaining_count == 0) break; // Objects remain but none was deleted. Either every one of them is referenced by a // live object - the batch marked the container 'failed' - or another purger (the // background worker beside this call, another node) deleted the batch chosen here // meanwhile: the container stays 'running' and the next batch takes what is left. var state = await GetDeletionProgressAsync(trashId, cancellationToken); if (state == null || state.Status != PurgeStatus.Running) await ThrowTrashReferencedAsync( trashId, result.remaining_count, deleted, startedAt, effectiveUser.Id, progress, cancellationToken); continue; } deleted += (int)result.deleted_count; var remaining = (int)result.remaining_count; var status = remaining == 0 ? PurgeStatus.Completed : PurgeStatus.Running; progress?.Report(new PurgeProgress( trashId, deleted, remaining, status, startedAt, effectiveUser.Id)); if (remaining == 0) { // A dialect whose purge statement cannot remove the finished container itself (SQLite). if (Sql.SoftDelete_DeleteCompletedTrashContainer() is { } removeContainer) await _context.ExecuteAsync(removeContainer, new object[] { trashId }, cancellationToken); break; } } } catch (OperationCanceledException) { progress?.Report(new PurgeProgress( trashId, deleted, totalCount - deleted, PurgeStatus.Cancelled, startedAt, effectiveUser.Id)); throw; } // LogDebug, not LogInformation — each Identity-level DELETE produces its own // trash container with 1 object, so this fires per-operation and floods INF // logs with "Deleted=1" entries (worker restart compounds it via // RecoverOrphanedTasksAsync draining the accumulated backlog one-by-one). // Operators who need per-purge visibility enable DBG for this category. _logger?.LogDebug( "PurgeTrash completed. TrashId={TrashId}, Deleted={Deleted}, User={UserId}", trashId, deleted, effectiveUser.Id); } /// /// A purge that ended with objects no batch may delete: live objects reference them. redb does /// not unlink those references (that would hide the caller's bug inside another object's data), /// so the purge surfaces them - both sides named - after the container was marked 'failed'. /// private async Task ThrowTrashReferencedAsync( long trashId, long remaining, int deleted, DateTimeOffset startedAt, long userId, IProgress? progress, CancellationToken cancellationToken) { var pairs = await _context.QueryAsync( Sql.SoftDelete_SelectLiveReferrersOfTrash(), new object[] { trashId }, cancellationToken); progress?.Report(new PurgeProgress( trashId, deleted, (int)remaining, PurgeStatus.Failed, startedAt, userId)); _logger?.LogWarning( "PurgeTrash failed. TrashId={TrashId}, Deleted={Deleted}, Remaining={Remaining}: objects are referenced by live objects", trashId, deleted, remaining); throw new RedbObjectReferencedException( trashId, remaining, pairs.Select(p => p.referenced_id).Distinct().ToList(), pairs.Select(p => p.referencing_id).Distinct().ToList()); } /// /// Gets deletion progress for a specific trash container from database. /// Returns null if trash container not found or already deleted. /// public async Task GetDeletionProgressAsync(long trashId, CancellationToken cancellationToken = default) { var results = await _context.QueryAsync( Sql.SoftDelete_GetDeletionProgress(), new object[] { trashId }, cancellationToken); var row = results.FirstOrDefault(); if (row == null) return null; return new PurgeProgress( row.trash_id, (int)row.deleted, (int)(row.total - row.deleted), ParsePurgeStatus(row.status), row.started_at, row.owner_id); } /// /// Gets all active (pending/running) deletions for a user from database. /// public async Task> GetUserActiveDeletionsAsync(long userId, CancellationToken cancellationToken = default) { var results = await _context.QueryAsync( Sql.SoftDelete_GetUserActiveDeletions(), new object[] { userId }, cancellationToken); return results.Select(row => new PurgeProgress( row.trash_id, (int)row.deleted, (int)(row.total - row.deleted), ParsePurgeStatus(row.status), row.started_at, row.owner_id)).ToList(); } private static PurgeStatus ParsePurgeStatus(string status) => status switch { "pending" => PurgeStatus.Pending, "running" => PurgeStatus.Running, "completed" => PurgeStatus.Completed, "failed" => PurgeStatus.Failed, "cancelled" => PurgeStatus.Cancelled, _ => PurgeStatus.Pending }; /// /// Gets orphaned deletion tasks for recovery at startup. /// CLUSTER-SAFE: Returns 'pending' OR 'running' with stale _date_modify. /// public async Task> GetOrphanedDeletionTasksAsync(int timeoutMinutes = 30, CancellationToken cancellationToken = default) { var results = await _context.QueryAsync( Sql.SoftDelete_GetOrphanedTasks(), new object[] { timeoutMinutes }, cancellationToken); return results.Select(row => new OrphanedTask( row.trash_id, (int)row.total, (int)row.deleted, row.status, row.owner_id)).ToList(); } /// /// Atomically claim an orphaned task for processing. /// CLUSTER-SAFE: Uses atomic UPDATE to prevent race conditions. /// public async Task TryClaimOrphanedTaskAsync(long trashId, int timeoutMinutes = 30, CancellationToken cancellationToken = default) { var affected = await _context.ExecuteAsync( Sql.SoftDelete_ClaimOrphanedTask(), new object[] { trashId, timeoutMinutes }, cancellationToken); return affected > 0; } /// /// Internal DTO for orphaned task query results. /// private class OrphanedTaskRow { public long trash_id { get; set; } public long total { get; set; } public long deleted { get; set; } public string status { get; set; } = ""; public long owner_id { get; set; } } // ===== BULK LOADING BY ID ===== /// /// Bulk load objects by ID (uses _securityContext) /// Supports polymorphic loading of objects from different schemes /// public async Task> LoadAsync(IEnumerable objectIds, int depth = 10, CancellationToken cancellationToken = default) { var effectiveUser = _securityContext.GetEffectiveUser(); return await LoadAsync(objectIds, effectiveUser, depth, cancellationToken); } /// /// Bulk loading of objects by ID with explicit user /// Supports two modes: EAGER (get_object_json) and LAZY (_objects + LoadPropsForManyAsync) /// public async Task> LoadAsync(IEnumerable objectIds, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) { var ids = objectIds.ToList(); if (ids.Count == 0) return new List(); var result = new List(); var idsToLoad = new List(); // === STEP 1: Cache check (if enabled) === // One query resolves the hash and scheme of every id (the polymorphic load needs the schemes anyway), and // the cache answers by hash. SkipHashValidationOnCacheCheck changes nothing here: it used to switch the // cache off for the batch (every object rematerialized), and without it the batch asked the database once // per id. This is the road of the list-item preload and of LoadLinkedObjectsAsync. if (_configuration.EnablePropsCache && PropsCache.Instance != null) { var rows = await _context.QueryAsync( Sql.ObjectStorage_SelectObjectsByIds(), new object[] { ids.ToArray() }, cancellationToken); var rowById = new Dictionary(rows.Count); foreach (var row in rows) rowById[row.Id] = row; var hits = new List<(long Id, IRedbObject Obj)>(); foreach (var id in ids) { IRedbObject? cachedObj = null; if (rowById.TryGetValue(id, out var row) && row.Hash.HasValue) { // Get type through AutomaticTypeRegistry var propsType = Cache.GetClrType(row.IdScheme); if (propsType != null) { // Typed Get(id, hash): the delegate is built once per props type. cachedObj = Caching.CacheDelegates.Get(PropsCache, propsType, id, row.Hash.Value); } } if (cachedObj != null) hits.Add((id, cachedObj)); // Cache HIT, checked for a stale graph below else idsToLoad.Add(id); // Cache MISS, or the object does not exist - the load reports that } // A cached graph keeps the references it was loaded with, and a target that changed or left for the // trash moves neither this object's hash nor its cache entry. One query checks every reference of // every hit; a stale graph is dropped and its object is read again. if (hits.Count > 0) { var stale = await FindStaleCachedGraphsAsync(hits.Select(h => h.Obj), cancellationToken); foreach (var (id, obj) in hits) { if (stale.Contains(id)) { PropsCache.Remove(id); idsToLoad.Add(id); } else { result.Add(obj); } } } } else { idsToLoad = ids; } if (idsToLoad.Count == 0) { return result; // All from cache! } // === STEP 2: Permission check === if (_configuration.DefaultCheckPermissionsOnLoad) { foreach (var id in idsToLoad) { var canRead = await _permissionProvider.CanUserSelectObject(id, user.Id); if (!canRead) { throw new UnauthorizedAccessException($"User {user.Id} has no read permission for object {id}"); } } } // === STEP 3: Loading missing objects === // V4 (L.0): the old per-call lazy switch is gone. Free loads eagerly via // get_object_json; Pro overrides LoadObjectsEagerAsync to its batch materializer. var loadedObjects = await LoadObjectsEagerAsync(idsToLoad, depth, cancellationToken); result.AddRange(loadedObjects); // === STEP 4: Check if all objects are found === if (_configuration.ThrowOnObjectNotFound) { var loadedIds = result.Select(o => o.Id).ToHashSet(); var missingIds = ids.Where(id => !loadedIds.Contains(id)).ToList(); if (missingIds.Count > 0) { throw new InvalidOperationException($"Objects with ID [{string.Join(", ", missingIds)}] not found"); } } return result; } /// /// LAZY loading: base fields from _objects + LoadPropsForManyAsync /// protected for access from Pro version /// protected async Task> LoadObjectsLazyAsync(List objectIds, int depth, CancellationToken cancellationToken = default) { if (objectIds.Count == 0) return new List(); // Load base fields from _objects via SQL var baseObjects = await _context.QueryAsync( Sql.ObjectStorage_SelectObjectsByIds(), new object[] { objectIds.ToArray() }, cancellationToken); if (baseObjects.Count == 0) return new List(); // Group by scheme_id for polymorphic deserialization var result = new List(); var objectsByScheme = baseObjects.GroupBy(o => o.IdScheme); foreach (var schemeGroup in objectsByScheme) { var schemeId = schemeGroup.Key; var objectsForScheme = schemeGroup.ToList(); // Resolve scheme_id → Type: lazy, self-healing, cross-domain-safe (loads the scheme by // id and derives via the global ClrSchemeTypeIndex if this domain hasn't seen it yet). // Null means the scheme genuinely has no CLR type → a legitimately non-generic object. var propsType = await Cache.ResolveClrTypeAsync(schemeId, SchemeSyncProvider); if (propsType == null) { // Non-generic RedbObject (Object scheme) - create without Props foreach (var baseObj in objectsForScheme) { result.Add(CreateNonGenericRedbObject(baseObj)); } continue; } // Create typed RedbObject var createMethod = typeof(ObjectStorageProviderBase) .GetMethod(nameof(CreateRedbObjectsFromBaseObjects), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)? .MakeGenericMethod(propsType); if (createMethod != null) { var createTask = (Task)createMethod.Invoke(this, new object[] { objectsForScheme, depth })!; await createTask; var typedObjects = createTask.GetType().GetProperty("Result")?.GetValue(createTask) as System.Collections.IEnumerable; if (typedObjects != null) { foreach (var obj in typedObjects) { if (obj is IRedbObject redbObj) { result.Add(redbObj); } } } } } return result; } /// /// Create non-generic RedbObject from RedbObjectRow (Object scheme, no Props). /// private RedbObject CreateNonGenericRedbObject(RedbObjectRow baseObj) { var obj = new RedbObject(); baseObj.ApplyHeaderTo(obj); return obj; } /// /// Creates RedbObject<TProps> from base RedbObjectRow fields with LazyPropsLoader and LoadPropsForManyAsync /// private async Task>> CreateRedbObjectsFromBaseObjects(List baseObjects, int depth) where TProps : class, new() { var redbObjects = baseObjects.Select(baseObj => { var obj = baseObj.ToRedbObject(); obj._lazyLoader = CreateLazyPropsLoader(); return obj; }).ToList(); // Bulk load Props via LoadPropsForManyAsync at the requested depth (V4: no sync-over-async) var lazyLoader = CreateLazyPropsLoader(); await lazyLoader.LoadPropsForManyAsync(redbObjects, propsDepth: depth); // Cache loaded objects - once the transaction commits (CachePublication). if (_configuration.EnablePropsCache && PropsCache.Instance != null) { Caching.CachePublication.AfterCommit(_context, () => { foreach (var obj in redbObjects.Where(o => o.hash.HasValue)) PropsCache.Set(obj); }); } return redbObjects; } /// /// EAGER loading: get_object_json for all IDs /// Open Source: uses get_object_json /// Pro: overrides for PVT approach /// protected virtual async Task> LoadObjectsEagerAsync(List objectIds, int depth, CancellationToken cancellationToken) { if (objectIds.Count == 0) return new List(); // Use unnest for bulk get_object_json call var idsArray = objectIds.ToArray(); // Execute get_object_json for each ID via SQL var objectsJsonList = await _context.ExecuteJsonListAsync( Sql.ObjectStorage_GetObjectsJsonBulk(), new object[] { idsArray, depth }, cancellationToken); var result = new List(); foreach (var objectJson in objectsJsonList) { if (string.IsNullOrEmpty(objectJson)) continue; // Extract scheme_id from JSON for polymorphic deserialization using var jsonDoc = System.Text.Json.JsonDocument.Parse(objectJson); var schemeId = jsonDoc.RootElement.GetProperty("scheme_id").GetInt64(); // Get type through AutomaticTypeRegistry var propsType = Cache.GetClrType(schemeId); if (propsType == null) { // Non-generic RedbObject (Object scheme) - deserialize base fields only var baseObj = System.Text.Json.JsonSerializer.Deserialize(objectJson); if (baseObj != null) { result.Add(baseObj); } continue; } // Dynamic deserialization var redbObj = _serializer.DeserializeRedbDynamic(objectJson, propsType); if (redbObj != null) { Utils.LazyReferenceInstaller.Install(redbObj, CreateLazyPropsLoader()); // V4 (L.3) // Cache main + nested objects if (_configuration.EnablePropsCache && PropsCache.Instance != null && redbObj.Hash.HasValue) { // The object and its nested objects in one walk. Caching.CacheDelegates.SetGraph(PropsCache, redbObj); } result.Add(redbObj); } } return result; } // ===== LAZY REFERENCE RELOAD (V4, LAZY Л2 §4.6) ===== /// public async Task LoadReferencesAsync(RedbObject parent, Func?>?> references, CancellationToken cancellationToken = default) where TProps : class, new() where TRef : class, new() { var props = parent?.GetPropsDirectly(); if (props == null) return; var stubs = (references(props) ?? Enumerable.Empty?>()) .Where(r => r is { id: > 0 } && !r.IsPropsLoaded) .Select(r => r!) .ToList(); if (stubs.Count == 0) return; // One batch: the loader checks the props cache first, then fetches the misses together. // Depth 1, exactly like a stub's first Props access: the reloaded objects' own references // are stubs again - laziness stays transitive through the batch form (§4.7). await CreateLazyPropsLoader().LoadPropsForManyAsync(stubs, propsDepth: 1, cancellationToken: cancellationToken); } /// public Task LoadReferencesAsync(RedbObject parent, Func?> reference, CancellationToken cancellationToken = default) where TProps : class, new() where TRef : class, new() => LoadReferencesAsync(parent, p => new[] { reference(p) }, cancellationToken); // ===== LOAD WITH PARENT CHAIN ===== /// /// Load object by ID with parent chain to root (uses _securityContext). /// public async Task?> LoadWithParentsAsync(long objectId, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() { var effectiveUser = _securityContext.GetEffectiveUser(); return await LoadWithParentsAsync(objectId, effectiveUser, depth, cancellationToken); } /// /// Load object with parent chain to root (uses _securityContext). /// public async Task?> LoadWithParentsAsync(IRedbObject obj, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() { var effectiveUser = _securityContext.GetEffectiveUser(); return await LoadWithParentsAsync(obj.Id, effectiveUser, depth, cancellationToken); } /// /// Load object by ID with parent chain to root with explicit user. /// public async Task?> LoadWithParentsAsync(IRedbObject obj, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() { return await LoadWithParentsAsync(obj.Id, user, depth, cancellationToken); } /// /// MAIN LoadWithParentsAsync - loads single object with parent chain. /// Delegates to bulk method for implementation reuse. /// public async Task?> LoadWithParentsAsync(long objectId, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() { var list = await LoadWithParentsAsync(new[] { objectId }, user, depth, cancellationToken); return list.FirstOrDefault(); } /// /// Bulk load objects with parent chains (uses _securityContext). /// public async Task>> LoadWithParentsAsync(IEnumerable objectIds, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() { var effectiveUser = _securityContext.GetEffectiveUser(); return await LoadWithParentsAsync(objectIds, effectiveUser, depth, cancellationToken); } /// /// MAIN bulk LoadWithParentsAsync - loads objects with parent chains to root. /// Uses recursive CTE to get all ancestor IDs, then bulk loads all objects. /// Parents are loaded polymorphically (each with its real Props type). /// public async Task>> LoadWithParentsAsync(IEnumerable objectIds, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new() { var ids = objectIds.ToList(); if (ids.Count == 0) return new List>(); // 1. Get IDs of all objects and their ancestors via recursive CTE var allIds = await _context.QueryScalarListAsync(_sql.Tree_SelectIdsWithAncestors(), new object[] { ids.ToArray(), TreeProviderBase.MaxAncestorDepth }, cancellationToken); // 2. Load all objects polymorphically (target + parents with real types) var loadedObjects = await LoadAsync(allIds, user, depth, cancellationToken); // 3. Convert to ITreeRedbObject (polymorphic - each keeps its real Props type) var treeObjects = new Dictionary(); foreach (var obj in loadedObjects) { treeObjects[obj.Id] = Utils.TreeObjectConverter.ToTreeObjectDynamic(obj); } // 4. Build Parent relationships (polymorphic) Utils.TreeObjectConverter.BuildParentRelationships(treeObjects.Values); // 5. Return only requested objects that match TProps type return ids .Where(id => treeObjects.ContainsKey(id) && treeObjects[id] is TreeRedbObject) .Select(id => (TreeRedbObject)treeObjects[id]) .ToList(); } /// /// Bulk polymorphic load with parent chains (uses _securityContext). /// public async Task> LoadWithParentsAsync(IEnumerable objectIds, int depth = 10, CancellationToken cancellationToken = default) { var effectiveUser = _securityContext.GetEffectiveUser(); return await LoadWithParentsAsync(objectIds, effectiveUser, depth, cancellationToken); } /// /// MAIN bulk polymorphic LoadWithParentsAsync. /// Preserves actual Props types for each object. /// public async Task> LoadWithParentsAsync(IEnumerable objectIds, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) { var ids = objectIds.ToList(); if (ids.Count == 0) return new List(); // 1. Get IDs of all objects and their ancestors var allIds = await _context.QueryScalarListAsync(_sql.Tree_SelectIdsWithAncestors(), new object[] { ids.ToArray(), TreeProviderBase.MaxAncestorDepth }, cancellationToken); // 2. Load all objects var loadedObjects = await LoadAsync(allIds, user, depth, cancellationToken); // 3. Convert to ITreeRedbObject and build dictionary var treeObjects = new Dictionary(); foreach (var obj in loadedObjects) { treeObjects[obj.Id] = Utils.TreeObjectConverter.ToTreeObjectDynamic(obj); } // 4. Build Parent relationships Utils.TreeObjectConverter.BuildParentRelationships(treeObjects.Values); // 5. Return only requested objects return ids .Where(id => treeObjects.ContainsKey(id)) .Select(id => treeObjects[id]) .ToList(); } public async Task SaveAsync(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) where TProps : class, new() { // Route through Batch pipeline — same TX + FOR UPDATE + DeadlockRetry for all strategies var results = await SaveAsync(new[] { (IRedbObject)obj }, user, cancellationToken); return results.FirstOrDefault(); } /// public Task LockForUpdateAsync(params long[] objectIds) => LockForUpdateAsync(objectIds, CancellationToken.None); /// public async Task LockForUpdateAsync(long[] objectIds, CancellationToken cancellationToken) { if (objectIds == null || objectIds.Length == 0) return 0; // SELECT _id ... FOR UPDATE/UPDLOCK: the rows that exist come back (and are locked); // the count is the caller\x27s signal. A deleted id locks nothing and MUST NOT be taken // for locked (BR-9, 2026-09-02: with the default AutoSwitchToInsert a CAS save after // a silent no-op lock resurrects the deleted object). var locked = await _context.QueryScalarListAsync( _sql.ObjectStorage_LockObjectsForUpdate(), new object[] { objectIds }, cancellationToken).ConfigureAwait(false); return locked.Count; } /// public Task LockForUpdateRequiredAsync(params long[] objectIds) => LockForUpdateRequiredAsync(objectIds, CancellationToken.None); /// public async Task LockForUpdateRequiredAsync(long[] objectIds, CancellationToken cancellationToken) { if (objectIds == null || objectIds.Length == 0) return; if (!_context.IsInTransaction) throw new InvalidOperationException( "LockForUpdateRequiredAsync must run inside an active transaction: a row lock " + "lives only until its transaction ends, so a lock taken outside one guarantees " + "nothing. Wrap the lock and the work it protects in ExecuteAtomicAsync or " + "BeginTransactionAsync."); var requested = objectIds.Distinct().ToArray(); var locked = await _context.QueryScalarListAsync( _sql.ObjectStorage_LockObjectsForUpdate(), new object[] { requested }, cancellationToken).ConfigureAwait(false); if (locked.Count == requested.Length) return; throw new RedbLockNotAcquiredException( requested, requested.Except(locked).OrderBy(x => x).ToArray()); } // CT-3 (ревью 2026-09-03, снесено 2026-09-04): здесь жил мёртвый одиночный путь // сохранения свойств (SavePropertiesAsync со своим Delete/Insert и ВТОРЫМ, расходящимся // алгоритмом ChangeTracking) - точка входа не имела ни одного вызова. Все сохранения V4 // идут батч-конвейером SaveAsync; Free заявляет ChangeTracking как NotSupported в // ExecuteBatchByStrategy, живой CT - в redb.Core.Pro. Вместе с кластером удалены его // хелперы (Methods.cs целиком) и пара мёртвых SQL-методов диалектов. /// /// Get scheme structures with full metadata including _store_null /// private async Task> GetStructuresWithMetadataAsync(long schemeId) { // Load structures with type info via SQL join var rows = await _context.QueryAsync( Sql.ObjectStorage_SelectStructuresWithMetadata(), schemeId); return rows.Select(r => new StructureMetadata { Id = r.Id, IdParent = r.IdParent, Name = r.Name, DbType = r.DbType, IsArray = r.CollectionType != null, CollectionType = r.CollectionType, KeyType = r.KeyType, StoreNull = r.StoreNull, Unique = r.Unique, UniqueScope = r.UniqueScope, TypeSemantic = r.TypeSemantic }).ToList(); } /// /// Helper class for mapping structure metadata query results. /// private class StructureMetadataRow { public long Id { get; set; } public long? IdParent { get; set; } public string Name { get; set; } = string.Empty; public string DbType { get; set; } = "String"; public long? CollectionType { get; set; } public long? KeyType { get; set; } public bool StoreNull { get; set; } public bool Unique { get; set; } public long? UniqueScope { get; set; } public string TypeSemantic { get; set; } = "string"; } /// /// AUTOSAVE: Processes nested RedbObjects, saving them recursively /// private async Task ProcessNestedObjectsAsync(object rawValue, string dbType, bool isArray) { if (rawValue == null) return null; // Process arrays if (isArray && rawValue is System.Collections.IEnumerable enumerable && rawValue is not string) { var processedList = new List(); foreach (var item in enumerable) { if (IsRedbObjectWithoutId(item)) { var nestedObj = (IRedbObject)item; var savedId = await SaveAsync(nestedObj); processedList.Add(savedId); } else if (IsRedbObjectWithId(item)) { processedList.Add(((IRedbObject)item).Id); } else if (item is IRedbListItem listItemInArray) { // Process IRedbListItem in array - extract Id processedList.Add(listItemInArray.Id); } else { processedList.Add(item); } } return processedList; } // Process single objects if (IsRedbObjectWithoutId(rawValue)) { var nestedObj = (IRedbObject)rawValue; var savedId = await SaveAsync(nestedObj); return savedId; } if (IsRedbObjectWithId(rawValue)) { return ((IRedbObject)rawValue).Id; } // Process IRedbListItem - extract Id if (rawValue is IRedbListItem listItem) { return listItem.Id; } return rawValue; } /// /// Checks if object is IRedbObject with Id = 0 (needs saving) /// private static bool IsRedbObjectWithoutId(object? value) { if (value is IRedbObject redbObj) { return redbObj.Id == 0; } return false; } /// /// Checks if object is IRedbObject with Id != 0 (already saved) /// private static bool IsRedbObjectWithId(object? value) { if (value is IRedbObject redbObj) { return redbObj.Id != 0; } return false; } /// /// UPDATED VERSION: Removed JSON arrays, only simple types /// private static void SetSimpleValueByType(RedbValue valueRecord, string dbType, object? processedValue) { if (processedValue == null) return; // ARRAYS NOT PROCESSED - they go through SaveArrayFieldAsync // Direct assignment of typed values switch (dbType) { case "String": case "Text": // A plain ToString() of a DateOnly uses the CURRENT culture, so a value written under one // culture failed or silently mis-parsed under another: the invariant round-trip form. valueRecord.String = processedValue switch { DateOnly dateOnly => Core.Utils.RedbTemporalFormat.ToText(dateOnly), _ => processedValue?.ToString() }; break; case "Long": case "bigint": // TimeOnly and TimeSpan carry db_type "Long" (_types seed): their Ticks. if (processedValue is TimeSpan timeSpan) valueRecord.Long = timeSpan.Ticks; else if (processedValue is TimeOnly timeOnly) valueRecord.Long = timeOnly.Ticks; else if (processedValue is long longVal) valueRecord.Long = longVal; else if (processedValue is int intVal) valueRecord.Long = intVal; else if (long.TryParse(processedValue?.ToString(), out var parsedLong)) valueRecord.Long = parsedLong; break; case "Double": if (processedValue is double doubleVal) valueRecord.Double = doubleVal; else if (processedValue is float floatVal) valueRecord.Double = floatVal; else if (double.TryParse(processedValue?.ToString(), out var parsedDouble)) valueRecord.Double = parsedDouble; break; case "Numeric": // Precise decimal numbers for financial calculations if (processedValue is decimal decimalVal) valueRecord.Numeric = decimalVal; else if (processedValue is double doubleVal2) valueRecord.Numeric = redb.Core.Utils.RedbDecimal.FromDouble(doubleVal2); else if (processedValue is float floatVal2) valueRecord.Numeric = redb.Core.Utils.RedbDecimal.FromSingle(floatVal2); else if (decimal.TryParse(processedValue?.ToString(), out var parsedDecimal)) valueRecord.Numeric = parsedDecimal; break; case "Boolean": if (processedValue is bool boolVal) valueRecord.Boolean = boolVal; else if (bool.TryParse(processedValue?.ToString(), out var parsedBool)) valueRecord.Boolean = parsedBool; break; // db_type "DateTime" belongs to DateOnly (the CLR DateTime type carries db_type // "DateTimeOffset" and is handled in the branch below, discriminated by the // runtime type of the value). case "DateTime": if (processedValue is DateOnly dateOnlyValue) { // Midnight of that date, as a zone-less clock reading. Was previously // DateTime.TryParse(dateOnly.ToString()) — a round-trip through the // current culture's short date pattern. valueRecord.DateTimeOffset = Core.Utils.DateTimeConverter.NormalizeForStorage( dateOnlyValue.ToDateTime(TimeOnly.MinValue)); } else if (processedValue is DateTime dateTime) { // Use centralized converter: DateTime → UTC valueRecord.DateTimeOffset = Core.Utils.DateTimeConverter.NormalizeForStorage(dateTime); } else if (Core.Utils.RedbTemporalFormat.TryParseDateOnly(processedValue?.ToString(), out var parsedDateOnly)) { valueRecord.DateTimeOffset = Core.Utils.DateTimeConverter.NormalizeForStorage( parsedDateOnly.ToDateTime(TimeOnly.MinValue)); } break; case "DateTimeOffset": if (processedValue is DateTimeOffset dateTimeOffset) valueRecord.DateTimeOffset = dateTimeOffset; else if (processedValue is DateTime dt) valueRecord.DateTimeOffset = Core.Utils.DateTimeConverter.NormalizeForStorage(dt); // DateOnly stores midnight of that date as a zone-less reading. It carries // db_type "DateTimeOffset" so that every JSON projection, PVT builder and the // SQLite native extension handle it through the branch they already have. else if (processedValue is DateOnly dateOnlyForOffset) valueRecord.DateTimeOffset = Core.Utils.DateTimeConverter.NormalizeForStorage( dateOnlyForOffset.ToDateTime(TimeOnly.MinValue)); else if (DateTimeOffset.TryParse(processedValue?.ToString(), System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind, out var parsedDate)) valueRecord.DateTimeOffset = parsedDate; break; case "ByteArray": if (processedValue is byte[] byteArray) valueRecord.ByteArray = byteArray; break; case "Object": // Object references are stored in separate _object field if (processedValue is long objectId) valueRecord.Object = objectId; else if (long.TryParse(processedValue?.ToString(), out var parsedObjId)) valueRecord.Object = parsedObjId; break; case "ListItem": // ListItem references are stored in separate _listitem field if (processedValue is IRedbListItem listItem) { valueRecord.ListItem = listItem.Id; } else if (processedValue is long listItemId) { valueRecord.ListItem = listItemId; } else if (long.TryParse(processedValue?.ToString(), out var parsedListId)) { valueRecord.ListItem = parsedListId; } else { throw new InvalidOperationException( $"ListItem value cannot be processed: value='{processedValue}', type='{processedValue?.GetType().FullName}'."); } break; case "Guid": if (processedValue is Guid guidVal) valueRecord.Guid = guidVal; else if (Guid.TryParse(processedValue?.ToString(), out var parsedGuid)) valueRecord.Guid = parsedGuid; break; default: valueRecord.String = processedValue?.ToString(); break; } } /// /// Converts IRedbStructure to StructureMetadata getting type info from cache /// private async Task> ConvertStructuresToMetadataAsync(IEnumerable structures) { var result = new List(); foreach (var structure in structures) { // Get type info by IdType via cache or DB var typeInfo = await GetTypeInfoAsync(structure.IdType); result.Add(new StructureMetadata { Id = structure.Id, IdParent = structure.IdParent, Name = structure.Name, DbType = typeInfo.DbType, IsArray = structure.CollectionType != null, StoreNull = structure.StoreNull ?? false, Unique = structure.Unique ?? false, TypeSemantic = typeInfo.TypeSemantic }); } return result; } /// /// Gets type info by IdType. /// private async Task<(string DbType, string TypeSemantic)> GetTypeInfoAsync(long typeId) { // Direct SQL query for type info var typeEntity = await _context.QueryFirstOrDefaultAsync( Sql.ObjectStorage_SelectTypeById(), typeId); return typeEntity != null ? (typeEntity.DbType ?? "String", typeEntity.Type1 ?? "string") : ("String", "string"); } /// /// OPTIMIZATION: Get scheme from cache WITHOUT hash validation /// Used inside SaveAsync transactions where scheme is guaranteed not to change /// protected async Task GetSchemeFromCacheOrDbAsync(long schemeId) { // First check cache WITHOUT DB query for hash validation var cachedScheme = Cache.GetScheme(schemeId); if (cachedScheme != null) { return cachedScheme; // Cache HIT - return without validation } // Cache MISS - load via provider (it will cache) return await _schemeSync.GetSchemeByIdAsync(schemeId); } } /// /// Structure metadata with extended info including _store_null /// internal class StructureMetadata { public long Id { get; set; } public long? IdParent { get; set; } // Add field for structure hierarchy public string Name { get; set; } = string.Empty; public string DbType { get; set; } = "String"; public bool IsArray { get; set; } public long? CollectionType { get; set; } // Array, Dictionary, etc. public long? KeyType { get; set; } // Key type for Dictionary public bool StoreNull { get; set; } /// The field is a [RedbUnique] key: its root scalar values carry a hash in _unique. public bool Unique { get; set; } /// S3: element-key scope of a collection key (null = default reading). public long? UniqueScope { get; set; } public string TypeSemantic { get; set; } = "string"; /// /// True if this is a Dictionary field /// public bool IsDictionary => CollectionType == RedbTypeIds.Dictionary; } /// /// DTO for mark_for_deletion SQL function result. /// internal class MarkForDeletionResult { public long trash_id { get; set; } public long marked_count { get; set; } } /// /// DTO for purge_trash SQL function result. /// internal class PurgeTrashResult { public long deleted_count { get; set; } public long remaining_count { get; set; } } /// /// DTO for the live-referrers-of-trash query: a trashed object and a live object referencing it. /// internal class TrashReferrerRow { public long referenced_id { get; set; } public long referencing_id { get; set; } } /// /// DTO for deletion progress SQL query result. /// internal class TrashProgressRow { public long trash_id { get; set; } public long total { get; set; } public long deleted { get; set; } public string status { get; set; } = "pending"; public DateTimeOffset started_at { get; set; } public long owner_id { get; set; } } }