Path: redb/redb.Core/Providers/Base/ObjectStorageProviderBase.SaveAsyncBatch.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.SaveAsyncBatch.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.Models.Contracts;
using redb.Core.Models.Entities;
using redb.Core.Models.Configuration;
using redb.Core.Models.Security;
using redb.Core.Caching;
using redb.Core.Query;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace redb.Core.Providers.Base
{
///
/// BATCH SAVE - high-performance saving of multiple objects
/// Supports two strategies: DeleteInsert (bulk operations) and ChangeTracking (EF diff)
///
public abstract partial class ObjectStorageProviderBase
{
///
/// Convert IRedbObject to RedbObjectRow for bulk operations
/// Uses 'as' optimization for direct access to RedbObject fields.
///
protected RedbObjectRow ConvertToObjectRecord(IRedbObject obj)
{
var redbObj = obj as RedbObject; // Optimization: direct access to fields
var record = new RedbObjectRow
{
Id = redbObj?.id ?? obj.Id,
IdScheme = redbObj?.scheme_id ?? obj.SchemeId,
IdParent = (redbObj?.parent_id ?? obj.ParentId) == 0 ? null : (redbObj?.parent_id ?? obj.ParentId),
IdOwner = redbObj?.owner_id ?? obj.OwnerId,
IdWhoChange = redbObj?.who_change_id ?? obj.WhoChangeId,
Name = redbObj?.name ?? obj.Name,
Hash = redbObj?.hash ?? obj.Hash,
ValueUnique = redbObj?.value_unique ?? obj.ValueUnique,
DateBegin = redbObj?.date_begin ?? obj.DateBegin,
DateComplete = redbObj?.date_complete ?? obj.DateComplete,
Key = redbObj?.key ?? obj.Key,
ValueLong = redbObj?.value_long ?? obj.ValueLong,
ValueString = redbObj?.value_string ?? obj.ValueString,
ValueGuid = redbObj?.value_guid ?? obj.ValueGuid,
ValueBool = redbObj?.value_bool ?? obj.ValueBool,
ValueDouble = redbObj?.value_double ?? obj.ValueDouble,
ValueNumeric = redbObj?.value_numeric ?? obj.ValueNumeric,
ValueDatetime = redbObj?.value_datetime ?? obj.ValueDatetime,
ValueBytes = redbObj?.value_bytes ?? obj.ValueBytes,
Note = redbObj?.note ?? obj.Note
};
// Handle creation/modification dates based on configuration
if (_configuration.AutoSetModifyDate)
{
if (record.Id == 0)
{
record.DateCreate = DateTimeOffset.UtcNow;
}
else
{
// For existing objects - take the old value
var existingDate = redbObj?.date_create ?? obj.DateCreate;
// If the date was not set (MinValue), use the current one
record.DateCreate = existingDate == DateTimeOffset.MinValue ? DateTimeOffset.UtcNow : existingDate;
}
record.DateModify = DateTimeOffset.UtcNow;
}
else
{
var dateCreate = redbObj?.date_create ?? obj.DateCreate;
// If the date was not set (MinValue), use the current one
record.DateCreate = dateCreate == DateTimeOffset.MinValue ? DateTimeOffset.UtcNow : dateCreate;
var dateModify = redbObj?.date_modify ?? obj.DateModify;
record.DateModify = dateModify == DateTimeOffset.MinValue ? DateTimeOffset.UtcNow : dateModify;
}
// The saved object carries the dates its row gets. For an existing object DateCreate
// already holds the stored value (SelectExistingAndTakeCreateDatesAsync), which the
// update leaves untouched in the database.
obj.DateCreate = record.DateCreate;
obj.DateModify = record.DateModify;
return record;
}
///
/// A row of the existing-objects query: an existing object (Id, DateCreate and its scheme's hash), or one of the
/// listed schemes (Id 0, DateCreate null), so that a save of new objects only learns the hashes as well.
///
private sealed class IdDateCreateRow
{
public long Id { get; set; }
public DateTimeOffset? DateCreate { get; set; }
/// The structure hash of the scheme as stored now; null from a dialect that does not read it.
public Guid? SchemeHash { get; set; }
public long SchemeId { get; set; }
}
///
/// The existing-objects query: the rows of that exist, and the stored structure hash
/// of every scheme of , in one statement. The object part is the query it always was,
/// on the object ids; the scheme part reads _schemes by its key.
///
private async Task<(List Existing, Dictionary HashByScheme)> SelectExistingAndSchemeHashesAsync(
long[] objectIds, IEnumerable objects, System.Threading.CancellationToken cancellationToken)
{
var schemeIds = objects.Select(o => o.SchemeId).Where(id => id != 0).Distinct().ToArray();
var rows = await _context.QueryAsync(
Sql.ObjectStorage_SelectExistingCreateDates(), new object[] { objectIds, schemeIds }, cancellationToken);
var hashByScheme = new Dictionary();
foreach (var row in rows)
hashByScheme[row.SchemeId] = row.SchemeHash;
return (rows.Where(r => r.Id != 0).ToList(), hashByScheme);
}
///
/// The save's view of each scheme against the database, from the hashes the existing-objects query already
/// returns (no round trip of its own): a cached scheme whose hash differs is read again, so a field or a version a
/// newer build wrote since is seen by this save. Then the version rule: a class older than the version the scheme
/// was synchronised with saves nothing of it (a newer build may have removed fields or changed types). Every
/// object of the save counts, new ones included. Returns whether a scheme was read again.
///
private async Task RefreshStaleSchemesAsync(
IEnumerable objects, Dictionary hashByScheme, System.Threading.CancellationToken cancellationToken)
{
var readAgain = false;
foreach (var group in objects.Where(o => hashByScheme.ContainsKey(o.SchemeId)).GroupBy(o => (o.SchemeId, Type: o.GetType())))
{
var generic = RedbObjectTypes.GenericOf(group.Key.Type);
if (generic == null)
continue;
var propsType = generic.GetGenericArguments()[0];
var stored = hashByScheme[group.Key.SchemeId];
var scheme = await _schemeSync.GetSchemeByTypeAsync(propsType, cancellationToken);
if (scheme == null || scheme.Id != group.Key.SchemeId)
continue;
if (stored.HasValue && scheme.StructureHash != stored)
{
// The invalidation drops the structure trees of the scheme as well (GlobalMetadataCache).
Cache.InvalidateScheme(scheme.Id);
Cache.InvalidateScheme(scheme.Name);
readAgain = true;
scheme = await _schemeSync.GetSchemeByIdAsync(scheme.Id, cancellationToken);
if (scheme == null)
continue;
}
var classVersion = System.Reflection.CustomAttributeExtensions.GetCustomAttribute(propsType)?.Version ?? 0;
var storedVersion = (scheme as RedbScheme)?.Version ?? 0;
if (storedVersion > classVersion)
throw new Exceptions.RedbPropsClassOlderException(scheme.Name, propsType, classVersion, storedVersion);
}
return readAgain;
}
///
/// A scheme of the save was changed by another process since this one cached it, and was read again before
/// anything was written: the save builds its value rows again from the current structures and runs once more.
/// The check is the first statement of each strategy, after the object locks only.
///
private sealed class SchemeReadAgainException : Exception
{
}
/// How many times one save builds its rows again after a scheme changed under it.
private const int SchemeReadAgainLimit = 2;
///
/// Ids of the objects that exist in the database. Each existing object takes its stored
/// creation date: an object built in memory (from JSON, say) and saved onto an existing row
/// had DateCreate 0001-01-01 after the save, while the row kept its own date.
/// Only the ids the caller set are looked up: an object this save gave its id is new ();
/// a save of new objects only sends the scheme part of the statement alone.
///
///
/// An object saved under the id of a stored object of another scheme (a different class, or an object in the trash,
/// scheme -10): the update kept the stored scheme, deleted its values and wrote the values of the saved class
/// into it. Refused before anything is written, from the scheme the existing-objects query already returns.
///
private static void RefuseOtherSchemeObjects(List objects, List rows)
{
if (rows.Count == 0) return;
var storedScheme = rows.ToDictionary(r => r.Id, r => r.SchemeId);
foreach (var obj in objects)
{
if (obj.Id != 0 && obj.SchemeId != 0
&& storedScheme.TryGetValue(obj.Id, out var stored) && stored != obj.SchemeId)
{
var type = obj.GetType().IsGenericType ? obj.GetType().GetGenericArguments()[0] : obj.GetType();
throw new Exceptions.RedbSchemeMismatchException(obj.Id, type, obj.SchemeId, stored,
$"Object {obj.Id} belongs to scheme {stored}" +
(stored == Utils.RedbTypeIds.DeletedScheme ? " (it is in the trash)" : "") +
$", but was saved as '{type.FullName ?? type.Name}' which maps to scheme {obj.SchemeId}. " +
"Saving it would delete its values and write the values of another class into it; nothing was " +
"written. Save a new object (id 0) or load the object under its own class.");
}
}
}
protected async Task> SelectExistingAndTakeCreateDatesAsync(
List objects, System.Threading.CancellationToken cancellationToken)
{
if (objects.Count == 0)
return new HashSet();
var created = _createdBySave;
var ids = objects.Where(o => created == null || !created.Contains(o)).Select(o => o.Id).ToArray();
var (rows, hashByScheme) = await SelectExistingAndSchemeHashesAsync(ids, objects, cancellationToken);
RefuseOtherSchemeObjects(objects, rows);
var createdById = rows.ToDictionary(r => r.Id, r => r.DateCreate!.Value);
// The value rows of this save were built from the trees of the schemes as they were cached: built again.
if (await RefreshStaleSchemesAsync(objects, hashByScheme, cancellationToken))
throw new SchemeReadAgainException();
foreach (var obj in objects)
{
if (createdById.TryGetValue(obj.Id, out var dateCreate))
obj.DateCreate = dateCreate;
}
return createdById.Keys.ToHashSet();
}
// ===== PUBLIC BATCH SAVE METHODS =====
///
/// BATCH SAVE: Save multiple objects (new + updates)
/// Uses _securityContext to get the user
///
public async Task> SaveAsync(IEnumerable objects, CancellationToken cancellationToken = default)
{
var effectiveUser = _securityContext.GetEffectiveUser();
return await SaveAsync(objects, effectiveUser, cancellationToken);
}
///
/// BATCH SAVE with explicit user
/// Supports two strategy modes:
/// - DeleteInsert: delete ALL values → BulkInsert/BulkUpdate of objects → BulkInsert of values
/// - ChangeTracking: tree-based diff → two-phase EF SaveChanges
///
public async Task> SaveAsync(IEnumerable objects, IRedbUser user, CancellationToken cancellationToken = default)
{
// CT-4 (решение владельца 2026-09-04, «как у EF»): контракт «один scope - один
// поток» защищён операционным детектором уровня EF DbContext. Командный страж
// соединения ловит только НАЛОЖИВШИЕСЯ команды; два перемежающихся async-сохранения
// могли молча перемешать pending-состояние ChangeTracking и транзакции. Вход -
// синхронно, до первого await, поэтому второй параллельный заход детерминированно
// получает исключение.
if (System.Threading.Interlocked.CompareExchange(ref _saveOperationInFlight, 1, 0) != 0)
throw new InvalidOperationException(
"A second SaveAsync started on this IRedbService scope before a previous one " +
"completed. Один scope - это одно соединение и одно операционное состояние " +
"(как DbContext в EF): параллельные сохранения ведите через отдельные scoped-сервисы.");
try
{
return await SaveBatchCoreAsync(objects, user, cancellationToken);
}
finally
{
_createdBySave = null;
System.Threading.Interlocked.Exchange(ref _saveOperationInFlight, 0);
}
}
private int _saveOperationInFlight;
///
/// The objects of the running save that got their id from it (AssignMissingIds). They are new by definition and
/// are never looked up as existing: an id the key cache handed out twice (a block cached before a restore or an
/// import) then fails on the primary key instead of updating the row that has the id. Set and cleared by the
/// batch save; one save at a time per scope (CT-4).
///
private HashSet? _createdBySave;
private sealed class IdHashRow
{
public long Id { get; set; }
public Guid? Hash { get; set; }
}
///
/// F1 (CT hash shortcut): ids of existing objects whose freshly recomputed content hash
/// equals the persisted _objects._hash. Root hashes come free with the phase-1
/// existence check; one extra SELECT runs only when the collected graph brought nested
/// existing objects. An object with no in-memory hash or no persisted hash is never listed
/// (legacy hashes computed by an older canon simply fail the comparison and take the full
/// path, migrating on save).
///
private async Task?> SelectUnchangedByHashAsync(
List allObjectsToSave, Dictionary dbHashById, CancellationToken cancellationToken)
{
var candidates = allObjectsToSave.Where(o => o.Id > 0 && o.Hash.HasValue).ToList();
if (candidates.Count == 0) return null;
var missingIds = candidates.Where(o => !dbHashById.ContainsKey(o.Id))
.Select(o => o.Id).Distinct().ToArray();
if (missingIds.Length > 0)
{
var rows = await _context.QueryAsync(
Sql.ObjectStorage_SelectIdHashPairs(), new object[] { missingIds }, cancellationToken);
foreach (var row in rows)
dbHashById[row.Id] = row.Hash;
}
var unchanged = new HashSet();
foreach (var obj in candidates)
{
if (dbHashById.TryGetValue(obj.Id, out var dbHash) &&
dbHash.HasValue && dbHash.Value == obj.Hash!.Value)
unchanged.Add(obj.Id);
}
return unchanged.Count > 0 ? unchanged : null;
}
private async Task> SaveBatchCoreAsync(IEnumerable objects, IRedbUser user, CancellationToken cancellationToken)
{
var objList = objects.ToList();
if (objList.Count == 0) return new List();
foreach (var obj in objList)
RefuseUnloadedReference(obj);
// === PHASE 1: VALIDATION AND PREPARATION (BATCH OPTIMIZATION) ===
// STEP 1: Hash recomputation (in-memory, no DB queries)
// Supports: RedbObject with Props, RedbObject with Props=null, RedbObject (non-generic)
foreach (var obj in objList)
RecomputeHash(obj);
// STEP 2: BATCH existence check (1 query instead of N!)
// F1: under ChangeTracking the same query also returns the persisted hash of each
// existing root, so the hash shortcut costs no extra round-trip for the typical save.
// Other strategies keep the id-only query - they never consult the hashes.
var ctShortcutActive = _configuration.PropsSaveStrategy == PropsSaveStrategy.ChangeTracking
&& _configuration.AutoRecomputeHash;
var existingIds = objList.Where(o => o.Id != 0).Select(o => o.Id).ToArray();
var dbHashById = new Dictionary(existingIds.Length);
HashSet existingIdsSet;
if (existingIds.Length == 0)
{
existingIdsSet = new HashSet();
}
else if (ctShortcutActive)
{
var idHashRows = await _context.QueryAsync(
Sql.ObjectStorage_SelectIdHashPairs(), new object[] { existingIds }, cancellationToken);
foreach (var row in idHashRows)
dbHashById[row.Id] = row.Hash;
existingIdsSet = dbHashById.Keys.ToHashSet();
}
else
{
var loadedIds = await _context.QueryScalarListAsync(
Sql.ObjectStorage_SelectExistingIds(), new object[] { existingIds }, cancellationToken);
existingIdsSet = loadedIds.ToHashSet();
}
// Processing of missing objects
foreach (var obj in objList.Where(o => o.Id != 0 && !existingIdsSet.Contains(o.Id)))
{
switch (_configuration.MissingObjectStrategy)
{
case MissingObjectStrategy.AutoSwitchToInsert:
obj.Id = 0;
break;
case MissingObjectStrategy.ReturnNull:
throw new InvalidOperationException($"Object with id {obj.Id} not found. Strategy: ReturnNull is not supported.");
case MissingObjectStrategy.ThrowException:
default:
throw new InvalidOperationException($"Object with id {obj.Id} not found.");
}
}
// STEP 3: BATCH auto-detection of schemes (caching by type)
var schemeCache = new Dictionary();
long? objectSchemeId = null; // Cache for non-generic RedbObject scheme
foreach (var obj in objList.Where(o => o.SchemeId == 0 && _configuration.AutoSyncSchemesOnSave))
{
var objType = obj.GetType();
var genericObjType = Utils.RedbObjectTypes.GenericOf(objType);
if (genericObjType != null)
{
var propsType = genericObjType.GetGenericArguments()[0];
// Check cache
if (schemeCache.TryGetValue(propsType, out var cachedSchemeId))
{
obj.SchemeId = cachedSchemeId;
continue;
}
// Load/sync the scheme (select generic overload without parameters)
var getSchemeMethod = typeof(ISchemeSyncProvider)
.GetMethods()
.FirstOrDefault(m => m.Name == nameof(ISchemeSyncProvider.GetSchemeByTypeAsync)
&& m.IsGenericMethod
&& m.GetParameters() is [{ ParameterType.Name: nameof(CancellationToken) }])?
.MakeGenericMethod(propsType);
if (getSchemeMethod != null)
{
var existingSchemeTask = (Task?)getSchemeMethod.Invoke(_schemeSync, new object[] { cancellationToken });
if (existingSchemeTask != null)
{
await existingSchemeTask.ConfigureAwait(false);
var existingScheme = existingSchemeTask.GetType().GetProperty("Result")?.GetValue(existingSchemeTask) as IRedbScheme;
if (existingScheme != null)
{
obj.SchemeId = existingScheme.Id;
schemeCache[propsType] = existingScheme.Id;
}
else if (_configuration.AutoSyncSchemesOnSave)
{
var syncMethod = typeof(ISchemeSyncProvider)
.GetMethods()
.FirstOrDefault(m => m.Name == nameof(ISchemeSyncProvider.SyncSchemeAsync)
&& m.IsGenericMethod
&& m.GetParameters() is [{ ParameterType.Name: nameof(CancellationToken) }])?
.MakeGenericMethod(propsType);
if (syncMethod != null)
{
var syncTask = (Task?)syncMethod.Invoke(_schemeSync, new object[] { cancellationToken });
if (syncTask != null)
{
await syncTask.ConfigureAwait(false);
var scheme = syncTask.GetType().GetProperty("Result")?.GetValue(syncTask) as IRedbScheme;
if (scheme != null)
{
obj.SchemeId = scheme.Id;
schemeCache[propsType] = scheme.Id;
}
}
}
}
}
}
}
else if (objType == typeof(RedbObject))
{
// Non-generic RedbObject - use Object scheme
if (objectSchemeId == null)
{
var objectScheme = await _schemeSync.EnsureObjectSchemeAsync("RedbObject");
objectSchemeId = objectScheme.Id;
}
obj.SchemeId = objectSchemeId.Value;
}
}
// STEP 4: BATCH permissions check
if (_configuration.DefaultCheckPermissionsOnSave)
{
// Load unique schemes once
var uniqueSchemeIds = objList.Select(o => o.SchemeId).Distinct().ToArray();
var schemesList = await _context.QueryAsync(
Sql.ObjectStorage_SelectSchemesByIds(), new object[] { uniqueSchemeIds }, cancellationToken);
var schemesDict = schemesList.ToDictionary(s => s.Id, s => s);
// Check INSERT permissions for new objects
var newObjectsByScheme = objList.Where(o => o.Id == 0).GroupBy(o => o.SchemeId);
foreach (var group in newObjectsByScheme)
{
if (schemesDict.TryGetValue(group.Key, out var schemeContract))
{
var canInsert = await _permissionProvider.CanUserInsertScheme(schemeContract, user);
if (!canInsert)
{
throw new UnauthorizedAccessException($"User {user.Id} has no create permission for objects in scheme {group.Key}");
}
}
}
// Check UPDATE permissions for existing objects
foreach (var obj in objList.Where(o => o.Id != 0))
{
var canUpdate = await _permissionProvider.CanUserEditObject(obj, user);
if (!canUpdate)
{
throw new UnauthorizedAccessException($"User {user.Id} has no update permission for object {obj.Id}");
}
}
}
// === PHASE 2: COLLECTION OF ALL OBJECTS (MAIN + NESTED) ===
var allObjectsToSave = new List();
var allValuesToSave = new List();
var processedObjectIds = new HashSet();
var seenInstances = new HashSet