fix(convert): reserve the photos still writing, keep photo ids out of the job row, never copy a source twice
Stage A's space guard reserved, before each photo, only that photo and the ones after it, so at the end of a sequence it counted a single photo while up to twice the parallelism were still converting: a volume filling meanwhile could go into the reserve. It now reserves the photo and every photo started whose converted file has not landed yet (a file lands whole, by a rename, before it is verified), so nothing in flight is missed and nothing landed is counted twice, at the end of a sequence as anywhere. The confirmed photo ids (about 21 MB for a million photos) lived in the job's parameters, read by every dry run's busy check, by each sequence turn of the conversion and by the job lists. They are now written whole, under a job id chosen before the job is queued, into convert-<job>.photos beside the journal, and go with it; the row keeps each sequence's digest, so the job still converts exactly the photos confirmed (without the file, the whole plan made again must match). The busy check reads only ids, kinds and targets (and a verify's parameters), never the asking job's row; a conversion's turn reads only its creation time; the server's job list and dashboard and the engine's queue peeks read jobs without parameters. A retried New sequence conversion could make a second copy. The journal now names the copy as soon as its photos are filed; a retry finishes that copy whatever changed in the source since, never remakes one deleted since, and needs no space again for what it holds; and a source another conversion copied in the same format after this one was confirmed is done with, with no copy made (new outcome Superseded, with its job log line). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b471a33bfc
commit
8ea25228eb
14 files changed
+966
-201
No files matched your search
@@ -76,18 +76,30 @@ public sealed class ConvertTests(TestContext context)
|
||||
return ValueTask.CompletedTask;
|
||||
});
|
||||
|
||||
/// <summary>The conversion job <paramref name="jobId"/> of <paramref name="plan"/>, run here as its handler runs it.</summary>
|
||||
private static Task<ConvertResult> RunHereAsync(ArchiveFixture fx, ConvertPlan plan, Guid jobId, ConvertCallbacks? callbacks = null) =>
|
||||
fx.Service.Converter.RunAsync(fx.Archive, Parameters(fx, plan), jobId, new ConvertRequester(null, null), callbacks ?? Callbacks(), fx.Ct);
|
||||
/// <summary>
|
||||
/// The conversion job <paramref name="jobId"/> of <paramref name="plan"/>, run here as its handler runs it, with the photos
|
||||
/// confirmed written beside its journal as <see cref="MassConverter.QueueAsync"/> writes them (once: a run again of the
|
||||
/// same job finds them), and <paramref name="confirmed"/> as the time it was queued.
|
||||
/// </summary>
|
||||
private static Task<ConvertResult> RunHereAsync(ArchiveFixture fx, ConvertPlan plan, Guid jobId, ConvertCallbacks? callbacks = null, DateTimeOffset? confirmed = null)
|
||||
{
|
||||
if (!File.Exists(ConfirmedPhotos.PathFor(fx.Paths, jobId))) Assert.True(ConfirmedPhotos.TryWrite(fx.Paths, jobId, plan));
|
||||
return fx.Service.Converter.RunAsync(fx.Archive, Parameters(fx, plan), jobId, new ConvertRequester(null, null, confirmed), callbacks ?? Callbacks(), fx.Ct);
|
||||
}
|
||||
|
||||
private static string StagingOf(ArchiveFixture fx, Guid job, Guid sequence) => Path.Combine(Staging(fx), $"convert-{job:N}", $"{sequence:N}");
|
||||
|
||||
private static async Task<Job> RunAsync(ArchiveFixture fx, JobEngine engine, ConvertPlan plan, JobState state = JobState.Done)
|
||||
/// <summary>The job of <paramref name="plan"/>, queued as the Library, the Archive manager and the panel queue it (<see cref="MassConverter.QueueAsync"/>).</summary>
|
||||
private static async Task<Job> QueueAsync(ArchiveFixture fx, JobEngine engine, ConvertPlan plan, Guid? createdBy = null)
|
||||
{
|
||||
var job = await engine.EnqueueAsync(ArchiveJobs.Convert(fx.Archive, plan), cancellationToken: fx.Ct);
|
||||
return await fx.WaitForAsync(job.Id, state, (int)TestTiming.Budget(60));
|
||||
Job? job = null;
|
||||
await fx.Service.Converter.QueueAsync(fx.Archive, plan, async r => job = await engine.EnqueueAsync(r, createdBy, fx.Ct), fx.Ct);
|
||||
return Assert.NotNull(job);
|
||||
}
|
||||
|
||||
private static async Task<Job> RunAsync(ArchiveFixture fx, JobEngine engine, ConvertPlan plan, JobState state = JobState.Done) =>
|
||||
await fx.WaitForAsync((await QueueAsync(fx, engine, plan)).Id, state, (int)TestTiming.Budget(60));
|
||||
|
||||
private static SequenceManifest Sidecar(ArchiveFixture fx, Sequence sequence) => ManifestStore.ReadSequence(fx.Paths.Sequence(sequence.Folder).ManifestPath);
|
||||
|
||||
private static string Sha(string path) => Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(path)));
|
||||
@@ -721,9 +733,16 @@ public sealed class ConvertTests(TestContext context)
|
||||
File.AppendAllText(ConvertJournal.PinsPathFor(fx.Paths, journal.JobId), "{\"sequence\":");
|
||||
var pinned = Assert.NotNull(read.Pins(fx.Paths).Of(first));
|
||||
Assert.Equal((5, photo, "bb"), (pinned.FramesVersion, pinned.Frames.Single().Id, pinned.Frames.Single().Sha256));
|
||||
// Its files and its staging folder are known by their names.
|
||||
Assert.SequenceEqual([journal.JobId, journal.JobId, journal.JobId],
|
||||
// Its files (the photos confirmed among them) and its staging folder are known by their names.
|
||||
Assert.SequenceEqual([journal.JobId, journal.JobId, journal.JobId, journal.JobId],
|
||||
ConvertJournal.Files(fx.Paths, journal.JobId).Select(p => ConvertJournal.JobOf(Path.GetFileName(p))));
|
||||
Assert.Contains(ConfirmedPhotos.PathFor(fx.Paths, journal.JobId), ConvertJournal.Files(fx.Paths, journal.JobId));
|
||||
// The copy a New sequence conversion made stays named whatever the sequence comes to after it.
|
||||
var copy = Guid.NewGuid();
|
||||
journal.Made(harbour, copy);
|
||||
journal.Note(new ConvertSequenceResult(harbour, "Harbour", ConvertOutcome.Failed, 0, Error: "no"));
|
||||
journal.Write(fx.Paths);
|
||||
Assert.Equal(copy, ConvertJournal.Read(fx.Paths, journal.JobId)!.Of(harbour)!.NewSequenceId);
|
||||
Assert.Equal(journal.JobId, ConvertJournal.JobOf(MassConverter.StagingFolder(journal.JobId)));
|
||||
Assert.Null(ConvertJournal.JobOf("convert-test"));
|
||||
Assert.Null(ConvertJournal.JobOf("rename-" + journal.JobId.ToString("N") + ".json"));
|
||||
@@ -1257,16 +1276,85 @@ public sealed class ConvertTests(TestContext context)
|
||||
}
|
||||
|
||||
/// <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.
|
||||
/// Before each photo of stage A, the space is checked for it and for every photo handed to the work before it whose file
|
||||
/// has not landed yet: a converted file lands whole, by a rename, before its photo's work verifies it, so the free space
|
||||
/// measured holds the files landed and none of what the photos still converting will write. Near the end of a sequence
|
||||
/// those are as many as anywhere else, never fewer; photos that are not there to start are never counted.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public async Task TheLastPhotosToStartNeedOnlyTheirOwnSpace()
|
||||
public void APhotoStartsOnlyWithTheSpaceForItAndThePhotosStillWriting()
|
||||
{
|
||||
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)));
|
||||
const long photo = 100_000_000;
|
||||
var staging = context.CreateTempDirectory("staging");
|
||||
string Target(int i) => Path.Combine(staging, $"{i:00}.tif");
|
||||
// The volume: what it had, less the files landed so far (those still converting are not on it yet).
|
||||
var landed = 0L;
|
||||
var volume = ConvertPlanner.Required(3 * photo);
|
||||
var space = new MassConverter.SpaceWatch(() => volume - landed);
|
||||
void Land(int i)
|
||||
{
|
||||
File.WriteAllBytes(Target(i), [1]);
|
||||
landed += photo;
|
||||
}
|
||||
|
||||
// The last photos of a sequence, four converting at once: none of the three started has landed, so the fourth, the
|
||||
// last one, needs the space of all four, not its own alone.
|
||||
for (var i = 0; i < 3; i++) Assert.Null(space.Start(photo, Target(i)));
|
||||
Assert.Equal(3 * photo, space.Writing);
|
||||
var refused = Assert.NotNull(space.Start(photo, Target(3)));
|
||||
Assert.True(refused.StartsWith("The conversion needs", StringComparison.Ordinal), refused);
|
||||
Assert.Equal(3 * photo, space.Writing);
|
||||
|
||||
// One lands, and its work verifies it: the volume holds it, so the watch counts it no more (never twice). The last
|
||||
// photo still waits: the two others and it need more than what is left.
|
||||
Land(0);
|
||||
Assert.Equal(2 * photo, space.Writing);
|
||||
Assert.NotNull(space.Start(photo, Target(3)));
|
||||
space.Ended(Target(0));
|
||||
Land(1);
|
||||
Land(2);
|
||||
Assert.Equal(0, space.Writing);
|
||||
space.Ended(Target(1));
|
||||
space.Ended(Target(2));
|
||||
// All three landed: what is left, with the margin and the reserve, cannot take a fourth; the reserve is whole.
|
||||
Assert.NotNull(space.Start(photo, Target(3)));
|
||||
Assert.True(volume - landed >= ConvertPlanner.SpaceReserve);
|
||||
|
||||
// Room for one more: it starts, and a photo whose work ends without a file (it failed) counts no more either.
|
||||
volume = landed + ConvertPlanner.Required(photo);
|
||||
Assert.Null(space.Start(photo, Target(3)));
|
||||
Assert.NotNull(space.Start(photo, Target(4)));
|
||||
space.Ended(Target(3));
|
||||
Assert.Null(space.Start(photo, Target(4)));
|
||||
space.Ended(Target(4));
|
||||
|
||||
// A file a crash left where a photo converts is not its file: the photo counts until the new one replaces it.
|
||||
File.WriteAllBytes(Target(5), [1, 2, 3]);
|
||||
File.SetLastWriteTimeUtc(Target(5), new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc));
|
||||
Assert.Null(space.Start(photo, Target(5)));
|
||||
Assert.Equal(photo, space.Writing);
|
||||
File.WriteAllBytes(Target(5), new byte[10]);
|
||||
Assert.Equal(0, space.Writing);
|
||||
|
||||
// Files staged over their estimate scale what is still writing too.
|
||||
var scaled = new MassConverter.SpaceWatch(() => ConvertPlanner.Required(3 * photo));
|
||||
scaled.Staged(2 * photo, photo);
|
||||
Assert.Equal(2, scaled.Ratio);
|
||||
Assert.Null(scaled.Start(photo, Target(6)));
|
||||
Assert.NotNull(scaled.Start(photo, Target(7)));
|
||||
scaled.Ended(Target(6));
|
||||
Assert.Null(scaled.Start(photo, Target(7)));
|
||||
// A volume that cannot be measured stops nothing.
|
||||
Assert.Null(new MassConverter.SpaceWatch(() => null).Start(long.MaxValue / 4, Target(8)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A job whose dry run had the space never stops short at the end of a sequence: the last photo to start counts only
|
||||
/// the photos that started and have not written yet, none that are not there.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public async Task TheLastPhotosToStartNeedOnlyTheSpaceOfThePhotosStillWriting()
|
||||
{
|
||||
long free = 1L << 50;
|
||||
await using var fx = await FixtureAsync(o => o with { FreeSpace = _ => free, Parallelism = () => 4 });
|
||||
var id = await UploadedAsync(fx, 1);
|
||||
@@ -1280,6 +1368,41 @@ public sealed class ConvertTests(TestContext context)
|
||||
Assert.Equal((ConvertOutcome.Converted, 1), (done.Outcome, done.Frames));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A sequence that fits converts to its last photo, four at once, while its converted files take the volume as they land:
|
||||
/// at the end the photos still writing are counted, those landed (verified meanwhile) are in the free space measured, and
|
||||
/// none is counted twice.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public async Task ASequenceThatFitsConvertsToItsLastPhotoWhileItsFilesFillTheVolume()
|
||||
{
|
||||
long volume = 1L << 50;
|
||||
string? staging = null;
|
||||
// The volume as the converted files land on it; an atomic write's temporary file is left out, being there only while
|
||||
// its photo still counts.
|
||||
long Landed() => staging is not null && Directory.Exists(staging)
|
||||
? Directory.EnumerateFiles(staging).Where(f => !Path.GetFileName(f).StartsWith('.')).Sum(f => new FileInfo(f).Length)
|
||||
: 0;
|
||||
await using var fx = await FixtureAsync(o => o with { FreeSpace = _ => volume - Landed(), Parallelism = () => 4 });
|
||||
var id = await UploadedAsync(fx, 12);
|
||||
var plan = await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.Replace, id);
|
||||
// What the twelve converted files take, each converted beforehand as the job converts it.
|
||||
var sequence = (await fx.Db.Sequences.GetAsync(id))!;
|
||||
var folder = fx.Paths.Sequence(sequence.Folder);
|
||||
var manifest = Sidecar(fx, sequence);
|
||||
var sizes = context.CreateTempDirectory("sizes");
|
||||
var converted = manifest.Frames.Sum(f => FrameConverter.Convert(new ConvertSource(folder.File(f.File), f, manifest.Camera, manifest.Lens),
|
||||
new ConvertOptions(ConvertTarget.Tiff16), DecoderFactory.CreateServer(), Path.Combine(sizes, f.Id.ToString("N") + ".tif"), cancellationToken: fx.Ct).Size);
|
||||
// Just the space they need with the margin and the reserve, and never less than the dry run asks.
|
||||
volume = ConvertPlanner.Required(Math.Max(converted, plan.BytesAfter));
|
||||
var jobId = Guid.CreateVersion7();
|
||||
staging = StagingOf(fx, jobId, id);
|
||||
|
||||
var done = (await RunHereAsync(fx, plan, jobId)).Sequences.Single();
|
||||
Assert.Equal((ConvertOutcome.Converted, 12), (done.Outcome, done.Frames));
|
||||
Assert.True((await FramesAsync(fx, id)).All(f => f.Format == ImageFileFormat.Tiff));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ASecondConversionOfTheSameSequencesIsRefusedWithOrWithoutADryRun()
|
||||
{
|
||||
@@ -1333,26 +1456,239 @@ public sealed class ConvertTests(TestContext context)
|
||||
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))
|
||||
var held = (await fx.Service.Converter.RunAsync(fx.Archive, Parameters(fx, plan), second.Id, new ConvertRequester(null, null, second.Created), 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))
|
||||
var made = (await fx.Service.Converter.RunAsync(fx.Archive, Parameters(fx, plan), first.Id, new ConvertRequester(null, null, first.Created), Callbacks(), fx.Ct))
|
||||
.Sequences.Single();
|
||||
Assert.Equal((ConvertOutcome.Created, 2), (made.Outcome, made.Frames));
|
||||
await fx.Db.Jobs.SetStateAsync(first.Id, JobState.Done, null, fx.Ct);
|
||||
// The duplicate, tried again once the first is done, finds the copy made since it was queued: it makes no second one.
|
||||
var again = (await fx.Service.Converter.RunAsync(fx.Archive, Parameters(fx, plan), second.Id, new ConvertRequester(null, null, second.Created), Callbacks(), fx.Ct))
|
||||
.Sequences.Single();
|
||||
Assert.Equal(ConvertOutcome.Superseded, again.Outcome);
|
||||
Assert.Null(await fx.Db.Sequences.FindBySessionKeyAsync(fx.Archive.Id, MassConverter.SessionKey(second.Id, id)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A job's row names no photo, so it stays as small as the number of sequences however many photos convert: the photos
|
||||
/// confirmed are written whole beside the journal, under the job's id, before it is queued, and go with the journal.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public async Task TheJobRowNamesNoPhotoAndThePhotosConfirmedWaitBesideItsJournal()
|
||||
{
|
||||
await using var fx = await FixtureAsync();
|
||||
var id = await UploadedAsync(fx, 3);
|
||||
var plan = await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.Replace, id);
|
||||
var frames = plan.Sequences.Single().Frames.Select(f => f.FrameId).ToList();
|
||||
// Queued and not run yet: an engine that is not started.
|
||||
await using var idle = new JobEngine(fx.Db, []);
|
||||
Job? job = null;
|
||||
await fx.Service.Converter.QueueAsync(fx.Archive, plan, async r =>
|
||||
{
|
||||
Assert.FileExists(ConfirmedPhotos.PathFor(fx.Paths, r.Id!.Value));
|
||||
job = await idle.EnqueueAsync(r, cancellationToken: fx.Ct);
|
||||
}, fx.Ct);
|
||||
var queued = Assert.NotNull(await fx.Db.Jobs.GetAsync(job!.Id, fx.Ct));
|
||||
Assert.SequenceEqual(frames, ConfirmedPhotos.Read(fx.Paths, queued.Id).Of(id)!);
|
||||
Assert.Null(ConfirmedPhotos.Read(fx.Paths, queued.Id).Of(Guid.NewGuid()));
|
||||
foreach (var frame in frames)
|
||||
{
|
||||
Assert.False(queued.ParametersJson!.Contains(frame.ToString(), StringComparison.OrdinalIgnoreCase), queued.ParametersJson);
|
||||
Assert.False(queued.ParametersJson!.Contains(ConfirmedPhotos.Encode([frame])[..20], StringComparison.Ordinal), queued.ParametersJson);
|
||||
}
|
||||
Assert.Equal(plan.Sequences.Single().Digest(), Parameters(fx, plan).Sequences.Single().Frames);
|
||||
// Lists of jobs read none of their parameters.
|
||||
Assert.Null((await fx.Db.Jobs.ListBriefAsync(JobState.Queued, JobKind.Convert, 10, null, fx.Ct)).Items.Single().ParametersJson);
|
||||
|
||||
// A confirmation the queue refuses leaves nothing behind.
|
||||
var other = await UploadedAsync(fx, 1, "upload-2", seed: 300);
|
||||
var refused = await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.Replace, other);
|
||||
Guid? named = null;
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => fx.Service.Converter.QueueAsync(fx.Archive, refused, r =>
|
||||
{
|
||||
named = r.Id;
|
||||
throw new InvalidOperationException("the index is away");
|
||||
}, fx.Ct));
|
||||
Assert.FileMissing(ConfirmedPhotos.PathFor(fx.Paths, named!.Value));
|
||||
|
||||
// The job runs, and once done with every sequence, its photos go with its journal.
|
||||
var engine = await fx.StartEngineAsync();
|
||||
engine.Wake();
|
||||
await fx.WaitForAsync(queued.Id, JobState.Done, (int)TestTiming.Budget(60));
|
||||
Assert.FileMissing(ConfirmedPhotos.PathFor(fx.Paths, queued.Id));
|
||||
Assert.True((await FramesAsync(fx, id)).All(f => f.Format == ImageFileFormat.Tiff));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AJobsParametersNameThePhotosItConverts()
|
||||
public void ThePhotosConfirmedReadBackAsWrittenAndALineThatCannotBeReadNamesNothing()
|
||||
{
|
||||
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()!);
|
||||
Assert.SequenceEqual(ids, ConfirmedPhotos.Decode(ConfirmedPhotos.Encode(ids)));
|
||||
Assert.Empty(ConfirmedPhotos.Decode(ConfirmedPhotos.Encode([])));
|
||||
Assert.Throws<FormatException>(() => ConfirmedPhotos.Decode(Convert.ToBase64String(new byte[15])));
|
||||
|
||||
var paths = new ArchivePaths(context.CreateTempDirectory("archive"));
|
||||
var job = Guid.CreateVersion7();
|
||||
var (good, bad) = (Guid.NewGuid(), Guid.NewGuid());
|
||||
Directory.CreateDirectory(paths.JournalDirectory);
|
||||
File.WriteAllLines(ConfirmedPhotos.PathFor(paths, job),
|
||||
[
|
||||
JsonSerializer.Serialize(new ConfirmedLine(good, ConfirmedPhotos.Encode(ids)), ArchiveJobJson.Default.ConfirmedLine),
|
||||
JsonSerializer.Serialize(new ConfirmedLine(bad, "not ids"), ArchiveJobJson.Default.ConfirmedLine),
|
||||
"{\"sequence\":",
|
||||
]);
|
||||
var read = ConfirmedPhotos.Read(paths, job);
|
||||
Assert.SequenceEqual(ids, read.Of(good)!);
|
||||
Assert.Null(read.Of(bad));
|
||||
// None at all where nothing was written: every sequence is then held to its whole plan.
|
||||
Assert.Null(ConfirmedPhotos.Read(paths, Guid.CreateVersion7()).Of(good));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Without the photos confirmed (they could not be written when the job was queued, or an earlier build queued it), a
|
||||
/// sequence converts only while its whole plan made again is the one confirmed: an upload since leaves it as it is.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public async Task WithoutThePhotosConfirmedASequenceIsHeldToItsWholePlan()
|
||||
{
|
||||
await using var fx = await FixtureAsync();
|
||||
var still = await UploadedAsync(fx, 2);
|
||||
var grown = await UploadedAsync(fx, 2, "upload-2", seed: 300);
|
||||
var plan = await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.Replace, still, grown);
|
||||
var (path, size, sha) = fx.Stage(Start.AddSeconds(60), 999);
|
||||
await fx.Service.Ingest.CommitAsync(new IngestRequest(fx.Archive.Id, grown, null, null, path, "IMG_0099.JPG", size, sha, null, null), fx.Ct);
|
||||
var before = await FramesAsync(fx, grown);
|
||||
|
||||
var result = await fx.Service.Converter.RunAsync(fx.Archive, Parameters(fx, plan), Guid.CreateVersion7(), new ConvertRequester(null, null), Callbacks(), fx.Ct);
|
||||
Assert.SequenceEqual([ConvertOutcome.Converted, ConvertOutcome.Changed], result.Sequences.Select(s => s.Outcome));
|
||||
Assert.SequenceEqual(before.Select(f => (f.Id, f.Sha256)), (await FramesAsync(fx, grown)).Select(f => (f.Id, f.Sha256)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A New sequence job that stopped once its copy held the photos, before its journal said the sequence was done (a crash,
|
||||
/// a stop): retried after the source changed, it finishes that copy and makes no other; the copy is reported as made.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public async Task ARetryAfterACrashOnceTheCopyWasFiledFinishesThatCopyAndMakesNoOther()
|
||||
{
|
||||
await using var fx = await FixtureAsync();
|
||||
var id = await UploadedAsync(fx, 3);
|
||||
await fx.Service.SetSequenceInfoAsync(id, "Roof", ["sunset"], 4, "From the roof", fx.Ct);
|
||||
var plan = await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.NewSequence, id);
|
||||
var jobId = Guid.CreateVersion7();
|
||||
// What the attempt that stopped there left: the photos confirmed, pinned and staged, and the copy filed, the journal
|
||||
// not saying more (it is written once the copy is finished).
|
||||
var left = new Dictionary<string, byte[]>();
|
||||
var callbacks = Callbacks(done: _ =>
|
||||
{
|
||||
foreach (var file in new[] { ConfirmedPhotos.PathFor(fx.Paths, jobId), ConvertJournal.PinsPathFor(fx.Paths, jobId), ConvertJournal.StagedPathFor(fx.Paths, jobId) })
|
||||
left[file] = File.ReadAllBytes(file);
|
||||
});
|
||||
var first = (await RunHereAsync(fx, plan, jobId, callbacks)).Sequences.Single();
|
||||
Assert.Equal(ConvertOutcome.Created, first.Outcome);
|
||||
var copy = first.NewSequenceId!.Value;
|
||||
await fx.Db.Sequences.EditAsync(copy, new SequenceEdit { Tags = ["other"], Rating = 1, Notes = "Scrambled" }, null, fx.Ct);
|
||||
foreach (var (file, bytes) in left) File.WriteAllBytes(file, bytes);
|
||||
// The source changed since: a photo of it deleted.
|
||||
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 sequences = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id, fx.Ct)).Count;
|
||||
|
||||
var retried = (await RunHereAsync(fx, plan, jobId)).Sequences.Single();
|
||||
Assert.Equal((ConvertOutcome.Created, 3, (Guid?)copy, 0), (retried.Outcome, retried.Frames, retried.NewSequenceId, retried.LeftOut));
|
||||
Assert.Equal(sequences, (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id, fx.Ct)).Count);
|
||||
Assert.Count(3, await FramesAsync(fx, copy));
|
||||
// Finished as stage B finishes a copy: the source's tags, rating and notes.
|
||||
var finished = (await fx.Db.Sequences.GetAsync(copy))!;
|
||||
Assert.Equal((4, "From the roof"), (finished.Rating, finished.Notes));
|
||||
Assert.SequenceEqual(["sunset"], finished.Tags);
|
||||
Assert.FileMissing(ConvertJournal.PathFor(fx.Paths, jobId));
|
||||
|
||||
// Its journal names the copy as soon as the copy holds its photos: a copy deleted since is not made again.
|
||||
var again = Guid.CreateVersion7();
|
||||
var journal = new ConvertJournal { JobId = again };
|
||||
journal.Made(id, Guid.CreateVersion7());
|
||||
journal.Write(fx.Paths);
|
||||
var gone = (await RunHereAsync(fx, plan, again)).Sequences.Single();
|
||||
Assert.Equal(ConvertOutcome.Changed, gone.Outcome);
|
||||
Assert.Null(await fx.Db.Sequences.FindBySessionKeyAsync(fx.Archive.Id, MassConverter.SessionKey(again, id)));
|
||||
Assert.Equal(sequences, (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id, fx.Ct)).Count);
|
||||
}
|
||||
|
||||
/// <summary>The photos a New sequence job filed into its copy before it stopped take no space again: its retry finishes on a full volume.</summary>
|
||||
[Test]
|
||||
public async Task ARetryOnceTheCopyWasFiledNeedsNoSpaceForItsPhotosAgain()
|
||||
{
|
||||
long free = 1L << 50;
|
||||
await using var fx = await FixtureAsync(o => o with { FreeSpace = _ => free });
|
||||
var id = await UploadedAsync(fx, 2);
|
||||
var plan = await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.NewSequence, id);
|
||||
var jobId = Guid.CreateVersion7();
|
||||
var left = new Dictionary<string, byte[]>();
|
||||
var callbacks = Callbacks(done: _ =>
|
||||
{
|
||||
foreach (var file in new[] { ConfirmedPhotos.PathFor(fx.Paths, jobId), ConvertJournal.PinsPathFor(fx.Paths, jobId), ConvertJournal.StagedPathFor(fx.Paths, jobId) })
|
||||
left[file] = File.ReadAllBytes(file);
|
||||
});
|
||||
var copy = (await RunHereAsync(fx, plan, jobId, callbacks)).Sequences.Single().NewSequenceId;
|
||||
foreach (var (file, bytes) in left) File.WriteAllBytes(file, bytes);
|
||||
free = 1_000;
|
||||
|
||||
var retried = (await RunHereAsync(fx, plan, jobId)).Sequences.Single();
|
||||
Assert.Equal((ConvertOutcome.Created, copy), (retried.Outcome, retried.NewSequenceId));
|
||||
Assert.Count(2, await FramesAsync(fx, copy!.Value));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A conversion into new sequences retried after another conversion, confirmed later, copied the same source in the same
|
||||
/// format: it makes no second copy, and is done with that sequence.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public async Task ARetriedConversionMakesNoSecondCopyOfASourceAnotherConversionCopiedSince()
|
||||
{
|
||||
await using var fx = await FixtureAsync();
|
||||
var id = await UploadedAsync(fx, 2);
|
||||
var title = (await fx.Db.Sequences.GetAsync(id))!.DisplayTitle;
|
||||
var plan = await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.NewSequence, id);
|
||||
// Job A finds the sequence busy (a render works on it), and fails.
|
||||
var a = await QueuedAsync(fx, plan, DateTimeOffset.UtcNow.AddMinutes(-10));
|
||||
var render = new Job { Id = Guid.CreateVersion7(), Kind = JobKind.Render, TargetIds = [id], State = JobState.Running, Created = DateTimeOffset.UtcNow };
|
||||
await fx.Db.Jobs.EnqueueAsync(render, fx.Ct);
|
||||
Assert.Equal(ConvertOutcome.Blocked, (await RunHereAsync(fx, plan, a.Id, confirmed: a.Created)).Sequences.Single().Outcome);
|
||||
await fx.Db.Jobs.SetStateAsync(render.Id, JobState.Done, null, fx.Ct);
|
||||
await fx.Db.Jobs.SetStateAsync(a.Id, JobState.Failed, "kept", fx.Ct);
|
||||
// The user plans again: job B makes the copy. A JPEG copy made meanwhile is another format, which does not count.
|
||||
var again = await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.NewSequence, id);
|
||||
var b = await QueuedAsync(fx, again, DateTimeOffset.UtcNow.AddMinutes(-5));
|
||||
var made = (await RunHereAsync(fx, again, b.Id, confirmed: b.Created)).Sequences.Single();
|
||||
Assert.Equal(ConvertOutcome.Created, made.Outcome);
|
||||
await fx.Db.Jobs.SetStateAsync(b.Id, JobState.Done, null, fx.Ct);
|
||||
var sequences = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id, fx.Ct)).Count;
|
||||
|
||||
// Retry on A: done with the sequence, no second copy.
|
||||
var lines = new List<string>();
|
||||
var retried = (await RunHereAsync(fx, plan, a.Id, Callbacks() with { Log = lines.Add }, a.Created)).Sequences.Single();
|
||||
Assert.Equal((ConvertOutcome.Superseded, true), (retried.Outcome, retried.Final));
|
||||
Assert.SequenceEqual([Loc.L("Archive.Log.ConvertSuperseded", title)], lines);
|
||||
Assert.Null(await fx.Db.Sequences.FindBySessionKeyAsync(fx.Archive.Id, MassConverter.SessionKey(a.Id, id)));
|
||||
Assert.Equal(sequences, (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id, fx.Ct)).Count);
|
||||
Assert.FileMissing(ConvertJournal.PathFor(fx.Paths, a.Id));
|
||||
|
||||
// A conversion confirmed after that copy was made is the user asking again: it makes its copy.
|
||||
var latest = await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.NewSequence, id);
|
||||
var later = await QueuedAsync(fx, latest, DateTimeOffset.UtcNow);
|
||||
Assert.Equal(ConvertOutcome.Created, (await RunHereAsync(fx, latest, later.Id, confirmed: later.Created)).Sequences.Single().Outcome);
|
||||
|
||||
// A copy in another format is no copy of this one: a TIFF conversion confirmed before a DNG copy was made makes its own.
|
||||
var other = await UploadedAsync(fx, 2, "upload-2", seed: 300);
|
||||
var tiff = await PlanAsync(fx, ConvertTarget.Tiff16, ConvertMode.NewSequence, other);
|
||||
var confirmedFirst = DateTimeOffset.UtcNow.AddMinutes(-1);
|
||||
var dng = await PlanAsync(fx, ConvertTarget.LinearDng, ConvertMode.NewSequence, other);
|
||||
Assert.Equal(ConvertOutcome.Created, (await RunHereAsync(fx, dng, Guid.CreateVersion7(), confirmed: DateTimeOffset.UtcNow)).Sequences.Single().Outcome);
|
||||
Assert.Equal(ConvertOutcome.Created, (await RunHereAsync(fx, tiff, Guid.CreateVersion7(), confirmed: confirmedFirst)).Sequences.Single().Outcome);
|
||||
}
|
||||
}
|
||||
@@ -103,6 +103,56 @@ public abstract class JobRepositoryTests(TestContext context) : RepositoryTest(c
|
||||
return job;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task HoldsNameTheTargetsOfRunningAndPausedJobsAndOnlyAVerifysParameters()
|
||||
{
|
||||
// What a dry run counts as busy, read at every one and at every sequence a conversion comes to: never the parameters
|
||||
// a conversion or an import keeps, nor the row of the job asking.
|
||||
var db = await OpenChronosAsync();
|
||||
Guid a = Guid.CreateVersion7(), b = Guid.CreateVersion7(), archive = Guid.CreateVersion7();
|
||||
var convert = await EnqueueAsync(db, TestData.Job(JobKind.Convert) with { TargetIds = [a, b], ParametersJson = "{\"fingerprint\": \"f\"}", State = JobState.Running });
|
||||
var verify = await EnqueueAsync(db, TestData.Job(JobKind.Verify) with { TargetIds = [archive], ParametersJson = "{\"sequenceIds\": []}", State = JobState.Paused });
|
||||
await EnqueueAsync(db, TestData.Job(JobKind.Thumbs) with { TargetIds = [a] });
|
||||
await EnqueueAsync(db, TestData.Job(JobKind.Scan) with { TargetIds = [archive], State = JobState.Done, Finished = TestData.Now });
|
||||
|
||||
var holds = await db.Jobs.ListHoldsAsync(cancellationToken: Ct);
|
||||
Assert.SequenceEqual(new[] { convert.Id, verify.Id }.Order(), holds.Select(h => h.Id).Order());
|
||||
var running = holds.Single(h => h.Id == convert.Id);
|
||||
Assert.Equal((JobKind.Convert, (string?)null), (running.Kind, running.ParametersJson));
|
||||
Assert.SequenceEqual([a, b], running.TargetIds);
|
||||
var paused = holds.Single(h => h.Id == verify.Id);
|
||||
Assert.Equal((JobKind.Verify, verify.ParametersJson), (paused.Kind, paused.ParametersJson));
|
||||
Assert.SequenceEqual([verify.Id], (await db.Jobs.ListHoldsAsync(convert.Id, Ct)).Select(h => h.Id));
|
||||
|
||||
Assert.Equal(convert.Created, await db.Jobs.GetCreatedAsync(convert.Id, Ct));
|
||||
Assert.Null(await db.Jobs.GetCreatedAsync(Guid.CreateVersion7(), Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task BriefListsReadEveryFieldButTheParameters()
|
||||
{
|
||||
var db = await OpenChronosAsync();
|
||||
var job = TestData.Job(JobKind.Convert, JobPriority.User) with
|
||||
{
|
||||
TargetIds = [Guid.CreateVersion7(), Guid.CreateVersion7()],
|
||||
TargetLabel = "Harbour sunset",
|
||||
ParametersJson = "{\"fingerprint\": \"f\"}",
|
||||
LogTail = "line 1",
|
||||
CreatedBy = Guid.CreateVersion7(),
|
||||
ScheduleId = Guid.CreateVersion7(),
|
||||
};
|
||||
await db.Jobs.EnqueueAsync(job, Ct);
|
||||
|
||||
var brief = Assert.NotNull((await db.Jobs.ListBriefAsync(JobState.Queued, JobKind.Convert, 10, null, Ct)).Items.SingleOrDefault());
|
||||
Assert.SequenceEqual(job.TargetIds, brief.TargetIds);
|
||||
Assert.Equal(job with { TargetIds = brief.TargetIds, ParametersJson = null }, brief);
|
||||
Assert.Equal(job.ParametersJson, (await db.Jobs.ListAsync(JobState.Queued, JobKind.Convert, 10, null, Ct)).Items.Single().ParametersJson);
|
||||
Assert.Empty((await db.Jobs.ListBriefAsync(JobState.Running, null, 10, null, Ct)).Items);
|
||||
var next = Assert.NotNull((await db.Jobs.ListQueuedBriefAsync([JobKind.Convert], 10, Chronos.Data.Jobs.JobPriorityQueue.Off, Ct)).SingleOrDefault());
|
||||
Assert.Equal((job.Id, (string?)null), (next.Id, next.ParametersJson));
|
||||
Assert.Empty(await db.Jobs.ListQueuedBriefAsync([], 10, Chronos.Data.Jobs.JobPriorityQueue.Off, Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ThePriorityQueueClaimsTheHigherKindsFirst()
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user