#region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Primitives; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion namespace Lumina.DataAccess.Common.Persistence; /// /// Resolves shared reference rows, whose identity is their name, so that each distinct name is represented by a single tracked instance. /// /// /// This is the toolkit's only concern expressed over a family of entity shapes, through the marker interface: /// a shared reference is resolved by its name, the stored row wins over the incoming instance, and within-request duplicates are collapsed to one instance. /// No per-entity method is ever needed, so a new shared reference type adds no new persistence type. A shared reference whose name is null or whitespace /// cannot be keyed and would be lost silently, so it fails the resolution with the caller-provided error instead of being dropped. /// internal static class SharedReferenceResolver { /// /// Resolves the single instance that represents each distinct name carried by . /// /// /// The stored row wins over the incoming instance, so that a shared reference that is already persisted is reused instead of inserted again. The /// instances are also collapsed by name, so that a name shared by several parents of the same request is only ever tracked once. /// /// The type of the shared reference entity. /// The Entity Framework context the stored rows are read through. /// The shared references carried by the entity that is about to be persisted. /// The error returned when a shared reference carries a name that is null or whitespace. /// Cancellation token that can be used to stop the execution. /// A result containing either a dictionary that maps each distinct name to the single instance that represents it, or an error. internal static async Task>> ResolveAsync(LuminaDbContext context, IEnumerable incomingEntities, Error invalidNameError, CancellationToken cancellationToken) where TEntity : class, ISharedReferenceEntity { // A shared reference whose name is null or whitespace cannot be keyed, and the database requires the name to be present, so the whole resolution // fails instead of silently dropping the reference. Dictionary resolvedByName = new(StringComparer.Ordinal); foreach (TEntity incomingEntity in incomingEntities) { string? name = incomingEntity.Name; if (string.IsNullOrWhiteSpace(name)) return invalidNameError; resolvedByName.TryAdd(name, incomingEntity); } if (resolvedByName.Count == 0) return resolvedByName; // Prefer the instances that the context already tracks, so that a reference resolved earlier in the same request does not trigger another query. HashSet namesResolvedFromTrackedEntities = []; foreach (TEntity trackedEntity in context.Set().Local) { string? trackedName = trackedEntity.Name; if (!string.IsNullOrWhiteSpace(trackedName) && resolvedByName.ContainsKey(trackedName)) { resolvedByName[trackedName] = trackedEntity; namesResolvedFromTrackedEntities.Add(trackedName); } } // Only the names that are not already tracked are read from the storage medium. List unresolvedNames = [.. resolvedByName.Keys.Where(name => !namesResolvedFromTrackedEntities.Contains(name))]; if (unresolvedNames.Count > 0) { List storedEntities = await context.Set() .Where(entity => unresolvedNames.Contains(EF.Property(entity, nameof(ISharedReferenceEntity.Name)))) .ToListAsync(cancellationToken).ConfigureAwait(false); foreach (TEntity storedEntity in storedEntities) resolvedByName[storedEntity.Name!] = storedEntity; } return resolvedByName; } /// /// Maps to the single resolved instance that represents each of their names. /// /// The type of the shared reference entity. /// The shared references that must be mapped to their resolved instances. /// The resolved instances, as returned by . /// The resolved instances, without any duplicate. internal static IReadOnlyCollection Normalize(IEnumerable incomingEntities, IReadOnlyDictionary resolvedEntities) where TEntity : class, ISharedReferenceEntity { HashSet normalizedEntities = []; foreach (TEntity incomingEntity in incomingEntities) { string? name = incomingEntity.Name; if (string.IsNullOrWhiteSpace(name)) continue; if (resolvedEntities.TryGetValue(name, out TEntity? resolvedEntity) && resolvedEntity is not null) normalizedEntities.Add(resolvedEntity); } return normalizedEntities; } /// /// Reconciles the shared reference collection against , reusing the stored rows whose names already exist. /// /// The type of the shared reference entity. /// The Entity Framework context the stored rows are read through. /// The tracked collection that is reconciled in place. /// The desired shared references. /// The error returned when a shared reference carries a name that is null or whitespace. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. internal static async Task> ReconcileAsync(LuminaDbContext context, ICollection existingEntities, IEnumerable incomingEntities, Error invalidNameError, CancellationToken cancellationToken) where TEntity : class, ISharedReferenceEntity { List incomingList = [.. incomingEntities]; Result> resolveResult = await ResolveAsync(context, incomingList, invalidNameError, cancellationToken).ConfigureAwait(false); if (resolveResult.IsFailure) return resolveResult.Errors; CollectionReconciler.Reconcile( existingEntities, Normalize(incomingList, resolveResult.Value), existingEntity => existingEntity.Name!, incomingEntity => incomingEntity.Name!, shouldReplace: (existingEntity, incomingEntity) => false, createNew: incomingEntity => incomingEntity); return Result.Updated; } }