fix(archive): Reorganize checks each step before it moves, holds a failed plan, recovers file renames safely
Owner review 2, phase 4a review findings on the renamer. - File rename recovery is safe to run again from wherever it stopped: once every file is at its temporary name the journal says phase 2, as Run does, so a second recovery (after a failure, a crash or a sidecar that could not be written) never moves a file that reached its new name. A new name something else took meanwhile is never written over: that photo and its companions go back to their old names, or to the first free _2, _3, recorded in the journal before they move, and the frame names where its photo is. A journal is never deleted while a temporary file of it is still there. - Every check that can refuse a step runs under the step's leases before anything of it moves: where its sequences are, strangers inside, its new folder taken since the plan (a restore, an upload), a sidecar of a newer format, a title edited since the plan (compare-and-set against the planned from-title, sidecar and index), and its file renames, compared by a digest of every move at the planned frames version (a verify that hashes photos does not bump the version). Once the folder moved, every index row follows it before any file is renamed, and a photo in use or files found changed keep their names: the step completes. - The same checks run up front for a held plan, so its retry either fits or is given up. - A failed move job holds its plan, as a pause does: an archive open no longer applies the rest unasked; only the job's retry does. File renames a step left half-way are still completed at an archive open. - Each sequence changed is told as its step is journaled, so a pause or a failure never keeps it untold; the plan's journal keeps the tally of every run, so the job log counts the whole plan. - A selected sequence deleted while the job waited is named in the log and the plan refused with the localized stale-plan error, not a raw ArgumentException. - The dry run renames no file of a newer-format sidecar. New log lines and error (en, it): title and file names kept, file names kept because a photo was in use. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 1d1c888120edd709dbb5341c1922bf85085c4857)
This commit is contained in:
1 parent
44e5b9da9e
commit
13c2ac321c
10 files changed
+961
-135
No files matched your search
@@ -1,3 +1,4 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.IO;
|
||||
@@ -63,10 +64,20 @@ public sealed record FileRenameJournal(int FramesVersion, int Phase, IReadOnlyLi
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the journal once its files are where it says; one whose temporary files are not all gone stays (logged), so
|
||||
/// no photo is ever left at a temporary name without a record of it: the next <see cref="Recover"/> completes it.
|
||||
/// </summary>
|
||||
public static void Delete(SequencePaths sequence)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sequence);
|
||||
if (File.Exists(sequence.FileRenameJournalPath)) File.Delete(sequence.FileRenameJournalPath);
|
||||
if (!File.Exists(sequence.FileRenameJournalPath)) return;
|
||||
if (Read(sequence) is { } journal && journal.Files.FirstOrDefault(f => Exists(sequence, f.Temp)) is { } left)
|
||||
{
|
||||
Log.Error("archive", $"The rename journal of {sequence.RelativeFolder} stays: {sequence.ArchiveRelative(left.Temp)} is still at its temporary name");
|
||||
return;
|
||||
}
|
||||
File.Delete(sequence.FileRenameJournalPath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -112,37 +123,98 @@ public sealed record FileRenameJournal(int FramesVersion, int Phase, IReadOnlyLi
|
||||
/// Completes a rename a crash interrupted (the caller holds the sequence's lease): the files go on to their new names,
|
||||
/// and <paramref name="manifest"/> names them (<see cref="Applied"/>), unless it does already. Returns
|
||||
/// the sidecar to write, or null when it is right as it is; the journal is left in place, <see cref="Delete"/> it once
|
||||
/// the result is written. A file found nowhere is logged, and its frame names the new file all the same (a verify then
|
||||
/// flags it missing, as it would have at its old name).
|
||||
/// the result is written. Safe to run again from wherever it stopped (a failure, a crash, a sidecar that could not be
|
||||
/// written): once every file is at its temporary name the journal says phase 2, as <see cref="Run"/> does, so no file
|
||||
/// that reached its new name is ever moved again. A new name something else took meanwhile is never written over: the
|
||||
/// files of that frame go back to their old names, or to the first free <c>_2</c>, <c>_3</c>… of them, recorded in the
|
||||
/// journal before they move, and the frame names where its photo is (logged). A file found nowhere is logged, and its
|
||||
/// frame names the new file all the same (a verify then flags it missing, as it would have at its old name).
|
||||
/// </summary>
|
||||
/// <exception cref="IOException">A file could not be moved (open elsewhere); the journal stays, and the next recovery goes on from there.</exception>
|
||||
public static SequenceManifest? Recover(SequencePaths sequence, SequenceManifest manifest)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sequence);
|
||||
ArgumentNullException.ThrowIfNull(manifest);
|
||||
if (Read(sequence) is not { } journal) return null;
|
||||
foreach (var file in journal.Files)
|
||||
if (journal.Phase == 1)
|
||||
{
|
||||
// In phase 2 no file is at its old name any more: what is there now came since, and stays.
|
||||
if (journal.Phase == 1 && Exists(sequence, file.From) && !Exists(sequence, file.Temp)) Move(sequence, file.From, file.Temp);
|
||||
foreach (var file in journal.Files)
|
||||
{
|
||||
// What is at an old name beside its file's temporary one came since, and stays.
|
||||
if (Exists(sequence, file.From) && !Exists(sequence, file.Temp)) Move(sequence, file.From, file.Temp);
|
||||
}
|
||||
// Every file is at its temporary name (or nowhere): from here on no old name is moved from again.
|
||||
journal = journal with { Phase = 2 };
|
||||
Write(sequence, journal);
|
||||
}
|
||||
journal = Redirected(sequence, journal);
|
||||
foreach (var file in journal.Files)
|
||||
{
|
||||
if (Exists(sequence, file.Temp) && !Exists(sequence, file.To)) Move(sequence, file.Temp, file.To);
|
||||
if (Exists(sequence, file.Temp)) Move(sequence, file.Temp, file.To);
|
||||
else if (!Exists(sequence, file.To)) Log.Warning("archive", $"{sequence.ArchiveRelative(file.To)} was not found after an interrupted rename");
|
||||
}
|
||||
Log.Warning("archive", $"An interrupted rename of the files of {sequence.RelativeFolder} was completed");
|
||||
return Applied(manifest, journal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The journal with a new name for every file still at its temporary name of a frame one of whose new names something
|
||||
/// else took since (a file, or a folder): all the files of that frame (its photo and companions, which stay together) go
|
||||
/// back to their old names, or to the first <c>_2</c>, <c>_3</c>… of the photo's old name that is free for all of them,
|
||||
/// none ever a name the rename gives another file. Written before anything moves, so a recovery run again finds them.
|
||||
/// </summary>
|
||||
private static FileRenameJournal Redirected(SequencePaths sequence, FileRenameJournal journal)
|
||||
{
|
||||
var claimed = new HashSet<string>(journal.Files.Select(f => f.To), StringComparer.OrdinalIgnoreCase);
|
||||
List<FileRenameEntry>? files = null;
|
||||
foreach (var frame in journal.Files.Select((f, i) => (File: f, Index: i)).GroupBy(f => f.File.FrameId))
|
||||
{
|
||||
var waiting = frame.Where(f => Exists(sequence, f.File.Temp)).ToList();
|
||||
if (!waiting.Any(f => Taken(sequence, f.File.To))) continue;
|
||||
var photo = frame.FirstOrDefault(f => !f.File.Companion).File ?? frame.First().File;
|
||||
List<string> names;
|
||||
for (var n = 1; ; n++)
|
||||
{
|
||||
names = waiting.ConvertAll(f => Numbered(f.File, photo, n));
|
||||
if (names.TrueForAll(name => !claimed.Contains(name) && !Taken(sequence, name)) && names.Distinct(StringComparer.OrdinalIgnoreCase).Count() == names.Count) break;
|
||||
}
|
||||
files ??= [.. journal.Files];
|
||||
for (var i = 0; i < waiting.Count; i++)
|
||||
{
|
||||
var (file, index) = waiting[i];
|
||||
claimed.Add(names[i]);
|
||||
files[index] = file with { To = names[i] };
|
||||
}
|
||||
Log.Error("archive", $"{string.Join(", ", waiting.Where(f => Taken(sequence, f.File.To)).Select(f => sequence.ArchiveRelative(f.File.To)))} taken while "
|
||||
+ $"a rename was interrupted; the files of that photo go to {string.Join(", ", names.Select(sequence.ArchiveRelative))}");
|
||||
}
|
||||
if (files is null) return journal;
|
||||
journal = journal with { Files = files };
|
||||
Write(sequence, journal);
|
||||
return journal;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The old name of <paramref name="file"/> (<paramref name="n"/> = 1), or the photo's old name with <c>_n</c> and the
|
||||
/// companion's tail after it (<c>IMG_0001_2.CR2</c>, <c>IMG_0001_2.xmp</c>).
|
||||
/// </summary>
|
||||
private static string Numbered(FileRenameEntry file, FileRenameEntry photo, int n)
|
||||
{
|
||||
if (n == 1) return file.From;
|
||||
var stem = photo.From[..^Path.GetExtension(photo.From).Length] + "_" + n.ToString(CultureInfo.InvariantCulture);
|
||||
return file.Companion ? stem + FrameCompanions.Tail(file.From, photo.From) : stem + Path.GetExtension(photo.From);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="manifest"/> naming the new files of <paramref name="journal"/> (frame order unchanged) one frames
|
||||
/// version further; null when no frame names an old file any more (the sidecar was written already).
|
||||
/// version further; null when no frame names an old file any more (the sidecar was written already). A file a recovery
|
||||
/// sent back to its old name (<see cref="Recover"/>) leaves its frame as it is.
|
||||
/// </summary>
|
||||
public static SequenceManifest? Applied(SequenceManifest manifest, FileRenameJournal journal)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(manifest);
|
||||
ArgumentNullException.ThrowIfNull(journal);
|
||||
var renamed = journal.Files.Where(f => !f.Companion).ToDictionary(f => f.FrameId, f => f);
|
||||
var renamed = journal.Files.Where(f => !f.Companion && !string.Equals(f.From, f.To, StringComparison.Ordinal)).ToDictionary(f => f.FrameId, f => f);
|
||||
var changed = false;
|
||||
var frames = manifest.Frames.Select(f =>
|
||||
{
|
||||
@@ -186,5 +258,8 @@ public sealed record FileRenameJournal(int FramesVersion, int Phase, IReadOnlyLi
|
||||
|
||||
private static bool Exists(SequencePaths sequence, string file) => File.Exists(sequence.File(file));
|
||||
|
||||
/// <summary>Whether a name is held, by a file or a folder: no file can be moved there.</summary>
|
||||
private static bool Taken(SequencePaths sequence, string file) => Path.Exists(sequence.File(file));
|
||||
|
||||
private static void Move(SequencePaths sequence, string from, string to) => File.Move(sequence.File(from), sequence.File(to), overwrite: false);
|
||||
}
|
||||
@@ -1,3 +1,6 @@
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Chronos.Core.Naming;
|
||||
|
||||
namespace Chronos.Core.Archiving;
|
||||
@@ -14,7 +17,7 @@ public enum RenameBlock
|
||||
/// <summary>Photos whose file is not there.</summary>
|
||||
Missing,
|
||||
|
||||
/// <summary>The sequence's sidecar cannot be read, or belongs to another sequence.</summary>
|
||||
/// <summary>The sequence's sidecar cannot be read, is of a newer format this build does not rewrite, or belongs to another sequence.</summary>
|
||||
Unreadable,
|
||||
}
|
||||
|
||||
@@ -34,6 +37,14 @@ public sealed record FileRename(Guid FrameId, string From, string To, bool Compa
|
||||
public sealed record FileRenamePlan(IReadOnlyList<FileRename> Moves, int Frames, IReadOnlyList<FileRename> Samples, IReadOnlyList<RenameBlocked> Blocked)
|
||||
{
|
||||
public static FileRenamePlan None { get; } = new([], 0, [], []);
|
||||
|
||||
/// <summary>A digest of every move in order (frame, old and new name, companion or not): two plans with the same one rename the same files the same way.</summary>
|
||||
public string Digest()
|
||||
{
|
||||
var text = new StringBuilder();
|
||||
foreach (var move in Moves) text.Append(CultureInfo.InvariantCulture, $"{move.FrameId:N}|{move.From}|{move.To}|{move.Companion}\n");
|
||||
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text.ToString())));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -41,6 +41,12 @@ public sealed record RenameStep(Guid SequenceId, string FromFolder, string ToFol
|
||||
/// <summary>The first renamed frames (<see cref="FileRenames.SampleCount"/>), old and new name relative to the sequence folder.</summary>
|
||||
public IReadOnlyList<FileRename> FileSamples { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Every file rename of the step, as a digest (<see cref="FileRenamePlan.Digest"/>): the apply renames the files only
|
||||
/// while they plan to exactly these. Null when no file gets a new name (or in a plan journaled before it existed).
|
||||
/// </summary>
|
||||
public string? FileDigest { get; init; }
|
||||
|
||||
/// <summary>Frames that keep their file names, and why.</summary>
|
||||
public IReadOnlyList<RenameBlocked> Blocked { get; init; } = [];
|
||||
}
|
||||
@@ -124,7 +130,7 @@ public sealed record RenamePlan(Guid Id, Guid ArchiveId, IReadOnlyList<RenameSte
|
||||
var text = new StringBuilder(FileTemplate).Append('\n');
|
||||
foreach (var s in Steps)
|
||||
{
|
||||
text.Append(CultureInfo.InvariantCulture, $"{s.SequenceId:N}|{s.FromFolder}|{s.ToFolder}|{s.FromTitle}|{s.ToTitle}|{s.Carried}|{s.FramesVersion}|{s.FileChanges}|");
|
||||
text.Append(CultureInfo.InvariantCulture, $"{s.SequenceId:N}|{s.FromFolder}|{s.ToFolder}|{s.FromTitle}|{s.ToTitle}|{s.Carried}|{s.FramesVersion}|{s.FileChanges}|{s.FileDigest}|");
|
||||
foreach (var sample in s.FileSamples) text.Append(sample.From).Append('>').Append(sample.To).Append(';');
|
||||
foreach (var blocked in s.Blocked) text.Append(CultureInfo.InvariantCulture, $"{blocked.Reason}:{blocked.Frames};");
|
||||
text.Append('\n');
|
||||
@@ -133,11 +139,30 @@ public sealed record RenamePlan(Guid Id, Guid ArchiveId, IReadOnlyList<RenameSte
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What the completed steps of a plan did, over every run that applied them (<see cref="RenameJournal.Done"/>): the
|
||||
/// sequences changed, the frames whose file got a new name, and the sequences not changed as planned because they changed
|
||||
/// since: left as they were (<see cref="Dropped"/>), their file names kept (<see cref="FilesKept"/>), their title and file
|
||||
/// names kept (<see cref="TitlesKept"/>), or their file names kept because a photo was in use (<see cref="FilesBusy"/>).
|
||||
/// </summary>
|
||||
public sealed record RenameTally
|
||||
{
|
||||
public IReadOnlyList<Guid> Changed { get; init; } = [];
|
||||
public int Files { get; init; }
|
||||
public IReadOnlyList<Guid> Dropped { get; init; } = [];
|
||||
public IReadOnlyList<Guid> FilesKept { get; init; } = [];
|
||||
public IReadOnlyList<Guid> TitlesKept { get; init; } = [];
|
||||
public IReadOnlyList<Guid> FilesBusy { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <summary>A plan being applied, with the steps already completed; lets an interrupted rename resume (BRIEF §7).</summary>
|
||||
/// <param name="Held">The job applying the plan was paused or cancelled between two steps: an archive open leaves the plan to
|
||||
/// that job, which completes it when it runs again.</param>
|
||||
/// <param name="Held">The job applying the plan was paused, cancelled or failed between two steps: an archive open leaves the
|
||||
/// plan to that job, which completes it when it is resumed or retried.</param>
|
||||
public sealed record RenameJournal(RenamePlan Plan, IReadOnlyList<Guid> Completed, bool Held = false)
|
||||
{
|
||||
/// <summary>What the completed steps did, so a resumed run reports the whole plan.</summary>
|
||||
public RenameTally Done { get; init; } = new();
|
||||
|
||||
public static string PathFor(ArchivePaths archive, Guid planId) => Path.Combine(archive.JournalDirectory, $"rename-{planId:N}.json");
|
||||
|
||||
public static void Write(ArchivePaths archive, RenameJournal journal)
|
||||
@@ -252,6 +277,7 @@ public static class RenamePlanner
|
||||
FramesVersion = plan.Frames > 0 ? files.Manifest.Versions.Frames : 0,
|
||||
FileChanges = plan.Frames,
|
||||
FileSamples = plan.Samples,
|
||||
FileDigest = plan.Frames > 0 ? plan.Digest() : null,
|
||||
Blocked = plan.Blocked,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user