feat: owner review 2 phase 4b: mass conversion after import #13

Merged
Alby96 merged 82 commits from claude/owner-review-2-p4b-rc7 into main 2026-11-03 10:41:59 +01:00
9 changed files with 455 additions and 77 deletions
Showing only changes of commit 8127373fd5 - Show all commits

No files matched your search

+1
View File
@@ -158,6 +158,7 @@
<data name="Archive.Log.Orphans" xml:space="preserve"><value>Unindexed photos: {0}, missing photos: {1}</value><comment>long: job log line</comment></data>
<data name="Archive.Log.ProxiesDone" xml:space="preserve"><value>{0}: made {1}, reused {2}, unreadable {3}, waiting {4}</value><comment>long: job log line; {4} frames whose proxy this host waits for from a client or render node</comment></data>
<data name="Archive.Log.ProxiesSent" xml:space="preserve"><value>Proxies for the server: {0} sent, {1} not sent</value><comment>long: job log line; {0} proxies sent; {1} proxies this PC could not make or the server refused</comment></data>
<data name="Archive.Log.ReorganizeCarriedKept" xml:space="preserve"><value>Left as it was, the folder it is in stayed: {0}</value><comment>long: job log line; {0} sequence title or folder</comment></data>
<data name="Archive.Log.ReorganizeDropped" xml:space="preserve"><value>Left as it was, changed after the plan: {0}</value><comment>long: job log line; {0} sequence title or folder</comment></data>
<data name="Archive.Log.ReorganizeFilesBusy" xml:space="preserve"><value>File names kept, a photo was in use or its new name was taken: {0}</value><comment>long: job log line; {0} sequence title or folder</comment></data>
<data name="Archive.Log.ReorganizeFilesKept" xml:space="preserve"><value>File names kept, photos changed after the plan: {0}</value><comment>long: job log line; {0} sequence title or folder</comment></data>
+1
View File
@@ -153,6 +153,7 @@
<data name="Archive.Log.Orphans" xml:space="preserve"><value>Foto non indicizzate: {0}, foto mancanti: {1}</value></data>
<data name="Archive.Log.ProxiesDone" xml:space="preserve"><value>{0}: create {1}, riusate {2}, illeggibili {3}, in attesa {4}</value></data>
<data name="Archive.Log.ProxiesSent" xml:space="preserve"><value>Proxy per il server: {0} inviati, {1} non inviati</value></data>
<data name="Archive.Log.ReorganizeCarriedKept" xml:space="preserve"><value>Lasciata com'era, la cartella che la contiene è rimasta: {0}</value></data>
<data name="Archive.Log.ReorganizeDropped" xml:space="preserve"><value>Lasciata com'era, cambiata dopo il piano: {0}</value></data>
<data name="Archive.Log.ReorganizeFilesBusy" xml:space="preserve"><value>Nomi dei file mantenuti, una foto era in uso o il suo nuovo nome era occupato: {0}</value></data>
<data name="Archive.Log.ReorganizeFilesKept" xml:space="preserve"><value>Nomi dei file mantenuti, foto cambiate dopo il piano: {0}</value></data>
+78 -22
View File
@@ -144,6 +144,15 @@ public sealed record RenamePlan(Guid Id, Guid ArchiveId, IReadOnlyList<RenameSte
/// <summary>The file template the steps' file names come from; null when files keep their names.</summary>
public string? FileTemplate { get; init; }
/// <summary>
/// The folder template the steps' folders come from; null when folders stay, or in a plan journaled before it was kept
/// (whose steps' folders are then taken as planned).
/// </summary>
public string? FolderTemplate { get; init; }
/// <summary>The title template the steps' titles come from; null when titles stay, or in a plan journaled before it was kept.</summary>
public string? TitleTemplate { get; init; }
/// <summary>The sequences the plan was made for, in the order they were given (the order that decides which new folder gets " (2)").</summary>
public IReadOnlyList<Guid> Subjects { get; init; } = [];
@@ -173,7 +182,9 @@ public sealed record RenamePlan(Guid Id, Guid ArchiveId, IReadOnlyList<RenameSte
/// sequences changed, the frames whose file got a new name, and the sequences not changed as planned: because they changed
/// since, left as they were (<see cref="Dropped"/>), their file names kept (<see cref="FilesKept"/>) or their title and file
/// names kept (<see cref="TitlesKept"/>); their file names kept because a photo was in use or a new name was taken
/// (<see cref="FilesBusy"/>); their title and file names kept because a newer Chronos wrote their sidecar (<see cref="Newer"/>).
/// (<see cref="FilesBusy"/>); their title and file names kept because a newer Chronos wrote their sidecar (<see cref="Newer"/>);
/// left as they were because the folder around them that was to carry them stayed, for its own reason
/// (<see cref="CarriedKept"/>).
/// </summary>
public sealed record RenameTally
{
@@ -184,6 +195,7 @@ public sealed record RenameTally
public IReadOnlyList<Guid> TitlesKept { get; init; } = [];
public IReadOnlyList<Guid> FilesBusy { get; init; } = [];
public IReadOnlyList<Guid> Newer { get; init; } = [];
public IReadOnlyList<Guid> CarriedKept { get; init; } = [];
}
/// <summary>A plan being applied, with the steps already completed; lets an interrupted rename resume (BRIEF §7).</summary>
@@ -275,10 +287,10 @@ public static class RenamePlanner
continue;
}
var context = Context(s);
var newTitle = title is null || context is null ? s.Title : Blank(title.ExpandText(context)) ?? s.Title;
var newTitle = NewTitle(context, s.Title, title);
var newFolder = s.Folder;
// The archive root itself (a folder adopted in place) cannot move; only its title changes.
if (folder is not null && context is not null && s.Folder.Length > 0 && Blank(folder.ExpandFolder(context with { Title = newTitle })) is { } expanded
if (folder is not null && context is not null && s.Folder.Length > 0 && NewFolder(context, newTitle, folder) is { } expanded
&& !expanded.Equals(s.Folder, StringComparison.Ordinal))
{
var inside = stuck.Where(u => IsInside(s.Folder, u.Folder)).Select(u => u.SequenceId).ToList();
@@ -323,9 +335,53 @@ public static class RenamePlanner
steps.Add((step, 0));
}
// Stable: subjects keep their order, sequences inside moving folders move out first, carried ones come last.
return new RenamePlan(Guid.CreateVersion7(), archiveId, [.. steps.OrderBy(s => s.Order).Select(s => s.Step)]) { FileTemplate = fileTemplate, Subjects = [.. subjects.Select(s => s.SequenceId)] };
return new RenamePlan(Guid.CreateVersion7(), archiveId, [.. steps.OrderBy(s => s.Order).Select(s => s.Step)])
{
FileTemplate = fileTemplate,
FolderTemplate = folderTemplate,
TitleTemplate = titleTemplate,
Subjects = [.. subjects.Select(s => s.SequenceId)],
};
}
/// <summary>
/// The title and the folder the templates give a sequence from its sidecar (<paramref name="manifest"/>) as
/// <see cref="Plan"/> gives them, where <c>{title}</c> of the title template is <paramref name="title"/>: the title is
/// <paramref name="title"/> without a title template or when it expands to nothing; the folder is the expansion itself,
/// before any <c>" (2)"</c> (<see cref="Gives"/>), null without a folder template or when it expands to nothing.
/// </summary>
public static (string? Title, string? Folder) Names(SequenceManifest manifest, string? title, string? folderTemplate, string? titleTemplate)
{
ArgumentNullException.ThrowIfNull(manifest);
var context = Context(manifest, title);
var newTitle = NewTitle(context, title, titleTemplate is null ? null : PathTemplate.Parse(titleTemplate));
return (newTitle, folderTemplate is null ? null : NewFolder(context, newTitle, PathTemplate.Parse(folderTemplate)));
}
/// <summary>
/// Whether <paramref name="folder"/> is a folder a plan gives for the expansion <paramref name="expanded"/>
/// (<see cref="Names"/>): that one, or the <c>" (n)"</c> of it that a folder of that name already there made it take.
/// </summary>
public static bool Gives(string expanded, string folder)
{
ArgumentNullException.ThrowIfNull(expanded);
ArgumentNullException.ThrowIfNull(folder);
return folder.Equals(expanded, StringComparison.Ordinal) || (Numbered(folder, expanded, StringComparison.Ordinal) is { } n && n >= 2
&& folder.Equals(string.Create(CultureInfo.InvariantCulture, $"{expanded} ({n})"), StringComparison.Ordinal));
}
/// <summary>The <c>n</c> of <paramref name="folder"/> when it is <paramref name="expanded"/> followed by <c>" (n)"</c>; null otherwise.</summary>
private static int? Numbered(string folder, string expanded, StringComparison comparison) =>
folder.Length > expanded.Length + 3 && folder.StartsWith(expanded + " (", comparison) && folder[^1] == ')'
&& int.TryParse(folder.AsSpan(expanded.Length + 2, folder.Length - expanded.Length - 3), NumberStyles.None, CultureInfo.InvariantCulture, out var n)
? n
: null;
private static string? NewTitle(NamingContext? context, string? title, PathTemplate? template) =>
template is null || context is null ? title : Blank(template.ExpandText(context)) ?? title;
private static string? NewFolder(NamingContext context, string? newTitle, PathTemplate template) => Blank(template.ExpandFolder(context with { Title = newTitle }));
/// <summary>
/// What the folder and title templates of a subject see: its first frame in its sidecar, as an upload filed it and as
/// Reorganize names its files (a sidecar without frames: when the sequence was made); without the sidecar, the index
@@ -334,20 +390,7 @@ public static class RenamePlanner
/// </summary>
private static NamingContext? Context(RenameSubject s)
{
if (s.Files?.Manifest is { } manifest)
{
if (manifest.Frames.Count > 0) return FrameNaming.Context(manifest.Frames[0], manifest, s.Title);
var start = FrameNaming.SessionStart(manifest);
return new NamingContext
{
CapturedAt = start,
SessionStart = start,
CameraMake = manifest.Camera?.Make,
CameraModel = manifest.Camera?.Model,
Lens = manifest.Lens,
Title = s.Title,
};
}
if (s.Files?.Manifest is { } manifest) return Context(manifest, s.Title);
if (s.FirstCapture is not { } first) return null;
return new NamingContext
{
@@ -360,6 +403,22 @@ public static class RenamePlanner
};
}
/// <summary>What the folder and title templates see in a sidecar: its first frame (<see cref="Context(RenameSubject)"/>).</summary>
private static NamingContext Context(SequenceManifest manifest, string? title)
{
if (manifest.Frames.Count > 0) return FrameNaming.Context(manifest.Frames[0], manifest, title);
var start = FrameNaming.SessionStart(manifest);
return new NamingContext
{
CapturedAt = start,
SessionStart = start,
CameraMake = manifest.Camera?.Make,
CameraModel = manifest.Camera?.Model,
Lens = manifest.Lens,
Title = title,
};
}
/// <summary>The step with the file renames of its sequence (<see cref="FileRenames.Plan"/>).</summary>
private static RenameStep WithFiles(RenameStep step, SequenceFiles files, PathTemplate template, string? title)
{
@@ -455,10 +514,7 @@ public static class RenamePlanner
{
string? same = null;
if (current.Equals(expanded, StringComparison.OrdinalIgnoreCase)) same = expanded;
else if (current.Length > expanded.Length + 3 && current.StartsWith(expanded + " (", StringComparison.OrdinalIgnoreCase) && current[^1] == ')'
&& int.TryParse(current.AsSpan(expanded.Length + 2, current.Length - expanded.Length - 3), NumberStyles.None, CultureInfo.InvariantCulture,
out var n) && n >= 2)
same = string.Create(CultureInfo.InvariantCulture, $"{expanded} ({n})");
else if (Numbered(current, expanded, StringComparison.OrdinalIgnoreCase) is { } n && n >= 2) same = string.Create(CultureInfo.InvariantCulture, $"{expanded} ({n})");
// "(02)" is not a number Unique gives: that folder moves to a name of its own.
if (same is null || !same.Equals(current, StringComparison.OrdinalIgnoreCase) || given.Contains(same)) return null;
if (same.Equals(current, StringComparison.Ordinal)) return same;
@@ -13,16 +13,19 @@ namespace Chronos.Data.Archiving.Jobs;
/// 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:&lt;id&gt;</c> once
/// the plan's journal is written. Paused, cancelled or failed, the job stops between two sequences and holds the plan
/// the plan's journal is written, <c>applied</c> when the job fails once the plan is over (given up, or completed with
/// sequences kept). 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.
/// meanwhile (at an archive open). A job retried once its plan is over plans again, and applies only a plan that is still
/// the one confirmed. 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, and
/// its folder and title too when the templates now give it others), a newer Chronos wrote their sidecar, a photo was in
/// use or its new name taken, or the folder around them stayed, 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; those of a
/// step that failed half-way (its folder moved, then a sidecar could not be read) are told at once. 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
{
@@ -31,6 +34,9 @@ internal sealed class MoveJobHandler(ChronosDatabase db, MassRenamer renamer, Fu
private const string Prefix = "plan:";
/// <summary>The checkpoint of a failed job whose plan is over (completed or given up): a retry plans again.</summary>
private const string Applied = "applied";
public JobKind Kind => JobKind.Move;
public async Task RunAsync(JobContext context)
@@ -78,15 +84,21 @@ internal sealed class MoveJobHandler(ChronosDatabase db, MassRenamer renamer, Fu
}
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);
// 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. A plan given up has no rest: a retry plans again.
if (!HoldFailed(context, archive, id)) await context.CheckpointAsync(Applied, context.Done, context.Total).ConfigureAwait(false);
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.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));
var error = kept > 0 ? Loc.Plural("Archive.Error.ReorganizeKept", kept)
: result.Newer.Count > 0 ? Loc.Plural("Archive.Error.ReorganizeNewer", result.Newer.Count)
: result.FilesBusy.Count > 0 ? Loc.Plural("Archive.Error.ReorganizeBusy", result.FilesBusy.Count)
: null;
if (error is null) return;
// The plan is over: a retry plans again instead of taking it for one an archive open completed.
await context.CheckpointAsync(Applied, context.Total, context.Total).ConfigureAwait(false);
throw new InvalidOperationException(error);
}
/// <summary>Completes a plan this job started; null when its journal went meanwhile (completed at an archive open).</summary>
@@ -120,12 +132,16 @@ internal sealed class MoveJobHandler(ChronosDatabase db, MassRenamer renamer, Fu
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>
private static void HoldFailed(JobContext context, Archive archive, Guid planId)
/// <summary>
/// Holds the plan of a failed run and logs what its completed steps did; a hold that cannot be written is logged. False
/// when the plan has no journal any more (given up as no longer matching the archive).
/// </summary>
private static bool HoldFailed(JobContext context, Archive archive, Guid planId)
{
try
{
if (!MassRenamer.Hold(archive, planId) || RenameJournal.Read(new ArchivePaths(archive.RootPath), planId) is not { } journal) return;
if (!MassRenamer.Hold(archive, planId)) return false;
if (RenameJournal.Read(new ArchivePaths(archive.RootPath), planId) is not { } journal) return true;
Log.Info("archive", $"Reorganize {planId} held by its failed job {context.Job.Id}");
LogDone(context, journal.Plan, RenameResult.Of(journal.Done));
}
@@ -133,6 +149,7 @@ internal sealed class MoveJobHandler(ChronosDatabase db, MassRenamer renamer, Fu
{
Log.Warning("archive", $"Reorganize {planId} could not be held after its job failed", ex);
}
return true;
}
/// <summary>The job log of what the plan did: the counts, then each sequence not changed as planned, and why.</summary>
@@ -143,6 +160,7 @@ internal sealed class MoveJobHandler(ChronosDatabase db, MassRenamer renamer, Fu
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.CarriedKept) context.Log(Loc.L("Archive.Log.ReorganizeCarriedKept", Name(plan, id)));
foreach (var id in result.FilesBusy) context.Log(Loc.L("Archive.Log.ReorganizeFilesBusy", Name(plan, id)));
}
+80 -35
View File
@@ -22,22 +22,24 @@ public sealed class StaleRenamePlanException(Guid sequenceId)
/// <summary>
/// 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"/>, 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).
/// plan (<see cref="Dropped"/>: when resuming, or when photos changed since so that the templates now give them another
/// folder or title), whose files kept their names because their photos changed since (<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, or their photos changed so that the templates now give them another one (<see cref="TitlesKept"/>;
/// their folder moved, with the folder around them or before an interruption), 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), 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), and that stayed as they were
/// because the folder around them that was to carry them stayed, for a reason of its own (<see cref="CarriedKept"/>).
/// </summary>
public sealed record RenameResult(IReadOnlyList<Guid> Changed, int Files, IReadOnlyList<Guid> Dropped, IReadOnlyList<Guid> FilesKept,
IReadOnlyList<Guid> TitlesKept, IReadOnlyList<Guid> FilesBusy, IReadOnlyList<Guid> Newer)
IReadOnlyList<Guid> TitlesKept, IReadOnlyList<Guid> FilesBusy, IReadOnlyList<Guid> Newer, IReadOnlyList<Guid> CarriedKept)
{
/// <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, tally.Newer);
return new(tally.Changed, tally.Files, tally.Dropped, tally.FilesKept, tally.TitlesKept, tally.FilesBusy, tally.Newer, tally.CarriedKept);
}
}
@@ -77,6 +79,12 @@ public sealed class MassRenamer
/// <summary>Its title was edited since the plan: its title and file names stay.</summary>
Title,
/// <summary>
/// Its photos changed since the plan so that the templates now give it another folder or title (a photo filed before
/// the first, or the first one gone): its folder (unless it moved already), title and file names stay.
/// </summary>
Names,
/// <summary>Its sidecar is of a newer format, which is never rewritten (only when resuming): its title and file names stay.</summary>
Newer,
}
@@ -157,7 +165,8 @@ public sealed class MassRenamer
/// <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.
/// folder and title change as planned while the templates still give them from its first photo as it is now (otherwise
/// it stays as it was: <see cref="RenameResult.Dropped"/>), 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, or a title it changes, or
@@ -167,9 +176,10 @@ public sealed class MassRenamer
/// 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. 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
/// the folder of a step moved, a sidecar of the step that cannot be read or written (this, <see cref="UnauthorizedAccessException"/>,
/// <see cref="InvalidDataException"/> or <see cref="NewerFormatException"/>) fails the step only after every index row of
/// the step followed the folder and each of its sequences was told (<see cref="ArchiveServiceOptions.SequenceChanged"/>);
/// 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>
@@ -192,8 +202,9 @@ public sealed class MassRenamer
/// <summary>
/// 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).
/// does), or one its job held, whose remaining steps are checked as a plan applied anew (what refuses a plan refuses the
/// rest, and that journal goes; photos changed since do not). Null when there is no journal: the plan completed or was
/// given up (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>
@@ -327,7 +338,7 @@ public sealed class MassRenamer
? [.. 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);
await ApplyStepAsync(archive, paths, journal.Plan, step, carried, resuming, result, cancellationToken).ConfigureAwait(false);
completed.Add(step.SequenceId);
foreach (var c in carried) completed.Add(c.SequenceId);
journal = journal with { Completed = [.. completed], Done = result.Record() };
@@ -409,15 +420,17 @@ 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"/>; 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.
/// settled: <see cref="FitAsync"/>; a sequence whose photos changed since keeps its file names, and its folder and title
/// too when the templates now give it others). A folder that stays keeps the sequences it was to carry
/// (<see cref="RenameResult.CarriedKept"/>). 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 every sequence of the step was told), 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
/// next scan indexes it wherever it ended up.</param>
private async Task ApplyStepAsync(Archive archive, ArchivePaths paths, string? fileTemplate, RenameStep step, IReadOnlyList<RenameStep> carried,
private async Task ApplyStepAsync(Archive archive, ArchivePaths paths, RenamePlan plan, RenameStep step, IReadOnlyList<RenameStep> carried,
bool resuming, Tally result, CancellationToken cancellationToken)
{
var ids = carried.Select(c => c.SequenceId).Append(step.SequenceId).Order().ToList();
@@ -434,10 +447,11 @@ public sealed class MassRenamer
_writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false));
}
}
// Checked before anything moves; a dropped step drops the sequences it would have carried, which stay inside it.
// Checked before anything moves; a dropped step keeps the sequences it would have carried, which stay inside it.
if (!await StandsAsync(step, resuming, cancellationToken).ConfigureAwait(false))
{
result.Dropped.Add(step.SequenceId);
result.CarriedKept.AddRange(carried.Select(c => c.SequenceId));
return;
}
var follow = new List<RenameStep>(carried.Count);
@@ -450,24 +464,24 @@ public sealed class MassRenamer
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));
result.CarriedKept.AddRange(follow.Select(c => c.SequenceId));
return;
}
var fits = new List<(RenameStep Step, Fit Fit)>(follow.Count + 1);
foreach (var s in follow.Prepend(step)) fits.Add((s, await FitAsync(paths, fileTemplate, s, Settle(paths, s), resuming, cancellationToken).ConfigureAwait(false)));
// Its title no longer fits (edited since, or planned anew in a sidecar of a newer format) while nothing of it moved:
// it stays as it was, with the sequences it would carry.
foreach (var s in follow.Prepend(step)) fits.Add((s, await FitAsync(paths, plan, s, Settle(paths, s), resuming, cancellationToken).ConfigureAwait(false)));
// Its folder or title no longer fits (its title edited since, the templates naming it otherwise now, or a new title
// planned 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))
if ((first is Fit.Title or Fit.Names || (first == Fit.Newer && step.Retitles)) && !Moved(paths, step))
{
(first == Fit.Newer ? result.Newer : result.Dropped).Add(step.SequenceId);
result.Dropped.AddRange(follow.Select(c => c.SequenceId));
result.CarriedKept.AddRange(follow.Select(c => c.SequenceId));
return;
}
RenamePlanner.MoveFolder(paths, step);
// Every index row follows the folder before any file is renamed, so nothing below can leave one behind it: a
// sequence whose sidecar cannot be read or written now has its row follow all the same, and fails the step once
// every other row did.
// every other row did and every sequence of the step was told (the retry that would complete it may never come).
ExceptionDispatchInfo? unrecorded = null;
foreach (var (s, fit) in fits)
{
@@ -481,12 +495,17 @@ public sealed class MassRenamer
unrecorded ??= ExceptionDispatchInfo.Capture(ex);
}
}
unrecorded?.Throw();
if (unrecorded is not null)
{
await TellAsync(_writer.Options.SequenceChanged, [.. fits.Select(f => f.Step.SequenceId)]).ConfigureAwait(false);
unrecorded.Throw();
}
var fileTemplate = plan.FileTemplate;
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);
if (fit is Fit.Title or Fit.Names) result.TitlesKept.Add(s.SequenceId);
else if (fit == Fit.Files) result.FilesKept.Add(s.SequenceId);
else if (fit == Fit.Newer) result.Newer.Add(s.SequenceId);
if (s.MovesFolder || (s.Retitles && TakesTitle(fit)) || renamed) result.Changed.Add(s.SequenceId);
@@ -520,16 +539,19 @@ public sealed class MassRenamer
/// 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 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.
/// a folder or title is given only while the templates still give it from the first photo as it is now
/// (<see cref="NamesStand"/>), 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 so do its folder and title when the templates now give it others,
/// 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 was edited since the plan.</exception>
private async Task<Fit> FitAsync(ArchivePaths paths, string? fileTemplate, RenameStep step, SequenceManifest manifest, bool resuming,
private async Task<Fit> FitAsync(ArchivePaths paths, RenamePlan plan, RenameStep step, SequenceManifest manifest, bool resuming,
CancellationToken cancellationToken)
{
var sequence = Where(paths, step);
var fileTemplate = plan.FileTemplate;
var files = fileTemplate is not null && step.FileChanges > 0;
if ((step.Retitles || files) && manifest.SchemaVersion > SequenceManifest.CurrentSchemaVersion)
{
@@ -543,6 +565,12 @@ public sealed class MassRenamer
Log.Warning("archive", $"{sequence.RelativeFolder} keeps its title and file names: its title was edited after the plan was made");
return Fit.Title;
}
if (!NamesStand(plan, step, manifest))
{
Log.Warning("archive", $"{sequence.RelativeFolder} keeps its folder, title and file names: its photos changed after the plan was made, "
+ "and the templates now name it otherwise");
return Fit.Names;
}
if (files && !FilesStand(sequence, PathTemplate.Parse(fileTemplate!), step, manifest))
{
Log.Warning("archive", $"The files of {sequence.RelativeFolder} keep their names: its photos changed after the plan was made");
@@ -565,6 +593,21 @@ public sealed class MassRenamer
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 plan's templates still give a step's sequence the folder and the title the step gives it, from its first
/// frame as <paramref name="manifest"/> has it now (<see cref="RenamePlanner.Names"/>, with the title the plan was made
/// from): a photo filed before the first since the plan, or the first one gone, would have them named after a photo
/// that is no longer first. Only what the step changes counts (a carried folder follows the folder around it); a plan
/// journaled before it kept its templates is taken as it was made.
/// </summary>
private static bool NamesStand(RenamePlan plan, RenameStep step, SequenceManifest manifest)
{
bool retitles = step.Retitles && plan.TitleTemplate is not null, moves = step.MovesFolder && !step.Carried && plan.FolderTemplate is not null;
if (!retitles && !moves) return true;
var (title, folder) = RenamePlanner.Names(manifest, step.FromTitle, plan.FolderTemplate, plan.TitleTemplate);
return (!retitles || string.Equals(title, step.ToTitle, StringComparison.Ordinal)) && (!moves || (folder is not null && RenamePlanner.Gives(folder, step.ToFolder)));
}
/// <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="Matches"/>), or none is left to
@@ -806,6 +849,7 @@ public sealed class MassRenamer
public List<Guid> TitlesKept { get; } = [.. done.TitlesKept];
public List<Guid> FilesBusy { get; } = [.. done.FilesBusy];
public List<Guid> Newer { get; } = [.. done.Newer];
public List<Guid> CarriedKept { get; } = [.. done.CarriedKept];
public int Files { get; set; } = done.Files;
public RenameTally Record() => new()
@@ -817,6 +861,7 @@ public sealed class MassRenamer
TitlesKept = [.. TitlesKept],
FilesBusy = [.. FilesBusy],
Newer = [.. Newer],
CarriedKept = [.. CarriedKept],
};
}
}
+2 -1
View File
@@ -54,7 +54,8 @@ public sealed record ArchiveServiceOptions
/// <summary>
/// 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"/>).
/// journaled, or once its folder moved and its index row followed when the step then failed: 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>
+3 -3
View File
@@ -141,9 +141,9 @@ public static class ArchiveEndpoints
/// <c>not_found</c> (<c>sequence</c>: not in the archive); 409 <c>nested_target</c> (details: the folder that would lie
/// inside a sequence's folder), <c>plan_changed</c> (details: the fingerprint now), <c>job_unavailable</c>; 503
/// <c>archive_offline</c>. Audited; the job tells each sequence it changes as <c>sequenceChanged</c> (<c>reorganized</c>)
/// once that sequence's step is journaled (a step that failed half-way, when its retry completes it; a plan the server
/// completes as it starts, no one: no client is connected yet). Photos a sequence receives between the dry run and the
/// confirmation under the names the plan leaves them keep the fingerprint as it was. A dry run's plan is made apart from
/// once that sequence's step is journaled (a step that failed half-way, once its folder moved and its index rows followed;
/// a plan the server completes as it starts, no one: no client is connected yet). Photos a sequence receives between the
/// dry run and the confirmation under the names the plan leaves them keep the fingerprint as it was. A dry run's plan is made apart from
/// the request, until the server stops, and kept a few minutes while what it reads from the index stays as it was
/// (<see cref="ReorganizePlanCache"/>): the same dry run again (also after the first was cut off), and its confirmation,
/// take it instead of planning again. So <c>plan_changed</c> answers a change the index has; one made on disk alone since
@@ -194,6 +194,37 @@ public sealed class ReorganizeTests(TestContext context)
Assert.True(Step("moved/{date}", "{n:000}") is { MovesFolder: true, FileChanges: 1, NamedByTitle: false, UsesTitle: false });
}
[Test]
public void APlanKeepsItsTemplatesSoTheNamesOfAFirstPhotoNoLongerFirstAreTold()
{
const string Folder = "moved/{date} {title}", Title = "{title} {time}";
var manifest = Sequence("originals/a.JPG", "originals/b.JPG");
// Another sequence holds the folder the template gives: this one takes its " (2)".
var plan = RenamePlanner.Plan(Guid.NewGuid(), [new RenameSubject(manifest.Id, "s", "Roof", Start, null, null, null)
{ Files = new SequenceFiles(manifest, [.. manifest.Frames.Select(f => f.File)]) }], Folder, Title, ["s", "moved/2026-09-28 Roof 18-00-00"], _ => false);
Assert.Equal((Folder, Title, (string?)null), (plan.FolderTemplate, plan.TitleTemplate, plan.FileTemplate));
var step = plan.Steps.Single();
Assert.Equal(("moved/2026-09-28 Roof 18-00-00 (2)", "Roof 18-00-00"), (step.ToFolder, step.ToTitle));
// From the sidecar as it was, the templates give what the plan gives; with its first photo gone, they name it otherwise.
var (title, folder) = RenamePlanner.Names(manifest, "Roof", Folder, Title);
Assert.Equal(("Roof 18-00-00", "moved/2026-09-28 Roof 18-00-00"), (title, folder));
Assert.True(RenamePlanner.Gives(folder!, step.ToFolder));
var (laterTitle, laterFolder) = RenamePlanner.Names(manifest with { Frames = [manifest.Frames[1]] }, "Roof", Folder, Title);
Assert.Equal(("Roof 18-00-10", "moved/2026-09-28 Roof 18-00-10"), (laterTitle, laterFolder));
Assert.False(RenamePlanner.Gives(laterFolder!, step.ToFolder));
// Without templates, the title stays and no folder is given.
Assert.Equal(("Roof", (string?)null), RenamePlanner.Names(manifest, "Roof", null, null));
// Only the folder itself or a number filing gives.
Assert.True(RenamePlanner.Gives("a/b", "a/b"));
Assert.True(RenamePlanner.Gives("a/b", "a/b (12)"));
Assert.False(RenamePlanner.Gives("a/b", "a/b (1)"));
Assert.False(RenamePlanner.Gives("a/b", "a/b (02)"));
Assert.False(RenamePlanner.Gives("a/b", "A/b"));
Assert.False(RenamePlanner.Gives("a/b", "a/b (2) x"));
}
[Test]
public void TemplatesAreCheckedAsTheArchiveSettingsAre()
{
@@ -932,4 +932,229 @@ public sealed class ReorganizeTests(TestContext context)
await FilesAsync(fx, parent);
Assert.Empty(RenameJournal.ListPending(fx.Paths));
}
[Test]
public async Task AMovedFolderWhoseSidecarCannotBeReadThereHasItsIndexRowFollowAndIsTold()
{
await using var fx = await CreateAsync(context);
var id = await UploadAsync(fx, 2);
var folder = fx.Paths.Sequence((await fx.Db.Sequences.GetAsync(id))!.Folder);
// The sidecar is a link, relative to where it lies, to a file outside the archive: one level deeper it leads nowhere.
// Unlike a read-only file, this holds whoever runs the test (root on the Linux runner).
var outside = Path.Combine(context.CreateTempDirectory("outside"), "sequence.json");
File.Move(folder.ManifestPath, outside);
try
{
File.CreateSymbolicLink(folder.ManifestPath, Path.GetRelativePath(folder.MetaDirectory, outside));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
File.Move(outside, folder.ManifestPath);
TestContext.Skip("needs symbolic links (Developer Mode on Windows)");
}
var deeper = string.Concat(Enumerable.Repeat("moved/", folder.RelativeFolder.Split('/').Length)) + "{date}";
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], new RenameTemplates(Folder: deeper, Title: "Roof"), fx.Ct);
var to = plan.Steps.Single().ToFolder;
var told = new ConcurrentQueue<(Guid, string)>();
var service = new ArchiveService(fx.Db, new ArchiveServiceOptions
{
Owner = "test",
SequenceChanged = (sequence, change, _) =>
{
told.Enqueue((sequence, change));
return Task.CompletedTask;
},
});
// The new title cannot be read where the folder moved: its index row followed it all the same, and clients hear of it.
await Assert.ThrowsAsync<IOException>(() => service.ApplyRenameAsync(plan, null, fx.Ct));
Assert.Equal(to, await FolderAsync(fx, id));
Assert.Null((await fx.Db.Sequences.GetAsync(id))!.Title);
Assert.SequenceEqual([(id, MassRenamer.Change)], told);
Assert.Empty(Assert.NotNull(RenameJournal.Read(fx.Paths, plan.Id)).Completed);
// Readable again, the retry completes the step.
var sidecar = fx.Paths.Sequence(to).ManifestPath;
File.Delete(sidecar);
File.Move(outside, sidecar);
var result = Assert.NotNull(await service.Renamer.ResumeAsync(fx.Archive, plan.Id, null, fx.Ct));
Assert.SequenceEqual([id], result.Changed);
Assert.Equal("Roof", (await fx.Db.Sequences.GetAsync(id))!.Title);
await FilesAsync(fx, id);
Assert.Empty(RenameJournal.ListPending(fx.Paths));
}
/// <summary>Moves the first photo of a sequence to the trash, as the editor's Delete does.</summary>
private static async Task TrashFirstPhotoAsync(ArchiveFixture fx, Guid id)
{
var sequence = Assert.NotNull(await fx.Db.Sequences.GetAsync(id));
var first = (await fx.Db.Frames.ListBySequenceAsync(id))[0];
var plan = await fx.Service.FrameTrash.PlanDeleteAsync(id, [first.Id], sequence.FramesVersion, fx.Ct);
Assert.True(plan.CanDelete, string.Join(", ", plan.Blocked));
await fx.Service.FrameTrash.DeleteAsync(plan, "editor", null, fx.Ct);
}
[Test]
public async Task AFolderOrTitleNamedAfterAPhotoNoLongerFirstIsNeverGiven()
{
await using var fx = await CreateAsync(context);
var trashed = await UploadAsync(fx, 3);
var earlier = await UploadAsync(fx, 2, firstSeed: 20, firstSecond: 3600, key: "upload-2");
var other = await UploadAsync(fx, 2, firstSeed: 40, firstSecond: 7200, key: "upload-3");
var templates = new RenameTemplates(Folder: "moved/{date} {time}", File: "{n:000}", Title: "{time}");
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [trashed, earlier, other], templates, fx.Ct);
Assert.SequenceEqual(["moved/2026-09-28 18-00-00", "moved/2026-09-28 19-00-00", "moved/2026-09-28 20-00-00"], plan.Steps.Select(s => s.ToFolder));
var from = new Dictionary<Guid, string>();
foreach (var id in new[] { trashed, earlier }) from[id] = await FolderAsync(fx, id);
var files = new Dictionary<Guid, List<string>>();
// Once the plan's own checks passed, the first photo of one goes to the trash and a photo taken before the first of
// another is filed into it: the templates now name each after another photo.
var result = await fx.Service.Renamer.ApplyAsync(fx.Archive, plan, async _ =>
{
await TrashFirstPhotoAsync(fx, trashed);
await UploadAsync(fx, 1, firstSeed: 30, firstSecond: 3595, key: "upload-2");
foreach (var id in from.Keys) files[id] = await FilesAsync(fx, id);
}, null, fx.Ct);
// Both stay as they were, their folder, title and file names; the other is reorganized.
Assert.SequenceEqual([trashed, earlier], result.Dropped);
Assert.SequenceEqual([other], result.Changed);
foreach (var id in from.Keys)
{
Assert.Equal(from[id], await FolderAsync(fx, id));
Assert.Null((await fx.Db.Sequences.GetAsync(id))!.Title);
Assert.SequenceEqual(files[id], await FilesAsync(fx, id));
}
Assert.Equal(("moved/2026-09-28 20-00-00", "20-00-00"), (await FolderAsync(fx, other), (await fx.Db.Sequences.GetAsync(other))!.Title));
Assert.SequenceEqual(["originals/001.JPG", "originals/002.JPG"], await FilesAsync(fx, other));
Assert.Empty(RenameJournal.ListPending(fx.Paths));
// Planned now, they are named after their first photo as it is.
var again = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [trashed, earlier], templates, fx.Ct);
Assert.SequenceEqual([("moved/2026-09-28 18-00-10", "18-00-10"), ("moved/2026-09-28 18-59-55", "18-59-55")],
again.Steps.Select(s => (s.ToFolder, s.ToTitle)));
}
[Test]
public async Task ARetryOfAJobThatKeptSequencesPlansAgain()
{
await using var fx = await CreateAsync(context);
var id = await UploadAsync(fx, 2);
var from = await FolderAsync(fx, id);
var templates = new RenameTemplates(Folder: "moved/{date} {time}");
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], templates, fx.Ct);
// Its job held the plan before its step (paused); the first photo then went to the trash.
RenameJournal.Write(fx.Paths, new RenameJournal(plan, [], Held: true));
await TrashFirstPhotoAsync(fx, id);
// Resumed, the job leaves the sequence as it was and says why it failed.
var engine = await fx.StartEngineAsync();
var job = await fx.EnqueueWithCheckpointAsync(engine, ArchiveJobs.Reorganize(fx.Archive, plan, templates), "plan:" + plan.Id.ToString("N"));
var failed = await fx.WaitForAsync(job.Id, JobState.Failed);
Assert.Equal(Loc.Plural("Archive.Error.ReorganizeKept", 1), failed.Error);
Assert.Contains(Loc.L("Archive.Log.ReorganizeDropped", from), failed.LogTail);
Assert.Equal(from, await FolderAsync(fx, id));
Assert.Empty(RenameJournal.ListPending(fx.Paths));
// Retried, it plans again instead of taking the plan for one an archive open completed: the archive is no longer
// the one the plan was confirmed for.
await engine.ResumeAsync(job.Id, fx.Ct);
var retried = await fx.WaitForAsync(job.Id, JobState.Failed);
Assert.Equal(Loc.L("Archive.Error.StalePlan"), retried.Error);
Assert.False(retried.LogTail!.Contains(Loc.L("Archive.Log.ReorganizedEarlier"), StringComparison.Ordinal), retried.LogTail);
Assert.Equal(from, await FolderAsync(fx, id));
}
[Test]
public async Task ASequenceAFolderWasToCarryIsToldItStayedWithIt()
{
await using var fx = await CreateAsync(context);
var parent = await UploadAsync(fx, 2);
var folder = (await fx.Db.Sequences.GetAsync(parent))!.Folder;
Photos.WriteSeries(Path.Combine(fx.Paths.FromRelative(folder), "extra"), Start.AddDays(3), 2, firstSeed: 50);
await fx.ScanAsync();
var nested = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Single(l => l.Folder == folder + "/extra").Id;
var templates = new RenameTemplates(Folder: "moved/{date}", Title: "Roof");
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [parent], templates, fx.Ct);
Assert.SequenceEqual([(parent, false), (nested, true)], plan.Steps.Select(s => (s.SequenceId, s.Carried)));
var inner = plan.Steps[1].ToTitle ?? plan.Steps[1].FromFolder;
// Interrupted before its step; a newer Chronos then rewrote the sidecar of the folder that carries the other.
RenameJournal.Write(fx.Paths, new RenameJournal(plan, []));
var sidecar = fx.Paths.Sequence(folder).ManifestPath;
var json = File.ReadAllText(sidecar);
Assert.Contains("\"schemaVersion\":1", json);
File.WriteAllText(sidecar, json.Replace("\"schemaVersion\":1", $"\"schemaVersion\":{SequenceManifest.CurrentSchemaVersion + 1}", StringComparison.Ordinal));
// Resumed, both stay where they are: the one inside is not said to have changed, and the job fails for the newer sidecar alone.
var engine = await fx.StartEngineAsync();
var failed = await fx.WaitForAsync((await fx.EnqueueWithCheckpointAsync(engine, ArchiveJobs.Reorganize(fx.Archive, plan, templates),
"plan:" + plan.Id.ToString("N"))).Id, JobState.Failed);
Assert.Equal(Loc.Plural("Archive.Error.ReorganizeNewer", 1), failed.Error);
Assert.Contains(Loc.L("Archive.Log.ReorganizeNewerKept", "Roof"), failed.LogTail);
Assert.Contains(Loc.L("Archive.Log.ReorganizeCarriedKept", inner), failed.LogTail);
Assert.False(failed.LogTail!.Contains(Loc.L("Archive.Log.ReorganizeDropped", inner), StringComparison.Ordinal), failed.LogTail);
Assert.Equal((folder, folder + "/extra"), (await FolderAsync(fx, parent), await FolderAsync(fx, nested)));
Assert.Empty(RenameJournal.ListPending(fx.Paths));
}
[Test]
public async Task AnArchiveOpensWhenAnInterruptedRenameMeetsASidecarOfANewerFormat()
{
await using var fx = await CreateAsync(context);
var id = await ChainAsync(fx);
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], new RenameTemplates(File: "{n:0}"), fx.Ct);
// Interrupted inside the step once every file reached its temporary name; a newer Chronos then rewrote the sidecar.
RenameJournal.Write(fx.Paths, new RenameJournal(plan, []));
var folder = fx.Paths.Sequence((await fx.Db.Sequences.GetAsync(id))!.Folder);
var manifest = ManifestStore.ReadSequence(folder.ManifestPath);
var moves = FileRenames.Plan(manifest, null, PathTemplate.Parse("{n:0}"), FileRenames.ListPresent(folder, manifest)).Moves;
var journal = FileRenameJournal.Create(manifest.Versions.Frames, moves, "crash") with { Phase = 2 };
FileRenameJournal.Write(folder, journal);
foreach (var file in journal.Files) File.Move(folder.File(file.From), folder.File(file.Temp));
var json = File.ReadAllText(folder.ManifestPath);
Assert.Contains("\"schemaVersion\":1", json);
var newer = json.Replace("\"schemaVersion\":1", $"\"schemaVersion\":{SequenceManifest.CurrentSchemaVersion + 1}", StringComparison.Ordinal);
File.WriteAllText(folder.ManifestPath, newer);
// Completing it would rewrite that sidecar, which this build never does: each open logs it, and the archive opens.
for (var open = 0; open < 2; open++)
{
Assert.Equal(fx.Archive.Id, (await fx.Service.OpenAsync(fx.Archive.RootPath, fx.Ct)).Id);
// Nothing is lost: the plan and the sequence's journal wait, and every photo is at the name that journal gives it.
Assert.NotNull(RenameJournal.Read(fx.Paths, plan.Id));
Assert.NotNull(FileRenameJournal.Read(folder));
foreach (var file in journal.Files) Assert.FileExists(folder.File(file.To));
Assert.Equal(newer, File.ReadAllText(folder.ManifestPath));
}
}
[Test]
public async Task AResumedStepWhoseFolderMovedKeepsATitleEditedSinceAndTheNamesFromIt()
{
await using var fx = await CreateAsync(context);
var id = await UploadAsync(fx, 2);
await fx.Service.SetSequenceInfoAsync(id, "Roof", [], 0, null, fx.Ct);
// The folder and the files are named after the title, which the plan does not change.
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], new RenameTemplates(Folder: "moved/{title}", File: "{title}_{n:000}"), fx.Ct);
var step = plan.Steps.Single();
Assert.True(step is { ToFolder: "moved/Roof", FileChanges: 2, Retitles: false, NamedByTitle: true });
// Retitled since the plan, and a run of it interrupted once the folder moved, before its index row followed.
await fx.Service.SetSequenceInfoAsync(id, "Roof north", [], 0, null, fx.Ct);
var before = await FilesAsync(fx, id);
RenameJournal.Write(fx.Paths, new RenameJournal(plan, []));
RenamePlanner.MoveFolder(fx.Paths, step);
// Resumed, its index row follows the folder; the title stays, and so do the file names that came from the old one.
var result = Assert.NotNull(await fx.Service.Renamer.ResumeAsync(fx.Archive, plan.Id, null, fx.Ct));
Assert.SequenceEqual([id], result.TitlesKept);
Assert.SequenceEqual([id], result.Changed);
Assert.Equal(0, result.Files);
Assert.Equal("moved/Roof", await FolderAsync(fx, id));
Assert.Equal("Roof north", (await fx.Db.Sequences.GetAsync(id))!.Title);
Assert.SequenceEqual(before, await FilesAsync(fx, id));
Assert.Empty(RenameJournal.ListPending(fx.Paths));
}
}