From 45e69110826a3b80e0d5aa885cf1d84db7560968 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Sun, 15 Nov 2026 13:38:05 +0100 Subject: [PATCH] feat(jobs): every job handler reports a structured progress detail The job list showed a bar and a free-text line that each handler worded its own way. Each handler now reports its step, the item it is on, photo x of y and sequence/folder/output/step n of m through the P2.1 JobContext detail. Clients can word and lay that out themselves, and the 2/s throttle keeps the cost low: counts within a step go through ReportItemAsync, which allocates nothing. - scan: List, then Index (folder n of m, photo x of y as an adopted or reconciled folder is read) or Check, then FollowUps - verify, thumbs, proxies, deep analysis: photo x of y of sequence n of m; light analysis: sequence n of m; a thumbnail/proxy checkpoint carries the frame count it saves - convert: Verify (resume), Convert photo x of y, Replace; reorganize: step n of m with the title; import: the file being copied, photo x of y - maintenance: the step key, step n of 5, then Check; duplicates, orphans and backup run with no count; cleanup names step n of m; empty trash: entry n of m - render (local, workspace, render node): Analyse, Encode (frames of the last output, output n of m in a batch), Verify; sync, video copy, workspace copy/send/move: Upload/Download/CopyProxy/CopyOriginal/ CopyVideo/Reorganize with their items and counts The detail carries keys and names only, never localized text. The existing Message strings stay for clients that still show them. Refs #65 Co-Authored-By: Claude Opus 5.5 --- src/Chronos.Core/Archiving/SequenceAdopter.cs | 29 ++- src/Chronos.Data/Archiving/ArchiveImages.cs | 27 ++- src/Chronos.Data/Archiving/ArchiveIndexer.cs | 61 ++++-- .../Archiving/ArchiveMaintenance.cs | 19 +- src/Chronos.Data/Archiving/ArchiveVerifier.cs | 15 +- .../Archiving/Jobs/ConvertJobHandler.cs | 6 +- .../Archiving/Jobs/EmptyTrashJobHandler.cs | 4 +- .../Archiving/Jobs/ImageJobHandler.cs | 20 +- .../Archiving/Jobs/ImportJobHandler.cs | 9 +- .../Archiving/Jobs/MaintenanceJobHandler.cs | 7 +- .../Archiving/Jobs/MoveJobHandler.cs | 14 +- .../Archiving/Jobs/ReportJobHandlers.cs | 6 +- .../Archiving/Jobs/ScanJobHandler.cs | 34 +++- .../Archiving/Jobs/VerifyJobHandler.cs | 15 +- src/Chronos.Data/Archiving/MassConverter.cs | 28 ++- src/Chronos.Data/Archiving/MassRenamer.cs | 27 ++- .../Archiving/SequenceTrash.Empty.cs | 14 +- .../Housekeeping/HousekeepingJobHandlers.cs | 6 +- .../Processing/Jobs/AnalyseJobHandler.cs | 18 +- .../Processing/Jobs/RenderJobHandler.cs | 56 +++++- .../Processing/RenderNodeClient.cs | 41 +++- src/Chronos.Data/Sync/SyncTransfers.cs | 32 +++- .../Videos/VideoCopyJobHandler.cs | 16 +- .../Workspaces/WorkspaceCopyJobHandler.cs | 15 +- .../Workspaces/WorkspaceMoveJobHandler.cs | 16 +- .../Workspaces/WorkspaceRenderJobHandler.cs | 9 +- .../Workspaces/WorkspaceSendJobHandler.cs | 2 + .../Archiving/ArchiveProgressDetailTests.cs | 180 ++++++++++++++++++ .../Archiving/PartialRowWriterTests.cs | 8 +- .../Chronos.Data.Tests/Jobs/DetailRecorder.cs | 62 ++++++ .../ProcessingProgressDetailTests.cs | 82 ++++++++ 31 files changed, 759 insertions(+), 119 deletions(-) create mode 100644 tests/Chronos.Data.Tests/Archiving/ArchiveProgressDetailTests.cs create mode 100644 tests/Chronos.Data.Tests/Jobs/DetailRecorder.cs create mode 100644 tests/Chronos.Data.Tests/Processing/ProcessingProgressDetailTests.cs diff --git a/src/Chronos.Core/Archiving/SequenceAdopter.cs b/src/Chronos.Core/Archiving/SequenceAdopter.cs index 45a96d08..276ef45f 100644 --- a/src/Chronos.Core/Archiving/SequenceAdopter.cs +++ b/src/Chronos.Core/Archiving/SequenceAdopter.cs @@ -17,9 +17,16 @@ public sealed record SequenceOrphans(string Folder, IReadOnlyList Uninde public static class SequenceAdopter { /// A new sidecar for a folder without one. A folder outside the layout (no originals/) is titled by its name. - public static SequenceManifest Build(Guid id, SequencePaths sequence, string? createdBy, CancellationToken cancellationToken = default) + public static SequenceManifest Build(Guid id, SequencePaths sequence, string? createdBy, CancellationToken cancellationToken = default) => + Build(id, sequence, createdBy, null, cancellationToken); + + /// + /// A new sidecar for a folder without one, telling after each photo it read (photo done of + /// total), so a scan can show how far it is inside a large folder. + /// + public static SequenceManifest Build(Guid id, SequencePaths sequence, string? createdBy, Action? photoRead, CancellationToken cancellationToken = default) { - var (frames, first) = ReadFrames(sequence, ArchiveScanner.ListPhotos(sequence), cancellationToken); + var (frames, first) = ReadFrames(sequence, ArchiveScanner.ListPhotos(sequence), photoRead, cancellationToken); var now = DateTimeOffset.UtcNow; var inLayout = Directory.Exists(sequence.Originals); var manifest = new SequenceManifest @@ -48,7 +55,14 @@ public static class SequenceAdopter /// Brings a sidecar in line with its folder: unindexed photos are added (in capture order), frames whose file is /// gone get and frames whose file came back lose it. Null when nothing changed. /// - public static SequenceManifest? Reconcile(SequencePaths sequence, SequenceManifest manifest, CancellationToken cancellationToken = default) + public static SequenceManifest? Reconcile(SequencePaths sequence, SequenceManifest manifest, CancellationToken cancellationToken = default) => + Reconcile(sequence, manifest, null, cancellationToken); + + /// + /// , telling after + /// each unindexed photo it read (photo done of total). + /// + public static SequenceManifest? Reconcile(SequencePaths sequence, SequenceManifest manifest, Action? photoRead, CancellationToken cancellationToken = default) { var orphans = FindOrphans(sequence, manifest); var missing = orphans.MissingFiles.Select(f => f.Id).ToHashSet(); @@ -61,7 +75,7 @@ public static class SequenceAdopter } if (flagChanges.Count == 0 && orphans.UnindexedFiles.Count == 0) return null; var updated = flagChanges.Count == 0 ? manifest : SequenceFrames.Update(manifest, flagChanges); - var (added, first) = ReadFrames(sequence, orphans.UnindexedFiles, cancellationToken); + var (added, first) = ReadFrames(sequence, orphans.UnindexedFiles, photoRead, cancellationToken); // Photos that cannot be read yet (held open by another program, no read permission, a placeholder not downloaded) // stay unindexed: with nothing else changed, nothing changed. if (added.Count == 0 && flagChanges.Count == 0) return null; @@ -70,13 +84,15 @@ public static class SequenceAdopter return SequenceFrames.Insert(updated, added); } - private static (List Frames, FrameMetadata? First) ReadFrames(SequencePaths sequence, IReadOnlyList files, CancellationToken cancellationToken) + private static (List Frames, FrameMetadata? First) ReadFrames(SequencePaths sequence, IReadOnlyList files, Action? photoRead, + CancellationToken cancellationToken) { var frames = new List(files.Count); FrameMetadata? first = null; - foreach (var file in files) + for (var i = 0; i < files.Count; i++) { cancellationToken.ThrowIfCancellationRequested(); + var file = files[i]; var path = sequence.File(file); try { @@ -88,6 +104,7 @@ public static class SequenceAdopter { Log.Warning("archive", $"Skipped unreadable photo {sequence.ArchiveRelative(file)}", ex); } + photoRead?.Invoke(i + 1, files.Count); } return (frames, first); } diff --git a/src/Chronos.Data/Archiving/ArchiveImages.cs b/src/Chronos.Data/Archiving/ArchiveImages.cs index 9587ce05..bca02184 100644 --- a/src/Chronos.Data/Archiving/ArchiveImages.cs +++ b/src/Chronos.Data/Archiving/ArchiveImages.cs @@ -208,8 +208,17 @@ public sealed class ArchiveImages /// Several frames are drawn at once (); the pack takes them in frame order /// (), so a checkpoint still means that every frame before it is in the pack. /// + public Task BuildThumbnailsAsync(Archive archive, Sequence sequence, bool force, int startFrame, + Func checkpoint, CancellationToken cancellationToken = default) => + BuildThumbnailsAsync(archive, sequence, force, startFrame, checkpoint, null, cancellationToken); + + /// + /// + /// Called after each frame the pack took (drawn or not decodable), in frame order, with the frames done of the sequence + /// and its frame count: cheap, between the checkpoints, for a job's progress. + /// public async Task BuildThumbnailsAsync(Archive archive, Sequence sequence, bool force, int startFrame, - Func checkpoint, CancellationToken cancellationToken = default) + Func checkpoint, Func? frameDone, CancellationToken cancellationToken = default) { var paths = new ArchivePaths(archive.RootPath); ArchiveVolume.EnsureWritable(paths); @@ -249,7 +258,7 @@ public sealed class ArchiveImages undecodable++; } if (drawn.Tier is { } tier) tiers[drawn.Frame.Id] = tier; - if (!cadence.Due()) return ValueTask.CompletedTask; + if (!cadence.Due()) return frameDone?.Invoke(drawn.Index + 1, manifest.Frames.Count) ?? ValueTask.CompletedTask; pack.Commit(); return checkpoint(drawn.Index + 1, manifest.Frames.Count); }, cancellationToken)) @@ -304,8 +313,17 @@ public sealed class ArchiveImages /// has it (another index moved it, until this index's next scan), or that holds another sequence now, stops the pass /// with an , nothing written there. /// + public Task BuildProxiesAsync(Archive archive, Sequence sequence, bool force, int startFrame, + Func checkpoint, CancellationToken cancellationToken = default) => + BuildProxiesAsync(archive, sequence, force, startFrame, checkpoint, null, cancellationToken); + + /// + /// + /// Called after each frame the pass handled in a batch (made, reused, waiting or not decodable), in frame order, with the + /// frames done of the sequence and its frame count: cheap, between the checkpoints, for a job's progress. + /// public async Task BuildProxiesAsync(Archive archive, Sequence sequence, bool force, int startFrame, - Func checkpoint, CancellationToken cancellationToken = default) + Func checkpoint, Func? frameDone, CancellationToken cancellationToken = default) { var paths = new ArchivePaths(archive.RootPath); ArchiveVolume.EnsureWritable(paths); @@ -357,7 +375,8 @@ public sealed class ArchiveImages break; } if (made.Tier is { } tier) tiers[made.FrameId] = tier; - return cadence.Due() ? checkpoint(made.Index + 1, read.Frames.Count) : ValueTask.CompletedTask; + return cadence.Due() ? checkpoint(made.Index + 1, read.Frames.Count) + : frameDone?.Invoke(made.Index + 1, read.Frames.Count) ?? ValueTask.CompletedTask; }, cancellationToken)) { // At least one frame per batch, so the pass always moves on. diff --git a/src/Chronos.Data/Archiving/ArchiveIndexer.cs b/src/Chronos.Data/Archiving/ArchiveIndexer.cs index a0249ea1..4e475c1a 100644 --- a/src/Chronos.Data/Archiving/ArchiveIndexer.cs +++ b/src/Chronos.Data/Archiving/ArchiveIndexer.cs @@ -19,7 +19,15 @@ public enum ScanMode Rebuild, } -public sealed record ScanProgress(int FoldersDone, int FoldersTotal, string Folder, bool Changed); +/// How far a scan is (). +/// Folders done; while , those before . +/// Whether is indexed (it changed), not only checked. +/// +/// True while is indexed, with the photos read so far when it reads them (adopted or reconciled: +/// photo of , 0 of 0 otherwise): not a resume point. False once +/// the folder is done. +/// +public sealed record ScanProgress(int FoldersDone, int FoldersTotal, string Folder, bool Changed, bool Indexing = false, int PhotosDone = 0, int PhotosTotal = 0); /// Folders that could not be indexed, with the reason; they are retried by the next scan. /// The sequences this run indexed ( of them), in folder order. @@ -48,7 +56,10 @@ public sealed class ArchiveIndexer } /// Last folder completed by an interrupted run (job checkpoint), or null. - /// Called after each folder; persist as the resume point. + /// + /// Called after each folder (persist as the resume point), and while a changed folder + /// is indexed (: before it and after each photo it reads, not a resume point). + /// /// The archive is offline or read-only; the index is left as it is. public async Task ScanAsync(Archive archive, ScanMode mode, string? resumeAfter, Func progress, CancellationToken cancellationToken = default) @@ -77,10 +88,15 @@ public sealed class ArchiveIndexer var changed = mode != ScanMode.Incremental || state is null || state.Sidecar != folder.Sidecar || state.Photos != folder.Photos; if (changed) { + await progress(new ScanProgress(i, folders.Count, folder.RelativeFolder, true, Indexing: true)).ConfigureAwait(false); + var done = i; + var relative = folder.RelativeFolder; + void PhotoRead(int photos, int total) => + Wait(progress(new ScanProgress(done, folders.Count, relative, true, Indexing: true, PhotosDone: photos, PhotosTotal: total))); try { var reconcile = mode == ScanMode.Full || (state is not null && state.Photos != folder.Photos); - var (id, bytes) = await IndexFolderAsync(archive, paths, folder, reconcile, snapshot, locations, cancellationToken).ConfigureAwait(false); + var (id, bytes) = await IndexFolderAsync(archive, paths, folder, reconcile, snapshot, locations, PhotoRead, cancellationToken).ConfigureAwait(false); // A full scan or a rebuild takes the projects' sidecars back too (owner review 2, R8). if (mode != ScanMode.Incremental) await ReconcileProjectsAsync(paths, id, cancellationToken).ConfigureAwait(false); if (snapshotWriter is not null) @@ -108,6 +124,16 @@ public sealed class ArchiveIndexer return new ScanSummary(folders.Count, indexed.Count, adopted, removed, failed, indexed); } + /// + /// Waits for a progress report made from code that reads photos synchronously: it is complete at once but when a job's + /// persist falls due (once every few seconds). + /// + private static void Wait(ValueTask report) + { + if (report.IsCompletedSuccessfully) return; + report.AsTask().GetAwaiter().GetResult(); + } + /// /// Writes a sequence's sidecar into the index (row, frames, session keys) and records the folder stamps. Frames /// inserted before indexed ones take the project's frame positions along (). The frames @@ -295,7 +321,11 @@ public sealed class ArchiveIndexer /// sidecar then tells every host, so the follow-ups make them again (the images on a server, /// ). /// - private static SequenceManifest? Reconcile(SequencePaths sequence, SequenceManifest manifest, CancellationToken cancellationToken) + private static SequenceManifest? Reconcile(SequencePaths sequence, SequenceManifest manifest, CancellationToken cancellationToken) => + Reconcile(sequence, manifest, null, cancellationToken); + + /// Told after each photo read (photo done of total); null for none. + private static SequenceManifest? Reconcile(SequencePaths sequence, SequenceManifest manifest, Action? photoRead, CancellationToken cancellationToken) { // A restore from the trash or a frame replacement that could not be settled yet (its entry busy, a file that could not // go back) may have photos in the folder its sidecar does not list: they are its own, not photos to adopt, until a @@ -305,7 +335,7 @@ public sealed class ArchiveIndexer Log.Info("archive", $"{sequence.RelativeFolder} is not reconciled while a restore from the trash or a replacement of its frames waits"); return null; } - return SequenceAdopter.Reconcile(sequence, manifest, cancellationToken) is { } reconciled + return SequenceAdopter.Reconcile(sequence, manifest, photoRead, cancellationToken) is { } reconciled ? reconciled with { Status = reconciled.Status & ~CoveringStatus } : null; } @@ -387,16 +417,19 @@ public sealed class ArchiveIndexer } } - /// Indexes one folder; returns its sequence and the sidecar bytes when they were read and not rewritten since (for the snapshot). + /// + /// Indexes one folder; returns its sequence and the sidecar bytes when they were read and not rewritten since (for the + /// snapshot). is told after each photo read (adopted or reconciled). + /// private async Task<(Guid Id, byte[]? Bytes)> IndexFolderAsync(Archive archive, ArchivePaths paths, SequenceFolder folder, bool reconcile, IndexSnapshot? snapshot, - Locations locations, CancellationToken cancellationToken) + Locations locations, Action? photoRead, CancellationToken cancellationToken) { var sequence = paths.Sequence(folder.RelativeFolder); SequenceManifest manifest; byte[]? bytes = null; if (folder.Sidecar is not { } stamp) { - manifest = await AdoptAsync(sequence, locations, cancellationToken).ConfigureAwait(false); + manifest = await AdoptAsync(sequence, locations, photoRead, cancellationToken).ConfigureAwait(false); } else { @@ -408,7 +441,7 @@ public sealed class ArchiveIndexer catch (InvalidDataException ex) { Log.Warning("archive", $"Damaged sidecar in {folder.RelativeFolder}; rebuilding it from the photos", ex); - manifest = await ReplaceDamagedAsync(sequence, locations, cancellationToken).ConfigureAwait(false); + manifest = await ReplaceDamagedAsync(sequence, locations, photoRead, cancellationToken).ConfigureAwait(false); bytes = null; } } @@ -424,7 +457,7 @@ public sealed class ArchiveIndexer || File.Exists(sequence.ReplaceJournalPath)) { // Photos added, gone or back clear what covered the frames, and the scan's follow-ups make it again. - manifest = await UpdateAndSyncAsync(archive, paths, sequence, manifest.Id, m => Reconcile(sequence, m, cancellationToken), cancellationToken) + manifest = await UpdateAndSyncAsync(archive, paths, sequence, manifest.Id, m => Reconcile(sequence, m, photoRead, cancellationToken), cancellationToken) .ConfigureAwait(false); bytes = null; } @@ -512,10 +545,10 @@ public sealed class ArchiveIndexer /// A sidecar for a folder that has none; ids and tombstones of a sequence the index already knew at this folder are /// kept, so a photo deleted from it is not offered back once the index is synced from the new sidecar. /// - private async Task AdoptAsync(SequencePaths sequence, Locations locations, CancellationToken cancellationToken) + private async Task AdoptAsync(SequencePaths sequence, Locations locations, Action? photoRead, CancellationToken cancellationToken) { var known = locations.AtFolder(sequence.RelativeFolder); - var manifest = await WithKnownFrameIdsAsync(SequenceAdopter.Build(known ?? Guid.CreateVersion7(), sequence, _writer.Options.Owner, cancellationToken), + var manifest = await WithKnownFrameIdsAsync(SequenceAdopter.Build(known ?? Guid.CreateVersion7(), sequence, _writer.Options.Owner, photoRead, cancellationToken), sequence, cancellationToken).ConfigureAwait(false); if (known is { } id && await _db.FrameRemovals.ListBySequenceAsync(id, cancellationToken).ConfigureAwait(false) is { Count: > 0 } removals) manifest = manifest with { Removed = SequenceMapping.ToTombstones(removals) }; @@ -525,10 +558,10 @@ public sealed class ArchiveIndexer } /// Keeps the unreadable sidecar aside (never deleted) and builds a new one from the photos. - private async Task ReplaceDamagedAsync(SequencePaths sequence, Locations locations, CancellationToken cancellationToken) + private async Task ReplaceDamagedAsync(SequencePaths sequence, Locations locations, Action? photoRead, CancellationToken cancellationToken) { File.Move(sequence.ManifestPath, $"{sequence.ManifestPath}.damaged-{DateTime.UtcNow:yyyyMMddHHmmss}"); - return await AdoptAsync(sequence, locations, cancellationToken).ConfigureAwait(false); + return await AdoptAsync(sequence, locations, photoRead, cancellationToken).ConfigureAwait(false); } private async Task WithKnownFrameIdsAsync(SequenceManifest manifest, SequencePaths sequence, CancellationToken cancellationToken) diff --git a/src/Chronos.Data/Archiving/ArchiveMaintenance.cs b/src/Chronos.Data/Archiving/ArchiveMaintenance.cs index 8a7a487d..905ab71a 100644 --- a/src/Chronos.Data/Archiving/ArchiveMaintenance.cs +++ b/src/Chronos.Data/Archiving/ArchiveMaintenance.cs @@ -123,10 +123,23 @@ public sealed class ArchiveMaintenance /// Number of maintenance steps (the job checkpoints after each). internal const int StepCount = 5; + /// + /// The key of each maintenance step, in order, as a job's progress names it (data each client words: + /// Jobs.Maintenance.Step.<Key>). + /// + internal static readonly IReadOnlyList StepKeys = ["leases", "temp", "packs", "duplicates", "vacuum"]; + /// Runs the maintenance steps from : stale leases, leftover temporary files, /// thumbnail pack compaction, duplicate flags, index vacuum (SQLite). A dry run only reports. - public async Task RunAsync(Archive archive, bool dryRun, int firstStep, Func stepDone, - CancellationToken cancellationToken = default) + public Task RunAsync(Archive archive, bool dryRun, int firstStep, Func stepDone, + CancellationToken cancellationToken = default) => + RunAsync(archive, dryRun, firstStep, stepDone, null, null, cancellationToken); + + /// + /// Told before each step with its index (0-based, ). + /// Told before the orphan count that follows the steps. + public async Task RunAsync(Archive archive, bool dryRun, int firstStep, Func stepDone, Func? stepStarting, + Func? orphansStarting, CancellationToken cancellationToken = default) { var paths = new ArchivePaths(archive.RootPath); if (!dryRun) ArchiveVolume.EnsureWritable(paths); @@ -142,6 +155,7 @@ public sealed class ArchiveMaintenance for (var step = firstStep; step < StepCount; step++) { cancellationToken.ThrowIfCancellationRequested(); + if (stepStarting is not null) await stepStarting(step).ConfigureAwait(false); switch (step) { case 0: @@ -162,6 +176,7 @@ public sealed class ArchiveMaintenance } await stepDone(step + 1).ConfigureAwait(false); } + if (orphansStarting is not null) await orphansStarting().ConfigureAwait(false); var orphans = await FindOrphansAsync(archive, cancellationToken).ConfigureAwait(false); return new MaintenanceReport(dryRun, leases, temps, packs, groups, flagChanges, orphans.UnindexedFiles, orphans.MissingFiles, reclaimable, reclaimed); } diff --git a/src/Chronos.Data/Archiving/ArchiveVerifier.cs b/src/Chronos.Data/Archiving/ArchiveVerifier.cs index e62d3ae6..82a726c6 100644 --- a/src/Chronos.Data/Archiving/ArchiveVerifier.cs +++ b/src/Chronos.Data/Archiving/ArchiveVerifier.cs @@ -11,6 +11,13 @@ public sealed record VerifyProblem(Guid SequenceId, Guid FrameId, string Relativ /// Where a verify stands: the next sequence (ordinal in the run) and the next frame index in it. public readonly record struct VerifyPosition(int Sequence, int Frame); +/// +/// Where a verify is after a frame: of hashed over the run, photo +/// of (1-based) of the sequence , which is +/// of (1-based) of the run. +/// +public readonly record struct VerifyProgress(long BytesDone, long BytesTotal, int Sequence, int Sequences, string Title, int Frame, int Frames); + /// Outcome of one verify run (frames before a resume point are counted by the run that checked them). public sealed record VerifyReport(int Sequences, long Checked, long Ok, long Hashed, IReadOnlyList Problems); @@ -41,9 +48,9 @@ public sealed class ArchiveVerifier /// Sequences to verify; null = the whole archive (ordered by folder). /// Called after each flush with the resume position, bytes done and bytes total. - /// Called after each frame with bytes done and bytes total (throughput and ETA). + /// Called after each frame with the bytes done and total (throughput and ETA) and where it is (photo x of y, sequence n of m). public async Task VerifyAsync(Archive archive, IReadOnlyList? sequenceIds, VerifyPosition resume, - Func checkpoint, Func? frameDone = null, CancellationToken cancellationToken = default) + Func checkpoint, Func? frameDone = null, CancellationToken cancellationToken = default) { var paths = new ArchivePaths(archive.RootPath); ArchiveVolume.EnsureWritable(paths); @@ -55,6 +62,7 @@ public sealed class ArchiveVerifier for (var s = resume.Sequence; s < targets.Count; s++) { var target = targets[s]; + var title = target.DisplayTitle; var sequence = paths.Sequence(target.Folder); var manifest = ManifestStore.ReadSequence(sequence.ManifestPath); var pending = new List(); @@ -68,7 +76,8 @@ public sealed class ArchiveVerifier var file = FileStamp.Of(sequence.File(manifest.Frames[i].File)); var check = await FrameVerifier.CheckAsync(sequence, manifest.Frames[i], read => bytesDone += read, cancellationToken).ConfigureAwait(false); checkedFrames++; - if (frameDone is not null) await frameDone(bytesDone, bytesTotal).ConfigureAwait(false); + if (frameDone is not null) + await frameDone(new VerifyProgress(bytesDone, bytesTotal, s + 1, targets.Count, title, i + 1, manifest.Frames.Count)).ConfigureAwait(false); if (check.Health == FrameHealth.Ok) ok++; else if (check.Health == FrameHealth.Hashed) hashed++; else problems.Add(new VerifyProblem(target.Id, check.Frame.Id, sequence.ArchiveRelative(check.Frame.File), check.Health)); diff --git a/src/Chronos.Data/Archiving/Jobs/ConvertJobHandler.cs b/src/Chronos.Data/Archiving/Jobs/ConvertJobHandler.cs index c7026207..614aba65 100644 --- a/src/Chronos.Data/Archiving/Jobs/ConvertJobHandler.cs +++ b/src/Chronos.Data/Archiving/Jobs/ConvertJobHandler.cs @@ -11,7 +11,8 @@ namespace Chronos.Data.Archiving.Jobs; /// () through , which settles what a crash left half-way, refuses /// when the volume lacks the space (measured again before each sequence and each photo), and converts one sequence at a /// time, each all or nothing, the photos confirmed alone and only while each holds the content confirmed (photos that came -/// in since stay as they are); its journal makes every stage resumable. Progress counts photos; the checkpoint only marks a +/// in since stay as they are); its journal makes every stage resumable. Progress counts photos, with the stage, photo x of y and +/// sequence n of m in the detail; the checkpoint only marks a /// resume, the journal says where. Each sequence whose frames were replaced is told as converted, each new sequence /// as created (), and the passes it needs (light analysis, a deep /// one when the source had it, thumbnails and proxies) are queued as follow-ups, as soon as it is done. Sequences left as @@ -45,7 +46,8 @@ internal sealed class ConvertJobHandler(ChronosDatabase db, MassConverter conver var result = await converter.RunAsync(archive, parameters, context.Job.Id, by, new ConvertCallbacks( (done, total) => context.ReportAsync(done, total), (done, total) => context.CheckpointAsync(Checkpoint, done, total), - context.Log, TellAsync, requests => QueueAsync(context, requests)), context.Cancellation).ConfigureAwait(false); + context.Log, TellAsync, requests => QueueAsync(context, requests), + (done, total, detail) => context.ReportAsync(done, total, detail), context.ReportItemAsync), context.Cancellation).ConfigureAwait(false); context.Log(Loc.L("Archive.Log.ConvertDone", result.Sequences.Count(s => s.Outcome == ConvertOutcome.Converted), result.Sequences.Count(s => s.Outcome == ConvertOutcome.Created), result.Frames)); var kept = result.Kept.Count(); diff --git a/src/Chronos.Data/Archiving/Jobs/EmptyTrashJobHandler.cs b/src/Chronos.Data/Archiving/Jobs/EmptyTrashJobHandler.cs index fac19808..0aed3b03 100644 --- a/src/Chronos.Data/Archiving/Jobs/EmptyTrashJobHandler.cs +++ b/src/Chronos.Data/Archiving/Jobs/EmptyTrashJobHandler.cs @@ -30,7 +30,9 @@ internal sealed class EmptyTrashJobHandler(ChronosDatabase db, SequenceTrash tra : 0; await context.ReportAsync(start, parameters.Entries.Count).ConfigureAwait(false); var result = await trash.EmptyAsync(archive, parameters, start, - (n, total) => context.CheckpointAsync(Prefix + n.ToString(CultureInfo.InvariantCulture), n, total), context.Cancellation).ConfigureAwait(false); + (n, total) => context.CheckpointAsync(Prefix + n.ToString(CultureInfo.InvariantCulture), n, total), + (n, total, title) => context.ReportAsync(n, total, new JobDetail(JobStep.Erase, title, 0, 0, n + 1, total, JobPartUnit.Entry)), + context.Cancellation).ConfigureAwait(false); context.Log(Loc.L("Archive.Log.TrashEmptied", result.Erased, CleanupSteps.Megabytes(result.Bytes))); foreach (var kept in result.Refused) context.Log(kept.LogLine); if (result.Refused.Count > 0) throw new InvalidOperationException(Loc.Plural("Archive.Error.TrashKept", result.Refused.Count)); diff --git a/src/Chronos.Data/Archiving/Jobs/ImageJobHandler.cs b/src/Chronos.Data/Archiving/Jobs/ImageJobHandler.cs index 5838fbf0..30e1bba2 100644 --- a/src/Chronos.Data/Archiving/Jobs/ImageJobHandler.cs +++ b/src/Chronos.Data/Archiving/Jobs/ImageJobHandler.cs @@ -7,13 +7,15 @@ namespace Chronos.Data.Archiving.Jobs; /// /// and over the target sequences. Progress counts frames -/// across all targets, so the speed and time left follow the photos even inside a long sequence; checkpoint: -/// sequence:frame. +/// across all targets, so the speed and time left follow the photos even inside a long sequence, reported frame after +/// frame with photo x of y of sequence n of m in the detail; checkpoint: sequence:frame. /// internal sealed class ImageJobHandler(ChronosDatabase db, ArchiveImages images, JobKind kind) : IJobHandler { public JobKind Kind => kind; + private JobStep Step => kind == JobKind.Thumbs ? JobStep.Thumbs : JobStep.Proxies; + public async Task RunAsync(JobContext context) { var force = ArchiveJobJson.Read(context.Job, ArchiveJobJson.Default.ImageJobParameters, new ImageJobParameters(false)).Force; @@ -40,12 +42,18 @@ internal sealed class ImageJobHandler(ChronosDatabase db, ArchiveImages images, } var index = s; var offset = before; - ValueTask Checkpoint(int nextFrame, int frames) => - context.CheckpointAsync(string.Create(CultureInfo.InvariantCulture, $"{index}:{nextFrame}"), Math.Min(total, offset + nextFrame), total); var start = s == first ? firstFrame : 0; + var detail = new JobDetail(Step, sequence.DisplayTitle, start, sequence.FrameCount, s + 1, targets.Count, JobPartUnit.Sequence); + // A checkpoint counts the frame it follows, as a report between them does. + ValueTask Checkpoint(int nextFrame, int frames) => + context.CheckpointAsync(string.Create(CultureInfo.InvariantCulture, $"{index}:{nextFrame}"), Math.Min(total, offset + nextFrame), total, + detail with { ItemDone = nextFrame, ItemTotal = frames }); + // Frame after frame between the checkpoints: counts only, the sequence's detail stays. + ValueTask FrameDone(int nextFrame, int frames) => context.ReportItemAsync(Math.Min(total, offset + nextFrame), total, nextFrame, frames); + await context.ReportAsync(Math.Min(total, offset + start), total, detail).ConfigureAwait(false); var result = kind == JobKind.Thumbs - ? await images.BuildThumbnailsAsync(archive, sequence, force, start, Checkpoint, context.Cancellation).ConfigureAwait(false) - : await images.BuildProxiesAsync(archive, sequence, force, start, Checkpoint, context.Cancellation).ConfigureAwait(false); + ? await images.BuildThumbnailsAsync(archive, sequence, force, start, Checkpoint, FrameDone, context.Cancellation).ConfigureAwait(false) + : await images.BuildProxiesAsync(archive, sequence, force, start, Checkpoint, FrameDone, context.Cancellation).ConfigureAwait(false); context.Log(kind == JobKind.Thumbs ? Loc.L("Archive.Log.ImagesDone", sequence.DisplayTitle, result.Built, result.Reused, result.Undecodable) : Loc.L("Archive.Log.ProxiesDone", sequence.DisplayTitle, result.Built, result.Reused, result.Undecodable, result.Waiting)); diff --git a/src/Chronos.Data/Archiving/Jobs/ImportJobHandler.cs b/src/Chronos.Data/Archiving/Jobs/ImportJobHandler.cs index 56f9868f..3b2142dc 100644 --- a/src/Chronos.Data/Archiving/Jobs/ImportJobHandler.cs +++ b/src/Chronos.Data/Archiving/Jobs/ImportJobHandler.cs @@ -9,7 +9,8 @@ using Chronos.Data.Processing; namespace Chronos.Data.Archiving.Jobs; /// -/// : executes the confirmed plan in its parameters; progress in bytes. Checkpoint: the +/// : executes the confirmed plan in its parameters; progress in bytes, with the file being +/// copied as photo x of y in the detail. Checkpoint: the /// number of plan items done. A removed card fails the job at a batch boundary; resuming it after re-insertion /// continues there. The sequences the import went into are then queued for light analysis. /// @@ -28,7 +29,11 @@ internal sealed class ImportJobHandler(ChronosDatabase db, ImportService imports context.Log(Loc.L("Archive.Log.ImportFailed", failed.Item.SourcePath, failed.Error)); await context.CheckpointAsync(batch.NextItem.ToString(CultureInfo.InvariantCulture), batch.Progress.BytesDone, batch.Progress.BytesTotal) .ConfigureAwait(false); - }, p => context.ReportAsync(p.BytesDone, p.BytesTotal, p.Current), context.Cancellation).ConfigureAwait(false); + }, p => p.Current is null + ? context.ReportItemAsync(p.BytesDone, p.BytesTotal, p.ItemsDone, p.ItemsTotal) + // The file being copied is photo x of y; the message keeps its name for the import screen. + : context.ReportAsync(p.BytesDone, p.BytesTotal, new JobDetail(JobStep.CopyPhoto, p.Current, Math.Min(p.ItemsDone + 1, p.ItemsTotal), p.ItemsTotal), + p.Current), context.Cancellation).ConfigureAwait(false); context.Log(Loc.L("Archive.Log.ImportDone", final.Copied, final.Skipped, final.Failed)); await AnalysisFollowUp.QueueAsync(db, context, await imports.SequencesOfAsync(parameters, context.Cancellation).ConfigureAwait(false)).ConfigureAwait(false); } diff --git a/src/Chronos.Data/Archiving/Jobs/MaintenanceJobHandler.cs b/src/Chronos.Data/Archiving/Jobs/MaintenanceJobHandler.cs index f7aa91c2..7d40a72c 100644 --- a/src/Chronos.Data/Archiving/Jobs/MaintenanceJobHandler.cs +++ b/src/Chronos.Data/Archiving/Jobs/MaintenanceJobHandler.cs @@ -7,8 +7,8 @@ namespace Chronos.Data.Archiving.Jobs; /// /// : stale leases, leftover temporary files, thumbnail pack compaction, duplicate -/// flags, the SQLite index vacuum (its reclaimable size in a dry run), then an orphan count. Checkpoint: the number of -/// steps done. +/// flags, the SQLite index vacuum (its reclaimable size in a dry run), then an orphan count. The step under way is in the +/// progress detail by its key (), step n of 5. Checkpoint: the number of steps done. /// internal sealed class MaintenanceJobHandler(ChronosDatabase db, ArchiveMaintenance maintenance) : IJobHandler { @@ -21,6 +21,9 @@ internal sealed class MaintenanceJobHandler(ChronosDatabase db, ArchiveMaintenan var first = int.TryParse(context.Checkpoint, NumberStyles.None, CultureInfo.InvariantCulture, out var step) ? step : 0; var report = await maintenance.RunAsync(archive, dryRun, first, done => context.CheckpointAsync(done.ToString(CultureInfo.InvariantCulture), done, ArchiveMaintenance.StepCount), + step => context.ReportAsync(step, ArchiveMaintenance.StepCount, + new JobDetail(JobStep.Maintenance, ArchiveMaintenance.StepKeys[step], 0, 0, step + 1, ArchiveMaintenance.StepCount, JobPartUnit.Step)), + () => context.ReportAsync(ArchiveMaintenance.StepCount, ArchiveMaintenance.StepCount, new JobDetail(JobStep.Check)), context.Cancellation).ConfigureAwait(false); if (dryRun) context.Log(Loc.L("Archive.Log.DryRun")); context.Log(Loc.L("Archive.Log.MaintenanceDone", report.StaleLeases.Count, report.TemporaryFiles.Count, report.CompactedPacks.Count, diff --git a/src/Chronos.Data/Archiving/Jobs/MoveJobHandler.cs b/src/Chronos.Data/Archiving/Jobs/MoveJobHandler.cs index 4c38ce38..eea013b6 100644 --- a/src/Chronos.Data/Archiving/Jobs/MoveJobHandler.cs +++ b/src/Chronos.Data/Archiving/Jobs/MoveJobHandler.cs @@ -12,7 +12,7 @@ namespace Chronos.Data.Archiving.Jobs; /// and title templates (). The job plans again from the templates and applies the plan only /// 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 +/// journal makes every step resumable. Progress counts the plan's steps (sequences), the one under way named in the detail; checkpoint: plan:<id> once /// the plan's journal is written, applied when the job fails once the plan is over (given up, or completed with /// sequences kept). Paused, cancelled or failed, the job stops between two sequences and holds the plan /// (), which an archive open then leaves to it (completing only file renames a step left @@ -78,7 +78,8 @@ internal sealed class MoveJobHandler(ChronosDatabase db, MassRenamer renamer, Fu { planId = p.Id; return context.CheckpointAsync(Checkpoint(p.Id), 0, total); - }, (n, changed) => StepDoneAsync(context, plan.Id, n, total, changed), context.Cancellation).ConfigureAwait(false); + }, (n, changed) => StepDoneAsync(context, plan.Id, n, total, changed), (n, step) => StepStartingAsync(context, n, total, step), context.Cancellation) + .ConfigureAwait(false); } } catch (OperationCanceledException) when (planId is { } id && context.Cancellation.IsCancellationRequested) @@ -113,8 +114,8 @@ internal sealed class MoveJobHandler(ChronosDatabase db, MassRenamer renamer, Fu { var total = Steps(journal.Plan); await context.ReportAsync(journal.Completed.Count, total).ConfigureAwait(false); - return await renamer.ResumeAsync(archive, journal.Plan.Id, (n, changed) => StepDoneAsync(context, journal.Plan.Id, n, total, changed), context.Cancellation) - .ConfigureAwait(false); + return await renamer.ResumeAsync(archive, journal.Plan.Id, (n, changed) => StepDoneAsync(context, journal.Plan.Id, n, total, changed), + (n, step) => StepStartingAsync(context, n, total, step), context.Cancellation).ConfigureAwait(false); } /// @@ -132,6 +133,11 @@ internal sealed class MoveJobHandler(ChronosDatabase db, MassRenamer renamer, Fu return present; } + /// Before each step: which sequence (its title, else its folder) and step n of m, in the detail. + private static ValueTask StepStartingAsync(JobContext context, int done, int total, RenameStep step) => + context.ReportAsync(done, total, new JobDetail(JobStep.Reorganize, step.ToTitle ?? step.FromTitle ?? step.FromFolder, 0, 0, Math.Min(done + 1, total), total, + JobPartUnit.Step)); + /// After each step: the checkpoint, then the sequences that step changed are told. private async ValueTask StepDoneAsync(JobContext context, Guid planId, int done, int total, IReadOnlyList changed) { diff --git a/src/Chronos.Data/Archiving/Jobs/ReportJobHandlers.cs b/src/Chronos.Data/Archiving/Jobs/ReportJobHandlers.cs index dfa3c8fe..0a6ae3d8 100644 --- a/src/Chronos.Data/Archiving/Jobs/ReportJobHandlers.cs +++ b/src/Chronos.Data/Archiving/Jobs/ReportJobHandlers.cs @@ -19,7 +19,8 @@ internal sealed class DuplicatesJobHandler(ChronosDatabase db, ArchiveMaintenanc public async Task RunAsync(JobContext context) { var archive = await JobArchive.LoadAsync(db, context.Job, context.Cancellation).ConfigureAwait(false); - await context.ReportAsync(0, 1).ConfigureAwait(false); + // No count while it reads: the bar runs without one rather than standing at 0 %. + await context.ReportAsync(0, 0, new JobDetail(JobStep.Check)).ConfigureAwait(false); var groups = await maintenance.FindDuplicatesAsync(archive.Id, context.Cancellation).ConfigureAwait(false); foreach (var group in groups.OrderByDescending(g => g.Frames.Count).ThenBy(g => g.Frames[0].RelativePath, StringComparer.Ordinal).Take(ListedGroups)) context.Log(Loc.L("Archive.Log.DuplicateGroup", group.Frames[0].RelativePath, group.Frames.Count - 1)); @@ -44,7 +45,8 @@ internal sealed class OrphansJobHandler(ChronosDatabase db, ArchiveMaintenance m public async Task RunAsync(JobContext context) { var archive = await JobArchive.LoadAsync(db, context.Job, context.Cancellation).ConfigureAwait(false); - await context.ReportAsync(0, 1).ConfigureAwait(false); + // No count while it reads: the bar runs without one rather than standing at 0 %. + await context.ReportAsync(0, 0, new JobDetail(JobStep.Check)).ConfigureAwait(false); var report = await maintenance.FindOrphansAsync(archive, context.Cancellation).ConfigureAwait(false); foreach (var missing in report.MissingSequences.Take(ListedFolders)) context.Log(Loc.L("Archive.Log.FolderMissing", missing.Folder)); diff --git a/src/Chronos.Data/Archiving/Jobs/ScanJobHandler.cs b/src/Chronos.Data/Archiving/Jobs/ScanJobHandler.cs index d571b3fd..d6de7b28 100644 --- a/src/Chronos.Data/Archiving/Jobs/ScanJobHandler.cs +++ b/src/Chronos.Data/Archiving/Jobs/ScanJobHandler.cs @@ -37,16 +37,16 @@ internal sealed class ScanJobHandler(ChronosDatabase db, ArchiveIndexer indexer, var parameters = ArchiveJobJson.Read(context.Job, ArchiveJobJson.Default.ScanParameters, new ScanParameters(false)); var mode = kind == JobKind.Rebuild ? ScanMode.Rebuild : parameters.Full ? ScanMode.Full : ScanMode.Incremental; var resume = context.Checkpoint is { } checkpoint && checkpoint.StartsWith(Prefix, StringComparison.Ordinal) ? checkpoint[Prefix.Length..] : null; - var summary = await indexer.ScanAsync(archive, mode, resume, async p => - { - if (p.Changed) await context.CheckpointAsync(Prefix + p.Folder, p.FoldersDone, p.FoldersTotal).ConfigureAwait(false); - else await context.ReportAsync(p.FoldersDone, p.FoldersTotal, p.Folder).ConfigureAwait(false); - }, context.Cancellation).ConfigureAwait(false); + // Listing the folders reads the whole tree before the first one is counted. + await context.ReportAsync(context.Done, context.Total, new JobDetail(JobStep.List)).ConfigureAwait(false); + var progress = new ScanReporter(context); + var summary = await indexer.ScanAsync(archive, mode, resume, progress.ReportAsync, context.Cancellation).ConfigureAwait(false); foreach (var (folder, error) in summary.Failed) context.Log(Loc.L("Archive.Log.FolderFailed", folder, error)); context.Log(Loc.L("Archive.Log.ScanDone", summary.Folders, summary.Indexed, summary.Adopted, summary.Removed)); // A resumed scan may have indexed its folders before the interruption. if (summary.Indexed > 0 || resume is not null) { + await context.ReportAsync(summary.Folders, summary.Folders, new JobDetail(JobStep.FollowUps)).ConfigureAwait(false); var awaiting = await indexer.AwaitingFolderAsync(new ArchivePaths(archive.RootPath), await db.Sequences.ListLocationsAsync(archive.Id, context.Cancellation).ConfigureAwait(false), context.Cancellation).ConfigureAwait(false); var unanalysed = (await AnalysisFollowUp.UnanalysedAsync(db, archive.Id, context.Cancellation).ConfigureAwait(false)) @@ -64,6 +64,30 @@ internal sealed class ScanJobHandler(ChronosDatabase db, ArchiveIndexer indexer, } } + /// + /// The scan's progress as the job's: folders on the bar; folder n of m, checked or indexed, with the photo being read + /// in an adopted or reconciled folder, in the detail. A changed folder done is the resume point. + /// + private sealed class ScanReporter(JobContext context) + { + private string? _indexing; + + public ValueTask ReportAsync(ScanProgress p) + { + if (p.Indexing) + { + // Photo after photo inside the folder: counts only, the folder's detail stays. + if (string.Equals(_indexing, p.Folder, StringComparison.Ordinal)) return context.ReportItemAsync(p.FoldersDone, p.FoldersTotal, p.PhotosDone, p.PhotosTotal); + _indexing = p.Folder; + return context.ReportAsync(p.FoldersDone, p.FoldersTotal, + new JobDetail(JobStep.Index, p.Folder, p.PhotosDone, p.PhotosTotal, p.FoldersDone + 1, p.FoldersTotal, JobPartUnit.Folder)); + } + _indexing = null; + if (p.Changed) return context.CheckpointAsync(Prefix + p.Folder, p.FoldersDone, p.FoldersTotal); + return context.ReportAsync(p.FoldersDone, p.FoldersTotal, new JobDetail(JobStep.Check, p.Folder, 0, 0, p.FoldersDone, p.FoldersTotal, JobPartUnit.Folder)); + } + } + /// /// Queues a background (thumbnails or proxies) of each sequence this run indexed whose /// flag is clear: new and adopted sequences, and those whose photos changed (the scan clears the diff --git a/src/Chronos.Data/Archiving/Jobs/VerifyJobHandler.cs b/src/Chronos.Data/Archiving/Jobs/VerifyJobHandler.cs index 8b8190be..409d6f89 100644 --- a/src/Chronos.Data/Archiving/Jobs/VerifyJobHandler.cs +++ b/src/Chronos.Data/Archiving/Jobs/VerifyJobHandler.cs @@ -6,7 +6,10 @@ using Chronos.Data.Jobs; namespace Chronos.Data.Archiving.Jobs; -/// ; progress in bytes hashed. Checkpoint: sequence:frame. +/// +/// ; progress in bytes hashed, with photo x of y of sequence n of m in the detail. Checkpoint: +/// sequence:frame. +/// internal sealed class VerifyJobHandler(ChronosDatabase db, ArchiveVerifier verifier) : IJobHandler { /// Problems listed one per log line; the rest are counted (the index flags them all). @@ -18,10 +21,17 @@ internal sealed class VerifyJobHandler(ChronosDatabase db, ArchiveVerifier verif { var archive = await JobArchive.LoadAsync(db, context.Job, context.Cancellation).ConfigureAwait(false); var parameters = ArchiveJobJson.Read(context.Job, ArchiveJobJson.Default.VerifyParameters, new VerifyParameters(null)); + var part = 0; var report = await verifier.VerifyAsync(archive, parameters.SequenceIds, Parse(context.Checkpoint), (position, done, total) => context.CheckpointAsync( string.Create(CultureInfo.InvariantCulture, $"{position.Sequence}:{position.Frame}"), done, total), - (done, total) => context.ReportAsync(done, total), + p => + { + // Photo after photo: counts only; a new detail when the sequence changes. + if (p.Sequence == part) return context.ReportItemAsync(p.BytesDone, p.BytesTotal, p.Frame, p.Frames); + part = p.Sequence; + return context.ReportAsync(p.BytesDone, p.BytesTotal, new JobDetail(JobStep.Verify, p.Title, p.Frame, p.Frames, p.Sequence, p.Sequences, JobPartUnit.Sequence)); + }, context.Cancellation).ConfigureAwait(false); foreach (var problem in report.Problems.Take(LoggedProblems)) { @@ -35,6 +45,7 @@ internal sealed class VerifyJobHandler(ChronosDatabase db, ArchiveVerifier verif context.Log(Loc.L("Archive.Log.VerifyDone", report.Checked, report.Ok, report.Hashed, report.Problems.Count)); } + private static VerifyPosition Parse(string? checkpoint) { var parts = checkpoint?.Split(':'); diff --git a/src/Chronos.Data/Archiving/MassConverter.cs b/src/Chronos.Data/Archiving/MassConverter.cs index 203e92f6..44ade12b 100644 --- a/src/Chronos.Data/Archiving/MassConverter.cs +++ b/src/Chronos.Data/Archiving/MassConverter.cs @@ -81,10 +81,13 @@ public sealed record ConvertResult(IReadOnlyList Sequence /// How a running conversion reports: progress in photos, a checkpoint after each sequence, job log lines, each sequence it /// came to an end with in this run once its outcome is journaled (to tell the sequences it changed or made while the rest /// of the job runs, as a Reorganize tells each step), and the passes a sequence it converted or made needs, to queue then -/// too (the journal says whether they were, so a pause, a yield, a stop or a crash later loses none). +/// too (the journal says whether they were, so a pause, a yield, a stop or a crash later loses none). : each +/// stage of a sequence as it starts (its staged photos checked again, converted, taking their place), sequence n of m, with +/// the progress; : each photo staged, with photo x of y of the sequence (else ). /// internal sealed record ConvertCallbacks(Func Progress, Func Checkpoint, Action Log, - Func? Done = null, Func, ValueTask>? Queue = null); + Func? Done = null, Func, ValueTask>? Queue = null, + Func? Step = null, Func? Photo = null); /// /// Who asked for a conversion: the user's name, kept in the trash records of a Replace, and id, the owner of a new sequence @@ -327,8 +330,10 @@ public sealed class MassConverter var results = new List(); var followUps = new List(); + var part = 0; foreach (var step in steps) { + part++; cancellationToken.ThrowIfCancellationRequested(); var noted = journal.Of(step.Id); var final = noted?.Final == true; @@ -350,7 +355,7 @@ public sealed class MassConverter // how far off the estimate is. EnsureSpace(unstaged.Values.Sum(), space); done = await ConvertOneAsync(archive, paths, step, row, options, parameters.Mode, jobId, by, journal, confirmed, pins, staged, progress, space, - callbacks, cancellationToken).ConfigureAwait(false); + callbacks, (part, steps.Count), cancellationToken).ConfigureAwait(false); } unstaged.Remove(step.Id); var result = done.Result; @@ -390,11 +395,11 @@ public sealed class MassConverter /// /// One sequence: under its lease, its sidecar settled, planned again and held to what was confirmed (the photos pinned the /// first time); then stage A without the lease, and stage B. A New sequence that has its copy already is not converted - /// again (). + /// again (). : which sequence of the job it is, for the progress detail. /// private async Task ConvertOneAsync(Archive archive, ArchivePaths paths, ConvertSequence step, Sequence row, ConvertOptions options, ConvertMode mode, Guid jobId, ConvertRequester by, ConvertJournal journal, ConfirmedPhotos confirmedPhotos, PinLog pins, StagedLog staged, - Progress progress, SpaceWatch space, ConvertCallbacks callbacks, CancellationToken cancellationToken) + Progress progress, SpaceWatch space, ConvertCallbacks callbacks, (int Part, int Parts) place, CancellationToken cancellationToken) { // Another job holds it now (a Reorganize paused since the job started, a render, a conversion of it queued first): it // waits for the retry. @@ -492,13 +497,17 @@ public sealed class MassConverter ? await FiledAsync(archive, key, cancellationToken).ConfigureAwait(false) : new HashSet(StringComparer.OrdinalIgnoreCase); var noted = staged.Of(row.Id, planned.FramesVersion); + // What an earlier attempt staged is hashed again before it is taken. + if (noted.Count > 0) await StepAsync(callbacks, progress, new JobDetail(JobStep.Verify, row.DisplayTitle, 0, 0, place.Part, place.Parts, JobPartUnit.Sequence)).ConfigureAwait(false); var ready = await Task.Run(() => Ready(manifest, planned, noted, staging, filed), cancellationToken).ConfigureAwait(false); progress.Count(row.Id, planned.Frames.Count, ready.Count); - await callbacks.Progress(progress.Done, progress.Total).ConfigureAwait(false); + await StepAsync(callbacks, progress, new JobDetail(JobStep.Convert, row.DisplayTitle, ready.Count, planned.Frames.Count, place.Part, place.Parts, JobPartUnit.Sequence)) + .ConfigureAwait(false); var failure = await StageAsync(row, manifest, folder, planned, ready, staging, options, staged, progress, space, callbacks, cancellationToken) .ConfigureAwait(false); if (failure is not null) return new StepDone(Result(row, ConvertOutcome.Failed, error: failure)); + await StepAsync(callbacks, progress, new JobDetail(JobStep.Replace, row.DisplayTitle, 0, 0, place.Part, place.Parts, JobPartUnit.Sequence)).ConfigureAwait(false); try { return mode == ConvertMode.Replace @@ -694,6 +703,10 @@ public sealed class MassConverter return planned.Frames.All(p => frames.TryGetValue(p.FrameId, out var f) && string.Equals(f.Sha256, p.Sha256, StringComparison.OrdinalIgnoreCase)); } + /// A stage of a sequence starts: told with its detail when the caller takes one, else as plain progress. + private static ValueTask StepAsync(ConvertCallbacks callbacks, Progress progress, JobDetail detail) => + callbacks.Step is { } step ? step(progress.Done, progress.Total, detail) : callbacks.Progress(progress.Done, progress.Total); + private static ConvertSequenceResult Result(Sequence row, ConvertOutcome outcome, int frames = 0, string? error = null) => new(row.Id, row.DisplayTitle, outcome, frames, Error: error); @@ -770,7 +783,8 @@ public sealed class MassConverter staged.Append(row.Id, planned.FramesVersion, conversion); ready[conversion.FrameId] = conversion; space.Staged(conversion.Size, estimates[conversion.FrameId]); - await callbacks.Progress(++progress.Done, progress.Total).ConfigureAwait(false); + if (callbacks.Photo is { } photo) await photo(++progress.Done, progress.Total, ready.Count, planned.Frames.Count).ConfigureAwait(false); + else await callbacks.Progress(++progress.Done, progress.Total).ConfigureAwait(false); }, cancellationToken); for (var i = 0; i < todo.Count && failure is null; i++) { diff --git a/src/Chronos.Data/Archiving/MassRenamer.cs b/src/Chronos.Data/Archiving/MassRenamer.cs index 97401b30..0af5679a 100644 --- a/src/Chronos.Data/Archiving/MassRenamer.cs +++ b/src/Chronos.Data/Archiving/MassRenamer.cs @@ -201,10 +201,16 @@ public sealed class MassRenamer /// Told once the plan's journal is written, before any step (a job saves the plan's id as its checkpoint). /// Told after each step is journaled, with the number of steps done and the sequences that step changed. public Task ApplyAsync(Archive archive, RenamePlan plan, Func? started, Func, ValueTask>? stepDone, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default) => + ApplyAsync(archive, plan, started, stepDone, null, cancellationToken); + + /// + /// Told before each step, with the number of steps done and the step (a job's progress names its sequence). + public Task ApplyAsync(Archive archive, RenamePlan plan, Func? started, Func, ValueTask>? stepDone, + Func? stepStarting, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(plan); - return RunAsync(archive, new RenameJournal(plan, []), resuming: false, started, stepDone, cancellationToken); + return RunAsync(archive, new RenameJournal(plan, []), resuming: false, started, stepDone, stepStarting, cancellationToken); } /// @@ -216,12 +222,18 @@ public sealed class MassRenamer /// /// Told after each step is journaled, with the number of steps done and the sequences that step changed. /// A held plan's remaining steps no longer match the archive; nothing more changed. - public async Task ResumeAsync(Archive archive, Guid planId, Func, ValueTask>? stepDone = null, - CancellationToken cancellationToken = default) + public Task ResumeAsync(Archive archive, Guid planId, Func, ValueTask>? stepDone = null, + CancellationToken cancellationToken = default) => + ResumeAsync(archive, planId, stepDone, null, cancellationToken); + + /// + /// Told before each step, with the number of steps done and the step (a job's progress names its sequence). + public async Task ResumeAsync(Archive archive, Guid planId, Func, ValueTask>? stepDone, + Func? stepStarting, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(archive); if (RenameJournal.Read(new ArchivePaths(archive.RootPath), planId) is not { } journal) return null; - return await RunAsync(archive, journal with { Held = false }, resuming: !journal.Held, null, stepDone, cancellationToken).ConfigureAwait(false); + return await RunAsync(archive, journal with { Held = false }, resuming: !journal.Held, null, stepDone, stepStarting, cancellationToken).ConfigureAwait(false); } /// @@ -251,7 +263,7 @@ public sealed class MassRenamer var pending = journals.Where(j => !j.Held).ToList(); foreach (var journal in pending) { - await RunAsync(archive, journal, resuming: true, null, (_, changed) => TellAsync(_writer.Options.SequenceChanged, changed), cancellationToken) + await RunAsync(archive, journal, resuming: true, null, (_, changed) => TellAsync(_writer.Options.SequenceChanged, changed), null, cancellationToken) .ConfigureAwait(false); } return pending.Count; @@ -308,7 +320,7 @@ public sealed class MassRenamer /// (or keep what no longer fits) instead of failing the rename: their sidecars still carry the ids, so the next scan /// indexes them wherever they ended up. private async Task RunAsync(Archive archive, RenameJournal journal, bool resuming, Func? started, - Func, ValueTask>? stepDone, CancellationToken cancellationToken) + Func, ValueTask>? stepDone, Func? stepStarting, CancellationToken cancellationToken) { var paths = new ArchivePaths(archive.RootPath); ArchiveVolume.EnsureWritable(paths); @@ -348,6 +360,7 @@ public sealed class MassRenamer carried = [.. steps.Where(c => c.Carried && !completed.Contains(c.SequenceId) && Carrier(steps, c) == step)]; along = await LeftInsideAsync(steps, step, completed, cancellationToken).ConfigureAwait(false); } + if (stepStarting is not null) await stepStarting(completed.Count, step).ConfigureAwait(false); var before = result.Changed.Count; await ApplyStepAsync(archive, paths, journal.Plan, step, carried, along, resuming, result, cancellationToken).ConfigureAwait(false); completed.Add(step.SequenceId); diff --git a/src/Chronos.Data/Archiving/SequenceTrash.Empty.cs b/src/Chronos.Data/Archiving/SequenceTrash.Empty.cs index 2476a483..7f223d91 100644 --- a/src/Chronos.Data/Archiving/SequenceTrash.Empty.cs +++ b/src/Chronos.Data/Archiving/SequenceTrash.Empty.cs @@ -169,8 +169,16 @@ public sealed partial class SequenceTrash /// /// Entries done so far (the resume point) and their number. /// The trash no longer holds exactly the planned entries; nothing was erased. + internal Task EmptyAsync(Archive archive, EmptyTrashParameters parameters, int start, Func progress, + CancellationToken cancellationToken) => + EmptyAsync(archive, parameters, start, progress, null, cancellationToken); + + /// + /// + /// Told before each entry with the entries done, their number and the entry's title (null when the trash no longer holds it). + /// internal async Task EmptyAsync(Archive archive, EmptyTrashParameters parameters, int start, Func progress, - CancellationToken cancellationToken) + Func? erasing, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(archive); ArgumentNullException.ThrowIfNull(parameters); @@ -188,7 +196,9 @@ public sealed partial class SequenceTrash { cancellationToken.ThrowIfCancellationRequested(); var item = items[i]; - if (current.Entries.FirstOrDefault(e => e.Name == item.Name) is { } entry) + var found = current.Entries.FirstOrDefault(e => e.Name == item.Name); + if (erasing is not null) await erasing(i, items.Count, found?.Title).ConfigureAwait(false); + if (found is { } entry) { if (EntryFingerprint(entry) != item.Fingerprint) { diff --git a/src/Chronos.Data/Housekeeping/HousekeepingJobHandlers.cs b/src/Chronos.Data/Housekeeping/HousekeepingJobHandlers.cs index 0b675704..ac9a86ce 100644 --- a/src/Chronos.Data/Housekeeping/HousekeepingJobHandlers.cs +++ b/src/Chronos.Data/Housekeeping/HousekeepingJobHandlers.cs @@ -29,7 +29,8 @@ internal sealed class BackupJobHandler(ChronosDatabase db, string? directory) : : "An index without a file cannot be backed up."); var own = Math.Clamp(ArchiveJobJson.Read(context.Job, ArchiveJobJson.Default.BackupParameters, new BackupParameters(DatabaseBackups.Keep)).Keep, 1, MaxKeep); var keep = int.Max(own, await DatabaseBackups.ScheduledKeepAsync(db, context.Cancellation).ConfigureAwait(false)); - await context.ReportAsync(0, 1).ConfigureAwait(false); + // No count while the copy is written: the bar runs without one rather than standing at 0 %. + await context.ReportAsync(0, 0, new JobDetail(JobStep.Backup)).ConfigureAwait(false); var copy = await db.BackupAsync(directory ?? DatabaseBackups.DefaultDirectory(path), keep, context.Cancellation).ConfigureAwait(false); context.Log(Loc.L("Archive.Log.BackupDone", copy, CleanupSteps.Megabytes(new FileInfo(copy).Length), keep)); await context.ReportAsync(1, 1).ConfigureAwait(false); @@ -56,7 +57,8 @@ internal sealed class CleanupJobHandler(ChronosDatabase db, IReadOnlyList). + await context.ReportAsync(i, names.Count, new JobDetail(JobStep.Cleanup, names[i], 0, 0, i + 1, names.Count, JobPartUnit.Step)).ConfigureAwait(false); var step = steps.FirstOrDefault(s => string.Equals(s.Name, names[i], StringComparison.Ordinal)); if (step is null) { diff --git a/src/Chronos.Data/Processing/Jobs/AnalyseJobHandler.cs b/src/Chronos.Data/Processing/Jobs/AnalyseJobHandler.cs index d6069534..b24599a6 100644 --- a/src/Chronos.Data/Processing/Jobs/AnalyseJobHandler.cs +++ b/src/Chronos.Data/Processing/Jobs/AnalyseJobHandler.cs @@ -9,7 +9,7 @@ namespace Chronos.Data.Processing.Jobs; /// /// and over the target sequences, one after the -/// other. Progress counts sequences (light) or frames (deep). A sequence that cannot be analysed is logged and the +/// other. Progress counts sequences (light) or frames (deep), with sequence k of m (and photo x of y in a deep pass) in the detail. A sequence that cannot be analysed is logged and the /// others still run; the job then fails, and a retry analyses only the failed ones. An offline archive stops the job at /// once. Checkpoint: the next target and the failed ones (next[;i,j…]). A deep pass interrupted inside a /// sequence resumes from that sequence's analysis.partial. @@ -25,8 +25,13 @@ internal sealed class AnalyseJobHandler(ChronosDatabase db, SequenceAnalyser ana var (next, retry) = Parse(context.Checkpoint, targets.Count); // Deep progress is in frames across all targets, so the bar and the ETA cover the whole job. var units = new long[targets.Count]; - for (var i = 0; i < targets.Count; i++) - units[i] = deep ? (await db.Sequences.GetAsync(targets[i], context.Cancellation).ConfigureAwait(false))?.FrameCount ?? 0 : 1; + var titles = new string?[targets.Count]; + for (var i = 0; i < targets.Count && deep; i++) + { + var sequence = await db.Sequences.GetAsync(targets[i], context.Cancellation).ConfigureAwait(false); + (units[i], titles[i]) = (sequence?.FrameCount ?? 0, sequence?.DisplayTitle); + } + if (!deep) Array.Fill(units, 1L); var total = units.Sum(); var done = Enumerable.Range(0, next).Where(i => !retry.Contains(i)).Sum(i => units[i]); var failed = new List(); @@ -37,7 +42,12 @@ internal sealed class AnalyseJobHandler(ChronosDatabase db, SequenceAnalyser ana context.Cancellation.ThrowIfCancellationRequested(); var i = order[k]; var before = done; - var chain = new ProgressChain(context.ReportAsync); + var frames = units[i]; + // Sequence k of m in the detail, with photo x of y in a deep pass (counts only, the sequence's detail stays). + var title = deep ? titles[i] : (await db.Sequences.GetAsync(targets[i], context.Cancellation).ConfigureAwait(false))?.DisplayTitle; + await context.ReportAsync(done, total, new JobDetail(JobStep.Analyse, title, 0, deep ? frames : 0, k + 1, order.Length, JobPartUnit.Sequence)) + .ConfigureAwait(false); + var chain = new ProgressChain((d, t, _) => context.ReportItemAsync(d, t, d - before, frames)); var progress = deep ? chain.For(p => (before + p.Done, total, null)) : null; try { diff --git a/src/Chronos.Data/Processing/Jobs/RenderJobHandler.cs b/src/Chronos.Data/Processing/Jobs/RenderJobHandler.cs index 51b9afaf..8d0810ae 100644 --- a/src/Chronos.Data/Processing/Jobs/RenderJobHandler.cs +++ b/src/Chronos.Data/Processing/Jobs/RenderJobHandler.cs @@ -28,6 +28,46 @@ namespace Chronos.Data.Processing.Jobs; /// internal sealed class RenderJobHandler(ChronosDatabase db, ProcessingOptions options, FrameTiers tiers) : IJobHandler { + /// + /// A render's progress as the job's (owner review 5, #65): the frames measured first (), + /// then each output encoded, frame x of y when it is the last one left (the frames of an earlier one are not told + /// apart from the next one's), output n of m, then its file hashed (). The detail carries + /// keys and data only; the message keeps the host's own words for the desktop's log line, as before. Shared with the + /// workspace's local render. + /// + internal sealed class RenderReporter(JobContext context, string title, IReadOnlyList<(int Index, ExportTarget Target)> entries) + { + private long _start = -1; + private int _part; + private bool _last; + + private int Parts => entries.Count > 1 ? entries.Count : 0; + + public ValueTask PreparingAsync() => context.ReportAsync(context.Done, context.Total, new JobDetail(JobStep.Analyse, title), context.Message); + + /// Output starts: the checkpoint names it, and the detail says which of the outputs it is. + public async ValueTask StartingAsync(int index, string checkpoint) + { + var at = 0; + while (at < entries.Count && entries[at].Index != index) at++; + (_part, _last, _start) = (at + 1, at + 1 >= entries.Count, context.Done); + await context.ReportAsync(context.Done, context.Total, new JobDetail(JobStep.Encode, title, 0, _last ? Math.Max(0, context.Total - _start) : 0, + Parts > 0 ? _part : 0, Parts, Parts > 0 ? JobPartUnit.Render : JobPartUnit.None), at < entries.Count ? entries[at].Target.PresetName : null) + .ConfigureAwait(false); + await context.CheckpointAsync(checkpoint, context.Done, context.Total).ConfigureAwait(false); + } + + /// The render's own progress: frames measured, then frames encoded (counts only, the output's detail stays). + public ValueTask ReportAsync(long done, long total, string? message) => + _start < 0 + ? context.ReportAsync(done, total, message) + : context.ReportItemAsync(done, total, Math.Max(0, done - _start), _last ? Math.Max(0, total - _start) : 0); + + public ValueTask VerifyingAsync(string output) => + context.ReportAsync(context.Done, context.Total, new JobDetail(JobStep.Verify, output, 0, 0, Parts > 0 ? _part : 0, Parts, + Parts > 0 ? JobPartUnit.Render : JobPartUnit.None), Loc.L("Export.Job.Verifying")); + } + public JobKind Kind => JobKind.Render; public Task RunAsync(JobContext context) => RunAsync(context, (target, _) => target); @@ -83,6 +123,8 @@ internal sealed class RenderJobHandler(ChronosDatabase db, ProcessingOptions opt if (targets.Count == 0) return; var companions = await GprCompanions.FindAsync(db, archive, frames.Frames, cancellation).ConfigureAwait(false); + var reporter = new RenderReporter(context, sequence.DisplayTitle, targets); + await reporter.PreparingAsync().ConfigureAwait(false); IReadOnlyList outcomes; await using (var render = new SequenceRender(frames, project, SequenceAnalyser.ReadReport(folder, frames), options, originals: !parameters.UseProxies, companions)) @@ -94,7 +136,7 @@ internal sealed class RenderJobHandler(ChronosDatabase db, ProcessingOptions opt string? sha = null; if (File.Exists(result.OutputPath)) { - await context.ReportAsync(context.Done, context.Total, Loc.L("Export.Job.Verifying")).ConfigureAwait(false); + await reporter.VerifyingAsync(Path.GetFileName(result.OutputPath)).ConfigureAwait(false); sha = await ContentHash.Sha256Async(result.OutputPath, cancellationToken: CancellationToken.None).ConfigureAwait(false); } var entity = result.ToEntity(sequence.Id, target.PresetName, settingsJson, options.ProducedBy) with @@ -118,14 +160,14 @@ internal sealed class RenderJobHandler(ChronosDatabase db, ProcessingOptions opt } if (parameters.IsStill) - outcomes = [await StillAsync(context, render, targets[0], still, sequence, project.Export, folder, names, done, Record).ConfigureAwait(false)]; + outcomes = [await StillAsync(context, reporter, render, targets[0], still, sequence, project.Export, folder, names, done, Record).ConfigureAwait(false)]; else outcomes = await render.RenderAllAsync( targets, (target, setup) => names.Reserve(taken => ExportNaming.OutputPath(project.Export, folder.Exports, SequenceRender.NameContext(sequence, target, setup), taken)), - (index, path) => context.CheckpointAsync(new RenderCheckpoint(done, index, path, sequence.Folder).ToJson(), context.Done, context.Total), + (index, path) => reporter.StartingAsync(index, new RenderCheckpoint(done, index, path, sequence.Folder).ToJson()), Record, - context.ReportAsync, + reporter.ReportAsync, cancellation).ConfigureAwait(false); if (render.StandIns.Count > 0) context.Log(Loc.L("Export.Log.StandIns", string.Join(", ", render.StandIns.Select(i => (i + 1).ToString(Loc.Culture))))); @@ -153,7 +195,7 @@ internal sealed class RenderJobHandler(ChronosDatabase db, ProcessingOptions opt /// The still of a still job: frame saved through the job's preset under the export's name and /// the frame number (), checkpointed and recorded like a video's output. /// - private static async Task StillAsync(JobContext context, SequenceRender render, (int Index, ExportTarget Target) entry, int frame, + private static async Task StillAsync(JobContext context, RenderReporter reporter, SequenceRender render, (int Index, ExportTarget Target) entry, int frame, Sequence sequence, ExportSettings export, SequencePaths folder, OutputNames names, List done, Func record) { @@ -164,8 +206,8 @@ internal sealed class RenderJobHandler(ChronosDatabase db, ProcessingOptions opt target, frame, setup => names.Reserve(taken => SequenceRender.StillPath(export, folder.Exports, SequenceRender.NameContext(sequence, target, setup), frame, taken)), - path => context.CheckpointAsync(new RenderCheckpoint(done, index, path, sequence.Folder).ToJson(), context.Done, context.Total), - context.ReportAsync, + path => reporter.StartingAsync(index, new RenderCheckpoint(done, index, path, sequence.Folder).ToJson()), + reporter.ReportAsync, context.Cancellation).ConfigureAwait(false); await record(index, target, result).ConfigureAwait(false); return new TargetOutcome(target, result, null); diff --git a/src/Chronos.Data/Processing/RenderNodeClient.cs b/src/Chronos.Data/Processing/RenderNodeClient.cs index 5108bab3..3bfea789 100644 --- a/src/Chronos.Data/Processing/RenderNodeClient.cs +++ b/src/Chronos.Data/Processing/RenderNodeClient.cs @@ -11,6 +11,7 @@ using Chronos.Core.Project; using Chronos.Core.Render; using Chronos.Core.Video; using Chronos.Data.Archiving; +using Chronos.Data.Jobs; using Chronos.Protocol; using Chronos.Protocol.Client; @@ -261,6 +262,7 @@ public sealed class RenderNodeClient : IAsyncDisposable }; IReadOnlyList outcomes; + reporter.Step(JobStep.Encode, sequence.DisplayTitle); await using (var render = new SequenceRender(input, project, null, _processing)) { outcomes = await render.RenderAllAsync( @@ -271,6 +273,8 @@ public sealed class RenderNodeClient : IAsyncDisposable { // Remarks first: completing the upload ends the job on the server. foreach (var remark in SequenceRender.Remarks(result)) await reporter.LogAsync(remark).ConfigureAwait(false); + reporter.Step(JobStep.Upload, Path.GetFileName(result.OutputPath)); + await reporter.ResendAsync().ConfigureAwait(false); await UploadAsync(reporter.NodeId, claimed.Job.Id, t, result, cancellationToken).ConfigureAwait(false); }, reporter.ReportAsync, @@ -374,6 +378,8 @@ public sealed class RenderNodeClient : IAsyncDisposable var fetched = claimed.Frames.Where(f => ((FrameFlags)f.Flags & NotFetched) == 0 && (Proxy(f) || !undecodable.Contains(f.Id))).ToList(); var done = 0; var total = fetched.Count; + // The log line stays for servers that show no detail. + reporter.Step(JobStep.Download, null); await reporter.ReportAsync(0, total, Loc.L("Export.Job.Downloading")).ConfigureAwait(false); var downloads = fetched.GroupBy(f => Proxy(f) || f.Sha256.Length == 0 ? f.Id.ToString("N") : f.Sha256.ToLowerInvariant()).ToList(); await Parallel.ForEachAsync(downloads, new ParallelOptions { MaxDegreeOfParallelism = _options.Downloads, CancellationToken = cancellationToken }, @@ -575,11 +581,15 @@ public sealed class RenderNodeClient : IAsyncDisposable }; /// - /// Progress of the job in flight to the server, at most every interval (and at the end). A refusal (409) means the - /// job was cancelled or given to another node: the job's token is cancelled. + /// Progress of the job in flight to the server, at most every interval (and at the end), with what the node does now + /// (: frames downloaded, encoded, the output uploaded; a server that shows no detail + /// ignores it). A refusal (409) means the job was cancelled or given to another node: the job's token is cancelled. /// private sealed class NodeReporter(ChronosClient client, Guid nodeId, Guid jobId, TimeSpan interval, CancellationTokenSource job) { + private JobStep _step; + private string? _item; + private bool _stepChanged; private readonly Stopwatch _clock = Stopwatch.StartNew(); private readonly SemaphoreSlim _gate = new(1, 1); private TimeSpan _last = TimeSpan.MinValue; @@ -589,9 +599,26 @@ public sealed class RenderNodeClient : IAsyncDisposable public Guid NodeId => nodeId; + /// What the node does from now on; its next report is sent at once. + public void Step(JobStep step, string? item) + { + _gate.Wait(CancellationToken.None); + try + { + (_step, _item, _stepChanged) = (step, item, true); + } + finally + { + _gate.Release(); + } + } + /// Progress, sent at most every interval; a stage message is sent when it changes. public ValueTask ReportAsync(long done, long total, string? message) => SendAsync(done, total, message, remark: false); + /// The progress last reported, sent again with the step set since. + public ValueTask ResendAsync() => SendAsync(-1, -1, null, remark: false); + /// A line for the job's log on the server, sent with the progress last reported. public ValueTask LogAsync(string line) => SendAsync(0, 0, line, remark: true); @@ -607,13 +634,17 @@ public sealed class RenderNodeClient : IAsyncDisposable } else { + if (done < 0) (done, total) = (_lastDone, _lastTotal); var now = _clock.Elapsed; var line = message is not null && message != _lastMessage ? message : null; - if (line is null && done < total && now - _last < interval) return; + if (line is null && !_stepChanged && done < total && now - _last < interval) return; double? rate = _last == TimeSpan.MinValue || done < _lastDone ? null : (done - _lastDone) / double.Max((now - _last).TotalSeconds, 1e-3); - (_last, _lastDone, _lastTotal) = (now, done, total); + (_last, _lastDone, _lastTotal, _stepChanged) = (now, done, total, false); if (line is not null) _lastMessage = line; - progress = new NodeProgress(done, total, rate, line); + var detail = _step == JobStep.None ? null + : new JobDetailDto(JobWire.Step(_step), _item is { Length: > JobDetail.MaxItemLength } item ? item[..JobDetail.MaxItemLength] : _item, + _step == JobStep.Upload ? 0 : done, _step == JobStep.Upload ? 0 : total); + progress = new NodeProgress(done, total, rate, line, detail); } await client.ReportNodeProgressAsync(nodeId, jobId, progress, job.Token).ConfigureAwait(false); } diff --git a/src/Chronos.Data/Sync/SyncTransfers.cs b/src/Chronos.Data/Sync/SyncTransfers.cs index 924bc49e..9ef185a8 100644 --- a/src/Chronos.Data/Sync/SyncTransfers.cs +++ b/src/Chronos.Data/Sync/SyncTransfers.cs @@ -60,7 +60,7 @@ internal sealed class SyncTransfers(SyncService sync) : new FramePhotos([]); var pending = new Queue(frames.Where(f => (f.Sha256 is null || (!present.Contains(tombstones.Canonical(f.Sha256)!) && !tombstones.DeletedRemotely(f.Sha256))) && adopted.IndexOf(new FramePhoto(f.Sha256, f.Size, f.CapturedAt)) is null)); - var progress = new TransferProgress(context, frames.Count, frames.Count - pending.Count); + var progress = new TransferProgress(context, frames.Count, frames.Count - pending.Count, new JobDetail(JobStep.Upload, local.DisplayTitle)); await progress.ReportAsync().ConfigureAwait(false); var skipped = 0; // The SHA-256 of each original the index has none for (a folder adopted and not verified), as its upload computes @@ -135,7 +135,7 @@ internal sealed class SyncTransfers(SyncService sync) var photos = SyncRules.Photos(frames); var camera = new SidecarCamera { Make = local.CameraMake, Model = local.CameraModel, Serial = local.CameraSerial }; var decoder = sync.Options.Archive.Decoder; - var progress = new TransferProgress(context, wanted.Count, 0); + var progress = new TransferProgress(context, wanted.Count, 0, new JobDetail(JobStep.Upload, local.DisplayTitle)); await progress.ReportAsync().ConfigureAwait(false); int sent = 0, unsent = 0; using var refused = CancellationTokenSource.CreateLinkedTokenSource(ct); @@ -241,7 +241,8 @@ internal sealed class SyncTransfers(SyncService sync) var staging = Path.Combine(paths.StagingDirectory, "sync-" + remoteId.ToString("N")); Directory.CreateDirectory(staging); - var progress = new TransferProgress(context, manifest.Frames.Count, manifest.Frames.Count - wanted.Count); + var progress = new TransferProgress(context, manifest.Frames.Count, manifest.Frames.Count - wanted.Count, + new JobDetail(JobStep.Download, local?.DisplayTitle ?? context.Job.TargetLabel)); await progress.ReportAsync().ConfigureAwait(false); var created = false; var rest = wanted; @@ -457,12 +458,13 @@ internal sealed class SyncTransfers(SyncService sync) ?? throw new InvalidOperationException(Loc.L("Errors.Sync.NotLinked")); var there = (await remote.GetManifestAsync(link.RemoteId, ct).ConfigureAwait(false)).Renders.Select(r => r.Id).ToHashSet(); var renders = (await db.Renders.ListBySequenceAsync(local.Id, ct).ConfigureAwait(false)).Where(r => !there.Contains(r.Id)).ToList(); - var progress = new TransferProgress(context, renders.Count, 0); + var progress = new TransferProgress(context, renders.Count, 0, new JobDetail(JobStep.Upload, local.DisplayTitle), items: false); await progress.ReportAsync().ConfigureAwait(false); var gone = 0; foreach (var render in renders) { var file = SyncService.RenderFile(archive, render); + await progress.PartAsync(Path.GetFileName(file)).ConfigureAwait(false); if (File.Exists(file)) { var sha = await ChronosClient.HashFileAsync(file, ct).ConfigureAwait(false); @@ -495,10 +497,11 @@ internal sealed class SyncTransfers(SyncService sync) var staging = Path.Combine(paths.StagingDirectory, "exports-" + remoteId.ToString("N")); Directory.CreateDirectory(staging); - var progress = new TransferProgress(context, wanted.Count, 0); + var progress = new TransferProgress(context, wanted.Count, 0, new JobDetail(JobStep.Download, local.DisplayTitle), items: false); await progress.ReportAsync().ConfigureAwait(false); foreach (var render in wanted) { + await progress.PartAsync(render.PresetName).ConfigureAwait(false); var (part, name, sha) = await FetchRenderAsync(remote, render, staging, ct).ConfigureAwait(false); var filed = await FileRenderAsync(sync.Archives, db, local, paths, part, name, new Render { @@ -630,7 +633,7 @@ internal sealed class SyncTransfers(SyncService sync) var files = new string?[frames.Count]; var kinds = new string?[frames.Count]; - var progress = new TransferProgress(context, frames.Count, 0); + var progress = new TransferProgress(context, frames.Count, 0, new JobDetail(JobStep.Download, context.Job.TargetLabel)); await progress.ReportAsync().ConfigureAwait(false); await Parallel.ForEachAsync(Enumerable.Range(0, frames.Count), Workers(sync.Options.Downloads, ct), async (i, token) => { @@ -906,8 +909,12 @@ internal sealed class SyncTransfers(SyncService sync) private static ParallelOptions Workers(int degree, CancellationToken cancellationToken) => new() { MaxDegreeOfParallelism = Math.Max(1, degree), CancellationToken = cancellationToken }; - /// Files done out of the total, reported in order from parallel workers. - private sealed class TransferProgress(JobContext context, long total, long done) + /// + /// Files done out of the total, reported in order from parallel workers, with what moves (: up or + /// down, the sequence): photo x of y of the transfer when , else the file being moved, video n of m + /// (). + /// + private sealed class TransferProgress(JobContext context, long total, long done, JobDetail detail, bool items = true) { private readonly SemaphoreSlim _gate = new(1, 1); @@ -917,7 +924,8 @@ internal sealed class SyncTransfers(SyncService sync) try { done++; - await context.ReportAsync(done, total).ConfigureAwait(false); + if (items) await context.ReportItemAsync(done, total, done, total).ConfigureAwait(false); + else await context.ReportAsync(done, total).ConfigureAwait(false); } finally { @@ -927,7 +935,11 @@ internal sealed class SyncTransfers(SyncService sync) public long Done => done; - public ValueTask ReportAsync() => context.ReportAsync(done, total); + public ValueTask ReportAsync() => context.ReportAsync(done, total, items ? detail with { ItemDone = done, ItemTotal = total } : detail); + + /// The next video starts moving: its file name, video n of m. + public ValueTask PartAsync(string? file) => + context.ReportAsync(done, total, detail with { Item = file, Part = (int)Math.Min(done + 1, total), Parts = (int)total, PartUnit = JobPartUnit.Render }); } } diff --git a/src/Chronos.Data/Videos/VideoCopyJobHandler.cs b/src/Chronos.Data/Videos/VideoCopyJobHandler.cs index 32a407fc..33380064 100644 --- a/src/Chronos.Data/Videos/VideoCopyJobHandler.cs +++ b/src/Chronos.Data/Videos/VideoCopyJobHandler.cs @@ -39,7 +39,8 @@ internal sealed class VideoCopyJobHandler(ChronosDatabase db, VideoLibrary libra ? int.Min(done, ids.Count) : 0; foreach (var id in ids.Skip(start)) Remove(VideosFolder.PartPath(folder, id)); - await context.ReportAsync(start, ids.Count, Loc.L("Videos.Job.Copying")).ConfigureAwait(false); + // The detail is the copy's step and video n of m; the message keeps the host's words for the desktop's log line. + await context.ReportAsync(start, ids.Count, new JobDetail(JobStep.CopyVideo), Loc.L("Videos.Job.Copying")).ConfigureAwait(false); using var remote = parameters.FromServer ? await ConnectAsync(parameters, ct).ConfigureAwait(false) : null; var sources = new List(ids.Count); @@ -58,9 +59,11 @@ internal sealed class VideoCopyJobHandler(ChronosDatabase db, VideoLibrary libra { failed++; } - else if (!await CopyAsync(context, parameters, remote, source, ct).ConfigureAwait(false)) + else { - failed++; + await context.ReportAsync(i, ids.Count, new JobDetail(JobStep.CopyVideo, source.Name, 0, 0, i + 1, ids.Count, JobPartUnit.Render), + Loc.L("Videos.Job.Copying")).ConfigureAwait(false); + if (!await CopyAsync(context, parameters, remote, source, ct).ConfigureAwait(false)) failed++; } await context.CheckpointAsync(Prefix + (i + 1).ToString(CultureInfo.InvariantCulture), i + 1, ids.Count).ConfigureAwait(false); } @@ -101,7 +104,8 @@ internal sealed class VideoCopyJobHandler(ChronosDatabase db, VideoLibrary libra if (sha is null) { // A render of before migration 0010: hashed now, and remembered. - await context.ReportAsync(context.Done, context.Total, Loc.L("Videos.Job.Verifying")).ConfigureAwait(false); + await context.ReportAsync(context.Done, context.Total, new JobDetail(JobStep.Verify, item.FileName, 0, 0, index + 1, parameters.RenderIds.Count, + JobPartUnit.Render), Loc.L("Videos.Job.Verifying")).ConfigureAwait(false); sha = await ContentHash.Sha256Async(item.FullPath, cancellationToken: ct).ConfigureAwait(false); await db.Renders.SetSha256Async(id, sha, CancellationToken.None).ConfigureAwait(false); } @@ -206,7 +210,9 @@ internal sealed class VideoCopyJobHandler(ChronosDatabase db, VideoLibrary libra /// The SHA-256 of the copy at when it matches (any, when none is known); null otherwise. private static async Task Verified(string path, string? expected, JobContext context, CancellationToken ct) { - await context.ReportAsync(context.Done, context.Total, Loc.L("Videos.Job.Verifying")).ConfigureAwait(false); + // The copy of the same video, now checked. + var detail = context.Detail is { } copying ? copying with { Step = JobStep.Verify } : new JobDetail(JobStep.Verify); + await context.ReportAsync(context.Done, context.Total, detail, Loc.L("Videos.Job.Verifying")).ConfigureAwait(false); var sha = await ContentHash.Sha256Async(path, cancellationToken: ct).ConfigureAwait(false); return expected is null || string.Equals(sha, expected, StringComparison.OrdinalIgnoreCase) ? sha : null; } diff --git a/src/Chronos.Data/Workspaces/WorkspaceCopyJobHandler.cs b/src/Chronos.Data/Workspaces/WorkspaceCopyJobHandler.cs index 42a15f4d..8c3c33d6 100644 --- a/src/Chronos.Data/Workspaces/WorkspaceCopyJobHandler.cs +++ b/src/Chronos.Data/Workspaces/WorkspaceCopyJobHandler.cs @@ -401,6 +401,9 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService var originalsLeft = withOriginals ? RemainingOriginals(project, frames, heldOriginals, (f, _) => f.Size) : new long[frames.Count + 1]; EnsureSpace(parameters.WorkspaceRoot, remaining[0] + originalsLeft[0]); var clock = System.Diagnostics.Stopwatch.StartNew(); + // Proxy x of y, then original x of y, of the sequence. + var start = Math.Min(copied, frames.Count); + await context.ReportAsync(start, total, new JobDetail(JobStep.CopyProxy, row.DisplayTitle, start, frames.Count)).ConfigureAwait(false); for (var i = 0; i < frames.Count; i++) { ct.ThrowIfCancellationRequested(); @@ -414,12 +417,13 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService } else { - await context.ReportAsync(i + 1, total).ConfigureAwait(false); + await context.ReportItemAsync(i + 1, total, i + 1, frames.Count).ConfigureAwait(false); } } var originals = new OriginalsTally(); if (withOriginals) { + await context.ReportAsync(frames.Count, total, new JobDetail(JobStep.CopyOriginal, row.DisplayTitle, 0, frames.Count)).ConfigureAwait(false); for (var i = 0; i < frames.Count; i++) { ct.ThrowIfCancellationRequested(); @@ -434,7 +438,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService } else { - await context.ReportAsync(done, total).ConfigureAwait(false); + await context.ReportItemAsync(done, total, i + 1, frames.Count).ConfigureAwait(false); } } } @@ -545,6 +549,8 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService EnsureSpace(parameters.WorkspaceRoot, remaining[0] + originalsLeft[0]); var clock = System.Diagnostics.Stopwatch.StartNew(); var options = new ParallelOptions { MaxDegreeOfParallelism = Downloads, CancellationToken = ct }; + var resumed = Math.Min(copied, frames.Count); + await context.ReportAsync(resumed, total, new JobDetail(JobStep.CopyProxy, sequence.DisplayTitle, resumed, frames.Count)).ConfigureAwait(false); for (var start = 0; start < frames.Count; start += DownloadBatch) { var end = Math.Min(frames.Count, start + DownloadBatch); @@ -561,13 +567,14 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService } else { - await context.ReportAsync(end, total).ConfigureAwait(false); + await context.ReportItemAsync(end, total, end, frames.Count).ConfigureAwait(false); } } foreach (var entry in entries.Where(e => e.File is not null)) fetched[entry.Id] = entry; var originals = new OriginalsTally(); if (withOriginals) { + await context.ReportAsync(frames.Count, total, new JobDetail(JobStep.CopyOriginal, sequence.DisplayTitle, 0, frames.Count)).ConfigureAwait(false); for (var start = 0; start < frames.Count; start += DownloadBatch) { var end = Math.Min(frames.Count, start + DownloadBatch); @@ -582,7 +589,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService } else { - await context.ReportAsync(frames.Count + end, total).ConfigureAwait(false); + await context.ReportItemAsync(frames.Count + end, total, end, frames.Count).ConfigureAwait(false); } } } diff --git a/src/Chronos.Data/Workspaces/WorkspaceMoveJobHandler.cs b/src/Chronos.Data/Workspaces/WorkspaceMoveJobHandler.cs index 71fe5652..53c2f64d 100644 --- a/src/Chronos.Data/Workspaces/WorkspaceMoveJobHandler.cs +++ b/src/Chronos.Data/Workspaces/WorkspaceMoveJobHandler.cs @@ -38,12 +38,20 @@ internal sealed class WorkspaceMoveJobHandler(ChronosDatabase db, WorkspaceJobOp var mover = Mover(parameters); if (WorkspaceMover.ReadJournal(mover.From) is null && await db.Jobs.HasPendingAsync(WorkspaceKinds, cancellationToken: ct).ConfigureAwait(false)) throw new InvalidOperationException(Loc.L("Errors.Workspace.JobsRunning")); + // Entry n of m in the detail, as a copy across volumes or a move on one (its journal says which); no project title (the + // mover tells counts only). + JobStep? step = null; + ValueTask Progress(long done, long total, bool durable) + { + step ??= WorkspaceMover.ReadJournal(mover.From) is { SameVolume: false } ? JobStep.CopyOriginal : JobStep.Reorganize; + var detail = new JobDetail(step.Value, null, 0, 0, (int)Math.Min(done + 1, total), (int)total, JobPartUnit.Entry); + return durable + ? context.CheckpointAsync(string.Create(CultureInfo.InvariantCulture, $"move:{done}"), done, total, detail) + : context.ReportAsync(done, total, detail); + } try { - await mover.MoveAsync(parameters.PlanFingerprint, options.Moved, (done, total, durable) => durable - ? context.CheckpointAsync(string.Create(CultureInfo.InvariantCulture, $"move:{done}"), done, total) - : context.ReportAsync(done, total), - context.Log, ct).ConfigureAwait(false); + await mover.MoveAsync(parameters.PlanFingerprint, options.Moved, Progress, context.Log, ct).ConfigureAwait(false); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { diff --git a/src/Chronos.Data/Workspaces/WorkspaceRenderJobHandler.cs b/src/Chronos.Data/Workspaces/WorkspaceRenderJobHandler.cs index 2baad146..c2427e25 100644 --- a/src/Chronos.Data/Workspaces/WorkspaceRenderJobHandler.cs +++ b/src/Chronos.Data/Workspaces/WorkspaceRenderJobHandler.cs @@ -93,6 +93,8 @@ internal sealed class WorkspaceRenderJobHandler(ChronosDatabase db, ArchiveServi { string? writing = null; IReadOnlyList outcomes; + var reporter = new RenderJobHandler.RenderReporter(context, sequence.DisplayTitle, targets); + await reporter.PreparingAsync().ConfigureAwait(false); try { await using var renderer = new SequenceRender(frames, projectSettings, inputs.Analysis, options.Processing, originals: true, companions: null); @@ -101,12 +103,13 @@ internal sealed class WorkspaceRenderJobHandler(ChronosDatabase db, ArchiveServi ValueTask Starting(int index, string path) { writing = path; - return context.CheckpointAsync(new RenderCheckpoint(done, index, path).ToJson(), context.Done, context.Total); + return reporter.StartingAsync(index, new RenderCheckpoint(done, index, path).ToJson()); } async ValueTask Record(int index, ExportTarget target, RenderResult result) { // The output is complete: recorded even if the job is being cancelled, so it is never orphaned. var id = RenderJobHandler.RenderId(context.Job.Id, index); + await reporter.VerifyingAsync(Path.GetFileName(result.OutputPath)).ConfigureAwait(false); var entry = await EntryAsync(project, context.Job.Id, id, target, result, versionId, settingsHash).ConfigureAwait(false); if (render.IsStill) entry = entry with { Fps = 0, DurationSeconds = 0, Kind = RenderKind.Still }; using (await project.LockAsync(LockWait, CancellationToken.None).ConfigureAwait(false)) @@ -135,7 +138,7 @@ internal sealed class WorkspaceRenderJobHandler(ChronosDatabase db, ArchiveServi setup => names.Reserve(taken => SequenceRender.StillPath(projectSettings.Export, exports, SequenceRender.NameContext(sequence, target, setup), still, name => Taken(taken, name))), path => Starting(index, path), - context.ReportAsync, + reporter.ReportAsync, cancellation).ConfigureAwait(false); await Record(index, target, result).ConfigureAwait(false); outcomes = [new TargetOutcome(target, result, null)]; @@ -154,7 +157,7 @@ internal sealed class WorkspaceRenderJobHandler(ChronosDatabase db, ArchiveServi name => Taken(taken, name))), Starting, Record, - context.ReportAsync, + reporter.ReportAsync, cancellation).ConfigureAwait(false); } if (renderer.StandIns.Count > 0) diff --git a/src/Chronos.Data/Workspaces/WorkspaceSendJobHandler.cs b/src/Chronos.Data/Workspaces/WorkspaceSendJobHandler.cs index d3085371..223db64c 100644 --- a/src/Chronos.Data/Workspaces/WorkspaceSendJobHandler.cs +++ b/src/Chronos.Data/Workspaces/WorkspaceSendJobHandler.cs @@ -115,6 +115,8 @@ internal sealed class WorkspaceSendJobHandler(ChronosDatabase db, ArchiveService ct.ThrowIfCancellationRequested(); if (held) await WhileHeldAsync(context).ConfigureAwait(false); var entry = entries[i]; + await context.ReportAsync(i, entries.Count, new JobDetail(JobStep.Upload, Path.GetFileName(entry.File), 0, 0, i + 1, entries.Count, JobPartUnit.Render)) + .ConfigureAwait(false); var file = project.ContainedExportFile(entry.File); var refusal = file is null ? Loc.L("Errors.Workspace.SendMissing", Path.GetFileName(entry.File ?? string.Empty)) : await CheckAsync(entry, file, folders: !held, ct).ConfigureAwait(false); if (refusal is null) diff --git a/tests/Chronos.Data.Tests/Archiving/ArchiveProgressDetailTests.cs b/tests/Chronos.Data.Tests/Archiving/ArchiveProgressDetailTests.cs new file mode 100644 index 00000000..39149417 --- /dev/null +++ b/tests/Chronos.Data.Tests/Archiving/ArchiveProgressDetailTests.cs @@ -0,0 +1,180 @@ +using Chronos.Core.Model; +using Chronos.Data.Archiving; +using Chronos.Data.Archiving.Jobs; +using Chronos.Data.Housekeeping; +using Chronos.Data.Jobs; +using Chronos.Data.Tests.Jobs; +using Chronos.Testing; +using static Chronos.Data.Tests.Archiving.ArchiveFixture; + +namespace Chronos.Data.Tests.Archiving; + +/// +/// What the archive jobs say they are doing (owner review 5, #65): the step, the item, photo x of y and sequence, folder +/// or step n of m, sent as the job's progress detail; no localized text in it. +/// +[Category("archive")] +public sealed class ArchiveProgressDetailTests(TestContext context) +{ + private static void Populate(ArchiveFixture fx) + { + Photos.WriteSeries(Path.Combine(fx.Paths.Root, "a"), Start, 4); + Photos.WriteSeries(Path.Combine(fx.Paths.Root, "b"), Start.AddDays(1), 3, firstSeed: 50); + } + + private static async Task<(DetailRecorder Recorder, JobEngine Engine)> StartAsync(ArchiveFixture fx) + { + var recorder = new DetailRecorder(); + var engine = recorder.Engine(fx.Db, fx.Service.CreateJobHandlers()); + await engine.StartAsync(fx.Ct); + return (recorder, engine); + } + + private static async Task RunAsync(ArchiveFixture fx, JobEngine engine, ArchiveJobRequest request) + { + var job = await engine.EnqueueAsync(request, cancellationToken: fx.Ct); + await fx.WaitForAsync(job.Id, JobState.Done); + return job.Id; + } + + [Test] + public async Task AScanListsThenIndexesEachNewFolderPhotoByPhotoAndChecksThemOnARescan() + { + await using var fx = await CreateAsync(context); + Populate(fx); + var (recorder, engine) = await StartAsync(fx); + await using var _ = engine; + + var first = await RunAsync(fx, engine, ArchiveJobs.Scan(fx.Archive)); + var details = recorder.Details(first); + Assert.Equal(JobStep.List, details[0].Step); + var index = details.Where(d => d.Step == JobStep.Index).ToList(); + Assert.Equal(new JobDetail(JobStep.Index, "a", 0, 0, 1, 2, JobPartUnit.Folder), index[0]); + // Photo after photo inside an adopted folder, then the next folder. + Assert.SequenceEqual([1L, 2L, 3L, 4L], index.Where(d => d.Item == "a" && d.ItemTotal > 0).Select(d => d.ItemDone)); + Assert.True(index.Where(d => d.ItemTotal > 0).All(d => d.ItemTotal == (d.Item == "a" ? 4 : 3))); + Assert.SequenceEqual([1, 2], index.Select(d => d.Part).Distinct()); + Assert.True(index.All(d => d.Parts == 2 && d.PartUnit == JobPartUnit.Folder)); + Assert.Equal(JobStep.Index, recorder.Steps(first)[1]); + + // Nothing changed: each folder is checked, folder n of m, and nothing is indexed. + var again = await RunAsync(fx, engine, ArchiveJobs.Scan(fx.Archive)); + Assert.SequenceEqual([JobStep.List, JobStep.Check], recorder.Steps(again)); + var check = recorder.Details(again).Where(d => d.Step == JobStep.Check).ToList(); + Assert.SequenceEqual([("a", 1), ("b", 2)], check.Select(d => (d.Item!, d.Part))); + Assert.True(check.All(d => d.Parts == 2 && d.PartUnit == JobPartUnit.Folder)); + } + + [Test] + public async Task AVerifyCountsThePhotosOfEachSequence() + { + await using var fx = await CreateAsync(context); + Populate(fx); + await fx.ScanAsync(); + var (recorder, engine) = await StartAsync(fx); + await using var _ = engine; + + var id = await RunAsync(fx, engine, ArchiveJobs.Verify(fx.Archive)); + var details = recorder.Details(id); + Assert.True(details.All(d => d.Step == JobStep.Verify && d.PartUnit == JobPartUnit.Sequence && d.Parts == 2), string.Join("; ", details)); + Assert.SequenceEqual([(1, 1L), (1, 2L), (1, 3L), (1, 4L), (2, 1L), (2, 2L), (2, 3L)], details.Select(d => (d.Part, d.ItemDone))); + Assert.SequenceEqual([4L, 3L], details.GroupBy(d => d.Part).Select(g => g.Max(d => d.ItemTotal))); + Assert.True(details.All(d => !string.IsNullOrEmpty(d.Item))); + } + + [Test] + public async Task AThumbnailPassReportsEachFrameOfEachSequence() + { + await using var fx = await CreateAsync(context); + Populate(fx); + await fx.ScanAsync(); + var ids = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Select(l => l.Id).ToList(); + var (recorder, engine) = await StartAsync(fx); + await using var _ = engine; + + var id = await RunAsync(fx, engine, ArchiveJobs.Thumbnails(ids)); + var details = recorder.Details(id); + Assert.True(details.All(d => d.Step == JobStep.Thumbs && d.PartUnit == JobPartUnit.Sequence && d.Parts == 2), string.Join("; ", details)); + Assert.SequenceEqual([1, 2], details.Select(d => d.Part).Distinct()); + // Every frame of a sequence goes out, up to its last. + Assert.SequenceEqual([(1, 4L), (2, 3L)], details.GroupBy(d => d.Part).Select(g => (g.Key, g.Max(d => d.ItemDone)))); + Assert.True(details.GroupBy(d => d.Part).All(g => g.Count() >= g.Max(d => d.ItemTotal))); + } + + [Test] + public async Task MaintenanceNamesItsStepsInOrder() + { + await using var fx = await CreateAsync(context); + Populate(fx); + await fx.ScanAsync(); + var (recorder, engine) = await StartAsync(fx); + await using var _ = engine; + + var id = await RunAsync(fx, engine, ArchiveJobs.Maintenance(fx.Archive)); + var details = recorder.Details(id); + var steps = details.Where(d => d.Step == JobStep.Maintenance).ToList(); + Assert.SequenceEqual(["leases", "temp", "packs", "duplicates", "vacuum"], steps.Select(d => d.Item!)); + Assert.SequenceEqual([1, 2, 3, 4, 5], steps.Select(d => d.Part)); + Assert.True(steps.All(d => d.Parts == 5 && d.PartUnit == JobPartUnit.Step)); + Assert.SequenceEqual([JobStep.Maintenance, JobStep.Check], recorder.Steps(id)); + } + + [Test] + public async Task DuplicatesAndOrphansRunWithoutACount() + { + await using var fx = await CreateAsync(context); + Populate(fx); + await fx.ScanAsync(); + var (recorder, engine) = await StartAsync(fx); + await using var _ = engine; + + foreach (var request in new[] { ArchiveJobs.Duplicates(fx.Archive), ArchiveJobs.Orphans(fx.Archive) }) + { + var id = await RunAsync(fx, engine, request); + // Every report until the one that completes it. + var reports = recorder.Of(id); + var running = reports.TakeWhile(p => p.Total == 0 || p.Done < p.Total).ToList(); + Assert.NotEmpty(running); + Assert.True(running.All(p => p.Detail == new JobDetail(JobStep.Check) && p.Total == 0), + $"{request.Kind}: {string.Join("; ", reports.Select(p => $"{p.Done}/{p.Total} {p.Detail}"))}"); + } + } + + [Test] + public async Task ABackupRunsWithoutACountAndACleanupNamesItsSteps() + { + await using var fx = await CreateAsync(context); + var (recorder, engine) = await StartAsync(fx); + await using var _ = engine; + + var backup = await RunAsync(fx, engine, ArchiveJobs.Backup(keep: 1)); + var reports = recorder.Of(backup); + var running = reports.TakeWhile(p => p.Total == 0 || p.Done < p.Total).ToList(); + Assert.NotEmpty(running); + Assert.True(running.All(p => p.Detail == new JobDetail(JobStep.Backup) && p.Total == 0), string.Join("; ", reports.Select(p => $"{p.Done}/{p.Total} {p.Detail}"))); + + var cleanup = await RunAsync(fx, engine, ArchiveJobs.Cleanup(fx.Archive, [CleanupSteps.JobHistory, CleanupSteps.Audit], 0)); + var steps = recorder.Details(cleanup); + Assert.SequenceEqual([(CleanupSteps.JobHistory, 1), (CleanupSteps.Audit, 2)], steps.Select(d => (d.Item!, d.Part))); + Assert.True(steps.All(d => d.Step == JobStep.Cleanup && d.Parts == 2 && d.PartUnit == JobPartUnit.Step)); + } + + [Test] + public async Task EmptyingTheTrashCountsItsEntries() + { + await using var fx = await CreateAsync(context); + Populate(fx); + await fx.ScanAsync(); + var ids = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Select(l => l.Id).ToList(); + await fx.Service.DeleteAsync(await fx.Service.PlanDeleteAsync(ids, null, fx.Ct), null, null, fx.Ct); + var empty = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct); + var (recorder, engine) = await StartAsync(fx); + await using var _ = engine; + + var id = await RunAsync(fx, engine, ArchiveJobs.EmptyTrash(fx.Archive, empty)); + var details = recorder.Details(id); + Assert.True(details.All(d => d.Step == JobStep.Erase && d.PartUnit == JobPartUnit.Entry && d.Parts == 2), string.Join("; ", details)); + Assert.SequenceEqual([1, 2], details.Select(d => d.Part)); + Assert.Empty(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)); + } +} diff --git a/tests/Chronos.Data.Tests/Archiving/PartialRowWriterTests.cs b/tests/Chronos.Data.Tests/Archiving/PartialRowWriterTests.cs index ed6b02bb..acd0987b 100644 --- a/tests/Chronos.Data.Tests/Archiving/PartialRowWriterTests.cs +++ b/tests/Chronos.Data.Tests/Archiving/PartialRowWriterTests.cs @@ -366,7 +366,7 @@ public abstract class PartialRowWriterTests(TestContext context) : DatabaseTest( // The first verify of photos a scan adopted hashes them all; a thumbnail pass records a preview-only frame meanwhile. var recorded = false; - var report = await fx.Service.Verifier.VerifyAsync(fx.Archive, [sequence.Id], default, (_, _, _) => ValueTask.CompletedTask, async (_, _) => + var report = await fx.Service.Verifier.VerifyAsync(fx.Archive, [sequence.Id], default, (_, _, _) => ValueTask.CompletedTask, async _ => { if (recorded) return; recorded = true; @@ -399,7 +399,7 @@ public abstract class PartialRowWriterTests(TestContext context) : DatabaseTest( // The verify finds the file missing, and an upload puts it back before the verify writes what it found. var checkedFrames = 0; - var report = await fx.Service.Verifier.VerifyAsync(fx.Archive, [sequence.Id], default, (_, _, _) => ValueTask.CompletedTask, async (_, _) => + var report = await fx.Service.Verifier.VerifyAsync(fx.Archive, [sequence.Id], default, (_, _, _) => ValueTask.CompletedTask, async _ => { if (++checkedFrames != 2) return; Assert.True((await fx.Service.Ingest.CommitAsync(Upload(fx.Stage(Start.AddSeconds(10), seed: 2)), fx.Ct)).Repaired, "repaired"); @@ -570,9 +570,9 @@ public abstract class PartialRowWriterTests(TestContext context) : DatabaseTest( // The server's PATCH takes the row as the last photo is checked, and commits while the verify stamps the sequence. Task? commit = null; - await fx.Service.Verifier.VerifyAsync(fx.Archive, [sequence.Id], default, (_, _, _) => ValueTask.CompletedTask, async (done, total) => + await fx.Service.Verifier.VerifyAsync(fx.Archive, [sequence.Id], default, (_, _, _) => ValueTask.CompletedTask, async p => { - if (done < total || commit is not null) return; + if (p.BytesDone < p.BytesTotal || commit is not null) return; var tx = await fx.Db.BeginAsync(fx.Ct); await tx.Sequences.EditAsync(sequence.Id, new SequenceEdit { SettingsJson = """{"heroFrame":1}""" }, sequence.SettingsVersion, fx.Ct); commit = CommitLaterAsync(tx, fx.Ct); diff --git a/tests/Chronos.Data.Tests/Jobs/DetailRecorder.cs b/tests/Chronos.Data.Tests/Jobs/DetailRecorder.cs new file mode 100644 index 00000000..dc0d8906 --- /dev/null +++ b/tests/Chronos.Data.Tests/Jobs/DetailRecorder.cs @@ -0,0 +1,62 @@ +using Chronos.Core.Model; +using Chronos.Data.Jobs; + +namespace Chronos.Data.Tests.Jobs; + +/// +/// Every progress report a job engine publishes, kept to tell which details a handler sent and in what order (owner review +/// 5, #65). The engine it records has no publish throttle (), so each report a handler makes goes out. +/// +internal sealed class DetailRecorder +{ + private readonly List _published = []; + + /// A started engine's options that publish every report: one worker, fast polls and checkpoints, no progress interval. + public static JobEngineOptions Options(string worker = "detail") => new() + { + Workers = 1, + WorkerId = worker, + PollInterval = TimeSpan.FromMilliseconds(50), + CheckpointInterval = TimeSpan.FromMilliseconds(50), + ProgressInterval = TimeSpan.Zero, + }; + + /// A new engine with , recorded, not started. + public JobEngine Engine(ChronosDatabase db, IEnumerable handlers, string worker = "detail") + { + var engine = new JobEngine(db, [.. handlers], Options(worker)); + engine.Progress += p => + { + lock (_published) _published.Add(p); + }; + return engine; + } + + /// The reports of in the order they went out. + public IReadOnlyList Of(Guid jobId) + { + lock (_published) return [.. _published.Where(p => p.JobId == jobId)]; + } + + /// The details of , without repeats of the one before. + public IReadOnlyList Details(Guid jobId) + { + var details = new List(); + foreach (var report in Of(jobId)) + { + if (report.Detail is { } detail && (details.Count == 0 || details[^1] != detail)) details.Add(detail); + } + return details; + } + + /// The steps of in order, each once in a row. + public IReadOnlyList Steps(Guid jobId) + { + var steps = new List(); + foreach (var detail in Details(jobId)) + { + if (steps.Count == 0 || steps[^1] != detail.Step) steps.Add(detail.Step); + } + return steps; + } +} diff --git a/tests/Chronos.Data.Tests/Processing/ProcessingProgressDetailTests.cs b/tests/Chronos.Data.Tests/Processing/ProcessingProgressDetailTests.cs new file mode 100644 index 00000000..27859e65 --- /dev/null +++ b/tests/Chronos.Data.Tests/Processing/ProcessingProgressDetailTests.cs @@ -0,0 +1,82 @@ +using Chronos.Core.Diagnostics.Synthetic; +using Chronos.Core.Export; +using Chronos.Core.Model; +using Chronos.Core.Project; +using Chronos.Data.Archiving; +using Chronos.Data.Archiving.Jobs; +using Chronos.Data.Jobs; +using Chronos.Data.Processing; +using Chronos.Data.Tests.Jobs; +using Chronos.Testing; + +namespace Chronos.Data.Tests.Processing; + +/// What the analysis and render jobs say they are doing (owner review 5, #65), as the job's progress detail. +[Category("processing")] +public sealed class ProcessingProgressDetailTests(TestContext context) +{ + private const int Frames = 12; + + private static SyntheticSequence Scene() => SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = Frames, StartEv = 0.5, EndEv = -0.5 }); + + private static async Task<(DetailRecorder Recorder, JobEngine Engine)> StartAsync(ProcessingFixture fx) + { + var recorder = new DetailRecorder(); + var engine = recorder.Engine(fx.Db, fx.Processing.CreateJobHandlers()); + await engine.StartAsync(fx.Ct); + return (recorder, engine); + } + + private static async Task RunAsync(ProcessingFixture fx, JobEngine engine, ArchiveJobRequest request) + { + var job = await engine.EnqueueAsync(request, cancellationToken: fx.Ct); + await fx.WaitForAsync(job.Id, JobState.Done); + return job.Id; + } + + [Test] + public async Task AnAnalysisNamesEachSequenceAndADeepOneCountsItsPhotos() + { + await using var fx = await ProcessingFixture.CreateAsync(context); + var first = await fx.AddAsync(Scene(), "First"); + var second = await fx.AddAsync(Scene(), "Second"); + var (recorder, engine) = await StartAsync(fx); + await using var _ = engine; + + var light = await RunAsync(fx, engine, ProcessingJobs.LightAnalysis([first.Id, second.Id], "both")); + var details = recorder.Details(light); + Assert.True(details.All(d => d.Step == JobStep.Analyse && d.PartUnit == JobPartUnit.Sequence && d.Parts == 2 && d.ItemTotal == 0), string.Join("; ", details)); + Assert.SequenceEqual([(1, first.DisplayTitle), (2, second.DisplayTitle)], details.Select(d => (d.Part, d.Item!))); + + var deep = await RunAsync(fx, engine, ProcessingJobs.DeepAnalysis([first.Id])); + details = recorder.Details(deep); + Assert.True(details.All(d => d.Step == JobStep.Analyse && d.Item == first.DisplayTitle && d.Part == 1 && d.Parts == 1 && d.ItemTotal == Frames), + string.Join("; ", details)); + Assert.True(details.Max(d => d.ItemDone) > 0, string.Join("; ", details)); + Assert.True(details.All(d => d.ItemDone <= Frames)); + } + + [Test] + public async Task ARenderPreparesEncodesThenVerifiesWithoutTextInTheDetail() + { + await using var fx = await ProcessingFixture.CreateAsync(context); + var sequence = await fx.AddAsync(Scene()); + var (recorder, engine) = await StartAsync(fx); + await using var _ = engine; + var mjpeg = new ExportSettings + { + Preset = new Auto().WithManual("mjpeg-avi"), + Overrides = new ExportOverrides { Width = 96, Height = 64 }, + NameTemplate = "clip-{codec}", + }; + + var id = await RunAsync(fx, engine, ProcessingJobs.Render(sequence, mjpeg, 96, 64)); + Assert.SequenceEqual([JobStep.Analyse, JobStep.Encode, JobStep.Verify], recorder.Steps(id)); + var details = recorder.Details(id); + Assert.Equal(new JobDetail(JobStep.Analyse, sequence.DisplayTitle), details[0]); + var encode = details.Where(d => d.Step == JobStep.Encode).ToList(); + Assert.True(encode.All(d => d.Item == sequence.DisplayTitle && d.Parts == 0 && d.ItemDone <= d.ItemTotal), string.Join("; ", encode)); + Assert.True(encode.Max(d => d.ItemDone) > 0, string.Join("; ", encode)); + Assert.Equal(new JobDetail(JobStep.Verify, "clip-MJPEG.avi"), details[^1]); + } +}