feat(archive): reorganize existing sequences with folder, file and title templates
Owner review 2, R7 asks for renaming and moving after import, on the web panel and the desktop. This is the engine and the server API both UIs build on. - FrameNaming (Core/Naming) is the one naming context and unique-name rule of a frame: imports, uploads and Reorganize now produce identical names (behaviour of the ingest and the import planner unchanged). - RenamePlanner takes a file template: each step counts its renamed frames, shows the first three and the frames version they were planned at, and lists what keeps its name (photos in place outside originals/, never hashed, missing, unreadable sidecar). Names are given in index order with _2, _3 as filing does; XMP companions follow their photo. - MassRenamer renames a step's files under the same leases after its folder moved, checks the frames version, journals .chronos/rename-files.json and moves files in two phases through temporary names so chains and swaps never meet; then sidecar, index (FrameRepository.RenameFilesAsync, both dialects) and journal. A failure puts every file back; a crash is completed by the next writer or the plan's resume, the index following. Plans a paused or cancelled job holds are left to that job. - JobKind.Move gets MoveJobHandler: it plans again and applies only the confirmed plan (fingerprint and frames versions), with progress and checkpoints per sequence. - POST /api/v1/archive/reorganize: dry run with the plan and its fingerprint, otherwise a 202 move job; validated templates, audited, sequenceChanged reorganized events. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit aae1c3eb18ea932b4a6251c5e2a282b9295a5785)
This commit is contained in:
1 parent
81cf58227d
commit
eb2395d9b0
36 files changed
+2238
-164
No files matched your search
@@ -435,10 +435,9 @@ public sealed class ArchiveIngest : IArchiveIngest
|
||||
if (!incoming.TryGetValue(frame.Id, out var entry)) continue;
|
||||
var staged = entry.Pending.Frame;
|
||||
var captured = frame.CapturedAt ?? DateTime.Now;
|
||||
var name = staged.PlannedName ?? template.ExpandFile(Naming(staged, captured, start ?? captured, frame.I + 1, manifest.Title));
|
||||
var file = directory + name;
|
||||
var stem = Path.GetFileNameWithoutExtension(name);
|
||||
for (var n = 2; !taken.Add(file); n++) file = string.Create(CultureInfo.InvariantCulture, $"{directory}{stem}_{n}{Path.GetExtension(name)}");
|
||||
var file = staged.PlannedName is { } planned
|
||||
? FrameNaming.Unique(directory + planned, taken.Add)
|
||||
: FrameNaming.FileName(template, Naming(staged, captured, start ?? captured, frame.I + 1, manifest.Title), taken, directory);
|
||||
named[frame.Id] = entry.Frame with { File = file };
|
||||
}
|
||||
return named;
|
||||
@@ -539,22 +538,8 @@ public sealed class ArchiveIngest : IArchiveIngest
|
||||
? client
|
||||
: frame.Metadata.CapturedAt ?? frame.ClientCapturedAt ?? DateTime.Now;
|
||||
|
||||
private static NamingContext Naming(StagedFrame frame, DateTime captured, DateTime sessionStart, int number, string? title) => new()
|
||||
{
|
||||
CapturedAt = captured,
|
||||
SessionStart = sessionStart,
|
||||
Number = number,
|
||||
NumberInSession = number,
|
||||
CameraMake = frame.Metadata.Make,
|
||||
CameraModel = frame.Metadata.Model,
|
||||
Lens = frame.Metadata.LensModel,
|
||||
Iso = frame.Metadata.Iso,
|
||||
ExposureTime = frame.Metadata.ExposureTime,
|
||||
FNumber = frame.Metadata.FNumber,
|
||||
OriginalName = Path.GetFileNameWithoutExtension(frame.OriginalFileName),
|
||||
Extension = Path.GetExtension(frame.OriginalFileName).TrimStart('.'),
|
||||
Title = title,
|
||||
};
|
||||
private static NamingContext Naming(StagedFrame frame, DateTime captured, DateTime sessionStart, int number, string? title) =>
|
||||
FrameNaming.Context(frame.Metadata, frame.OriginalFileName, captured, sessionStart, number, title);
|
||||
|
||||
private sealed class CommitQueue
|
||||
{
|
||||
|
||||
@@ -73,8 +73,8 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
|
||||
/// <summary>
|
||||
/// Handlers for scan, rebuild, verify, import, thumbs, proxies and maintenance jobs, the read-only duplicates and orphans
|
||||
/// reports, index backups and clean-ups (owner review 2, R10) and the emptying of the trash (R6); register them on the
|
||||
/// <see cref="JobEngine"/>.
|
||||
/// reports, index backups and clean-ups (owner review 2, R10), the emptying of the trash (R6) and Reorganize (R7,
|
||||
/// <see cref="JobKind.Move"/>); register them on the <see cref="JobEngine"/>.
|
||||
/// </summary>
|
||||
public IReadOnlyList<IJobHandler> CreateJobHandlers() =>
|
||||
[
|
||||
@@ -90,6 +90,7 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
new Housekeeping.BackupJobHandler(_db, _writer.Options.BackupDirectory),
|
||||
new Housekeeping.CleanupJobHandler(_db, CleanupSteps, TimeProvider.System),
|
||||
new EmptyTrashJobHandler(_db, Trash),
|
||||
new MoveJobHandler(_db, Renamer, _writer.Options.SequenceChanged),
|
||||
];
|
||||
|
||||
/// <summary>Makes <paramref name="root"/> a new, empty archive and indexes it.</summary>
|
||||
@@ -351,7 +352,23 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
await Renamer.PlanAsync(await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false), sequenceIds, folderTemplate, titleTemplate,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
|
||||
public async Task ApplyRenameAsync(RenamePlan plan, IProgress<int>? progress = null, CancellationToken cancellationToken = default) =>
|
||||
/// <summary>
|
||||
/// The dry run of a Reorganize (owner review 2, R7): <paramref name="templates"/> over <paramref name="sequenceIds"/>, or
|
||||
/// over every sequence of the archive (by folder) when null. Apply it in a job (<see cref="ArchiveJobs.Reorganize"/>) or
|
||||
/// with <see cref="ApplyRenameAsync"/>.
|
||||
/// </summary>
|
||||
/// <exception cref="ArgumentException">The archive is unknown, or a sequence is not in it.</exception>
|
||||
/// <exception cref="NestedRenameException">A new folder would lie inside a sequence's folder.</exception>
|
||||
public async Task<RenamePlan> PlanReorganizeAsync(Guid archiveId, IReadOnlyList<Guid>? sequenceIds, RenameTemplates templates,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(templates);
|
||||
var archive = await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false);
|
||||
var ids = sequenceIds ?? [.. (await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false)).Select(l => l.Id)];
|
||||
return await Renamer.PlanAsync(archive, ids, templates, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task<RenameResult> ApplyRenameAsync(RenamePlan plan, IProgress<int>? progress = null, CancellationToken cancellationToken = default) =>
|
||||
await Renamer.ApplyAsync(await LoadArchiveAsync(plan.ArchiveId, cancellationToken).ConfigureAwait(false), plan, progress, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
@@ -567,6 +584,24 @@ public static class ArchiveJobs
|
||||
JobPriority.User);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Move"/>: applies the Reorganize <paramref name="plan"/> (the dry run of <paramref name="templates"/>,
|
||||
/// <see cref="ArchiveService.PlanReorganizeAsync"/>) as confirmed, refused when the archive changed since
|
||||
/// (<see cref="MoveJobParameters"/>; owner review 2, R7).
|
||||
/// </summary>
|
||||
public static ArchiveJobRequest Reorganize(Archive archive, RenamePlan plan, RenameTemplates templates)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
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();
|
||||
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);
|
||||
}
|
||||
|
||||
public static Task<Job> EnqueueAsync(this JobEngine engine, ArchiveJobRequest request, Guid? createdBy = null, CancellationToken cancellationToken = default) =>
|
||||
engine.EnqueueAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, request.Priority, createdBy, cancellationToken);
|
||||
|
||||
|
||||
@@ -176,7 +176,7 @@ public sealed partial class FrameTrash
|
||||
continue;
|
||||
}
|
||||
var original = photo.Files[0];
|
||||
var tails = photo.Files.Skip(1).Select(c => CompanionTail(c.From, original.From)).ToList();
|
||||
var tails = photo.Files.Skip(1).Select(c => FrameCompanions.Tail(c.From, original.From)).ToList();
|
||||
var file = FreeName(folder, original.From, tails, taken);
|
||||
var stem = file[..^Path.GetExtension(file).Length];
|
||||
taken.Add(file);
|
||||
@@ -417,7 +417,7 @@ public sealed partial class FrameTrash
|
||||
if (folder is null && sequenceId is { } known && await _db.Sequences.GetAsync(known, CancellationToken.None).ConfigureAwait(false) is { } row)
|
||||
folder = paths.Sequence(row.Folder);
|
||||
var original = photo.Files[0];
|
||||
var tails = photo.Files.Skip(1).Select(c => CompanionTail(c.From, original.From)).ToList();
|
||||
var tails = photo.Files.Skip(1).Select(c => FrameCompanions.Tail(c.From, original.From)).ToList();
|
||||
var planned = FreeName(folder, ArchiveLayout.OriginalsFolder + "/" + Path.GetFileName(original.From), tails, names);
|
||||
var inEntry = Path.Combine(entryFolder, original.Path);
|
||||
var path = Path.Combine(staging, original.Path);
|
||||
@@ -475,7 +475,7 @@ public sealed partial class FrameTrash
|
||||
names.Add(ArchiveLayout.OriginalsFolder + "/" + Path.GetFileName(placed));
|
||||
foreach (var companion in photo.Files.Skip(1))
|
||||
{
|
||||
var beside = stem + CompanionTail(companion.From, original.From);
|
||||
var beside = stem + FrameCompanions.Tail(companion.From, original.From);
|
||||
names.Add(ArchiveLayout.OriginalsFolder + "/" + Path.GetFileName(beside));
|
||||
try
|
||||
{
|
||||
@@ -563,14 +563,6 @@ public sealed partial class FrameTrash
|
||||
return all.Count > 0 ? all : null;
|
||||
}
|
||||
|
||||
/// <summary>What a companion's name adds to its photo's stem (<c>.xmp</c>, <c>.CR2.xmp</c>).</summary>
|
||||
private static string CompanionTail(string companion, string photo)
|
||||
{
|
||||
var stem = Path.GetFileNameWithoutExtension(Path.GetFileName(photo));
|
||||
var name = Path.GetFileName(companion);
|
||||
return name.StartsWith(stem, StringComparison.OrdinalIgnoreCase) ? name[stem.Length..] : Path.GetExtension(name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="file"/> when it and its companions' names (<paramref name="tails"/> after its stem) are free in
|
||||
/// <paramref name="taken"/> and on disk in <paramref name="folder"/> (none yet: in <paramref name="taken"/> only), else
|
||||
|
||||
@@ -347,7 +347,7 @@ public sealed partial class FrameTrash
|
||||
var used = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var claimed = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var keptStems = kept.Select(f => Stem(f.File)).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var companions = new CompanionIndex(folder);
|
||||
var companions = new FrameCompanions.Index(folder);
|
||||
var photos = new List<TrashedPhoto>(removed.Count);
|
||||
foreach (var frame in removed)
|
||||
{
|
||||
@@ -431,35 +431,6 @@ public sealed partial class FrameTrash
|
||||
return Convert.ToHexStringLower(hash.GetHashAndReset());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The XMP files of a sequence's photo directories, each directory listed once (a deletion of thousands of photos does
|
||||
/// not list it again for each) and case-insensitively on every system (<c>IMG_0001.XMP</c> too).
|
||||
/// </summary>
|
||||
private sealed class CompanionIndex(SequencePaths folder)
|
||||
{
|
||||
private static readonly EnumerationOptions Listing = new() { MatchCasing = MatchCasing.CaseInsensitive, AttributesToSkip = 0 };
|
||||
private readonly Dictionary<string, ILookup<string, string>> _directories = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>The XMP files beside a photo that name it (<c>stem.xmp</c> or <c>file.xmp</c>), relative to the sequence folder.</summary>
|
||||
public IEnumerable<string> Of(string file)
|
||||
{
|
||||
var prefix = file.Contains('/') ? file[..(file.LastIndexOf('/') + 1)] : string.Empty;
|
||||
if (!_directories.TryGetValue(prefix, out var named))
|
||||
{
|
||||
var directory = Path.GetDirectoryName(folder.File(file))!;
|
||||
named = (System.IO.Directory.Exists(directory) ? System.IO.Directory.EnumerateFiles(directory, "*.xmp", Listing) : [])
|
||||
.Select(p => Path.GetFileName(p))
|
||||
.Where(n => Path.GetExtension(n).Equals(".xmp", StringComparison.OrdinalIgnoreCase))
|
||||
.ToLookup(n => Path.GetFileNameWithoutExtension(n), StringComparer.OrdinalIgnoreCase);
|
||||
_directories[prefix] = named;
|
||||
}
|
||||
var name = Path.GetFileName(file);
|
||||
var stem = Path.GetFileNameWithoutExtension(name);
|
||||
var matches = stem.Equals(name, StringComparison.OrdinalIgnoreCase) ? named[stem] : named[stem].Concat(named[name]);
|
||||
return matches.Select(n => prefix + n);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A photo's stem with its folder (<c>originals/IMG_0001</c>): its companions share it.</summary>
|
||||
private static string Stem(string file)
|
||||
{
|
||||
|
||||
@@ -40,6 +40,17 @@ public sealed record EmptyTrashParameters(IReadOnlyList<EmptyTrashItem> Entries,
|
||||
/// <summary>One entry of a confirmed emptying: its name and fingerprint when it was planned.</summary>
|
||||
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.
|
||||
/// </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 job ready to enqueue.</summary>
|
||||
public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList<Guid> Targets, string? Label, string? ParametersJson, JobPriority Priority);
|
||||
|
||||
@@ -52,6 +63,7 @@ public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList<Guid> Targets
|
||||
[JsonSerializable(typeof(BackupParameters))]
|
||||
[JsonSerializable(typeof(CleanupParameters))]
|
||||
[JsonSerializable(typeof(EmptyTrashParameters))]
|
||||
[JsonSerializable(typeof(MoveJobParameters))]
|
||||
[JsonSerializable(typeof(CardProfile))]
|
||||
internal sealed partial class ArchiveJobJson : JsonSerializerContext
|
||||
{
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Jobs;
|
||||
|
||||
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), through <see cref="MassRenamer"/>, whose journal makes
|
||||
/// every step resumable. Progress counts the plan's steps (sequences); checkpoint: <c>plan:<id></c> once the plan's
|
||||
/// journal is written. Paused or cancelled, the job stops between two sequences and holds the plan
|
||||
/// (<see cref="MassRenamer.Hold"/>), which an archive open then leaves to it; resumed or retried, it completes the rest when
|
||||
/// it still fits. A plan whose journal is gone completed meanwhile (at an archive open). Sequences left as they were, or
|
||||
/// whose files kept their names, because they changed after the plan are logged and fail the job at the end, after the
|
||||
/// others changed. Each sequence changed is told to <see cref="ArchiveServiceOptions.SequenceChanged"/> (<see cref="Change"/>).
|
||||
/// </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";
|
||||
|
||||
private const string Prefix = "plan:";
|
||||
|
||||
public JobKind Kind => JobKind.Move;
|
||||
|
||||
public async Task RunAsync(JobContext context)
|
||||
{
|
||||
var archive = await JobArchive.LoadAsync(db, context.Job, context.Cancellation).ConfigureAwait(false);
|
||||
var parameters = ArchiveJobJson.Read(context.Job, ArchiveJobJson.Default.MoveJobParameters, new MoveJobParameters(null, null, null, [], string.Empty));
|
||||
if (parameters.Fingerprint.Length == 0) throw new InvalidOperationException($"Move job {context.Job.Id} has no confirmed plan.");
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
var planId = PlanOf(context.Checkpoint);
|
||||
RenamePlan plan;
|
||||
RenameResult? result;
|
||||
try
|
||||
{
|
||||
if (planId is { } resumed)
|
||||
{
|
||||
if (RenameJournal.Read(paths, resumed) is not { } journal || await ResumeAsync(context, archive, journal).ConfigureAwait(false) is not { } done)
|
||||
{
|
||||
context.Log(Loc.L("Archive.Log.ReorganizedEarlier"));
|
||||
await context.ReportAsync(context.Total, context.Total).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
(plan, result) = (journal.Plan, done);
|
||||
}
|
||||
else
|
||||
{
|
||||
plan = await renamer.PlanAsync(archive, [.. parameters.Sequences.Select(s => s.Id)],
|
||||
new RenameTemplates(parameters.FolderTemplate, parameters.FileTemplate, parameters.TitleTemplate), context.Cancellation).ConfigureAwait(false);
|
||||
if (!IsConfirmed(plan, parameters)) throw new StaleRenamePlanException(Guid.Empty);
|
||||
var total = Steps(plan);
|
||||
await context.ReportAsync(0, total).ConfigureAwait(false);
|
||||
result = await renamer.ApplyAsync(archive, plan, p =>
|
||||
{
|
||||
planId = p.Id;
|
||||
return context.CheckpointAsync(Checkpoint(p.Id), 0, total);
|
||||
}, n => context.CheckpointAsync(Checkpoint(plan.Id), n, total), context.Cancellation).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (planId is { } id && context.Cancellation.IsCancellationRequested)
|
||||
{
|
||||
// Paused or cancelled by a user, not a yield to another job or the host stopping: the rest waits for this job.
|
||||
if (await db.Jobs.GetAsync(context.Job.Id, CancellationToken.None).ConfigureAwait(false) is { State: JobState.Paused or JobState.Cancelled }
|
||||
&& MassRenamer.Hold(archive, id))
|
||||
Log.Info("archive", $"Reorganize {id} held by its job {context.Job.Id}");
|
||||
throw;
|
||||
}
|
||||
context.Log(Loc.L("Archive.Log.Reorganized", result.Changed.Count, result.Files));
|
||||
foreach (var id in result.Dropped) context.Log(Loc.L("Archive.Log.ReorganizeDropped", Name(plan, id)));
|
||||
foreach (var id in result.FilesKept) context.Log(Loc.L("Archive.Log.ReorganizeFilesKept", Name(plan, id)));
|
||||
await TellAsync(result.Changed).ConfigureAwait(false);
|
||||
var kept = result.Dropped.Count + result.FilesKept.Count;
|
||||
if (kept > 0) throw new InvalidOperationException(Loc.Plural("Archive.Error.ReorganizeKept", kept));
|
||||
}
|
||||
|
||||
/// <summary>Completes a plan this job started; null when its journal went meanwhile (completed at an archive open).</summary>
|
||||
private async Task<RenameResult?> ResumeAsync(JobContext context, Archive archive, RenameJournal journal)
|
||||
{
|
||||
var total = Steps(journal.Plan);
|
||||
await context.ReportAsync(journal.Completed.Count, total).ConfigureAwait(false);
|
||||
return await renamer.ResumeAsync(archive, journal.Plan.Id, n => context.CheckpointAsync(Checkpoint(journal.Plan.Id), n, total), context.Cancellation)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static int Steps(RenamePlan plan) => plan.Steps.Count(s => s.Changes);
|
||||
|
||||
/// <summary>How the job log names a sequence of the plan: its title, else its folder.</summary>
|
||||
private static string Name(RenamePlan plan, Guid id) =>
|
||||
plan.Steps.FirstOrDefault(s => s.SequenceId == id) is { } step ? step.ToTitle ?? step.FromTitle ?? step.FromFolder : id.ToString();
|
||||
|
||||
private static string Checkpoint(Guid planId) => Prefix + planId.ToString("N");
|
||||
|
||||
private static Guid? PlanOf(string? checkpoint) =>
|
||||
checkpoint is not null && checkpoint.StartsWith(Prefix, StringComparison.Ordinal) && Guid.TryParseExact(checkpoint[Prefix.Length..], "N", out var id)
|
||||
? id
|
||||
: null;
|
||||
}
|
||||
@@ -2,13 +2,14 @@ using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Naming;
|
||||
using Chronos.Data.Repositories;
|
||||
|
||||
namespace Chronos.Data.Archiving;
|
||||
|
||||
/// <summary>
|
||||
/// The plan no longer matches the archive: a sequence moved or vanished since it was made, or one was indexed inside a
|
||||
/// folder the plan moves.
|
||||
/// folder the plan moves, or the photos of a sequence whose files it renames changed.
|
||||
/// </summary>
|
||||
public sealed class StaleRenamePlanException(Guid sequenceId)
|
||||
: InvalidOperationException(Loc.L("Archive.Error.StalePlan"))
|
||||
@@ -17,9 +18,19 @@ public sealed class StaleRenamePlanException(Guid sequenceId)
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Mass rename of sequence folders and titles (BRIEF §7, §12.5): <see cref="PlanAsync"/> is the dry run;
|
||||
/// <see cref="ApplyAsync"/> makes exactly the planned changes to folders, sidecars and the index, step by step, with a
|
||||
/// journal on the archive so an interrupted rename is completed by <see cref="ResumePendingAsync"/>.
|
||||
/// What applying a plan did: the sequences changed (in the order of the plan), the frames whose files got a new name, the
|
||||
/// sequences left as they were because they changed since the plan (<see cref="Dropped"/>, only when resuming) and those
|
||||
/// whose files kept their names because their photos changed since (<see cref="FilesKept"/>; their folder and title changed).
|
||||
/// </summary>
|
||||
public sealed record RenameResult(IReadOnlyList<Guid> Changed, int Files, IReadOnlyList<Guid> Dropped, IReadOnlyList<Guid> FilesKept);
|
||||
|
||||
/// <summary>
|
||||
/// Mass rename of sequence folders, titles and file names (BRIEF §7, §12.5; Reorganize, owner review 2, R7):
|
||||
/// <see cref="PlanAsync(Archive, IReadOnlyList{Guid}, RenameTemplates, CancellationToken)"/> is the dry run;
|
||||
/// <see cref="ApplyAsync(Archive, RenamePlan, IProgress{int}?, CancellationToken)"/> makes exactly the planned changes to
|
||||
/// folders, files, sidecars and the index, step by step, with a journal on the archive so an interrupted rename is
|
||||
/// completed by <see cref="ResumePendingAsync"/> (or, for a plan its job held, by <see cref="ResumeAsync"/>). A step's file
|
||||
/// renames have their own journal in the sequence (<see cref="FileRenameJournal"/>).
|
||||
/// </summary>
|
||||
public sealed class MassRenamer
|
||||
{
|
||||
@@ -38,20 +49,35 @@ public sealed class MassRenamer
|
||||
/// <param name="titleTemplate">New title template (<c>{title}</c> = the current title), or null to keep titles.</param>
|
||||
/// <remarks>Sequences nested in a folder that moves are part of the plan (they move with it); see <see cref="RenamePlanner.Plan"/>.</remarks>
|
||||
/// <exception cref="NestedRenameException">A new folder would lie inside a sequence's folder.</exception>
|
||||
public async Task<RenamePlan> PlanAsync(Archive archive, IReadOnlyList<Guid> sequenceIds, string? folderTemplate, string? titleTemplate,
|
||||
CancellationToken cancellationToken = default)
|
||||
public Task<RenamePlan> PlanAsync(Archive archive, IReadOnlyList<Guid> sequenceIds, string? folderTemplate, string? titleTemplate,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
PlanAsync(archive, sequenceIds, new RenameTemplates(folderTemplate, null, titleTemplate), cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// The dry run of a Reorganize: the plan of <paramref name="templates"/> over <paramref name="sequenceIds"/>. With a file
|
||||
/// template each sequence's sidecar is read (without its lease) with the files beside its frames, so the plan names
|
||||
/// exactly the files the apply will rename while nothing changes. A sequence created without photos, which has no
|
||||
/// folder yet, is left out.
|
||||
/// </summary>
|
||||
/// <exception cref="ArgumentException">A sequence is not in the archive.</exception>
|
||||
/// <exception cref="NestedRenameException">A new folder would lie inside a sequence's folder.</exception>
|
||||
public async Task<RenamePlan> PlanAsync(Archive archive, IReadOnlyList<Guid> sequenceIds, RenameTemplates templates, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
ArgumentNullException.ThrowIfNull(sequenceIds);
|
||||
ArgumentNullException.ThrowIfNull(templates);
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
var locations = await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false);
|
||||
var subjects = new List<RenameSubject>(sequenceIds.Count);
|
||||
foreach (var id in sequenceIds)
|
||||
foreach (var id in sequenceIds.Distinct())
|
||||
{
|
||||
if (await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } s || s.ArchiveId != archive.Id)
|
||||
throw new ArgumentException($"Sequence {id} is not in archive {archive.Id}.", nameof(sequenceIds));
|
||||
subjects.Add(Subject(s));
|
||||
if (ArchiveIngest.AwaitsFolder(s, paths)) continue;
|
||||
subjects.Add(Subject(s) with { Files = templates.File is null ? null : ReadFiles(paths, s) });
|
||||
}
|
||||
var nested = new List<RenameSubject>();
|
||||
if (folderTemplate is not null)
|
||||
if (templates.Folder is not null)
|
||||
{
|
||||
var selected = sequenceIds.ToHashSet();
|
||||
foreach (var location in locations.Where(l => !selected.Contains(l.Id) && subjects.Any(s => RenamePlanner.IsInside(s.Folder, l.Folder))))
|
||||
@@ -59,51 +85,115 @@ public sealed class MassRenamer
|
||||
if (await _db.Sequences.GetAsync(location.Id, cancellationToken).ConfigureAwait(false) is { } inner) nested.Add(Subject(inner));
|
||||
}
|
||||
}
|
||||
return RenamePlanner.Plan(archive.Id, subjects, folderTemplate, titleTemplate, locations.Select(l => l.Folder),
|
||||
folder => Directory.Exists(paths.Sequence(folder).Folder), nested);
|
||||
return RenamePlanner.Plan(archive.Id, subjects, templates.Folder, templates.Title, locations.Select(l => l.Folder),
|
||||
folder => Directory.Exists(paths.Sequence(folder).Folder), nested, templates.File);
|
||||
}
|
||||
|
||||
private static RenameSubject Subject(Sequence s) => new(s.Id, s.Folder, s.Title, s.FirstCapture, s.CameraMake, s.CameraModel, s.Lens);
|
||||
|
||||
/// <summary>Applies a plan; each completed step is journaled before the next starts.</summary>
|
||||
/// <exception cref="StaleRenamePlanException">A sequence is no longer where the plan expects it, or a folder that moves holds
|
||||
/// a sequence the plan does not take along; nothing of that step was changed.</exception>
|
||||
public Task ApplyAsync(Archive archive, RenamePlan plan, IProgress<int>? progress = null, CancellationToken cancellationToken = default) =>
|
||||
RunAsync(archive, new RenameJournal(plan, []), resuming: false, progress, cancellationToken);
|
||||
/// <summary>The sidecar of a sequence and the files beside its frames; null (logged) when it cannot be read or is another sequence's.</summary>
|
||||
private static SequenceFiles? ReadFiles(ArchivePaths paths, Sequence sequence)
|
||||
{
|
||||
var folder = paths.Sequence(sequence.Folder);
|
||||
try
|
||||
{
|
||||
var manifest = ManifestStore.ReadSequence(folder.ManifestPath);
|
||||
if (manifest.Id == sequence.Id) return new SequenceFiles(manifest, FileRenames.ListPresent(folder, manifest));
|
||||
Log.Warning("archive", $"{folder.ManifestPath} belongs to sequence {manifest.Id}, not {sequence.Id}; its files keep their names");
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
|
||||
{
|
||||
Log.Warning("archive", $"The sidecar of {sequence.DisplayTitle} cannot be read; its files keep their names", ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Completes renames interrupted by a crash; returns how many plans were resumed.</summary>
|
||||
/// <summary>Applies a plan; each completed step is journaled before the next starts.</summary>
|
||||
/// <exception cref="StaleRenamePlanException">A sequence is no longer where the plan expects it, a folder that moves holds
|
||||
/// a sequence the plan does not take along, or the photos of a sequence whose files it renames changed; nothing of that
|
||||
/// step was changed (a step found stale only once its folder moved keeps its folder and title, and its journal has the
|
||||
/// next open complete the rest).</exception>
|
||||
/// <exception cref="IOException">A file could not be renamed (open elsewhere); the step's files went back to their names.</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 =>
|
||||
{
|
||||
progress.Report(n);
|
||||
return ValueTask.CompletedTask;
|
||||
}, cancellationToken);
|
||||
|
||||
/// <inheritdoc cref="ApplyAsync(Archive, RenamePlan, IProgress{int}?, CancellationToken)"/>
|
||||
/// <param name="started">Told once the plan's journal is written, before any step (a job saves the plan's id as its checkpoint).</param>
|
||||
/// <param name="stepDone">Told after each step with the number of steps done.</param>
|
||||
public Task<RenameResult> ApplyAsync(Archive archive, RenamePlan plan, Func<RenamePlan, ValueTask>? started, Func<int, ValueTask>? stepDone,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
return RunAsync(archive, new RenameJournal(plan, []), resuming: false, started, stepDone, cancellationToken);
|
||||
}
|
||||
|
||||
/// <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).
|
||||
/// </summary>
|
||||
/// <exception cref="StaleRenamePlanException">A held plan's remaining steps no longer match the archive; nothing more changed.</exception>
|
||||
public async Task<RenameResult?> ResumeAsync(Archive archive, Guid planId, Func<int, ValueTask>? stepDone = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
if (RenameJournal.Read(new ArchivePaths(archive.RootPath), planId) is not { } journal) return null;
|
||||
return await RunAsync(archive, journal with { Held = false }, resuming: !journal.Held, null, stepDone, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks the plan <paramref name="planId"/> held (<see cref="RenameJournal.Held"/>): its job was paused or cancelled between
|
||||
/// two steps, so an archive open leaves the rest to that job. False when it has no journal (it completed).
|
||||
/// </summary>
|
||||
public static bool Hold(Archive archive, Guid planId)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
if (RenameJournal.Read(paths, planId) is not { } journal) return false;
|
||||
RenameJournal.Write(paths, journal with { Held = true });
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Completes renames interrupted by a crash (not those their job held); returns how many plans were resumed.</summary>
|
||||
public async Task<int> ResumePendingAsync(Archive archive, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
var pending = RenameJournal.ListPending(paths).Where(j => j.Plan.ArchiveId == archive.Id).ToList();
|
||||
foreach (var journal in pending) await RunAsync(archive, journal, resuming: true, null, cancellationToken).ConfigureAwait(false);
|
||||
var pending = RenameJournal.ListPending(paths).Where(j => j.Plan.ArchiveId == archive.Id && !j.Held).ToList();
|
||||
foreach (var journal in pending) await RunAsync(archive, journal, resuming: true, null, null, cancellationToken).ConfigureAwait(false);
|
||||
return pending.Count;
|
||||
}
|
||||
|
||||
/// <param name="resuming">Steps whose sequence the index no longer knows are dropped instead of failing the rename:
|
||||
/// their sidecars still carry the ids, so the next scan indexes them wherever they ended up.</param>
|
||||
private async Task RunAsync(Archive archive, RenameJournal journal, bool resuming, IProgress<int>? progress, CancellationToken cancellationToken)
|
||||
private async Task<RenameResult> RunAsync(Archive archive, RenameJournal journal, bool resuming, Func<RenamePlan, ValueTask>? started,
|
||||
Func<int, ValueTask>? stepDone, CancellationToken cancellationToken)
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
if (journal.Plan.ArchiveId != archive.Id) throw new ArgumentException("The plan belongs to another archive.", nameof(journal));
|
||||
var completed = journal.Completed.ToHashSet();
|
||||
// A step that changes nothing (its files kept their names, and why) has nothing to apply.
|
||||
var steps = journal.Plan.Steps.Where(s => s.Changes).ToList();
|
||||
if (!resuming)
|
||||
{
|
||||
// A plan made before another change is refused before anything moves: a sequence moved, or one was indexed
|
||||
// inside a folder that moves (a scan adopted a subfolder copied in since the dry run).
|
||||
foreach (var step in journal.Plan.Steps)
|
||||
try
|
||||
{
|
||||
if ((await _db.Sequences.GetAsync(step.SequenceId, cancellationToken).ConfigureAwait(false))?.Folder != step.FromFolder)
|
||||
throw new StaleRenamePlanException(step.SequenceId);
|
||||
await RefuseStaleAsync(archive, paths, journal.Plan, [.. steps.Where(s => !completed.Contains(s.SequenceId))], cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (StaleRenamePlanException) when (completed.Count > 0 || File.Exists(RenameJournal.PathFor(paths, journal.Plan.Id)))
|
||||
{
|
||||
// A held plan that no longer fits: what it applied stays, the rest never will.
|
||||
RenameJournal.Delete(paths, journal.Plan.Id);
|
||||
Log.Warning("archive", $"The rest of rename {journal.Plan.Id} no longer matches the archive; it was given up");
|
||||
throw;
|
||||
}
|
||||
var planned = journal.Plan.Steps.Select(s => s.SequenceId).ToHashSet();
|
||||
if (await StrangerInsideAsync(archive, journal.Plan.Steps.Where(s => s.MovesFolder && !s.Carried), planned, cancellationToken)
|
||||
.ConfigureAwait(false) is { } stranger)
|
||||
throw new StaleRenamePlanException(stranger.Id);
|
||||
}
|
||||
RenameJournal.Write(paths, journal);
|
||||
var steps = journal.Plan.Steps;
|
||||
if (started is not null) await started(journal.Plan).ConfigureAwait(false);
|
||||
var result = new Tally();
|
||||
foreach (var step in steps)
|
||||
{
|
||||
if (completed.Contains(step.SequenceId)) continue;
|
||||
@@ -112,13 +202,50 @@ public sealed class MassRenamer
|
||||
IReadOnlyList<RenameStep> carried = step.MovesFolder && !step.Carried
|
||||
? [.. steps.Where(c => c.Carried && !completed.Contains(c.SequenceId) && Carrier(steps, c) == step)]
|
||||
: [];
|
||||
await ApplyStepAsync(archive, paths, step, carried, resuming, cancellationToken).ConfigureAwait(false);
|
||||
await ApplyStepAsync(archive, paths, journal.Plan.FileTemplate, step, carried, resuming, result, cancellationToken).ConfigureAwait(false);
|
||||
completed.Add(step.SequenceId);
|
||||
foreach (var c in carried) completed.Add(c.SequenceId);
|
||||
RenameJournal.Write(paths, journal with { Completed = [.. completed] });
|
||||
progress?.Report(completed.Count);
|
||||
if (stepDone is not null) await stepDone(completed.Count).ConfigureAwait(false);
|
||||
}
|
||||
RenameJournal.Delete(paths, journal.Plan.Id);
|
||||
return new RenameResult(result.Changed, result.Files, result.Dropped, result.FilesKept);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A plan made before another change is refused before anything moves: a sequence moved, one was indexed inside a
|
||||
/// folder that moves (a scan adopted a subfolder copied in since the dry run), or the photos of a sequence whose files
|
||||
/// it renames changed (another frames version in its sidecar).
|
||||
/// </summary>
|
||||
private async Task RefuseStaleAsync(Archive archive, ArchivePaths paths, RenamePlan plan, IReadOnlyList<RenameStep> remaining, CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (var step in remaining)
|
||||
{
|
||||
if ((await _db.Sequences.GetAsync(step.SequenceId, cancellationToken).ConfigureAwait(false))?.Folder != step.FromFolder)
|
||||
throw new StaleRenamePlanException(step.SequenceId);
|
||||
}
|
||||
var planned = plan.Steps.Select(s => s.SequenceId).ToHashSet();
|
||||
if (await StrangerInsideAsync(archive, remaining.Where(s => s.MovesFolder && !s.Carried), planned, cancellationToken).ConfigureAwait(false) is { } stranger)
|
||||
throw new StaleRenamePlanException(stranger.Id);
|
||||
if (plan.FileTemplate is null) return;
|
||||
foreach (var step in remaining.Where(s => s.FileChanges > 0))
|
||||
{
|
||||
if (FramesVersionOf(paths.Sequence(step.FromFolder), step.SequenceId) != step.FramesVersion) throw new StaleRenamePlanException(step.SequenceId);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The frames version of a sequence's sidecar (read without its lease); null when it cannot be read or is another sequence's.</summary>
|
||||
private static int? FramesVersionOf(SequencePaths sequence, Guid sequenceId)
|
||||
{
|
||||
try
|
||||
{
|
||||
var manifest = ManifestStore.ReadSequence(sequence.ManifestPath);
|
||||
return manifest.Id == sequenceId ? manifest.Versions.Frames : null;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The step whose folder move carries <paramref name="carried"/>: the nearest moving folder around it (as planned).</summary>
|
||||
@@ -127,14 +254,15 @@ public sealed class MassRenamer
|
||||
|
||||
/// <summary>
|
||||
/// Applies a step, and the steps of the sequences its folder carries, under all their leases: sequence leases, then
|
||||
/// for a move the thumbnail leases, each by sequence id (the order trash and pack compaction take them in). No
|
||||
/// writer of a carried sequence (ingest, an editor save, a thumbnail pass) works in the folder while it moves or
|
||||
/// before its index row follows.
|
||||
/// for a move or file renames the thumbnail leases, each by sequence id (the order trash and pack compaction take them
|
||||
/// in). No writer of a carried sequence (ingest, an editor save, a thumbnail pass) works in the folder while it moves or
|
||||
/// its files are renamed, or before its index row follows. Once the folder moved the step goes to its end whatever
|
||||
/// the caller cancels.
|
||||
/// </summary>
|
||||
/// <param name="resuming">A step whose sequence the index no longer has where the plan says is dropped instead of
|
||||
/// failing the rename: its sidecar still carries the id, so the next scan indexes it wherever it ended up.</param>
|
||||
private async Task ApplyStepAsync(Archive archive, ArchivePaths paths, RenameStep step, IReadOnlyList<RenameStep> carried, bool resuming,
|
||||
CancellationToken cancellationToken)
|
||||
private async Task ApplyStepAsync(Archive archive, ArchivePaths paths, string? fileTemplate, RenameStep step, IReadOnlyList<RenameStep> carried,
|
||||
bool resuming, Tally result, CancellationToken cancellationToken)
|
||||
{
|
||||
var ids = carried.Select(c => c.SequenceId).Append(step.SequenceId).Order().ToList();
|
||||
var locks = new List<IAsyncDisposable>(ids.Count);
|
||||
@@ -142,7 +270,7 @@ public sealed class MassRenamer
|
||||
try
|
||||
{
|
||||
foreach (var id in ids) locks.Add(await _writer.LockAsync(paths, id, cancellationToken).ConfigureAwait(false));
|
||||
if (step.MovesFolder)
|
||||
if (step.MovesFolder || step.FileChanges > 0 || carried.Any(c => c.FileChanges > 0))
|
||||
{
|
||||
foreach (var id in ids)
|
||||
{
|
||||
@@ -151,17 +279,31 @@ public sealed class MassRenamer
|
||||
}
|
||||
}
|
||||
// Checked before anything moves; a dropped step drops the sequences it would have carried, which stay inside it.
|
||||
if (!await StandsAsync(step, resuming, cancellationToken).ConfigureAwait(false)) return;
|
||||
if (!await StandsAsync(step, resuming, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
result.Dropped.Add(step.SequenceId);
|
||||
return;
|
||||
}
|
||||
var follow = new List<RenameStep>(carried.Count);
|
||||
foreach (var c in carried)
|
||||
{
|
||||
if (await StandsAsync(c, resuming, cancellationToken).ConfigureAwait(false)) follow.Add(c);
|
||||
else result.Dropped.Add(c.SequenceId);
|
||||
}
|
||||
if (!await CarriesAllInsideAsync(archive, paths, step, carried, resuming, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
result.Dropped.Add(step.SequenceId);
|
||||
result.Dropped.AddRange(follow.Select(c => c.SequenceId));
|
||||
return;
|
||||
}
|
||||
if (!await CarriesAllInsideAsync(archive, paths, step, carried, resuming, cancellationToken).ConfigureAwait(false)) return;
|
||||
RenamePlanner.MoveFolder(paths, step);
|
||||
await RecordAsync(archive, paths, step, cancellationToken).ConfigureAwait(false);
|
||||
// Moved with their carrier: only their sidecars and index rows follow.
|
||||
foreach (var c in follow) await RecordAsync(archive, paths, c, cancellationToken).ConfigureAwait(false);
|
||||
// Moved with their carrier: only their sidecars and index rows follow, and the names of their files.
|
||||
foreach (var s in follow.Prepend(step))
|
||||
{
|
||||
await RecordAsync(archive, paths, s, CancellationToken.None).ConfigureAwait(false);
|
||||
var renamed = await RenameFilesAsync(archive, paths, fileTemplate, s, resuming, result, CancellationToken.None).ConfigureAwait(false);
|
||||
if (s.MovesFolder || s.Retitles || renamed) result.Changed.Add(s.SequenceId);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -215,16 +357,18 @@ public sealed class MassRenamer
|
||||
/// The index row changes in its folder and title only (<see cref="SequenceRepository.RelocateAsync"/>): a settings edit
|
||||
/// committed meanwhile stays, and frames another process listed in the sidecar are left to the next scan, for which
|
||||
/// the folder keeps no stamps unless the index held it as it was
|
||||
/// (<see cref="ArchiveIndexer.InStepAsync(Archive, string, SequencePaths, SequenceManifest, CancellationToken)"/>).
|
||||
/// (<see cref="ArchiveIndexer.InStepAsync(Archive, string, SequencePaths, SequenceManifest, CancellationToken)"/>). A step
|
||||
/// that only renames files has nothing to record here.
|
||||
/// </summary>
|
||||
private async Task RecordAsync(Archive archive, ArchivePaths paths, RenameStep step, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!step.MovesFolder && !step.Retitles) return;
|
||||
var sequence = paths.Sequence(step.ToFolder);
|
||||
var manifest = SequenceWriter.ReadLocked(sequence, step.SequenceId);
|
||||
// The folder moved with its files' stamps, which the index recorded at its old place.
|
||||
var inStep = await _indexer.InStepAsync(archive, step.FromFolder, sequence, manifest, cancellationToken).ConfigureAwait(false);
|
||||
// A step that only moves the folder keeps the title, which an edit may have changed since the plan.
|
||||
var retitle = step.FromTitle != step.ToTitle;
|
||||
var retitle = step.Retitles;
|
||||
if (retitle && manifest.Title != step.ToTitle)
|
||||
{
|
||||
manifest = manifest with
|
||||
@@ -244,4 +388,83 @@ public sealed class MassRenamer
|
||||
}
|
||||
if (inStep) await _indexer.RecordStampsAsync(archive, sequence, step.SequenceId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The file renames of a step, under the leases its step holds, once its folder is in place (Reorganize, owner review 2,
|
||||
/// R7). The renames are planned again from the sidecar read under the lease (<see cref="FileRenames.Plan"/>, with the
|
||||
/// step's title, the one the dry run showed), which names exactly what the dry run showed while its frames version is the plan's: another one
|
||||
/// refuses the step (<see cref="StaleRenamePlanException"/>), or, when resuming, leaves its files as they are. The files
|
||||
/// move in two phases through temporary names under the sequence's journal (<see cref="FileRenameJournal"/>), then the
|
||||
/// sidecar names them (the frame order unchanged, frames version + 1), then the index (<see cref="FrameRepository.RenameFilesAsync"/>),
|
||||
/// then the journal goes. When nothing moves here but the index names other files than the sidecar, a writer completed
|
||||
/// the renames after a crash (<see cref="SequenceWriter.ReadLocked"/>) before the index followed, and the index is synced
|
||||
/// from the sidecar. Proxies (named by frame index), thumbnails (by index and content hash), renders and exports need
|
||||
/// nothing.
|
||||
/// </summary>
|
||||
/// <returns>False when the step renames no file, or its files kept their names.</returns>
|
||||
private async Task<bool> RenameFilesAsync(Archive archive, ArchivePaths paths, string? fileTemplate, RenameStep step, bool resuming, Tally result,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (fileTemplate is null || step.FileChanges == 0) return false;
|
||||
var sequence = paths.Sequence(step.ToFolder);
|
||||
var manifest = SequenceWriter.ReadLocked(sequence, step.SequenceId);
|
||||
var inStep = await _indexer.InStepAsync(archive, sequence, manifest, cancellationToken).ConfigureAwait(false);
|
||||
var plan = FileRenames.Plan(manifest, step.ToTitle, PathTemplate.Parse(fileTemplate), FileRenames.ListPresent(sequence, manifest));
|
||||
var before = manifest.Versions.Frames;
|
||||
if (plan.Moves.Count > 0 && before != step.FramesVersion)
|
||||
{
|
||||
if (!resuming) throw new StaleRenamePlanException(step.SequenceId);
|
||||
Log.Warning("archive", $"The files of {sequence.RelativeFolder} keep their names: its photos changed after the plan was made");
|
||||
result.FilesKept.Add(step.SequenceId);
|
||||
return false;
|
||||
}
|
||||
if (plan.Moves.Count > 0)
|
||||
{
|
||||
var journal = FileRenameJournal.Create(before, plan.Moves, Guid.NewGuid().ToString("N")[..8]);
|
||||
FileRenameJournal.Write(sequence, journal);
|
||||
journal = FileRenameJournal.Run(sequence, journal);
|
||||
manifest = FileRenameJournal.Applied(manifest, journal) ?? manifest;
|
||||
ManifestStore.WriteSequence(sequence.ManifestPath, manifest);
|
||||
result.Files += plan.Frames;
|
||||
Log.Info("archive", $"{sequence.RelativeFolder}: {plan.Frames} file(s) renamed, {plan.Moves.Count - plan.Frames} companion(s) with them");
|
||||
await _db.Frames.RenameFilesAsync(manifest.Id, await BehindAsync(sequence, manifest, cancellationToken).ConfigureAwait(false), before,
|
||||
manifest.Versions.Frames, cancellationToken).ConfigureAwait(false);
|
||||
if (inStep) await _indexer.RecordStampsAsync(archive, sequence, step.SequenceId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else if ((await BehindAsync(sequence, manifest, cancellationToken).ConfigureAwait(false)).Count > 0)
|
||||
{
|
||||
// Photos copied in by hand meanwhile are left to the next scan's reconcile (the photo stamp stays as recorded).
|
||||
await _indexer.SyncAsync(archive, sequence, manifest, null, SequenceStatus.None, photosChanged: true, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
FileRenameJournal.Delete(sequence);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The frames the index names by another file than the sidecar does, with the sidecar's path and name; frames the index does not have are left to the next scan.</summary>
|
||||
private async Task<List<FrameFileName>> BehindAsync(SequencePaths sequence, SequenceManifest manifest, CancellationToken cancellationToken)
|
||||
{
|
||||
const int page = 1000;
|
||||
var files = manifest.Frames.ToDictionary(f => f.Id, f => f.File);
|
||||
var behind = new List<FrameFileName>();
|
||||
for (var last = -1; ;)
|
||||
{
|
||||
var rows = await _db.Frames.ListBySequenceAsync(manifest.Id, last, page, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var row in rows)
|
||||
{
|
||||
if (!files.TryGetValue(row.Id, out var file)) continue;
|
||||
var path = sequence.ArchiveRelative(file);
|
||||
if (row.RelativePath != path) behind.Add(new FrameFileName(row.Id, path, Path.GetFileName(file)));
|
||||
}
|
||||
if (rows.Count < page) return behind;
|
||||
last = rows[^1].Index;
|
||||
}
|
||||
}
|
||||
/// <summary>What a run did, as it goes.</summary>
|
||||
private sealed class Tally
|
||||
{
|
||||
public List<Guid> Changed { get; } = [];
|
||||
public List<Guid> Dropped { get; } = [];
|
||||
public List<Guid> FilesKept { get; } = [];
|
||||
public int Files { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,12 @@ public sealed record ArchiveServiceOptions
|
||||
/// </summary>
|
||||
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.
|
||||
/// </summary>
|
||||
public Func<Guid, string, CancellationToken, Task>? SequenceChanged { get; init; }
|
||||
|
||||
/// <summary>Half the logical cores, at least one: the parallelism when the host sets none.</summary>
|
||||
public static int DefaultParallelism => Math.Max(1, Environment.ProcessorCount / 2);
|
||||
|
||||
@@ -88,9 +94,11 @@ internal sealed class SequenceWriter(ArchiveServiceOptions options)
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the sidecar of a locked sequence, undoing an interrupted photo deletion (<see cref="FrameRemovalJournal"/>),
|
||||
/// settling an interrupted restore from the trash (<see cref="FrameRestoreJournal"/>; left for later while its trash
|
||||
/// entry is busy) and completing an interrupted ingest batch first.
|
||||
/// Reads the sidecar of a locked sequence, completing an interrupted Reorganize of its files (<see cref="FileRenameJournal"/>),
|
||||
/// undoing an interrupted photo deletion (<see cref="FrameRemovalJournal"/>), settling an interrupted restore from the
|
||||
/// trash (<see cref="FrameRestoreJournal"/>; left for later while its trash entry is busy) and completing an interrupted
|
||||
/// ingest batch first. A sidecar a rename recovery rewrites leaves the index behind it until the rename resumes or the
|
||||
/// next scan reads it.
|
||||
/// </summary>
|
||||
/// <param name="heldEntryLease">The trash entry lease the caller holds already (a restore of that entry), if any.</param>
|
||||
/// <exception cref="InvalidDataException">The sidecar in the folder belongs to another sequence.</exception>
|
||||
@@ -99,6 +107,15 @@ internal sealed class SequenceWriter(ArchiveServiceOptions options)
|
||||
var manifest = ManifestStore.ReadSequence(sequence.ManifestPath);
|
||||
if (manifest.Id != sequenceId)
|
||||
throw new InvalidDataException($"{sequence.ManifestPath} belongs to sequence {manifest.Id}, not {sequenceId}.");
|
||||
if (File.Exists(sequence.FileRenameJournalPath))
|
||||
{
|
||||
if (FileRenameJournal.Recover(sequence, manifest) is { } renamed)
|
||||
{
|
||||
ManifestStore.WriteSequence(sequence.ManifestPath, renamed);
|
||||
manifest = renamed;
|
||||
}
|
||||
FileRenameJournal.Delete(sequence);
|
||||
}
|
||||
FrameRemovalJournal.Recover(sequence, manifest);
|
||||
FrameTrash.RecoverRestore(sequence, manifest, heldEntryLease);
|
||||
if (IngestJournal.Recover(sequence, manifest) is { } recovered)
|
||||
|
||||
@@ -19,6 +19,9 @@ public readonly record struct FramePosition(Guid FrameId, int Index);
|
||||
/// <summary>A frame whose content (SHA-256) also exists elsewhere in the archive.</summary>
|
||||
public sealed record DuplicateFrame(string Sha256, Guid FrameId, Guid SequenceId, int Index, string RelativePath);
|
||||
|
||||
/// <summary>A frame's file after a Reorganize renamed it (owner review 2, R7): its archive-relative path and its file name.</summary>
|
||||
public readonly record struct FrameFileName(Guid FrameId, string RelativePath, string FileName);
|
||||
|
||||
/// <summary>Light statistics of one frame, written by the analysis job.</summary>
|
||||
public readonly record struct FrameLightStats(Guid FrameId, double? MeanLogLuminance, double? ClipLow, double? ClipHigh);
|
||||
|
||||
@@ -292,6 +295,60 @@ public sealed class FrameRepository
|
||||
[sequenceId, newFolder, length, length, prefix], cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rewrites the paths and file names of frames of one sequence after a Reorganize renamed their files (owner review 2,
|
||||
/// R7), in one transaction that locks the sequence's row first (<see cref="SequenceRepository.GetForUpdateAsync"/>'s
|
||||
/// order); with <paramref name="toVersion"/> the row's frames version becomes it, when it is still
|
||||
/// <paramref name="fromVersion"/> (the sidecar's before the renames). Frames of other sequences are never touched and
|
||||
/// repeating it is harmless. Returns the number of frames updated.
|
||||
/// </summary>
|
||||
public Task<int> RenameFilesAsync(Guid sequenceId, IReadOnlyList<FrameFileName> files, int? fromVersion = null, int? toVersion = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(files);
|
||||
return _db.InTransactionAsync(async session =>
|
||||
{
|
||||
var updated = 0;
|
||||
if (_db.Sql.IsPostgres)
|
||||
{
|
||||
// The row before its frames, as every writer of a sequence's frames; SQLite's write lock already serialises writers.
|
||||
await session.ExecuteAsync($"SELECT id FROM sequences WHERE id = $1{_db.Sql.ForUpdate}", [sequenceId], cancellationToken).ConfigureAwait(false);
|
||||
// One UPDATE … FROM (VALUES …) per batch instead of a round trip per frame.
|
||||
for (var start = 0; start < files.Count; start += Batch)
|
||||
{
|
||||
var count = Math.Min(Batch, files.Count - start);
|
||||
var sql = new StringBuilder("UPDATE frames AS f SET relative_path = v.p, file_name = v.n FROM (VALUES ");
|
||||
var args = new DbParam[count * 3 + 1];
|
||||
args[0] = sequenceId;
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var file = files[start + i];
|
||||
sql.Append(i > 0 ? ", (" : "(").Append('$').Append(3 * i + 2).Append(", $").Append(3 * i + 3).Append(", $").Append(3 * i + 4).Append(')');
|
||||
args[3 * i + 1] = file.FrameId;
|
||||
args[3 * i + 2] = file.RelativePath;
|
||||
args[3 * i + 3] = file.FileName;
|
||||
}
|
||||
sql.Append(") AS v(id, p, n) WHERE f.id = v.id AND f.sequence_id = $1");
|
||||
updated += await session.ExecuteAsync(sql.ToString(), args, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (var file in files)
|
||||
{
|
||||
updated += await session.ExecuteAsync("UPDATE frames SET relative_path = $3, file_name = $4 WHERE id = $1 AND sequence_id = $2",
|
||||
[file.FrameId, sequenceId, file.RelativePath, file.FileName], cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
if (toVersion is { } to && fromVersion is { } from)
|
||||
{
|
||||
await session.ExecuteAsync("UPDATE sequences SET frames_version = $3, updated_at = $4 WHERE id = $1 AND frames_version = $2",
|
||||
[sequenceId, from, to, DateTimeOffset.UtcNow], cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
return updated;
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes what a verify found, in one transaction: the <see cref="FrameFlags.Missing"/> and <see cref="FrameFlags.Corrupt"/>
|
||||
/// bits and new hashes. Every other flag stays as stored: decode tiers, duplicates and exclusions belong to other
|
||||
|
||||
Reference in new issue
Block a user