Files
Chronos/src/Chronos.Data/Archiving/Jobs/ScanJobHandler.cs
T
Alby96andClaude Opus 5.5 45e6911082 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 <noreply@anthropic.com>
2026-11-15 13:38:05 +01:00

123 lines
8.0 KiB
C#

using Chronos.Core.Archiving;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Repositories;
namespace Chronos.Data.Archiving.Jobs;
/// <summary>Resolves the archive a job targets (its first target id).</summary>
internal static class JobArchive
{
public static async Task<Archive> LoadAsync(ChronosDatabase db, Job job, CancellationToken cancellationToken) =>
job.TargetIds.Count > 0 && await db.Archives.GetAsync(job.TargetIds[0], cancellationToken).ConfigureAwait(false) is { } archive
? archive
: throw new InvalidOperationException($"{job.Kind} job {job.Id} does not target a known archive.");
}
/// <summary>
/// <see cref="JobKind.Scan"/> (incremental, or full with <see cref="ScanParameters.Full"/>) and
/// <see cref="JobKind.Rebuild"/>. Checkpoint: <c>after:&lt;folder&gt;</c>, the last folder indexed. When anything was
/// indexed, the sequences without a current light analysis (adopted folders, new sidecars, photos added to a folder) are
/// queued for it, and for a background deep analysis too when <see cref="ScanParameters.DeepAnalysis"/> asks. On the
/// server (<paramref name="imagesAfterScan"/>, <see cref="ArchiveServiceOptions.ImagesAfterScan"/>) the sequences it indexed
/// without thumbnails or proxies are queued for them too, one pass per sequence as after an upload. Sequences waiting for
/// their first frame (<see cref="ArchiveIndexer.AwaitingFolderAsync"/>) have nothing to analyse or draw yet and are left out.
/// </summary>
internal sealed class ScanJobHandler(ChronosDatabase db, ArchiveIndexer indexer, JobKind kind, bool imagesAfterScan = false) : IJobHandler
{
private const string Prefix = "after:";
public JobKind Kind => kind;
public async Task RunAsync(JobContext context)
{
var archive = await JobArchive.LoadAsync(db, context.Job, context.Cancellation).ConfigureAwait(false);
var parameters = ArchiveJobJson.Read(context.Job, ArchiveJobJson.Default.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;
// 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))
.Where(id => !awaiting.Contains(id)).ToList();
await AnalysisFollowUp.QueueAsync(db, context, unanalysed).ConfigureAwait(false);
if (kind == JobKind.Scan && parameters.DeepAnalysis) await AnalysisFollowUp.QueueDeepAsync(db, context, unanalysed).ConfigureAwait(false);
if (imagesAfterScan)
{
var resumed = resume is not null;
await QueueImagesAsync(context, archive, JobKind.Thumbs, SequenceStatus.ThumbsBuilt, summary.Sequences, resumed, awaiting).ConfigureAwait(false);
// An archive whose policy makes no proxies would get a pass that does nothing.
if (archive.ProxyLongEdge != ProxyPolicy.Disabled)
await QueueImagesAsync(context, archive, JobKind.Proxies, SequenceStatus.ProxiesBuilt, summary.Sequences, resumed, awaiting).ConfigureAwait(false);
}
}
}
/// <summary>
/// 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.
/// </summary>
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));
}
}
/// <summary>
/// Queues a background <paramref name="pass"/> (thumbnails or proxies) of each sequence this run indexed whose
/// <paramref name="built"/> flag is clear: new and adopted sequences, and those whose photos changed (the scan clears the
/// flag then, in this server's own row when another writer listed them in the sidecar itself). After a resumed run,
/// which may have indexed sequences before the interruption, of every sequence of the archive without the flag but
/// those in <paramref name="awaiting"/>. One pass per sequence, as after an upload: a folder renamed, deleted or
/// damaged before its pass runs fails that pass alone, and the other sequences still get their images. A sequence
/// whose own pass of that kind is already queued is left out.
/// </summary>
private async Task QueueImagesAsync(JobContext context, Archive archive, JobKind pass, SequenceStatus built, IReadOnlyList<Guid> indexed,
bool resumed, IReadOnlySet<Guid> awaiting)
{
var missing = new Dictionary<Guid, Sequence>();
var query = new SequenceQuery { ArchiveId = archive.Id, WithoutStatus = built, Sort = SequenceSort.Oldest, Limit = 1000 };
do
{
var page = await db.Sequences.ListAsync(query, context.Cancellation).ConfigureAwait(false);
foreach (var sequence in page.Items) missing[sequence.Id] = sequence;
query = query with { Cursor = page.NextCursor };
}
while (query.Cursor is not null);
var targets = resumed ? missing.Values.ToList() : indexed.Distinct().Where(missing.ContainsKey).Select(id => missing[id]).ToList();
foreach (var sequence in targets)
{
if (awaiting.Contains(sequence.Id) || await db.Jobs.IsQueuedAsync(pass, sequence.Id, context.Cancellation).ConfigureAwait(false)) continue;
var request = pass == JobKind.Thumbs
? ArchiveJobs.Thumbnails([sequence.Id], sequence.DisplayTitle)
: ArchiveJobs.Proxies([sequence.Id], sequence.DisplayTitle);
await context.EnqueueFollowUpAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, request.Priority).ConfigureAwait(false);
}
}
}