merge: bring phase 4b's final code (v0.1.0-rc.7) into phase 5a

Phase 5a was cut from an earlier phase 4b commit (e3cbe30b). This merges the
final 4b head 11d2c67e (squashed into main as efa87f68): fix rounds 2-3 of
the mass conversion and the replaced-photo trash, the residuals, the 4b
strings in the 36 other languages, and 4b's docs, so 5a builds on the code
that was released.

Conflicts:
- JobRepository: 5a's ListPendingAsync (the workspace copies of a sequence)
  and 4b's ListHoldsAsync (what running and paused jobs hold, without the
  parameters) are both kept.
- ARCHITECTURE: 4b's rows and paragraph kept whole, 5a's additions
  (projects, workspaces, the Edit picker, the WorkspaceCopy job) laid onto
  them; both paragraphs kept.

The resx files merged cleanly: the 36 other cultures hold 4b's
translations, and 5a's new keys stay untranslated there. JobKind values are
unchanged (Backup 16, Cleanup 17, EmptyTrash 18, Convert 19,
WorkspaceCopy 20).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-03 15:44:47 +01:00
commit 6e00c3c996
290 files changed
+14129 -884

No files matched your search

@@ -1,3 +1,4 @@
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text.Json;
using Chronos.Core.Archiving;
@@ -75,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)));
@@ -109,6 +122,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 +505,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]
@@ -631,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"));
@@ -803,19 +912,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 +1094,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 +1163,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 +1182,519 @@ 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 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 void APhotoStartsOnlyWithTheSpaceForItAndThePhotosStillWriting()
{
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);
// 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));
}
/// <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()
{
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, 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, 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 ThePhotosConfirmedReadBackAsWrittenAndALineThatCannotBeReadNamesNothing()
{
Guid[] ids = [Guid.CreateVersion7(), Guid.CreateVersion7(), Guid.NewGuid()];
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);
var sequences = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id, fx.Ct)).Count;
// While job B has not finished (it failed after filing its copy), Retry on A waits for it: no second copy, not done with.
await fx.Db.Jobs.SetStateAsync(b.Id, JobState.Failed, "kept", fx.Ct);
var waiting = (await RunHereAsync(fx, plan, a.Id, confirmed: a.Created)).Sequences.Single();
Assert.Equal((ConvertOutcome.Blocked, Loc.L("Archive.Convert.CopyUnfinished")), (waiting.Outcome, waiting.Error));
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);
await fx.Db.Jobs.SetStateAsync(b.Id, JobState.Done, null, fx.Ct);
// 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);
}
}
@@ -439,9 +439,19 @@ public abstract class FrameTrashTests(TestContext context) : DatabaseTest(contex
var (sequence, frames) = await UploadedAsync(fx, 2);
var replacement = frames[1];
var good = WriteReplaced(fx, sequence, "20261027100000", replacement.Sha256!);
// A replacement no frame of the sequence holds any more (its conversion deleted and erased): the dry run says so, and
// the emptying confirmed with it erases the originals (owner review 2, R7).
var gone = WriteReplaced(fx, sequence, "20261027110000", new string('a', 64));
// A replacement no frame of the sequence holds any more, and whose deletion the sidecar records (its conversion deleted
// and erased): the dry run says so, and the emptying confirmed with it erases the originals (owner review 2, R7).
var deleted = new string('a', 64);
var gone = WriteReplaced(fx, sequence, "20261027110000", deleted);
var sidecar = fx.Paths.Sequence(sequence.Folder).ManifestPath;
var manifest = ManifestStore.ReadSequence(sidecar);
ManifestStore.WriteSequence(sidecar, manifest with
{
Removed = [.. (manifest.Removed ?? []), new RemovedPhoto { Sha256 = deleted, Reason = RemovalReason.Deleted, At = DateTimeOffset.UtcNow }],
});
// One that nothing in the archive says was deleted stays: the sidecar holds no frame of it and no tombstone of it, as a
// sidecar rebuilt from the photos shows a conversion it never knew.
var untraced = WriteReplaced(fx, sequence, "20261027113000", new string('b', 64));
var engine = await fx.StartEngineAsync();
var listed = await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct);
Assert.True(listed.All(e => e.Kind == TrashKind.Replaced));
@@ -449,9 +459,11 @@ public abstract class FrameTrashTests(TestContext context) : DatabaseTest(contex
var plan = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
Assert.True(plan.Entries.Single(e => e.Name == FrameTrash.EntryPrefix + gone).ConversionDeleted);
Assert.False(plan.Entries.Single(e => e.Name == FrameTrash.EntryPrefix + good).ConversionDeleted);
Assert.False(plan.Entries.Single(e => e.Name == FrameTrash.EntryPrefix + untraced).ConversionDeleted, "the archive does not say it was deleted");
var job = await engine.EnqueueAsync(ArchiveJobs.EmptyTrash(fx.Archive, plan), cancellationToken: fx.Ct);
await fx.WaitForAsync(job.Id, JobState.Done);
Assert.Empty(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct));
var kept = await fx.WaitForAsync(job.Id, JobState.Failed);
Assert.Contains(Chronos.Core.Localization.Loc.L("Archive.Log.TrashKeptUnknown", sequence.DisplayTitle), kept.LogTail);
Assert.Equal(FrameTrash.EntryPrefix + untraced, (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Single().Name, "the others are erased");
// A replacement whose file no longer hashes to it keeps its originals.
var other = WriteReplaced(fx, sequence, "20261027120000", replacement.Sha256!);
@@ -1,6 +1,7 @@
using System.Security.Cryptography;
using Chronos.Core.Archiving;
using Chronos.Core.Import;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Archiving;
@@ -45,9 +46,11 @@ public sealed class ReplacedTrashTests(TestContext context)
/// <summary>
/// Replaces the files of the frames at <paramref name="indices"/> (in the sidecar now) with other photos, as a
/// conversion's stage B does (<see cref="FrameTrash.ReplaceAsync"/>); returns the trash entry of the originals.
/// conversion's stage B does (<see cref="FrameTrash.ReplaceAsync"/>), on this host or on <paramref name="by"/> (another
/// host sharing the archive, whose index this one does not read); returns the trash entry of the originals.
/// </summary>
private static async Task<TrashEntry> ReplaceAsync(ArchiveFixture fx, Guid sequenceId, IReadOnlyList<int> indices, int seed, Guid? job = null)
private static async Task<TrashEntry> ReplaceAsync(ArchiveFixture fx, Guid sequenceId, IReadOnlyList<int> indices, int seed, Guid? job = null,
(ArchiveService Service, Archive Archive)? by = null)
{
var sequence = (await fx.Db.Sequences.GetAsync(sequenceId))!;
var manifest = Sidecar(fx, sequence);
@@ -68,10 +71,21 @@ public sealed class ReplacedTrashTests(TestContext context)
Source = new FrameSource { Sha256 = current.Sha256, Format = current.Format, File = current.File, Size = current.Size },
}));
}
var result = Assert.NotNull(await fx.Service.FrameTrash.ReplaceAsync(fx.Archive, sequenceId, null, swaps, null, job, null, null, fx.Ct));
var (service, archive) = by ?? (fx.Service, fx.Archive);
var result = Assert.NotNull(await service.FrameTrash.ReplaceAsync(archive, sequenceId, null, swaps, null, job, null, null, fx.Ct));
return Assert.NotNull(result.Entry);
}
/// <summary>Flips a byte near the end of <paramref name="path"/>; returns its bytes before.</summary>
private static byte[] Damage(string path)
{
var bytes = File.ReadAllBytes(path);
var damaged = (byte[])bytes.Clone();
damaged[^10] ^= 0x01;
File.WriteAllBytes(path, damaged);
return bytes;
}
private static SequenceManifest Sidecar(ArchiveFixture fx, Sequence sequence) => ManifestStore.ReadSequence(fx.Paths.Sequence(sequence.Folder).ManifestPath);
private static string Sha(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes));
@@ -84,6 +98,10 @@ public sealed class ReplacedTrashTests(TestContext context)
return await fx.WaitForAsync(job.Id, state);
}
/// <summary>What the emptying job of <paramref name="plan"/> is given, for a test that runs the emptying itself.</summary>
private static EmptyTrashParameters Parameters(TrashEmptyPlan plan) =>
new([.. plan.Entries.Select(e => new EmptyTrashItem(e.Name, SequenceTrash.EntryFingerprint(e)))], plan.Fingerprint);
[Test]
public async Task AReplacementThatCouldNotBeUndoneIsUndoneBeforeAnythingElseIsFiled()
{
@@ -279,6 +297,424 @@ public sealed class ReplacedTrashTests(TestContext context)
Assert.Count(2, await fx.Db.Frames.ListBySequenceAsync(id));
}
[Test]
public async Task AConversionAnotherHostMadeIsHashedWhereTheArchiveHoldsIt()
{
await using var fx = await CreateAsync(context);
var (id, photos) = await UploadedAsync(fx, 2);
var engine = await fx.StartEngineAsync();
// A desktop sharing the archive converts the first photo; this index still holds the original there.
var replaced = await ReplaceAsync(fx, id, [0], 500, by: await fx.OtherWriterAsync());
Assert.Equal(Sha(photos[0]), (await fx.Db.Frames.ListBySequenceAsync(id))[0].Sha256);
var sequence = (await fx.Db.Sequences.GetAsync(id))!;
var converted = fx.Paths.Sequence(sequence.Folder).File(Sidecar(fx, sequence).Frames[0].File);
// The conversion is damaged since: the dry run finds it in the sequence, and the emptying keeps the originals.
var bytes = Damage(converted);
var plan = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
Assert.False(plan.Entries.Single().ConversionDeleted, "the archive holds the conversion, whatever this index has");
var kept = await EmptyAsync(fx, engine, plan, JobState.Failed);
Assert.Contains(Loc.L("Archive.Log.TrashKeptMismatch", replaced.Title), kept.LogTail);
Assert.Equal(replaced.Name, (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Single().Name);
// Whole again: the originals go.
File.WriteAllBytes(converted, bytes);
await EmptyAsync(fx, engine, await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct), JobState.Done);
Assert.Empty(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct));
}
[Test]
public async Task AConversionAnotherIndexMovedIsHashedWhereItIsNow()
{
await using var fx = await CreateAsync(context);
var (id, _) = await UploadedAsync(fx, 2);
var engine = await fx.StartEngineAsync();
var replaced = await ReplaceAsync(fx, id, [0], 500);
// Another index moves the sequence into another folder; this one has not scanned since.
var before = (await fx.Db.Sequences.GetAsync(id))!.Folder;
var (other, archive) = await fx.OtherWriterAsync();
await other.ApplyRenameAsync(await other.PlanRenameAsync(archive.Id, [id], "moved/{title}", null, fx.Ct), null, fx.Ct);
Assert.Equal(before, (await fx.Db.Sequences.GetAsync(id))!.Folder);
var folder = ArchiveScanner.FindSequenceFolders(fx.Paths, fx.Ct).Select(s => fx.Paths.Sequence(s.RelativeFolder)).Single(s => s.RelativeFolder != before);
Assert.True(folder.RelativeFolder.StartsWith("moved", StringComparison.Ordinal), folder.RelativeFolder);
var converted = folder.File(ManifestStore.ReadSequence(folder.ManifestPath).Frames[0].File);
var bytes = Damage(converted);
var plan = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
Assert.False(plan.Entries.Single().ConversionDeleted, "found in the folder the sequence is in now");
Assert.Contains(Loc.L("Archive.Log.TrashKeptMismatch", replaced.Title), (await EmptyAsync(fx, engine, plan, JobState.Failed)).LogTail);
File.WriteAllBytes(converted, bytes);
await EmptyAsync(fx, engine, await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct), JobState.Done);
Assert.Empty(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct));
}
[Test]
public async Task OriginalsStayWhileTheArchiveCannotTellWhereTheirConversionIs()
{
await using var fx = await CreateAsync(context);
var (id, photos) = await UploadedAsync(fx, 2);
var engine = await fx.StartEngineAsync();
var replaced = await ReplaceAsync(fx, id, [0], 500);
var sequence = (await fx.Db.Sequences.GetAsync(id))!;
var folder = fx.Paths.Sequence(sequence.Folder);
var manifest = Sidecar(fx, sequence);
// A sidecar that cannot be read: a scan rebuilds it, as the line says.
File.WriteAllText(folder.ManifestPath, "{ \"damaged");
var plan = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
Assert.False(plan.Entries.Single().ConversionDeleted);
Assert.Contains(Loc.L("Archive.Log.TrashKeptUnreadable", replaced.Title), (await EmptyAsync(fx, engine, plan, JobState.Failed)).LogTail);
// A sidecar rebuilt from the photos, as a scan adopts a folder that lost its own: new frame ids, nothing hashed, no
// tombstones. A verify of the sequence, as the line says, may find the conversion in one of its frames.
var rebuilt = manifest with { Frames = [.. manifest.Frames.Select(f => f with { Id = Guid.CreateVersion7(), Sha256 = null })], Removed = null };
ManifestStore.WriteSequence(folder.ManifestPath, rebuilt);
plan = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
Assert.False(plan.Entries.Single().ConversionDeleted);
Assert.Contains(Loc.L("Archive.Log.TrashKeptUnhashed", replaced.Title), (await EmptyAsync(fx, engine, plan, JobState.Failed)).LogTail);
// Unless their files are missing: there is nothing a verify could hash.
ManifestStore.WriteSequence(folder.ManifestPath, rebuilt with { Frames = [.. rebuilt.Frames.Select(f => f with { Flags = f.Flags | FrameFlags.Missing })] });
plan = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
Assert.Contains(Loc.L("Archive.Log.TrashKeptUnknown", replaced.Title), (await EmptyAsync(fx, engine, plan, JobState.Failed)).LogTail);
// Nor when they are flagged corrupt: a verify does not hash a file whose size differs from its record, so it would
// never settle the entry.
ManifestStore.WriteSequence(folder.ManifestPath, rebuilt with { Frames = [.. rebuilt.Frames.Select(f => f with { Flags = f.Flags | FrameFlags.Corrupt })] });
plan = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
Assert.Contains(Loc.L("Archive.Log.TrashKeptUnknown", replaced.Title), (await EmptyAsync(fx, engine, plan, JobState.Failed)).LogTail);
// Hashed, the conversion damaged meanwhile: no frame holds it and no tombstone says it was deleted. The originals stay,
// and the dry run never calls them the last copy: only the archive's own word makes a conversion deleted.
Damage(folder.File(manifest.Frames[0].File));
ManifestStore.WriteSequence(folder.ManifestPath, rebuilt with { Frames = [.. rebuilt.Frames.Select(f => f with { Sha256 = Sha(folder.File(f.File)) })] });
plan = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
Assert.False(plan.Entries.Single().ConversionDeleted, "nothing in the archive says the conversion was deleted");
Assert.Contains(Loc.L("Archive.Log.TrashKeptUnknown", replaced.Title), (await EmptyAsync(fx, engine, plan, JobState.Failed)).LogTail);
// Restored, as the line says, the original comes back whole, as a sequence of its own.
var restored = await fx.Service.RestoreEntryAsync(fx.Archive.Id, replaced.Name, null, fx.Ct);
Assert.True(restored.NewSequence);
Assert.SequenceEqual([Sha(photos[0])], (await fx.Db.Frames.ListBySequenceAsync(restored.Sequence.Id)).Select(f => f.Sha256!));
Assert.Empty(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct));
}
[Test]
public async Task AConversionAnotherHostMadeIsNotTakenForDeletedOnceItsSidecarIsRebuilt()
{
await using var fx = await CreateAsync(context);
var (id, photos) = await UploadedAsync(fx, 2);
var engine = await fx.StartEngineAsync();
// A desktop sharing the archive converts the first photo: this index never sees the converted file.
var replaced = await ReplaceAsync(fx, id, [0], 500, by: await fx.OtherWriterAsync());
var sequence = (await fx.Db.Sequences.GetAsync(id))!;
var folder = fx.Paths.Sequence(sequence.Folder);
// The conversion is damaged and the sidecar lost since: this index's scan rebuilds the sidecar from the photos with what
// it knew, which is nothing of the conversion (the converted file gets a new frame id, no tombstone names it).
Damage(folder.File(Sidecar(fx, sequence).Frames[0].File));
File.Delete(folder.ManifestPath);
await fx.ScanAsync();
Assert.Null(Sidecar(fx, sequence).Removed);
var before = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
Assert.False(before.Entries.Single().ConversionDeleted);
Assert.Contains(Loc.L("Archive.Log.TrashKeptUnhashed", replaced.Title), (await EmptyAsync(fx, engine, before, JobState.Failed)).LogTail);
// A routine verify hashes every photo, the damaged conversion too: still nothing says the conversion was deleted, so the
// originals, the only good copy of that photo, are neither called the last copy nor erased.
await fx.Service.Verifier.VerifyAsync(fx.Archive, [id], default, (_, _, _) => ValueTask.CompletedTask, cancellationToken: fx.Ct);
Assert.True(Sidecar(fx, sequence).Frames.All(f => f.Sha256 is not null), "verified");
var plan = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
Assert.False(plan.Entries.Single().ConversionDeleted, "the archive does not say the conversion was deleted");
Assert.Contains(Loc.L("Archive.Log.TrashKeptUnknown", replaced.Title), (await EmptyAsync(fx, engine, plan, JobState.Failed)).LogTail);
var record = Assert.NotNull(FrameTrash.ReadEntry(fx.Paths, replaced.Name));
Assert.Equal(Sha(photos[0]), Sha(Path.Combine(FrameTrash.Location(fx.Paths, replaced.Name).Folder, record.Photos[0].Files[0].Path)));
}
[Test]
public async Task OriginalsOfASequenceAnotherHostDeletedAndErasedGoAsTheDryRunSays()
{
await using var fx = await CreateAsync(context);
var (id, _) = await UploadedAsync(fx, 2);
var engine = await fx.StartEngineAsync();
var replaced = await ReplaceAsync(fx, id, [0, 1], 500);
// A desktop sharing the archive deletes the converted sequence and erases its entry alone; this index still lists it.
var (other, archive) = await fx.OtherWriterAsync();
await other.Trash.DeleteAsync(await other.Trash.PlanAsync([id], null, fx.Ct), null, null, fx.Ct);
var deleted = (await other.ListTrashAsync(archive.Id, fx.Ct)).Single(e => e.Kind == TrashKind.Sequence);
var erased = await other.Trash.EmptyAsync(archive, Parameters(await other.Trash.PlanEmptyAsync(archive, [deleted.Name], fx.Ct)), 0,
(_, _) => ValueTask.CompletedTask, fx.Ct);
Assert.Equal((1, 0), (erased.Erased, erased.Refused.Count));
Assert.NotNull(await fx.Db.Sequences.GetAsync(id));
var erasures = Path.Combine(SequenceTrash.TrashDirectory(fx.Paths), ".erased");
Assert.FileExists(Path.Combine(erasures, $"{id:N}.json"));
// The trash's record of that erasing is the archive's word that the conversions went with the sequence, whatever this
// index still lists: the dry run says so, and the emptying confirmed with it erases.
var plan = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
Assert.True(plan.Entries.Single().ConversionDeleted, "the trash erased the sequence that held the conversions");
await EmptyAsync(fx, engine, plan, JobState.Done);
Assert.Empty(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct));
Assert.False(Directory.Exists(erasures), "no entry needs the record any more");
}
[Test]
public async Task ASequenceThatAlsoLivesLeavesNoRecordOfItsErasing()
{
await using var fx = await CreateAsync(context);
var (id, _) = await UploadedAsync(fx, 2);
var engine = await fx.StartEngineAsync();
var replaced = await ReplaceAsync(fx, id, [0, 1], 500);
var sequence = (await fx.Db.Sequences.GetAsync(id))!;
// A copy of the converted sequence's folder made outside Chronos: its sidecar names the same sequence.
var source = fx.Paths.Sequence(sequence.Folder).Folder;
var copy = Path.Combine(fx.Paths.Root, "copy", Path.GetFileName(source));
foreach (var file in Directory.EnumerateFiles(source, "*", SearchOption.AllDirectories))
{
var target = Path.Combine(copy, Path.GetRelativePath(source, file));
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
File.Copy(file, target);
}
await fx.Service.Trash.DeleteAsync(await fx.Service.Trash.PlanAsync([id], null, fx.Ct), null, null, fx.Ct);
var deleted = (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Single(e => e.Kind == TrashKind.Sequence);
// Erasing the deleted sequence while a folder still names it leaves no record that its conversions went with it.
var erased = await fx.Service.Trash.EmptyAsync(fx.Archive, Parameters(await fx.Service.Trash.PlanEmptyAsync(fx.Archive, [deleted.Name], fx.Ct)), 0,
(_, _) => ValueTask.CompletedTask, fx.Ct);
Assert.Equal((1, 0), (erased.Erased, erased.Refused.Count));
Assert.FileMissing(Path.Combine(SequenceTrash.TrashDirectory(fx.Paths), ".erased", $"{id:N}.json"));
// So once the copy's sidecar is lost, the walk missing it, the originals stay: its conversions are still there.
File.Delete(Path.Combine(copy, Path.GetRelativePath(source, fx.Paths.Sequence(sequence.Folder).ManifestPath)));
var plan = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
Assert.False(plan.Entries.Single().ConversionDeleted);
Assert.Contains(Loc.L("Archive.Log.TrashKeptUnknown", replaced.Title), (await EmptyAsync(fx, engine, plan, JobState.Failed)).LogTail);
Assert.Equal(replaced.Name, (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Single().Name);
}
[Test]
public async Task OriginalsOfASequenceGoneWithoutTheTrashErasingItStay()
{
await using var fx = await CreateAsync(context);
var (id, photos) = await UploadedAsync(fx, 2);
var engine = await fx.StartEngineAsync();
var replaced = await ReplaceAsync(fx, id, [0], 500);
var sequence = (await fx.Db.Sequences.GetAsync(id))!;
// The sequence's folder removed outside Chronos while this index still lists it: kept, and the line says what drops the row.
Directory.Delete(fx.Paths.Sequence(sequence.Folder).Folder, recursive: true);
var plan = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
Assert.False(plan.Entries.Single().ConversionDeleted);
Assert.Contains(Loc.L("Archive.Log.TrashKeptStaleIndex", replaced.Title), (await EmptyAsync(fx, engine, plan, JobState.Failed)).LogTail);
// Rebuilt, the index lists it no more; still nothing in the archive says the conversion was deleted, so the originals,
// the only copy of that photo there is, stay.
await fx.ScanAsync(ScanMode.Rebuild);
Assert.Null(await fx.Db.Sequences.GetAsync(id));
plan = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
Assert.False(plan.Entries.Single().ConversionDeleted, "no sequence of that id anywhere, and no record of erasing it");
Assert.Contains(Loc.L("Archive.Log.TrashKeptUnknown", replaced.Title), (await EmptyAsync(fx, engine, plan, JobState.Failed)).LogTail);
// Restored, as the line says, it comes back as a sequence of its own.
var restored = await fx.Service.RestoreEntryAsync(fx.Archive.Id, replaced.Name, null, fx.Ct);
Assert.True(restored.NewSequence);
Assert.SequenceEqual([Sha(photos[0])], (await fx.Db.Frames.ListBySequenceAsync(restored.Sequence.Id)).Select(f => f.Sha256!));
Assert.Empty(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct));
}
[Test]
public async Task OriginalsStayWhileTheirSequenceIsInAFolderWithoutSidecar()
{
await using var fx = await CreateAsync(context);
var (id, _) = await UploadedAsync(fx, 2);
var engine = await fx.StartEngineAsync();
var replaced = await ReplaceAsync(fx, id, [0], 500);
// Another index moves the sequence, its sidecar is lost there, and this index, which never saw the move, lists it no more.
var (other, archive) = await fx.OtherWriterAsync();
await other.ApplyRenameAsync(await other.PlanRenameAsync(archive.Id, [id], "moved/{title}", null, fx.Ct), null, fx.Ct);
var moved = ArchiveScanner.FindSequenceFolders(fx.Paths, fx.Ct).Select(s => fx.Paths.Sequence(s.RelativeFolder)).Single();
Assert.True(moved.RelativeFolder.StartsWith("moved", StringComparison.Ordinal), moved.RelativeFolder);
File.Delete(moved.ManifestPath);
await fx.Db.Sequences.DeleteAsync(id, fx.Ct);
// The walk of the archive cannot tell whose photos those are, and the trash never erased the sequence: its conversion,
// alive there, is not taken for deleted, and the originals stay without it being hashed.
var plan = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
Assert.False(plan.Entries.Single().ConversionDeleted);
Assert.Contains(Loc.L("Archive.Log.TrashKeptUnknown", replaced.Title), (await EmptyAsync(fx, engine, plan, JobState.Failed)).LogTail);
Assert.Equal(replaced.Name, (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Single().Name);
}
[Test]
public async Task OriginalsOfAConvertedSequenceErasedBeforeThemGoAsTheDryRunSays()
{
await using var fx = await CreateAsync(context);
var (id, _) = await UploadedAsync(fx, 2);
var (second, _) = await UploadedAsync(fx, 2, "upload-2");
var engine = await fx.StartEngineAsync();
var replaced = await ReplaceAsync(fx, id, [0, 1], 500);
var together = await ReplaceAsync(fx, second, [0], 600);
await fx.Service.Trash.DeleteAsync(await fx.Service.Trash.PlanAsync([id, second], null, fx.Ct), null, null, fx.Ct);
var erasures = Path.Combine(SequenceTrash.TrashDirectory(fx.Paths), ".erased");
// The first sequence's entry erased alone: the trash records erasing it, for the originals it leaves there.
var deleted = (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Single(e => e.Kind == TrashKind.Sequence && e.SequenceId == id);
await EmptyAsync(fx, engine, await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, [deleted.Name], fx.Ct), JobState.Done);
Assert.Equal($"{id:N}.json", Path.GetFileName(Directory.EnumerateFiles(erasures).Single()));
// Then everything in one run: the first one's originals as that record says, the second sequence, then its originals
// as the record its erasing leaves says. No record is left once no entry needs one.
var plan = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
Assert.Count(3, plan.Entries);
Assert.True(plan.Entries.Single(e => e.Name == replaced.Name).ConversionDeleted, "the trash erased the sequence that held the conversions");
Assert.True(plan.Entries.Single(e => e.Name == together.Name).ConversionDeleted, "its sequence is in the trash");
await EmptyAsync(fx, engine, plan, JobState.Done);
Assert.Empty(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct));
Assert.False(Directory.Exists(erasures), "no entry needs a record of erasing any more");
Assert.Empty(Directory.EnumerateFiles(SequenceTrash.TrashDirectory(fx.Paths), "*", SearchOption.AllDirectories));
}
[Test]
public async Task AnEmptyingWalksTheArchiveAgainForASequenceThatMovedSinceItsWalk()
{
await using var fx = await CreateAsync(context);
var (id, _) = await UploadedAsync(fx, 2);
var (second, _) = await UploadedAsync(fx, 3, "upload-2");
var replaced = await ReplaceAsync(fx, id, [0], 500);
// Photos deleted from another sequence since: the newer entry, erased first.
var row = (await fx.Db.Sequences.GetAsync(second))!;
var deletion = await fx.Service.FrameTrash.DeleteAsync(
await fx.Service.FrameTrash.PlanDeleteAsync(second, [(await fx.Db.Frames.ListBySequenceAsync(second))[0].Id], row.FramesVersion, fx.Ct), null, null, fx.Ct);
// Another index moved the converted sequence: this one finds it by walking the archive, once for the whole plan.
var (other, archive) = await fx.OtherWriterAsync();
await other.ApplyRenameAsync(await other.PlanRenameAsync(archive.Id, [id], "moved/{title}", null, fx.Ct), null, fx.Ct);
var plan = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
Assert.SequenceEqual([deletion.Entry.Name, replaced.Name], plan.Entries.Select(e => e.Name));
Assert.False(plan.Entries.Single(e => e.Name == replaced.Name).ConversionDeleted, "found where it is now");
// It moves again while the emptying erases the other entry: the folder that walk found no longer holds it, so the archive
// is walked again, and the conversion is hashed where it is now.
var result = await fx.Service.Trash.EmptyAsync(fx.Archive, Parameters(plan), 0, async (done, _) =>
{
if (done == 1) await other.ApplyRenameAsync(await other.PlanRenameAsync(archive.Id, [id], "again/{title}", null, fx.Ct), null, fx.Ct);
}, fx.Ct);
Assert.Equal((2, 0), (result.Erased, result.Refused.Count));
Assert.Empty(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct));
}
[Test]
public async Task OriginalsOfABusySequenceStayInTheTrash()
{
await using var fx = await CreateAsync(context, configure: o => o with { LeaseWait = TimeSpan.FromMilliseconds(300) });
var (id, _) = await UploadedAsync(fx, 2);
var replaced = await ReplaceAsync(fx, id, [0], 500);
var plan = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
var parameters = new EmptyTrashParameters([.. plan.Entries.Select(e => new EmptyTrashItem(e.Name, SequenceTrash.EntryFingerprint(e)))], plan.Fingerprint);
// Another host writes the sequence meanwhile: the conversion is not weighed under it.
using (Assert.NotNull(LeaseFile.TryAcquire(fx.Paths.LocksDirectory, $"seq-{id:N}", "another host")))
{
var busy = await fx.Service.Trash.EmptyAsync(fx.Archive, parameters, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
Assert.Equal((0, TrashKeptReason.Busy), (busy.Erased, busy.Refused.Single().Reason));
Assert.Equal(Loc.L("Archive.Log.TrashKeptBusy", replaced.Title), busy.Refused.Single().LogLine);
}
Assert.Equal(replaced.Name, (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Single().Name);
var free = await fx.Service.Trash.EmptyAsync(fx.Archive, parameters, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
Assert.Equal((1, 0), (free.Erased, free.Refused.Count));
}
[Test]
public async Task AConversionAnotherHostDeletedIsReadFromTheArchiveNotThisIndex()
{
await using var fx = await CreateAsync(context);
var (id, _) = await UploadedAsync(fx, 3);
var engine = await fx.StartEngineAsync();
var replaced = await ReplaceAsync(fx, id, [0], 500);
var frames = await fx.Db.Frames.ListBySequenceAsync(id);
// A desktop sharing the archive deletes the converted photo; this index still holds it.
var (other, _) = await fx.OtherWriterAsync();
var deletion = await other.FrameTrash.DeleteAsync(await other.FrameTrash.PlanDeleteAsync(id, [frames[0].Id], null, fx.Ct), null, null, fx.Ct);
Assert.Count(3, await fx.Db.Frames.ListBySequenceAsync(id));
var plan = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
Assert.True(plan.Entries.Single(e => e.Name == replaced.Name).ConversionDeleted, "the sidecar's tombstone says so, whatever this index holds");
Assert.False(plan.Entries.Single(e => e.Name == deletion.Entry.Name).ConversionDeleted);
// The deleted conversion is in the trash, damaged: the originals stay.
var record = Assert.NotNull(FrameTrash.ReadEntry(fx.Paths, deletion.Entry.Name));
var copy = Path.Combine(FrameTrash.Location(fx.Paths, deletion.Entry.Name).Folder, record.Photos[0].Files[0].Path);
var bytes = Damage(copy);
var kept = await EmptyAsync(fx, engine, await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, [replaced.Name], fx.Ct), JobState.Failed);
Assert.Contains(Loc.L("Archive.Log.TrashKeptMismatch", replaced.Title), kept.LogTail);
// Whole again: the originals go, the deleted conversion stays where it is.
File.WriteAllBytes(copy, bytes);
await EmptyAsync(fx, engine, await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, [replaced.Name], fx.Ct), JobState.Done);
Assert.Equal(deletion.Entry.Name, (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Single().Name);
}
[Test]
public async Task OriginalsStayWhenTheirConversionChangedSince()
{
await using var fx = await CreateAsync(context);
var (id, _) = await UploadedAsync(fx, 2);
var engine = await fx.StartEngineAsync();
var replaced = await ReplaceAsync(fx, id, [0], 500);
var sequence = (await fx.Db.Sequences.GetAsync(id))!;
var folder = fx.Paths.Sequence(sequence.Folder);
var manifest = Sidecar(fx, sequence);
// The converted file was edited in place and hashed again: its frame holds other content, and nothing says what
// became of the conversion.
var edited = Photos.Jpeg(manifest.Frames[0].CapturedAt, 700);
File.WriteAllBytes(folder.File(manifest.Frames[0].File), edited);
ManifestStore.WriteSequence(folder.ManifestPath, manifest with
{
Frames = [.. manifest.Frames.Select((f, i) => i == 0 ? f with { Sha256 = Sha(edited), Size = edited.Length } : f)],
});
var plan = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
Assert.False(plan.Entries.Single().ConversionDeleted, "the frame is there");
Assert.Contains(Loc.L("Archive.Log.TrashKeptMismatch", replaced.Title), (await EmptyAsync(fx, engine, plan, JobState.Failed)).LogTail);
Assert.Equal(replaced.Name, (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Single().Name);
}
[Test]
public async Task AnEmptyingReadsAnEntryOnlyOnceAnUndoWaitingForItIsSettled()
{
await using var fx = await CreateAsync(context);
var (id, photos) = await UploadedAsync(fx, 2);
var engine = await fx.StartEngineAsync();
var replaced = await ReplaceAsync(fx, id, [0], 500);
var (entryFolder, recordPath) = FrameTrash.Location(fx.Paths, replaced.Name);
var record = await File.ReadAllTextAsync(recordPath, fx.Ct);
// Undone: the original is back in its frame, the conversion in an entry of its own.
await fx.Service.RestoreEntryAsync(fx.Archive.Id, replaced.Name, null, fx.Ct);
var undo = (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Single();
// As a crash right after the undo's sidecar was written leaves it: the entry its original came from still lists it,
// and the undo's completion waits for that entry's lease.
Directory.CreateDirectory(entryFolder);
await File.WriteAllTextAsync(recordPath, record, fx.Ct);
var sequence = (await fx.Db.Sequences.GetAsync(id))!;
var folder = fx.Paths.Sequence(sequence.Folder);
var manifest = Sidecar(fx, sequence);
var (undoFolder, undoRecord) = FrameTrash.Location(fx.Paths, undo.Name);
new FrameReplaceJournal(manifest.Versions.Frames - 1, fx.Paths.ToRelative(undoRecord), fx.Paths.ToRelative(undoFolder), [], [], false,
new ConsumedEntry(fx.Paths.ToRelative(recordPath), fx.Paths.ToRelative(entryFolder), SequenceTrash.EntryLease(replaced.Name), [manifest.Frames[0].Id],
null))
{
Phase = ReplacePhase.Written,
}.Write(folder);
var plan = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, [replaced.Name], fx.Ct);
Assert.Equal(replaced.Name, plan.Entries.Single().Name);
// The emptying settles the undo under the entry's lease before it reads the entry again, which takes the photo out of
// it: the entry is not erased as planned, and the sequence keeps its original.
var kept = await EmptyAsync(fx, engine, plan, JobState.Failed);
Assert.Contains(Loc.L("Archive.Log.TrashKept", replaced.Title), kept.LogTail);
Assert.FileMissing(folder.ReplaceJournalPath);
Assert.Equal(undo.Name, (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Single().Name);
Assert.Equal(Sha(photos[0]), Sha(folder.File(Sidecar(fx, sequence).Frames[0].File)));
}
[Test]
public async Task AnEntryNamesTheJobThatReplacedItsPhotos()
{
@@ -252,6 +252,51 @@ public sealed class JobEngineTests(TestContext context)
Assert.Empty((await db.Jobs.ListAsync(null, JobKind.LightAnalyse)).Items);
}
/// <summary>
/// A follow-up of work already done (a sync download's frame swapped to another encoding, whose thumbnails it cleared) is
/// queued whatever stops its job meanwhile: a cancel arriving right after the work leaves it queued, and it runs.
/// </summary>
[Test]
public async Task AFollowUpQueuedWhateverStopsItsJobOutlivesACancel()
{
await using var db = await OpenAsync();
var target = Guid.CreateVersion7();
var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var queued = new TaskCompletionSource<Job?>(TaskCreationOptions.RunContinuationsAsynchronously);
var download = new CallbackHandler(JobKind.Scan, async c =>
{
started.TrySetResult();
try
{
await Task.Delay(Timeout.InfiniteTimeSpan, c.Cancellation);
}
catch (OperationCanceledException)
{
// The work is done; the cancel came before its follow-up was queued.
}
try
{
queued.TrySetResult(await c.EnqueueFollowUpAsync(JobKind.Thumbs, [target], "Roof", null, JobPriority.Background, CancellationToken.None));
}
catch (Exception ex)
{
queued.TrySetException(ex);
}
c.Cancellation.ThrowIfCancellationRequested();
});
await using var engine = new JobEngine(db, [download, new CountingHandler(JobKind.Thumbs, 1)],
new JobEngineOptions { Workers = 1, WorkerId = "t", PollInterval = TimeSpan.FromMilliseconds(50) });
await engine.StartAsync();
var job = await engine.EnqueueAsync(JobKind.Scan, []);
await started.Task.WaitAsync(TimeSpan.FromSeconds(10));
await engine.CancelAsync(job.Id);
var followUp = Assert.NotNull(await queued.Task.WaitAsync(TimeSpan.FromSeconds(10)), "queued although its job was cancelled");
await WaitForStateAsync(db, job.Id, JobState.Cancelled, TimeSpan.FromSeconds(5));
Assert.SequenceEqual([target], (await WaitForStateAsync(db, followUp.Id, JobState.Done, TimeSpan.FromSeconds(10))).TargetIds);
}
/// <summary>Waits until <paramref name="condition"/> holds, failing with <paramref name="what"/> after ten seconds.</summary>
private static async Task UntilAsync(Func<bool> condition, string what)
{
@@ -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()
{
@@ -5,6 +5,7 @@ using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Data.Archiving;
using Chronos.Data.Sync;
using Chronos.Data.Tests.Archiving;
using Chronos.Protocol;
@@ -180,7 +181,7 @@ public sealed class SyncTransferTests(TestContext context)
var kept = await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct);
Assert.True(kept.Select(k => k.Sha256).ToHashSet().SetEquals(photos[1..].Select(Sha)), "the photo deleted here stays deleted");
Assert.True(await f.Db.FrameRemovals.IsRemovedAsync(local.Id, Sha(photos[0])), "and keeps its tombstone");
Assert.Contains("deleted on this PC, not downloaded", done.LogTail);
Assert.Contains(Loc.L("Archive.Log.SyncDeletedHere", remote.Frames.Single(fr => fr.Sha256 == Sha(photos[0])).FileName), done.LogTail);
Assert.False(Directory.Exists(Path.Combine(f.Archive.Paths.StagingDirectory, "sync-" + remote.Id.ToString("N"))), "staging cleaned up");
}
@@ -207,7 +208,7 @@ public sealed class SyncTransferTests(TestContext context)
var done = await f.Archive.WaitForAsync(job.Id, JobState.Done);
Assert.Equal(3, remote.Frames.Count);
Assert.Contains("deleted on the server, not uploaded", done.LogTail);
Assert.Contains(Loc.L("Archive.Log.SyncDeletedThere", "DSC_0004.JPG"), done.LogTail);
// Its hash is in the index now: the comparison leaves it out, so the row settles instead of offering Upload for good.
Assert.True((await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct)).All(fr => fr.Sha256 is not null), "hashed by the verify");
var entry = await f.EntryAsync(local.DisplayTitle);
@@ -881,6 +882,36 @@ public sealed class SyncTransferTests(TestContext context)
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status);
}
[Test]
public async Task AFrameThatTookBackItsPhotoInAnotherEncodingIsDrawnAgain()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Harbour", photos);
var engine = await f.StartEngineAsync();
var drawn = await engine.EnqueueAsync(ArchiveJobs.Thumbnails([local.Id], "Harbour"), cancellationToken: f.Ct);
await f.Archive.WaitForAsync(drawn.Id, JobState.Done);
var lost = (await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct))[1];
File.Delete(f.Archive.Paths.FromRelative(lost.RelativePath));
await f.Archive.Service.Verifier.VerifyAsync(f.Archive.Archive, [local.Id], default, (_, _, _) => ValueTask.CompletedTask, cancellationToken: f.Ct);
Assert.True(((await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.Status & SequenceStatus.ThumbsBuilt) != 0, "drawn before");
// The server converted that photo.
var converted = f.NewPhotos(1)[0];
var remote = f.Remote.Add("Harbour", [photos[0], converted, photos[2]]);
remote.Removed.Add(new RemovedPhotoDto(Sha(photos[1]), Sha(converted), "replaced", DateTimeOffset.UtcNow));
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Harbour", SyncDownloadMode.Originals, null);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
// Nothing was filed, only a frame swapped, which cleared what covered the sequence: the thumbnails it had are drawn again.
Assert.Equal(lost.Id, (await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct))[1].Id);
var again = Assert.Contains((await f.Db.Jobs.ListAsync(null, JobKind.Thumbs, 50, null, f.Ct)).Items, j => j.Id != drawn.Id && j.TargetIds.Contains(local.Id));
await f.Archive.WaitForAsync(again.Id, JobState.Done);
Assert.True(((await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.Status & SequenceStatus.ThumbsBuilt) != 0, "drawn again");
}
[Test]
public async Task AFrameTakesBackItsPhotoInAnotherEncodingOnlyWhereTheSequenceIsNow()
{