A scan can index a sequence inside a folder the plan moves after the dry run was shown (photos copied into a subfolder). The folder would then move with it while its index row stayed behind. Apply now lists the index again before anything moves and under each moving step's leases just before the move, and throws StaleRenamePlanException naming the newcomer. A resumed journal drops such a step while its folder has not moved yet. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
239 lines
15 KiB
C#
239 lines
15 KiB
C#
using Titano.Core.Archiving;
|
|
using Titano.Core.Diagnostics;
|
|
using Titano.Core.Localization;
|
|
using Titano.Core.Model;
|
|
using Titano.Data.Repositories;
|
|
|
|
namespace Titano.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.
|
|
/// </summary>
|
|
public sealed class StaleRenamePlanException(Guid sequenceId)
|
|
: InvalidOperationException(Loc.L("Archive.Error.StalePlan"))
|
|
{
|
|
public Guid SequenceId { get; } = 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"/>.
|
|
/// </summary>
|
|
public sealed class MassRenamer
|
|
{
|
|
private readonly TitanoDatabase _db;
|
|
private readonly SequenceWriter _writer;
|
|
private readonly ArchiveIndexer _indexer;
|
|
|
|
internal MassRenamer(TitanoDatabase db, SequenceWriter writer, ArchiveIndexer indexer)
|
|
{
|
|
_db = db;
|
|
_writer = writer;
|
|
_indexer = indexer;
|
|
}
|
|
|
|
/// <param name="folderTemplate">New folder template (<c>{title}</c> = the new title), or null to keep folders.</param>
|
|
/// <param name="titleTemplate">New title template (<c>{title}</c> = the current title), or null to keep titles.</param>
|
|
/// <remarks>Sequences nested in a folder that moves are part of the plan (they move with it); see <see cref="RenamePlanner.Plan"/>.</remarks>
|
|
/// <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)
|
|
{
|
|
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)
|
|
{
|
|
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));
|
|
}
|
|
var nested = new List<RenameSubject>();
|
|
if (folderTemplate 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))))
|
|
{
|
|
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);
|
|
}
|
|
|
|
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>Completes renames interrupted by a crash; 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);
|
|
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)
|
|
{
|
|
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();
|
|
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)
|
|
{
|
|
if ((await _db.Sequences.GetAsync(step.SequenceId, cancellationToken).ConfigureAwait(false))?.Folder != step.FromFolder)
|
|
throw new StaleRenamePlanException(step.SequenceId);
|
|
}
|
|
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;
|
|
foreach (var step in steps)
|
|
{
|
|
if (completed.Contains(step.SequenceId)) continue;
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
// A folder that moves carries the sequences inside it: they are locked, moved and recorded with it.
|
|
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);
|
|
completed.Add(step.SequenceId);
|
|
foreach (var c in carried) completed.Add(c.SequenceId);
|
|
RenameJournal.Write(paths, journal with { Completed = [.. completed] });
|
|
progress?.Report(completed.Count);
|
|
}
|
|
RenameJournal.Delete(paths, journal.Plan.Id);
|
|
}
|
|
|
|
/// <summary>The step whose folder move carries <paramref name="carried"/>: the nearest moving folder around it (as planned).</summary>
|
|
private static RenameStep? Carrier(IReadOnlyList<RenameStep> steps, RenameStep carried) =>
|
|
steps.Where(m => !m.Carried && m.MovesFolder && RenamePlanner.IsInside(m.FromFolder, carried.FromFolder)).MaxBy(m => m.FromFolder.Length);
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </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)
|
|
{
|
|
var ids = carried.Select(c => c.SequenceId).Append(step.SequenceId).Order().ToList();
|
|
var locks = new List<IAsyncDisposable>(ids.Count);
|
|
var leases = new List<LeaseFile>(ids.Count);
|
|
try
|
|
{
|
|
foreach (var id in ids) locks.Add(await _writer.LockAsync(paths, id, cancellationToken).ConfigureAwait(false));
|
|
if (step.MovesFolder)
|
|
{
|
|
foreach (var id in ids)
|
|
{
|
|
leases.Add(await LeaseFile.AcquireAsync(paths.LocksDirectory, $"thumbs-{id:N}", _writer.Options.Owner, _writer.Options.LeaseWait,
|
|
_writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false));
|
|
}
|
|
}
|
|
// 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;
|
|
var follow = new List<RenameStep>(carried.Count);
|
|
foreach (var c in carried)
|
|
{
|
|
if (await StandsAsync(c, resuming, cancellationToken).ConfigureAwait(false)) follow.Add(c);
|
|
}
|
|
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);
|
|
}
|
|
finally
|
|
{
|
|
for (var i = leases.Count - 1; i >= 0; i--) leases[i].Dispose();
|
|
for (var i = locks.Count - 1; i >= 0; i--) await locks[i].DisposeAsync().ConfigureAwait(false);
|
|
}
|
|
}
|
|
|
|
/// <summary>The index still has the step's sequence where the plan says (or where it already took it); otherwise stale.</summary>
|
|
/// <exception cref="StaleRenamePlanException">Not resuming, and the sequence moved or vanished since the plan was made.</exception>
|
|
private async Task<bool> StandsAsync(RenameStep step, bool resuming, CancellationToken cancellationToken)
|
|
{
|
|
var row = await _db.Sequences.GetAsync(step.SequenceId, cancellationToken).ConfigureAwait(false);
|
|
if (row is not null && (row.Folder == step.FromFolder || row.Folder == step.ToFolder)) return true;
|
|
if (!resuming) throw new StaleRenamePlanException(step.SequenceId);
|
|
Log.Warning("archive", $"Rename of {step.FromFolder} dropped: the index no longer has that sequence there");
|
|
return false;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Whether every sequence the index has inside the folder of a moving step moves with it as planned, checked again under
|
|
/// the step's leases just before the folder moves. One indexed there since the dry run would move without its index
|
|
/// row following, and was never shown in the plan: the step is refused, or dropped when resuming a folder that has not
|
|
/// moved yet (a folder moved before the interruption goes on; the next scan indexes the newcomer where it ended up).
|
|
/// </summary>
|
|
/// <exception cref="StaleRenamePlanException">Not resuming, and such a sequence is inside the folder.</exception>
|
|
private async Task<bool> CarriesAllInsideAsync(Archive archive, ArchivePaths paths, RenameStep step, IReadOnlyList<RenameStep> carried, bool resuming,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
if (!step.MovesFolder) return true;
|
|
var taken = carried.Select(c => c.SequenceId).ToHashSet();
|
|
if (await StrangerInsideAsync(archive, [step], taken, cancellationToken).ConfigureAwait(false) is not { } stranger) return true;
|
|
if (!resuming) throw new StaleRenamePlanException(stranger.Id);
|
|
if (!Directory.Exists(paths.Sequence(step.FromFolder).Folder)) return true;
|
|
Log.Warning("archive", $"Rename of {step.FromFolder} dropped: {stranger.Folder} was indexed inside it after the plan was made");
|
|
return false;
|
|
}
|
|
|
|
/// <summary>A sequence the index has inside the folder of one of <paramref name="moving"/> that is not in <paramref name="taken"/>; null when there is none.</summary>
|
|
private async Task<SequenceLocation?> StrangerInsideAsync(Archive archive, IEnumerable<RenameStep> moving, IReadOnlySet<Guid> taken,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
var folders = moving.Select(s => s.FromFolder).ToList();
|
|
if (folders.Count == 0) return null;
|
|
return (await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false))
|
|
.FirstOrDefault(l => !taken.Contains(l.Id) && folders.Any(f => RenamePlanner.IsInside(f, l.Folder)));
|
|
}
|
|
|
|
/// <summary>Sidecar title, then index (folder, frames' paths); each part is idempotent so a resumed step can repeat it.</summary>
|
|
private async Task RecordAsync(Archive archive, ArchivePaths paths, RenameStep step, CancellationToken cancellationToken)
|
|
{
|
|
var sequence = paths.Sequence(step.ToFolder);
|
|
var manifest = SequenceWriter.ReadLocked(sequence, step.SequenceId);
|
|
if (manifest.Title != step.ToTitle)
|
|
{
|
|
manifest = manifest with
|
|
{
|
|
Title = step.ToTitle,
|
|
Versions = manifest.Versions with { Settings = manifest.Versions.Settings + 1 },
|
|
UpdatedAt = DateTimeOffset.UtcNow,
|
|
};
|
|
ManifestStore.WriteSequence(sequence.ManifestPath, manifest);
|
|
}
|
|
await using (var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false))
|
|
{
|
|
var existing = await tx.Sequences.GetAsync(step.SequenceId, cancellationToken).ConfigureAwait(false);
|
|
await tx.Sequences.UpsertAsync(SequenceMapping.ToSequence(manifest, archive.Id, sequence, existing), cancellationToken).ConfigureAwait(false);
|
|
if (step.MovesFolder) await tx.Frames.RebaseFolderAsync(step.SequenceId, step.FromFolder, step.ToFolder, cancellationToken).ConfigureAwait(false);
|
|
await tx.Archives.DeleteFolderStateAsync(archive.Id, step.FromFolder, cancellationToken).ConfigureAwait(false);
|
|
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
|
|
}
|
|
await _indexer.RecordStampsAsync(archive, sequence, step.SequenceId, cancellationToken).ConfigureAwait(false);
|
|
}
|
|
}
|