using Titano.Core.Archiving; using Titano.Core.Diagnostics; using Titano.Core.Localization; using Titano.Core.Model; using Titano.Data.Repositories; namespace Titano.Data.Archiving; /// /// The plan no longer matches the archive: a sequence moved or vanished since it was made, or one was indexed inside a /// folder the plan moves. /// public sealed class StaleRenamePlanException(Guid sequenceId) : InvalidOperationException(Loc.L("Archive.Error.StalePlan")) { public Guid SequenceId { get; } = sequenceId; } /// /// Mass rename of sequence folders and titles (BRIEF §7, §12.5): is the dry run; /// makes exactly the planned changes to folders, sidecars and the index, step by step, with a /// journal on the archive so an interrupted rename is completed by . /// public sealed class MassRenamer { private readonly TitanoDatabase _db; private readonly SequenceWriter _writer; private readonly ArchiveIndexer _indexer; internal MassRenamer(TitanoDatabase db, SequenceWriter writer, ArchiveIndexer indexer) { _db = db; _writer = writer; _indexer = indexer; } /// New folder template ({title} = the new title), or null to keep folders. /// New title template ({title} = the current title), or null to keep titles. /// Sequences nested in a folder that moves are part of the plan (they move with it); see . /// A new folder would lie inside a sequence's folder. public async Task PlanAsync(Archive archive, IReadOnlyList sequenceIds, string? folderTemplate, string? titleTemplate, CancellationToken cancellationToken = default) { var paths = new ArchivePaths(archive.RootPath); var locations = await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false); var subjects = new List(sequenceIds.Count); foreach (var id in sequenceIds) { if (await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } s || s.ArchiveId != archive.Id) throw new ArgumentException($"Sequence {id} is not in archive {archive.Id}.", nameof(sequenceIds)); subjects.Add(Subject(s)); } var nested = new List(); if (folderTemplate is not null) { var selected = sequenceIds.ToHashSet(); foreach (var location in locations.Where(l => !selected.Contains(l.Id) && subjects.Any(s => RenamePlanner.IsInside(s.Folder, l.Folder)))) { if (await _db.Sequences.GetAsync(location.Id, cancellationToken).ConfigureAwait(false) is { } inner) nested.Add(Subject(inner)); } } return RenamePlanner.Plan(archive.Id, subjects, folderTemplate, titleTemplate, locations.Select(l => l.Folder), folder => Directory.Exists(paths.Sequence(folder).Folder), nested); } private static RenameSubject Subject(Sequence s) => new(s.Id, s.Folder, s.Title, s.FirstCapture, s.CameraMake, s.CameraModel, s.Lens); /// Applies a plan; each completed step is journaled before the next starts. /// A sequence is no longer where the plan expects it, or a folder that moves holds /// a sequence the plan does not take along; nothing of that step was changed. public Task ApplyAsync(Archive archive, RenamePlan plan, IProgress? progress = null, CancellationToken cancellationToken = default) => RunAsync(archive, new RenameJournal(plan, []), resuming: false, progress, cancellationToken); /// Completes renames interrupted by a crash; returns how many plans were resumed. public async Task ResumePendingAsync(Archive archive, CancellationToken cancellationToken = default) { var paths = new ArchivePaths(archive.RootPath); var pending = RenameJournal.ListPending(paths).Where(j => j.Plan.ArchiveId == archive.Id).ToList(); foreach (var journal in pending) await RunAsync(archive, journal, resuming: true, null, cancellationToken).ConfigureAwait(false); return pending.Count; } /// Steps whose sequence the index no longer knows are dropped instead of failing the rename: /// their sidecars still carry the ids, so the next scan indexes them wherever they ended up. private async Task RunAsync(Archive archive, RenameJournal journal, bool resuming, IProgress? progress, CancellationToken cancellationToken) { var paths = new ArchivePaths(archive.RootPath); ArchiveVolume.EnsureWritable(paths); if (journal.Plan.ArchiveId != archive.Id) throw new ArgumentException("The plan belongs to another archive.", nameof(journal)); var completed = journal.Completed.ToHashSet(); if (!resuming) { // A plan made before another change is refused before anything moves: a sequence moved, or one was indexed // inside a folder that moves (a scan adopted a subfolder copied in since the dry run). foreach (var step in journal.Plan.Steps) { if ((await _db.Sequences.GetAsync(step.SequenceId, cancellationToken).ConfigureAwait(false))?.Folder != step.FromFolder) throw new StaleRenamePlanException(step.SequenceId); } var planned = journal.Plan.Steps.Select(s => s.SequenceId).ToHashSet(); if (await StrangerInsideAsync(archive, journal.Plan.Steps.Where(s => s.MovesFolder && !s.Carried), planned, cancellationToken) .ConfigureAwait(false) is { } stranger) throw new StaleRenamePlanException(stranger.Id); } RenameJournal.Write(paths, journal); var steps = journal.Plan.Steps; foreach (var step in steps) { if (completed.Contains(step.SequenceId)) continue; cancellationToken.ThrowIfCancellationRequested(); // A folder that moves carries the sequences inside it: they are locked, moved and recorded with it. IReadOnlyList carried = step.MovesFolder && !step.Carried ? [.. steps.Where(c => c.Carried && !completed.Contains(c.SequenceId) && Carrier(steps, c) == step)] : []; await ApplyStepAsync(archive, paths, step, carried, resuming, cancellationToken).ConfigureAwait(false); completed.Add(step.SequenceId); foreach (var c in carried) completed.Add(c.SequenceId); RenameJournal.Write(paths, journal with { Completed = [.. completed] }); progress?.Report(completed.Count); } RenameJournal.Delete(paths, journal.Plan.Id); } /// The step whose folder move carries : the nearest moving folder around it (as planned). private static RenameStep? Carrier(IReadOnlyList steps, RenameStep carried) => steps.Where(m => !m.Carried && m.MovesFolder && RenamePlanner.IsInside(m.FromFolder, carried.FromFolder)).MaxBy(m => m.FromFolder.Length); /// /// Applies a step, and the steps of the sequences its folder carries, under all their leases: sequence leases, then /// for a move the thumbnail leases, each by sequence id (the order trash and pack compaction take them in). No /// writer of a carried sequence (ingest, an editor save, a thumbnail pass) works in the folder while it moves or /// before its index row follows. /// /// A step whose sequence the index no longer has where the plan says is dropped instead of /// failing the rename: its sidecar still carries the id, so the next scan indexes it wherever it ended up. private async Task ApplyStepAsync(Archive archive, ArchivePaths paths, RenameStep step, IReadOnlyList carried, bool resuming, CancellationToken cancellationToken) { var ids = carried.Select(c => c.SequenceId).Append(step.SequenceId).Order().ToList(); var locks = new List(ids.Count); var leases = new List(ids.Count); try { foreach (var id in ids) locks.Add(await _writer.LockAsync(paths, id, cancellationToken).ConfigureAwait(false)); if (step.MovesFolder) { foreach (var id in ids) { leases.Add(await LeaseFile.AcquireAsync(paths.LocksDirectory, $"thumbs-{id:N}", _writer.Options.Owner, _writer.Options.LeaseWait, _writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false)); } } // Checked before anything moves; a dropped step drops the sequences it would have carried, which stay inside it. if (!await StandsAsync(step, resuming, cancellationToken).ConfigureAwait(false)) return; var follow = new List(carried.Count); foreach (var c in carried) { if (await StandsAsync(c, resuming, cancellationToken).ConfigureAwait(false)) follow.Add(c); } if (!await CarriesAllInsideAsync(archive, paths, step, carried, resuming, cancellationToken).ConfigureAwait(false)) return; RenamePlanner.MoveFolder(paths, step); await RecordAsync(archive, paths, step, cancellationToken).ConfigureAwait(false); // Moved with their carrier: only their sidecars and index rows follow. foreach (var c in follow) await RecordAsync(archive, paths, c, cancellationToken).ConfigureAwait(false); } finally { for (var i = leases.Count - 1; i >= 0; i--) leases[i].Dispose(); for (var i = locks.Count - 1; i >= 0; i--) await locks[i].DisposeAsync().ConfigureAwait(false); } } /// The index still has the step's sequence where the plan says (or where it already took it); otherwise stale. /// Not resuming, and the sequence moved or vanished since the plan was made. private async Task StandsAsync(RenameStep step, bool resuming, CancellationToken cancellationToken) { var row = await _db.Sequences.GetAsync(step.SequenceId, cancellationToken).ConfigureAwait(false); if (row is not null && (row.Folder == step.FromFolder || row.Folder == step.ToFolder)) return true; if (!resuming) throw new StaleRenamePlanException(step.SequenceId); Log.Warning("archive", $"Rename of {step.FromFolder} dropped: the index no longer has that sequence there"); return false; } /// /// Whether every sequence the index has inside the folder of a moving step moves with it as planned, checked again under /// the step's leases just before the folder moves. One indexed there since the dry run would move without its index /// row following, and was never shown in the plan: the step is refused, or dropped when resuming a folder that has not /// moved yet (a folder moved before the interruption goes on; the next scan indexes the newcomer where it ended up). /// /// Not resuming, and such a sequence is inside the folder. private async Task CarriesAllInsideAsync(Archive archive, ArchivePaths paths, RenameStep step, IReadOnlyList carried, bool resuming, CancellationToken cancellationToken) { if (!step.MovesFolder) return true; var taken = carried.Select(c => c.SequenceId).ToHashSet(); if (await StrangerInsideAsync(archive, [step], taken, cancellationToken).ConfigureAwait(false) is not { } stranger) return true; if (!resuming) throw new StaleRenamePlanException(stranger.Id); if (!Directory.Exists(paths.Sequence(step.FromFolder).Folder)) return true; Log.Warning("archive", $"Rename of {step.FromFolder} dropped: {stranger.Folder} was indexed inside it after the plan was made"); return false; } /// A sequence the index has inside the folder of one of that is not in ; null when there is none. private async Task StrangerInsideAsync(Archive archive, IEnumerable moving, IReadOnlySet taken, CancellationToken cancellationToken) { var folders = moving.Select(s => s.FromFolder).ToList(); if (folders.Count == 0) return null; return (await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false)) .FirstOrDefault(l => !taken.Contains(l.Id) && folders.Any(f => RenamePlanner.IsInside(f, l.Folder))); } /// Sidecar title, then index (folder, frames' paths); each part is idempotent so a resumed step can repeat it. private async Task RecordAsync(Archive archive, ArchivePaths paths, RenameStep step, CancellationToken cancellationToken) { var sequence = paths.Sequence(step.ToFolder); var manifest = SequenceWriter.ReadLocked(sequence, step.SequenceId); if (manifest.Title != step.ToTitle) { manifest = manifest with { Title = step.ToTitle, Versions = manifest.Versions with { Settings = manifest.Versions.Settings + 1 }, UpdatedAt = DateTimeOffset.UtcNow, }; ManifestStore.WriteSequence(sequence.ManifestPath, manifest); } await using (var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false)) { var existing = await tx.Sequences.GetAsync(step.SequenceId, cancellationToken).ConfigureAwait(false); await tx.Sequences.UpsertAsync(SequenceMapping.ToSequence(manifest, archive.Id, sequence, existing), cancellationToken).ConfigureAwait(false); if (step.MovesFolder) await tx.Frames.RebaseFolderAsync(step.SequenceId, step.FromFolder, step.ToFolder, cancellationToken).ConfigureAwait(false); await tx.Archives.DeleteFolderStateAsync(archive.Id, step.FromFolder, cancellationToken).ConfigureAwait(false); await tx.CommitAsync(cancellationToken).ConfigureAwait(false); } await _indexer.RecordStampsAsync(archive, sequence, step.SequenceId, cancellationToken).ConfigureAwait(false); } }