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
@@ -5,6 +5,7 @@ using System.Text.Json;
|
||||
using Chronos.App.Archiving;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Tests.Import;
|
||||
using Chronos.App.Tests.Uploader;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Conversion;
|
||||
using Chronos.Core.Imaging;
|
||||
@@ -70,17 +71,42 @@ public sealed class ConvertDialogTests(TestContext context)
|
||||
Loc.Plural("Archive.Convert.SkippedPhotos", 3)), ConvertPlans.Summary(plan));
|
||||
Assert.Equal(Loc.Plural("Archive.Rename.Summary", 0, 1), ConvertPlans.Summary(plan with { Sequences = [comet] }), "nothing converts, nothing more is said");
|
||||
|
||||
// Into a new sequence, which holds the converted copies alone: the photos skipped are not copied into it.
|
||||
var copies = plan with { Mode = ConvertMode.NewSequence };
|
||||
// Into a new sequence, which holds the converted copies alone: the photos skipped are not copied into it. Of a
|
||||
// sequence that converts nothing no copy is made, and its photos stay as they are.
|
||||
var same = new ConvertSequencePlan(Guid.CreateVersion7(), "Lake", "2025/Lake", 1, [], [new ConvertSkipped(ConvertSkip.SameFormat, 2)], []);
|
||||
var copies = plan with { Mode = ConvertMode.NewSequence, Sequences = [harbour, comet, empty, untitled, same] };
|
||||
var copied = ConvertPlans.Rows(copies);
|
||||
Assert.SequenceEqual(
|
||||
[
|
||||
Loc.L("Archive.Convert.NotCopied.SameFormat") + Loc.Separator + Loc.Plural("Shell.Status.Photos", 2),
|
||||
Loc.L("Archive.Convert.NotCopied.Unhashed") + Loc.Separator + Loc.Plural("Shell.Status.Photos", 1),
|
||||
],
|
||||
ConvertPlans.Rows(copies)[0].Kept);
|
||||
Assert.SequenceEqual(busy.Kept, ConvertPlans.Rows(copies)[1].Kept, "what blocks a sequence reads the same");
|
||||
Assert.Equal(string.Join(Loc.Separator, Loc.Plural("Archive.Rename.Summary", 2, 4), Loc.Plural("Shell.Status.Photos", 4), ConvertPlans.Sizes(3_500_000, 6_700_000),
|
||||
Loc.Plural("Archive.Convert.NotCopiedPhotos", 3)), ConvertPlans.Summary(copies));
|
||||
copied[0].Kept);
|
||||
Assert.SequenceEqual(busy.Kept, copied[1].Kept, "what blocks a sequence reads the same");
|
||||
Assert.SequenceEqual([Loc.L("Archive.Convert.Skipped.SameFormat") + Loc.Separator + Loc.Plural("Shell.Status.Photos", 2)], copied[3].Kept);
|
||||
Assert.Equal(3, ConvertPlans.LeftOut(copies));
|
||||
Assert.Equal(string.Join(Loc.Separator, Loc.Plural("Archive.Rename.Summary", 2, 5), Loc.Plural("Shell.Status.Photos", 4), ConvertPlans.Sizes(3_500_000, 6_700_000),
|
||||
Loc.Plural("Archive.Convert.NotCopiedPhotos", 3), Loc.Plural("Archive.Convert.SkippedPhotos", 2)), ConvertPlans.Summary(copies));
|
||||
|
||||
// New sequence is confirmed too, before anything is queued: what is copied, nothing to type, and which photos the
|
||||
// new sequences lack, with their count, sequence by sequence.
|
||||
var copy = Assert.NotNull(ConvertPlans.NewRequest(copies));
|
||||
Assert.False(copy.IsDestructive);
|
||||
Assert.Null(copy.TypedConfirmation);
|
||||
Assert.Equal(Loc.Plural("Archive.Convert.NewHeading", 2), copy.Heading);
|
||||
Assert.Equal(Loc.L("Archive.Convert.NewMessage", Loc.Plural("Shell.Status.Photos", 4), Formatting.Bytes(3_500_000), Loc.L("Archive.Convert.Target.LinearDng"))
|
||||
+ " " + Loc.Plural("Archive.Convert.NewLeftOut", 3), copy.Message);
|
||||
Assert.SequenceEqual(
|
||||
[
|
||||
Loc.L("Archive.Delete.Line", "Harbour sunset", Loc.Plural("Shell.Status.Photos", 3), ConvertPlans.Sizes(3_000_000, 6_000_000))
|
||||
+ Loc.Separator + Loc.Plural("Archive.Convert.NotCopiedPhotos", 3),
|
||||
Loc.L("Archive.Delete.Line", "2026/2026-09-29", Loc.Plural("Shell.Status.Photos", 1), ConvertPlans.Sizes(500_000, 700_000)),
|
||||
],
|
||||
copy.Detail!.Split(Environment.NewLine));
|
||||
Assert.Equal((Loc.L("Archive.Convert.Confirm"), Loc.L("Archive.Dialog.Cancel")), (copy.ActionText, copy.SafeText));
|
||||
Assert.Equal(Loc.L("Archive.Convert.NewMessage", Loc.Plural("Shell.Status.Photos", 1), Formatting.Bytes(500_000), Loc.L("Archive.Convert.Target.LinearDng")),
|
||||
ConvertPlans.NewRequest(copies with { Sequences = [untitled, same] })!.Message, "nothing left out, nothing said of it");
|
||||
Assert.Null(ConvertPlans.NewRequest(copies with { Sequences = [comet, empty, same] }), "nothing to copy, nothing to confirm");
|
||||
|
||||
// The space line: enough, short, or not measurable.
|
||||
var required = Formatting.Bytes(plan.Space.Required);
|
||||
@@ -119,16 +145,16 @@ public sealed class ConvertDialogTests(TestContext context)
|
||||
var comet = await UploadAsync(archives, archive, "comet", Start.AddDays(1), 11);
|
||||
|
||||
var queued = new TaskCompletionSource<ArchiveJobRequest>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var asked = 0;
|
||||
List<ConfirmRequest> asked = [];
|
||||
var closed = false;
|
||||
using var dialog = new ConvertDialogViewModel(archives, archive, [harbour, comet], request =>
|
||||
{
|
||||
queued.TrySetResult(request);
|
||||
return Task.CompletedTask;
|
||||
}, _ =>
|
||||
}, request =>
|
||||
{
|
||||
asked++;
|
||||
return false;
|
||||
asked.Add(request);
|
||||
return true;
|
||||
}, _ => closed = true);
|
||||
|
||||
// The archival format, the default quality, and no mode: every run chooses it.
|
||||
@@ -157,13 +183,13 @@ public sealed class ConvertDialogTests(TestContext context)
|
||||
Assert.Equal(Loc.L("Tooltips.Archive.ConvertApplyNew"), dialog.ApplyToolTip);
|
||||
Assert.True(dialog.ApplyCommand.CanExecute(null));
|
||||
|
||||
// JPEG to JPEG converts nothing: into a new sequence those photos are not copied, which the rows and the summary
|
||||
// say, and Replace's words are that they stay as they are. A quality outside 1-100 blocks a JPEG only.
|
||||
// JPEG to JPEG converts nothing: no new sequence is made of them, so in either mode the rows and the summary say the
|
||||
// photos stay as they are. A quality outside 1-100 blocks a JPEG only.
|
||||
dialog.IsJpeg = true;
|
||||
Assert.Equal(Loc.L("Archive.Blocked.Planning"), dialog.ApplyToolTip, "the dry run on screen is not the one of the format chosen");
|
||||
await dialog.PlanAsync();
|
||||
Assert.SequenceEqual([Loc.L("Archive.Convert.NotCopied.SameFormat") + Loc.Separator + Loc.Plural("Shell.Status.Photos", 2)], dialog.Rows[0].Kept);
|
||||
Assert.Equal(Loc.Plural("Archive.Convert.NotCopiedPhotos", 4), dialog.SummaryText.Split(Loc.Separator)[^1]);
|
||||
Assert.SequenceEqual([Loc.L("Archive.Convert.Skipped.SameFormat") + Loc.Separator + Loc.Plural("Shell.Status.Photos", 2)], dialog.Rows[0].Kept);
|
||||
Assert.Equal(Loc.Plural("Archive.Convert.SkippedPhotos", 4), dialog.SummaryText.Split(Loc.Separator)[^1]);
|
||||
dialog.IsReplace = true;
|
||||
Assert.SequenceEqual([Loc.L("Archive.Convert.Skipped.SameFormat") + Loc.Separator + Loc.Plural("Shell.Status.Photos", 2)], dialog.Rows[0].Kept);
|
||||
Assert.Equal(Loc.Plural("Archive.Convert.SkippedPhotos", 4), dialog.SummaryText.Split(Loc.Separator)[^1]);
|
||||
@@ -190,7 +216,10 @@ public sealed class ConvertDialogTests(TestContext context)
|
||||
dialog.ApplyCommand.Execute(null);
|
||||
var request = await queued.Task.WaitAsync(TimeSpan.FromSeconds(TestTiming.Budget(20)));
|
||||
await UntilAsync(() => closed);
|
||||
Assert.Equal(0, asked, "a new sequence leaves the originals as they are: nothing to type");
|
||||
// Confirmed first, with what the new sequences hold: the originals stay as they are, so nothing to type.
|
||||
var confirmed = asked.Single();
|
||||
Assert.Equal(ConvertPlans.NewRequest(plan with { Mode = ConvertMode.NewSequence }), confirmed);
|
||||
Assert.Null(confirmed.TypedConfirmation);
|
||||
Assert.Equal(JobKind.Convert, request.Kind);
|
||||
Assert.SequenceEqual(new[] { harbour, comet }.Order(), request.Targets.Order());
|
||||
Assert.Equal(archive.Name, request.Label);
|
||||
@@ -207,6 +236,75 @@ public sealed class ConvertDialogTests(TestContext context)
|
||||
Assert.Equal(2, (await db.Frames.ListBySequenceAsync(harbour)).Count(f => f.Format == ImageFileFormat.Jpeg), "the job converts, not the dialog");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ASecondDialogOnTheSameSequencesIsRefusedAndShowsThemBusy()
|
||||
{
|
||||
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
||||
var directory = context.CreateTempDirectory("convert-twice");
|
||||
await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(directory, "index.db")), context.Cancellation);
|
||||
var archives = Service(db);
|
||||
var archive = await archives.CreateAsync(Path.Combine(directory, "archive"), "Main", cancellationToken: context.Cancellation);
|
||||
var harbour = await UploadAsync(archives, archive, "harbour", Start, 1);
|
||||
// Queued as the engine does: the job waits in the index.
|
||||
async Task Enqueue(ArchiveJobRequest request) => await db.Jobs.EnqueueAsync(new Job
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Kind = request.Kind,
|
||||
TargetIds = request.Targets,
|
||||
ParametersJson = request.ParametersJson,
|
||||
State = JobState.Queued,
|
||||
Created = DateTimeOffset.UtcNow,
|
||||
}, context.Cancellation);
|
||||
var closed = new List<ArchiveDialogViewModel>();
|
||||
ConvertDialogViewModel Open() => new(archives, archive, [harbour], Enqueue, _ => true, closed.Add) { IsNewSequence = true };
|
||||
|
||||
// The Library's dialog and the Archive manager's, both planned before either applies.
|
||||
using var library = Open();
|
||||
using var manager = Open();
|
||||
await library.PlanAsync();
|
||||
await manager.PlanAsync();
|
||||
library.ApplyCommand.Execute(null);
|
||||
await UntilAsync(() => closed.Contains(library));
|
||||
|
||||
// The second is refused: it says why, plans again with the sequence busy, and stays open.
|
||||
manager.ApplyCommand.Execute(null);
|
||||
await UntilAsync(() => manager.ErrorText is not null && !manager.IsBusy && manager.Plan is not null);
|
||||
Assert.Equal(Loc.L("Archive.Convert.AlreadyQueued"), manager.ErrorText);
|
||||
Assert.SequenceEqual([Loc.L("Archive.Convert.Blocked.Busy")], manager.Rows.Single().Kept);
|
||||
Assert.Equal(Loc.L("Archive.Blocked.NothingToConvert"), manager.ApplyToolTip);
|
||||
Assert.DoesNotContain(manager, closed);
|
||||
Assert.Count(1, (await db.Jobs.ListAsync(JobState.Queued, JobKind.Convert)).Items);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Apply queues the job on the dialog's own thread, the check against the conversions queued already included: the
|
||||
/// desktop's enqueue tells the user with a toast, which only the UI thread may show.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public void TheJobIsQueuedOnTheDialogsThread() => SingleThreadedContext.Run(async () =>
|
||||
{
|
||||
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
||||
var directory = context.CreateTempDirectory("convert-thread");
|
||||
await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(directory, "index.db")), context.Cancellation);
|
||||
var archives = Service(db);
|
||||
var archive = await archives.CreateAsync(Path.Combine(directory, "archive"), "Main", cancellationToken: context.Cancellation);
|
||||
var harbour = await UploadAsync(archives, archive, "harbour", Start, 1);
|
||||
var ui = Environment.CurrentManagedThreadId;
|
||||
int? queuedOn = null;
|
||||
var closed = false;
|
||||
using var dialog = new ConvertDialogViewModel(archives, archive, [harbour], _ =>
|
||||
{
|
||||
queuedOn = Environment.CurrentManagedThreadId;
|
||||
return Task.CompletedTask;
|
||||
}, _ => true, _ => closed = true);
|
||||
dialog.IsNewSequence = true;
|
||||
await dialog.PlanAsync();
|
||||
|
||||
dialog.ApplyCommand.Execute(null);
|
||||
await UntilAsync(() => closed);
|
||||
Assert.Equal<int?>(ui, queuedOn);
|
||||
});
|
||||
|
||||
[Test]
|
||||
public async Task AVolumeWithoutTheSpaceBlocksApply()
|
||||
{
|
||||
|
||||
@@ -102,6 +102,42 @@ public sealed class ConvertPlannerTests(TestContext context)
|
||||
Assert.SequenceEqual([0, 1], native.Frames.Select(f => f.Index));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A file the plan cannot read is not called missing unless it is gone: one another program holds, or that access is
|
||||
/// denied to, could not be opened now (a plan made once it is free converts it), and one shorter than its own headers
|
||||
/// cannot be decoded.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public void AFileThatCannotBeReadNowSaysWhy()
|
||||
{
|
||||
var folder = new ArchivePaths(context.CreateTempDirectory("archive")).Sequence("roof");
|
||||
Exception[] failures =
|
||||
[
|
||||
new FileNotFoundException("gone"), new DirectoryNotFoundException("gone"), new IOException("held by another process"),
|
||||
new UnauthorizedAccessException("denied"), new EndOfStreamException("short"),
|
||||
];
|
||||
SidecarFrame[] frames = [.. failures.Select((_, i) => Frame(i, $"IMG_{i:0000}.CR2", ImageFileFormat.Cr2))];
|
||||
var manifest = new SequenceManifest { Id = Guid.NewGuid(), Frames = frames };
|
||||
// IMG_0000 fails as the first, IMG_0004 as the last.
|
||||
var decoder = new ImageDecoder([new ProbeFails(path => failures[Path.GetFileNameWithoutExtension(path)[^1] - '0'])]);
|
||||
|
||||
var plan = ConvertPlanner.Plan(manifest, folder, [.. frames.Select(f => f.File)], new ConvertOptions(ConvertTarget.LinearDng), decoder, "Roof");
|
||||
Assert.Empty(plan.Frames);
|
||||
Assert.SequenceEqual([(ConvertSkip.Undecodable, 1), (ConvertSkip.Missing, 2), (ConvertSkip.Inaccessible, 2)], plan.Skipped.Select(s => (s.Reason, s.Frames)));
|
||||
}
|
||||
|
||||
/// <summary>A RAW decoder whose probe of a file fails as <paramref name="failure"/> says.</summary>
|
||||
private sealed class ProbeFails(Func<string, Exception> failure) : IImageDecoderProvider
|
||||
{
|
||||
public string Name => "fails";
|
||||
|
||||
public DecodeTier? TierFor(ImageFileFormat format) => format == ImageFileFormat.Cr2 ? DecodeTier.Native : null;
|
||||
|
||||
public FileTier Probe(string path, ImageFileFormat format) => throw failure(path);
|
||||
|
||||
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default) => null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The managed decoder develops every RAW it reads natively (at float precision) even where WIC could; a RAW only WIC's
|
||||
/// Raw Image Extension develops, at 8 bits, converts to JPEG but not to TIFF-16 or linear DNG.
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Runtime.Versioning;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Archiving;
|
||||
@@ -109,6 +110,54 @@ public sealed class ConvertTests(TestContext context)
|
||||
private static bool StagedAnything(ArchiveFixture fx) =>
|
||||
Directory.Exists(Staging(fx)) && Directory.EnumerateDirectories(Staging(fx), "convert-*").Any();
|
||||
|
||||
/// <summary>
|
||||
/// Makes <paramref name="path"/> unreadable until disposed, as another program holding it does: without read permission
|
||||
/// where that stops the test process (UnauthorizedAccessException), otherwise (Windows, root) held open without sharing
|
||||
/// (IOException).
|
||||
/// </summary>
|
||||
private static IDisposable Unreadable(string path)
|
||||
{
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
var mode = File.GetUnixFileMode(path);
|
||||
File.SetUnixFileMode(path, UnixFileMode.None);
|
||||
try
|
||||
{
|
||||
File.OpenRead(path).Dispose();
|
||||
File.SetUnixFileMode(path, mode);
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
return new UnixPermissions(path, mode);
|
||||
}
|
||||
}
|
||||
return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None);
|
||||
}
|
||||
|
||||
/// <summary>Gives a file its permissions back.</summary>
|
||||
[UnsupportedOSPlatform("windows")]
|
||||
private sealed class UnixPermissions(string path, UnixFileMode mode) : IDisposable
|
||||
{
|
||||
public void Dispose() => File.SetUnixFileMode(path, mode);
|
||||
}
|
||||
|
||||
/// <summary>A queued conversion job of <paramref name="plan"/>, as the engine would hold it, created at <paramref name="created"/>.</summary>
|
||||
private static async Task<Job> QueuedAsync(ArchiveFixture fx, ConvertPlan plan, DateTimeOffset created)
|
||||
{
|
||||
var request = ArchiveJobs.Convert(fx.Archive, plan);
|
||||
var job = new Job
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Kind = request.Kind,
|
||||
TargetIds = request.Targets,
|
||||
ParametersJson = request.ParametersJson,
|
||||
State = JobState.Queued,
|
||||
Created = created,
|
||||
};
|
||||
await fx.Db.Jobs.EnqueueAsync(job, fx.Ct);
|
||||
return job;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheDryRunCountsWhatConvertsAndChangesNothing()
|
||||
{
|
||||
@@ -444,19 +493,60 @@ public sealed class ConvertTests(TestContext context)
|
||||
public async Task ASequenceThatChangedAfterThePlanIsLeftAsItWas()
|
||||
{
|
||||
await using var fx = await FixtureAsync();
|
||||
var id = await UploadedAsync(fx, 2);
|
||||
var id = await UploadedAsync(fx, 3);
|
||||
var engine = await fx.StartEngineAsync();
|
||||
var plan = await PlanAsync(fx, ConvertTarget.LinearDng, ConvertMode.Replace, id);
|
||||
// Another photo arrives before the job runs.
|
||||
var (path, size, sha) = fx.Stage(Start.AddSeconds(60), 999);
|
||||
await fx.Service.Ingest.CommitAsync(new IngestRequest(fx.Archive.Id, id, null, null, path, "IMG_0099.JPG", size, sha, null, null), fx.Ct);
|
||||
// A photo of the plan is deleted before the job runs.
|
||||
var sequence = (await fx.Db.Sequences.GetAsync(id))!;
|
||||
var delete = await fx.Service.FrameTrash.PlanDeleteAsync(id, [(await FramesAsync(fx, id))[1].Id], sequence.FramesVersion, fx.Ct);
|
||||
await fx.Service.FrameTrash.DeleteAsync(delete, "alberto", null, fx.Ct);
|
||||
var before = await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id);
|
||||
|
||||
var job = await RunAsync(fx, engine, plan, JobState.Failed);
|
||||
Assert.Equal(Loc.Plural("Archive.Error.ConvertKept", 1), job.Error);
|
||||
Assert.Contains(Loc.L("Archive.Log.ConvertChanged", (await fx.Db.Sequences.GetAsync(id))!.DisplayTitle), job.LogTail);
|
||||
var changed = Loc.L("Archive.Log.ConvertChanged", sequence.DisplayTitle);
|
||||
Assert.Contains(changed, job.LogTail);
|
||||
Assert.Equal(before, await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id));
|
||||
Assert.Empty(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct));
|
||||
Assert.DoesNotContain(TrashKind.Replaced, (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Select(e => e.Kind));
|
||||
// The refusal holds on a retry too, and says so: the user plans again.
|
||||
await engine.ResumeAsync(job.Id, fx.Ct);
|
||||
Assert.Contains(changed, (await fx.WaitForAsync(job.Id, JobState.Failed)).LogTail);
|
||||
Assert.Equal(before, await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task PhotosThatComeInWhileTheJobWaitsItsTurnStayAsTheyAreAndThoseConfirmedConvert()
|
||||
{
|
||||
foreach (var mode in new[] { ConvertMode.Replace, ConvertMode.NewSequence })
|
||||
{
|
||||
await using var fx = await FixtureAsync();
|
||||
var id = await UploadedAsync(fx, 2);
|
||||
var engine = await fx.StartEngineAsync();
|
||||
var plan = await PlanAsync(fx, ConvertTarget.Tiff16, mode, id);
|
||||
var title = (await fx.Db.Sequences.GetAsync(id))!.DisplayTitle;
|
||||
// An upload lands after the confirmation, before the job comes to the sequence (it waited behind a render, or
|
||||
// behind other sequences).
|
||||
var (path, size, sha) = fx.Stage(Start.AddSeconds(60), 999);
|
||||
await fx.Service.Ingest.CommitAsync(new IngestRequest(fx.Archive.Id, id, null, null, path, "IMG_0099.JPG", size, sha, null, null), fx.Ct);
|
||||
|
||||
var job = await RunAsync(fx, engine, plan);
|
||||
var frames = await FramesAsync(fx, id);
|
||||
Assert.Equal((sha, ImageFileFormat.Jpeg), frames.Where(f => f.Sha256 == sha).Select(f => (f.Sha256, f.Format)).Single(), mode.ToString());
|
||||
if (mode == ConvertMode.Replace)
|
||||
{
|
||||
Assert.Contains(Loc.L("Archive.Log.Converted", title, 2), job.LogTail);
|
||||
Assert.Equal(2, frames.Count(f => f.Format == ImageFileFormat.Tiff));
|
||||
Assert.Equal(2, (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Single().Frames);
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.Contains(Loc.L("Archive.Log.ConvertedNew", title, 2), job.LogTail);
|
||||
Assert.Contains(Loc.L("Archive.Log.ConvertLeftOut", title, 1), job.LogTail);
|
||||
var made = Assert.NotNull(await fx.Db.Sequences.FindBySessionKeyAsync(fx.Archive.Id, MassConverter.SessionKey(job.Id, id)));
|
||||
Assert.True((await FramesAsync(fx, made)) is { Count: 2 } copies && copies.All(f => f.Format == ImageFileFormat.Tiff));
|
||||
Assert.True(frames.All(f => f.Format == ImageFileFormat.Jpeg));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -803,19 +893,16 @@ public sealed class ConvertTests(TestContext context)
|
||||
Assert.Equal((2, ConvertSkip.Unhashed), (plan.Frames, plan.Sequences.Single().Skipped.Single().Reason));
|
||||
// A verify then hashes it before the job runs, as ArchiveVerifier does: no new frames version.
|
||||
ManifestStore.WriteSequence(path, verified);
|
||||
var before = await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id);
|
||||
|
||||
var job = await RunAsync(fx, engine, plan, JobState.Failed);
|
||||
Assert.Equal(Loc.Plural("Archive.Error.ConvertKept", 1), job.Error);
|
||||
Assert.Contains(Loc.L("Archive.Log.ConvertChanged", sequence.DisplayTitle), job.LogTail);
|
||||
Assert.Equal(before, await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id));
|
||||
Assert.SequenceEqual(verified.Frames.Select(f => (f.Id, f.Sha256, f.File)), ManifestStore.ReadSequence(path).Frames.Select(f => (f.Id, f.Sha256, f.File)));
|
||||
Assert.Empty(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct));
|
||||
// The job converts the two photos the plan listed, and leaves the third as it is, as the dry run said.
|
||||
var job = await RunAsync(fx, engine, plan);
|
||||
Assert.Contains(Loc.L("Archive.Log.Converted", sequence.DisplayTitle, 2), job.LogTail);
|
||||
var frames = await FramesAsync(fx, id);
|
||||
Assert.SequenceEqual(verified.Frames.Select(f => f.Id), frames.Select(f => f.Id));
|
||||
Assert.Equal((verified.Frames[1].Sha256, ImageFileFormat.Jpeg), (frames[1].Sha256, frames[1].Format));
|
||||
Assert.True(frames[0].Format == ImageFileFormat.Dng && frames[2].Format == ImageFileFormat.Dng);
|
||||
Assert.Equal(2, (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Single().Frames);
|
||||
Assert.False(StagedAnything(fx));
|
||||
// A retry does not convert it either: the user plans again.
|
||||
await engine.ResumeAsync(job.Id, fx.Ct);
|
||||
await fx.WaitForAsync(job.Id, JobState.Failed);
|
||||
Assert.Empty(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -988,6 +1075,8 @@ public sealed class ConvertTests(TestContext context)
|
||||
|
||||
var failed = (await RunHereAsync(fx, plan, jobId, callbacks)).Sequences.Single();
|
||||
Assert.Equal(ConvertOutcome.Failed, failed.Outcome);
|
||||
// Why, in the catalog's words: the job log has no English exception text.
|
||||
Assert.Equal(Loc.L("Archive.Convert.NotPlaced", Loc.L("Archive.Convert.Unstaged", first.File)), failed.Error);
|
||||
Assert.Null(await fx.Db.Sequences.FindBySessionKeyAsync(fx.Archive.Id, MassConverter.SessionKey(jobId, id)));
|
||||
// The retry converts that photo again and makes the whole copy.
|
||||
var made = (await RunHereAsync(fx, plan, jobId)).Sequences.Single();
|
||||
@@ -1055,6 +1144,7 @@ public sealed class ConvertTests(TestContext context)
|
||||
var paused = Guid.CreateVersion7();
|
||||
var finished = Guid.CreateVersion7();
|
||||
var forgotten = Guid.CreateVersion7();
|
||||
var stray = Guid.CreateVersion7();
|
||||
foreach (var (id, state) in new[] { (paused, JobState.Paused), (finished, JobState.Done) })
|
||||
await fx.Db.Jobs.EnqueueAsync(new Job { Id = id, Kind = JobKind.Convert, State = state, Created = DateTimeOffset.UtcNow }, fx.Ct);
|
||||
string Staged(Guid job)
|
||||
@@ -1073,22 +1163,196 @@ public sealed class ConvertTests(TestContext context)
|
||||
var (pausedFile, pausedJournal) = (Staged(paused), Journal(paused));
|
||||
var (finishedFile, finishedJournal) = (Staged(finished), Journal(finished));
|
||||
var (forgottenFile, forgottenJournal) = (Staged(forgotten), Journal(forgotten));
|
||||
var strayFile = Staged(stray);
|
||||
|
||||
var dry = await fx.Service.Maintenance.RunAsync(fx.Archive, dryRun: true, 0, _ => ValueTask.CompletedTask, fx.Ct);
|
||||
Assert.SequenceEqual(new[] { finishedFile, finishedJournal, forgottenFile }.Select(fx.Paths.ToRelative).Order(), dry.TemporaryFiles.Order());
|
||||
Assert.SequenceEqual(new[] { finishedFile, finishedJournal, strayFile }.Select(fx.Paths.ToRelative).Order(), dry.TemporaryFiles.Order());
|
||||
await fx.Service.Maintenance.RunAsync(fx.Archive, dryRun: false, 0, _ => ValueTask.CompletedTask, fx.Ct);
|
||||
// A paused job's staged conversions stay however old; a finished job's go with its journal; a job this index does not
|
||||
// know (another host's, or forgotten by the history) loses staged files idle for a day, and keeps its journal a while.
|
||||
// A paused job's staged conversions stay however old; a finished job's go with its journal. A job this index does not
|
||||
// know (another host's on a shared archive, or forgotten by the history) may still resume where it is known: its
|
||||
// staged conversions stay as long as its journal; without a journal no resume can use them, and they go once idle.
|
||||
Assert.FileExists(pausedFile);
|
||||
Assert.FileExists(pausedJournal);
|
||||
Assert.False(Directory.Exists(Path.Combine(Staging(fx), MassConverter.StagingFolder(finished))));
|
||||
Assert.FileMissing(finishedJournal);
|
||||
Assert.False(Directory.Exists(Path.Combine(Staging(fx), MassConverter.StagingFolder(forgotten))));
|
||||
Assert.FileMissing(forgottenFile);
|
||||
Assert.FileExists(forgottenFile);
|
||||
Assert.FileExists(forgottenJournal);
|
||||
File.SetLastWriteTimeUtc(forgottenJournal, DateTime.UtcNow.AddDays(-CleanupSteps.DefaultHistoryDays - 1));
|
||||
Assert.False(Directory.Exists(Path.Combine(Staging(fx), MassConverter.StagingFolder(stray))));
|
||||
|
||||
// Its journal untouched for as long as the history keeps jobs, but a staged file written since: both stay.
|
||||
var longAgo = DateTime.UtcNow.AddDays(-CleanupSteps.DefaultHistoryDays - 1);
|
||||
File.SetLastWriteTimeUtc(forgottenJournal, longAgo);
|
||||
await fx.Service.Maintenance.RunAsync(fx.Archive, dryRun: false, 0, _ => ValueTask.CompletedTask, fx.Ct);
|
||||
Assert.FileExists(forgottenJournal);
|
||||
Assert.FileExists(forgottenFile);
|
||||
// Neither written for that long: they go together.
|
||||
File.SetLastWriteTimeUtc(forgottenFile, longAgo);
|
||||
await fx.Service.Maintenance.RunAsync(fx.Archive, dryRun: false, 0, _ => ValueTask.CompletedTask, fx.Ct);
|
||||
Assert.FileMissing(forgottenJournal);
|
||||
Assert.False(Directory.Exists(Path.Combine(Staging(fx), MassConverter.StagingFolder(forgotten))));
|
||||
Assert.FileExists(pausedJournal);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task APhotoAnotherProgramHoldsIsSaidSoAndNeverConvertedWithoutAPlanThatListsIt()
|
||||
{
|
||||
await using var fx = await FixtureAsync();
|
||||
var id = await UploadedAsync(fx, 3);
|
||||
var title = (await fx.Db.Sequences.GetAsync(id))!.DisplayTitle;
|
||||
var originals = await FramesAsync(fx, id);
|
||||
var held = fx.Paths.FromRelative(originals[1].RelativePath);
|
||||
|
||||
// A sync client holds it while the dry run is made: not missing, and not planned, with why.
|
||||
ConvertPlan plan;
|
||||
using (Unreadable(held)) plan = await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.Replace, id);
|
||||
var step = plan.Sequences.Single();
|
||||
Assert.Equal((2, ConvertSkip.Inaccessible, 1), (step.Frames.Count, step.Skipped.Single().Reason, step.Skipped.Single().Frames));
|
||||
Assert.DoesNotContain(originals[1].Id, step.Frames.Select(f => f.FrameId));
|
||||
|
||||
// Free again when the job runs: it converts the two photos the plan listed, not that one.
|
||||
var done = (await RunHereAsync(fx, plan, Guid.CreateVersion7())).Sequences.Single();
|
||||
Assert.Equal((ConvertOutcome.Converted, 2), (done.Outcome, done.Frames));
|
||||
var frames = await FramesAsync(fx, id);
|
||||
Assert.Equal((originals[1].Sha256, ImageFileFormat.Jpeg), (frames[1].Sha256, frames[1].Format));
|
||||
Assert.True(frames[0].Format == ImageFileFormat.Tiff && frames[2].Format == ImageFileFormat.Tiff);
|
||||
|
||||
// Held again while the job that converts it comes to it: left as it is, saying why, and the retry converts it once free.
|
||||
var rest = await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.Replace, id);
|
||||
Assert.Equal(1, rest.Frames);
|
||||
var jobId = Guid.CreateVersion7();
|
||||
var lines = new List<string>();
|
||||
ConvertSequenceResult left;
|
||||
using (Unreadable(held))
|
||||
left = (await RunHereAsync(fx, rest, jobId, Callbacks() with { Log = lines.Add })).Sequences.Single();
|
||||
Assert.Equal((ConvertOutcome.Blocked, Loc.L("Archive.Convert.PhotoHeld")), (left.Outcome, left.Error));
|
||||
Assert.SequenceEqual([Loc.L("Archive.Log.ConvertFailed", title, Loc.L("Archive.Convert.PhotoHeld"))], lines);
|
||||
Assert.Equal(ImageFileFormat.Jpeg, (await FramesAsync(fx, id))[1].Format);
|
||||
Assert.Equal(ConvertOutcome.Converted, (await RunHereAsync(fx, rest, jobId)).Sequences.Single().Outcome);
|
||||
Assert.True((await FramesAsync(fx, id)).All(f => f.Format == ImageFileFormat.Tiff));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Only a photo the job converts makes a sequence wait for its retry while another program holds it: one the plan left
|
||||
/// out being held does not hide that a photo confirmed is gone, which no retry can mend.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public async Task APhotoHeldThatTheJobDoesNotConvertDoesNotHideAChange()
|
||||
{
|
||||
await using var fx = await FixtureAsync();
|
||||
var id = await UploadedAsync(fx, 3);
|
||||
var originals = await FramesAsync(fx, id);
|
||||
var held = fx.Paths.FromRelative(originals[0].RelativePath);
|
||||
ConvertPlan plan;
|
||||
using (Unreadable(held)) plan = await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.Replace, id);
|
||||
Assert.Equal(2, plan.Frames);
|
||||
// A photo of the plan is deleted before the job comes to the sequence, and the one left out is held again then.
|
||||
var sequence = (await fx.Db.Sequences.GetAsync(id))!;
|
||||
var delete = await fx.Service.FrameTrash.PlanDeleteAsync(id, [originals[1].Id], sequence.FramesVersion, fx.Ct);
|
||||
await fx.Service.FrameTrash.DeleteAsync(delete, "alberto", null, fx.Ct);
|
||||
|
||||
ConvertSequenceResult left;
|
||||
using (Unreadable(held)) left = (await RunHereAsync(fx, plan, Guid.CreateVersion7())).Sequences.Single();
|
||||
Assert.Equal((ConvertOutcome.Changed, (string?)null), (left.Outcome, left.Error));
|
||||
Assert.True((await FramesAsync(fx, id)).All(f => f.Format == ImageFileFormat.Jpeg));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Before each photo of stage A, the space is checked for it and the photos after it that may convert at once with it:
|
||||
/// fewer near the end, so a job whose dry run had the space never stops short for photos that are not there.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public async Task TheLastPhotosToStartNeedOnlyTheirOwnSpace()
|
||||
{
|
||||
ConvertFramePlan[] todo = [.. new long[] { 10, 20, 30, 40 }.Select((bytes, i) => new ConvertFramePlan(Guid.NewGuid(), i, $"originals/{i}.JPG", ImageFileFormat.Jpeg, 1, bytes))];
|
||||
Assert.SequenceEqual([60L, 90, 70, 40], Enumerable.Range(0, todo.Length).Select(i => MassConverter.Ahead(todo, i, 3)));
|
||||
Assert.SequenceEqual([10L, 20, 30, 40], Enumerable.Range(0, todo.Length).Select(i => MassConverter.Ahead(todo, i, 1)));
|
||||
|
||||
long free = 1L << 50;
|
||||
await using var fx = await FixtureAsync(o => o with { FreeSpace = _ => free, Parallelism = () => 4 });
|
||||
var id = await UploadedAsync(fx, 1);
|
||||
// Exactly what the dry run asks for: four photos may convert at once, but there is one.
|
||||
free = ConvertPlanner.Required(ConvertPlanner.EstimateBytes(new ConvertOptions(ConvertTarget.Tiff16), 48, 32));
|
||||
var plan = await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.Replace, id);
|
||||
Assert.True(plan.Space.Enough);
|
||||
Assert.Equal(free, plan.Space.Required);
|
||||
|
||||
var done = (await RunHereAsync(fx, plan, Guid.CreateVersion7())).Sequences.Single();
|
||||
Assert.Equal((ConvertOutcome.Converted, 1), (done.Outcome, done.Frames));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ASecondConversionOfTheSameSequencesIsRefusedWithOrWithoutADryRun()
|
||||
{
|
||||
await using var fx = await FixtureAsync();
|
||||
var id = await UploadedAsync(fx, 2);
|
||||
var plan = await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.NewSequence, id);
|
||||
async Task Enqueue(ArchiveJobRequest request)
|
||||
{
|
||||
// Long enough for the other confirmation to check meanwhile, were it not held back.
|
||||
await Task.Delay(50, fx.Ct);
|
||||
await fx.Db.Jobs.EnqueueAsync(new Job
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Kind = request.Kind,
|
||||
TargetIds = request.Targets,
|
||||
ParametersJson = request.ParametersJson,
|
||||
State = JobState.Queued,
|
||||
Created = DateTimeOffset.UtcNow,
|
||||
}, fx.Ct);
|
||||
}
|
||||
async Task<bool> ConfirmAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await fx.Service.Converter.QueueAsync(fx.Archive, plan, Enqueue, fx.Ct);
|
||||
return true;
|
||||
}
|
||||
catch (ConversionQueuedException ex)
|
||||
{
|
||||
Assert.SequenceEqual([id], ex.SequenceIds);
|
||||
Assert.Equal(Loc.L("Archive.Convert.AlreadyQueued"), ex.Message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// The Library's dialog and the Archive manager's confirm the same plan at once: one job.
|
||||
var confirmed = await Task.WhenAll(ConfirmAsync(), ConfirmAsync());
|
||||
Assert.SequenceEqual([false, true], confirmed.Order());
|
||||
// And again later from that plan, made before the job was queued and never planned again.
|
||||
Assert.False(await ConfirmAsync());
|
||||
Assert.Count(1, (await fx.Db.Jobs.ListAsync(JobState.Queued, JobKind.Convert)).Items);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AConversionQueuedFirstHoldsItsSequencesFromADuplicateQueuedAfterIt()
|
||||
{
|
||||
await using var fx = await FixtureAsync();
|
||||
var id = await UploadedAsync(fx, 2);
|
||||
var plan = await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.NewSequence, id);
|
||||
// Queued twice anyway (an earlier build, two processes on one index): the copies are made once.
|
||||
var first = await QueuedAsync(fx, plan, DateTimeOffset.UtcNow.AddMinutes(-2));
|
||||
var second = await QueuedAsync(fx, plan, DateTimeOffset.UtcNow.AddMinutes(-1));
|
||||
|
||||
var held = (await fx.Service.Converter.RunAsync(fx.Archive, Parameters(fx, plan), second.Id, new ConvertRequester(null, null), Callbacks(), fx.Ct))
|
||||
.Sequences.Single();
|
||||
Assert.Equal(ConvertOutcome.Blocked, held.Outcome);
|
||||
Assert.Null(await fx.Db.Sequences.FindBySessionKeyAsync(fx.Archive.Id, MassConverter.SessionKey(second.Id, id)));
|
||||
// The one queued first is not held back by the one after it.
|
||||
var made = (await fx.Service.Converter.RunAsync(fx.Archive, Parameters(fx, plan), first.Id, new ConvertRequester(null, null), Callbacks(), fx.Ct))
|
||||
.Sequences.Single();
|
||||
Assert.Equal((ConvertOutcome.Created, 2), (made.Outcome, made.Frames));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AJobsParametersNameThePhotosItConverts()
|
||||
{
|
||||
Guid[] ids = [Guid.CreateVersion7(), Guid.CreateVersion7(), Guid.NewGuid()];
|
||||
var step = new ConvertSequence(Guid.NewGuid(), 3, "digest", ConvertSequence.EncodePhotos(ids));
|
||||
Assert.SequenceEqual(ids, step.PhotoIds()!);
|
||||
var json = JsonSerializer.Serialize(step, ArchiveJobJson.Default.ConvertSequence);
|
||||
Assert.SequenceEqual(ids, JsonSerializer.Deserialize(json, ArchiveJobJson.Default.ConvertSequence)!.PhotoIds()!);
|
||||
// A job an earlier build queued names none.
|
||||
Assert.Null(new ConvertSequence(Guid.NewGuid(), 3, "digest").PhotoIds());
|
||||
Assert.Empty(new ConvertSequence(Guid.NewGuid(), 3, "digest", ConvertSequence.EncodePhotos([])).PhotoIds()!);
|
||||
}
|
||||
}
|
||||
@@ -185,11 +185,16 @@ public sealed class ConvertTests(TestContext context)
|
||||
var skipped = plan.Steps.Single().Skipped.Single();
|
||||
Assert.Equal(("convert_on_pc", 2), (skipped.Reason, skipped.Photos));
|
||||
Assert.Equal(Loc.Get("Server.Convert.OnPc", italian), skipped.Message);
|
||||
// Into a new sequence, which holds the converted copies alone: the dry run says the copy lacks them.
|
||||
var copies = await DryRunAsync(admin, new ConvertRequest([id], false, "linear-dng", null, "new-sequence", DryRun: true));
|
||||
Assert.Equal((1, 2), (copies.Photos, copies.Skipped));
|
||||
var left = copies.Steps.Single().Skipped.Single();
|
||||
// Into a new sequence, which holds the converted copies alone: the dry run says the copy lacks them. Of a sequence
|
||||
// that converts nothing, no copy is made: its photos stay as they are.
|
||||
var lake = (await Uploads.UploadAsync(editor, Heif(9), "IMG_0009.HEIC", sessionKey: "lake")).SequenceId;
|
||||
await UntilIdleAsync(server);
|
||||
var copies = await DryRunAsync(admin, new ConvertRequest([id, lake], false, "linear-dng", null, "new-sequence", DryRun: true));
|
||||
Assert.Equal((1, 3), (copies.Photos, copies.Skipped));
|
||||
var left = copies.Steps.Single(s => s.SequenceId == id).Skipped.Single();
|
||||
Assert.Equal(("convert_on_pc", 2, Loc.Get("Server.Convert.OnPcNew", italian)), (left.Reason, left.Photos, left.Message));
|
||||
var stays = copies.Steps.Single(s => s.SequenceId == lake).Skipped.Single();
|
||||
Assert.Equal(("convert_on_pc", 1, Loc.Get("Server.Convert.OnPc", italian)), (stays.Reason, stays.Photos, stays.Message));
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -251,10 +256,11 @@ public sealed class ConvertTests(TestContext context)
|
||||
await UntilJobAsync(admin, job.Id, "done");
|
||||
Assert.True((await server.Database.Frames.ListBySequenceAsync(id)).All(f => f.Format == ImageFileFormat.Tiff), "converted");
|
||||
|
||||
// Converted: the next dry run is another plan, which says why nothing converts, in New sequence's words too.
|
||||
// Converted: the next dry run is another plan, which says why nothing converts; with New sequence too, which makes no
|
||||
// copy of a sequence that converts nothing, so its photos stay as they are.
|
||||
var done = await DryRunAsync(admin, request with { Mode = "new-sequence" });
|
||||
Assert.Equal((0, 5), (done.Photos, done.Skipped));
|
||||
Assert.Equal(Loc.Get("Archive.Convert.NotCopied.SameFormat", italian), done.Steps.Single().Skipped.Single().Message);
|
||||
Assert.Equal(Loc.Get("Archive.Convert.Skipped.SameFormat", italian), done.Steps.Single().Skipped.Single().Message);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -301,23 +307,140 @@ public sealed class ConvertTests(TestContext context)
|
||||
Assert.True((await server.Database.Frames.ListBySequenceAsync(id)).All(f => f.Format == ImageFileFormat.Dng), "converted");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AConfirmationConvertsThePhotosItsDryRunShowedWhateverChangedOnDiskSince()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var admin = await server.AdminAsync();
|
||||
Guid id = default;
|
||||
for (var i = 0; i < 3; i++) id = (await Uploads.UploadAsync(editor, Photo(i), $"IMG_{i + 1:0000}.JPG", sessionKey: "roof")).SequenceId;
|
||||
await UntilIdleAsync(server);
|
||||
var before = await server.Database.Frames.ListBySequenceAsync(id);
|
||||
// Gone on disk alone while the dry run is made (a sync client moving it): the dry run says it stays as it is.
|
||||
var file = Path.Combine(server.Options.ArchivePath, before[0].RelativePath);
|
||||
var bytes = await File.ReadAllBytesAsync(file);
|
||||
File.Delete(file);
|
||||
var request = new ConvertRequest([id], false, "tiff16", null, "replace", DryRun: true);
|
||||
var plan = await DryRunAsync(admin, request);
|
||||
Assert.Equal((2, 1, "missing"), (plan.Photos, plan.Skipped, plan.Steps.Single().Skipped.Single().Reason));
|
||||
|
||||
// Back before the confirmation, which the index cannot tell: the plan kept is confirmed, and its job converts the two
|
||||
// photos it showed, not the third.
|
||||
await File.WriteAllBytesAsync(file, bytes);
|
||||
JobDto job;
|
||||
using (var applied = await admin.PostAsJsonAsync(Url, request with { DryRun = false, Fingerprint = plan.Fingerprint }, ProtocolJson.Default.ConvertRequest))
|
||||
{
|
||||
await applied.ExpectAsync(HttpStatusCode.Accepted);
|
||||
job = await applied.ReadAsync(ProtocolJson.Default.JobDto);
|
||||
}
|
||||
await UntilJobAsync(admin, job.Id, "done");
|
||||
var after = await server.Database.Frames.ListBySequenceAsync(id);
|
||||
Assert.Equal((before[0].Sha256, ImageFileFormat.Jpeg), (after[0].Sha256, after[0].Format));
|
||||
Assert.True(after[1].Format == ImageFileFormat.Tiff && after[2].Format == ImageFileFormat.Tiff, "converted");
|
||||
using var trash = await admin.GetAsync("/api/v1/archive/trash");
|
||||
Assert.Contains("replaced", await trash.Content.ReadAsStringAsync());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ADryRunAndItsConfirmationSeeTheJobsAsTheyAreNow()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var admin = await server.AdminAsync();
|
||||
var plans = server.Services.GetRequiredService<PlanCache>();
|
||||
Guid id = default;
|
||||
for (var i = 0; i < 2; i++) id = (await Uploads.UploadAsync(editor, Photo(i), $"IMG_{i + 1:0000}.JPG", sessionKey: "roof")).SequenceId;
|
||||
await UntilIdleAsync(server);
|
||||
var request = new ConvertRequest([id], false, "tiff16", null, "replace", DryRun: true);
|
||||
Job Held(JobKind kind) => new()
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Kind = kind,
|
||||
TargetIds = [id],
|
||||
State = JobState.Paused,
|
||||
Created = DateTimeOffset.UtcNow,
|
||||
};
|
||||
|
||||
// A paused pass holds the sequence: busy.
|
||||
var thumbs = Held(JobKind.Thumbs);
|
||||
await server.Database.Jobs.EnqueueAsync(thumbs);
|
||||
var busy = await DryRunAsync(admin, request);
|
||||
Assert.Equal((0, "busy"), (busy.Photos, busy.Steps.Single().Blocked.Single().Reason));
|
||||
// It ends: the plan kept shows the sequence free at once, not minutes later.
|
||||
await server.Database.Jobs.SetStateAsync(thumbs.Id, JobState.Done);
|
||||
var free = await DryRunAsync(admin, request);
|
||||
Assert.Equal((2, 0), (free.Photos, free.Steps.Single().Blocked.Count));
|
||||
Assert.Equal(1, plans.Count);
|
||||
|
||||
// Another tab queued a conversion of it since: the confirmation of this dry run is refused with the plan now.
|
||||
await server.Database.Jobs.EnqueueAsync(Held(JobKind.Convert));
|
||||
using (var refused = await admin.PostAsJsonAsync(Url, request with { DryRun = false, Fingerprint = free.Fingerprint }, ProtocolJson.Default.ConvertRequest))
|
||||
Assert.Equal(busy.Fingerprint, (await refused.ExpectErrorAsync(HttpStatusCode.Conflict, "plan_changed")).Details);
|
||||
Assert.Empty((await server.Database.Jobs.ListAsync(JobState.Queued, JobKind.Convert)).Items);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AConfirmationTakesOnlyThePlanKeptAndQueuesOneJob()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var admin = await server.AdminAsync();
|
||||
var plans = server.Services.GetRequiredService<PlanCache>();
|
||||
Guid id = default;
|
||||
for (var i = 0; i < 2; i++) id = (await Uploads.UploadAsync(editor, Photo(i), $"IMG_{i + 1:0000}.JPG", sessionKey: "roof")).SequenceId;
|
||||
await UntilIdleAsync(server);
|
||||
var archive = (await server.Database.Archives.ListAsync()).Single().Id;
|
||||
var request = new ConvertRequest([id], false, "tiff16", null, "new-sequence", DryRun: true);
|
||||
var plan = await DryRunAsync(admin, request);
|
||||
var apply = request with { DryRun = false, Fingerprint = plan.Fingerprint };
|
||||
|
||||
// Let go since (past its lifetime): the confirmation does not plan inside its own request; the panel asks the dry run again.
|
||||
plans.Forget(ConvertPlanKey.Of(archive, await server.Database.Sequences.GetConvertStampAsync(archive, [id]), [id],
|
||||
new Chronos.Core.Conversion.ConvertOptions(Chronos.Core.Conversion.ConvertTarget.Tiff16)));
|
||||
using (var dropped = await admin.PostAsJsonAsync(Url, apply, ProtocolJson.Default.ConvertRequest))
|
||||
await dropped.ExpectErrorAsync(HttpStatusCode.ServiceUnavailable, "plan_dropped");
|
||||
Assert.Equal(0, plans.Count);
|
||||
Assert.Equal(plan.Fingerprint, (await DryRunAsync(admin, request)).Fingerprint);
|
||||
|
||||
// Two tabs confirm it at once: one job, one new sequence.
|
||||
var answers = await Task.WhenAll(admin.PostAsJsonAsync(Url, apply, ProtocolJson.Default.ConvertRequest),
|
||||
admin.PostAsJsonAsync(Url, apply, ProtocolJson.Default.ConvertRequest));
|
||||
try
|
||||
{
|
||||
Assert.SequenceEqual([HttpStatusCode.Accepted], answers.Select(a => a.StatusCode).Where(s => s == HttpStatusCode.Accepted));
|
||||
Assert.True(answers.Any(a => a.StatusCode is HttpStatusCode.Conflict or HttpStatusCode.ServiceUnavailable), "the other is refused");
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var answer in answers) answer.Dispose();
|
||||
}
|
||||
var jobs = (await server.Database.Jobs.ListAsync(null, JobKind.Convert)).Items;
|
||||
Assert.Count(1, jobs);
|
||||
await UntilJobAsync(admin, jobs[0].Id, "done");
|
||||
Assert.Equal(2, (await server.Database.Sequences.ListLocationsAsync(archive)).Count);
|
||||
}
|
||||
|
||||
private static async Task<ConvertPlanDto> DryRunAsync(HttpClient client, ConvertRequest request)
|
||||
{
|
||||
using var response = await client.PostAsJsonAsync(Url, request with { DryRun = true }, ProtocolJson.Default.ConvertRequest);
|
||||
return await response.ReadAsync(ProtocolJson.Default.ConvertPlanDto);
|
||||
}
|
||||
|
||||
/// <summary>Every reason a photo stays as it is has its wire name and its sentence in the catalog (en and it).</summary>
|
||||
/// <summary>Every reason a photo stays as it is has its wire name and its sentences in the catalog (en and it), in either mode's words.</summary>
|
||||
[Test]
|
||||
public void EverySkipReasonHasItsWireNameAndSentence()
|
||||
{
|
||||
Assert.SequenceEqual(
|
||||
["same_format", "convert_on_pc", "convert_on_pc", "undecodable", "missing", "unhashed", "eight_bit", "color_profile", "too_large"],
|
||||
["same_format", "convert_on_pc", "convert_on_pc", "undecodable", "missing", "unhashed", "eight_bit", "color_profile", "too_large", "inaccessible"],
|
||||
Enum.GetValues<Chronos.Core.Conversion.ConvertSkip>().Select(Chronos.Server.Api.ArchiveEndpoints.Wire));
|
||||
foreach (var reason in Enum.GetValues<Chronos.Core.Conversion.ConvertSkip>())
|
||||
{
|
||||
foreach (var culture in (string[])["en", "it"])
|
||||
Assert.NotNull(Chronos.Core.Localization.Loc.Get("Archive.Convert.Skipped." + reason, System.Globalization.CultureInfo.GetCultureInfo(culture)));
|
||||
{
|
||||
foreach (var words in (string[])["Skipped", "NotCopied"])
|
||||
Assert.NotNull(Loc.Get($"Archive.Convert.{words}.{reason}", CultureInfo.GetCultureInfo(culture)), $"{words}.{reason} {culture}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -100,6 +100,38 @@ public sealed class PlanCacheTests
|
||||
Assert.Equal(3 + PlanCache.Capacity, made);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AConfirmationTakesOnlyAPlanKeptWithinItsLifetime()
|
||||
{
|
||||
var clock = new SteppedTimeProvider();
|
||||
using var plans = new PlanCache(clock);
|
||||
var archive = Guid.NewGuid();
|
||||
var key = ConvertPlanKey.Of(archive, "stamp", null, new ConvertOptions(ConvertTarget.LinearDng));
|
||||
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var made = new ConvertPlan(archive, new ConvertOptions(ConvertTarget.LinearDng), ConvertMode.Replace, [], new ConvertSpace(0, null));
|
||||
async Task<ConvertPlan> Plan(CancellationToken stop)
|
||||
{
|
||||
await release.Task.WaitAsync(stop);
|
||||
return made;
|
||||
}
|
||||
|
||||
// Never asked, then still being made: nothing to confirm, and nothing is planned for the asking.
|
||||
Assert.Null(plans.Kept(key));
|
||||
var making = plans.GetOrPlanAsync(key, Plan);
|
||||
Assert.Null(plans.Kept(key));
|
||||
release.SetResult();
|
||||
await making;
|
||||
Assert.True(ReferenceEquals(made, await plans.Kept(key)!), "kept");
|
||||
// Past its lifetime: let go, whatever its timer.
|
||||
clock.Advance(PlanCache.Lifetime);
|
||||
Assert.Null(plans.Kept(key));
|
||||
Assert.Equal(0, plans.Count);
|
||||
// A refusal kept is a refusal for the confirmation too.
|
||||
var unknown = ConvertPlanKey.Of(archive, "stamp", [Guid.NewGuid()], new ConvertOptions(ConvertTarget.LinearDng));
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => plans.GetOrPlanAsync(unknown, _ => throw new ArgumentException("Not in the archive.")));
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => plans.Kept(unknown)!);
|
||||
}
|
||||
|
||||
/// <summary>Waits until <paramref name="condition"/> holds.</summary>
|
||||
private static async Task EventuallyAsync(Func<bool> condition, [System.Runtime.CompilerServices.CallerArgumentExpression(nameof(condition))] string? expression = null)
|
||||
{
|
||||
|
||||
@@ -71,6 +71,21 @@ public sealed partial class AdminConvertTests(TestContext context)
|
||||
Assert.Contains(@"const PREVIEW_MODE = ""replace"";", dialog);
|
||||
Assert.Contains(@"t(copies ? ""Admin.Convert.TotalsNew"" : ""Admin.Convert.Totals""", dialog);
|
||||
Assert.Contains(@"plural(""Admin.Convert.ConfirmNewNotCopied"", notCopied)", dialog);
|
||||
// Only the sequences copied lack photos (one that converts nothing gets no copy), counted in the totals, the
|
||||
// confirmation and each of its lines.
|
||||
Assert.Contains("formatNumber(copies ? leftOut(converting(plan.steps)) : plan.skipped)", dialog);
|
||||
Assert.Contains("const notCopied = leftOut(going);", dialog);
|
||||
Assert.Contains(@"t(""Admin.Convert.PlanItemNotCopied"", item, plural(""Admin.Convert.NotCopiedCount"", left))", dialog);
|
||||
// The server confirms only the plan it keeps: Apply asks the dry run first (the totals saying how long it takes when
|
||||
// it is made again), confirms the same fingerprint, shows a different one, and asks again once for a plan let go.
|
||||
Assert.Contains("now = await waiting(() => dryRun(body, shownPlan.key));", dialog);
|
||||
Assert.Contains("if (now.fingerprint !== shownPlan.fingerprint) {", dialog);
|
||||
Assert.Contains(@"if (err?.code === ""plan_dropped"" && attempt < DROPPED_CONFIRMS && dialog.open) continue;", dialog);
|
||||
// Asking that dry run sends nothing to convert: the fields and Apply wait, Close and Esc stay; only the confirmation
|
||||
// itself holds the dialog open.
|
||||
Assert.Contains("applyButton.disabled = busy || checking || !current || reason !== null;", dialog);
|
||||
Assert.Contains("closeButton.disabled = busy;", dialog);
|
||||
Assert.Contains("if (busy) e.preventDefault();", dialog);
|
||||
// A dry run the server is still making is asked again (a proxy cut the request off, or the server let the plan go)
|
||||
// while the totals say how long it takes; a confirmation the server let go plans again, one that changed says so,
|
||||
// and one with no answer is not sent again (its job may be queued).
|
||||
@@ -166,13 +181,14 @@ public sealed partial class AdminConvertTests(TestContext context)
|
||||
Assert.Equal(("same_format", 2), (skipped.GetProperty("reason").GetString(), skipped.GetProperty("photos").GetInt32()));
|
||||
Assert.Equal(Loc.Get("Archive.Convert.Skipped.SameFormat", italian), skipped.GetProperty("message").GetString());
|
||||
}
|
||||
// Into a new sequence, the same photos are not copied into it, and the table says so.
|
||||
// Into a new sequence: none is made of a sequence that converts nothing, so its photos stay as they are, and the table
|
||||
// says so.
|
||||
using (var same = await browser.SendAsync(HttpMethod.Post, Url, Body("jpeg", "90", "new-sequence", "\"dryRun\":true")))
|
||||
{
|
||||
using var plan = JsonDocument.Parse(await same.Content.ReadAsStringAsync());
|
||||
var skipped = plan.RootElement.GetProperty("steps")[0].GetProperty("skipped").EnumerateArray().Single();
|
||||
Assert.Equal(("same_format", 2), (skipped.GetProperty("reason").GetString(), skipped.GetProperty("photos").GetInt32()));
|
||||
Assert.Equal(Loc.Get("Archive.Convert.NotCopied.SameFormat", italian), skipped.GetProperty("message").GetString());
|
||||
Assert.Equal(Loc.Get("Archive.Convert.Skipped.SameFormat", italian), skipped.GetProperty("message").GetString());
|
||||
}
|
||||
// A plan that no longer matches is refused with the one there is now: the dialog plans again.
|
||||
using (var stale = await browser.SendAsync(HttpMethod.Post, Url, Body("linear-dng", "null", "replace", $"\"dryRun\":false,\"fingerprint\":\"{new string('0', 64)}\"")))
|
||||
|
||||
Reference in new issue
Block a user