diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 306beda2..19f224e8 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -40,7 +40,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S | `Render` | Render plan (timing modes), preparation pass, geometry, `RenderPipeline`, self-test suite | | `Export` | Preset resolution, encoder selection with fallbacks, output naming | | `Video` (+ `Mp4`, `Avi`, `Bitstream`, `Yuv`, `Managed`) | `IVideoEncoderProvider`, MP4 muxer and inspector, AVI-MJPEG, NV12/P010, managed encoders (MJPEG-AVI, GIF, APNG, image sequences) | -| `Archiving` | Archive layout and paths, sidecars (`sequence.json`, `project.json`), scanner, index snapshot, leases, thumbnail packs, verify, adopt, rename plans (`RenamePlanner`: folder, title and file templates, `RenameTemplates`, the plan's fingerprint; `FileRenames`: a sequence's new file names; `FileRenameJournal`: two-phase renames through temporary names, `.chronos/rename-files.json`, a recovery safe to run again from wherever it stopped, a new name taken meanwhile sending that photo and its companions back to their old names or a free `_2`; `FrameCompanions`: the XMP files that follow a photo, one rule for the trash and Reorganize, matched whatever their case and each folder listed once by `FrameCompanions.Index`) | +| `Archiving` | Archive layout and paths, sidecars (`sequence.json`, `project.json`), scanner, index snapshot, leases, thumbnail packs, verify, adopt, rename plans (`RenamePlanner`: folder, title and file templates, `RenameTemplates`, the plan's fingerprint, which pins every file rename by its digest and not the frames version; `FileRenames`: a sequence's new file names; `FileRenameJournal`: two-phase renames through temporary names, `.chronos/rename-files.json`, a recovery safe to run again from wherever it stopped, a new name taken meanwhile sending that photo and its companions back together to their old names or a free `_2`, those that took their new names already with them; `FrameCompanions`: the XMP files that follow a photo, one rule for the trash and Reorganize, matched whatever their case and each folder listed once by `FrameCompanions.Index`) | | `Import` | Card scan, session detection, import plan, hash-verified copy, card eraser (re-hash before delete) | | `Naming` | Folder/file templates and tokens (folder levels scans skip escaped with `_`; `ExpandText` for titles); `FrameNaming` (the naming context and unique file name of a frame, shared by import, upload and Reorganize: the sequence's camera and lens, the first frame for folders; `UniqueNames`: `_2`, `_3`… in linear time); `TemplateRules` (what every place a template is typed or sent refuses: a folder scans skip, a lost extension, names that repeat) | | `Model` | Domain entities and enums (§5) shared by Data, Server and clients | @@ -58,7 +58,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S | `Jobs` | `JobEngine` (one job at a time; reviews the priority queue and makes a lower running job yield, requeued with its checkpoint; no history purge, the housekeeping schedule's clean-up does it), `JobPriorityQueue` (a level per job kind, the claim order, settings round trip), `IJobHandler`, `IJobHandlerProvider`, `JobContext` (progress, checkpoints, follow-up jobs that never interrupt their parent), `JobThroughput`/`JobEta` (rate and bounded time left) | | `Scheduling` | `Scheduler` (one per host: seeds the host's system schedules, claims due runs by compare-and-set, catch-up, clock changes, create/edit/reset/delete/run now as API v1 DTOs), `ScheduleRecurrence` (the in-house `every:`/`daily:`/`weekly:`/`monthly:` form, wall-clock times across DST), `ScheduleActions` (action names, parameters, availability, the archive jobs a run queues), `IScheduleHost` and `SystemSchedule` (what the server and the desktop supply), `ScheduleOutcome`, `ScheduleMapping` (model ↔ DTO) | | `Housekeeping` | `BackupJobHandler`, `CleanupJobHandler`, `ICleanupStep` with the shared steps (`CleanupSteps`: job history, audit log, trash report that never deletes); hosts add their own steps through `ArchiveServiceOptions.CleanupSteps` | -| `Archiving` | `ArchiveService` (create/adopt/open, archive settings written to `archive.json` then the index), `ArchiveIndexer` (scan, rebuild), `ArchiveIngest` (uploads and imports), `ImportService`, `ArchiveVerifier`, `ArchiveImages` (thumbnail and proxy passes, several photos at once through `OrderedWork`, which hands results back in frame order), `FrameTiers` (decode tier, `PreviewOnly`/`Undecodable` flags and preview size of frames, written to sidecar and index by the light analysis, deep analysis, renders and image passes), `GprCompanions` (the JPEG of each GoPro GPR, found in the index when an import kept it in another sequence), `ArchiveMaintenance`, `MassRenamer` (mass rename and Reorganize: the dry run reads each sidecar for a file template; each step checked under its leases before anything of it moves (where its sequences are, what is inside and at its new folder, a sidecar of a newer format, the title it was planned from, its file renames by digest at the planned frames version), then the folder, every index row (the frame and render paths follow it in one transaction), then the files under the plan's journal in `journal/` (a sequence whose files are found changed or in use there keeps their names, and the step completes); the journal keeps the tally of the whole plan, and a plan its job held (paused, cancelled or failed) is left to that job, only its half-done file renames completed at an archive open; the file renames of a step: sidecar, a sequence whose sidecar cannot be read staying as it is with every folder around it, index (`FrameRepository.RenameFilesAsync`) and the sequence's journal), `SequenceTrash` (delete into the archive's hidden trash with a dry run, restore; the folder moves back when the index step fails; lists sequence and photo entries; `SequenceTrash.Empty`: the emptying's dry run, fingerprint and erase, each entry checked against its fingerprint again under its lease), `FrameTrash` (photos of a sequence into `trash/photos` with a dry run, a journal that undoes an interrupted deletion whose entry stays unlisted until its sidecar is written, tombstones (a photo never hashed is hashed as it goes; one whose original is missing goes without a file or tombstone; a frame that stays and may be a twin is hashed, its hash kept), positions parked and placed back, proxies and thumbnails moved to follow their frames; `FrameTrash.Restore`: restore re-hashes each file and says why each kept photo stayed (`KeptReason`), under a journal of its own into the sequence that another writer settles only under the entry's lease, into a new sequence through the ingest when theirs is gone, each original staged inside its own entry and the record rewritten after each photo filed), job handlers | +| `Archiving` | `ArchiveService` (create/adopt/open, archive settings written to `archive.json` then the index), `ArchiveIndexer` (scan, rebuild), `ArchiveIngest` (uploads and imports), `ImportService`, `ArchiveVerifier`, `ArchiveImages` (thumbnail and proxy passes, several photos at once through `OrderedWork`, which hands results back in frame order), `FrameTiers` (decode tier, `PreviewOnly`/`Undecodable` flags and preview size of frames, written to sidecar and index by the light analysis, deep analysis, renders and image passes), `GprCompanions` (the JPEG of each GoPro GPR, found in the index when an import kept it in another sequence), `ArchiveMaintenance`, `MassRenamer` (mass rename and Reorganize: the dry run reads each sidecar for a file template; each step checked under its leases before anything of it moves (where its sequences are, what is inside and at its new folder, a sidecar of a newer format, the title it was planned from when it changes it or names the folder or files after it), then the folder, every index row (the frame and render paths follow it in one transaction; a sidecar that cannot be read or written then still has its row follow, and fails the step), then the files under the plan's journal in `journal/` (a sequence whose photos changed since, such as one still receiving them, or whose files are in use or have their new names taken keeps its file names, the renames being pinned by digest, and the step and the plan go on); the journal keeps the tally of the whole plan, and a plan its job held (paused, cancelled or failed) is left to that job, only its half-done file renames completed at an archive open, which completes any other plan an interruption left and tells each sequence changed; the file renames of a step: sidecar, a sequence whose sidecar cannot be read staying as it is with every folder around it, index (`FrameRepository.RenameFilesAsync`) and the sequence's journal), `SequenceTrash` (delete into the archive's hidden trash with a dry run, restore; the folder moves back when the index step fails; lists sequence and photo entries; `SequenceTrash.Empty`: the emptying's dry run, fingerprint and erase, each entry checked against its fingerprint again under its lease), `FrameTrash` (photos of a sequence into `trash/photos` with a dry run, a journal that undoes an interrupted deletion whose entry stays unlisted until its sidecar is written, tombstones (a photo never hashed is hashed as it goes; one whose original is missing goes without a file or tombstone; a frame that stays and may be a twin is hashed, its hash kept), positions parked and placed back, proxies and thumbnails moved to follow their frames; `FrameTrash.Restore`: restore re-hashes each file and says why each kept photo stayed (`KeptReason`), under a journal of its own into the sequence that another writer settles only under the entry's lease, into a new sequence through the ingest when theirs is gone, each original staged inside its own entry and the record rewritten after each photo filed), job handlers | | `Processing` | `ProcessingService`, `SequenceAnalyser`, `DeepReports` (a saved deep report while it still describes the frames), `SequenceRender`, `ProjectStore`, `ProjectBundles` (a `.chronos` file for a sequence, and the sequence a file names), `RenderNodeClient`, job handlers | | `Sync` | `SyncService` (sync table of one server: compare, link by content, settle conflicts, enqueue transfers), `SyncRules` (status, settings merge and differences, no I/O), `SyncTombstones` (photos either side removed are not offered back, a replaced photo counts as its replacement), `SyncPositions` (the settings' frame positions translated by photo to the frames of the copy they go to), `SyncLinkStore` (`sync_links`, `sync_state`), `SyncTransfers` and `SyncJobHandler` (resumable, hash-verified uploads and downloads as jobs; downloads commit through the archive ingest), `SyncAgent` (background comparison, server events, backoff, offline proxies), `ProxyCache` and `RemoteSequence` (server sequences opened with proxies), `ISyncRemote` (the server calls; `ChronosSyncRemote` over `ChronosClient`) | diff --git a/i18n/en/Archive.resx b/i18n/en/Archive.resx index 574d0b1d..682efc8a 100644 --- a/i18n/en/Archive.resx +++ b/i18n/en/Archive.resx @@ -87,10 +87,12 @@ {0} was written by a newer Chronos (format {1}).long: error sentence The archive {0} is offline.long: error sentence The archive {0} is read-only.long: error sentence - {0:N0} sequence kept its file names: a photo was in use.long: error sentence of a Reorganize job - {0:N0} sequences kept their file names: a photo was in use.long: error sentence of a Reorganize job + {0:N0} sequence kept its file names: a photo was in use or its new name was taken.long: error sentence of a Reorganize job + {0:N0} sequences kept their file names: a photo was in use or its new name was taken.long: error sentence of a Reorganize job {0:N0} sequence was not reorganized as planned: it changed after the plan.long: error sentence of a Reorganize job {0:N0} sequences were not reorganized as planned: they changed after the plan.long: error sentence of a Reorganize job + {0:N0} sequence kept its title and file names: its sequence file is from a newer Chronos.long: error sentence of a Reorganize job + {0:N0} sequences kept their titles and file names: their sequence files are from a newer Chronos.long: error sentence of a Reorganize job {0} changed after the plan was made.long: error sentence The card or folder {0} is no longer available.long: error sentence The archive changed after this plan was made.long: error sentence @@ -157,8 +159,9 @@ {0}: made {1}, reused {2}, unreadable {3}, waiting {4}long: job log line; {4} frames whose proxy this host waits for from a client or render node Proxies for the server: {0} sent, {1} not sentlong: job log line; {0} proxies sent; {1} proxies this PC could not make or the server refused Left as it was, changed after the plan: {0}long: job log line; {0} sequence title or folder - File names kept, a photo was in use: {0}long: job log line; {0} sequence title or folder + File names kept, a photo was in use or its new name was taken: {0}long: job log line; {0} sequence title or folder File names kept, photos changed after the plan: {0}long: job log line; {0} sequence title or folder + Title and file names kept, its sequence file is from a newer Chronos: {0}long: job log line; {0} sequence title or folder Title and file names kept, changed after the plan: {0}long: job log line; {0} sequence title or folder Sequences changed: {0}, files renamed: {1}long: job log line of a Reorganize; {0} sequences, {1} photos The reorganization was completed when the archive was openedlong: job log line diff --git a/i18n/it/Archive.it.resx b/i18n/it/Archive.it.resx index 939debbe..77588681 100644 --- a/i18n/it/Archive.it.resx +++ b/i18n/it/Archive.it.resx @@ -82,10 +82,12 @@ {0} è stato scritto da un Chronos più recente (formato {1}). L'archivio {0} non è raggiungibile. L'archivio {0} è di sola lettura. - {0:N0} sequenza ha mantenuto i nomi dei file: una foto era in uso. - {0:N0} sequenze hanno mantenuto i nomi dei file: una foto era in uso. + {0:N0} sequenza ha mantenuto i nomi dei file: una foto era in uso o il suo nuovo nome era occupato. + {0:N0} sequenze hanno mantenuto i nomi dei file: una foto era in uso o il suo nuovo nome era occupato. {0:N0} sequenza non è stata riorganizzata come previsto: è cambiata dopo il piano. {0:N0} sequenze non sono state riorganizzate come previsto: sono cambiate dopo il piano. + {0:N0} sequenza ha mantenuto titolo e nomi dei file: il file della sequenza è di un Chronos più recente. + {0:N0} sequenze hanno mantenuto titoli e nomi dei file: i file delle sequenze sono di un Chronos più recente. {0} è cambiato dopo la creazione del piano. La scheda o cartella {0} non è più disponibile. L'archivio è cambiato dopo la creazione del piano. @@ -152,8 +154,9 @@ {0}: create {1}, riusate {2}, illeggibili {3}, in attesa {4} Proxy per il server: {0} inviati, {1} non inviati Lasciata com'era, cambiata dopo il piano: {0} - Nomi dei file mantenuti, una foto era in uso: {0} + Nomi dei file mantenuti, una foto era in uso o il suo nuovo nome era occupato: {0} Nomi dei file mantenuti, foto cambiate dopo il piano: {0} + Titolo e nomi dei file mantenuti, il file della sequenza è di un Chronos più recente: {0} Titolo e nomi dei file mantenuti, cambiata dopo il piano: {0} Sequenze cambiate: {0}, file rinominati: {1} La riorganizzazione è stata completata all'apertura dell'archivio diff --git a/src/Chronos.Core/Archiving/FileRenameJournal.cs b/src/Chronos.Core/Archiving/FileRenameJournal.cs index 55df0543..03e80396 100644 --- a/src/Chronos.Core/Archiving/FileRenameJournal.cs +++ b/src/Chronos.Core/Archiving/FileRenameJournal.cs @@ -125,9 +125,10 @@ public sealed record FileRenameJournal(int FramesVersion, int Phase, IReadOnlyLi /// the sidecar to write, or null when it is right as it is; the journal is left in place, it once /// the result is written. Safe to run again from wherever it stopped (a failure, a crash, a sidecar that could not be /// written): once every file is at its temporary name the journal says phase 2, as does, so no file - /// that reached its new name is ever moved again. A new name something else took meanwhile is never written over: the - /// files of that frame go back to their old names, or to the first free _2, _3… of them, recorded in the - /// journal before they move, and the frame names where its photo is (logged). A file found nowhere is logged, and its + /// that reached its new name is ever moved again, but with its frame as follows. A new name something else took meanwhile + /// is never written over: all the files of that frame, its photo and companions together, go back to their old names, or + /// to the first free _2, _3… of them, recorded in the journal before they move on, and the frame names + /// where its photo is (logged). A file found nowhere is logged, and its /// frame names the new file all the same (a verify then flags it missing, as it would have at its old name). /// /// A file could not be moved (open elsewhere); the journal stays, and the next recovery goes on from there. @@ -158,10 +159,11 @@ public sealed record FileRenameJournal(int FramesVersion, int Phase, IReadOnlyLi } /// - /// The journal with a new name for every file still at its temporary name of a frame one of whose new names something - /// else took since (a file, or a folder): all the files of that frame (its photo and companions, which stay together) go - /// back to their old names, or to the first _2, _3… of the photo's old name that is free for all of them, - /// none ever a name the rename gives another file. Written before anything moves, so a recovery run again finds them. + /// The journal with a new name for every file of a frame one of whose new names something else took since (a file, or a + /// folder) while that file waits at its temporary name: all the files of that frame (its photo and companions, which stay + /// together: one that reached its new name already goes back to its temporary name first) go back to their old names, or + /// to the first _2, _3… of the photo's old name that is free for all of them, none ever a name the rename + /// gives another file. Written before any of them moves on, so a recovery run again finds them. /// private static FileRenameJournal Redirected(SequencePaths sequence, FileRenameJournal journal) { @@ -169,8 +171,11 @@ public sealed record FileRenameJournal(int FramesVersion, int Phase, IReadOnlyLi List? files = null; foreach (var frame in journal.Files.Select((f, i) => (File: f, Index: i)).GroupBy(f => f.File.FrameId)) { + var taken = frame.Where(f => Exists(sequence, f.File.Temp) && Taken(sequence, f.File.To)).Select(f => f.File.To).ToList(); + if (taken.Count == 0) continue; + // A photo whose companion's new name was taken never stays apart from it at its own new name, nor the other way round. + foreach (var (file, _) in frame.Where(f => !Exists(sequence, f.File.Temp) && Exists(sequence, f.File.To))) Move(sequence, file.To, file.Temp); var waiting = frame.Where(f => Exists(sequence, f.File.Temp)).ToList(); - if (!waiting.Any(f => Taken(sequence, f.File.To))) continue; var photo = frame.FirstOrDefault(f => !f.File.Companion).File ?? frame.First().File; List names; for (var n = 1; ; n++) @@ -185,7 +190,7 @@ public sealed record FileRenameJournal(int FramesVersion, int Phase, IReadOnlyLi claimed.Add(names[i]); files[index] = file with { To = names[i] }; } - Log.Error("archive", $"{string.Join(", ", waiting.Where(f => Taken(sequence, f.File.To)).Select(f => sequence.ArchiveRelative(f.File.To)))} taken while " + Log.Error("archive", $"{string.Join(", ", taken.Select(sequence.ArchiveRelative))} taken while " + $"a rename was interrupted; the files of that photo go to {string.Join(", ", names.Select(sequence.ArchiveRelative))}"); } if (files is null) return journal; diff --git a/src/Chronos.Core/Archiving/MassRename.cs b/src/Chronos.Core/Archiving/MassRename.cs index ced7b6e2..04aa0564 100644 --- a/src/Chronos.Core/Archiving/MassRename.cs +++ b/src/Chronos.Core/Archiving/MassRename.cs @@ -44,7 +44,19 @@ public sealed record RenameStep(Guid SequenceId, string FromFolder, string ToFol /// Whether applying the step changes anything: the folder, the title or file names. public bool Changes => MovesFolder || Retitles || FileChanges > 0; - /// The sidecar's frames version the file names were planned at; 0 when no file gets a new name. + /// + /// The new folder or file names come from the sequence's title (the folder or file template uses {title}): a title + /// edited since the plan would leave them named after the old one. + /// + public bool NamedByTitle { get; init; } + + /// Whether what the step changes depends on the sequence's title: it changes it, or names the folder or files after it. + public bool UsesTitle => Retitles || NamedByTitle; + + /// + /// The sidecar's frames version the file names were planned at; 0 when no file gets a new name. What the apply checks the + /// files by only in a plan journaled without . + /// public int FramesVersion { get; init; } /// Frames whose file gets a new name (their companions follow them). @@ -123,15 +135,18 @@ public sealed record RenamePlan(Guid Id, Guid ArchiveId, IReadOnlyList Subjects { get; init; } = []; /// - /// A digest of what the plan changes (its steps in order, as a dry run shows them, and the file template), the same for - /// two plans of the same archive state: what a confirmation sends back so the change made is the one that was shown. + /// A digest of what the plan changes (its steps in order, as a dry run shows them, every file rename by its digest, and + /// the file template), the same for two plans of the same archive state: what a confirmation sends back so the change + /// made is the one that was shown. The frames version is not part of it: photos a sequence received since under the names + /// the plan gives them (an upload filed with the same template) leave the plan as it was, and the apply renames the files + /// only while they rename exactly as planned (). /// public string Fingerprint() { var text = new StringBuilder(FileTemplate).Append('\n'); foreach (var s in Steps) { - text.Append(CultureInfo.InvariantCulture, $"{s.SequenceId:N}|{s.FromFolder}|{s.ToFolder}|{s.FromTitle}|{s.ToTitle}|{s.Carried}|{s.FramesVersion}|{s.FileChanges}|{s.FileDigest}|"); + text.Append(CultureInfo.InvariantCulture, $"{s.SequenceId:N}|{s.FromFolder}|{s.ToFolder}|{s.FromTitle}|{s.ToTitle}|{s.Carried}|{s.FileChanges}|{s.FileDigest}|"); foreach (var sample in s.FileSamples) text.Append(sample.From).Append('>').Append(sample.To).Append(';'); foreach (var blocked in s.Blocked) text.Append(CultureInfo.InvariantCulture, $"{blocked.Reason}:{blocked.Frames};"); text.Append('\n'); @@ -142,9 +157,10 @@ public sealed record RenamePlan(Guid Id, Guid ArchiveId, IReadOnlyList /// What the completed steps of a plan did, over every run that applied them (): the -/// 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 (), their file names kept (), their title and file -/// names kept (), or their file names kept because a photo was in use (). +/// 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 (), their file names kept () or their title and file +/// names kept (); their file names kept because a photo was in use or a new name was taken +/// (); their title and file names kept because a newer Chronos wrote their sidecar (). /// public sealed record RenameTally { @@ -154,6 +170,7 @@ public sealed record RenameTally public IReadOnlyList FilesKept { get; init; } = []; public IReadOnlyList TitlesKept { get; init; } = []; public IReadOnlyList FilesBusy { get; init; } = []; + public IReadOnlyList Newer { get; init; } = []; } /// A plan being applied, with the steps already completed; lets an interrupted rename resume (BRIEF §7). @@ -204,7 +221,8 @@ public static class RenamePlanner /// name (). A target folder that is any current sequence folder, exists on disk or /// was given to an earlier subject (whatever its case) gets " (2)", " (3)"…. With every /// subject's frames get their names from it as filing names them (, with the new title), - /// counted and sampled in its step, and the frames that keep their names are listed there with the reason. A subject + /// counted and sampled in its step, and the frames that keep their names are listed there with the reason; a step whose + /// new folder or file names come from {title} says so (). A subject /// whose sidecar could not be read (, or no for a /// file template) stays as it is, listed with the reason, and so does the folder of every subject it is inside. Null /// templates leave that part unchanged; subjects without a change produce no step, unless frames of theirs keep their @@ -220,6 +238,7 @@ public static class RenamePlanner var folder = folderTemplate is null ? null : PathTemplate.Parse(folderTemplate); var title = titleTemplate is null ? null : PathTemplate.Parse(titleTemplate); var file = fileTemplate is null ? null : PathTemplate.Parse(fileTemplate); + bool folderByTitle = folder?.Uses("title") == true, filesByTitle = file?.Uses("title") == true; var taken = occupied.ToList(); var claimed = new HashSet(taken, StringComparer.OrdinalIgnoreCase); // The folders given in this plan so far: Kept never gives one twice (two folders that differ only in case). @@ -256,7 +275,8 @@ public static class RenamePlanner } } var step = new RenameStep(s.SequenceId, s.Folder, newFolder, s.Title, newTitle); - own.Add(file is null ? step : WithFiles(step, s.Files!, file, newTitle)); + if (file is not null) step = WithFiles(step, s.Files!, file, newTitle); + own.Add(step with { NamedByTitle = (folderByTitle && step.MovesFolder) || (filesByTitle && step.FileChanges > 0) }); } var moving = own.Where(s => s.MovesFolder).ToList(); diff --git a/src/Chronos.Core/Naming/PathTemplate.cs b/src/Chronos.Core/Naming/PathTemplate.cs index fb55a0a1..7fa9c1dd 100644 --- a/src/Chronos.Core/Naming/PathTemplate.cs +++ b/src/Chronos.Core/Naming/PathTemplate.cs @@ -48,6 +48,9 @@ public sealed class PathTemplate public bool IsValid => Errors.Count == 0; + /// Whether the template holds (title for {title}), whatever its case or format. + public bool Uses(string token) => _parts.Any(p => p.IsToken && string.Equals(p.Text, token, StringComparison.OrdinalIgnoreCase)); + /// Parses a template; '/' separates folder levels (only meaningful for folder templates). public static PathTemplate Parse(string template) { diff --git a/src/Chronos.Data/Archiving/ArchiveService.cs b/src/Chronos.Data/Archiving/ArchiveService.cs index 77dd9625..df44a6df 100644 --- a/src/Chronos.Data/Archiving/ArchiveService.cs +++ b/src/Chronos.Data/Archiving/ArchiveService.cs @@ -128,7 +128,8 @@ public sealed class ArchiveService : IJobHandlerProvider /// /// Registers an existing archive (or relinks a moved one: same id, new root) and completes renames a crash - /// interrupted. An offline archive is registered as it was last seen. + /// interrupted (each sequence they change is told to ); one that + /// cannot be completed yet is logged and waits for the next open. An offline archive is registered as it was last seen. /// public async Task OpenAsync(string root, CancellationToken cancellationToken = default) { @@ -139,9 +140,9 @@ public sealed class ArchiveService : IJobHandlerProvider { await Renamer.ResumePendingAsync(archive, cancellationToken).ConfigureAwait(false); } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException) + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or NewerFormatException) { - // The journal stays; the next open tries again. The archive itself is usable meanwhile. + // The journal stays; the next open tries again. The archive itself is usable meanwhile (a server starts all the same). Log.Warning("archive", $"Resuming an interrupted rename in {paths.Root} failed", ex); } return archive; @@ -595,8 +596,8 @@ public static class ArchiveJobs ArgumentNullException.ThrowIfNull(plan); ArgumentNullException.ThrowIfNull(templates); // The sequences that have a step, in the order the plan was made for: the others change nothing, now or when planned again. - var steps = plan.Steps.ToDictionary(s => s.SequenceId); - var sequences = plan.Subjects.Where(steps.ContainsKey).Select(id => new MoveSequence(id, steps[id].FramesVersion)).ToList(); + var steps = plan.Steps.Select(s => s.SequenceId).ToHashSet(); + var sequences = plan.Subjects.Where(steps.Contains).Select(id => new MoveSequence(id)).ToList(); return new(JobKind.Move, [archive.Id], archive.Name, Json(new MoveJobParameters(templates.Folder, templates.File, templates.Title, sequences, plan.Fingerprint()), ArchiveJobJson.Default.MoveJobParameters), JobPriority.User); diff --git a/src/Chronos.Data/Archiving/Jobs/ArchiveJobParameters.cs b/src/Chronos.Data/Archiving/Jobs/ArchiveJobParameters.cs index 2263938c..74aa2437 100644 --- a/src/Chronos.Data/Archiving/Jobs/ArchiveJobParameters.cs +++ b/src/Chronos.Data/Archiving/Jobs/ArchiveJobParameters.cs @@ -42,14 +42,14 @@ public sealed record EmptyTrashItem(string Name, string Fingerprint); /// /// (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 (). -/// No file list: the job plans again and refuses when the plan is no longer the one confirmed. +/// the sequences the confirmed plan changes in the order it was made for, and the plan's fingerprint +/// (, which pins every file rename by its digest). No file list: the job +/// plans again and refuses when the plan is no longer the one confirmed. /// public sealed record MoveJobParameters(string? FolderTemplate, string? FileTemplate, string? TitleTemplate, IReadOnlyList Sequences, string Fingerprint); -/// A sequence of a and the frames version its file names were planned at. -public sealed record MoveSequence(Guid Id, int FramesVersion); +/// A sequence of a (a job queued by an earlier build also names a frames version, which is ignored). +public sealed record MoveSequence(Guid Id); /// A job ready to enqueue. public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList Targets, string? Label, string? ParametersJson, JobPriority Priority); diff --git a/src/Chronos.Data/Archiving/Jobs/MoveJobHandler.cs b/src/Chronos.Data/Archiving/Jobs/MoveJobHandler.cs index 3a77d7a8..bf074529 100644 --- a/src/Chronos.Data/Archiving/Jobs/MoveJobHandler.cs +++ b/src/Chronos.Data/Archiving/Jobs/MoveJobHandler.cs @@ -10,22 +10,24 @@ namespace Chronos.Data.Archiving.Jobs; /// /// : a Reorganize (owner review 2, R7; BRIEF §12.5) of existing sequences with new folder, file /// and title templates (). 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; -/// otherwise, nothing changed; a sequence of it gone since is named in the log), -/// through , whose journal makes every step resumable. Progress counts the plan's steps -/// (sequences); checkpoint: plan:<id> once the plan's journal is written. Paused, cancelled or failed, the job -/// stops between two sequences and holds the plan (), which an archive open then leaves to it -/// (completing only file renames a step left half-way); resumed or retried, it completes the rest when it still fits. A -/// plan whose journal is gone completed meanwhile (at an archive open). Sequences left as they were, or that kept their -/// title or file names, because they changed after the plan or a photo was in use are logged and fail the job at the end, -/// after the others changed. Each sequence changed is told to -/// () as soon as its step is journaled, so a pause or a failure later never keeps it untold; the log -/// counts the whole plan, over every run of the job. +/// when it is still the one confirmed (its fingerprint, which pins every file rename; +/// otherwise, nothing changed; a sequence of it gone since is named in the log), through , whose +/// journal makes every step resumable. Progress counts the plan's steps (sequences); checkpoint: plan:<id> once +/// the plan's journal is written. Paused, cancelled or failed, the job stops between two sequences and holds the plan +/// (), 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 () 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. /// internal sealed class MoveJobHandler(ChronosDatabase db, MassRenamer renamer, Func? sequenceChanged) : IJobHandler { /// The change a Reorganize tells about a sequence (a server's sequenceChanged event). - public const string Change = "reorganized"; + public const string Change = MassRenamer.Change; private const string Prefix = "plan:"; @@ -83,6 +85,7 @@ internal sealed class MoveJobHandler(ChronosDatabase db, MassRenamer renamer, Fu LogDone(context, plan, result); var kept = result.Dropped.Count + result.FilesKept.Count + result.TitlesKept.Count; if (kept > 0) throw new InvalidOperationException(Loc.Plural("Archive.Error.ReorganizeKept", kept)); + if (result.Newer.Count > 0) throw new InvalidOperationException(Loc.Plural("Archive.Error.ReorganizeNewer", result.Newer.Count)); if (result.FilesBusy.Count > 0) throw new InvalidOperationException(Loc.Plural("Archive.Error.ReorganizeBusy", result.FilesBusy.Count)); } @@ -114,7 +117,7 @@ internal sealed class MoveJobHandler(ChronosDatabase db, MassRenamer renamer, Fu private async ValueTask StepDoneAsync(JobContext context, Guid planId, int done, int total, IReadOnlyList changed) { await context.CheckpointAsync(Checkpoint(planId), done, total).ConfigureAwait(false); - await TellAsync(changed).ConfigureAwait(false); + await MassRenamer.TellAsync(sequenceChanged, changed).ConfigureAwait(false); } /// Holds the plan of a failed run and logs what its completed steps did; a hold that cannot be written is logged. @@ -139,33 +142,16 @@ internal sealed class MoveJobHandler(ChronosDatabase db, MassRenamer renamer, Fu foreach (var id in result.Dropped) context.Log(Loc.L("Archive.Log.ReorganizeDropped", Name(plan, id))); foreach (var id in result.TitlesKept) context.Log(Loc.L("Archive.Log.ReorganizeTitleKept", Name(plan, id))); foreach (var id in result.FilesKept) context.Log(Loc.L("Archive.Log.ReorganizeFilesKept", Name(plan, id))); + foreach (var id in result.Newer) context.Log(Loc.L("Archive.Log.ReorganizeNewerKept", Name(plan, id))); foreach (var id in result.FilesBusy) context.Log(Loc.L("Archive.Log.ReorganizeFilesBusy", Name(plan, id))); } - /// Whether the plan made now is the one confirmed: the same fingerprint, and the frames versions its file names were planned at. - 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); - } - - /// Tells each sequence changed; a failure is logged, never passed on to the job. - private async Task TellAsync(IReadOnlyList 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); - } - } - } + /// + /// Whether the plan made now is the one confirmed: the same fingerprint, which pins every file rename by its digest + /// (photos a sequence received since under the names the plan leaves them change nothing of it). + /// + private static bool IsConfirmed(RenamePlan plan, MoveJobParameters parameters) => + string.Equals(plan.Fingerprint(), parameters.Fingerprint, StringComparison.Ordinal); private static int Steps(RenamePlan plan) => plan.Steps.Count(s => s.Changes); diff --git a/src/Chronos.Data/Archiving/MassRenamer.cs b/src/Chronos.Data/Archiving/MassRenamer.cs index 7ffa5b5e..babda93d 100644 --- a/src/Chronos.Data/Archiving/MassRenamer.cs +++ b/src/Chronos.Data/Archiving/MassRenamer.cs @@ -1,3 +1,4 @@ +using System.Runtime.ExceptionServices; using Chronos.Core.Archiving; using Chronos.Core.Diagnostics; using Chronos.Core.Localization; @@ -8,9 +9,9 @@ using Chronos.Data.Repositories; namespace Chronos.Data.Archiving; /// -/// The plan no longer matches the archive: a sequence moved or vanished since it was made, one was indexed inside a -/// folder the plan moves, something took a folder it moves one into, a title it changes was edited, or the photos of a -/// sequence whose files it renames changed. +/// The plan no longer matches the archive: planned again it is another (a job's confirmed plan), a sequence moved or +/// vanished since it was made, one was indexed inside a folder the plan moves, something took a folder it moves one into, +/// or a title it changes, or names a folder or files after, was edited. /// public sealed class StaleRenamePlanException(Guid sequenceId) : InvalidOperationException(Loc.L("Archive.Error.StalePlan")) @@ -22,18 +23,21 @@ public sealed class StaleRenamePlanException(Guid sequenceId) /// What applying a plan did, over every run that applied it: the sequences changed (in the order of the plan), the frames /// whose files got a new name, and the sequences not changed as planned: left as they were because they changed since the /// plan (, only when resuming), whose files kept their names because their photos changed since -/// (; their folder and title changed), whose title and file names stayed because their title was -/// edited since or their sidecar is of a newer format (, only when resuming; their folder moved), -/// and whose files kept their names because a photo was in use (; their folder and title changed). +/// (, a sequence still receiving photos among them; their folder and title changed), whose title and +/// file names stayed because their title was edited since (, only when resuming; their folder +/// moved), whose files kept their names because a photo was in use or a new name was taken (; their +/// folder and title changed), and whose title and file names stayed because a newer Chronos wrote their sidecar since +/// (, only when resuming; their folder moved, or, planned a new title, they stayed as they were when it +/// had not moved yet). /// public sealed record RenameResult(IReadOnlyList Changed, int Files, IReadOnlyList Dropped, IReadOnlyList FilesKept, - IReadOnlyList TitlesKept, IReadOnlyList FilesBusy) + IReadOnlyList TitlesKept, IReadOnlyList FilesBusy, IReadOnlyList Newer) { /// The result a plan's journal records for its completed steps (). public static RenameResult Of(RenameTally tally) { ArgumentNullException.ThrowIfNull(tally); - return new(tally.Changed, tally.Files, tally.Dropped, tally.FilesKept, tally.TitlesKept, tally.FilesBusy); + return new(tally.Changed, tally.Files, tally.Dropped, tally.FilesKept, tally.TitlesKept, tally.FilesBusy, tally.Newer); } } @@ -47,6 +51,9 @@ public sealed record RenameResult(IReadOnlyList Changed, int Files, IReadO /// public sealed class MassRenamer { + /// The change a Reorganize tells about a sequence it changed (a server's sequenceChanged event). + public const string Change = "reorganized"; + private readonly ChronosDatabase _db; private readonly SequenceWriter _writer; private readonly ArchiveIndexer _indexer; @@ -64,11 +71,14 @@ public sealed class MassRenamer /// As planned. Whole, - /// Its photos changed since the plan (or its sidecar is of a newer format): its folder and title change, its files keep their names. + /// Its photos changed since the plan (photos added, gone, hashed or copied in): its folder and title change, its files keep their names. Files, - /// Its title was edited since the plan (or its sidecar is of a newer format): its title and file names stay. + /// Its title was edited since the plan: its title and file names stay. Title, + + /// Its sidecar is of a newer format, which is never rewritten (only when resuming): its title and file names stay. + Newer, } /// New folder template ({title} = the new title), or null to keep folders. @@ -144,16 +154,24 @@ public sealed class MassRenamer return Subject(sequence) with { Unreadable = true }; } - /// Applies a plan; each completed step is journaled before the next starts. + /// + /// 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 (), its + /// folder and title change as planned, and the steps after it go on. + /// /// A sequence is no longer where the plan expects it, a folder that moves holds - /// a sequence the plan does not take along, something took a folder the plan moves one into, a title it changes was - /// edited, or the photos of a sequence whose files it renames changed; nothing of that step was changed (each is - /// checked under the step's leases before anything of it moves), the steps before it were. + /// a sequence the plan does not take along, something took a folder the plan moves one into, or a title it changes, or + /// names a folder or files after, was edited; nothing of that step was changed (each is checked under the step's leases + /// before anything of it moves), the steps before it were. /// A sequence whose title or file names the plan changes has a sidecar of a newer /// format, which this build never rewrites; nothing of that step was changed. /// A folder could not be moved, or () a sequence is - /// busy, or holds a restore from the trash whose entry is busy and not settled yet; nothing of that step changed. A - /// file that could not be renamed (open elsewhere) does not fail the step: the sequence keeps its file names + /// busy, or holds a restore from the trash whose entry is busy and not settled yet; nothing of that step changed. Once + /// the folder of a step moved, a sidecar of the step that cannot be read or written (this, + /// or ) fails the step only after every index row of the step followed the folder; its + /// title and file names wait for a retry. So does a file that could neither take its new name nor go back, when the + /// sequence's journal cannot complete the renames at once either: its next writer does. A file that could not be + /// renamed (open elsewhere, or its new name taken) does not fail the step: the sequence keeps its file names /// (). public Task ApplyAsync(Archive archive, RenamePlan plan, IProgress? progress = null, CancellationToken cancellationToken = default) => ApplyAsync(archive, plan, null, progress is null ? null : (n, _) => @@ -202,9 +220,10 @@ public sealed class MassRenamer } /// - /// Completes renames interrupted by a crash (not those their job held); returns how many plans were resumed. The file - /// renames a held plan's step left half-way are completed all the same (), so no photo - /// waits at a temporary name for that job. + /// Completes renames interrupted by a crash, a yield to another job or a host that stopped (not those their job held); + /// returns how many plans were resumed. Each sequence a resumed step changed is told, as its job would have + /// (, ). The file renames a held plan's step left + /// half-way are completed all the same (), so no photo waits at a temporary name for that job. /// public async Task ResumePendingAsync(Archive archive, CancellationToken cancellationToken = default) { @@ -212,10 +231,34 @@ public sealed class MassRenamer var journals = RenameJournal.ListPending(paths).Where(j => j.Plan.ArchiveId == archive.Id).ToList(); foreach (var held in journals.Where(j => j.Held)) await SettleFilesAsync(paths, held, cancellationToken).ConfigureAwait(false); var pending = journals.Where(j => !j.Held).ToList(); - foreach (var journal in pending) await RunAsync(archive, journal, resuming: true, null, null, cancellationToken).ConfigureAwait(false); + foreach (var journal in pending) + { + await RunAsync(archive, journal, resuming: true, null, (_, changed) => TellAsync(_writer.Options.SequenceChanged, changed), cancellationToken) + .ConfigureAwait(false); + } return pending.Count; } + /// + /// Tells (null: no one) each sequence of a Reorganize + /// changed (); a failure is logged, never passed on. + /// + internal static async ValueTask TellAsync(Func? sequenceChanged, IReadOnlyList 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); + } + } + } + /// /// Completes, each under its sequence's lease, the file renames a crash or a failure left in the steps of a plan that are /// not completed (: the files go on to their new names and the sidecar names them; @@ -296,26 +339,26 @@ public sealed class MassRenamer } /// - /// A plan made before another change is refused before anything moves: a sequence moved, a title it changes was edited, - /// one was indexed inside a folder that moves (a scan adopted a subfolder copied in since the dry run), something took a - /// folder it moves one into (), the photos of a sequence whose files it renames changed - /// (), or a sidecar it rewrites is of a newer format. A step a failed run left half-way (its - /// folder at its new place) still fits. Read without the leases, each step checks the same again under its own - /// (), so a held plan resumed by its job either fits here or is given up. + /// A plan made before another change is refused before anything moves: a sequence moved, a title it changes or names a + /// folder or files after was edited, one was indexed inside a folder that moves (a scan adopted a subfolder copied in + /// since the dry run), something took a folder it moves one into (), or a sidecar it rewrites is + /// of a newer format. A step a failed run left half-way (its folder at its new place) still fits. Photos changed since + /// (a sequence still receiving them) refuse nothing: under its leases that step keeps their names. Read without the + /// leases, each step checks the same again under its own (), so a held plan resumed by its job + /// either fits here or is given up. /// /// A sidecar the plan rewrites is of a newer format. private async Task RefuseStaleAsync(Archive archive, ArchivePaths paths, RenamePlan plan, IReadOnlyList remaining, CancellationToken cancellationToken) { var locations = await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false); - var template = plan.FileTemplate is null ? null : PathTemplate.Parse(plan.FileTemplate); foreach (var step in remaining) { var row = await _db.Sequences.GetAsync(step.SequenceId, cancellationToken).ConfigureAwait(false); - if (row is null || (row.Folder != step.FromFolder && row.Folder != step.ToFolder) || (step.Retitles && !Planned(step, row.Title)) + if (row is null || (row.Folder != step.FromFolder && row.Folder != step.ToFolder) || (step.UsesTitle && !Planned(step, row.Title)) || (!step.Carried && TargetTaken(paths, step, locations))) throw new StaleRenamePlanException(step.SequenceId); - var files = template is not null && step.FileChanges > 0; - if (!step.Retitles && !files) continue; + var files = plan.FileTemplate is not null && step.FileChanges > 0; + if (!step.UsesTitle && !files) continue; // A sidecar that cannot be read refuses file renames planned from it; a title alone fails under the step's lease, with its reason. var sequence = Where(paths, step); if (ReadSidecar(sequence, step.SequenceId) is not { } manifest) @@ -323,9 +366,9 @@ public sealed class MassRenamer if (files) throw new StaleRenamePlanException(step.SequenceId); continue; } - if (manifest.SchemaVersion > SequenceManifest.CurrentSchemaVersion) throw new NewerFormatException(sequence.ManifestPath, manifest.SchemaVersion); - if ((step.Retitles && !TitleStands(step, row, manifest)) || (files && !FilesStand(sequence, template!, step, manifest))) - throw new StaleRenamePlanException(step.SequenceId); + if ((step.Retitles || files) && manifest.SchemaVersion > SequenceManifest.CurrentSchemaVersion) + throw new NewerFormatException(sequence.ManifestPath, manifest.SchemaVersion); + if (step.UsesTitle && !TitleStands(step, row, manifest)) throw new StaleRenamePlanException(step.SequenceId); } var planned = plan.Steps.Select(s => s.SequenceId).ToHashSet(); if (StrangerInside(locations, remaining.Where(s => s.MovesFolder && !s.Carried), planned) is { } stranger) @@ -366,9 +409,10 @@ public sealed class MassRenamer /// in). No writer of a carried sequence (ingest, an editor save, a thumbnail pass) works in the folder while it moves or /// its files are renamed, or before its index row follows. Whatever can refuse the step is checked under the leases /// before anything of it moves (where its sequences are, what is inside and at its new folder, then each sidecar, - /// settled: ). Then the folder moves, every index row follows it, and only then are the files - /// renamed; a sequence whose files are found changed or in use there keeps its file names, and the step goes to its - /// end whatever the caller cancels. + /// settled: ; 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. /// /// A step whose sequence the index no longer has where the plan says, or that no longer fits it, /// is dropped (or keeps what no longer fits) instead of failing the rename: its sidecar still carries the id, so the @@ -411,23 +455,41 @@ public sealed class MassRenamer } var fits = new List<(RenameStep Step, Fit Fit)>(follow.Count + 1); foreach (var s in follow.Prepend(step)) fits.Add((s, await FitAsync(paths, fileTemplate, s, Settle(paths, s), resuming, cancellationToken).ConfigureAwait(false))); - // Its title no longer fits while nothing of it moved: it stays as it was, with the sequences it would carry. - if (fits[0].Fit == Fit.Title && !Moved(paths, step)) + // Its title no longer fits (edited since, or planned anew in a sidecar of a newer format) while nothing of it moved: + // it stays as it was, with the sequences it would carry. + var first = fits[0].Fit; + if ((first == Fit.Title || (first == Fit.Newer && step.Retitles)) && !Moved(paths, step)) { - result.Dropped.Add(step.SequenceId); + (first == Fit.Newer ? result.Newer : result.Dropped).Add(step.SequenceId); result.Dropped.AddRange(follow.Select(c => c.SequenceId)); return; } RenamePlanner.MoveFolder(paths, step); - // Every index row follows the folder before any file is renamed, so nothing below can leave one behind it. - foreach (var (s, fit) in fits) await RecordAsync(archive, paths, s, s.Retitles && fit != Fit.Title, CancellationToken.None).ConfigureAwait(false); + // Every index row follows the folder before any file is renamed, so nothing below can leave one behind it: a + // sequence whose sidecar cannot be read or written now has its row follow all the same, and fails the step once + // every other row did. + ExceptionDispatchInfo? unrecorded = null; + foreach (var (s, fit) in fits) + { + try + { + await RecordAsync(archive, paths, s, s.Retitles && TakesTitle(fit), CancellationToken.None).ConfigureAwait(false); + } + catch (Exception ex) when (step.MovesFolder && ex is IOException or UnauthorizedAccessException or InvalidDataException or NewerFormatException) + { + Log.Warning("archive", $"{s.ToFolder} could not be recorded after its folder moved; its index row followed it", ex); + unrecorded ??= ExceptionDispatchInfo.Capture(ex); + } + } + unrecorded?.Throw(); foreach (var (s, fit) in fits) { var renamed = fit == Fit.Whole && fileTemplate is not null && await RenameFilesAsync(archive, paths, fileTemplate, s, result, CancellationToken.None).ConfigureAwait(false); if (fit == Fit.Title) result.TitlesKept.Add(s.SequenceId); else if (fit == Fit.Files) result.FilesKept.Add(s.SequenceId); - if (s.MovesFolder || (s.Retitles && fit != Fit.Title) || renamed) result.Changed.Add(s.SequenceId); + else if (fit == Fit.Newer) result.Newer.Add(s.SequenceId); + if (s.MovesFolder || (s.Retitles && TakesTitle(fit)) || renamed) result.Changed.Add(s.SequenceId); } } finally @@ -457,11 +519,13 @@ public sealed class MassRenamer /// /// How far a sequence of a step still fits the plan, under the step's leases with its sidecar settled /// () 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 (), and the files are renamed only as the - /// plan renames them (). When not resuming, what no longer fits refuses the step. + /// a title edited since the plan is never written over nor are names given from the old one (), + /// and the files are renamed only as the plan renames them (). 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. /// /// Not resuming, and the step would rewrite a sidecar of a newer format. - /// Not resuming, and its title or photos changed since the plan. + /// Not resuming, and its title was edited since the plan. private async Task FitAsync(ArchivePaths paths, string? fileTemplate, RenameStep step, SequenceManifest manifest, bool resuming, CancellationToken cancellationToken) { @@ -471,9 +535,9 @@ public sealed class MassRenamer { if (!resuming) throw new NewerFormatException(sequence.ManifestPath, manifest.SchemaVersion); Log.Warning("archive", $"{sequence.RelativeFolder} keeps its title and file names: its sidecar was written by a newer Chronos"); - return step.Retitles ? Fit.Title : Fit.Files; + return Fit.Newer; } - if (step.Retitles && await _db.Sequences.GetAsync(step.SequenceId, cancellationToken).ConfigureAwait(false) is { } row && !TitleStands(step, row, manifest)) + if (step.UsesTitle && await _db.Sequences.GetAsync(step.SequenceId, cancellationToken).ConfigureAwait(false) is { } row && !TitleStands(step, row, manifest)) { if (!resuming) throw new StaleRenamePlanException(step.SequenceId); Log.Warning("archive", $"{sequence.RelativeFolder} keeps its title and file names: its title was edited after the plan was made"); @@ -481,13 +545,15 @@ public sealed class MassRenamer } if (files && !FilesStand(sequence, PathTemplate.Parse(fileTemplate!), step, manifest)) { - if (!resuming) throw new StaleRenamePlanException(step.SequenceId); Log.Warning("archive", $"The files of {sequence.RelativeFolder} keep their names: its photos changed after the plan was made"); return Fit.Files; } return Fit.Whole; } + /// Whether a sequence of a step takes the title the plan gives it: not when its title was edited since, nor in a sidecar of a newer format. + private static bool TakesTitle(Fit fit) => fit is Fit.Whole or Fit.Files; + /// /// Whether a sequence's title is still one the plan knows (the one it was made from, or the one it gives, which an /// interrupted run may have recorded): the index's, and the sidecar's unless the index is ahead of it (an edit only the @@ -501,9 +567,9 @@ public sealed class MassRenamer /// /// Whether the files of a step's sequence still rename as planned: planned again from and the - /// files beside its frames, they rename exactly the files the plan renamed () at its - /// frames version, or none is left to rename (an interrupted run renamed them). A photo hashed, back or added since, - /// or a file copied in beside them, would give other names than the dry run showed. + /// files beside its frames, they rename exactly the files the plan renamed (), or none is left to + /// rename (an interrupted run renamed them). A photo hashed, gone or added since where the plan would rename it, or a + /// file copied in beside them, would give other names than the dry run showed. /// private static bool FilesStand(SequencePaths sequence, PathTemplate template, RenameStep step, SequenceManifest manifest) { @@ -511,8 +577,13 @@ public sealed class MassRenamer return plan.Moves.Count == 0 || Matches(step, plan, manifest); } + /// + /// Whether file renames planned again are exactly the plan's: every move the same (), + /// whatever photos the sequence received since under the names the plan leaves them (an upload filed with the same + /// template), which only raised its frames version; a plan journaled without a digest, at the frames version it was made at. + /// private static bool Matches(RenameStep step, FileRenamePlan plan, SequenceManifest manifest) => - manifest.Versions.Frames == step.FramesVersion && (step.FileDigest is null || string.Equals(step.FileDigest, plan.Digest(), StringComparison.Ordinal)); + step.FileDigest is { } digest ? string.Equals(digest, plan.Digest(), StringComparison.Ordinal) : manifest.Versions.Frames == step.FramesVersion; /// The index still has the step's sequence where the plan says (or where it already took it); otherwise stale. /// Not resuming, and the sequence moved or vanished since the plan was made. @@ -584,48 +655,62 @@ public sealed class MassRenamer /// committed meanwhile stays, and frames another process listed in the sidecar are left to the next scan, for which /// the folder keeps no stamps unless the index held it as it was /// (). A step - /// that only renames files, or keeps its title, has nothing to record here. + /// that only renames files, or keeps its title, has nothing to record here. A moved folder whose sidecar cannot be read + /// or written now still has its index row follow it (its title left as it was, no stamps for the next scan), and the + /// failure is thrown. /// /// Whether the step's title is written (false: the title stays, edited since the plan or in a sidecar of a newer format). private async Task RecordAsync(Archive archive, ArchivePaths paths, RenameStep step, bool retitle, CancellationToken cancellationToken) { if (!step.MovesFolder && !retitle) return; var sequence = paths.Sequence(step.ToFolder); - var manifest = SequenceWriter.ReadLocked(sequence, step.SequenceId); - // The folder moved with its files' stamps, which the index recorded at its old place. - var inStep = await _indexer.InStepAsync(archive, step.FromFolder, sequence, manifest, cancellationToken).ConfigureAwait(false); - if (retitle && manifest.Title != step.ToTitle) + bool inStep; + try { - manifest = manifest with + var manifest = SequenceWriter.ReadLocked(sequence, step.SequenceId); + // The folder moved with its files' stamps, which the index recorded at its old place. + inStep = await _indexer.InStepAsync(archive, step.FromFolder, sequence, manifest, cancellationToken).ConfigureAwait(false); + if (retitle && manifest.Title != step.ToTitle) { - Title = step.ToTitle, - Versions = manifest.Versions with { Settings = manifest.Versions.Settings + 1 }, - UpdatedAt = DateTimeOffset.UtcNow, - }; - ManifestStore.WriteSequence(sequence.ManifestPath, manifest); - } - await using (var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false)) - { - await tx.Sequences.RelocateAsync(step.SequenceId, step.ToFolder, retitle ? step.ToTitle : null, cancellationToken).ConfigureAwait(false); - if (step.MovesFolder) - { - await tx.Frames.RebaseFolderAsync(step.SequenceId, step.FromFolder, step.ToFolder, cancellationToken).ConfigureAwait(false); - await tx.Renders.RebaseFolderAsync(step.SequenceId, step.FromFolder, step.ToFolder, cancellationToken).ConfigureAwait(false); + ManifestStore.WriteSequence(sequence.ManifestPath, manifest with + { + Title = step.ToTitle, + Versions = manifest.Versions with { Settings = manifest.Versions.Settings + 1 }, + UpdatedAt = DateTimeOffset.UtcNow, + }); } - await tx.Archives.DeleteFolderStateAsync(archive.Id, step.FromFolder, cancellationToken).ConfigureAwait(false); - await tx.CommitAsync(cancellationToken).ConfigureAwait(false); } + catch (Exception ex) when (step.MovesFolder && ex is IOException or UnauthorizedAccessException or InvalidDataException or NewerFormatException) + { + await RelocateAsync(archive, step, null, cancellationToken).ConfigureAwait(false); + throw; + } + await RelocateAsync(archive, step, retitle ? step.ToTitle : null, cancellationToken).ConfigureAwait(false); if (inStep) await _indexer.RecordStampsAsync(archive, sequence, step.SequenceId, cancellationToken).ConfigureAwait(false); } + /// The index rows of a step, in one transaction: its sequence's folder and title (null: kept), the paths of its frames and of the renders whose export moved with the folder. + private async Task RelocateAsync(Archive archive, RenameStep step, string? title, CancellationToken cancellationToken) + { + await using var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false); + await tx.Sequences.RelocateAsync(step.SequenceId, step.ToFolder, title, cancellationToken).ConfigureAwait(false); + if (step.MovesFolder) + { + await tx.Frames.RebaseFolderAsync(step.SequenceId, step.FromFolder, step.ToFolder, cancellationToken).ConfigureAwait(false); + await tx.Renders.RebaseFolderAsync(step.SequenceId, step.FromFolder, step.ToFolder, cancellationToken).ConfigureAwait(false); + } + await tx.Archives.DeleteFolderStateAsync(archive.Id, step.FromFolder, cancellationToken).ConfigureAwait(false); + await tx.CommitAsync(cancellationToken).ConfigureAwait(false); + } + /// /// The file renames of a step, under the leases its step holds, once its folder is in place and every index row of the /// step followed it (Reorganize, owner review 2, R7). The renames are planned again from the sidecar read under the /// lease (, with the step's title, the one the dry run showed) and made only while they are /// exactly the plan's (, checked before the folder moved already); found otherwise here (a writer - /// that takes no lease) the files keep their names, and so do they when one is in use (every file goes back to its - /// name): the step goes on either way. The files move in two phases through temporary names under the sequence's - /// journal (), then the sidecar names them (the frame order unchanged, frames version + 1), + /// that takes no lease) the files keep their names, and so do they when one is in use or a new name is taken (every + /// file goes back to its name): the step goes on either way. The files move in two phases through temporary names + /// under the sequence's journal (), then the sidecar names them (the frame order unchanged, frames version + 1), /// then the index (), then the journal goes. A file that could not go back /// after such a failure has the journal complete the renames at once, as the next writer would. When nothing moves here /// but the index names other files than the sidecar, a writer completed the renames after a crash @@ -662,8 +747,8 @@ public sealed class MassRenamer } catch (Exception ex) when ((ex is IOException or UnauthorizedAccessException) && FileRenameJournal.Read(sequence) is null) { - // A file open elsewhere, and every file went back to its name: nothing of the sequence's files changed. - Log.Warning("archive", $"The files of {sequence.RelativeFolder} keep their names: one of them is in use", ex); + // A file open elsewhere or a new name taken, and every file went back to its name: nothing of the sequence's files changed. + Log.Warning("archive", $"The files of {sequence.RelativeFolder} keep their names: one of them is in use or its new name is taken", ex); result.FilesBusy.Add(step.SequenceId); return false; } @@ -716,6 +801,7 @@ public sealed class MassRenamer public List FilesKept { get; } = [.. done.FilesKept]; public List TitlesKept { get; } = [.. done.TitlesKept]; public List FilesBusy { get; } = [.. done.FilesBusy]; + public List Newer { get; } = [.. done.Newer]; public int Files { get; set; } = done.Files; public RenameTally Record() => new() @@ -726,6 +812,7 @@ public sealed class MassRenamer FilesKept = [.. FilesKept], TitlesKept = [.. TitlesKept], FilesBusy = [.. FilesBusy], + Newer = [.. Newer], }; } } diff --git a/src/Chronos.Data/Archiving/SequenceWriter.cs b/src/Chronos.Data/Archiving/SequenceWriter.cs index 28901eba..5ca5584a 100644 --- a/src/Chronos.Data/Archiving/SequenceWriter.cs +++ b/src/Chronos.Data/Archiving/SequenceWriter.cs @@ -53,8 +53,10 @@ public sealed record ArchiveServiceOptions public string? BackupDirectory { get; init; } /// - /// Told after a job changed a sequence's folder, title or file names (change reorganized, a Reorganize): a server - /// tells its connected clients (BRIEF §14.3). A failure is logged and never fails the job. + /// Told after a Reorganize changed a sequence's folder, title or file names (change reorganized), once its step is + /// journaled: by its job, or by an archive open that completed a plan an interruption left (). + /// 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. /// public Func? SequenceChanged { get; init; } diff --git a/src/Chronos.Server/Api/ArchiveEndpoints.cs b/src/Chronos.Server/Api/ArchiveEndpoints.cs index 020bbfde..627efbe8 100644 --- a/src/Chronos.Server/Api/ArchiveEndpoints.cs +++ b/src/Chronos.Server/Api/ArchiveEndpoints.cs @@ -137,9 +137,12 @@ public static class ArchiveEndpoints /// invalid_template (details: folderTemplate, fileTemplate or titleTemplate); 404 /// not_found (sequence: not in the archive); 409 nested_target (details: the folder that would lie /// inside a sequence's folder), plan_changed (details: the fingerprint now), job_unavailable; 503 - /// archive_offline. Audited; the job tells every sequence it changes as sequenceChanged - /// (reorganized). A dry run's plan is kept a few minutes while the index stays as it was - /// (): the same dry run again, and its confirmation, take it instead of planning again. + /// archive_offline. Audited; the job tells each sequence it changes as sequenceChanged (reorganized) + /// 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 kept a few + /// minutes while the index stays as it was (): the same dry run again, and its + /// confirmation, take it instead of planning again. /// private static async Task ReorganizeAsync(HttpContext context, Caller caller, ReorganizeRequest request, ChronosDatabase db, ServerArchive archive, [FromServices] ArchiveService? archives, JobEngineHost host, AuditLog audit, ReorganizePlanCache plans) diff --git a/tests/Chronos.Core.Tests/Archiving/ReorganizeTests.cs b/tests/Chronos.Core.Tests/Archiving/ReorganizeTests.cs index 5dfc4920..e9137da0 100644 --- a/tests/Chronos.Core.Tests/Archiving/ReorganizeTests.cs +++ b/tests/Chronos.Core.Tests/Archiving/ReorganizeTests.cs @@ -171,7 +171,27 @@ public sealed class ReorganizeTests(TestContext context) var plan = Make(manifest); Assert.Equal(64, plan.Fingerprint().Length); Assert.Equal(plan.Fingerprint(), Make(manifest).Fingerprint()); - Assert.NotEqual(plan.Fingerprint(), Make(manifest with { Versions = new ManifestVersions { Frames = 5 } }).Fingerprint()); + // A photo received since under the name the plan gives it raises the frames version only: the plan is the one shown. + var received = manifest with + { + Versions = new ManifestVersions { Frames = 5 }, + Frames = [.. manifest.Frames, manifest.Frames[0] with { Id = Guid.NewGuid(), I = 1, File = "originals/002.JPG", CapturedAt = Start.AddSeconds(10) }], + }; + Assert.Equal(plan.Fingerprint(), Make(received).Fingerprint()); + // One the plan would rename too, or a file renamed otherwise, is another plan. + Assert.NotEqual(plan.Fingerprint(), Make(received with { Frames = [.. received.Frames.SkipLast(1), received.Frames[1] with { File = "originals/b.JPG" }] }).Fingerprint()); + Assert.NotEqual(plan.Fingerprint(), Make(manifest with { Frames = [manifest.Frames[0] with { File = "originals/c.JPG" }] }).Fingerprint()); + } + + [Test] + public void AStepNamedAfterTheTitleSaysSo() + { + var manifest = Sequence("originals/a.JPG"); + RenameStep Step(string? folder, string? file) => 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, null, ["s"], _ => false, fileTemplate: file).Steps.Single(); + Assert.True(Step("moved/{TITLE}", null) is { MovesFolder: true, NamedByTitle: true, UsesTitle: true, Retitles: false }); + Assert.True(Step(null, "{title}_{n:000}") is { FileChanges: 1, NamedByTitle: true, UsesTitle: true }); + Assert.True(Step("moved/{date}", "{n:000}") is { MovesFolder: true, FileChanges: 1, NamedByTitle: false, UsesTitle: false }); } [Test] @@ -560,4 +580,34 @@ public sealed class ReorganizeTests(TestContext context) Assert.FileMissing(sequence.File("originals/0001.CR2")); Assert.Empty(Directory.EnumerateFiles(sequence.Originals, ".chronos-rename-*")); } + + [Test] + public void APhotoThatTookItsNewNameGoesBackWithACompanionWhoseNewNameIsTaken() + { + var sequence = Folder(out _); + var manifest = Sequence("originals/A.CR2"); + Write(sequence, "originals/A.CR2", "photo"); + Write(sequence, "originals/A.xmp", "sidecar"); + var id = manifest.Frames[0].Id; + FileRename[] moves = [new(id, "originals/A.CR2", "originals/0001.CR2"), new(id, "originals/A.xmp", "originals/0001.xmp", Companion: true)]; + var journal = FileRenameJournal.Create(manifest.Versions.Frames, moves, "t6") with { Phase = 2 }; + FileRenameJournal.Write(sequence, journal); + foreach (var f in journal.Files) File.Move(sequence.File(f.From), sequence.File(f.Temp)); + // Stopped once the photo took its new name, before its companion did; then something took the companion's, and the + // photo's old name too. + File.Move(sequence.File(journal.Files[0].Temp), sequence.File(journal.Files[0].To)); + Write(sequence, "originals/0001.xmp", "other"); + Write(sequence, "originals/A.CR2", "another"); + + // The photo goes back with its companion, both to the first free number of its old name; the frame names the photo. + var recovered = Assert.NotNull(FileRenameJournal.Recover(sequence, manifest)); + Assert.Equal("originals/A_2.CR2", recovered.Frames.Single().File); + Assert.Equal(("photo", "sidecar"), (Read(sequence, "originals/A_2.CR2"), Read(sequence, "originals/A_2.xmp"))); + Assert.Equal(("other", "another"), (Read(sequence, "originals/0001.xmp"), Read(sequence, "originals/A.CR2"))); + Assert.FileMissing(sequence.File("originals/0001.CR2")); + Assert.Empty(Directory.EnumerateFiles(sequence.Originals, ".chronos-rename-*")); + // Run again, every file stays where it is. + Assert.Equal("originals/A_2.CR2", Assert.NotNull(FileRenameJournal.Recover(sequence, manifest)).Frames.Single().File); + Assert.Equal(("photo", "sidecar"), (Read(sequence, "originals/A_2.CR2"), Read(sequence, "originals/A_2.xmp"))); + } } diff --git a/tests/Chronos.Data.Tests/Archiving/ReorganizeTests.cs b/tests/Chronos.Data.Tests/Archiving/ReorganizeTests.cs index 41e06e02..68b1e533 100644 --- a/tests/Chronos.Data.Tests/Archiving/ReorganizeTests.cs +++ b/tests/Chronos.Data.Tests/Archiving/ReorganizeTests.cs @@ -252,29 +252,52 @@ public sealed class ReorganizeTests(TestContext context) } [Test] - public async Task APlanWhosePhotosChangedIsRefusedOrResumedWithoutTheirNames() + public async Task APlanWhosePhotosChangedAppliesWithoutTheirNames() { await using var fx = await CreateAsync(context); var id = await UploadAsync(fx, 2); var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], new RenameTemplates(File: "{n:000}", Title: "Roof"), fx.Ct); - // A photo arrives after the dry run: the names shown are no longer the ones the template gives. + // A photo arrives after the dry run, filed between them: the names shown are no longer the ones the template gives. await UploadAsync(fx, 1, firstSeed: 9, firstSecond: 5); var before = await FilesAsync(fx, id); - var stale = await Assert.ThrowsAsync(() => fx.Service.ApplyRenameAsync(plan, null, fx.Ct)); - Assert.Equal(id, stale.SequenceId); - Assert.SequenceEqual(before, await FilesAsync(fx, id)); - Assert.Null((await fx.Db.Sequences.GetAsync(id))!.Title); - Assert.Empty(RenameJournal.ListPending(fx.Paths)); - - // Interrupted before its step began, the plan resumes: the title changes, the files keep their names. - RenameJournal.Write(fx.Paths, new RenameJournal(plan, [])); - Assert.Equal(1, await fx.Service.Renamer.ResumePendingAsync(fx.Archive, fx.Ct)); + // The title changes, the files keep their names. + var result = await fx.Service.ApplyRenameAsync(plan, null, fx.Ct); + Assert.SequenceEqual([id], result.FilesKept); + Assert.SequenceEqual([id], result.Changed); + Assert.Equal(0, result.Files); Assert.SequenceEqual(before, await FilesAsync(fx, id)); Assert.Equal("Roof", (await fx.Db.Sequences.GetAsync(id))!.Title); Assert.Empty(RenameJournal.ListPending(fx.Paths)); } + [Test] + public async Task PhotosReceivedUnderTheNamesThePlanGivesLeaveItAsItWas() + { + await using var fx = await CreateAsync(context); + var id = await UploadAsync(fx, 2); + // The archive files new photos as the Reorganize names them, which its photos do not follow yet. + const string Template = "{n:000}"; + await fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Templates = s.Templates with { File = Template } }, fx.Ct); + var templates = new RenameTemplates(File: Template); + var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], templates, fx.Ct); + Assert.Equal(2, plan.Steps.Single().FileChanges); + var request = ArchiveJobs.Reorganize(fx.Archive, plan, templates); + + // A camera still uploads into it: its photo is filed under the name the plan leaves it, which changes nothing of the plan. + await UploadAsync(fx, 1, firstSeed: 3, firstSecond: 20); + Assert.Equal("originals/003.JPG", (await FilesAsync(fx, id))[2]); + var now = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], templates, fx.Ct); + Assert.NotEqual(plan.Steps.Single().FramesVersion, now.Steps.Single().FramesVersion); + Assert.Equal(plan.Fingerprint(), now.Fingerprint()); + + // The job confirmed before it applies it as it was shown. + var engine = await fx.StartEngineAsync(); + var done = await fx.WaitForAsync((await engine.EnqueueAsync(request, cancellationToken: fx.Ct)).Id, JobState.Done); + Assert.Contains(Loc.L("Archive.Log.Reorganized", 1, 2), done.LogTail); + Assert.SequenceEqual(["originals/001.JPG", "originals/002.JPG", "originals/003.JPG"], await FilesAsync(fx, id)); + } + [Test] public async Task CompanionsMoveWithTheirPhoto() { @@ -403,26 +426,72 @@ public sealed class ReorganizeTests(TestContext context) } [Test] - public async Task AStepWhosePhotosChangedIsRefusedUnderItsLeasesBeforeAnythingMoves() + public async Task AStepWhosePhotosChangedUnderItsLeasesMovesWithoutRenamingThem() { await using var fx = await CreateAsync(context); var (parent, nested, plan) = await CarrierAsync(fx); - var from = await FolderAsync(fx, parent); - // A photo uploaded once the plan's own checks passed, before its step: nothing of that step moves. - var stale = await Assert.ThrowsAsync(() => fx.Service.Renamer.ApplyAsync(fx.Archive, plan, - async _ => await UploadAsync(fx, 1, firstSeed: 9, firstSecond: 5), null, fx.Ct)); - Assert.Equal(parent, stale.SequenceId); - var before = await FilesAsync(fx, parent); - Assert.Equal((from, from + "/extra"), (await FolderAsync(fx, parent), await FolderAsync(fx, nested))); - Assert.Empty(Assert.NotNull(RenameJournal.Read(fx.Paths, plan.Id)).Completed); - - // Resumed after an interruption, the folder moves with the one inside it, whose index row follows, and the files keep their names. - var result = Assert.NotNull(await fx.Service.Renamer.ResumeAsync(fx.Archive, plan.Id, null, fx.Ct)); + // A photo uploaded once the plan's own checks passed, before its step: the folder moves with the one inside it, + // whose index row follows, and the files keep their names. + var result = await fx.Service.Renamer.ApplyAsync(fx.Archive, plan, async _ => await UploadAsync(fx, 1, firstSeed: 9, firstSecond: 5), null, fx.Ct); Assert.SequenceEqual([parent], result.FilesKept); Assert.SequenceEqual([parent, nested], result.Changed); Assert.Equal(("moved/2026-09-28", "moved/2026-09-28/extra"), (await FolderAsync(fx, parent), await FolderAsync(fx, nested))); - Assert.SequenceEqual(before, await FilesAsync(fx, parent)); + var files = await FilesAsync(fx, parent); + Assert.Count(3, files); + Assert.Empty(files.Intersect(plan.Steps[0].FileSamples.Select(s => s.To))); + Assert.Empty(RenameJournal.ListPending(fx.Paths)); + } + + [Test] + public async Task ASequenceStillReceivingPhotosKeepsItsFileNamesWhileTheJobGoesOn() + { + await using var fx = await CreateAsync(context); + var first = await UploadAsync(fx, 2); + var second = await UploadAsync(fx, 2, firstSeed: 20, firstSecond: 3600, key: "upload-2"); + var third = await UploadAsync(fx, 2, firstSeed: 40, firstSecond: 7200, key: "upload-3"); + var templates = new RenameTemplates(Folder: "moved/{date} {hm}", File: "{n:000}"); + var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [first, second, third], templates, fx.Ct); + var told = new ConcurrentQueue(); + var service = new ArchiveService(fx.Db, new ArchiveServiceOptions + { + Owner = "jobs", + LeaseWait = TimeSpan.FromSeconds(TestTiming.Budget(20)), + SequenceChanged = (id, _, _) => + { + told.Enqueue(id); + return Task.CompletedTask; + }, + }); + await using var engine = new JobEngine(fx.Db, service.CreateJobHandlers(), + new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) }); + await engine.StartAsync(fx.Ct); + + // A camera uploads into the second sequence while the job waits for the first. + Job job; + using (await LeaseFile.AcquireAsync(fx.Paths.LocksDirectory, $"seq-{first:N}", "editor", TimeSpan.FromSeconds(5), cancellationToken: fx.Ct)) + { + job = await engine.EnqueueAsync(ArchiveJobs.Reorganize(fx.Archive, plan, templates), cancellationToken: fx.Ct); + var until = DateTime.UtcNow.AddSeconds(TestTiming.Budget(15)); + while (RenameJournal.ListPending(fx.Paths).Count == 0) + { + Assert.True(DateTime.UtcNow < until, "the job never started its plan"); + await Task.Delay(20, fx.Ct); + } + await UploadAsync(fx, 1, firstSeed: 30, firstSecond: 3605, key: "upload-2"); + } + var received = await FilesAsync(fx, second); + + // Its folder moves and its files keep their names; the sequence after it is reorganized; the job then says why it failed. + var failed = await fx.WaitForAsync(job.Id, JobState.Failed, (int)TestTiming.Budget(60)); + Assert.Equal(Loc.Plural("Archive.Error.ReorganizeKept", 1), failed.Error); + Assert.Contains(Loc.L("Archive.Log.Reorganized", 3, 4), failed.LogTail); + Assert.Contains(Loc.L("Archive.Log.ReorganizeFilesKept", plan.Steps.Single(s => s.SequenceId == second).FromFolder), failed.LogTail); + Assert.Equal(("moved/2026-09-28 18-00", "moved/2026-09-28 19-00", "moved/2026-09-28 20-00"), + (await FolderAsync(fx, first), await FolderAsync(fx, second), await FolderAsync(fx, third))); + Assert.SequenceEqual(received, await FilesAsync(fx, second)); + foreach (var id in new[] { first, third }) Assert.SequenceEqual(["originals/001.JPG", "originals/002.JPG"], await FilesAsync(fx, id)); + Assert.SequenceEqual([first, second, third], told); Assert.Empty(RenameJournal.ListPending(fx.Paths)); } @@ -452,7 +521,7 @@ public sealed class ReorganizeTests(TestContext context) await using var fx = await CreateAsync(context); var first = await UploadAsync(fx, 2); var second = await UploadAsync(fx, 2, firstSeed: 20, firstSecond: 3600, key: "upload-2"); - var templates = new RenameTemplates(File: "{n:000}"); + var templates = new RenameTemplates(File: "{n:000}", Title: "Roof"); var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [first, second], templates, fx.Ct); var told = new ConcurrentQueue<(Guid, string)>(); var service = new ArchiveService(fx.Db, new ArchiveServiceOptions @@ -469,7 +538,7 @@ public sealed class ReorganizeTests(TestContext context) new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) }); await engine.StartAsync(fx.Ct); - // An editor holds the first sequence while the job starts its plan (planned again: its own id); a photo reaches the second meanwhile. + // An editor holds the first sequence while the job starts its plan (planned again: its own id); the second is retitled meanwhile. Job job; using (await LeaseFile.AcquireAsync(fx.Paths.LocksDirectory, $"seq-{first:N}", "editor", TimeSpan.FromSeconds(5), cancellationToken: fx.Ct)) { @@ -480,7 +549,7 @@ public sealed class ReorganizeTests(TestContext context) Assert.True(DateTime.UtcNow < until, "the job never started its plan"); await Task.Delay(20, fx.Ct); } - await UploadAsync(fx, 1, firstSeed: 30, firstSecond: 3605, key: "upload-2"); + await fx.Service.SetSequenceInfoAsync(second, "Roof north", [], 0, null, fx.Ct); } var failed = await fx.WaitForAsync(job.Id, JobState.Failed, (int)TestTiming.Budget(60)); @@ -492,7 +561,7 @@ public sealed class ReorganizeTests(TestContext context) Assert.SequenceEqual([first], journal.Completed); Assert.SequenceEqual(["originals/001.JPG", "originals/002.JPG"], await FilesAsync(fx, first)); var untouched = await FilesAsync(fx, second); - Assert.Count(3, untouched); + Assert.Equal("Roof north", (await fx.Db.Sequences.GetAsync(second))!.Title); // An archive open leaves it alone; the retry checks the rest as a plan applied anew and gives it up. Assert.Equal(0, await fx.Service.Renamer.ResumePendingAsync(fx.Archive, fx.Ct)); @@ -617,8 +686,12 @@ public sealed class ReorganizeTests(TestContext context) Assert.SequenceEqual(before, await FilesAsync(fx, id)); Assert.Null(FileRenameJournal.Read(folder)); - // Interrupted there, the plan resumes at the next open without its files; a new dry run renames none of them. - await fx.Service.OpenAsync(fx.Archive.RootPath, fx.Ct); + // Interrupted there, its job resumes the plan without its files and says why; a new dry run renames none of them. + 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", plan.Steps.Single().FromFolder), failed.LogTail); Assert.Empty(RenameJournal.ListPending(fx.Paths)); Assert.SequenceEqual(before, await FilesAsync(fx, id)); var again = (await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], templates, fx.Ct)).Steps.Single(); @@ -669,16 +742,114 @@ public sealed class ReorganizeTests(TestContext context) var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], new RenameTemplates(File: "{n:000}"), fx.Ct); Assert.Equal((2, RenameBlock.Unhashed), (plan.Steps.Single().FileChanges, plan.Steps.Single().Blocked.Single().Reason)); - // A verify hashes it afterwards, which leaves the frames version as it is: the plan would now rename it too. + // A verify hashes it afterwards, which leaves the frames version as it is: the plan would now rename it too, so none is. ManifestStore.WriteSequence(folder.ManifestPath, manifest); var before = await FilesAsync(fx, id); - await Assert.ThrowsAsync(() => fx.Service.ApplyRenameAsync(plan, null, fx.Ct)); + var result = await fx.Service.ApplyRenameAsync(plan, null, fx.Ct); + Assert.SequenceEqual([id], result.FilesKept); + Assert.Empty(result.Changed); Assert.SequenceEqual(before, await FilesAsync(fx, id)); - // Interrupted before its step, it resumes without renaming any of them. + // So it is when resumed after an interruption before its step. RenameJournal.Write(fx.Paths, new RenameJournal(plan, [])); - var result = Assert.NotNull(await fx.Service.Renamer.ResumeAsync(fx.Archive, plan.Id, null, fx.Ct)); + result = Assert.NotNull(await fx.Service.Renamer.ResumeAsync(fx.Archive, plan.Id, null, fx.Ct)); Assert.SequenceEqual([id], result.FilesKept); Assert.SequenceEqual(before, await FilesAsync(fx, id)); } + + [Test] + public async Task NamesComeFromATitleEditedAfterThePlanNever() + { + await using var fx = await CreateAsync(context); + var id = await UploadAsync(fx, 2); + await fx.Service.SetSequenceInfoAsync(id, "Roof", [], 0, null, fx.Ct); + var from = await FolderAsync(fx, id); + // 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); + Assert.True(plan.Steps.Single() is { ToFolder: "moved/Roof", FileChanges: 2, Retitles: false, NamedByTitle: true }); + var before = await FilesAsync(fx, id); + + // Retitled once the plan's own checks passed: refused before anything of it moves. + await Assert.ThrowsAsync(() => fx.Service.Renamer.ApplyAsync(fx.Archive, plan, + async _ => await fx.Service.SetSequenceInfoAsync(id, "Roof north", [], 0, null, fx.Ct), null, fx.Ct)); + Assert.Equal(from, await FolderAsync(fx, id)); + Assert.SequenceEqual(before, await FilesAsync(fx, id)); + + // Held by its job, the rest is refused as a plan applied anew; interrupted, it is dropped. + Assert.True(MassRenamer.Hold(fx.Archive, plan.Id)); + await Assert.ThrowsAsync(() => fx.Service.Renamer.ResumeAsync(fx.Archive, plan.Id, null, fx.Ct)); + RenameJournal.Write(fx.Paths, new RenameJournal(plan, [])); + var result = Assert.NotNull(await fx.Service.Renamer.ResumeAsync(fx.Archive, plan.Id, null, fx.Ct)); + Assert.SequenceEqual([id], result.Dropped); + Assert.Equal(from, await FolderAsync(fx, id)); + Assert.SequenceEqual(before, await FilesAsync(fx, id)); + Assert.Equal("Roof north", (await fx.Db.Sequences.GetAsync(id))!.Title); + Assert.Empty(RenameJournal.ListPending(fx.Paths)); + } + + [Test] + public async Task APlanAnArchiveOpenCompletesTellsTheSequencesItChanged() + { + await using var fx = await CreateAsync(context); + var id = await UploadAsync(fx, 1); + var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], new RenameTemplates(Folder: "moved/{date}"), fx.Ct); + // Its job yielded to another, or its host stopped, before the step: the plan is not held. + RenameJournal.Write(fx.Paths, new RenameJournal(plan, [])); + 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; + }, + }); + + await service.OpenAsync(fx.Archive.RootPath, fx.Ct); + Assert.SequenceEqual([(id, MassRenamer.Change)], told); + Assert.Equal("moved/2026-09-28", await FolderAsync(fx, id)); + Assert.Empty(RenameJournal.ListPending(fx.Paths)); + } + + [Test] + [WindowsOnly] + public async Task AMovedFolderWhoseSidecarCannotBeWrittenHasEveryIndexRowFollowIt() + { + 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 plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [parent], new RenameTemplates(Folder: "moved/{date}", Title: "Roof"), fx.Ct); + Assert.SequenceEqual([(parent, false), (nested, true)], plan.Steps.Select(s => (s.SequenceId, s.Carried))); + string[] sidecars = [fx.Paths.Sequence(folder).ManifestPath, fx.Paths.Sequence("moved/2026-09-28").ManifestPath]; + void Writable(bool writable) + { + foreach (var sidecar in sidecars.Where(File.Exists)) + File.SetAttributes(sidecar, writable ? File.GetAttributes(sidecar) & ~FileAttributes.ReadOnly : File.GetAttributes(sidecar) | FileAttributes.ReadOnly); + } + + try + { + // Its sidecar can be read, not written: the new title fails once the folder moved. + Writable(false); + await Assert.ThrowsAsync(() => fx.Service.ApplyRenameAsync(plan, null, fx.Ct)); + // Both index rows followed the folder all the same; the title waits for the rest of the step. + Assert.Equal(("moved/2026-09-28", "moved/2026-09-28/extra"), (await FolderAsync(fx, parent), await FolderAsync(fx, nested))); + Assert.Null((await fx.Db.Sequences.GetAsync(parent))!.Title); + Assert.Empty(Assert.NotNull(RenameJournal.Read(fx.Paths, plan.Id)).Completed); + } + finally + { + Writable(true); + } + + var result = Assert.NotNull(await fx.Service.Renamer.ResumeAsync(fx.Archive, plan.Id, null, fx.Ct)); + Assert.SequenceEqual([parent, nested], result.Changed); + Assert.Equal("Roof", (await fx.Db.Sequences.GetAsync(parent))!.Title); + await FilesAsync(fx, parent); + Assert.Empty(RenameJournal.ListPending(fx.Paths)); + } } diff --git a/tests/Chronos.Server.Tests/Api/ReorganizeTests.cs b/tests/Chronos.Server.Tests/Api/ReorganizeTests.cs index d4ebce9b..6ec1a841 100644 --- a/tests/Chronos.Server.Tests/Api/ReorganizeTests.cs +++ b/tests/Chronos.Server.Tests/Api/ReorganizeTests.cs @@ -284,6 +284,35 @@ public sealed class ReorganizeTests(TestContext context) Assert.SequenceEqual(["001.JPG", "002.JPG", "003.JPG"], (await server.Database.Frames.ListBySequenceAsync(id)).Select(f => f.FileName)); } + [Test] + public async Task AnUploadFiledUnderTheNameThePlanGivesLeavesThePlanToConfirm() + { + await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register); + var (editor, _, _) = await server.UserAsync("alberto", "editor"); + var admin = await server.AdminAsync(); + Guid id = default; + for (var i = 0; i < 2; i++) id = (await Uploads.UploadAsync(editor, Photo(i), $"IMG_{i + 1:0000}.JPG", sessionKey: "roof")).SequenceId; + await UntilIdleAsync(server); + // The archive files new photos as the Reorganize names them; the two filed before do not follow it yet. + using (var read = await admin.GetAsync("/api/v1/archive/settings")) + { + var settings = await read.ReadAsync(ProtocolJson.Default.ArchiveSettingsDto); + using var put = await admin.PutAsJsonAsync("/api/v1/archive/settings", settings with { FileTemplate = "{n:000}" }, ProtocolJson.Default.ArchiveSettingsDto); + await put.ExpectAsync(HttpStatusCode.OK); + } + var request = new ReorganizeRequest([id], false, null, "{n:000}", null, DryRun: true); + var shown = await DryRunAsync(admin, request); + Assert.Equal(2, shown.Files); + + // The camera still uploads before Apply, a photo after the others: it takes the name the plan leaves it, so the plan + // confirmed is the one now. + await Uploads.UploadAsync(editor, Photo(2), "IMG_0003.JPG", sessionKey: "roof", capturedAt: new DateTime(2026, 9, 28, 18, 3, 0)); + await UntilIdleAsync(server); + Assert.Equal("003.JPG", (await server.Database.Frames.ListBySequenceAsync(id))[^1].FileName); + await UntilJobAsync(admin, await ConfirmAsync(admin, request with { DryRun = false, Fingerprint = shown.Fingerprint }), "done"); + Assert.SequenceEqual(["001.JPG", "002.JPG", "003.JPG"], (await server.Database.Frames.ListBySequenceAsync(id)).Select(f => f.FileName)); + } + [Test] public async Task AMoveJobPausedBetweenTwoSequencesCompletesTheRestWhenResumed() { diff --git a/tests/Chronos.Server.Tests/Uploads.cs b/tests/Chronos.Server.Tests/Uploads.cs index d5e47855..444812ce 100644 --- a/tests/Chronos.Server.Tests/Uploads.cs +++ b/tests/Chronos.Server.Tests/Uploads.cs @@ -19,11 +19,13 @@ internal static class Uploads public static string Sha(byte[] data) => Convert.ToHexStringLower(SHA256.HashData(data)); + /// The capture time the client sends; null: 2026-09-28 18:02:11. public static async Task StartAsync(HttpClient client, byte[] data, string fileName = "IMG_0001.CR3", Guid? sequenceId = null, - string? sessionKey = null, HttpStatusCode expected = HttpStatusCode.Created) + string? sessionKey = null, HttpStatusCode expected = HttpStatusCode.Created, DateTime? capturedAt = null) { using var response = await client.PostAsJsonAsync("/api/v1/uploads", - new StartUploadRequest(sequenceId, fileName, data.Length, Sha(data), new DateTime(2026, 9, 28, 18, 2, 11), sessionKey), ProtocolJson.Default.StartUploadRequest); + new StartUploadRequest(sequenceId, fileName, data.Length, Sha(data), capturedAt ?? new DateTime(2026, 9, 28, 18, 2, 11), sessionKey), + ProtocolJson.Default.StartUploadRequest); await response.ExpectAsync(expected); return await response.ReadAsync(ProtocolJson.Default.StartUploadResponse); } @@ -40,9 +42,9 @@ internal static class Uploads /// Start, every chunk, complete; returns the committed frame. public static async Task UploadAsync(HttpClient client, byte[] data, string fileName = "IMG_0001.CR3", Guid? sequenceId = null, - string? sessionKey = null) + string? sessionKey = null, DateTime? capturedAt = null) { - var start = await StartAsync(client, data, fileName, sequenceId, sessionKey); + var start = await StartAsync(client, data, fileName, sequenceId, sessionKey, capturedAt: capturedAt); var id = Assert.NotNull(start.UploadId); var chunks = (data.Length + start.ChunkSize - 1) / start.ChunkSize; for (var i = 0; i < chunks; i++)