diff --git a/src/Titano.Data/Archiving/MassRenamer.cs b/src/Titano.Data/Archiving/MassRenamer.cs index 6846e70d..e6b1c11e 100644 --- a/src/Titano.Data/Archiving/MassRenamer.cs +++ b/src/Titano.Data/Archiving/MassRenamer.cs @@ -2,10 +2,14 @@ using Titano.Core.Archiving; using Titano.Core.Diagnostics; using Titano.Core.Localization; using Titano.Core.Model; +using Titano.Data.Repositories; namespace Titano.Data.Archiving; -/// The plan no longer matches the archive (a sequence moved or vanished since it was made). +/// +/// 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. +/// public sealed class StaleRenamePlanException(Guid sequenceId) : InvalidOperationException(Loc.L("Archive.Error.StalePlan")) { @@ -62,7 +66,8 @@ public sealed class MassRenamer private static RenameSubject Subject(Sequence s) => new(s.Id, s.Folder, s.Title, s.FirstCapture, s.CameraMake, s.CameraModel, s.Lens); /// Applies a plan; each completed step is journaled before the next starts. - /// A sequence is no longer where the plan expects it; nothing of that step was changed. + /// 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. public Task ApplyAsync(Archive archive, RenamePlan plan, IProgress? progress = null, CancellationToken cancellationToken = default) => RunAsync(archive, new RenameJournal(plan, []), resuming: false, progress, cancellationToken); @@ -85,12 +90,17 @@ public sealed class MassRenamer var completed = journal.Completed.ToHashSet(); if (!resuming) { - // A plan made before another change is refused before anything moves. + // 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; @@ -147,6 +157,7 @@ public sealed class MassRenamer { 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. @@ -170,6 +181,35 @@ public sealed class MassRenamer return false; } + /// + /// 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). + /// + /// Not resuming, and such a sequence is inside the folder. + private async Task CarriesAllInsideAsync(Archive archive, ArchivePaths paths, RenameStep step, IReadOnlyList 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; + } + + /// A sequence the index has inside the folder of one of that is not in ; null when there is none. + private async Task StrangerInsideAsync(Archive archive, IEnumerable moving, IReadOnlySet 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))); + } + /// Sidecar title, then index (folder, frames' paths); each part is idempotent so a resumed step can repeat it. private async Task RecordAsync(Archive archive, ArchivePaths paths, RenameStep step, CancellationToken cancellationToken) { diff --git a/tests/Titano.Data.Tests/Archiving/MassRenameTests.cs b/tests/Titano.Data.Tests/Archiving/MassRenameTests.cs index d15b5036..cdcee194 100644 --- a/tests/Titano.Data.Tests/Archiving/MassRenameTests.cs +++ b/tests/Titano.Data.Tests/Archiving/MassRenameTests.cs @@ -105,6 +105,57 @@ public sealed class MassRenameTests(TestContext context) Assert.True(Directory.Exists(fx.Paths.FromRelative(other.Steps[0].ToFolder))); } + [Test] + public async Task ASequenceIndexedInsideAMovingFolderAfterTheDryRunMakesThePlanStale() + { + await using var fx = await CreateAsync(context); + Photos.WriteSeries(Path.Combine(fx.Paths.Root, "trips"), Start, 2); + await fx.ScanAsync(); + var trips = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Single(); + var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, [trips.Id], "moved/{date}", null, fx.Ct); + Assert.Count(1, plan.Steps); + + // Photos copied into a subfolder and indexed by the next scan, after the dry run was shown. + Photos.WriteSeries(Path.Combine(fx.Paths.Root, "trips", "day2"), Start.AddDays(1), 2, firstSeed: 10); + await fx.ScanAsync(); + var day2 = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Single(l => l.Folder == "trips/day2"); + + var stale = await Assert.ThrowsAsync(() => fx.Service.ApplyRenameAsync(plan, null, fx.Ct)); + Assert.Equal(day2.Id, stale.SequenceId); + Assert.Empty(RenameJournal.ListPending(fx.Paths)); + Assert.SequenceEqual(["trips|trips|trips/IMG_0001.JPG,trips/IMG_0002.JPG", "trips/day2|day2|trips/day2/IMG_0001.JPG,trips/day2/IMG_0002.JPG"], + await StateAsync(fx, [trips.Id, day2.Id])); + } + + [Test] + public async Task AFolderThatGainedASequenceWhileTheRenameRanStaysWhereItIs() + { + await using var fx = await CreateAsync(context); + var ids = await PopulateAsync(fx); + var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, [ids[0], ids[1]], "renamed/{date}", null, fx.Ct); + Assert.SequenceEqual(["inbox/a", "inbox/b"], plan.Steps.Select(s => s.FromFolder)); + + // Once the first folder moved, a scan indexes photos copied into the second one. + var late = Path.Combine(fx.Paths.Root, "inbox", "b", "late"); + var progress = new SyncProgress(done => + { + if (done != 1) return; + Photos.WriteSeries(late, Start.AddDays(5), 2, firstSeed: 40); + fx.ScanAsync().GetAwaiter().GetResult(); + }); + await Assert.ThrowsAsync(() => fx.Service.ApplyRenameAsync(plan, progress, fx.Ct)); + var newcomer = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Single(l => l.Folder == "inbox/b/late"); + Assert.True(Directory.Exists(late), "the folder did not move"); + Assert.Count(1, RenameJournal.ListPending(fx.Paths).Single().Completed); + + // Resumed, the rest of the plan runs but that step is dropped: every index row still names its files. + Assert.Equal(1, await fx.Service.Renamer.ResumePendingAsync(fx.Archive, fx.Ct)); + Assert.Empty(RenameJournal.ListPending(fx.Paths)); + var state = await StateAsync(fx, [ids[0], ids[1], newcomer.Id]); + Assert.SequenceEqual(["renamed/2026-09-28", "inbox/b", "inbox/b/late"], state.Select(s => s.Split('|')[0])); + Assert.Equal(0, (await fx.ScanAsync()).Indexed); + } + /// "trips" with photos of its own, "trips/day2" inside it and "trips/day2/dawn" inside that: three nested sequences. private static async Task> NestedAsync(ArchiveFixture fx) {