Path: redb/redb.Core/Providers/IObjectStorageProvider.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/IObjectStorageProvider.cs
----
using redb.Core.Models.Entities;
using redb.Core.Models.Contracts;
using redb.Core.Services;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace redb.Core.Providers
{
///
/// Provider for saving/loading objects in EAV storage.
/// Permission checks are managed centrally via configuration.
///
public interface IObjectStorageProvider
{
// ===== BASE 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.
///
Task?> LoadAsync(long objectId, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new();
///
/// Synchronous for the
/// thread-pool-free lazy path (the sync getter of RedbListItem.Object): the whole load runs
/// on the calling thread down to ADO.NET, so a saturated thread pool cannot slow or
/// deadlock it. The default falls back to blocking on the async form (pool-coupled);
/// the in-tree base provider overrides with a true sync path.
///
RedbObject? Load(long objectId, int depth = 10) where TProps : class, new()
=> LoadAsync(objectId, depth).ConfigureAwait(false).GetAwaiter().GetResult();
///
/// Load object from EAV (uses _securityContext and config.DefaultCheckPermissionsOnLoad).
/// Returns null if object not found and config.ThrowOnObjectNotFound = false.
///
Task?> LoadAsync(IRedbObject obj, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new();
///
/// Load object from EAV with explicit user by ID (uses config.DefaultCheckPermissionsOnLoad).
/// Returns null if object not found and config.ThrowOnObjectNotFound = false.
///
Task?> LoadAsync(long objectId, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new();
///
/// Load object from EAV with explicit user (uses config.DefaultCheckPermissionsOnLoad).
/// Returns null if object not found and config.ThrowOnObjectNotFound = false.
///
Task?> LoadAsync(IRedbObject obj, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new();
///
/// Load the whole object as raw JSON by ID, without a CLR props type — the in-database
/// materializer (get_object_json on every provider) serializes the full RedbObject tree
/// to the given depth. Permission check per config.DefaultCheckPermissionsOnLoad; the
/// typed props cache is not consulted (it is keyed by CLR type).
/// Returns null if object not found and config.ThrowOnObjectNotFound = false.
///
Task LoadJsonAsync(long objectId, int depth = 10, CancellationToken cancellationToken = default);
///
/// Load the whole object as raw JSON by ID with explicit user (see
/// ).
///
Task LoadJsonAsync(long objectId, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default);
///
/// The object whose [RedbUnique] property holds the given value, or null. One probe of the
/// partial unique index: the value is canonicalised and hashed exactly as the save path
/// does it. Throws RedbUniqueKeyDefinitionException when the property is not a unique key.
///
Task?> GetByUniqueAsync(System.Linq.Expressions.Expression> keyProperty, object? value, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new();
///
Task?> GetByUniqueAsync(string propertyName, object? value, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new();
///
/// Upsert by the object key (P1): resolves the _objects row by (scheme, ValueUnique) and
/// saves onto it - the values ride the ordinary pipeline in the same save. A lost creation
/// race retries onto the winner's row, so a concurrent accept of one key is idempotent:
/// exactly one object per key, last writer's content. Returns the object id.
/// Throws RedbUniqueKeyDefinitionException when ValueUnique is empty.
///
Task SaveByUniqueAsync(RedbObject obj, CancellationToken cancellationToken = default) where TProps : class, new();
///
/// Save object to EAV (uses _securityContext and config.DefaultCheckPermissionsOnSave).
/// Determines type (generic/non-generic) internally.
///
Task SaveAsync(IRedbObject obj, CancellationToken cancellationToken = default);
///
/// Save generic object to EAV (uses _securityContext and config.DefaultCheckPermissionsOnSave).
///
Task SaveAsync(IRedbObject obj, CancellationToken cancellationToken = default) where TProps : class, new();
///
/// Delete object (uses _securityContext and config.DefaultCheckPermissionsOnDelete).
///
Task DeleteAsync(IRedbObject obj, CancellationToken cancellationToken = default);
// ===== OVERLOADS WITH EXPLICIT USER (use configuration) =====
///
/// Save object to EAV with explicit user. Determines type internally.
///
Task SaveAsync(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default);
///
/// Save generic object to EAV with explicit user (uses config.DefaultCheckPermissionsOnSave).
///
Task SaveAsync(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default) where TProps : class, new();
///
/// Delete object with explicit user (uses config.DefaultCheckPermissionsOnDelete).
///
Task DeleteAsync(IRedbObject obj, IRedbUser user, CancellationToken cancellationToken = default);
// ===== DELETE BY ID =====
///
/// Delete object by ID (uses _securityContext and config.DefaultCheckPermissionsOnDelete).
///
/// true if object deleted, false if not found
Task DeleteAsync(long objectId, CancellationToken cancellationToken = default);
///
/// Delete object by ID with explicit user (uses config.DefaultCheckPermissionsOnDelete).
///
/// true if object deleted, false if not found
Task DeleteAsync(long objectId, IRedbUser user, CancellationToken cancellationToken = default);
// ===== BULK OPERATIONS WITH PERMISSION CHECK =====
///
/// Bulk delete objects by ID (uses _securityContext and config.DefaultCheckPermissionsOnDelete).
///
/// Number of deleted objects
Task DeleteAsync(IEnumerable objectIds, CancellationToken cancellationToken = default);
///
/// Bulk delete objects by ID with explicit user (uses config.DefaultCheckPermissionsOnDelete).
///
/// Number of deleted objects
Task DeleteAsync(IEnumerable objectIds, IRedbUser user, CancellationToken cancellationToken = default);
///
/// Bulk delete objects by interface (uses _securityContext and config.DefaultCheckPermissionsOnDelete).
///
/// Number of deleted objects
Task DeleteAsync(IEnumerable objects, CancellationToken cancellationToken = default);
///
/// Bulk delete objects by interface with explicit user (uses config.DefaultCheckPermissionsOnDelete).
///
/// Number of deleted objects
Task DeleteAsync(IEnumerable objects, IRedbUser user, CancellationToken cancellationToken = default);
///
/// Bulk polymorphic load of objects by ID (uses _securityContext and config.DefaultCheckPermissionsOnLoad).
/// Supports objects of different schemes in one request.
///
/// List of object IDs to load
/// Depth for loading nested objects (EAGER mode only)
/// List of polymorphic IRedbObject instances
/// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes).
Task> LoadAsync(IEnumerable objectIds, int depth = 10, CancellationToken cancellationToken = default);
///
/// Bulk polymorphic load of objects by ID with explicit user (uses config.DefaultCheckPermissionsOnLoad).
/// Supports objects of different schemes in one request.
///
/// List of object IDs to load
/// User for permission check
/// Depth for loading nested objects (EAGER mode only)
/// List of polymorphic IRedbObject instances
/// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes).
Task> LoadAsync(IEnumerable objectIds, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default);
///
/// Bulk save of polymorphic objects (uses _securityContext and config).
/// Supports new and existing objects, nested objects.
/// Uses two strategies: DeleteInsert (bulk operations) or ChangeTracking (EF diff).
///
/// List of IDs of all main objects
Task> SaveAsync(IEnumerable objects, CancellationToken cancellationToken = default);
///
/// Bulk save of polymorphic objects with explicit user (uses config).
/// Supports new and existing objects, nested objects.
/// Uses two strategies: DeleteInsert (bulk operations) or ChangeTracking (EF diff).
///
/// List of IDs of all main objects
Task> SaveAsync(IEnumerable objects, IRedbUser user, CancellationToken cancellationToken = default);
// ===== SOFT DELETE (BACKGROUND DELETION) =====
///
/// Mark objects for soft-deletion (uses _securityContext).
/// Creates a trash container and moves objects and their descendants under it.
/// Actual deletion happens in background via IBackgroundDeletionService.
///
/// IDs of objects to mark for deletion
/// Optional parent ID for trash container (null = root level)
/// Deletion mark with trash container ID and count of marked objects
/// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes).
Task SoftDeleteAsync(IEnumerable objectIds, long? trashParentId = null, CancellationToken cancellationToken = default);
///
/// Mark objects for soft-deletion with explicit user.
/// Creates a trash container and moves objects and their descendants under it.
/// Actual deletion happens in background via IBackgroundDeletionService.
///
/// IDs of objects to mark for deletion
/// User performing the operation
/// Optional parent ID for trash container (null = root level)
/// Deletion mark with trash container ID and count of marked objects
/// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes).
Task SoftDeleteAsync(IEnumerable objectIds, IRedbUser user, long? trashParentId = null, CancellationToken cancellationToken = default);
///
/// Mark objects for soft-deletion (uses _securityContext).
/// Creates a trash container and moves objects and their descendants under it.
///
/// Objects to mark for deletion
/// Optional parent ID for trash container (null = root level)
/// Deletion mark with trash container ID and count of marked objects
/// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes).
Task SoftDeleteAsync(IEnumerable objects, long? trashParentId = null, CancellationToken cancellationToken = default);
///
/// Mark objects for soft-deletion with explicit user.
/// Creates a trash container and moves objects and their descendants under it.
///
/// Objects to mark for deletion
/// User performing the operation
/// Optional parent ID for trash container (null = root level)
/// Deletion mark with trash container ID and count of marked objects
/// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes).
Task SoftDeleteAsync(IEnumerable objects, IRedbUser user, long? trashParentId = null, CancellationToken cancellationToken = default);
///
/// Delete objects with background purge and progress reporting.
/// Marks objects for deletion, then purges them in batches with progress callback.
///
/// IDs of objects to delete
/// Number of objects to delete per batch
/// Optional progress reporter
/// Cancellation token
/// Optional parent ID for trash container (null = root level)
Task DeleteWithPurgeAsync(
IEnumerable objectIds,
int batchSize = 10,
IProgress? progress = null,
CancellationToken cancellationToken = default,
long? trashParentId = null);
///
/// Purge a trash container created by SoftDeleteAsync.
/// Physically deletes objects in batches with progress callback.
/// Call this after SoftDeleteAsync if you want to control purge timing separately.
///
/// Trash container ID from DeletionMark.TrashId
/// Total objects to delete (from DeletionMark.MarkedCount)
/// Number of objects to delete per batch
/// Optional progress reporter
/// Cancellation token
Task PurgeTrashAsync(
long trashId,
int totalCount,
int batchSize = 10,
IProgress? progress = null,
CancellationToken cancellationToken = default);
///
/// Gets deletion progress for a specific trash container from database.
/// Returns null if trash container not found or already deleted.
///
/// Trash container ID
/// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes).
Task GetDeletionProgressAsync(long trashId, CancellationToken cancellationToken = default);
///
/// Gets all active (pending/running) deletions for a user from database.
///
/// User ID
/// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes).
Task> GetUserActiveDeletionsAsync(long userId, CancellationToken cancellationToken = default);
///
/// Gets orphaned deletion tasks for recovery at startup.
/// CLUSTER-SAFE: Returns 'pending' OR 'running' with stale _date_modify.
///
/// Minutes after which 'running' task is considered orphaned
/// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes).
Task> GetOrphanedDeletionTasksAsync(int timeoutMinutes = 30, CancellationToken cancellationToken = default);
///
/// Atomically claim an orphaned task for processing.
/// CLUSTER-SAFE: Uses atomic UPDATE to prevent race conditions.
///
/// Trash container ID to claim
/// Minutes for stale check
/// True if successfully claimed, false if already taken by another instance
/// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes).
Task TryClaimOrphanedTaskAsync(long trashId, int timeoutMinutes = 30, CancellationToken cancellationToken = default);
// ===== BULK OPERATIONS (WITHOUT PERMISSION CHECK) =====
///
/// BULK INSERT: Create many new objects in one operation (does NOT check permissions).
/// - Creates schemes if missing (similar to SaveAsync)
/// - Generates IDs for objects with id == 0 via GetNextKey
/// - Fully processes recursive nested objects, arrays, Class fields
/// - Uses BulkInsert for maximum performance
/// - If id != 0, relies on DB errors for duplicates (does not check in advance)
/// - An object the given ones refer to that is already in the database is a reference: its id is written, the
/// object itself is neither inserted nor changed
/// - A nested new object keeps the ParentId it carries (null when none was set), as in SaveAsync: a reference
/// is not a place in the tree
///
Task> AddNewObjectsAsync(IEnumerable> objects, CancellationToken cancellationToken = default) where TProps : class, new();
///
/// BULK INSERT with explicit user: Create many new objects (does NOT check permissions).
/// - Sets OwnerId and WhoChangeId for all objects from specified user
/// - Rest of logic identical to AddNewObjectsAsync without user
///
Task> AddNewObjectsAsync(IEnumerable> objects, IRedbUser user, CancellationToken cancellationToken = default) where TProps : class, new();
// NOTE: Non-generic RedbObject (Object scheme) uses existing methods:
// - SaveAsync(IEnumerable) - RedbObject : IRedbObject
// - LoadAsync(IEnumerable) - returns List, cast to RedbObject
// ===== LOAD WITH PARENT CHAIN =====
///
/// Load object from EAV by ID with parent chain to root (uses _securityContext).
/// Returns TreeRedbObject with populated Parent property up to root.
/// Returns null if object not found and config.ThrowOnObjectNotFound = false.
///
/// Object ID to load
/// Depth for loading nested objects in Props
/// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes).
Task?> LoadWithParentsAsync(long objectId, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new();
///
/// Load object from EAV with parent chain to root (uses _securityContext).
/// Returns TreeRedbObject with populated Parent property up to root.
/// Returns null if object not found and config.ThrowOnObjectNotFound = false.
///
Task?> LoadWithParentsAsync(IRedbObject obj, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new();
///
/// Load object from EAV by ID with parent chain to root with explicit user.
/// Returns TreeRedbObject with populated Parent property up to root.
/// Returns null if object not found and config.ThrowOnObjectNotFound = false.
///
Task?> LoadWithParentsAsync(long objectId, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new();
///
/// Load object from EAV with parent chain to root with explicit user.
/// Returns TreeRedbObject with populated Parent property up to root.
/// Returns null if object not found and config.ThrowOnObjectNotFound = false.
///
Task?> LoadWithParentsAsync(IRedbObject obj, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new();
///
/// Bulk load objects by ID with parent chains to root (uses _securityContext).
/// Each object has its Parent chain populated up to root.
/// Parent objects that are common across multiple chains are shared (same reference).
///
/// Object IDs to load
/// Depth for loading nested objects in Props
/// Cancels the operation; see the cancellation contract in the plan (OCE only, rollback always completes).
Task>> LoadWithParentsAsync(IEnumerable objectIds, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new();
///
/// Bulk load objects by ID with parent chains to root with explicit user.
/// Each object has its Parent chain populated up to root.
/// Parent objects that are common across multiple chains are shared (same reference).
///
Task>> LoadWithParentsAsync(IEnumerable objectIds, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default) where TProps : class, new();
///
/// Bulk polymorphic load of objects by ID with parent chains (uses _securityContext).
/// Supports objects of different schemes in one request.
/// Each object has its Parent chain populated up to root.
///
Task> LoadWithParentsAsync(IEnumerable objectIds, int depth = 10, CancellationToken cancellationToken = default);
///
/// Bulk polymorphic load of objects by ID with parent chains with explicit user.
/// Supports objects of different schemes in one request.
/// Each object has its Parent chain populated up to root.
///
Task> LoadWithParentsAsync(IEnumerable objectIds, IRedbUser user, int depth = 10, CancellationToken cancellationToken = default);
// ===== LAZY REFERENCE RELOAD (V4, LAZY Л2 §4.6) =====
///
/// Loads a COLLECTION of reference stubs under a loaded parent in ONE batch query - the
/// antidote to N+1 on lazy collections. Already-loaded references are skipped; a stub whose
/// target left for the trash gets null Props, not an exception.
///
Task LoadReferencesAsync(RedbObject parent,
Func?>?> references,
CancellationToken cancellationToken = default)
where TProps : class, new() where TRef : class, new();
/// Single-reference form of .
Task LoadReferencesAsync(RedbObject parent,
Func?> reference,
CancellationToken cancellationToken = default)
where TProps : class, new() where TRef : class, new();
// ===== ROW-LEVEL LOCKING =====
///
/// Acquire row-level locks on objects by id within the current transaction and report how
/// many of the requested rows exist (and are therefore locked). A deleted or never-created
/// id locks nothing and is NOT an error here - the returned count is the signal; compare it
/// with your distinct id set (BR-9, 2026-09-02: a silent no-op lock plus the default
/// MissingObjectStrategy.AutoSwitchToInsert let a CAS save resurrect a deleted object).
/// Must be called inside an active transaction (
/// or ): locks release when the
/// transaction ends. Rows are locked in ascending id order, so concurrent lockers do not
/// deadlock on each other. PostgreSQL: SELECT ... FOR UPDATE. MSSQL: WITH (UPDLOCK, ROWLOCK).
/// SQLite: an existence check only - writers are serialized database-wide.
///
/// IDs of objects to lock
/// How many distinct requested ids exist in _objects (those rows are locked).
Task LockForUpdateAsync(params long[] objectIds);
///
/// Paired overload: params is incompatible with a trailing token (B1 amendment).
Task LockForUpdateAsync(long[] objectIds, CancellationToken cancellationToken);
///
/// Strict form of for CAS patterns (lock -> re-read -> save):
/// every requested id must exist. Throws
/// naming the missing ids, and refuses with to run
/// outside an active transaction, where a "lock" would guarantee nothing.
///
/// IDs of objects that must all be locked
Task LockForUpdateRequiredAsync(params long[] objectIds);
///
/// Paired overload: params is incompatible with a trailing token (B1 amendment).
Task LockForUpdateRequiredAsync(long[] objectIds, CancellationToken cancellationToken);
}
}