fix(convert): the job converts exactly the photos its preview listed, once
A conversion job could still do something its confirmed dry run did not show, or refuse what it should have converted: - An upload landing between the confirmation and the sequence's turn made the sequence Changed at every retry. Each ConvertSequence now names the photos the plan converts (Photos, their frame ids); the job takes those from its re-plan, checks their content against the confirmed digest and leaves photos that came in since as they are. A photo the plan did not list is never converted, whatever changed on disk or in the index since the dry run. - A file another program held during the dry run was planned as Missing and then converted or not depending on the re-plan. It is now its own reason (inaccessible, "held open or cannot be opened"); a truncated file reads as undecodable. At job time a confirmed photo that cannot be opened leaves the sequence Blocked for the retry; a held photo the job does not convert does not hide a real change. - The same sequences could be converted twice (two dialogs or tabs, a lost answer, no dry run at all). MassConverter.QueueAsync checks the queued, running and paused conversions and queues under one lock, in the caller's context (the desktop's enqueue shows a toast on the UI thread); a job's own re-plan treats sequences of conversions queued before it as busy. - The per-photo space check reserved a full batch of photos even when fewer were left, so a job whose preview had the space could stop at every retry. It now reserves the photo and those after it that may convert at once. - New sequence now says in the dry run, the panel's totals and confirmation, and a new desktop confirmation, how many photos each new sequence lacks; only sequences that are copied use those words. - On the server, a confirmation takes only the plan kept for the index as it is now (503 plan_dropped otherwise, never a plan made inside the request), and busy sequences and free space are as they are at every request. The panel's Apply asks the dry run again first, with Close still available, and confirms only the same fingerprint. - Maintenance keeps another host's conversion staging as long as its journal and purges both together; the unstaged-copy failure and blocked sequences are logged in catalog sentences. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit fefd9c34ebfeed1f9e84161610ef286026d38355)
This commit is contained in:
1 parent
5b5acaf307
commit
c669d0504d
25 files changed
+1307
-226
No files matched your search
@@ -20,8 +20,10 @@ namespace Chronos.App.Archiving;
|
||||
/// the converted files replace the photos (the originals go to the archive's trash) or go into new sequences (the originals
|
||||
/// stay as they are). The dry run (the engine's plan, nothing changes on disk) follows the choices and lists each sequence
|
||||
/// with what converts and what stays as it is, a summary and the free space line. Apply asks to type the number of photos a
|
||||
/// Replace replaces, then queues the conversion job of exactly that plan (<see cref="ArchiveJobs.Convert"/>): resumable,
|
||||
/// paused and followed in Jobs; a sequence changed after the dry run is left as it is.
|
||||
/// Replace replaces, or confirms a New sequence with the photos the new sequences lack, then queues the conversion job of
|
||||
/// exactly that plan (<see cref="MassConverter.QueueAsync"/>, refused while a conversion of one of its sequences waits or
|
||||
/// runs): resumable, paused and followed in Jobs; it converts the photos of the plan alone, and leaves as it is a sequence
|
||||
/// where one of them changed after the dry run.
|
||||
/// </summary>
|
||||
public sealed class ConvertDialogViewModel : ArchiveDialogViewModel
|
||||
{
|
||||
@@ -42,7 +44,7 @@ public sealed class ConvertDialogViewModel : ArchiveDialogViewModel
|
||||
|
||||
/// <param name="set">The sequences to convert; null for every sequence of <paramref name="archive"/>.</param>
|
||||
/// <param name="enqueue">Queues the conversion job and says so.</param>
|
||||
/// <param name="confirm">Asks the typed confirmation of a Replace; true when the user typed it and chose Replace.</param>
|
||||
/// <param name="confirm">Asks the confirmation of the mode chosen (typed for a Replace); true when the user chose its action.</param>
|
||||
public ConvertDialogViewModel(ArchiveService archives, Core.Model.Archive archive, IReadOnlyList<Guid>? set, Func<ArchiveJobRequest, Task> enqueue,
|
||||
Func<ConfirmRequest, bool> confirm, Action<ArchiveDialogViewModel> close)
|
||||
: base(close)
|
||||
@@ -175,7 +177,7 @@ public sealed class ConvertDialogViewModel : ArchiveDialogViewModel
|
||||
/// <summary>The space line shows and says nothing is missing (or that the free space cannot be measured).</summary>
|
||||
public bool IsSpaceFine => Plan is { Frames: > 0 } plan && plan.Space.Enough;
|
||||
|
||||
/// <summary>Asks the typed confirmation of a Replace, then queues the job of the plan on screen and closes.</summary>
|
||||
/// <summary>Asks the confirmation of the mode chosen (typed for a Replace), then queues the job of the plan on screen and closes.</summary>
|
||||
public ICommand ApplyCommand { get; }
|
||||
|
||||
public string ApplyToolTip => ApplyBlocker
|
||||
@@ -345,14 +347,27 @@ public sealed class ConvertDialogViewModel : ArchiveDialogViewModel
|
||||
{
|
||||
if (ApplyBlocker is not null || Plan is not { } plan || _mode is not { } mode) return;
|
||||
ClearError();
|
||||
// Replace changes the photos of the archive: the number of photos it replaces is typed first.
|
||||
if (mode == ConvertMode.Replace && (ConvertPlans.ReplaceRequest(plan) is not { } request || !_confirm(request))) return;
|
||||
// Replace changes the photos of the archive: the number of photos it replaces is typed first. New sequence says which
|
||||
// photos the new sequences lack before anything is queued.
|
||||
var request = mode == ConvertMode.Replace ? ConvertPlans.ReplaceRequest(plan) : ConvertPlans.NewRequest(plan);
|
||||
if (request is null || !_confirm(request)) return;
|
||||
IsBusy = true;
|
||||
try
|
||||
{
|
||||
await _enqueue(ArchiveJobs.Convert(_archive, plan));
|
||||
// Refused when a conversion of these sequences waits or runs already (another dialog, the Library and the Archive
|
||||
// manager): this plan may be older than it.
|
||||
await _archives.Converter.QueueAsync(_archive, plan, _enqueue);
|
||||
Log.Info("archive", $"Conversion of {plan.Frames} photo(s) in {plan.Converted.Count()} sequence(s) of {_archive.RootPath} to {plan.Options.Target} ({mode}) queued");
|
||||
}
|
||||
catch (ConversionQueuedException ex)
|
||||
{
|
||||
Log.Info("archive", $"The conversion was not queued: {ex.SequenceIds.Count} of its sequence(s) are converted by another job already");
|
||||
IsBusy = false;
|
||||
// Planned again, the rows show those sequences busy; the sentence stays under them.
|
||||
await PlanAsync();
|
||||
ShowMessage(ex.Message);
|
||||
return;
|
||||
}
|
||||
catch (DatabaseException ex)
|
||||
{
|
||||
Log.Warning("archive", "The conversion was not queued", ex);
|
||||
|
||||
@@ -26,7 +26,8 @@ public sealed record ConvertSpaceLine(string Text, bool IsShort);
|
||||
|
||||
/// <summary>
|
||||
/// The words of a mass conversion (owner review 2, R7; BRIEF §12.5): the engine's dry run (<see cref="ConvertPlan"/>) as
|
||||
/// rows, a summary and the free space line, and the typed confirmation a Replace asks for.
|
||||
/// rows, a summary and the free space line, the typed confirmation a Replace asks for, and the one New sequence asks for,
|
||||
/// which says which photos the new sequences lack.
|
||||
/// </summary>
|
||||
public static class ConvertPlans
|
||||
{
|
||||
@@ -53,32 +54,47 @@ public static class ConvertPlans
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One sequence of a plan: what converts, then what blocks it, then the photos skipped with why. With
|
||||
/// <see cref="ConvertMode.NewSequence"/> those are not copied into the new sequence, which holds the converted copies
|
||||
/// alone; with <see cref="ConvertMode.Replace"/> they stay as they are.
|
||||
/// One sequence of a plan: what converts, then what blocks it, then the photos skipped with why. Of a sequence
|
||||
/// <see cref="ConvertMode.NewSequence"/> copies, those are not copied into the new sequence, which holds the converted
|
||||
/// copies alone; otherwise (a Replace, or a sequence that converts nothing now, of which no new sequence is made) they
|
||||
/// stay as they are.
|
||||
/// </summary>
|
||||
public static ConvertRow Row(ConvertSequencePlan step, ConvertMode mode = ConvertMode.Replace)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(step);
|
||||
var named = !string.IsNullOrWhiteSpace(step.Title);
|
||||
var name = named ? step.Title : step.Folder.Length > 0 ? step.Folder : step.SequenceId.ToString("N")[..8];
|
||||
var (name, named) = NameOf(step);
|
||||
var note = step.Converts
|
||||
? Loc.Plural("Shell.Status.Photos", step.Frames.Count) + Loc.Separator + Sizes(step.BytesBefore, step.BytesAfter)
|
||||
: string.Empty;
|
||||
// What blocks the whole sequence comes first: the photos it would skip anyway do not matter until it can convert.
|
||||
List<string> kept = [.. step.Blocked.Distinct().Select(b => Loc.L("Archive.Convert.Blocked." + b))];
|
||||
var why = mode == ConvertMode.NewSequence ? "Archive.Convert.NotCopied." : "Archive.Convert.Skipped.";
|
||||
var why = mode == ConvertMode.NewSequence && step.Converts ? "Archive.Convert.NotCopied." : "Archive.Convert.Skipped.";
|
||||
kept.AddRange(step.Skipped.Select(s => Loc.L(why + s.Reason) + Loc.Separator + Loc.Plural("Shell.Status.Photos", s.Frames)));
|
||||
return new ConvertRow(step.SequenceId, name, !named, note, kept, step.Blocked.Count > 0);
|
||||
}
|
||||
|
||||
/// <summary>A sequence's title, else its folder (a path), else the start of its id; and whether it has a title.</summary>
|
||||
private static (string Name, bool Named) NameOf(ConvertSequencePlan step)
|
||||
{
|
||||
var named = !string.IsNullOrWhiteSpace(step.Title);
|
||||
return (named ? step.Title : step.Folder.Length > 0 ? step.Folder : step.SequenceId.ToString("N")[..8], named);
|
||||
}
|
||||
|
||||
/// <summary>The photos a conversion into new sequences leaves out of them: those the sequences it copies skip.</summary>
|
||||
public static int LeftOut(ConvertPlan plan)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
return plan.Converted.Sum(s => s.SkippedFrames);
|
||||
}
|
||||
|
||||
/// <summary>"12.4 GB → 9.8 GB".</summary>
|
||||
public static string Sizes(long before, long after) => Loc.L("Archive.Convert.Sizes", Formatting.Bytes(before), Formatting.Bytes(after));
|
||||
|
||||
/// <summary>
|
||||
/// "12 of 36 change · 3,600 photos · 41 GB → 32 GB · 20 skipped": the sequences converted of those planned, then the
|
||||
/// photos and their sizes when something converts, the photos skipped when there are any ("20 not copied" with
|
||||
/// <see cref="ConvertMode.NewSequence"/>: the new sequences lack them).
|
||||
/// photos and their sizes when something converts, the photos skipped when there are any. With
|
||||
/// <see cref="ConvertMode.NewSequence"/>, those of the sequences copied first ("20 not copied": the new sequences lack
|
||||
/// them), then those of the sequences that convert nothing now ("4 skipped").
|
||||
/// </summary>
|
||||
public static string Summary(ConvertPlan plan)
|
||||
{
|
||||
@@ -89,8 +105,9 @@ public static class ConvertPlans
|
||||
parts.Add(Loc.Plural("Shell.Status.Photos", plan.Frames));
|
||||
parts.Add(Sizes(plan.BytesBefore, plan.BytesAfter));
|
||||
}
|
||||
if (plan.Skipped > 0)
|
||||
parts.Add(Loc.Plural(plan.Mode == ConvertMode.NewSequence ? "Archive.Convert.NotCopiedPhotos" : "Archive.Convert.SkippedPhotos", plan.Skipped));
|
||||
var leftOut = plan.Mode == ConvertMode.NewSequence ? LeftOut(plan) : 0;
|
||||
if (leftOut > 0) parts.Add(Loc.Plural("Archive.Convert.NotCopiedPhotos", leftOut));
|
||||
if (plan.Skipped - leftOut > 0) parts.Add(Loc.Plural("Archive.Convert.SkippedPhotos", plan.Skipped - leftOut));
|
||||
return string.Join(Loc.Separator, parts);
|
||||
}
|
||||
|
||||
@@ -138,4 +155,38 @@ public static class ConvertPlans
|
||||
TypedPrompt = Loc.L("Archive.Delete.Type", count),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The confirmation of a conversion into new sequences: the photos converted into copies beside their sources, the
|
||||
/// originals untouched, how many photos the new sequences lack (those the plan skips there, for the reasons its rows
|
||||
/// give), and each sequence copied with its photos, their size and the photos its new sequence lacks; null when the plan
|
||||
/// converts nothing.
|
||||
/// </summary>
|
||||
public static ConfirmRequest? NewRequest(ConvertPlan plan)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
var converted = plan.Converted.ToList();
|
||||
if (converted.Count == 0) return null;
|
||||
var lines = converted.Take(DeletePlans.ListedLines).Select(s =>
|
||||
{
|
||||
var line = Loc.L("Archive.Delete.Line", NameOf(s).Name, Loc.Plural("Shell.Status.Photos", s.Frames.Count), Sizes(s.BytesBefore, s.BytesAfter));
|
||||
return s.SkippedFrames > 0 ? line + Loc.Separator + Loc.Plural("Archive.Convert.NotCopiedPhotos", s.SkippedFrames) : line;
|
||||
}).ToList();
|
||||
if (converted.Count > DeletePlans.ListedLines) lines.Add(Loc.Plural("Archive.Delete.More", converted.Count - DeletePlans.ListedLines));
|
||||
var message = Loc.L("Archive.Convert.NewMessage", Loc.Plural("Shell.Status.Photos", plan.Frames), Formatting.Bytes(plan.BytesBefore),
|
||||
TargetText(plan.Options.Target));
|
||||
if (LeftOut(plan) is > 0 and var leftOut) message += " " + Loc.Plural("Archive.Convert.NewLeftOut", leftOut);
|
||||
return new ConfirmRequest
|
||||
{
|
||||
Heading = Loc.Plural("Archive.Convert.NewHeading", converted.Count),
|
||||
Message = message,
|
||||
Detail = string.Join(Environment.NewLine, lines),
|
||||
IsDetailMonospaced = false,
|
||||
DetailToolTip = Loc.L("Tooltips.Archive.ConvertPlanNew"),
|
||||
SafeText = Loc.L("Archive.Dialog.Cancel"),
|
||||
SafeToolTip = Loc.L("Tooltips.Archive.ConvertBack"),
|
||||
ActionText = Loc.L("Archive.Convert.Confirm"),
|
||||
ActionToolTip = Loc.L("Tooltips.Archive.ConvertNew"),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,12 @@ public enum ConvertSkip
|
||||
/// every converted file must (<see cref="ConvertPlanner.TooLarge"/>).
|
||||
/// </summary>
|
||||
TooLarge,
|
||||
|
||||
/// <summary>
|
||||
/// The photo's file is there but could not be opened when the plan was made: another program holds it without sharing
|
||||
/// (a sync client, an editor), or access is denied. A plan made once it is free converts it.
|
||||
/// </summary>
|
||||
Inaccessible,
|
||||
}
|
||||
|
||||
/// <summary>Why a whole sequence is not converted now; nothing of it is touched.</summary>
|
||||
@@ -265,9 +271,21 @@ public static class ConvertPlanner
|
||||
if (TooLarge(options, probe.Width, probe.Height)) return ConvertSkip.TooLarge;
|
||||
return FrameConverter.Treatment(SourceColor.Read(path, frame.Format), options.Target) == ColorTreatment.Refuse ? ConvertSkip.ColorProfile : null;
|
||||
}
|
||||
catch (Exception ex) when (ex is FileNotFoundException or DirectoryNotFoundException)
|
||||
{
|
||||
// Gone since the folder was listed.
|
||||
return ConvertSkip.Missing;
|
||||
}
|
||||
catch (EndOfStreamException)
|
||||
{
|
||||
// Opened, and shorter than its own headers say: no decoder gets its pixels.
|
||||
return ConvertSkip.Undecodable;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return ConvertSkip.Missing;
|
||||
// There, but held by another program or denied: not missing, and not planned (a conversion job converts only the
|
||||
// photos its plan listed), so the dry run says why.
|
||||
return ConvertSkip.Inaccessible;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -41,8 +41,9 @@ public sealed class ArchiveMaintenance
|
||||
private static readonly TimeSpan StagingAge = TimeSpan.FromHours(24);
|
||||
|
||||
/// <summary>
|
||||
/// The journal of a conversion job this index does not know (another host's, or one its history forgot) is left alone
|
||||
/// until it has not been written for this long: the job history keeps finished jobs as long by default.
|
||||
/// The journal and staged conversions of a conversion job this index does not know (another host's, or one its history
|
||||
/// forgot) are left alone until none of them has been written for this long: the job history keeps finished jobs as long
|
||||
/// by default.
|
||||
/// </summary>
|
||||
private static readonly TimeSpan JournalAge = TimeSpan.FromDays(Housekeeping.CleanupSteps.DefaultHistoryDays);
|
||||
|
||||
@@ -182,8 +183,10 @@ public sealed class ArchiveMaintenance
|
||||
/// Staging copies and atomic-write temporaries left behind by crashes (never originals), and what a conversion job left
|
||||
/// (<see cref="ConvertJournal"/>): its staged conversions stay while the job is queued, running or paused, however old, go
|
||||
/// as soon as it is done, and otherwise once none of them was written for a day (a retry then converts again); its journal
|
||||
/// stays while a retry can use it, and goes once the job is done, or unknown to this index and untouched for as long as
|
||||
/// the job history keeps jobs.
|
||||
/// stays while a retry can use it, and goes once the job is done. A job this index does not know (another host's on a
|
||||
/// shared archive, or one its history forgot) may still be resumed where it is known: its journal and staged conversions
|
||||
/// stay together while any of them was written within as long as the job history keeps jobs, then go together (staged
|
||||
/// conversions without a journal, which no resume can use, once idle for a day).
|
||||
/// </summary>
|
||||
private async Task<List<string>> PurgeTemporaryFilesAsync(ArchivePaths paths, IReadOnlyList<SequenceLocation> locations, bool dryRun,
|
||||
CancellationToken cancellationToken)
|
||||
@@ -198,6 +201,14 @@ public sealed class ArchiveMaintenance
|
||||
return state;
|
||||
}
|
||||
bool Old(string file, TimeSpan age) => now - File.GetLastWriteTimeUtc(file) > age;
|
||||
// The journal and staged conversions of a conversion job this index does not know, none written for JournalAge: a
|
||||
// resume where the job is known would no longer find them worth keeping, so they go together.
|
||||
bool Expired(Guid job)
|
||||
{
|
||||
var staging = Path.Combine(paths.StagingDirectory, MassConverter.StagingFolder(job));
|
||||
IEnumerable<string> staged = Directory.Exists(staging) ? Directory.EnumerateFiles(staging, "*", SearchOption.AllDirectories) : [];
|
||||
return ConvertJournal.Files(paths, job).Where(File.Exists).Concat(staged).All(f => Old(f, JournalAge));
|
||||
}
|
||||
void Collect(string directory, string pattern, TimeSpan age, bool recursive)
|
||||
{
|
||||
if (!Directory.Exists(directory)) return;
|
||||
@@ -222,7 +233,14 @@ public sealed class ArchiveMaintenance
|
||||
var state = await StateAsync(job).ConfigureAwait(false);
|
||||
if (state is JobState.Queued or JobState.Running or JobState.Paused) continue;
|
||||
var files = Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories).ToList();
|
||||
if (state == JobState.Done || files.All(f => Old(f, StagingAge)))
|
||||
var gone = state switch
|
||||
{
|
||||
JobState.Done => true,
|
||||
// Another host's, or forgotten: kept as long as its journal, and going with it.
|
||||
null when ConvertJournal.Files(paths, job).Any(File.Exists) => Expired(job),
|
||||
_ => files.All(f => Old(f, StagingAge)),
|
||||
};
|
||||
if (gone)
|
||||
{
|
||||
found.AddRange(files);
|
||||
conversions.Add(directory);
|
||||
@@ -235,7 +253,7 @@ public sealed class ArchiveMaintenance
|
||||
{
|
||||
if (ConvertJournal.JobOf(Path.GetFileName(file)) is not { } job) continue;
|
||||
var state = await StateAsync(job).ConfigureAwait(false);
|
||||
if (state == JobState.Done || state is null && Old(file, JournalAge)) found.Add(file);
|
||||
if (state == JobState.Done || state is null && Expired(job)) found.Add(file);
|
||||
}
|
||||
}
|
||||
Collect(paths.MetaDirectory, ".*.tmp", TempAge, recursive: false);
|
||||
|
||||
@@ -697,16 +697,20 @@ public static class ArchiveJobs
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Convert"/>: applies the conversion <paramref name="plan"/> (<see cref="ArchiveService.PlanConvertAsync"/>)
|
||||
/// as confirmed (owner review 2, R7): the sequences it converts, in its order with their frames versions and the digest of
|
||||
/// the photos each converts (<see cref="ConvertSequencePlan.Digest"/>), are the job's targets, so jobs that would touch
|
||||
/// them wait. A sequence whose photos to convert are no longer those when the job comes to it is left as it is and reported.
|
||||
/// as confirmed (owner review 2, R7): the sequences it converts, in its order with their frames versions, the photos each
|
||||
/// converts and their digest (<see cref="ConvertSequencePlan.Digest"/>), are the job's targets, so jobs that would touch
|
||||
/// them wait. The job converts those photos alone, and leaves as it is and reports a sequence where one of them no longer
|
||||
/// holds the content confirmed when the job comes to it. Queue it through <see cref="MassConverter.QueueAsync"/>, which
|
||||
/// refuses a second conversion of the same sequences.
|
||||
/// </summary>
|
||||
/// <exception cref="ArgumentException">The plan converts nothing.</exception>
|
||||
public static ArchiveJobRequest Convert(Archive archive, ConvertPlan plan)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
var sequences = plan.Converted.Select(s => new ConvertSequence(s.SequenceId, s.FramesVersion, s.Digest())).ToList();
|
||||
var sequences = plan.Converted
|
||||
.Select(s => new ConvertSequence(s.SequenceId, s.FramesVersion, s.Digest(), ConvertSequence.EncodePhotos(s.Frames.Select(f => f.FrameId))))
|
||||
.ToList();
|
||||
if (sequences.Count == 0) throw new ArgumentException("The plan converts nothing.", nameof(plan));
|
||||
var label = sequences.Count == 1 ? plan.Converted.First().Title : archive.Name;
|
||||
return new(JobKind.Convert, [.. sequences.Select(s => s.Id)], label,
|
||||
|
||||
@@ -62,11 +62,46 @@ public sealed record ConvertJobParameters(Guid ArchiveId, ConvertTarget Target,
|
||||
string Fingerprint);
|
||||
|
||||
/// <summary>
|
||||
/// A sequence of a <see cref="ConvertJobParameters"/>: the frames version it was planned at and the digest of the photos it
|
||||
/// converts, each with its content (<see cref="ConvertSequencePlan.Digest"/>), which the job checks under the sequence's
|
||||
/// lease before it converts anything; null in a job an earlier build queued, which checks the frames version only.
|
||||
/// A sequence of a <see cref="ConvertJobParameters"/>: the frames version it was planned at, the digest of the photos it
|
||||
/// converts, each with its content (<see cref="ConvertSequencePlan.Digest"/>), and which photos those are (<see cref="Photos"/>).
|
||||
/// Under the sequence's lease, before it converts anything, the job takes those photos from its plan made again and goes
|
||||
/// on only while they have the digest confirmed: photos that came in since (an upload while the job waited its turn) stay
|
||||
/// as they are, and a photo the plan did not list (one another program held while it was made) is never converted. Null
|
||||
/// in a job an earlier build queued, which checks the frames version only (no digest), or the whole plan's digest (no photos).
|
||||
/// </summary>
|
||||
public sealed record ConvertSequence(Guid Id, int FramesVersion, string? Frames = null);
|
||||
/// <param name="Photos">The frame ids of the photos converted, in the plan's order, as <see cref="EncodePhotos"/> writes them.</param>
|
||||
public sealed record ConvertSequence(Guid Id, int FramesVersion, string? Frames = null, string? Photos = null)
|
||||
{
|
||||
/// <summary>
|
||||
/// Frame ids as a job's parameters hold them: their 16 bytes each, one after the other, in base64 (a whole-archive
|
||||
/// conversion lists every photo it converts, so the job row stays about half the size of a list of ids).
|
||||
/// </summary>
|
||||
public static string EncodePhotos(IEnumerable<Guid> ids)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(ids);
|
||||
IReadOnlyCollection<Guid> frames = ids as IReadOnlyCollection<Guid> ?? [.. ids];
|
||||
var bytes = new byte[frames.Count * 16];
|
||||
var at = 0;
|
||||
foreach (var frame in frames)
|
||||
{
|
||||
frame.TryWriteBytes(bytes.AsSpan(at, 16));
|
||||
at += 16;
|
||||
}
|
||||
return Convert.ToBase64String(bytes);
|
||||
}
|
||||
|
||||
/// <summary>The frame ids <see cref="Photos"/> holds, in order; null when it holds none (a job an earlier build queued).</summary>
|
||||
/// <exception cref="FormatException">The text is not ids as <see cref="EncodePhotos"/> writes them.</exception>
|
||||
public IReadOnlyList<Guid>? PhotoIds()
|
||||
{
|
||||
if (Photos is null) return null;
|
||||
var bytes = Convert.FromBase64String(Photos);
|
||||
if (bytes.Length % 16 != 0) throw new FormatException($"The photos of sequence {Id} are not frame ids.");
|
||||
var ids = new Guid[bytes.Length / 16];
|
||||
for (var i = 0; i < ids.Length; i++) ids[i] = new Guid(bytes.AsSpan(i * 16, 16));
|
||||
return ids;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A job ready to enqueue.</summary>
|
||||
public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList<Guid> Targets, string? Label, string? ParametersJson, JobPriority Priority);
|
||||
|
||||
@@ -10,12 +10,14 @@ namespace Chronos.Data.Archiving.Jobs;
|
||||
/// <see cref="JobKind.Convert"/>: a mass conversion (owner review 2, R7; BRIEF §12.5) of the sequences of a confirmed plan
|
||||
/// (<see cref="ConvertJobParameters"/>) through <see cref="MassConverter"/>, 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 and only while the photos it converts are those confirmed; its journal makes every stage
|
||||
/// resumable. Progress counts photos; the checkpoint only marks a resume, the journal says where. Each sequence whose frames
|
||||
/// were replaced is told as <c>converted</c>, each new sequence as <c>created</c> (<see cref="ArchiveServiceOptions.SequenceChanged"/>),
|
||||
/// 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 they were (changed after the plan, busy, a photo that failed) are
|
||||
/// logged and fail the job at the end, after the others are converted; a retry tries them again with what they staged.
|
||||
/// 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
|
||||
/// resume, the journal says where. Each sequence whose frames were replaced is told as <c>converted</c>, each new sequence
|
||||
/// as <c>created</c> (<see cref="ArchiveServiceOptions.SequenceChanged"/>), 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
|
||||
/// they were (changed after the plan, busy, a photo another program holds, a photo that failed) are logged and fail the
|
||||
/// job at the end, after the others are converted; a retry tries again those busy, held or failed, with what they staged,
|
||||
/// and leaves one that changed after the plan as it is (its log line says to plan again).
|
||||
/// </summary>
|
||||
internal sealed class ConvertJobHandler(ChronosDatabase db, MassConverter converter, Func<Guid, string, CancellationToken, Task>? sequenceChanged) : IJobHandler
|
||||
{
|
||||
|
||||
@@ -29,10 +29,16 @@ public enum ConvertOutcome
|
||||
/// <summary>It had nothing to convert.</summary>
|
||||
Nothing,
|
||||
|
||||
/// <summary>Left as it was: the photos it converts are no longer those of the plan confirmed, or it is no longer in the archive.</summary>
|
||||
/// <summary>
|
||||
/// Left as it was: a photo it converts no longer holds the content confirmed (it changed, is gone, or no longer converts),
|
||||
/// or it is no longer in the archive. A retry finds the same: the user plans again.
|
||||
/// </summary>
|
||||
Changed,
|
||||
|
||||
/// <summary>Left as it was: it is busy, or its sidecar cannot be read.</summary>
|
||||
/// <summary>
|
||||
/// Left as it was for now: it is busy, another index moved its folder, a photo it converts is held by another program, or
|
||||
/// its sidecar cannot be read or settled; a retry converts it once that is over.
|
||||
/// </summary>
|
||||
Blocked,
|
||||
|
||||
/// <summary>Left as it was: a photo could not be converted (all or nothing), or the files could not move.</summary>
|
||||
@@ -72,17 +78,28 @@ internal sealed record ConvertCallbacks(Func<long, long, ValueTask> Progress, Fu
|
||||
/// <summary>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 when its source has none.</summary>
|
||||
internal sealed record ConvertRequester(string? Name, Guid? Id);
|
||||
|
||||
/// <summary>
|
||||
/// A conversion of sequences a confirmed plan converts is queued, running or paused already, so its job was not queued
|
||||
/// (<see cref="MassConverter.QueueAsync"/>): a dry run made now shows them busy.
|
||||
/// </summary>
|
||||
public sealed class ConversionQueuedException(IReadOnlyList<Guid> sequenceIds) : InvalidOperationException(Loc.L("Archive.Convert.AlreadyQueued"))
|
||||
{
|
||||
/// <summary>The sequences another conversion holds.</summary>
|
||||
public IReadOnlyList<Guid> SequenceIds { get; } = sequenceIds;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Mass conversion of existing sequences (owner review 2, R7; BRIEF §12.5): <see cref="PlanAsync(Archive, IReadOnlyList{Guid}, ConvertOptions, ConvertMode, CancellationToken)"/>
|
||||
/// is the dry run (<see cref="ConvertPlanner"/> per sequence, what blocks it, the space needed against the free space where
|
||||
/// the conversion writes, <see cref="ArchiveServiceOptions.FreeSpace"/>), and a <see cref="JobKind.Convert"/> job applies the
|
||||
/// confirmed plan one sequence at a time. Under the sequence's lease, its sidecar settled where the index has it then
|
||||
/// (<see cref="SequenceWriter.ReadLocked"/>), the job plans it again and goes on only while the photos it converts are those
|
||||
/// confirmed, each with its content (<see cref="ConvertSequence.Frames"/>); it pins them then (<see cref="PinLog"/>), so a photo
|
||||
/// that comes in or is verified later stays as it is, on a retry too. Stage A, without the lease: each photo is hashed
|
||||
/// against its record and converted (<see cref="FrameConverter"/>, several at once as the host's parallelism and memory
|
||||
/// allow) into <c>.chronos/staging/convert-<job>/<sequence>/</c>, the free space checked before each one, each staged
|
||||
/// file appended to the job's journal (<see cref="ConvertJournal"/>), so a resumed or retried job keeps the staged files
|
||||
/// confirmed plan (queued by <see cref="QueueAsync"/>, which refuses a second conversion of the same sequences) one sequence
|
||||
/// at a time. Under the sequence's lease, its sidecar settled where the index has it then (<see cref="SequenceWriter.ReadLocked"/>),
|
||||
/// the job plans it again and takes the photos confirmed (<see cref="ConvertSequence.Photos"/>), going on only while each is
|
||||
/// still planned with its content confirmed (<see cref="ConvertSequence.Frames"/>); it pins them then (<see cref="PinLog"/>),
|
||||
/// so a photo that came in, was verified or could be opened again since the plan stays as it is, on a retry too. Stage A,
|
||||
/// without the lease: each photo is hashed against its record and converted (<see cref="FrameConverter"/>, several at once
|
||||
/// as the host's parallelism and memory allow) into <c>.chronos/staging/convert-<job>/<sequence>/</c>, the free
|
||||
/// space checked before each one, each staged file appended to the job's journal (<see cref="ConvertJournal"/>), so a resumed or retried job keeps the staged files
|
||||
/// whose hash still verifies. Stage B, all or nothing, under the sequence's lease and while every photo pinned still holds
|
||||
/// the content converted: <see cref="ConvertMode.Replace"/> swaps the frames' files (<see cref="FrameTrash.ReplaceAsync"/>:
|
||||
/// the originals into one trash entry of kind <see cref="TrashKind.Replaced"/>, same ids and indices, tombstones naming the
|
||||
@@ -98,6 +115,9 @@ public sealed class MassConverter
|
||||
/// <summary>What the frames of a sequence no longer have once their files were replaced (<see cref="FrameTrash.ReplaceAsync"/>).</summary>
|
||||
private const SequenceStatus Uncovered = SequenceStatus.AnalyzedLight | SequenceStatus.AnalyzedDeep | SequenceStatus.ThumbsBuilt | SequenceStatus.ProxiesBuilt;
|
||||
|
||||
/// <summary>Held while a confirmed conversion is checked against those pending and queued (<see cref="QueueAsync"/>): one at a time in this process.</summary>
|
||||
private static readonly SemaphoreSlim Queueing = new(1, 1);
|
||||
|
||||
private readonly ChronosDatabase _db;
|
||||
private readonly SequenceWriter _writer;
|
||||
private readonly ArchiveIngest _ingest;
|
||||
@@ -135,11 +155,7 @@ public sealed class MassConverter
|
||||
if (!Enum.IsDefined(mode)) throw new ArgumentException($"Unknown mode {mode}.", nameof(mode));
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
var online = ArchiveVolume.Probe(paths) == ArchiveAvailability.Online;
|
||||
var busy = new HashSet<Guid>(await _trash.BusyAsync(job, cancellationToken).ConfigureAwait(false));
|
||||
// A conversion waiting in the queue holds its sequences for a dry run too, so the same conversion is not confirmed twice
|
||||
// (another tab or user, an answer lost and Apply pressed again). A job planning again counts only running and paused
|
||||
// jobs: a duplicate queued after it would otherwise hold back the one before it.
|
||||
if (job is null) busy.UnionWith(await _db.Jobs.ListPendingTargetsAsync(JobKind.Convert, cancellationToken).ConfigureAwait(false));
|
||||
var busy = await HeldAsync(job, cancellationToken).ConfigureAwait(false);
|
||||
var plans = new List<ConvertSequencePlan>();
|
||||
foreach (var id in sequenceIds.Distinct())
|
||||
{
|
||||
@@ -152,6 +168,56 @@ public sealed class MassConverter
|
||||
return new ConvertPlan(archive.Id, options, mode, plans, new ConvertSpace(ConvertPlanner.Required(estimated), FreeSpace(paths)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sequences and archives a dry run counts as busy (<see cref="ConvertBlock.Busy"/>): what running and paused jobs hold,
|
||||
/// and the sequences of every conversion waiting in the queue, so the same conversion is not confirmed twice. Reads only.
|
||||
/// </summary>
|
||||
public async Task<IReadOnlySet<Guid>> BusyAsync(CancellationToken cancellationToken = default) =>
|
||||
await HeldAsync(null, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
/// <summary>
|
||||
/// What makes a sequence busy for a dry run (<paramref name="job"/> null: <see cref="BusyAsync"/>), or for the conversion
|
||||
/// job <paramref name="job"/> planning again: what other running and paused jobs hold, and the sequences of the conversions
|
||||
/// queued before it, which come first (a duplicate queued after it must not hold it back, and one queued before it, by an
|
||||
/// earlier build or another tab, must not make a second copy of the same sequence).
|
||||
/// </summary>
|
||||
private async Task<HashSet<Guid>> HeldAsync(Guid? job, CancellationToken cancellationToken)
|
||||
{
|
||||
var busy = new HashSet<Guid>(await _trash.BusyAsync(job, cancellationToken).ConfigureAwait(false));
|
||||
if (job is not { } self)
|
||||
busy.UnionWith(await _db.Jobs.ListPendingTargetsAsync(JobKind.Convert, cancellationToken).ConfigureAwait(false));
|
||||
else if (await _db.Jobs.GetAsync(self, cancellationToken).ConfigureAwait(false) is { } running)
|
||||
busy.UnionWith(await _db.Jobs.ListPendingTargetsAsync(JobKind.Convert, running.Created, cancellationToken).ConfigureAwait(false));
|
||||
return busy;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queues the job of the confirmed <paramref name="plan"/> (<see cref="ArchiveJobs.Convert"/>) through <paramref name="enqueue"/>,
|
||||
/// unless a conversion of a sequence it converts is queued, running or paused already: another dialog or tab, an answer
|
||||
/// lost and Apply pressed again, a dry run made before that one was queued or none at all. Checked and queued under one
|
||||
/// lock of this process, so two confirmations at once queue one job. <paramref name="enqueue"/> runs in the caller's
|
||||
/// context (a desktop's tells the user on its UI thread).
|
||||
/// </summary>
|
||||
/// <exception cref="ConversionQueuedException">A conversion of one of its sequences waits or runs; nothing was queued.</exception>
|
||||
/// <exception cref="ArgumentException">The plan converts nothing.</exception>
|
||||
public async Task QueueAsync(Archive archive, ConvertPlan plan, Func<ArchiveJobRequest, Task> enqueue, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(enqueue);
|
||||
var request = ArchiveJobs.Convert(archive, plan);
|
||||
// No ConfigureAwait(false) here: each wait comes back to the caller's context, where enqueue is called.
|
||||
await Queueing.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
var pending = await _db.Jobs.ListPendingTargetsAsync(JobKind.Convert, cancellationToken);
|
||||
if (request.Targets.Where(pending.Contains).ToList() is { Count: > 0 } queued) throw new ConversionQueuedException(queued);
|
||||
await enqueue(request);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Queueing.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<ConvertSequencePlan> PlanOneAsync(ArchivePaths paths, Sequence row, bool online, bool busy, ConvertOptions options,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -289,8 +355,9 @@ public sealed class MassConverter
|
||||
ConvertMode mode, Guid jobId, ConvertRequester by, ConvertJournal journal, PinLog pins, StagedLog staged, Progress progress, SpaceWatch space,
|
||||
ConvertCallbacks callbacks, CancellationToken cancellationToken)
|
||||
{
|
||||
// Another job holds it now (a Reorganize paused since the job started, a render): it waits for the retry.
|
||||
var busy = await _trash.BusyAsync(jobId, cancellationToken).ConfigureAwait(false);
|
||||
// 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.
|
||||
var busy = await HeldAsync(jobId, cancellationToken).ConfigureAwait(false);
|
||||
if (busy.Contains(step.Id) || busy.Contains(archive.Id)) return new StepDone(Result(row, ConvertOutcome.Blocked));
|
||||
SequencePaths folder;
|
||||
SequenceManifest manifest;
|
||||
@@ -320,11 +387,22 @@ public sealed class MassConverter
|
||||
var had = journal.Of(step.Id)?.Had ?? row.Status;
|
||||
return new StepDone(Result(synced, ConvertOutcome.Converted, frames), had, _frames.FollowUps(archive, synced, had));
|
||||
}
|
||||
var (sidecar, at, title) = (manifest, folder, row.DisplayTitle);
|
||||
var fresh = await Task.Run(() => ConvertPlanner.Plan(sidecar, at, FileRenames.ListPresent(at, sidecar), options, _writer.Options.Decoder, title),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
var (sidecar, at, title, decoder) = (manifest, folder, row.DisplayTitle, _writer.Options.Decoder);
|
||||
var (fresh, present) = await Task.Run(() =>
|
||||
{
|
||||
// As the planner keeps them (by name, whatever the case), so the photos left out are asked again alike.
|
||||
IReadOnlySet<string> files = new HashSet<string>(FileRenames.ListPresent(at, sidecar), StringComparer.OrdinalIgnoreCase);
|
||||
return (ConvertPlanner.Plan(sidecar, at, files, options, decoder, title), files);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
if (Confirmed(step, fresh, pin) is not { } confirmed)
|
||||
{
|
||||
// A photo it converts that another program holds now cannot be told from one that changed: the retry, once it
|
||||
// is free, can.
|
||||
if (await Task.Run(() => Held(step, pin, sidecar, at, present, fresh, options, decoder), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
Core.Diagnostics.Log.Info("archive", $"{row.DisplayTitle}: a photo it converts cannot be opened now; it is not converted");
|
||||
return new StepDone(Result(row, ConvertOutcome.Blocked, error: Loc.L("Archive.Convert.PhotoHeld")));
|
||||
}
|
||||
Core.Diagnostics.Log.Info("archive", $"{row.DisplayTitle}: the photos it converts are no longer those of the plan confirmed; it is not converted");
|
||||
return new StepDone(Result(row, ConvertOutcome.Changed));
|
||||
}
|
||||
@@ -345,7 +423,7 @@ public sealed class MassConverter
|
||||
catch (Exception ex) when (ex is LeaseUnavailableException or IOException or UnauthorizedAccessException or InvalidDataException or InvalidOperationException)
|
||||
{
|
||||
Core.Diagnostics.Log.Warning("archive", $"The sidecar of {row.DisplayTitle} cannot be read; it is not converted", ex);
|
||||
return new StepDone(Result(row, ConvertOutcome.Blocked, error: ex.Message));
|
||||
return new StepDone(Result(row, ConvertOutcome.Blocked, error: Blocker(ex)));
|
||||
}
|
||||
var staging = StagingOf(paths, jobId, row.Id);
|
||||
var key = SessionKey(jobId, row.Id);
|
||||
@@ -378,22 +456,42 @@ public sealed class MassConverter
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or InvalidOperationException)
|
||||
{
|
||||
Core.Diagnostics.Log.Warning("archive", $"{row.DisplayTitle}: the converted photos could not take their place", ex);
|
||||
var cause = Loc.L(ex is UnauthorizedAccessException ? "Archive.Failed.Access" : "Archive.Failed.Files");
|
||||
var cause = ex switch
|
||||
{
|
||||
UnstagedException => ex.Message,
|
||||
UnauthorizedAccessException => Loc.L("Archive.Failed.Access"),
|
||||
_ => Loc.L("Archive.Failed.Files"),
|
||||
};
|
||||
return new StepDone(Result(row, ConvertOutcome.Failed, error: Loc.L("Archive.Convert.NotPlaced", cause)));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Why a sequence's sidecar could not be settled or read under its lease, as one catalog sentence for the job log (the
|
||||
/// exception goes to the diagnostics log): another writer holds it, access is denied, or the file is not its sidecar.
|
||||
/// </summary>
|
||||
private static string Blocker(Exception ex) => ex switch
|
||||
{
|
||||
LeaseUnavailableException => ex.Message,
|
||||
UnauthorizedAccessException => Loc.L("Archive.Failed.Access"),
|
||||
InvalidDataException or InvalidOperationException => Loc.L("Archive.Convert.Blocked.Unreadable"),
|
||||
_ => Loc.L("Archive.Failed.Files"),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// What the job converts of a sequence whose plan is now <paramref name="fresh"/>: the photos it pinned when it first came to
|
||||
/// it, each still planned with the content it had then (photos that came in or were verified since stay as they are); the
|
||||
/// first time, the whole plan while it is still the one confirmed (the step's digest; a job an earlier build queued: its
|
||||
/// frames version). Null when it is not: the sequence changed after the plan, and the user plans again.
|
||||
/// it, each still planned with the content it had then; the first time, the photos confirmed (<see cref="ConvertSequence.Photos"/>)
|
||||
/// while each is still planned with the content confirmed (the step's digest). Photos that came in, were verified or could
|
||||
/// be opened again since stay as they are, so an upload while the job waits its turn neither changes what it converts
|
||||
/// nor holds it back. A job an earlier build queued: the whole plan while it has the step's digest, or its frames
|
||||
/// version. Null when a photo confirmed no longer converts as it was: the sequence changed after the plan, and the user
|
||||
/// plans again.
|
||||
/// </summary>
|
||||
internal static ConvertSequencePlan? Confirmed(ConvertSequence step, ConvertSequencePlan fresh, PinnedSequence? pin)
|
||||
{
|
||||
var now = fresh.Frames.ToDictionary(f => f.FrameId);
|
||||
if (pin is not null)
|
||||
{
|
||||
var now = fresh.Frames.ToDictionary(f => f.FrameId);
|
||||
var frames = new List<ConvertFramePlan>(pin.Frames.Count);
|
||||
foreach (var pinned in pin.Frames)
|
||||
{
|
||||
@@ -402,6 +500,17 @@ public sealed class MassConverter
|
||||
}
|
||||
return frames.Count > 0 ? fresh with { FramesVersion = pin.FramesVersion, Frames = frames } : null;
|
||||
}
|
||||
if (step is { Frames: { } confirmedDigest } && step.PhotoIds() is { Count: > 0 } photos)
|
||||
{
|
||||
var frames = new List<ConvertFramePlan>(photos.Count);
|
||||
foreach (var id in photos)
|
||||
{
|
||||
if (!now.TryGetValue(id, out var frame)) return null;
|
||||
frames.Add(frame);
|
||||
}
|
||||
var held = ConvertSequencePlan.DigestOf(frames.Select(f => (f.FrameId, f.Sha256)));
|
||||
return string.Equals(held, confirmedDigest, StringComparison.Ordinal) ? fresh with { Frames = frames } : null;
|
||||
}
|
||||
if (fresh.Frames.Count == 0) return null;
|
||||
var confirmed = step.Frames is { } digest
|
||||
? string.Equals(fresh.Digest(), digest, StringComparison.Ordinal)
|
||||
@@ -409,6 +518,24 @@ public sealed class MassConverter
|
||||
return confirmed ? fresh : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether the plan made now (<paramref name="fresh"/>) leaves out a photo the job converts of the sequence (one it pinned,
|
||||
/// else one confirmed) only because its file could not be opened (<see cref="ConvertSkip.Inaccessible"/>: another program
|
||||
/// holds it): the sequence then waits for the retry rather than counting as changed. Photos the job does not convert do
|
||||
/// not count, nor does a confirmed photo that changed meanwhile. A job an earlier build queued, which names no photos:
|
||||
/// any photo of the sequence that could not be opened.
|
||||
/// </summary>
|
||||
private static bool Held(ConvertSequence step, PinnedSequence? pin, SequenceManifest manifest, SequencePaths folder, IReadOnlySet<string> present,
|
||||
ConvertSequencePlan fresh, ConvertOptions options, ImageDecoder decoder)
|
||||
{
|
||||
IReadOnlyList<Guid>? converts = pin is not null ? [.. pin.Frames.Select(f => f.Id)] : step.PhotoIds();
|
||||
if (converts is null) return fresh.Skipped.Any(s => s.Reason == ConvertSkip.Inaccessible);
|
||||
var planned = fresh.Frames.Select(f => f.FrameId).ToHashSet();
|
||||
var frames = manifest.Frames.ToDictionary(f => f.Id);
|
||||
return converts.Any(id => !planned.Contains(id) && frames.TryGetValue(id, out var frame)
|
||||
&& ConvertPlanner.Skip(frame, folder, present, options, decoder) == ConvertSkip.Inaccessible);
|
||||
}
|
||||
|
||||
/// <summary>Whether every photo of <paramref name="planned"/> is a frame of <paramref name="manifest"/> still holding the content it was planned with.</summary>
|
||||
private static bool Holds(SequenceManifest manifest, ConvertSequencePlan planned)
|
||||
{
|
||||
@@ -452,8 +579,10 @@ public sealed class MassConverter
|
||||
|
||||
/// <summary>
|
||||
/// Stage A: converts the planned frames not staged yet, several at once, each staged file appended to the journal as it
|
||||
/// is consumed (in frame order). A photo starts only while the volume has the space it and those being converted may
|
||||
/// take, with the reserve: short of it the job stops (<c>Archive.Error.ConvertSpace</c>) before the volume fills. Returns
|
||||
/// is consumed (in frame order). A photo starts only while the volume has the space it and the photos after it that may
|
||||
/// convert at once with it take (as many as the host converts at once, never photos that are not there to start), with
|
||||
/// the reserve: short of it the job stops (<c>Archive.Error.ConvertSpace</c>) before the volume fills. The space the
|
||||
/// photos converting already take is in the volume's free space as they write it, so it is not counted twice. Returns
|
||||
/// the first failure (the file and why, localised; the exception goes to the diagnostics log); the frames converted
|
||||
/// meanwhile stay staged for a retry.
|
||||
/// </summary>
|
||||
@@ -491,15 +620,14 @@ public sealed class MassConverter
|
||||
space.Staged(conversion.Size, estimates[conversion.FrameId]);
|
||||
await callbacks.Progress(++progress.Done, progress.Total).ConfigureAwait(false);
|
||||
}, cancellationToken);
|
||||
foreach (var next in todo)
|
||||
for (var i = 0; i < todo.Count && failure is null; i++)
|
||||
{
|
||||
if (failure is not null) break;
|
||||
if (space.Short(next.EstimatedBytes * atOnce) is { } message)
|
||||
if (space.Short(Ahead(todo, i, atOnce)) is { } message)
|
||||
{
|
||||
full = message;
|
||||
break;
|
||||
}
|
||||
var frame = frames[next.FrameId];
|
||||
var frame = frames[todo[i].FrameId];
|
||||
await work.AddAsync(token => Stage(frame, manifest, folder, staging, options, decoder, threads, token)).ConfigureAwait(false);
|
||||
}
|
||||
await work.CompleteAsync().ConfigureAwait(false);
|
||||
@@ -512,6 +640,18 @@ public sealed class MassConverter
|
||||
return failure;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The bytes photo <paramref name="index"/> of <paramref name="todo"/> and the photos after it that may convert at once with
|
||||
/// it are estimated at: <paramref name="atOnce"/> of them, fewer near the end (the space a photo of stage A starts with).
|
||||
/// </summary>
|
||||
internal static long Ahead(IReadOnlyList<ConvertFramePlan> todo, int index, int atOnce)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(todo);
|
||||
long bytes = 0;
|
||||
for (var i = index; i < Math.Min(todo.Count, index + Math.Max(1, atOnce)); i++) bytes += todo[i].EstimatedBytes;
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/// <summary>One photo of stage A: hashed against its record, converted into the staging folder and verified.</summary>
|
||||
private static Staged Stage(SidecarFrame frame, SequenceManifest manifest, SequencePaths folder, string staging, ConvertOptions options, ImageDecoder decoder,
|
||||
int threads, CancellationToken cancellationToken)
|
||||
@@ -621,7 +761,7 @@ public sealed class MassConverter
|
||||
if (filed.Contains(conversion.Sha256)) continue;
|
||||
var frame = frames[converted.FrameId];
|
||||
var path = Path.Combine(staging, conversion.File);
|
||||
if (!Present(path, conversion)) throw new FileNotFoundException($"The conversion of {frame.File} is no longer staged; a retry converts it again.", path);
|
||||
if (!Present(path, conversion)) throw new UnstagedException(frame.File, path);
|
||||
pending.Add(new StagedFrame(path, frame.Original ?? Path.GetFileName(frame.File), conversion.Size, conversion.Sha256, Metadata(path, frame), null, null)
|
||||
{
|
||||
NamedAs = options.WithExtension(Path.GetFileName(frame.File)),
|
||||
@@ -715,9 +855,10 @@ public sealed class MassConverter
|
||||
/// <summary>
|
||||
/// The photos converted, when this job replaced the sequence's frames already (a crash after its stage B, before the
|
||||
/// journal said so): every photo it pinned is a frame holding a file of the target's format converted from the content
|
||||
/// pinned. Without a pin (its journal lost), the frames holding a conversion to the target are, by their sources, the
|
||||
/// photos confirmed (the step's digest); a job an earlier build queued: every staged conversion is a frame holding the
|
||||
/// converted content. Null otherwise.
|
||||
/// pinned. Without a pin (its journal lost), every photo confirmed (<see cref="ConvertSequence.Photos"/>) is a frame
|
||||
/// holding a conversion to the target whose sources have the step's digest; a job an earlier build queued: the frames
|
||||
/// holding a conversion to the target are, by their sources, the photos of the step's digest, or every staged conversion
|
||||
/// is a frame holding the converted content. Null otherwise.
|
||||
/// </summary>
|
||||
private static int? ReplacedEarlier(SequenceManifest manifest, ConvertSequence step, PinnedSequence? pin, IReadOnlyList<StagedConversion> noted,
|
||||
ConvertOptions options)
|
||||
@@ -731,6 +872,16 @@ public sealed class MassConverter
|
||||
? pin.Frames.Count
|
||||
: null;
|
||||
}
|
||||
if (step is { Frames: { } confirmed } && step.PhotoIds() is { Count: > 0 } photos)
|
||||
{
|
||||
var sources = new List<(Guid, string?)>(photos.Count);
|
||||
foreach (var id in photos)
|
||||
{
|
||||
if (!frames.TryGetValue(id, out var f) || f.Format != options.Format || f.Source?.Sha256 is not { } source) return null;
|
||||
sources.Add((id, source));
|
||||
}
|
||||
return string.Equals(ConvertSequencePlan.DigestOf(sources), confirmed, StringComparison.Ordinal) ? photos.Count : null;
|
||||
}
|
||||
if (step.Frames is { } digest)
|
||||
{
|
||||
var converted = manifest.Frames.Where(f => f.Format == options.Format && f.Source?.Sha256 is not null).ToList();
|
||||
@@ -892,7 +1043,8 @@ public sealed class MassConverter
|
||||
ConvertOutcome.Created => Loc.L("Archive.Log.ConvertedNew", result.Title, result.Frames),
|
||||
ConvertOutcome.Nothing => Loc.L("Archive.Log.ConvertNothing", result.Title),
|
||||
ConvertOutcome.Changed => Loc.L("Archive.Log.ConvertChanged", result.Title),
|
||||
ConvertOutcome.Blocked => Loc.L("Archive.Log.ConvertBlocked", result.Title),
|
||||
// Busy, or why the retry may do better (a photo another program holds, a folder another index moved), in one sentence.
|
||||
ConvertOutcome.Blocked when result.Error is null => Loc.L("Archive.Log.ConvertBlocked", result.Title),
|
||||
_ => Loc.L("Archive.Log.ConvertFailed", result.Title, result.Error),
|
||||
};
|
||||
callbacks.Log(line);
|
||||
@@ -900,7 +1052,19 @@ public sealed class MassConverter
|
||||
if (result is { Outcome: ConvertOutcome.Created, LeftOut: > 0 }) callbacks.Log(Loc.L("Archive.Log.ConvertLeftOut", result.Title, result.LeftOut));
|
||||
}
|
||||
|
||||
private static string Gigabytes(long bytes) => Loc.L("Common.Size.GB", (bytes / 1e9).ToString("0.#", Loc.Culture));
|
||||
/// <summary>
|
||||
/// Two sizes as the space error gives them: GB from one gigabyte, MB below, with more decimals when one would read as the
|
||||
/// other ("needs 0.5 GB, 0.5 GB free").
|
||||
/// </summary>
|
||||
private static (string Required, string Free) Sizes(long required, long free)
|
||||
{
|
||||
var (a, b) = (Size(required, "0.#"), Size(free, "0.#"));
|
||||
return a != b ? (a, b) : (Size(required, "0.###"), Size(free, "0.###"));
|
||||
}
|
||||
|
||||
private static string Size(long bytes, string digits) => bytes >= 1_000_000_000
|
||||
? Loc.L("Common.Size.GB", (bytes / 1e9).ToString(digits, Loc.Culture))
|
||||
: Loc.L("Common.Size.MB", (bytes / 1e6).ToString(digits, Loc.Culture));
|
||||
|
||||
/// <summary>The session key of the new sequence a conversion makes from <paramref name="source"/>.</summary>
|
||||
internal static string SessionKey(Guid job, Guid source) => $"convert:{job:N}:{source:N}";
|
||||
@@ -972,7 +1136,9 @@ public sealed class MassConverter
|
||||
public string? Short(long estimated)
|
||||
{
|
||||
var space = new ConvertSpace(ConvertPlanner.Required((long)Math.Ceiling(estimated * Ratio)), converter.FreeSpace(paths));
|
||||
return space.Enough ? null : Loc.L("Archive.Error.ConvertSpace", Gigabytes(space.Required), Gigabytes(space.Free ?? 0));
|
||||
if (space.Enough) return null;
|
||||
var (required, free) = Sizes(space.Required, space.Free ?? 0);
|
||||
return Loc.L("Archive.Error.ConvertSpace", required, free);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -981,6 +1147,12 @@ public sealed class MassConverter
|
||||
|
||||
/// <summary>A photo of stage A: its file and its staged conversion, or why it failed.</summary>
|
||||
private sealed record Staged(string File, StagedConversion? Conversion, Exception? Error);
|
||||
|
||||
/// <summary>
|
||||
/// The staged conversion of a photo a new sequence is about to file is gone (a clean-up, a quarantine): the sequence fails
|
||||
/// rather than leave the photo out, and the retry converts it again. Its message is the job log's catalog sentence.
|
||||
/// </summary>
|
||||
private sealed class UnstagedException(string file, string path) : FileNotFoundException(Loc.L("Archive.Convert.Unstaged", file), path);
|
||||
}
|
||||
|
||||
/// <summary>One photo converted and staged: its frame, the content it was converted from, the staged file's name, size and SHA-256, and its size in pixels.</summary>
|
||||
|
||||
@@ -197,11 +197,23 @@ public sealed class JobRepository
|
||||
|
||||
/// <summary>The targets of the queued, running and paused jobs of <paramref name="kind"/> (the newest 5000 such jobs).</summary>
|
||||
public Task<HashSet<Guid>> ListPendingTargetsAsync(JobKind kind, CancellationToken cancellationToken = default) =>
|
||||
PendingTargetsAsync(kind, null, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// The targets of the queued, running and paused jobs of <paramref name="kind"/> created before <paramref name="createdBefore"/>
|
||||
/// (the newest 5000 such jobs): those that came first.
|
||||
/// </summary>
|
||||
public Task<HashSet<Guid>> ListPendingTargetsAsync(JobKind kind, DateTimeOffset createdBefore, CancellationToken cancellationToken = default) =>
|
||||
PendingTargetsAsync(kind, createdBefore, cancellationToken);
|
||||
|
||||
private Task<HashSet<Guid>> PendingTargetsAsync(JobKind kind, DateTimeOffset? createdBefore, CancellationToken cancellationToken) =>
|
||||
_db.RunAsync(async session =>
|
||||
{
|
||||
var before = createdBefore is null ? string.Empty : " AND created < $2";
|
||||
DbParam[] parameters = createdBefore is { } created ? [(int)kind, created] : [(int)kind];
|
||||
var rows = await session.QueryListAsync(
|
||||
$"SELECT target_ids FROM jobs WHERE kind = $1 AND state IN ({PendingStates}) ORDER BY created DESC, id DESC LIMIT 5000",
|
||||
[(int)kind], r => r.GetString(0), cancellationToken).ConfigureAwait(false);
|
||||
$"SELECT target_ids FROM jobs WHERE kind = $1 AND state IN ({PendingStates}){before} ORDER BY created DESC, id DESC LIMIT 5000",
|
||||
parameters, r => r.GetString(0), cancellationToken).ConfigureAwait(false);
|
||||
var ids = new HashSet<Guid>();
|
||||
foreach (var text in rows)
|
||||
{
|
||||
|
||||
@@ -133,11 +133,14 @@ public sealed record ReorganizePlanDto(IReadOnlyList<ReorganizeStepDto> Steps, i
|
||||
/// become the frames, the originals go to the archive's trash) or <c>new-sequence</c> (copies in a new sequence, the source
|
||||
/// untouched, the photos it leaves as they are not copied into it). <see cref="DryRun"/> answers the plan
|
||||
/// (<see cref="ConvertPlanDto"/>) and changes nothing; the server keeps it a few minutes, a refusal too, so the same dry run
|
||||
/// again (also after one cut off, in either mode, at any quality of a lossless target) is answered from it with the free
|
||||
/// space measured again; 503 <c>plan_dropped</c> when the server stopped making it (it took too long, or too many were
|
||||
/// asked at once). The change itself sends that plan's <see cref="Fingerprint"/> back (409 <c>plan_changed</c> when the
|
||||
/// index changed since in what the plan reads: the sequences' rows, and the formats, sizes, hashes and flags of their
|
||||
/// photos) and runs as a <c>convert</c> job (202), which plans again and leaves as it is a sequence that no longer fits.
|
||||
/// again (also after one cut off, in either mode, at any quality of a lossless target) is answered from it with the busy
|
||||
/// sequences and the free space as they are then; 503 <c>plan_dropped</c> when the server stopped making it (it took too
|
||||
/// long, or too many were asked at once). The change itself sends that plan's <see cref="Fingerprint"/> back and takes the
|
||||
/// plan kept (503 <c>plan_dropped</c> when none is kept for the index as it is now, let go since or the index changed in
|
||||
/// what the plan reads, the sequences' rows and the formats, sizes, hashes and flags of their photos: ask the dry run
|
||||
/// again, then confirm that one; 409 <c>plan_changed</c> when the plan kept is not the one confirmed: a job made one of its
|
||||
/// sequences busy or free since, or a conversion of them was queued) and runs as a <c>convert</c> job (202), which
|
||||
/// converts the photos of that plan alone and leaves as it is a sequence where one of them no longer fits.
|
||||
/// </summary>
|
||||
public sealed record ConvertRequest(IReadOnlyList<Guid>? SequenceIds, bool All, string? Target, int? Quality, string? Mode, bool DryRun,
|
||||
string? Fingerprint = null);
|
||||
@@ -146,9 +149,10 @@ public sealed record ConvertRequest(IReadOnlyList<Guid>? SequenceIds, bool All,
|
||||
/// Photos of a sequence a conversion leaves as they are: <see cref="Reason"/> <c>same_format</c>, <c>convert_on_pc</c> (the
|
||||
/// server cannot read them at full resolution: a CR3, a HEIC, a body its RAW decoder does not support), <c>undecodable</c>,
|
||||
/// <c>missing</c>, <c>unhashed</c> (never verified), <c>eight_bit</c> (a RAW the host develops at 8 bits only, for a 16-bit
|
||||
/// target), <c>color_profile</c> (a colour profile the target can neither keep nor convert to) or <c>too_large</c>, how
|
||||
/// many, and the reason as one localised sentence: with <c>new-sequence</c>, that the new sequence lacks them (it holds the
|
||||
/// converted copies alone).
|
||||
/// target), <c>color_profile</c> (a colour profile the target can neither keep nor convert to), <c>too_large</c> or
|
||||
/// <c>inaccessible</c> (another program held the file open, or it could not be opened, when the plan was made), how many,
|
||||
/// and the reason as one localised sentence: of a sequence <c>new-sequence</c> copies, that the new sequence lacks them (it
|
||||
/// holds the converted copies alone).
|
||||
/// </summary>
|
||||
public sealed record ConvertSkippedDto(string Reason, int Photos, string Message);
|
||||
|
||||
|
||||
@@ -26,6 +26,12 @@ const RETRY_DELAY = 2000;
|
||||
const PLAN_PATIENCE = 16 * 60 * 1000;
|
||||
const DROPPED_RETRIES = 1;
|
||||
const SLOW_PLAN = 10;
|
||||
/**
|
||||
* Apply confirms only the plan the server keeps, a few minutes from when it was made: the dry run is asked first (at once
|
||||
* while kept, else made again), and a plan let go between that answer and the confirmation is asked for DROPPED_CONFIRMS
|
||||
* times more.
|
||||
*/
|
||||
const DROPPED_CONFIRMS = 1;
|
||||
/** The formats, as the API names them, with their strings; linear DNG, the archival choice, is the one chosen first. */
|
||||
const TARGETS = [
|
||||
{ value: "jpeg", label: "Admin.Convert.Format.Jpeg", tip: "Admin.Convert.Format.Jpeg.Tip" },
|
||||
@@ -62,6 +68,8 @@ export function openConvert({ api, target, names = new Map() } = {}) {
|
||||
let timer = null;
|
||||
let planning = false;
|
||||
let again = false;
|
||||
/** Apply asks the dry run again before it confirms (checking: nothing sent yet, Close stays), then sends it (busy). */
|
||||
let checking = false;
|
||||
let busy = false;
|
||||
let queued = null;
|
||||
/** A message the next plan shows (why the plan was made again). */
|
||||
@@ -227,18 +235,9 @@ export function openConvert({ api, target, names = new Map() } = {}) {
|
||||
const body = request();
|
||||
const key = JSON.stringify(body);
|
||||
planning = true;
|
||||
// Waiting: how long it has taken, once that is long, with why in the tooltip.
|
||||
const started = Date.now();
|
||||
const showWait = () => {
|
||||
const seconds = Math.floor((Date.now() - started) / 1000);
|
||||
totals.textContent = seconds < SLOW_PLAN ? t("Admin.Convert.Planning") : t("Admin.Convert.PlanningFor", formatDuration(seconds));
|
||||
};
|
||||
const ticking = setInterval(showWait, 1000);
|
||||
showWait();
|
||||
totals.title = t("Admin.Convert.Planning.Tip");
|
||||
drawButtons();
|
||||
try {
|
||||
const answer = await dryRun(body, key);
|
||||
const answer = await waiting(() => dryRun(body, key));
|
||||
if (!dialog.open) return;
|
||||
plan = { ...answer, key };
|
||||
shown = PAGE;
|
||||
@@ -251,8 +250,6 @@ export function openConvert({ api, target, names = new Map() } = {}) {
|
||||
if (key === keyNow()) showProblem(err);
|
||||
} finally {
|
||||
planning = false;
|
||||
clearInterval(ticking);
|
||||
totals.title = "";
|
||||
}
|
||||
if (again) {
|
||||
again = false;
|
||||
@@ -263,6 +260,24 @@ export function openConvert({ api, target, names = new Map() } = {}) {
|
||||
drawPlan();
|
||||
}
|
||||
|
||||
/** Runs work while the totals say it is planning and, once that is long, for how long, with why in their tooltip. */
|
||||
async function waiting(work) {
|
||||
const started = Date.now();
|
||||
const showWait = () => {
|
||||
const seconds = Math.floor((Date.now() - started) / 1000);
|
||||
totals.textContent = seconds < SLOW_PLAN ? t("Admin.Convert.Planning") : t("Admin.Convert.PlanningFor", formatDuration(seconds));
|
||||
};
|
||||
const ticking = setInterval(showWait, 1000);
|
||||
showWait();
|
||||
totals.title = t("Admin.Convert.Planning.Tip");
|
||||
try {
|
||||
return await work();
|
||||
} finally {
|
||||
clearInterval(ticking);
|
||||
totals.title = "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The dry run of body. The server makes it apart from the request and keeps it a few minutes, so a request cut off on
|
||||
* the way (a proxy's timeout) is asked again, and answered once the plan is made; a plan the server stopped (let go for
|
||||
@@ -294,12 +309,12 @@ export function openConvert({ api, target, names = new Map() } = {}) {
|
||||
next.hidden = true;
|
||||
preview.hidden = true;
|
||||
} else {
|
||||
// New sequence's words: the photos left as they are are not copied into the new sequence.
|
||||
// New sequence's words: the photos left as they are in the sequences copied are not copied into the new sequences.
|
||||
const copies = plan.mode === "new-sequence";
|
||||
leftHeader.textContent = t(copies ? "Admin.Convert.Column.NotCopied" : "Admin.Convert.Column.Unchanged");
|
||||
totals.textContent = plan.photos === 0 ? t("Admin.Convert.NothingToConvert")
|
||||
: t(copies ? "Admin.Convert.TotalsNew" : "Admin.Convert.Totals", formatNumber(plan.sequences), formatNumber(plan.photos), formatNumber(plan.skipped),
|
||||
formatBytes(plan.bytesBefore), formatBytes(plan.bytesAfter));
|
||||
: t(copies ? "Admin.Convert.TotalsNew" : "Admin.Convert.Totals", formatNumber(plan.sequences), formatNumber(plan.photos),
|
||||
formatNumber(copies ? leftOut(converting(plan.steps)) : plan.skipped), formatBytes(plan.bytesBefore), formatBytes(plan.bytesAfter));
|
||||
space.hidden = plan.photos === 0;
|
||||
space.textContent = plan.space.message;
|
||||
space.classList.toggle("short", !plan.space.enough);
|
||||
@@ -343,37 +358,48 @@ export function openConvert({ api, target, names = new Map() } = {}) {
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** Apply waits for a current plan that converts something, with the space it needs, and for the mode; its tooltip says which. */
|
||||
/**
|
||||
* Apply waits for a current plan that converts something, with the space it needs, and for the mode; its tooltip says
|
||||
* which. While Apply asks the dry run again the fields and Apply wait, and Close stays: nothing was sent to convert yet.
|
||||
*/
|
||||
function drawButtons() {
|
||||
for (const field of form.querySelectorAll("input")) field.disabled = busy;
|
||||
for (const field of form.querySelectorAll("input")) field.disabled = busy || checking;
|
||||
const current = plan !== null && plan.key === keyNow() && !planning;
|
||||
const mode = chosen(modeSet);
|
||||
const reason = !current ? null
|
||||
: plan.photos === 0 ? "Admin.Convert.Nothing.Tip"
|
||||
: !plan.space.enough ? "Admin.Convert.NoSpace.Tip"
|
||||
: mode === null ? "Admin.Convert.ChooseMode.Tip" : null;
|
||||
applyButton.disabled = busy || !current || reason !== null;
|
||||
applyButton.disabled = busy || checking || !current || reason !== null;
|
||||
applyButton.title = t(reason ?? "Admin.Convert.Apply.Tip");
|
||||
closeButton.disabled = busy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace asks for a word to be typed (the originals leave the sequence for the trash); New sequence for a plain
|
||||
* confirmation that says how many photos the new sequences lack. The plan sent back is the one the table showed. The
|
||||
* fields cannot change meanwhile, but a dry run scheduled before may answer during it: the same plan again (same
|
||||
* request and fingerprint) is applied all the same; a different one is shown instead, and Apply waits for the user.
|
||||
* confirmation that says how many photos the new sequences lack, and each sequence's count in the list. The plan sent
|
||||
* back is the one the table showed. The fields cannot change meanwhile, but a dry run scheduled before may answer
|
||||
* during it: the same plan again (same request and fingerprint) is applied all the same; a different one is shown
|
||||
* instead, and Apply waits for the user. The server confirms only the plan it keeps, which lives a few minutes from
|
||||
* when it was made: the dry run is asked first, answered at once while it is kept and otherwise made again while the
|
||||
* totals say so (Close stays meanwhile, nothing being sent yet); the same fingerprint is then confirmed, and a
|
||||
* different one is shown instead.
|
||||
*/
|
||||
async function apply() {
|
||||
if (applyButton.disabled) return;
|
||||
const shownPlan = plan;
|
||||
const body = JSON.parse(shownPlan.key);
|
||||
const format = targetLabel(body.target);
|
||||
const going = shownPlan.steps.filter((s) => (s.blocked ?? []).length === 0 && s.photos > 0);
|
||||
const list = listed(going.map((s) => t("Admin.Convert.PlanItem", names.get(s.sequenceId) || s.title || folderName(s.folder),
|
||||
plural("Admin.Dashboard.PhotoCount", s.photos), t("Admin.Convert.SizeChange", formatBytes(s.bytesBefore), formatBytes(s.bytesAfter)))));
|
||||
// The photos of the sequences converted that stay as they are: their new sequences hold the converted copies alone.
|
||||
const notCopied = going.reduce((sum, s) => sum + (s.skipped ?? []).reduce((photos, k) => photos + k.photos, 0), 0);
|
||||
const going = converting(shownPlan.steps);
|
||||
const replace = body.mode === "replace";
|
||||
const list = listed(going.map((s) => {
|
||||
const item = t("Admin.Convert.PlanItem", names.get(s.sequenceId) || s.title || folderName(s.folder),
|
||||
plural("Admin.Dashboard.PhotoCount", s.photos), t("Admin.Convert.SizeChange", formatBytes(s.bytesBefore), formatBytes(s.bytesAfter)));
|
||||
const left = leftOut([s]);
|
||||
return replace || left === 0 ? item : t("Admin.Convert.PlanItemNotCopied", item, plural("Admin.Convert.NotCopiedCount", left));
|
||||
}));
|
||||
// The photos of the sequences converted that stay as they are: their new sequences hold the converted copies alone.
|
||||
const notCopied = leftOut(going);
|
||||
const confirmed = await confirmDialog(replace ? {
|
||||
title: t("Admin.Convert.ConfirmReplaceTitle", format),
|
||||
body: plural("Admin.Convert.ConfirmReplace", shownPlan.photos, plural("Admin.Library.Count", shownPlan.sequences)),
|
||||
@@ -400,36 +426,81 @@ export function openConvert({ api, target, names = new Map() } = {}) {
|
||||
if (plan) showError(t("Admin.Convert.PlanChanged"));
|
||||
return;
|
||||
}
|
||||
busy = true;
|
||||
showError("");
|
||||
drawButtons();
|
||||
try {
|
||||
const job = await api.post(ENDPOINT, { ...body, dryRun: false, fingerprint: shownPlan.fingerprint });
|
||||
queued = job;
|
||||
busy = false;
|
||||
dialog.close();
|
||||
toast(t("Admin.Convert.Queued"), false,
|
||||
{ label: t("Admin.Convert.OpenJob"), tip: t("Admin.Convert.OpenJob.Tip"), href: `#/jobs?job=${encodeURIComponent(job.id)}` });
|
||||
} catch (err) {
|
||||
busy = false;
|
||||
if (!dialog.open) return;
|
||||
if (["plan_changed", "plan_dropped", "not_enough_space", "nothing_to_convert"].includes(err?.code)) {
|
||||
// The archive changed since the dry run (or its volume filled up, or the server let the plan go before it was
|
||||
// confirmed): nothing was queued; the plan is made again and shown, and Apply waits for it.
|
||||
notice = err.code === "plan_changed" ? t("Admin.Convert.PlanChanged") : errorText(err);
|
||||
plan = null;
|
||||
schedule(0);
|
||||
} else if (cutOff(err, Infinity)) {
|
||||
// No answer: the job may have been queued all the same, and Apply again would queue another one.
|
||||
showError(t("Admin.Convert.NoAnswer"));
|
||||
} else {
|
||||
showProblem(err);
|
||||
}
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
// The dry run first, while the totals say so: nothing is sent to convert yet, so Close stays.
|
||||
checking = true;
|
||||
drawButtons();
|
||||
(applyButton.disabled ? closeButton : applyButton).focus();
|
||||
let now;
|
||||
try {
|
||||
now = await waiting(() => dryRun(body, shownPlan.key));
|
||||
} catch (err) {
|
||||
// Nothing was sent to convert: the plan shown stays, and Apply asks again.
|
||||
checking = false;
|
||||
if (!dialog.open) return;
|
||||
drawPlan();
|
||||
showProblem(err);
|
||||
applyButton.focus();
|
||||
return;
|
||||
}
|
||||
checking = false;
|
||||
// Closed meanwhile: nothing is sent.
|
||||
if (!dialog.open) return;
|
||||
if (now.fingerprint !== shownPlan.fingerprint) {
|
||||
// Made again, and no longer the plan confirmed: shown, and Apply waits for the user.
|
||||
plan = { ...now, key: shownPlan.key };
|
||||
shown = PAGE;
|
||||
drawPlan();
|
||||
showError(t("Admin.Convert.PlanChanged"));
|
||||
(applyButton.disabled ? closeButton : applyButton).focus();
|
||||
return;
|
||||
}
|
||||
busy = true;
|
||||
drawButtons();
|
||||
try {
|
||||
const job = await api.post(ENDPOINT, { ...body, dryRun: false, fingerprint: shownPlan.fingerprint });
|
||||
queued = job;
|
||||
busy = false;
|
||||
dialog.close();
|
||||
toast(t("Admin.Convert.Queued"), false,
|
||||
{ label: t("Admin.Convert.OpenJob"), tip: t("Admin.Convert.OpenJob.Tip"), href: `#/jobs?job=${encodeURIComponent(job.id)}` });
|
||||
return;
|
||||
} catch (err) {
|
||||
busy = false;
|
||||
// Let go between the dry run's answer and the confirmation: asked again, as the dry run was.
|
||||
if (err?.code === "plan_dropped" && attempt < DROPPED_CONFIRMS && dialog.open) continue;
|
||||
if (!dialog.open) return;
|
||||
drawPlan();
|
||||
if (["plan_changed", "plan_dropped", "not_enough_space", "nothing_to_convert"].includes(err?.code)) {
|
||||
// The archive changed since the dry run (or a conversion of these sequences was queued meanwhile, or the volume
|
||||
// filled up, or the server let the plan go): nothing was queued; the plan is made again and shown, and Apply
|
||||
// waits for it.
|
||||
notice = err.code === "plan_changed" ? t("Admin.Convert.PlanChanged") : errorText(err);
|
||||
plan = null;
|
||||
schedule(0);
|
||||
} else if (cutOff(err, Infinity)) {
|
||||
// No answer: the job may have been queued all the same, and Apply again would queue another one.
|
||||
showError(t("Admin.Convert.NoAnswer"));
|
||||
} else {
|
||||
showProblem(err);
|
||||
}
|
||||
drawButtons();
|
||||
(applyButton.disabled ? closeButton : applyButton).focus();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The steps that convert: nothing blocks them, and they have photos to convert. */
|
||||
function converting(steps) {
|
||||
return steps.filter((s) => (s.blocked ?? []).length === 0 && s.photos > 0);
|
||||
}
|
||||
|
||||
/** The photos steps leave as they are: of a sequence New sequence copies, those its new sequence lacks. */
|
||||
function leftOut(steps) {
|
||||
return steps.reduce((sum, s) => sum + (s.skipped ?? []).reduce((photos, k) => photos + k.photos, 0), 0);
|
||||
}
|
||||
|
||||
/** A refusal on the field it names (quality, format, mode), else under the table. */
|
||||
function showProblem(err) {
|
||||
const field = err?.code === "bad_request" ? { quality, target: targetSet, mode: modeSet }[err.details] : undefined;
|
||||
|
||||
@@ -258,25 +258,30 @@ public static class ArchiveEndpoints
|
||||
/// Convert: the photos of <c>sequenceIds</c> or, with <c>all</c>, of every sequence of the archive, converted to
|
||||
/// <c>target</c> (<c>jpeg</c>, <c>tiff16</c>, <c>linear-dng</c>) at <c>quality</c> (JPEG, 1–100, default 95) in <c>mode</c>
|
||||
/// (<c>replace</c> or <c>new-sequence</c>; BRIEF §12.5). With <c>dryRun</c> the plan, nothing touched: per sequence the
|
||||
/// photos converted, their size and the estimate after, the photos left as they are with why in the mode's words (with
|
||||
/// <c>new-sequence</c>, that the new sequence lacks them; <c>convert_on_pc</c> for a format the server cannot read at
|
||||
/// full resolution), what blocks it; the totals; the space needed and free; the fingerprint. Otherwise the request
|
||||
/// carries that fingerprint and the server queues a <c>convert</c> job (202) that applies exactly that plan, leaving as it
|
||||
/// is (and reporting) a sequence that changed before it ran. 400 <c>bad_request</c> (details <c>sequenceIds</c>: neither
|
||||
/// or both of them, none, or more than <see cref="LibraryEndpoints.MaxBulkIds"/>; <c>target</c>, <c>quality</c>,
|
||||
/// <c>mode</c>, <c>fingerprint</c>); 404 <c>not_found</c> (<c>sequence</c>: not in the archive); 409 <c>plan_changed</c>
|
||||
/// (details: the fingerprint now), <c>nothing_to_convert</c>, <c>not_enough_space</c> (details: the bytes needed),
|
||||
/// <c>job_unavailable</c>; 503 <c>archive_offline</c>, <c>plan_dropped</c> (the plan was stopped: past its time, let go
|
||||
/// for newer ones, or the server stopping). Audited (<c>archive_converted</c>: sequences · photos · target · mode); the job
|
||||
/// tells each sequence it replaces the frames of as <c>sequenceChanged</c> <c>converted</c>, each new one as
|
||||
/// <c>created</c>. A dry run's plan is made apart from the request, a few at once (Reorganize's among them) and each for
|
||||
/// a limited time, and kept a few minutes, a refusal too, while what it reads from the index stays as it was
|
||||
/// (<see cref="PlanCache"/>, <see cref="ConvertPlanKey"/>: the sequences' rows, and of the photos of those planned their
|
||||
/// formats, sizes, hashes and the flags that decide): the same dry run again (also after the first was cut off), in
|
||||
/// either mode and at any quality of a lossless target, and its confirmation, take it instead of planning again; only
|
||||
/// the free space is measured again at every request. So <c>plan_changed</c> answers a change the index has. One made on
|
||||
/// disk alone since the plan, or a job that started or ended on its sequences (which a kept plan shows as it found
|
||||
/// them, busy or not), is found by the job, which plans again and leaves as it is a sequence that no longer fits.
|
||||
/// photos converted, their size and the estimate after, the photos left as they are with why in the mode's words (of a
|
||||
/// sequence <c>new-sequence</c> copies, that the new sequence lacks them; <c>convert_on_pc</c> for a format the server
|
||||
/// cannot read at full resolution), what blocks it; the totals; the space needed and free; the fingerprint. Otherwise
|
||||
/// the request carries that fingerprint and the server queues a <c>convert</c> job (202) that converts exactly the photos
|
||||
/// that plan converts, leaving as it is (and reporting) a sequence where one of them changed before it ran. 400
|
||||
/// <c>bad_request</c> (details <c>sequenceIds</c>: neither or both of them, none, or more than
|
||||
/// <see cref="LibraryEndpoints.MaxBulkIds"/>; <c>target</c>, <c>quality</c>, <c>mode</c>, <c>fingerprint</c>); 404
|
||||
/// <c>not_found</c> (<c>sequence</c>: not in the archive); 409 <c>plan_changed</c> (details: the fingerprint now; none
|
||||
/// when a conversion of these sequences was queued meanwhile), <c>nothing_to_convert</c>, <c>not_enough_space</c>
|
||||
/// (details: the bytes needed), <c>job_unavailable</c>; 503 <c>archive_offline</c>, <c>plan_dropped</c> (the plan was
|
||||
/// stopped: past its time, let go for newer ones, or the server stopping; for a confirmation, no plan is kept for the
|
||||
/// index as it is now, let go since or the index changed: ask the dry run again, and confirm that one). Audited
|
||||
/// (<c>archive_converted</c>: sequences · photos · target · mode); the job tells each sequence it replaces the frames of
|
||||
/// as <c>sequenceChanged</c> <c>converted</c>, each new one as <c>created</c>. A dry run's plan is made apart from the
|
||||
/// request, a few at once (Reorganize's among them) and each for a limited time, and kept a few minutes, a refusal too,
|
||||
/// while what it reads from the index stays as it was (<see cref="PlanCache"/>, <see cref="ConvertPlanKey"/>: the
|
||||
/// sequences' rows, and of the photos of those planned their formats, sizes, hashes and the flags that decide): the
|
||||
/// same dry run again (also after the first was cut off), in either mode and at any quality of a lossless target, takes
|
||||
/// it instead of planning again, and a confirmation takes only it, never planning inside its own request (a proxy could
|
||||
/// cut that off once the job is queued); the sequences jobs make busy and the free space are as they are at every
|
||||
/// request. So a confirmation answers <c>plan_dropped</c> when the index changed, and <c>plan_changed</c> when the plan
|
||||
/// kept is not the one confirmed (a job started or ended on one of its sequences since). One made on disk alone since
|
||||
/// the plan is found by the job, which plans again and converts the photos confirmed alone, each only while it holds
|
||||
/// the content confirmed, leaving the sequence as it is otherwise.
|
||||
/// </summary>
|
||||
private static async Task<IResult> ConvertAsync(HttpContext context, Caller caller, ConvertRequest request, ChronosDatabase db, ServerArchive archive,
|
||||
[FromServices] ArchiveService? archives, JobEngineHost host, AuditLog audit, PlanCache plans)
|
||||
@@ -299,11 +304,25 @@ public static class ArchiveEndpoints
|
||||
ConvertPlan plan;
|
||||
try
|
||||
{
|
||||
// Made whatever becomes of this request, until the cache stops it: the same request again takes it, in either mode.
|
||||
var kept = await plans.GetOrPlanAsync(key, stop => PlanConvertAsync(engine, archive.Current, sequences, options, stop), ct);
|
||||
ConvertPlan kept;
|
||||
if (request.DryRun)
|
||||
{
|
||||
// Made whatever becomes of this request, until the cache stops it: the same request again takes it, in either mode.
|
||||
kept = await plans.GetOrPlanAsync(key, stop => PlanConvertAsync(engine, archive.Current, sequences, options, stop), ct);
|
||||
}
|
||||
else if (plans.Kept(key) is { } shown)
|
||||
{
|
||||
kept = await shown;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Let go since its dry run (past its lifetime, or for newer plans): planned again inside this request, it could
|
||||
// outlast a proxy, which would cut it off after its job was queued. The client asks the dry run again.
|
||||
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "plan_dropped");
|
||||
}
|
||||
// What converts is the same in either mode and at any quality of a lossless target: the request's own are set on
|
||||
// it, and the free space is the volume's now.
|
||||
plan = kept with { Options = options, Mode = mode, Space = kept.Space with { Free = await FreeSpaceAsync(engine, archive.Id, options, ct) } };
|
||||
// it; the sequences busy and the free space are as they are now.
|
||||
plan = Now(kept with { Options = options, Mode = mode }, await engine.Converter.BusyAsync(ct), await FreeSpaceAsync(engine, archive.Id, options, ct));
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
@@ -324,17 +343,45 @@ public static class ArchiveEndpoints
|
||||
if (plan.Frames == 0) return ApiErrors.Conflict(context, "nothing_to_convert");
|
||||
if (!plan.Space.Enough) return ApiErrors.Conflict(context, "not_enough_space", plan.Space.Required.ToString(CultureInfo.InvariantCulture));
|
||||
if (!host.CanRun(JobKind.Convert)) return ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(JobKind.Convert));
|
||||
var job = await host.Engine.EnqueueAsync(ArchiveJobs.Convert(archive.Current, plan), caller.Id, ct);
|
||||
Job? job = null;
|
||||
try
|
||||
{
|
||||
// Checked against the conversions pending and queued under one lock: two confirmations at once queue one job.
|
||||
await engine.Converter.QueueAsync(archive.Current, plan, async r => job = await host.Engine.EnqueueAsync(r, caller.Id, ct), ct);
|
||||
}
|
||||
catch (ConversionQueuedException)
|
||||
{
|
||||
// Another tab or user queued a conversion of these sequences since: the dry run now shows them busy.
|
||||
return ApiErrors.Conflict(context, "plan_changed");
|
||||
}
|
||||
plans.Forget(key);
|
||||
await audit.WriteAsync(caller, context, "archive_converted", "job", job.Id.ToString(),
|
||||
await audit.WriteAsync(caller, context, "archive_converted", "job", job!.Id.ToString(),
|
||||
$"{plan.Converted.Count()} · {plan.Frames} · {Wire(target)} · {Wire(mode)}");
|
||||
return Results.Json(Dto.Job(job), ProtocolJson.Default.JobDto, statusCode: StatusCodes.Status202Accepted);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A kept conversion plan as it stands now: each sequence busy or not as the jobs are now (<see cref="MassConverter.BusyAsync"/>:
|
||||
/// a kept plan never shows one busy once its job ended, nor free once a conversion of it was queued), and the space it
|
||||
/// needs for the sequences that convert then, against the free space measured now. A busy sequence is planned all the
|
||||
/// same, so its photos are those it converts once free.
|
||||
/// </summary>
|
||||
private static ConvertPlan Now(ConvertPlan plan, IReadOnlySet<Guid> busy, long? free)
|
||||
{
|
||||
var archiveBusy = busy.Contains(plan.ArchiveId);
|
||||
List<ConvertSequencePlan> sequences = [.. plan.Sequences.Select(s => s with { Blocked = Blocks(s.Blocked, archiveBusy || busy.Contains(s.SequenceId)) })];
|
||||
var estimated = sequences.Where(s => s.Converts).Sum(s => s.BytesAfter);
|
||||
return plan with { Sequences = sequences, Space = new ConvertSpace(ConvertPlanner.Required(estimated), free) };
|
||||
|
||||
// In the order a plan made now lists them: offline, busy, then what its sidecar said.
|
||||
static IReadOnlyList<ConvertBlock> Blocks(IReadOnlyList<ConvertBlock> blocked, bool held) =>
|
||||
[.. blocked.Where(b => b == ConvertBlock.Offline), .. held ? [ConvertBlock.Busy] : (ConvertBlock[])[], .. blocked.Where(b => b is not (ConvertBlock.Offline or ConvertBlock.Busy))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The conversion plan <see cref="PlanCache"/> keeps for a <see cref="ConvertPlanKey"/>, made in one mode for both (the
|
||||
/// request's is set on it). One made while the archive's volume was away read nothing of it: it is not kept, and the
|
||||
/// request is answered <c>archive_offline</c>.
|
||||
/// request's is set on it, and the busy sequences and free space at every request: <see cref="Now"/>). One made while
|
||||
/// the archive's volume was away read nothing of it: it is not kept, and the request is answered <c>archive_offline</c>.
|
||||
/// </summary>
|
||||
private static async Task<ConvertPlan> PlanConvertAsync(ArchiveService engine, Archive archive, IReadOnlyList<Guid>? sequences, ConvertOptions options,
|
||||
CancellationToken cancellationToken)
|
||||
@@ -362,7 +409,7 @@ public static class ArchiveEndpoints
|
||||
return new ConvertPlanDto(Wire(plan.Options.Target), plan.Options.Quality, Wire(plan.Mode),
|
||||
[.. plan.Sequences.Select(s => new ConvertSequenceDto(s.SequenceId, s.Title, s.Folder, s.FramesVersion, s.Frames.Count, s.BytesBefore, s.BytesAfter,
|
||||
[.. s.Skipped.GroupBy(k => Wire(k.Reason))
|
||||
.Select(g => new ConvertSkippedDto(g.Key, g.Sum(k => k.Frames), SkipMessage(g.First().Reason, plan.Mode, culture)))],
|
||||
.Select(g => new ConvertSkippedDto(g.Key, g.Sum(k => k.Frames), SkipMessage(g.First().Reason, plan.Mode == ConvertMode.NewSequence && s.Converts, culture)))],
|
||||
[.. s.Blocked.Select(b => new ConvertBlockedDto(Wire(b), Loc.Get("Archive.Convert.Blocked." + b, culture) ?? Wire(b)))]))],
|
||||
plan.Converted.Count(),
|
||||
plan.Frames,
|
||||
@@ -378,7 +425,8 @@ public static class ArchiveEndpoints
|
||||
/// full-resolution decoder for, or a file it reads only from its preview: a PC with the camera's codec may convert
|
||||
/// them), <c>undecodable</c>, <c>missing</c>, <c>unhashed</c>, <c>eight_bit</c> (a RAW this host develops at 8 bits only,
|
||||
/// for a 16-bit target), <c>color_profile</c> (a colour profile the target can neither keep nor convert to),
|
||||
/// <c>too_large</c>.
|
||||
/// <c>too_large</c>, <c>inaccessible</c> (a file another program held open, or that could not be opened, when the plan
|
||||
/// was made).
|
||||
/// </summary>
|
||||
public static string Wire(ConvertSkip reason) => reason switch
|
||||
{
|
||||
@@ -389,6 +437,7 @@ public static class ArchiveEndpoints
|
||||
ConvertSkip.EightBit => "eight_bit",
|
||||
ConvertSkip.ColorProfile => "color_profile",
|
||||
ConvertSkip.TooLarge => "too_large",
|
||||
ConvertSkip.Inaccessible => "inaccessible",
|
||||
_ => "unhashed",
|
||||
};
|
||||
|
||||
@@ -420,13 +469,14 @@ public static class ArchiveEndpoints
|
||||
|
||||
/// <summary>
|
||||
/// Why photos are not converted, in <paramref name="culture"/>: on the server, a format it cannot read says to convert on
|
||||
/// a PC. With <see cref="ConvertMode.NewSequence"/> it says that the new sequence lacks them (it holds the converted
|
||||
/// copies alone); otherwise that they stay as they are.
|
||||
/// a PC. Of a sequence <see cref="ConvertMode.NewSequence"/> copies (<paramref name="copied"/>) it says that the new
|
||||
/// sequence lacks them (it holds the converted copies alone); otherwise, and of a sequence that converts nothing now (no
|
||||
/// new sequence is made of it), that they stay as they are.
|
||||
/// </summary>
|
||||
private static string SkipMessage(ConvertSkip reason, ConvertMode mode, CultureInfo culture)
|
||||
private static string SkipMessage(ConvertSkip reason, bool copied, CultureInfo culture)
|
||||
{
|
||||
var onPc = reason is ConvertSkip.NoNativeDecoder or ConvertSkip.PreviewOnly;
|
||||
var key = mode == ConvertMode.NewSequence
|
||||
var key = copied
|
||||
? onPc ? "Server.Convert.OnPcNew" : "Archive.Convert.NotCopied." + reason
|
||||
: onPc ? "Server.Convert.OnPc" : "Archive.Convert.Skipped." + reason;
|
||||
return Loc.Get(key, culture) ?? Wire(reason);
|
||||
|
||||
@@ -16,8 +16,9 @@ namespace Chronos.Server.Api;
|
||||
/// plans are made at once, of either kind; one still being made past <see cref="PlanTimeout"/>, let go for newer ones
|
||||
/// (<see cref="Capacity"/>), or when the server stops, is stopped, and whoever waits for it is told it was dropped
|
||||
/// (<see cref="OperationCanceledException"/>). A change made on disk alone, which the index does not have, is not seen by a
|
||||
/// kept plan, and neither is one of the jobs running: the job that applies a plan plans again and leaves as it is what no
|
||||
/// longer matches it, so nothing changes that the dry run did not show.
|
||||
/// kept plan: the job that applies a plan plans again and does only what the plan confirmed showed, leaving as it is what
|
||||
/// no longer matches it. A conversion's confirmation takes a kept plan only (<see cref="Kept"/>): one let go since is
|
||||
/// planned again by a dry run, apart from the request, and confirmed then.
|
||||
/// </summary>
|
||||
public sealed class PlanCache : IDisposable
|
||||
{
|
||||
@@ -94,6 +95,31 @@ public sealed class PlanCache : IDisposable
|
||||
return (TPlan)await entry!.Plan.Task.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The plan kept for <paramref name="key"/> (or the refusal kept for it, which the task throws), within its lifetime; null
|
||||
/// when there is none: never made, still being made, stopped, or let go. Plans nothing: a confirmation takes the plan its
|
||||
/// dry run showed, never one made inside its own request, which a proxy may cut off once the job is queued.
|
||||
/// </summary>
|
||||
public Task<TPlan>? Kept<TPlan>(PlanKey<TPlan> key) where TPlan : class
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(key);
|
||||
Task<object> plan;
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_plans.TryGetValue(key, out var entry) || entry.Made is not { } made) return null;
|
||||
if (_time.GetUtcNow() - made >= Lifetime)
|
||||
{
|
||||
Remove(key);
|
||||
return null;
|
||||
}
|
||||
plan = entry.Plan.Task;
|
||||
}
|
||||
return As(plan);
|
||||
|
||||
// The key's kind names the plan's: what was made for it is a TPlan.
|
||||
static async Task<TPlan> As(Task<object> made) => (TPlan)await made.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Forgets the plan kept for <paramref name="key"/>: its job is queued, and what the job changes gives the index another stamp.</summary>
|
||||
public void Forget(PlanKey key)
|
||||
{
|
||||
@@ -252,6 +278,7 @@ public sealed record ReorganizePlanKey(Guid ArchiveId, string Stamp, string Sequ
|
||||
/// (<see cref="SequenceRepository.GetConvertStampAsync"/>), the sequences (all of them, or the ids in the order given) and
|
||||
/// the target with the quality that counts (<see cref="ConvertOptions.Key"/>: a lossless target's ignores it). Not the
|
||||
/// mode: what converts is the same in either, so the plan made with one serves the other (the endpoint sets the request's).
|
||||
/// Nor the jobs that make a sequence busy, nor the free space: the endpoint sets those as they are at every request.
|
||||
/// A sequence not in the archive (<see cref="ArgumentException"/>) refuses it.
|
||||
/// </summary>
|
||||
public sealed record ConvertPlanKey(Guid ArchiveId, string Stamp, string Sequences, string Options) : PlanKey<ConvertPlan>
|
||||
|
||||
Reference in new issue
Block a user