using System.Runtime.ExceptionServices; using Chronos.Core.Archiving; using Chronos.Core.Diagnostics; using Chronos.Core.Localization; using Chronos.Core.Model; using Chronos.Core.Naming; using Chronos.Data.Repositories; namespace Chronos.Data.Archiving; /// /// The plan no longer matches the archive: planned again it is another (a job's confirmed plan), a sequence moved or /// vanished since it was made, one was indexed inside a folder the plan moves, something took a folder it moves one into, /// or a title it changes, or names a folder or files after, was edited. /// public sealed class StaleRenamePlanException(Guid sequenceId) : InvalidOperationException(Loc.L("Archive.Error.StalePlan")) { public Guid SequenceId { get; } = sequenceId; } /// /// What applying a plan did, over every run that applied it: the sequences changed (in the order of the plan), the frames /// whose files got a new name, and the sequences not changed as planned: left as they were because they changed since the /// plan (, only when resuming), whose files kept their names because their photos changed since /// (, a sequence still receiving photos among them; their folder and title changed), whose title and /// file names stayed because their title was edited since (, only when resuming; their folder /// moved), whose files kept their names because a photo was in use or a new name was taken (; their /// folder and title changed), and whose title and file names stayed because a newer Chronos wrote their sidecar since /// (, only when resuming; their folder moved, or, planned a new title, they stayed as they were when it /// had not moved yet). /// public sealed record RenameResult(IReadOnlyList Changed, int Files, IReadOnlyList Dropped, IReadOnlyList FilesKept, IReadOnlyList TitlesKept, IReadOnlyList FilesBusy, IReadOnlyList Newer) { /// The result a plan's journal records for its completed steps (). public static RenameResult Of(RenameTally tally) { ArgumentNullException.ThrowIfNull(tally); return new(tally.Changed, tally.Files, tally.Dropped, tally.FilesKept, tally.TitlesKept, tally.FilesBusy, tally.Newer); } } /// /// Mass rename of sequence folders, titles and file names (BRIEF §7, §12.5; Reorganize, owner review 2, R7): /// is the dry run; /// makes exactly the planned changes to /// folders, files, sidecars and the index, step by step, with a journal on the archive so an interrupted rename is /// completed by (or, for a plan its job held, by ). A step's file /// renames have their own journal in the sequence (). /// public sealed class MassRenamer { /// The change a Reorganize tells about a sequence it changed (a server's sequenceChanged event). public const string Change = "reorganized"; private readonly ChronosDatabase _db; private readonly SequenceWriter _writer; private readonly ArchiveIndexer _indexer; internal MassRenamer(ChronosDatabase db, SequenceWriter writer, ArchiveIndexer indexer) { _db = db; _writer = writer; _indexer = indexer; } /// How far a sequence of a step still fits the plan, checked under the step's leases before anything of the step moves. private enum Fit { /// As planned. Whole, /// Its photos changed since the plan (photos added, gone, hashed or copied in): its folder and title change, its files keep their names. Files, /// Its title was edited since the plan: its title and file names stay. Title, /// Its sidecar is of a newer format, which is never rewritten (only when resuming): its title and file names stay. Newer, } /// 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 Task PlanAsync(Archive archive, IReadOnlyList sequenceIds, string? folderTemplate, string? titleTemplate, CancellationToken cancellationToken = default) => PlanAsync(archive, sequenceIds, new RenameTemplates(folderTemplate, null, titleTemplate), cancellationToken); /// /// The dry run of a Reorganize: the plan of over . Each /// sequence's sidecar is read (without its lease), and so is that of every sequence a moving folder would take along: /// the folder and title templates see the first frame as filing did, and a sequence whose sidecar cannot be read stays /// as it is, with every folder around it. With a file template the files beside its frames are listed too, so the plan /// names exactly the files the apply will rename while nothing changes. A sequence created without photos, which has /// no folder yet, is left out. /// /// A sequence is not in the archive. /// A new folder would lie inside a sequence's folder. public async Task PlanAsync(Archive archive, IReadOnlyList sequenceIds, RenameTemplates templates, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(archive); ArgumentNullException.ThrowIfNull(sequenceIds); ArgumentNullException.ThrowIfNull(templates); 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.Distinct()) { 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)); if (ArchiveIngest.AwaitsFolder(s, paths)) continue; subjects.Add(templates.IsEmpty ? Subject(s) : Read(paths, s, listFiles: templates.File is not null)); } var nested = new List(); if (templates.Folder 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(Read(paths, inner, listFiles: false)); } } return RenamePlanner.Plan(archive.Id, subjects, templates.Folder, templates.Title, locations.Select(l => l.Folder), folder => Directory.Exists(paths.Sequence(folder).Folder), nested, templates.File, folder => RenamePlanner.ExistsExactly(paths, folder)); } private static RenameSubject Subject(Sequence s) => new(s.Id, s.Folder, s.Title, s.FirstCapture, s.CameraMake, s.CameraModel, s.Lens); /// /// A sequence with its sidecar and, when , the files beside its frames; marked /// (logged) when the sidecar cannot be read, is another sequence's, or is of a /// newer format this build never rewrites. /// private static RenameSubject Read(ArchivePaths paths, Sequence sequence, bool listFiles) { var folder = paths.Sequence(sequence.Folder); try { var manifest = ManifestStore.ReadSequence(folder.ManifestPath); if (manifest.Id != sequence.Id) Log.Warning("archive", $"{folder.ManifestPath} belongs to sequence {manifest.Id}, not {sequence.Id}; the sequence stays as it is"); else if (manifest.SchemaVersion > SequenceManifest.CurrentSchemaVersion) Log.Warning("archive", $"{folder.ManifestPath} was written by a newer Chronos (format {manifest.SchemaVersion}); the sequence stays as it is"); else return Subject(sequence) with { Files = new SequenceFiles(manifest, listFiles ? FileRenames.ListPresent(folder, manifest) : []) }; } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException) { Log.Warning("archive", $"The sidecar of {sequence.DisplayTitle} cannot be read; the sequence stays as it is", ex); } return Subject(sequence) with { Unreadable = true }; } /// /// Applies a plan; each completed step is journaled before the next starts. A sequence whose photos changed since the /// plan (one still receiving them) refuses nothing: it keeps its file names (), its /// folder and title change as planned, and the steps after it go on. /// /// A sequence is no longer where the plan expects it, a folder that moves holds /// a sequence the plan does not take along, something took a folder the plan moves one into, or a title it changes, or /// names a folder or files after, was edited; nothing of that step was changed (each is checked under the step's leases /// before anything of it moves), the steps before it were. /// A sequence whose title or file names the plan changes has a sidecar of a newer /// format, which this build never rewrites; nothing of that step was changed. /// A folder could not be moved, or () a sequence is /// busy, or holds a restore from the trash whose entry is busy and not settled yet; nothing of that step changed. Once /// the folder of a step moved, a sidecar of the step that cannot be read or written (this, /// or ) fails the step only after every index row of the step followed the folder; its /// title and file names wait for a retry. So does a file that could neither take its new name nor go back, when the /// sequence's journal cannot complete the renames at once either: its next writer does. A file that could not be /// renamed (open elsewhere, or its new name taken) does not fail the step: the sequence keeps its file names /// (). public Task ApplyAsync(Archive archive, RenamePlan plan, IProgress? progress = null, CancellationToken cancellationToken = default) => ApplyAsync(archive, plan, null, progress is null ? null : (n, _) => { progress.Report(n); return ValueTask.CompletedTask; }, cancellationToken); /// /// Told once the plan's journal is written, before any step (a job saves the plan's id as its checkpoint). /// Told after each step is journaled, with the number of steps done and the sequences that step changed. public Task ApplyAsync(Archive archive, RenamePlan plan, Func? started, Func, ValueTask>? stepDone, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(plan); return RunAsync(archive, new RenameJournal(plan, []), resuming: false, started, stepDone, cancellationToken); } /// /// Completes the plan from its journal: one an interruption left (as /// does), or one its job held, whose remaining steps are checked as a plan applied anew (a sequence changed since refuses /// the rest, and that journal goes). Null when there is no journal: the plan completed (here, or at an archive open). /// The result covers the whole plan, the steps of earlier runs included. /// /// Told after each step is journaled, with the number of steps done and the sequences that step changed. /// A held plan's remaining steps no longer match the archive; nothing more changed. public async Task ResumeAsync(Archive archive, Guid planId, Func, ValueTask>? stepDone = null, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(archive); if (RenameJournal.Read(new ArchivePaths(archive.RootPath), planId) is not { } journal) return null; return await RunAsync(archive, journal with { Held = false }, resuming: !journal.Held, null, stepDone, cancellationToken).ConfigureAwait(false); } /// /// Marks the plan held (): its job was paused, cancelled or /// failed between two steps, so an archive open leaves the rest to that job. False when it has no journal (it completed). /// public static bool Hold(Archive archive, Guid planId) { ArgumentNullException.ThrowIfNull(archive); var paths = new ArchivePaths(archive.RootPath); if (RenameJournal.Read(paths, planId) is not { } journal) return false; RenameJournal.Write(paths, journal with { Held = true }); return true; } /// /// Completes renames interrupted by a crash, a yield to another job or a host that stopped (not those their job held); /// returns how many plans were resumed. Each sequence a resumed step changed is told, as its job would have /// (, ). The file renames a held plan's step left /// half-way are completed all the same (), so no photo waits at a temporary name for that job. /// public async Task ResumePendingAsync(Archive archive, CancellationToken cancellationToken = default) { var paths = new ArchivePaths(archive.RootPath); var journals = RenameJournal.ListPending(paths).Where(j => j.Plan.ArchiveId == archive.Id).ToList(); foreach (var held in journals.Where(j => j.Held)) await SettleFilesAsync(paths, held, cancellationToken).ConfigureAwait(false); var pending = journals.Where(j => !j.Held).ToList(); foreach (var journal in pending) { await RunAsync(archive, journal, resuming: true, null, (_, changed) => TellAsync(_writer.Options.SequenceChanged, changed), cancellationToken) .ConfigureAwait(false); } return pending.Count; } /// /// Tells (null: no one) each sequence of a Reorganize /// changed (); a failure is logged, never passed on. /// internal static async ValueTask TellAsync(Func? sequenceChanged, IReadOnlyList changed) { if (sequenceChanged is null) return; foreach (var id in changed) { try { await sequenceChanged(id, Change, CancellationToken.None).ConfigureAwait(false); } catch (Exception ex) { Log.Warning("archive", $"The change of sequence {id} was not told", ex); } } } /// /// Completes, each under its sequence's lease, the file renames a crash or a failure left in the steps of a plan that are /// not completed (: the files go on to their new names and the sidecar names them; /// the index follows when the plan resumes, or at the next scan). One that cannot be completed yet is logged and left /// to the next writer of that sequence. /// private async Task SettleFilesAsync(ArchivePaths paths, RenameJournal journal, CancellationToken cancellationToken) { var completed = journal.Completed.ToHashSet(); foreach (var step in journal.Plan.Steps.Where(s => s.FileChanges > 0 && !completed.Contains(s.SequenceId))) { var sequence = Where(paths, step); if (!File.Exists(sequence.FileRenameJournalPath)) continue; try { await using (await _writer.LockAsync(paths, step.SequenceId, cancellationToken).ConfigureAwait(false)) { SequenceWriter.ReadLocked(sequence, step.SequenceId); } } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or NewerFormatException) { Log.Warning("archive", $"The interrupted rename of the files of {sequence.RelativeFolder} could not be completed yet", ex); } } } /// Steps whose sequence the index no longer knows, or that no longer fit the plan, are dropped /// (or keep what no longer fits) 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, Func? started, Func, ValueTask>? stepDone, 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(); // A step that changes nothing (its files kept their names, and why) has nothing to apply. var steps = journal.Plan.Steps.Where(s => s.Changes).ToList(); if (!resuming) { // Checked as the files are: file renames a crash or a failure left half-way are completed first. await SettleFilesAsync(paths, journal, cancellationToken).ConfigureAwait(false); try { await RefuseStaleAsync(archive, paths, journal.Plan, [.. steps.Where(s => !completed.Contains(s.SequenceId))], cancellationToken).ConfigureAwait(false); } catch (Exception ex) when (ex is StaleRenamePlanException or NewerFormatException && (completed.Count > 0 || File.Exists(RenameJournal.PathFor(paths, journal.Plan.Id)))) { // A held plan that no longer fits: what it applied stays, the rest never will. RenameJournal.Delete(paths, journal.Plan.Id); Log.Warning("archive", $"The rest of rename {journal.Plan.Id} no longer matches the archive; it was given up"); throw; } } RenameJournal.Write(paths, journal); if (started is not null) await started(journal.Plan).ConfigureAwait(false); var result = new Tally(journal.Done); 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)] : []; var before = result.Changed.Count; await ApplyStepAsync(archive, paths, journal.Plan.FileTemplate, step, carried, resuming, result, cancellationToken).ConfigureAwait(false); completed.Add(step.SequenceId); foreach (var c in carried) completed.Add(c.SequenceId); journal = journal with { Completed = [.. completed], Done = result.Record() }; RenameJournal.Write(paths, journal); if (stepDone is not null) await stepDone(completed.Count, result.Changed.GetRange(before, result.Changed.Count - before)).ConfigureAwait(false); } RenameJournal.Delete(paths, journal.Plan.Id); return RenameResult.Of(result.Record()); } /// /// A plan made before another change is refused before anything moves: a sequence moved, a title it changes or names a /// folder or files after was edited, one was indexed inside a folder that moves (a scan adopted a subfolder copied in /// since the dry run), something took a folder it moves one into (), or a sidecar it rewrites is /// of a newer format. A step a failed run left half-way (its folder at its new place) still fits. Photos changed since /// (a sequence still receiving them) refuse nothing: under its leases that step keeps their names. Read without the /// leases, each step checks the same again under its own (), so a held plan resumed by its job /// either fits here or is given up. /// /// A sidecar the plan rewrites is of a newer format. private async Task RefuseStaleAsync(Archive archive, ArchivePaths paths, RenamePlan plan, IReadOnlyList remaining, CancellationToken cancellationToken) { var locations = await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false); foreach (var step in remaining) { var row = await _db.Sequences.GetAsync(step.SequenceId, cancellationToken).ConfigureAwait(false); if (row is null || (row.Folder != step.FromFolder && row.Folder != step.ToFolder) || (step.UsesTitle && !Planned(step, row.Title)) || (!step.Carried && TargetTaken(paths, step, locations))) throw new StaleRenamePlanException(step.SequenceId); var files = plan.FileTemplate is not null && step.FileChanges > 0; if (!step.UsesTitle && !files) continue; // A sidecar that cannot be read refuses file renames planned from it; a title alone fails under the step's lease, with its reason. var sequence = Where(paths, step); if (ReadSidecar(sequence, step.SequenceId) is not { } manifest) { if (files) throw new StaleRenamePlanException(step.SequenceId); continue; } if ((step.Retitles || files) && manifest.SchemaVersion > SequenceManifest.CurrentSchemaVersion) throw new NewerFormatException(sequence.ManifestPath, manifest.SchemaVersion); if (step.UsesTitle && !TitleStands(step, row, manifest)) throw new StaleRenamePlanException(step.SequenceId); } var planned = plan.Steps.Select(s => s.SequenceId).ToHashSet(); if (StrangerInside(locations, remaining.Where(s => s.MovesFolder && !s.Carried), planned) is { } stranger) throw new StaleRenamePlanException(stranger.Id); } /// The sidecar of a sequence (read without its lease); null when it cannot be read or is another sequence's. private static SequenceManifest? ReadSidecar(SequencePaths sequence, Guid sequenceId) { try { var manifest = ManifestStore.ReadSequence(sequence.ManifestPath); return manifest.Id == sequenceId ? manifest : null; } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException) { return null; } } /// 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); /// Where a step's sequence is now: its folder moves first, so a resumed step may find it at its new place already. private static SequencePaths Where(ArchivePaths paths, RenameStep step) { var sequence = paths.Sequence(step.FromFolder); return step.MovesFolder && !File.Exists(sequence.ManifestPath) ? paths.Sequence(step.ToFolder) : sequence; } /// Whether a step's folder moved already (an interrupted run moved it before every index row followed). private static bool Moved(ArchivePaths paths, RenameStep step) => step.MovesFolder && !Directory.Exists(paths.FromRelative(step.FromFolder)); /// /// Applies a step, and the steps of the sequences its folder carries, under all their leases: sequence leases, then /// for a move or file renames 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 /// its files are renamed, or before its index row follows. Whatever can refuse the step is checked under the leases /// before anything of it moves (where its sequences are, what is inside and at its new folder, then each sidecar, /// settled: ; a sequence whose photos changed since keeps its file names). Then the folder moves, /// every index row follows it (a sidecar that cannot be read or written there fails the step once the others did), and /// only then are the files renamed; a sequence whose files are found changed or in use there keeps its file names, and /// the step goes to its end whatever the caller cancels. /// /// A step whose sequence the index no longer has where the plan says, or that no longer fits it, /// is dropped (or keeps what no longer fits) 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, string? fileTemplate, RenameStep step, IReadOnlyList carried, bool resuming, Tally result, 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 || step.FileChanges > 0 || carried.Any(c => c.FileChanges > 0)) { 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)) { result.Dropped.Add(step.SequenceId); return; } var follow = new List(carried.Count); foreach (var c in carried) { if (await StandsAsync(c, resuming, cancellationToken).ConfigureAwait(false)) follow.Add(c); else result.Dropped.Add(c.SequenceId); } IReadOnlyList locations = step.MovesFolder ? await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false) : []; if (!CarriesAllInside(paths, step, carried, locations, resuming) || !TargetFree(paths, step, locations, resuming)) { result.Dropped.Add(step.SequenceId); result.Dropped.AddRange(follow.Select(c => c.SequenceId)); return; } var fits = new List<(RenameStep Step, Fit Fit)>(follow.Count + 1); foreach (var s in follow.Prepend(step)) fits.Add((s, await FitAsync(paths, fileTemplate, s, Settle(paths, s), resuming, cancellationToken).ConfigureAwait(false))); // Its title no longer fits (edited since, or planned anew in a sidecar of a newer format) while nothing of it moved: // it stays as it was, with the sequences it would carry. var first = fits[0].Fit; if ((first == Fit.Title || (first == Fit.Newer && step.Retitles)) && !Moved(paths, step)) { (first == Fit.Newer ? result.Newer : result.Dropped).Add(step.SequenceId); result.Dropped.AddRange(follow.Select(c => c.SequenceId)); return; } RenamePlanner.MoveFolder(paths, step); // Every index row follows the folder before any file is renamed, so nothing below can leave one behind it: a // sequence whose sidecar cannot be read or written now has its row follow all the same, and fails the step once // every other row did. ExceptionDispatchInfo? unrecorded = null; foreach (var (s, fit) in fits) { try { await RecordAsync(archive, paths, s, s.Retitles && TakesTitle(fit), CancellationToken.None).ConfigureAwait(false); } catch (Exception ex) when (step.MovesFolder && ex is IOException or UnauthorizedAccessException or InvalidDataException or NewerFormatException) { Log.Warning("archive", $"{s.ToFolder} could not be recorded after its folder moved; its index row followed it", ex); unrecorded ??= ExceptionDispatchInfo.Capture(ex); } } unrecorded?.Throw(); foreach (var (s, fit) in fits) { var renamed = fit == Fit.Whole && fileTemplate is not null && await RenameFilesAsync(archive, paths, fileTemplate, s, result, CancellationToken.None).ConfigureAwait(false); if (fit == Fit.Title) result.TitlesKept.Add(s.SequenceId); else if (fit == Fit.Files) result.FilesKept.Add(s.SequenceId); else if (fit == Fit.Newer) result.Newer.Add(s.SequenceId); if (s.MovesFolder || (s.Retitles && TakesTitle(fit)) || renamed) result.Changed.Add(s.SequenceId); } } 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); } } /// /// Settles, under the step's leases and before anything of it moves, what a crash or a busy trash entry left in the /// sequence, as every writer does (): an interrupted rename of its files, photo /// deletion, restore from the trash or ingest. A restore whose trash entry is busy is not settled yet, and the step /// waits for it () as a deletion of the sequence does: its journal names the /// files it moved by the names they had, so neither the folder nor those names change under it. Returns the sidecar as /// settled. /// /// A restore from the trash into the sequence is not settled; nothing of the step changed. private static SequenceManifest Settle(ArchivePaths paths, RenameStep step) { var sequence = Where(paths, step); var manifest = SequenceWriter.ReadLocked(sequence, step.SequenceId); FrameTrash.EnsureSettled(sequence); return manifest; } /// /// How far a sequence of a step still fits the plan, under the step's leases with its sidecar settled /// () and before anything of the step moves: a sidecar of a newer format is never rewritten, /// a title edited since the plan is never written over nor are names given from the old one (), /// and the files are renamed only as the plan renames them (). When not resuming, a newer format /// or an edited title refuses the step; photos changed since (a sequence still receiving them) never do: its files keep /// their names, and the rest of the step and of the plan goes on. /// /// Not resuming, and the step would rewrite a sidecar of a newer format. /// Not resuming, and its title was edited since the plan. private async Task FitAsync(ArchivePaths paths, string? fileTemplate, RenameStep step, SequenceManifest manifest, bool resuming, CancellationToken cancellationToken) { var sequence = Where(paths, step); var files = fileTemplate is not null && step.FileChanges > 0; if ((step.Retitles || files) && manifest.SchemaVersion > SequenceManifest.CurrentSchemaVersion) { if (!resuming) throw new NewerFormatException(sequence.ManifestPath, manifest.SchemaVersion); Log.Warning("archive", $"{sequence.RelativeFolder} keeps its title and file names: its sidecar was written by a newer Chronos"); return Fit.Newer; } if (step.UsesTitle && await _db.Sequences.GetAsync(step.SequenceId, cancellationToken).ConfigureAwait(false) is { } row && !TitleStands(step, row, manifest)) { if (!resuming) throw new StaleRenamePlanException(step.SequenceId); Log.Warning("archive", $"{sequence.RelativeFolder} keeps its title and file names: its title was edited after the plan was made"); return Fit.Title; } if (files && !FilesStand(sequence, PathTemplate.Parse(fileTemplate!), step, manifest)) { Log.Warning("archive", $"The files of {sequence.RelativeFolder} keep their names: its photos changed after the plan was made"); return Fit.Files; } return Fit.Whole; } /// Whether a sequence of a step takes the title the plan gives it: not when its title was edited since, nor in a sidecar of a newer format. private static bool TakesTitle(Fit fit) => fit is Fit.Whole or Fit.Files; /// /// Whether a sequence's title is still one the plan knows (the one it was made from, or the one it gives, which an /// interrupted run may have recorded): the index's, and the sidecar's unless the index is ahead of it (an edit only the /// index has, as the server's API makes). An edit made since, here or by another process sharing the archive, is kept. /// private static bool TitleStands(RenameStep step, Sequence row, SequenceManifest manifest) => Planned(step, row.Title) && (row.SettingsVersion > manifest.Versions.Settings || Planned(step, manifest.Title)); private static bool Planned(RenameStep step, string? title) => string.Equals(title, step.FromTitle, StringComparison.Ordinal) || string.Equals(title, step.ToTitle, StringComparison.Ordinal); /// /// Whether the files of a step's sequence still rename as planned: planned again from and the /// files beside its frames, they rename exactly the files the plan renamed (), or none is left to /// rename (an interrupted run renamed them). A photo hashed, gone or added since where the plan would rename it, or a /// file copied in beside them, would give other names than the dry run showed. /// private static bool FilesStand(SequencePaths sequence, PathTemplate template, RenameStep step, SequenceManifest manifest) { var plan = FileRenames.Plan(manifest, step.ToTitle, template, FileRenames.ListPresent(sequence, manifest)); return plan.Moves.Count == 0 || Matches(step, plan, manifest); } /// /// Whether file renames planned again are exactly the plan's: every move the same (), /// whatever photos the sequence received since under the names the plan leaves them (an upload filed with the same /// template), which only raised its frames version; a plan journaled without a digest, at the frames version it was made at. /// private static bool Matches(RenameStep step, FileRenamePlan plan, SequenceManifest manifest) => step.FileDigest is { } digest ? string.Equals(digest, plan.Digest(), StringComparison.Ordinal) : manifest.Versions.Frames == step.FramesVersion; /// 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 static bool CarriesAllInside(ArchivePaths paths, RenameStep step, IReadOnlyList carried, IReadOnlyList locations, bool resuming) { if (!step.MovesFolder) return true; if (StrangerInside(locations, [step], carried.Select(c => c.SequenceId).ToHashSet()) is not { } stranger) return true; if (!resuming) throw new StaleRenamePlanException(stranger.Id); if (Moved(paths, step)) return true; Log.Warning("archive", $"Rename of {step.FromFolder} dropped: {stranger.Folder} was indexed inside it after the plan was made"); return false; } /// /// Whether the new folder of a moving step is still free (), checked again under the step's /// leases just before the folder moves: one taken since the plan refuses the step, or drops it when resuming; nothing /// of it moved either way, and no folder is ever moved into another. /// /// Not resuming, and something took the new folder. private static bool TargetFree(ArchivePaths paths, RenameStep step, IReadOnlyList locations, bool resuming) { if (step.Carried || !TargetTaken(paths, step, locations)) return true; if (!resuming) throw new StaleRenamePlanException(step.SequenceId); Log.Warning("archive", $"Rename of {step.FromFolder} dropped: {step.ToFolder} was taken after the plan was made"); return false; } /// /// Whether something took the new folder of a step whose folder has not moved yet: a folder there on disk, or a sequence /// the index has there, around it or inside it (a restore from the trash, an upload or an import since the plan). A /// change of case only is the step's own folder, unless another folder holds the new name exactly beside it (a /// case-sensitive file system), which could never move onto. /// private static bool TargetTaken(ArchivePaths paths, RenameStep step, IReadOnlyList locations) { if (!step.MovesFolder || Moved(paths, step)) return false; if (step.FromFolder.Equals(step.ToFolder, StringComparison.OrdinalIgnoreCase)) return RenamePlanner.ExistsExactly(paths, step.ToFolder) && RenamePlanner.ExistsExactly(paths, step.FromFolder); return Directory.Exists(paths.FromRelative(step.ToFolder)) || locations.Any(l => l.Id != step.SequenceId && (l.Folder.Equals(step.ToFolder, StringComparison.OrdinalIgnoreCase) || RenamePlanner.IsInside(l.Folder, step.ToFolder) || RenamePlanner.IsInside(step.ToFolder, l.Folder))); } /// A sequence of inside the folder of one of that is not in ; null when there is none. private static SequenceLocation? StrangerInside(IReadOnlyList locations, IEnumerable moving, IReadOnlySet taken) { var folders = moving.Select(s => s.FromFolder).ToList(); return folders.Count == 0 ? null : locations.FirstOrDefault(l => !taken.Contains(l.Id) && folders.Any(f => RenamePlanner.IsInside(f, l.Folder))); } /// /// Sidecar title, then index (folder, title, frames' paths and the paths of renders whose export moved with the /// folder, the sequence's own or another's saved inside it, in one transaction); each part is idempotent so a resumed /// step can repeat it. /// The index row changes in its folder and title only (): a settings edit /// committed meanwhile stays, and frames another process listed in the sidecar are left to the next scan, for which /// the folder keeps no stamps unless the index held it as it was /// (). A step /// that only renames files, or keeps its title, has nothing to record here. A moved folder whose sidecar cannot be read /// or written now still has its index row follow it (its title left as it was, no stamps for the next scan), and the /// failure is thrown. /// /// Whether the step's title is written (false: the title stays, edited since the plan or in a sidecar of a newer format). private async Task RecordAsync(Archive archive, ArchivePaths paths, RenameStep step, bool retitle, CancellationToken cancellationToken) { if (!step.MovesFolder && !retitle) return; var sequence = paths.Sequence(step.ToFolder); bool inStep; try { var manifest = SequenceWriter.ReadLocked(sequence, step.SequenceId); // The folder moved with its files' stamps, which the index recorded at its old place. inStep = await _indexer.InStepAsync(archive, step.FromFolder, sequence, manifest, cancellationToken).ConfigureAwait(false); if (retitle && manifest.Title != step.ToTitle) { ManifestStore.WriteSequence(sequence.ManifestPath, manifest with { Title = step.ToTitle, Versions = manifest.Versions with { Settings = manifest.Versions.Settings + 1 }, UpdatedAt = DateTimeOffset.UtcNow, }); } } catch (Exception ex) when (step.MovesFolder && ex is IOException or UnauthorizedAccessException or InvalidDataException or NewerFormatException) { await RelocateAsync(archive, step, null, cancellationToken).ConfigureAwait(false); throw; } await RelocateAsync(archive, step, retitle ? step.ToTitle : null, cancellationToken).ConfigureAwait(false); if (inStep) await _indexer.RecordStampsAsync(archive, sequence, step.SequenceId, cancellationToken).ConfigureAwait(false); } /// The index rows of a step, in one transaction: its sequence's folder and title (null: kept), the paths of its frames and of the renders whose export moved with the folder. private async Task RelocateAsync(Archive archive, RenameStep step, string? title, CancellationToken cancellationToken) { await using var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false); await tx.Sequences.RelocateAsync(step.SequenceId, step.ToFolder, title, cancellationToken).ConfigureAwait(false); if (step.MovesFolder) { await tx.Frames.RebaseFolderAsync(step.SequenceId, step.FromFolder, step.ToFolder, cancellationToken).ConfigureAwait(false); await ArchiveIndexer.RebaseRendersAsync(tx, archive, 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); } /// /// The file renames of a step, under the leases its step holds, once its folder is in place and every index row of the /// step followed it (Reorganize, owner review 2, R7). The renames are planned again from the sidecar read under the /// lease (, with the step's title, the one the dry run showed) and made only while they are /// exactly the plan's (, checked before the folder moved already); found otherwise here (a writer /// that takes no lease) the files keep their names, and so do they when one is in use or a new name is taken (every /// file goes back to its name): the step goes on either way. The files move in two phases through temporary names /// under the sequence's journal (), then the sidecar names them (the frame order unchanged, frames version + 1), /// then the index (), then the journal goes. A file that could not go back /// after such a failure has the journal complete the renames at once, as the next writer would. When nothing moves here /// but the index names other files than the sidecar, a writer completed the renames after a crash /// () before the index followed, and the index is synced from the sidecar. /// Proxies (named by frame index), thumbnails (by index and content hash), renders and exports need nothing. /// /// False when the step renames no file, or its files kept their names. /// A file could neither go on to its new name nor back; the sequence's journal stays, and /// its next writer (or the next archive open, for a plan its job holds) completes the renames. private async Task RenameFilesAsync(Archive archive, ArchivePaths paths, string fileTemplate, RenameStep step, Tally result, CancellationToken cancellationToken) { if (step.FileChanges == 0) return false; var sequence = paths.Sequence(step.ToFolder); var manifest = SequenceWriter.ReadLocked(sequence, step.SequenceId); var inStep = await _indexer.InStepAsync(archive, sequence, manifest, cancellationToken).ConfigureAwait(false); var plan = FileRenames.Plan(manifest, step.ToTitle, PathTemplate.Parse(fileTemplate), FileRenames.ListPresent(sequence, manifest)); var before = manifest.Versions.Frames; if (plan.Moves.Count > 0 && !Matches(step, plan, manifest)) { Log.Warning("archive", $"The files of {sequence.RelativeFolder} keep their names: its photos changed after the plan was made"); result.FilesKept.Add(step.SequenceId); return false; } if (plan.Moves.Count > 0) { var journal = FileRenameJournal.Create(before, plan.Moves, Guid.NewGuid().ToString("N")[..8]); FileRenameJournal.Write(sequence, journal); try { journal = FileRenameJournal.Run(sequence, journal); manifest = FileRenameJournal.Applied(manifest, journal) ?? manifest; ManifestStore.WriteSequence(sequence.ManifestPath, manifest); } catch (Exception ex) when ((ex is IOException or UnauthorizedAccessException) && FileRenameJournal.Read(sequence) is null) { // A file open elsewhere or a new name taken, and every file went back to its name: nothing of the sequence's files changed. Log.Warning("archive", $"The files of {sequence.RelativeFolder} keep their names: one of them is in use or its new name is taken", ex); result.FilesBusy.Add(step.SequenceId); return false; } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { // One could not go back: its journal completes the renames instead, now, and the sidecar names the files. Log.Warning("archive", $"The files of {sequence.RelativeFolder} could not all go back after a failed rename; it is completed instead", ex); manifest = SequenceWriter.ReadLocked(sequence, step.SequenceId); } result.Files += plan.Frames; Log.Info("archive", $"{sequence.RelativeFolder}: {plan.Frames} file(s) renamed, {plan.Moves.Count - plan.Frames} companion(s) with them"); await _db.Frames.RenameFilesAsync(manifest.Id, await BehindAsync(sequence, manifest, cancellationToken).ConfigureAwait(false), before, manifest.Versions.Frames, cancellationToken).ConfigureAwait(false); if (inStep) await _indexer.RecordStampsAsync(archive, sequence, step.SequenceId, cancellationToken).ConfigureAwait(false); } else if ((await BehindAsync(sequence, manifest, cancellationToken).ConfigureAwait(false)).Count > 0) { // Photos copied in by hand meanwhile are left to the next scan's reconcile (the photo stamp stays as recorded). await _indexer.SyncAsync(archive, sequence, manifest, null, SequenceStatus.None, photosChanged: true, cancellationToken).ConfigureAwait(false); } FileRenameJournal.Delete(sequence); return true; } /// The frames the index names by another file than the sidecar does, with the sidecar's path and name; frames the index does not have are left to the next scan. private async Task> BehindAsync(SequencePaths sequence, SequenceManifest manifest, CancellationToken cancellationToken) { const int page = 1000; var files = manifest.Frames.ToDictionary(f => f.Id, f => f.File); var behind = new List(); for (var last = -1; ;) { var rows = await _db.Frames.ListBySequenceAsync(manifest.Id, last, page, cancellationToken).ConfigureAwait(false); foreach (var row in rows) { if (!files.TryGetValue(row.Id, out var file)) continue; var path = sequence.ArchiveRelative(file); if (row.RelativePath != path) behind.Add(new FrameFileName(row.Id, path, Path.GetFileName(file))); } if (rows.Count < page) return behind; last = rows[^1].Index; } } /// What a plan's runs did, as they go: from what its completed steps did already (). private sealed class Tally(RenameTally done) { public List Changed { get; } = [.. done.Changed]; public List Dropped { get; } = [.. done.Dropped]; public List FilesKept { get; } = [.. done.FilesKept]; public List TitlesKept { get; } = [.. done.TitlesKept]; public List FilesBusy { get; } = [.. done.FilesBusy]; public List Newer { get; } = [.. done.Newer]; public int Files { get; set; } = done.Files; public RenameTally Record() => new() { Changed = [.. Changed], Files = Files, Dropped = [.. Dropped], FilesKept = [.. FilesKept], TitlesKept = [.. TitlesKept], FilesBusy = [.. FilesBusy], Newer = [.. Newer], }; } }