fix(reorganize): a sequence still receiving photos keeps its file names and the job goes on
A Reorganize with a file template failed its job at the step of a sequence
a camera was still uploading into, and its retry gave the rest up. Photos
changed since the plan now never refuse a step: that sequence keeps its file
names (FilesKept), its folder and title change as planned, the other steps go
on and the job ends with ReorganizeKept. The fingerprint, the job's
confirmation and the check under the leases pin file renames by their digest
instead of the frames version, so photos filed under the names the plan gives
them no longer make a dry run or a queued job stale.
- A step whose folder or files a template names after {title} checks the
title as a retitle does (RenameStep.NamedByTitle): no name comes from a
title edited since the plan.
- Recovery sends a photo that already took its new name back together with a
companion whose new name was taken, so the two never end up apart.
- ArchiveService.OpenAsync logs a NewerFormatException from resuming a plan
and keeps its journal, so a server still boots.
- Once a step's folder moved, every index row of the step follows it even
when a sidecar cannot be read or written; the step then fails for a retry.
- Job log lines and errors give the real reason for files kept busy (in use
or a new name taken) and for a sidecar of a newer format (new Newer
outcome; strings en and it).
- A plan an archive open completes tells sequenceChanged; the docs that
promised more than that are corrected.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit f8554b8af0828ab9b0ff128e694abacdd53e6fd7)
This commit is contained in:
1 parent
59ee982e4d
commit
9e1f109b58
16 files changed
+560
-195
No files matched your search
@@ -128,7 +128,8 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
|
||||
/// <summary>
|
||||
/// Registers an existing archive (or relinks a moved one: same id, new root) and completes renames a crash
|
||||
/// interrupted. An offline archive is registered as it was last seen.
|
||||
/// interrupted (each sequence they change is told to <see cref="ArchiveServiceOptions.SequenceChanged"/>); one that
|
||||
/// cannot be completed yet is logged and waits for the next open. An offline archive is registered as it was last seen.
|
||||
/// </summary>
|
||||
public async Task<Archive> OpenAsync(string root, CancellationToken cancellationToken = default)
|
||||
{
|
||||
@@ -139,9 +140,9 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
{
|
||||
await Renamer.ResumePendingAsync(archive, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or NewerFormatException)
|
||||
{
|
||||
// The journal stays; the next open tries again. The archive itself is usable meanwhile.
|
||||
// The journal stays; the next open tries again. The archive itself is usable meanwhile (a server starts all the same).
|
||||
Log.Warning("archive", $"Resuming an interrupted rename in {paths.Root} failed", ex);
|
||||
}
|
||||
return archive;
|
||||
@@ -595,8 +596,8 @@ public static class ArchiveJobs
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
ArgumentNullException.ThrowIfNull(templates);
|
||||
// The sequences that have a step, in the order the plan was made for: the others change nothing, now or when planned again.
|
||||
var steps = plan.Steps.ToDictionary(s => s.SequenceId);
|
||||
var sequences = plan.Subjects.Where(steps.ContainsKey).Select(id => new MoveSequence(id, steps[id].FramesVersion)).ToList();
|
||||
var steps = plan.Steps.Select(s => s.SequenceId).ToHashSet();
|
||||
var sequences = plan.Subjects.Where(steps.Contains).Select(id => new MoveSequence(id)).ToList();
|
||||
return new(JobKind.Move, [archive.Id], archive.Name,
|
||||
Json(new MoveJobParameters(templates.Folder, templates.File, templates.Title, sequences, plan.Fingerprint()), ArchiveJobJson.Default.MoveJobParameters),
|
||||
JobPriority.User);
|
||||
|
||||
@@ -42,14 +42,14 @@ public sealed record EmptyTrashItem(string Name, string Fingerprint);
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Move"/> (Reorganize, owner review 2, R7): target = the archive; the templates (null keeps that part),
|
||||
/// the sequences the confirmed plan changes in the order it was made for, each with the frames version its file names
|
||||
/// were planned at (0 when none is renamed), and the plan's fingerprint (<see cref="Core.Archiving.RenamePlan.Fingerprint"/>).
|
||||
/// No file list: the job plans again and refuses when the plan is no longer the one confirmed.
|
||||
/// the sequences the confirmed plan changes in the order it was made for, and the plan's fingerprint
|
||||
/// (<see cref="Core.Archiving.RenamePlan.Fingerprint"/>, which pins every file rename by its digest). No file list: the job
|
||||
/// plans again and refuses when the plan is no longer the one confirmed.
|
||||
/// </summary>
|
||||
public sealed record MoveJobParameters(string? FolderTemplate, string? FileTemplate, string? TitleTemplate, IReadOnlyList<MoveSequence> Sequences, string Fingerprint);
|
||||
|
||||
/// <summary>A sequence of a <see cref="MoveJobParameters"/> and the frames version its file names were planned at.</summary>
|
||||
public sealed record MoveSequence(Guid Id, int FramesVersion);
|
||||
/// <summary>A sequence of a <see cref="MoveJobParameters"/> (a job queued by an earlier build also names a frames version, which is ignored).</summary>
|
||||
public sealed record MoveSequence(Guid Id);
|
||||
|
||||
/// <summary>A job ready to enqueue.</summary>
|
||||
public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList<Guid> Targets, string? Label, string? ParametersJson, JobPriority Priority);
|
||||
|
||||
@@ -10,22 +10,24 @@ namespace Chronos.Data.Archiving.Jobs;
|
||||
/// <summary>
|
||||
/// <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; 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.
|
||||
/// when it is still the one confirmed (its fingerprint, which pins every file rename; <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 (one still receiving photos keeps its file names), a newer Chronos wrote their sidecar, or a
|
||||
/// photo was in use or its new name taken, 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"/>) once its step is
|
||||
/// journaled, by this run or by an archive open that completed a plan an interruption left; a step that failed half-way
|
||||
/// (its folder moved, then a sidecar could not be read) is told when its retry completes it. 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
|
||||
{
|
||||
/// <summary>The change a Reorganize tells about a sequence (a server's <c>sequenceChanged</c> event).</summary>
|
||||
public const string Change = "reorganized";
|
||||
public const string Change = MassRenamer.Change;
|
||||
|
||||
private const string Prefix = "plan:";
|
||||
|
||||
@@ -83,6 +85,7 @@ internal sealed class MoveJobHandler(ChronosDatabase db, MassRenamer renamer, Fu
|
||||
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.Newer.Count > 0) throw new InvalidOperationException(Loc.Plural("Archive.Error.ReorganizeNewer", result.Newer.Count));
|
||||
if (result.FilesBusy.Count > 0) throw new InvalidOperationException(Loc.Plural("Archive.Error.ReorganizeBusy", result.FilesBusy.Count));
|
||||
}
|
||||
|
||||
@@ -114,7 +117,7 @@ internal sealed class MoveJobHandler(ChronosDatabase db, MassRenamer renamer, Fu
|
||||
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);
|
||||
await MassRenamer.TellAsync(sequenceChanged, 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>
|
||||
@@ -139,33 +142,16 @@ internal sealed class MoveJobHandler(ChronosDatabase db, MassRenamer renamer, Fu
|
||||
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.Newer) context.Log(Loc.L("Archive.Log.ReorganizeNewerKept", 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)
|
||||
{
|
||||
if (!string.Equals(plan.Fingerprint(), parameters.Fingerprint, StringComparison.Ordinal)) return false;
|
||||
var versions = parameters.Sequences.ToDictionary(s => s.Id, s => s.FramesVersion);
|
||||
return plan.Steps.Where(s => s.FileChanges > 0).All(s => versions.TryGetValue(s.SequenceId, out var version) && version == s.FramesVersion);
|
||||
}
|
||||
|
||||
/// <summary>Tells each sequence changed; a failure is logged, never passed on to the job.</summary>
|
||||
private async Task TellAsync(IReadOnlyList<Guid> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Whether the plan made now is the one confirmed: the same fingerprint, which pins every file rename by its digest
|
||||
/// (photos a sequence received since under the names the plan leaves them change nothing of it).
|
||||
/// </summary>
|
||||
private static bool IsConfirmed(RenamePlan plan, MoveJobParameters parameters) =>
|
||||
string.Equals(plan.Fingerprint(), parameters.Fingerprint, StringComparison.Ordinal);
|
||||
|
||||
private static int Steps(RenamePlan plan) => plan.Steps.Count(s => s.Changes);
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Runtime.ExceptionServices;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
@@ -8,9 +9,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, 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.
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class StaleRenamePlanException(Guid sequenceId)
|
||||
: InvalidOperationException(Loc.L("Archive.Error.StalePlan"))
|
||||
@@ -22,18 +23,21 @@ public sealed class StaleRenamePlanException(Guid 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 (<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).
|
||||
/// (<see cref="FilesKept"/>, a sequence still receiving photos among them; their folder and title changed), whose title and
|
||||
/// file names stayed because their title was edited since (<see cref="TitlesKept"/>, only when resuming; their folder
|
||||
/// moved), whose files kept their names because a photo was in use or a new name was taken (<see cref="FilesBusy"/>; their
|
||||
/// folder and title changed), and whose title and file names stayed because a newer Chronos wrote their sidecar since
|
||||
/// (<see cref="Newer"/>, only when resuming; their folder moved, or, planned a new title, they stayed as they were when it
|
||||
/// had not moved yet).
|
||||
/// </summary>
|
||||
public sealed record RenameResult(IReadOnlyList<Guid> Changed, int Files, IReadOnlyList<Guid> Dropped, IReadOnlyList<Guid> FilesKept,
|
||||
IReadOnlyList<Guid> TitlesKept, IReadOnlyList<Guid> FilesBusy)
|
||||
IReadOnlyList<Guid> TitlesKept, IReadOnlyList<Guid> FilesBusy, IReadOnlyList<Guid> Newer)
|
||||
{
|
||||
/// <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);
|
||||
return new(tally.Changed, tally.Files, tally.Dropped, tally.FilesKept, tally.TitlesKept, tally.FilesBusy, tally.Newer);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,6 +51,9 @@ public sealed record RenameResult(IReadOnlyList<Guid> Changed, int Files, IReadO
|
||||
/// </summary>
|
||||
public sealed class MassRenamer
|
||||
{
|
||||
/// <summary>The change a Reorganize tells about a sequence it changed (a server's <c>sequenceChanged</c> event).</summary>
|
||||
public const string Change = "reorganized";
|
||||
|
||||
private readonly ChronosDatabase _db;
|
||||
private readonly SequenceWriter _writer;
|
||||
private readonly ArchiveIndexer _indexer;
|
||||
@@ -64,11 +71,14 @@ public sealed class MassRenamer
|
||||
/// <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>
|
||||
/// <summary>Its photos changed since the plan (photos added, gone, hashed or copied in): 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>
|
||||
/// <summary>Its title was edited since the plan: its title and file names stay.</summary>
|
||||
Title,
|
||||
|
||||
/// <summary>Its sidecar is of a newer format, which is never rewritten (only when resuming): its title and file names stay.</summary>
|
||||
Newer,
|
||||
}
|
||||
|
||||
/// <param name="folderTemplate">New folder template (<c>{title}</c> = the new title), or null to keep folders.</param>
|
||||
@@ -144,16 +154,24 @@ public sealed class MassRenamer
|
||||
return Subject(sequence) with { Unreadable = true };
|
||||
}
|
||||
|
||||
/// <summary>Applies a plan; each completed step is journaled before the next starts.</summary>
|
||||
/// <summary>
|
||||
/// 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 (<see cref="RenameResult.FilesKept"/>), its
|
||||
/// folder and title change as planned, and the steps after it go on.
|
||||
/// </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, 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>
|
||||
/// 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.</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
|
||||
/// 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, <see cref="InvalidDataException"/>
|
||||
/// or <see cref="NewerFormatException"/>) 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
|
||||
/// (<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, _) =>
|
||||
@@ -202,9 +220,10 @@ public sealed class MassRenamer
|
||||
}
|
||||
|
||||
/// <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.
|
||||
/// 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
|
||||
/// (<see cref="ArchiveServiceOptions.SequenceChanged"/>, <see cref="Change"/>). 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)
|
||||
{
|
||||
@@ -212,10 +231,34 @@ public sealed class MassRenamer
|
||||
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);
|
||||
foreach (var journal in pending)
|
||||
{
|
||||
await RunAsync(archive, journal, resuming: true, null, (_, changed) => TellAsync(_writer.Options.SequenceChanged, changed), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
return pending.Count;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tells <paramref name="sequenceChanged"/> (null: no one) each sequence of <paramref name="changed"/> a Reorganize
|
||||
/// changed (<see cref="Change"/>); a failure is logged, never passed on.
|
||||
/// </summary>
|
||||
internal static async ValueTask TellAsync(Func<Guid, string, CancellationToken, Task>? sequenceChanged, IReadOnlyList<Guid> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <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;
|
||||
@@ -296,26 +339,26 @@ public sealed class MassRenamer
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// 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 (<see cref="TargetTaken"/>), 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 (<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)
|
||||
{
|
||||
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))
|
||||
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 = template is not null && step.FileChanges > 0;
|
||||
if (!step.Retitles && !files) continue;
|
||||
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)
|
||||
@@ -323,9 +366,9 @@ public sealed class MassRenamer
|
||||
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);
|
||||
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)
|
||||
@@ -366,9 +409,10 @@ public sealed class MassRenamer
|
||||
/// 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: <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.
|
||||
/// settled: <see cref="FitAsync"/>; 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.
|
||||
/// </summary>
|
||||
/// <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
|
||||
@@ -411,23 +455,41 @@ public sealed class MassRenamer
|
||||
}
|
||||
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))
|
||||
// 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))
|
||||
{
|
||||
result.Dropped.Add(step.SequenceId);
|
||||
(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.
|
||||
foreach (var (s, fit) in fits) await RecordAsync(archive, paths, s, s.Retitles && fit != Fit.Title, CancellationToken.None).ConfigureAwait(false);
|
||||
// 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);
|
||||
if (s.MovesFolder || (s.Retitles && fit != Fit.Title) || renamed) result.Changed.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
|
||||
@@ -457,11 +519,13 @@ public sealed class MassRenamer
|
||||
/// <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.
|
||||
/// a title edited since the plan is never written over nor are names given from the old one (<see cref="TitleStands"/>),
|
||||
/// and the files are renamed only as the plan renames them (<see cref="FilesStand"/>). 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.
|
||||
/// </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>
|
||||
/// <exception cref="StaleRenamePlanException">Not resuming, and its title was edited since the plan.</exception>
|
||||
private async Task<Fit> FitAsync(ArchivePaths paths, string? fileTemplate, RenameStep step, SequenceManifest manifest, bool resuming,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -471,9 +535,9 @@ public sealed class MassRenamer
|
||||
{
|
||||
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;
|
||||
return Fit.Newer;
|
||||
}
|
||||
if (step.Retitles && await _db.Sequences.GetAsync(step.SequenceId, cancellationToken).ConfigureAwait(false) is { } row && !TitleStands(step, row, manifest))
|
||||
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");
|
||||
@@ -481,13 +545,15 @@ public sealed class MassRenamer
|
||||
}
|
||||
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 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.</summary>
|
||||
private static bool TakesTitle(Fit fit) => fit is Fit.Whole or Fit.Files;
|
||||
|
||||
/// <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
|
||||
@@ -501,9 +567,9 @@ public sealed class MassRenamer
|
||||
|
||||
/// <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.
|
||||
/// files beside its frames, they rename exactly the files the plan renamed (<see cref="Matches"/>), 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.
|
||||
/// </summary>
|
||||
private static bool FilesStand(SequencePaths sequence, PathTemplate template, RenameStep step, SequenceManifest manifest)
|
||||
{
|
||||
@@ -511,8 +577,13 @@ public sealed class MassRenamer
|
||||
return plan.Moves.Count == 0 || Matches(step, plan, manifest);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether file renames planned again are exactly the plan's: every move the same (<see cref="RenameStep.FileDigest"/>),
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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));
|
||||
step.FileDigest is { } digest ? string.Equals(digest, plan.Digest(), StringComparison.Ordinal) : manifest.Versions.Frames == step.FramesVersion;
|
||||
|
||||
/// <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>
|
||||
@@ -584,48 +655,62 @@ 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, or keeps its title, has nothing to record here.
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <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 && !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);
|
||||
if (retitle && manifest.Title != step.ToTitle)
|
||||
bool inStep;
|
||||
try
|
||||
{
|
||||
manifest = manifest with
|
||||
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)
|
||||
{
|
||||
Title = step.ToTitle,
|
||||
Versions = manifest.Versions with { Settings = manifest.Versions.Settings + 1 },
|
||||
UpdatedAt = DateTimeOffset.UtcNow,
|
||||
};
|
||||
ManifestStore.WriteSequence(sequence.ManifestPath, manifest);
|
||||
}
|
||||
await using (var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await tx.Sequences.RelocateAsync(step.SequenceId, step.ToFolder, retitle ? step.ToTitle : null, cancellationToken).ConfigureAwait(false);
|
||||
if (step.MovesFolder)
|
||||
{
|
||||
await tx.Frames.RebaseFolderAsync(step.SequenceId, step.FromFolder, step.ToFolder, cancellationToken).ConfigureAwait(false);
|
||||
await tx.Renders.RebaseFolderAsync(step.SequenceId, step.FromFolder, step.ToFolder, cancellationToken).ConfigureAwait(false);
|
||||
ManifestStore.WriteSequence(sequence.ManifestPath, manifest with
|
||||
{
|
||||
Title = step.ToTitle,
|
||||
Versions = manifest.Versions with { Settings = manifest.Versions.Settings + 1 },
|
||||
UpdatedAt = DateTimeOffset.UtcNow,
|
||||
});
|
||||
}
|
||||
await tx.Archives.DeleteFolderStateAsync(archive.Id, step.FromFolder, cancellationToken).ConfigureAwait(false);
|
||||
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>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.</summary>
|
||||
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 tx.Renders.RebaseFolderAsync(step.SequenceId, step.FromFolder, step.ToFolder, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
await tx.Archives.DeleteFolderStateAsync(archive.Id, step.FromFolder, cancellationToken).ConfigureAwait(false);
|
||||
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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),
|
||||
/// 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 (<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
|
||||
@@ -662,8 +747,8 @@ public sealed class MassRenamer
|
||||
}
|
||||
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);
|
||||
// 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;
|
||||
}
|
||||
@@ -716,6 +801,7 @@ public sealed class MassRenamer
|
||||
public List<Guid> FilesKept { get; } = [.. done.FilesKept];
|
||||
public List<Guid> TitlesKept { get; } = [.. done.TitlesKept];
|
||||
public List<Guid> FilesBusy { get; } = [.. done.FilesBusy];
|
||||
public List<Guid> Newer { get; } = [.. done.Newer];
|
||||
public int Files { get; set; } = done.Files;
|
||||
|
||||
public RenameTally Record() => new()
|
||||
@@ -726,6 +812,7 @@ public sealed class MassRenamer
|
||||
FilesKept = [.. FilesKept],
|
||||
TitlesKept = [.. TitlesKept],
|
||||
FilesBusy = [.. FilesBusy],
|
||||
Newer = [.. Newer],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -53,8 +53,10 @@ public sealed record ArchiveServiceOptions
|
||||
public string? BackupDirectory { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Told after a job changed a sequence's folder, title or file names (change <c>reorganized</c>, a Reorganize): a server
|
||||
/// tells its connected clients (BRIEF §14.3). A failure is logged and never fails the job.
|
||||
/// Told after a Reorganize changed a sequence's folder, title or file names (change <c>reorganized</c>), once its step is
|
||||
/// journaled: by its job, or by an archive open that completed a plan an interruption left (<see cref="ArchiveService.OpenAsync"/>).
|
||||
/// A server tells its connected clients (BRIEF §14.3); the service it opens its archive with at start sets none, as no
|
||||
/// client is connected yet. A failure is logged and never fails the job.
|
||||
/// </summary>
|
||||
public Func<Guid, string, CancellationToken, Task>? SequenceChanged { get; init; }
|
||||
|
||||
|
||||
Reference in new issue
Block a user