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.Text.Json;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
@@ -10,13 +11,16 @@ namespace Chronos.Data.Archiving.Jobs;
|
||||
/// <see cref="JobKind.Move"/>: a Reorganize (owner review 2, R7; BRIEF §12.5) of existing sequences with new folder, file
|
||||
/// and title templates (<see cref="MoveJobParameters"/>). The job plans again from the templates and applies the plan only
|
||||
/// when it is still the one confirmed (its fingerprint and the frames versions its file names were planned at;
|
||||
/// <see cref="StaleRenamePlanException"/> otherwise, nothing changed), through <see cref="MassRenamer"/>, whose journal makes
|
||||
/// every step resumable. Progress counts the plan's steps (sequences); checkpoint: <c>plan:<id></c> once the plan's
|
||||
/// journal is written. Paused or cancelled, the job stops between two sequences and holds the plan
|
||||
/// (<see cref="MassRenamer.Hold"/>), which an archive open then leaves to it; resumed or retried, it completes the rest when
|
||||
/// it still fits. A plan whose journal is gone completed meanwhile (at an archive open). Sequences left as they were, or
|
||||
/// whose files kept their names, because they changed after the plan are logged and fail the job at the end, after the
|
||||
/// others changed. Each sequence changed is told to <see cref="ArchiveServiceOptions.SequenceChanged"/> (<see cref="Change"/>).
|
||||
/// <see cref="StaleRenamePlanException"/> otherwise, nothing changed; a sequence of it gone since is named in the log),
|
||||
/// through <see cref="MassRenamer"/>, whose journal makes every step resumable. Progress counts the plan's steps
|
||||
/// (sequences); checkpoint: <c>plan:<id></c> once the plan's journal is written. Paused, cancelled or failed, the job
|
||||
/// stops between two sequences and holds the plan (<see cref="MassRenamer.Hold"/>), which an archive open then leaves to it
|
||||
/// (completing only file renames a step left half-way); resumed or retried, it completes the rest when it still fits. A
|
||||
/// plan whose journal is gone completed meanwhile (at an archive open). Sequences left as they were, or that kept their
|
||||
/// title or file names, because they changed after the plan or a photo was in use are logged and fail the job at the end,
|
||||
/// after the others changed. Each sequence changed is told to <see cref="ArchiveServiceOptions.SequenceChanged"/>
|
||||
/// (<see cref="Change"/>) as soon as its step is journaled, so a pause or a failure later never keeps it untold; the log
|
||||
/// counts the whole plan, over every run of the job.
|
||||
/// </summary>
|
||||
internal sealed class MoveJobHandler(ChronosDatabase db, MassRenamer renamer, Func<Guid, string, CancellationToken, Task>? sequenceChanged) : IJobHandler
|
||||
{
|
||||
@@ -50,7 +54,7 @@ internal sealed class MoveJobHandler(ChronosDatabase db, MassRenamer renamer, Fu
|
||||
}
|
||||
else
|
||||
{
|
||||
plan = await renamer.PlanAsync(archive, [.. parameters.Sequences.Select(s => s.Id)],
|
||||
plan = await renamer.PlanAsync(archive, await PresentAsync(context, archive, parameters).ConfigureAwait(false),
|
||||
new RenameTemplates(parameters.FolderTemplate, parameters.FileTemplate, parameters.TitleTemplate), context.Cancellation).ConfigureAwait(false);
|
||||
if (!IsConfirmed(plan, parameters)) throw new StaleRenamePlanException(Guid.Empty);
|
||||
var total = Steps(plan);
|
||||
@@ -59,7 +63,7 @@ internal sealed class MoveJobHandler(ChronosDatabase db, MassRenamer renamer, Fu
|
||||
{
|
||||
planId = p.Id;
|
||||
return context.CheckpointAsync(Checkpoint(p.Id), 0, total);
|
||||
}, n => context.CheckpointAsync(Checkpoint(plan.Id), n, total), context.Cancellation).ConfigureAwait(false);
|
||||
}, (n, changed) => StepDoneAsync(context, plan.Id, n, total, changed), context.Cancellation).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (planId is { } id && context.Cancellation.IsCancellationRequested)
|
||||
@@ -70,12 +74,16 @@ internal sealed class MoveJobHandler(ChronosDatabase db, MassRenamer renamer, Fu
|
||||
Log.Info("archive", $"Reorganize {id} held by its job {context.Job.Id}");
|
||||
throw;
|
||||
}
|
||||
context.Log(Loc.L("Archive.Log.Reorganized", result.Changed.Count, result.Files));
|
||||
foreach (var id in result.Dropped) context.Log(Loc.L("Archive.Log.ReorganizeDropped", Name(plan, id)));
|
||||
foreach (var id in result.FilesKept) context.Log(Loc.L("Archive.Log.ReorganizeFilesKept", Name(plan, id)));
|
||||
await TellAsync(result.Changed).ConfigureAwait(false);
|
||||
var kept = result.Dropped.Count + result.FilesKept.Count;
|
||||
catch (Exception ex) when (planId is { } id && !(ex is OperationCanceledException && context.Cancellation.IsCancellationRequested))
|
||||
{
|
||||
// Failed (a sequence changed, busy, or a folder that could not move): the rest waits for this job's retry, never for an archive open.
|
||||
HoldFailed(context, archive, id);
|
||||
throw;
|
||||
}
|
||||
LogDone(context, plan, result);
|
||||
var kept = result.Dropped.Count + result.FilesKept.Count + result.TitlesKept.Count;
|
||||
if (kept > 0) throw new InvalidOperationException(Loc.Plural("Archive.Error.ReorganizeKept", kept));
|
||||
if (result.FilesBusy.Count > 0) throw new InvalidOperationException(Loc.Plural("Archive.Error.ReorganizeBusy", result.FilesBusy.Count));
|
||||
}
|
||||
|
||||
/// <summary>Completes a plan this job started; null when its journal went meanwhile (completed at an archive open).</summary>
|
||||
@@ -83,10 +91,57 @@ internal sealed class MoveJobHandler(ChronosDatabase db, MassRenamer renamer, Fu
|
||||
{
|
||||
var total = Steps(journal.Plan);
|
||||
await context.ReportAsync(journal.Completed.Count, total).ConfigureAwait(false);
|
||||
return await renamer.ResumeAsync(archive, journal.Plan.Id, n => context.CheckpointAsync(Checkpoint(journal.Plan.Id), n, total), context.Cancellation)
|
||||
return await renamer.ResumeAsync(archive, journal.Plan.Id, (n, changed) => StepDoneAsync(context, journal.Plan.Id, n, total, changed), context.Cancellation)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sequences of the confirmed plan the index still has in the archive; each one gone since (deleted while the job
|
||||
/// waited in the queue) is named in the log, and the plan made without it is then not the one confirmed.
|
||||
/// </summary>
|
||||
private async Task<IReadOnlyList<Guid>> PresentAsync(JobContext context, Archive archive, MoveJobParameters parameters)
|
||||
{
|
||||
var present = new List<Guid>(parameters.Sequences.Count);
|
||||
foreach (var sequence in parameters.Sequences)
|
||||
{
|
||||
if (await db.Sequences.GetAsync(sequence.Id, context.Cancellation).ConfigureAwait(false) is { } row && row.ArchiveId == archive.Id) present.Add(sequence.Id);
|
||||
else context.Log(Loc.L("Archive.Log.SequenceMissing", sequence.Id));
|
||||
}
|
||||
return present;
|
||||
}
|
||||
|
||||
/// <summary>After each step: the checkpoint, then the sequences that step changed are told.</summary>
|
||||
private async ValueTask StepDoneAsync(JobContext context, Guid planId, int done, int total, IReadOnlyList<Guid> changed)
|
||||
{
|
||||
await context.CheckpointAsync(Checkpoint(planId), done, total).ConfigureAwait(false);
|
||||
await TellAsync(changed).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Holds the plan of a failed run and logs what its completed steps did; a hold that cannot be written is logged.</summary>
|
||||
private static void HoldFailed(JobContext context, Archive archive, Guid planId)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!MassRenamer.Hold(archive, planId) || RenameJournal.Read(new ArchivePaths(archive.RootPath), planId) is not { } journal) return;
|
||||
Log.Info("archive", $"Reorganize {planId} held by its failed job {context.Job.Id}");
|
||||
LogDone(context, journal.Plan, RenameResult.Of(journal.Done));
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException)
|
||||
{
|
||||
Log.Warning("archive", $"Reorganize {planId} could not be held after its job failed", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The job log of what the plan did: the counts, then each sequence not changed as planned, and why.</summary>
|
||||
private static void LogDone(JobContext context, RenamePlan plan, RenameResult result)
|
||||
{
|
||||
context.Log(Loc.L("Archive.Log.Reorganized", result.Changed.Count, result.Files));
|
||||
foreach (var id in result.Dropped) context.Log(Loc.L("Archive.Log.ReorganizeDropped", Name(plan, id)));
|
||||
foreach (var id in result.TitlesKept) context.Log(Loc.L("Archive.Log.ReorganizeTitleKept", Name(plan, id)));
|
||||
foreach (var id in result.FilesKept) context.Log(Loc.L("Archive.Log.ReorganizeFilesKept", Name(plan, id)));
|
||||
foreach (var id in result.FilesBusy) context.Log(Loc.L("Archive.Log.ReorganizeFilesBusy", Name(plan, id)));
|
||||
}
|
||||
|
||||
/// <summary>Whether the plan made now is the one confirmed: the same fingerprint, and the frames versions its file names were planned at.</summary>
|
||||
private static bool IsConfirmed(RenamePlan plan, MoveJobParameters parameters)
|
||||
{
|
||||
|
||||
@@ -8,8 +8,9 @@ using Chronos.Data.Repositories;
|
||||
namespace Chronos.Data.Archiving;
|
||||
|
||||
/// <summary>
|
||||
/// 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, or the photos of a sequence whose files it renames changed.
|
||||
/// The plan no longer matches the archive: 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, a title it changes was edited, or the photos of a
|
||||
/// sequence whose files it renames changed.
|
||||
/// </summary>
|
||||
public sealed class StaleRenamePlanException(Guid sequenceId)
|
||||
: InvalidOperationException(Loc.L("Archive.Error.StalePlan"))
|
||||
@@ -18,11 +19,23 @@ public sealed class StaleRenamePlanException(Guid sequenceId)
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What applying a plan did: the sequences changed (in the order of the plan), the frames whose files got a new name, the
|
||||
/// sequences left as they were because they changed since the plan (<see cref="Dropped"/>, only when resuming) and those
|
||||
/// whose files kept their names because their photos changed since (<see cref="FilesKept"/>; their folder and title changed).
|
||||
/// 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 (<see cref="Dropped"/>, only when resuming), whose files kept their names because their photos changed since
|
||||
/// (<see cref="FilesKept"/>; their folder and title changed), whose title and file names stayed because their title was
|
||||
/// edited since or their sidecar is of a newer format (<see cref="TitlesKept"/>, only when resuming; their folder moved),
|
||||
/// and whose files kept their names because a photo was in use (<see cref="FilesBusy"/>; their folder and title changed).
|
||||
/// </summary>
|
||||
public sealed record RenameResult(IReadOnlyList<Guid> Changed, int Files, IReadOnlyList<Guid> Dropped, IReadOnlyList<Guid> FilesKept);
|
||||
public sealed record RenameResult(IReadOnlyList<Guid> Changed, int Files, IReadOnlyList<Guid> Dropped, IReadOnlyList<Guid> FilesKept,
|
||||
IReadOnlyList<Guid> TitlesKept, IReadOnlyList<Guid> FilesBusy)
|
||||
{
|
||||
/// <summary>The result a plan's journal records for its completed steps (<see cref="RenameJournal.Done"/>).</summary>
|
||||
public static RenameResult Of(RenameTally tally)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(tally);
|
||||
return new(tally.Changed, tally.Files, tally.Dropped, tally.FilesKept, tally.TitlesKept, tally.FilesBusy);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Mass rename of sequence folders, titles and file names (BRIEF §7, §12.5; Reorganize, owner review 2, R7):
|
||||
@@ -45,6 +58,19 @@ public sealed class MassRenamer
|
||||
_indexer = indexer;
|
||||
}
|
||||
|
||||
/// <summary>How far a sequence of a step still fits the plan, checked under the step's leases before anything of the step moves.</summary>
|
||||
private enum Fit
|
||||
{
|
||||
/// <summary>As planned.</summary>
|
||||
Whole,
|
||||
|
||||
/// <summary>Its photos changed since the plan (or its sidecar is of a newer format): its folder and title change, its files keep their names.</summary>
|
||||
Files,
|
||||
|
||||
/// <summary>Its title was edited since the plan (or its sidecar is of a newer format): its title and file names stay.</summary>
|
||||
Title,
|
||||
}
|
||||
|
||||
/// <param name="folderTemplate">New folder template (<c>{title}</c> = the new title), or null to keep folders.</param>
|
||||
/// <param name="titleTemplate">New title template (<c>{title}</c> = the current title), or null to keep titles.</param>
|
||||
/// <remarks>Sequences nested in a folder that moves are part of the plan (they move with it); see <see cref="RenamePlanner.Plan"/>.</remarks>
|
||||
@@ -91,15 +117,22 @@ public sealed class MassRenamer
|
||||
|
||||
private static RenameSubject Subject(Sequence s) => new(s.Id, s.Folder, s.Title, s.FirstCapture, s.CameraMake, s.CameraModel, s.Lens);
|
||||
|
||||
/// <summary>The sidecar of a sequence and the files beside its frames; null (logged) when it cannot be read or is another sequence's.</summary>
|
||||
/// <summary>
|
||||
/// The sidecar of a sequence and the files beside its frames; null (logged) when it cannot be read, is another
|
||||
/// sequence's, or is of a newer format this build never rewrites (its files cannot get new names here).
|
||||
/// </summary>
|
||||
private static SequenceFiles? ReadFiles(ArchivePaths paths, Sequence sequence)
|
||||
{
|
||||
var folder = paths.Sequence(sequence.Folder);
|
||||
try
|
||||
{
|
||||
var manifest = ManifestStore.ReadSequence(folder.ManifestPath);
|
||||
if (manifest.Id == sequence.Id) return new SequenceFiles(manifest, FileRenames.ListPresent(folder, manifest));
|
||||
Log.Warning("archive", $"{folder.ManifestPath} belongs to sequence {manifest.Id}, not {sequence.Id}; its files keep their names");
|
||||
if (manifest.Id != sequence.Id)
|
||||
Log.Warning("archive", $"{folder.ManifestPath} belongs to sequence {manifest.Id}, not {sequence.Id}; its files keep their names");
|
||||
else if (manifest.SchemaVersion > SequenceManifest.CurrentSchemaVersion)
|
||||
Log.Warning("archive", $"{folder.ManifestPath} was written by a newer Chronos (format {manifest.SchemaVersion}); its files keep their names");
|
||||
else
|
||||
return new SequenceFiles(manifest, FileRenames.ListPresent(folder, manifest));
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
|
||||
{
|
||||
@@ -110,14 +143,17 @@ public sealed class MassRenamer
|
||||
|
||||
/// <summary>Applies a plan; each completed step is journaled before the next starts.</summary>
|
||||
/// <exception cref="StaleRenamePlanException">A sequence is no longer where the plan expects it, a folder that moves holds
|
||||
/// a sequence the plan does not take along, or the photos of a sequence whose files it renames changed; nothing of that
|
||||
/// step was changed (a step found stale only once its folder moved keeps its folder and title, and its journal has the
|
||||
/// next open complete the rest).</exception>
|
||||
/// <exception cref="IOException">A file could not be renamed (open elsewhere); the step's files went back to their names. Or
|
||||
/// (<see cref="LeaseUnavailableException"/>) a sequence is busy, or holds a restore from the trash whose entry is busy and
|
||||
/// not settled yet; nothing of that step changed.</exception>
|
||||
/// a sequence the plan does not take along, something took a folder the plan moves one into, a title it changes was
|
||||
/// edited, or the photos of a sequence whose files it renames changed; nothing of that step was changed (each is
|
||||
/// checked under the step's leases before anything of it moves), the steps before it were.</exception>
|
||||
/// <exception cref="NewerFormatException">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.</exception>
|
||||
/// <exception cref="IOException">A folder could not be moved, or (<see cref="LeaseUnavailableException"/>) a sequence is
|
||||
/// busy, or holds a restore from the trash whose entry is busy and not settled yet; nothing of that step changed. A
|
||||
/// file that could not be renamed (open elsewhere) does not fail the step: the sequence keeps its file names
|
||||
/// (<see cref="RenameResult.FilesBusy"/>).</exception>
|
||||
public Task<RenameResult> ApplyAsync(Archive archive, RenamePlan plan, IProgress<int>? progress = null, CancellationToken cancellationToken = default) =>
|
||||
ApplyAsync(archive, plan, null, progress is null ? null : n =>
|
||||
ApplyAsync(archive, plan, null, progress is null ? null : (n, _) =>
|
||||
{
|
||||
progress.Report(n);
|
||||
return ValueTask.CompletedTask;
|
||||
@@ -125,8 +161,8 @@ public sealed class MassRenamer
|
||||
|
||||
/// <inheritdoc cref="ApplyAsync(Archive, RenamePlan, IProgress{int}?, CancellationToken)"/>
|
||||
/// <param name="started">Told once the plan's journal is written, before any step (a job saves the plan's id as its checkpoint).</param>
|
||||
/// <param name="stepDone">Told after each step with the number of steps done.</param>
|
||||
public Task<RenameResult> ApplyAsync(Archive archive, RenamePlan plan, Func<RenamePlan, ValueTask>? started, Func<int, ValueTask>? stepDone,
|
||||
/// <param name="stepDone">Told after each step is journaled, with the number of steps done and the sequences that step changed.</param>
|
||||
public Task<RenameResult> ApplyAsync(Archive archive, RenamePlan plan, Func<RenamePlan, ValueTask>? started, Func<int, IReadOnlyList<Guid>, ValueTask>? stepDone,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
@@ -137,9 +173,12 @@ public sealed class MassRenamer
|
||||
/// Completes the plan <paramref name="planId"/> from its journal: one an interruption left (as <see cref="ResumePendingAsync"/>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="stepDone">Told after each step is journaled, with the number of steps done and the sequences that step changed.</param>
|
||||
/// <exception cref="StaleRenamePlanException">A held plan's remaining steps no longer match the archive; nothing more changed.</exception>
|
||||
public async Task<RenameResult?> ResumeAsync(Archive archive, Guid planId, Func<int, ValueTask>? stepDone = null, CancellationToken cancellationToken = default)
|
||||
public async Task<RenameResult?> ResumeAsync(Archive archive, Guid planId, Func<int, IReadOnlyList<Guid>, ValueTask>? stepDone = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
if (RenameJournal.Read(new ArchivePaths(archive.RootPath), planId) is not { } journal) return null;
|
||||
@@ -147,8 +186,8 @@ public sealed class MassRenamer
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks the plan <paramref name="planId"/> held (<see cref="RenameJournal.Held"/>): its job was paused or cancelled between
|
||||
/// two steps, so an archive open leaves the rest to that job. False when it has no journal (it completed).
|
||||
/// Marks the plan <paramref name="planId"/> held (<see cref="RenameJournal.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).
|
||||
/// </summary>
|
||||
public static bool Hold(Archive archive, Guid planId)
|
||||
{
|
||||
@@ -159,19 +198,53 @@ public sealed class MassRenamer
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Completes renames interrupted by a crash (not those their job held); returns how many plans were resumed.</summary>
|
||||
/// <summary>
|
||||
/// Completes renames interrupted by a crash (not those their job held); returns how many plans were resumed. The file
|
||||
/// renames a held plan's step left half-way are completed all the same (<see cref="SettleFilesAsync"/>), so no photo
|
||||
/// waits at a temporary name for that job.
|
||||
/// </summary>
|
||||
public async Task<int> ResumePendingAsync(Archive archive, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
var pending = RenameJournal.ListPending(paths).Where(j => j.Plan.ArchiveId == archive.Id && !j.Held).ToList();
|
||||
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, null, cancellationToken).ConfigureAwait(false);
|
||||
return pending.Count;
|
||||
}
|
||||
|
||||
/// <param name="resuming">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.</param>
|
||||
/// <summary>
|
||||
/// 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 (<see cref="SequenceWriter.ReadLocked"/>: 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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <param name="resuming">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.</param>
|
||||
private async Task<RenameResult> RunAsync(Archive archive, RenameJournal journal, bool resuming, Func<RenamePlan, ValueTask>? started,
|
||||
Func<int, ValueTask>? stepDone, CancellationToken cancellationToken)
|
||||
Func<int, IReadOnlyList<Guid>, ValueTask>? stepDone, CancellationToken cancellationToken)
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
@@ -181,11 +254,14 @@ public sealed class MassRenamer
|
||||
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 (StaleRenamePlanException) when (completed.Count > 0 || File.Exists(RenameJournal.PathFor(paths, journal.Plan.Id)))
|
||||
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);
|
||||
@@ -195,7 +271,7 @@ public sealed class MassRenamer
|
||||
}
|
||||
RenameJournal.Write(paths, journal);
|
||||
if (started is not null) await started(journal.Plan).ConfigureAwait(false);
|
||||
var result = new Tally();
|
||||
var result = new Tally(journal.Done);
|
||||
foreach (var step in steps)
|
||||
{
|
||||
if (completed.Contains(step.SequenceId)) continue;
|
||||
@@ -204,45 +280,62 @@ public sealed class MassRenamer
|
||||
IReadOnlyList<RenameStep> 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);
|
||||
RenameJournal.Write(paths, journal with { Completed = [.. completed] });
|
||||
if (stepDone is not null) await stepDone(completed.Count).ConfigureAwait(false);
|
||||
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 new RenameResult(result.Changed, result.Files, result.Dropped, result.FilesKept);
|
||||
return RenameResult.Of(result.Record());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A plan made before another change is refused before anything moves: a sequence moved, one was indexed inside a
|
||||
/// folder that moves (a scan adopted a subfolder copied in since the dry run), or the photos of a sequence whose files
|
||||
/// it renames changed (another frames version in its sidecar).
|
||||
/// A plan made before another change is refused before anything moves: a sequence moved, a title it changes 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 (<see cref="TargetTaken"/>), the photos of a sequence whose files it renames changed
|
||||
/// (<see cref="FilesStand"/>), 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. Read without the leases, each step checks the same again under its own
|
||||
/// (<see cref="FitAsync"/>), so a held plan resumed by its job either fits here or is given up.
|
||||
/// </summary>
|
||||
/// <exception cref="NewerFormatException">A sidecar the plan rewrites is of a newer format.</exception>
|
||||
private async Task RefuseStaleAsync(Archive archive, ArchivePaths paths, RenamePlan plan, IReadOnlyList<RenameStep> remaining, CancellationToken cancellationToken)
|
||||
{
|
||||
var locations = await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false);
|
||||
var template = plan.FileTemplate is null ? null : PathTemplate.Parse(plan.FileTemplate);
|
||||
foreach (var step in remaining)
|
||||
{
|
||||
if ((await _db.Sequences.GetAsync(step.SequenceId, cancellationToken).ConfigureAwait(false))?.Folder != step.FromFolder)
|
||||
var row = await _db.Sequences.GetAsync(step.SequenceId, cancellationToken).ConfigureAwait(false);
|
||||
if (row is null || (row.Folder != step.FromFolder && row.Folder != step.ToFolder) || (step.Retitles && !Planned(step, row.Title))
|
||||
|| (!step.Carried && TargetTaken(paths, step, locations)))
|
||||
throw new StaleRenamePlanException(step.SequenceId);
|
||||
var files = template is not null && step.FileChanges > 0;
|
||||
if (!step.Retitles && !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 (manifest.SchemaVersion > SequenceManifest.CurrentSchemaVersion) throw new NewerFormatException(sequence.ManifestPath, manifest.SchemaVersion);
|
||||
if ((step.Retitles && !TitleStands(step, row, manifest)) || (files && !FilesStand(sequence, template!, step, manifest)))
|
||||
throw new StaleRenamePlanException(step.SequenceId);
|
||||
}
|
||||
var planned = plan.Steps.Select(s => s.SequenceId).ToHashSet();
|
||||
if (await StrangerInsideAsync(archive, remaining.Where(s => s.MovesFolder && !s.Carried), planned, cancellationToken).ConfigureAwait(false) is { } stranger)
|
||||
if (StrangerInside(locations, remaining.Where(s => s.MovesFolder && !s.Carried), planned) is { } stranger)
|
||||
throw new StaleRenamePlanException(stranger.Id);
|
||||
if (plan.FileTemplate is null) return;
|
||||
foreach (var step in remaining.Where(s => s.FileChanges > 0))
|
||||
{
|
||||
if (FramesVersionOf(paths.Sequence(step.FromFolder), step.SequenceId) != step.FramesVersion) throw new StaleRenamePlanException(step.SequenceId);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The frames version of a sequence's sidecar (read without its lease); null when it cannot be read or is another sequence's.</summary>
|
||||
private static int? FramesVersionOf(SequencePaths sequence, Guid sequenceId)
|
||||
/// <summary>The sidecar of a sequence (read without its lease); null when it cannot be read or is another sequence's.</summary>
|
||||
private static SequenceManifest? ReadSidecar(SequencePaths sequence, Guid sequenceId)
|
||||
{
|
||||
try
|
||||
{
|
||||
var manifest = ManifestStore.ReadSequence(sequence.ManifestPath);
|
||||
return manifest.Id == sequenceId ? manifest.Versions.Frames : null;
|
||||
return manifest.Id == sequenceId ? manifest : null;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
|
||||
{
|
||||
@@ -254,15 +347,29 @@ public sealed class MassRenamer
|
||||
private static RenameStep? Carrier(IReadOnlyList<RenameStep> steps, RenameStep carried) =>
|
||||
steps.Where(m => !m.Carried && m.MovesFolder && RenamePlanner.IsInside(m.FromFolder, carried.FromFolder)).MaxBy(m => m.FromFolder.Length);
|
||||
|
||||
/// <summary>Where a step's sequence is now: its folder moves first, so a resumed step may find it at its new place already.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Whether a step's folder moved already (an interrupted run moved it before every index row followed).</summary>
|
||||
private static bool Moved(ArchivePaths paths, RenameStep step) => step.MovesFolder && !Directory.Exists(paths.FromRelative(step.FromFolder));
|
||||
|
||||
/// <summary>
|
||||
/// 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. Once the folder moved the step goes to its end whatever
|
||||
/// the caller cancels.
|
||||
/// 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: <see cref="FitAsync"/>). Then the folder moves, every index row follows it, 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.
|
||||
/// </summary>
|
||||
/// <param name="resuming">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.</param>
|
||||
/// <param name="resuming">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.</param>
|
||||
private async Task ApplyStepAsync(Archive archive, ArchivePaths paths, string? fileTemplate, RenameStep step, IReadOnlyList<RenameStep> carried,
|
||||
bool resuming, Tally result, CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -292,20 +399,32 @@ public sealed class MassRenamer
|
||||
if (await StandsAsync(c, resuming, cancellationToken).ConfigureAwait(false)) follow.Add(c);
|
||||
else result.Dropped.Add(c.SequenceId);
|
||||
}
|
||||
if (!await CarriesAllInsideAsync(archive, paths, step, carried, resuming, cancellationToken).ConfigureAwait(false))
|
||||
IReadOnlyList<SequenceLocation> 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;
|
||||
}
|
||||
foreach (var s in follow.Prepend(step)) Settle(paths, s);
|
||||
RenamePlanner.MoveFolder(paths, step);
|
||||
// Moved with their carrier: only their sidecars and index rows follow, and the names of their files.
|
||||
foreach (var s in follow.Prepend(step))
|
||||
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 while nothing of it moved: it stays as it was, with the sequences it would carry.
|
||||
if (fits[0].Fit == Fit.Title && !Moved(paths, step))
|
||||
{
|
||||
await RecordAsync(archive, paths, s, CancellationToken.None).ConfigureAwait(false);
|
||||
var renamed = await RenameFilesAsync(archive, paths, fileTemplate, s, resuming, result, CancellationToken.None).ConfigureAwait(false);
|
||||
if (s.MovesFolder || s.Retitles || renamed) result.Changed.Add(s.SequenceId);
|
||||
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.
|
||||
foreach (var (s, fit) in fits) await RecordAsync(archive, paths, s, s.Retitles && fit != Fit.Title, CancellationToken.None).ConfigureAwait(false);
|
||||
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);
|
||||
if (s.MovesFolder || (s.Retitles && fit != Fit.Title) || renamed) result.Changed.Add(s.SequenceId);
|
||||
}
|
||||
}
|
||||
finally
|
||||
@@ -320,18 +439,78 @@ public sealed class MassRenamer
|
||||
/// sequence, as every writer does (<see cref="SequenceWriter.ReadLocked"/>): 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 (<see cref="FrameTrash.EnsureSettled"/>) 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.
|
||||
/// files it moved by the names they had, so neither the folder nor those names change under it. Returns the sidecar as
|
||||
/// settled.
|
||||
/// </summary>
|
||||
/// <exception cref="LeaseUnavailableException">A restore from the trash into the sequence is not settled; nothing of the step changed.</exception>
|
||||
private static void Settle(ArchivePaths paths, RenameStep step)
|
||||
private static SequenceManifest Settle(ArchivePaths paths, RenameStep step)
|
||||
{
|
||||
// Where the sequence is now: its folder moves first, so a resumed step may find it at its new place already.
|
||||
var sequence = paths.Sequence(step.FromFolder);
|
||||
if (step.MovesFolder && !File.Exists(sequence.ManifestPath)) sequence = paths.Sequence(step.ToFolder);
|
||||
SequenceWriter.ReadLocked(sequence, step.SequenceId);
|
||||
var sequence = Where(paths, step);
|
||||
var manifest = SequenceWriter.ReadLocked(sequence, step.SequenceId);
|
||||
FrameTrash.EnsureSettled(sequence);
|
||||
return manifest;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// How far a sequence of a step still fits the plan, under the step's leases with its sidecar settled
|
||||
/// (<paramref name="manifest"/>) 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 (<see cref="TitleStands"/>), and the files are renamed only as the
|
||||
/// plan renames them (<see cref="FilesStand"/>). When not resuming, what no longer fits refuses the step.
|
||||
/// </summary>
|
||||
/// <exception cref="NewerFormatException">Not resuming, and the step would rewrite a sidecar of a newer format.</exception>
|
||||
/// <exception cref="StaleRenamePlanException">Not resuming, and its title or photos changed since the plan.</exception>
|
||||
private async Task<Fit> 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 step.Retitles ? Fit.Title : Fit.Files;
|
||||
}
|
||||
if (step.Retitles && 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))
|
||||
{
|
||||
if (!resuming) throw new StaleRenamePlanException(step.SequenceId);
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
|
||||
/// <summary>
|
||||
/// Whether the files of a step's sequence still rename as planned: planned again from <paramref name="manifest"/> and the
|
||||
/// files beside its frames, they rename exactly the files the plan renamed (<see cref="RenameStep.FileDigest"/>) at its
|
||||
/// frames version, or none is left to rename (an interrupted run renamed them). A photo hashed, back or added since,
|
||||
/// or a file copied in beside them, would give other names than the dry run showed.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
private static bool Matches(RenameStep step, FileRenamePlan plan, SequenceManifest manifest) =>
|
||||
manifest.Versions.Frames == step.FramesVersion && (step.FileDigest is null || string.Equals(step.FileDigest, plan.Digest(), StringComparison.Ordinal));
|
||||
|
||||
/// <summary>The index still has the step's sequence where the plan says (or where it already took it); otherwise stale.</summary>
|
||||
/// <exception cref="StaleRenamePlanException">Not resuming, and the sequence moved or vanished since the plan was made.</exception>
|
||||
private async Task<bool> StandsAsync(RenameStep step, bool resuming, CancellationToken cancellationToken)
|
||||
@@ -350,26 +529,49 @@ public sealed class MassRenamer
|
||||
/// moved yet (a folder moved before the interruption goes on; the next scan indexes the newcomer where it ended up).
|
||||
/// </summary>
|
||||
/// <exception cref="StaleRenamePlanException">Not resuming, and such a sequence is inside the folder.</exception>
|
||||
private async Task<bool> CarriesAllInsideAsync(Archive archive, ArchivePaths paths, RenameStep step, IReadOnlyList<RenameStep> carried, bool resuming,
|
||||
CancellationToken cancellationToken)
|
||||
private static bool CarriesAllInside(ArchivePaths paths, RenameStep step, IReadOnlyList<RenameStep> carried, IReadOnlyList<SequenceLocation> locations,
|
||||
bool resuming)
|
||||
{
|
||||
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 (StrangerInside(locations, [step], carried.Select(c => c.SequenceId).ToHashSet()) is not { } stranger) return true;
|
||||
if (!resuming) throw new StaleRenamePlanException(stranger.Id);
|
||||
if (!Directory.Exists(paths.Sequence(step.FromFolder).Folder)) return true;
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>A sequence the index has inside the folder of one of <paramref name="moving"/> that is not in <paramref name="taken"/>; null when there is none.</summary>
|
||||
private async Task<SequenceLocation?> StrangerInsideAsync(Archive archive, IEnumerable<RenameStep> moving, IReadOnlySet<Guid> taken,
|
||||
CancellationToken cancellationToken)
|
||||
/// <summary>
|
||||
/// Whether the new folder of a moving step is still free (<see cref="TargetTaken"/>), 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.
|
||||
/// </summary>
|
||||
/// <exception cref="StaleRenamePlanException">Not resuming, and something took the new folder.</exception>
|
||||
private static bool TargetFree(ArchivePaths paths, RenameStep step, IReadOnlyList<SequenceLocation> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private static bool TargetTaken(ArchivePaths paths, RenameStep step, IReadOnlyList<SequenceLocation> locations)
|
||||
{
|
||||
if (!step.MovesFolder || step.FromFolder.Equals(step.ToFolder, StringComparison.OrdinalIgnoreCase) || Moved(paths, step)) return false;
|
||||
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)));
|
||||
}
|
||||
|
||||
/// <summary>A sequence of <paramref name="locations"/> inside the folder of one of <paramref name="moving"/> that is not in <paramref name="taken"/>; null when there is none.</summary>
|
||||
private static SequenceLocation? StrangerInside(IReadOnlyList<SequenceLocation> locations, IEnumerable<RenameStep> moving, IReadOnlySet<Guid> taken)
|
||||
{
|
||||
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)));
|
||||
return folders.Count == 0 ? null : locations.FirstOrDefault(l => !taken.Contains(l.Id) && folders.Any(f => RenamePlanner.IsInside(f, l.Folder)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -378,17 +580,16 @@ public sealed class MassRenamer
|
||||
/// 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
|
||||
/// (<see cref="ArchiveIndexer.InStepAsync(Archive, string, SequencePaths, SequenceManifest, CancellationToken)"/>). A step
|
||||
/// that only renames files has nothing to record here.
|
||||
/// that only renames files, or keeps its title, has nothing to record here.
|
||||
/// </summary>
|
||||
private async Task RecordAsync(Archive archive, ArchivePaths paths, RenameStep step, CancellationToken cancellationToken)
|
||||
/// <param name="retitle">Whether the step's title is written (false: the title stays, edited since the plan or in a sidecar of a newer format).</param>
|
||||
private async Task RecordAsync(Archive archive, ArchivePaths paths, RenameStep step, bool retitle, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!step.MovesFolder && !step.Retitles) return;
|
||||
if (!step.MovesFolder && !retitle) return;
|
||||
var sequence = paths.Sequence(step.ToFolder);
|
||||
var manifest = SequenceWriter.ReadLocked(sequence, step.SequenceId);
|
||||
// The folder moved with its files' stamps, which the index recorded at its old place.
|
||||
var inStep = await _indexer.InStepAsync(archive, step.FromFolder, sequence, manifest, cancellationToken).ConfigureAwait(false);
|
||||
// A step that only moves the folder keeps the title, which an edit may have changed since the plan.
|
||||
var retitle = step.Retitles;
|
||||
if (retitle && manifest.Title != step.ToTitle)
|
||||
{
|
||||
manifest = manifest with
|
||||
@@ -410,30 +611,33 @@ public sealed class MassRenamer
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The file renames of a step, under the leases its step holds, once its folder is in place (Reorganize, owner review 2,
|
||||
/// R7). The renames are planned again from the sidecar read under the lease (<see cref="FileRenames.Plan"/>, with the
|
||||
/// step's title, the one the dry run showed), which names exactly what the dry run showed while its frames version is the plan's: another one
|
||||
/// refuses the step (<see cref="StaleRenamePlanException"/>), or, when resuming, leaves its files as they are. The files
|
||||
/// move in two phases through temporary names under the sequence's journal (<see cref="FileRenameJournal"/>), then the
|
||||
/// sidecar names them (the frame order unchanged, frames version + 1), then the index (<see cref="FrameRepository.RenameFilesAsync"/>),
|
||||
/// then the journal goes. When nothing moves here but the index names other files than the sidecar, a writer completed
|
||||
/// the renames after a crash (<see cref="SequenceWriter.ReadLocked"/>) 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.
|
||||
/// 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 (<see cref="FileRenames.Plan"/>, with the step's title, the one the dry run showed) and made only while they are
|
||||
/// exactly the plan's (<see cref="Matches"/>, 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 (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 (<see cref="FileRenameJournal"/>), then the sidecar names them (the frame order unchanged, frames version + 1),
|
||||
/// then the index (<see cref="FrameRepository.RenameFilesAsync"/>), 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
|
||||
/// (<see cref="SequenceWriter.ReadLocked"/>) 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.
|
||||
/// </summary>
|
||||
/// <returns>False when the step renames no file, or its files kept their names.</returns>
|
||||
private async Task<bool> RenameFilesAsync(Archive archive, ArchivePaths paths, string? fileTemplate, RenameStep step, bool resuming, Tally result,
|
||||
/// <exception cref="IOException">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.</exception>
|
||||
private async Task<bool> RenameFilesAsync(Archive archive, ArchivePaths paths, string fileTemplate, RenameStep step, Tally result,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (fileTemplate is null || step.FileChanges == 0) return false;
|
||||
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 && before != step.FramesVersion)
|
||||
if (plan.Moves.Count > 0 && !Matches(step, plan, manifest))
|
||||
{
|
||||
if (!resuming) throw new StaleRenamePlanException(step.SequenceId);
|
||||
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;
|
||||
@@ -442,9 +646,25 @@ public sealed class MassRenamer
|
||||
{
|
||||
var journal = FileRenameJournal.Create(before, plan.Moves, Guid.NewGuid().ToString("N")[..8]);
|
||||
FileRenameJournal.Write(sequence, journal);
|
||||
journal = FileRenameJournal.Run(sequence, journal);
|
||||
manifest = FileRenameJournal.Applied(manifest, journal) ?? manifest;
|
||||
ManifestStore.WriteSequence(sequence.ManifestPath, manifest);
|
||||
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, 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", 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,
|
||||
@@ -479,12 +699,25 @@ public sealed class MassRenamer
|
||||
last = rows[^1].Index;
|
||||
}
|
||||
}
|
||||
/// <summary>What a run did, as it goes.</summary>
|
||||
private sealed class Tally
|
||||
|
||||
/// <summary>What a plan's runs did, as they go: from what its completed steps did already (<see cref="RenameJournal.Done"/>).</summary>
|
||||
private sealed class Tally(RenameTally done)
|
||||
{
|
||||
public List<Guid> Changed { get; } = [];
|
||||
public List<Guid> Dropped { get; } = [];
|
||||
public List<Guid> FilesKept { get; } = [];
|
||||
public int Files { get; set; }
|
||||
public List<Guid> Changed { get; } = [.. done.Changed];
|
||||
public List<Guid> Dropped { get; } = [.. done.Dropped];
|
||||
public List<Guid> FilesKept { get; } = [.. done.FilesKept];
|
||||
public List<Guid> TitlesKept { get; } = [.. done.TitlesKept];
|
||||
public List<Guid> FilesBusy { get; } = [.. done.FilesBusy];
|
||||
public int Files { get; set; } = done.Files;
|
||||
|
||||
public RenameTally Record() => new()
|
||||
{
|
||||
Changed = [.. Changed],
|
||||
Files = Files,
|
||||
Dropped = [.. Dropped],
|
||||
FilesKept = [.. FilesKept],
|
||||
TitlesKept = [.. TitlesKept],
|
||||
FilesBusy = [.. FilesBusy],
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user