fix(archive): settle trash journals under their leases and say why restored photos stayed

Second fix round of owner review 2, phase 3 (engine, server, desktop).

- A photo never hashed whose original is missing can be deleted again: it goes
  into its trash record without a file and without a tombstone (nothing is left
  to name), stays listed until Empty erases it, and a restore keeps it with the
  reason "no file". FrameDeleteBlock.Unhashable now blocks only a present
  original that cannot be read; the API answers it as 409 photo_unreadable
  naming the photo, and every block has its own code and message.
- Deleting a whole sequence first settles an interrupted photo deletion,
  restore or ingest of it (ReadLocked under its lease), so no journal or half
  entry travels into the sequence's trash entry; it refuses while a restore
  into it waits for its busy entry.
- FrameTrash.Settle takes the photo entry's lease and leaves the journal for
  later while the entry is busy (an emptying), so it never races EraseAsync;
  meanwhile no other restore writes its journal over it and scans do not adopt
  its files.
- The hashes computed for frames that stay (to find a twin of a deleted photo)
  go into the sidecar and index, and only a frame whose first and last 64 KiB
  match a deleted photo's is read whole.
- A restore into a new sequence rewrites its record after each photo filed, so
  a crash or a database failure never leaves filed photos listed.
- An upload completion no longer has a window before the commit: the ingest
  checks the sidecar's tombstones under the sequence lease a deletion takes
  (IngestRequest.RefuseRemoved), unless the upload asked to bring it back.
- A restore reports each kept photo with its reason (no longer matches its
  record, could not be moved back, already in the sequence, had no file); the
  desktop line and the API message say so in en and it, and the tooltip holds
  the whole sentence. The desktop tells TrashMismatchException by its type.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 1858f1f450a35fb8383ede8d80ce5f8de9b7ceac)
This commit is contained in:
Alby96 committed 2026-10-27 13:53:41 +01:00
1 parent a133306fb0
commit 4518ffe655
29 files changed
+856 -162

No files matched your search

@@ -171,7 +171,9 @@ public sealed class TrashDialogTests(TestContext context)
await RestoreAsync(Only(dialog.Rows));
Assert.Equal(Loc.Plural("Archive.Trash.KeptFiles", 1), dialog.ErrorText, "the sentence itself, not a generic file error");
Assert.Equal(Loc.Plural("Archive.Trash.Kept.Mismatch", 1), dialog.ErrorText, "the sentence itself, not a generic file error");
// The line may cut the sentence: the tooltip holds it whole, then the photo's name.
Assert.True(dialog.ErrorToolTip!.StartsWith(dialog.ErrorText + Environment.NewLine, StringComparison.Ordinal), dialog.ErrorToolTip);
Assert.Contains(frames[2].OriginalFileName ?? Path.GetFileName(frames[2].RelativePath), dialog.ErrorToolTip);
Assert.Equal(1, restored, "the other photo came back");
var left = Only(dialog.Rows);
@@ -200,13 +202,47 @@ public sealed class TrashDialogTests(TestContext context)
await RestoreAsync(Only(dialog.Rows));
Assert.Equal(Loc.L("Archive.Error.TrashMismatch"), dialog.ErrorText, "the sentence itself, not a generic file error");
Assert.Equal(dialog.ErrorText, dialog.ErrorToolTip, "the whole sentence, once");
Assert.Equal(0, restored);
Assert.Equal(2, Only(dialog.Rows).Entry.Frames);
Assert.Equal(2, (await fx.Db.Sequences.GetAsync(sequence.Id))!.FrameCount);
// Any other invalid data (a sidecar of another sequence, say) still reads as a file error.
// Told by its type: an IOException that merely carries the same words, or any other invalid data (a sidecar of
// another sequence, say), still reads as a file error.
Assert.Equal(Loc.L("Archive.Error.TrashMismatch"), ArchiveFailures.Cause(new TrashMismatchException()));
Assert.Equal(Loc.L("Archive.Failed.Files"), ArchiveFailures.Cause(new IOException(Loc.L("Archive.Error.TrashMismatch"))));
Assert.Equal(Loc.L("Archive.Failed.Files"), ArchiveFailures.Cause(new InvalidDataException("sequence.json belongs to sequence 42, not 43.")));
}
[Test]
public void WhatARestoreKeptSaysWhyForEachReasonAndNamesThePhotos()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
// One reason: its sentence on the line, repeated whole in the tooltip above the names.
var (one, oneTip) = TrashDialogViewModel.KeptText([new KeptPhoto("IMG_0001.CR3", KeptReason.NotMoved), new KeptPhoto("IMG_0002.CR3", KeptReason.NotMoved)]);
Assert.Equal(Loc.Plural("Archive.Trash.Kept.NotMoved", 2), one);
Assert.Equal(string.Join(Environment.NewLine, one, Formatting.LeftToRight("IMG_0001.CR3"), Formatting.LeftToRight("IMG_0002.CR3")), oneTip);
// Several reasons: how many stayed on the line; each reason's sentence in the tooltip, names counted past the list.
var kept = Enumerable.Range(0, DeletePlans.ListedLines + 3)
.Select(i => new KeptPhoto($"IMG_{i:0000}.JPG", i % 3 == 0 ? KeptReason.InSequence : i % 3 == 1 ? KeptReason.Mismatch : KeptReason.NoFile)).ToList();
var (several, tip) = TrashDialogViewModel.KeptText(kept);
Assert.Equal(Loc.Plural("Archive.Trash.KeptPhotos", kept.Count), several);
var lines = tip.Split(Environment.NewLine);
Assert.Equal(several, lines[0]);
foreach (var reason in new[] { KeptReason.Mismatch, KeptReason.InSequence, KeptReason.NoFile })
Assert.Contains(KeptPhoto.Sentence(reason, kept.Count(k => k.Reason == reason), Loc.Culture), lines);
Assert.DoesNotContain(Loc.Plural("Archive.Trash.Kept.NotMoved", 1), lines);
Assert.Equal(Loc.Plural("Archive.Trash.KeptMore", 3), lines[^1]);
Assert.Equal(DeletePlans.ListedLines, lines.Count(l => l.Contains("IMG_", StringComparison.Ordinal)));
// Italian counts photos, which are feminine.
var italian = CultureInfo.GetCultureInfo("it");
Assert.Equal("1 foto è rimasta nel cestino: non corrisponde più al suo registro.", KeptPhoto.Sentence(KeptReason.Mismatch, 1, italian));
Assert.Equal("3 foto sono rimaste nel cestino: la sequenza le contiene già.", KeptPhoto.Sentence(KeptReason.InSequence, 3, italian));
Assert.Equal("+ altre 3", Loc.Text("Archive.Trash.KeptMore", [3], italian));
Assert.Equal("+ un'altra", Loc.Text("Archive.Trash.KeptMore", [1], italian));
}
private static TrashRowViewModel Only(IReadOnlyList<TrashRowViewModel> rows)
{
Assert.Count(1, rows);
@@ -258,7 +258,7 @@ public abstract class FrameTrashTests(TestContext context) : DatabaseTest(contex
var restored = await fx.Service.RestoreEntryAsync(fx.Archive.Id, deleted.Entry.Name, null, fx.Ct);
Assert.Equal(1, restored.Photos);
Assert.SequenceEqual([frames[2].OriginalFileName!], restored.Kept);
Assert.SequenceEqual([new KeptPhoto(frames[2].OriginalFileName!, KeptReason.Mismatch)], restored.Kept);
Assert.SequenceEqual([frames[0].Id, frames[1].Id, frames[3].Id], (await fx.Db.Frames.ListBySequenceAsync(sequence.Id)).Select(f => f.Id));
Assert.SequenceEqual([frames[2].Sha256], (await fx.Db.FrameRemovals.ListBySequenceAsync(sequence.Id)).Select(r => r.Sha256));
var left = Assert.Contains(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct), e => e.Name == deleted.Entry.Name);
@@ -705,7 +705,7 @@ public abstract class FrameTrashTests(TestContext context) : DatabaseTest(contex
var restored = await fx.Service.RestoreEntryAsync(fx.Archive.Id, deleted.Entry.Name, null, fx.Ct);
Assert.Equal(0, restored.Photos);
Assert.SequenceEqual([frames[1].OriginalFileName!], restored.Kept);
Assert.SequenceEqual([new KeptPhoto(frames[1].OriginalFileName!, KeptReason.NotMoved)], restored.Kept);
Assert.FileMissing(photo);
Assert.FileMissing(folder.RestoreJournalPath);
var entryFolder = EntryFolder(fx, deleted.Entry);
@@ -806,13 +806,92 @@ public abstract class FrameTrashTests(TestContext context) : DatabaseTest(contex
Assert.True(await fx.Db.FrameRemovals.IsRemovedAsync(sequence.Id, sha));
Assert.Equal(sha, Sha(Path.Combine(EntryFolder(fx, deleted.Entry), "originals", Path.GetFileName(frames[1].RelativePath))));
// One whose original is gone as well could leave none: the plan refuses it, and says which.
// One whose original is gone as well has no content left to name: it goes without a file and without a tombstone,
// and its record stays in the trash, listed until Empty erases it (nothing can bring it back).
var third = Sha(fx.Paths.FromRelative(frames[2].RelativePath));
File.Delete(fx.Paths.FromRelative(frames[3].RelativePath));
var row = (await fx.Db.Sequences.GetAsync(sequence.Id))!;
var refused = await fx.Service.FrameTrash.PlanDeleteAsync(sequence.Id, [frames[2].Id, frames[3].Id], row.FramesVersion, fx.Ct);
Assert.SequenceEqual([FrameDeleteBlock.Unhashable], refused.Blocked);
Assert.SequenceEqual([frames[3].Id], refused.Unhashable.Select(f => f.Id));
await Assert.ThrowsAsync<StaleDeletePlanException>(() => fx.Service.FrameTrash.DeleteAsync(refused, null, null, fx.Ct));
var gone = await DeleteAsync(fx, (await fx.Db.Sequences.GetAsync(sequence.Id))!, frames[2], frames[3]);
Assert.Equal((2, 1), (gone.Entry.Frames, gone.Entry.Files));
Assert.SequenceEqual(new[] { sha, third }.Order(), Assert.NotNull(ManifestStore.ReadSequence(folder.ManifestPath).Removed).Select(r => r.Sha256).Order());
Assert.SequenceEqual([frames[0].Id], ManifestStore.ReadSequence(folder.ManifestPath).Frames.Select(f => f.Id));
var restored = await fx.Service.RestoreEntryAsync(fx.Archive.Id, gone.Entry.Name, null, fx.Ct);
Assert.Equal(1, restored.Photos);
Assert.SequenceEqual([KeptReason.NoFile], restored.Kept.Select(k => k.Reason));
var left = Assert.Contains(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct), e => e.Name == gone.Entry.Name);
Assert.Equal((1, 0), (left.Frames, left.Files));
await Assert.ThrowsAsync<TrashMismatchException>(() => fx.Service.RestoreEntryAsync(fx.Archive.Id, gone.Entry.Name, null, fx.Ct));
var plan = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, [gone.Entry.Name], fx.Ct);
var items = plan.Entries.Select(e => new EmptyTrashItem(e.Name, SequenceTrash.EntryFingerprint(e))).ToList();
var emptied = await fx.Service.Trash.EmptyAsync(fx.Archive, new EmptyTrashParameters(items, plan.Fingerprint), 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
Assert.Equal(1, emptied.Erased);
Assert.DoesNotContain(gone.Entry.Name, (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Select(e => e.Name));
}
[Test]
[WindowsOnly]
public async Task APhotoNeverHashedThatCannotBeReadWaitsUntilItCan()
{
var fx = await FixtureAsync();
var (sequence, frames) = await AdoptedAsync(fx, "Shoot", 3);
var original = fx.Paths.FromRelative(frames[1].RelativePath);
var sha = Sha(original);
// Another program holds it: it could not be hashed for its tombstone, so the plan refuses it and says which.
using (new FileStream(original, FileMode.Open, FileAccess.Read, FileShare.None))
{
var refused = await fx.Service.FrameTrash.PlanDeleteAsync(sequence.Id, [frames[1].Id], sequence.FramesVersion, fx.Ct);
Assert.SequenceEqual([FrameDeleteBlock.Unhashable], refused.Blocked);
Assert.SequenceEqual([frames[1].Id], refused.Unhashable.Select(f => f.Id));
await Assert.ThrowsAsync<StaleDeletePlanException>(() => fx.Service.FrameTrash.DeleteAsync(refused, null, null, fx.Ct));
}
Assert.Equal(sha, Sha(original));
await DeleteAsync(fx, sequence, frames[1]);
Assert.True(await fx.Db.FrameRemovals.IsRemovedAsync(sequence.Id, sha));
}
[Test]
public async Task AFrameThatStaysHashedToFindATwinKeepsItsHashAndOnlyLikelyTwinsAreReadWhole()
{
var fx = await FixtureAsync();
var shoot = Path.Combine(fx.Archive.RootPath, "Raw");
Directory.CreateDirectory(shoot);
// Originals of one size, as uncompressed raw files are: only one whose first and last 64 KiB match a deleted photo's
// is read whole.
const int Size = 300_000;
static byte[] Padded(int seed)
{
var bytes = new byte[Size];
Photos.Jpeg(Start, seed).CopyTo(bytes, 0);
return bytes;
}
var deleted = Padded(1);
var near = (byte[])deleted.Clone();
near[Size / 2] ^= 0xFF;
File.WriteAllBytes(Path.Combine(shoot, "IMG_0001.JPG"), Padded(2));
File.WriteAllBytes(Path.Combine(shoot, "IMG_0002.JPG"), deleted);
File.WriteAllBytes(Path.Combine(shoot, "IMG_0003.JPG"), deleted);
File.WriteAllBytes(Path.Combine(shoot, "IMG_0004.JPG"), near);
await fx.ScanAsync();
var id = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Single(l => l.Folder == "Raw").Id;
var frames = await fx.Db.Frames.ListBySequenceAsync(id);
Assert.True(frames.All(f => f.Sha256 is null), "adopted, not verified");
await DeleteAsync(fx, (await fx.Db.Sequences.GetAsync(id))!, frames.Single(f => f.RelativePath.EndsWith("IMG_0002.JPG", StringComparison.Ordinal)));
var sidecar = ManifestStore.ReadSequence(fx.Paths.Sequence("Raw").ManifestPath);
Assert.Null(sidecar.Removed, "its twin stays");
string? InSidecar(string name) => sidecar.Frames.Single(f => f.File.EndsWith(name, StringComparison.Ordinal)).Sha256;
Assert.Equal(Convert.ToHexStringLower(SHA256.HashData(deleted)), InSidecar("IMG_0003.JPG"));
Assert.Equal(Convert.ToHexStringLower(SHA256.HashData(near)), InSidecar("IMG_0004.JPG"));
Assert.Null(InSidecar("IMG_0001.JPG"), "its first 64 KiB differ: never read whole");
// The index holds the hashes too, so a later deletion does not read those files again.
var now = await fx.Db.Frames.ListBySequenceAsync(id);
Assert.Equal(InSidecar("IMG_0003.JPG"), now.Single(f => f.RelativePath.EndsWith("IMG_0003.JPG", StringComparison.Ordinal)).Sha256);
Assert.Null(now.Single(f => f.RelativePath.EndsWith("IMG_0001.JPG", StringComparison.Ordinal)).Sha256);
}
[Test]
@@ -974,6 +1053,148 @@ public abstract class FrameTrashTests(TestContext context) : DatabaseTest(contex
Assert.FileExists(Path.Combine(SequenceTrash.TrashDirectory(fx.Paths), names[1], "added.bin"));
}
[Test]
public async Task ASequenceDeletedAfterAnInterruptedPhotoDeletionTakesNoHalfEntryAlong()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 3);
var folder = fx.Paths.Sequence(sequence.Folder);
// As a photo deletion leaves it when the process dies after its first move: journal, pending record, one file moved.
var name = $"{sequence.Id:N}-20261027120000";
var entry = Path.Combine(FrameTrash.Directory(fx.Paths), name);
var record = entry + ".json";
var sidecar = ManifestStore.ReadSequence(folder.ManifestPath).Frames.Take(2).ToList();
var files = sidecar.Select(f => new TrashedFile(f.File, "originals/" + Path.GetFileName(f.File), f.Size, f.Sha256)).ToList();
Directory.CreateDirectory(Path.Combine(entry, "originals"));
File.WriteAllText(FrameRemovalJournal.PendingRecord(record), JsonSerializer.Serialize(new PhotoTrashRecord(TrashKind.Photos, sequence.Id, sequence.DisplayTitle,
sequence.Folder, [.. sidecar.Zip(files, (f, t) => new TrashedPhoto(f, [t], null))], files.Sum(f => f.Size), DateTimeOffset.UtcNow, "alberto"),
TrashJson.Default.PhotoTrashRecord));
var moves = files.Select(f => new FrameRemovalMove(f.From, fx.Paths.ToRelative(Path.Combine(entry, f.Path)))).ToList();
FrameRemovalJournal.Write(folder, new FrameRemovalJournal(fx.Paths.ToRelative(record), fx.Paths.ToRelative(entry), [.. sidecar.Select(f => f.Id)], moves));
File.Move(folder.File(moves[0].From), fx.Paths.FromRelative(moves[0].To));
await DeleteSequenceAsync(fx, sequence.Id);
// The deletion was undone first: every photo went with its sequence, and neither its journal nor half an entry is left.
var deleted = Assert.Contains(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct), e => e.Kind == TrashKind.Sequence);
var trashed = fx.Paths.Sequence(".chronos/trash/" + deleted.Name);
Assert.FileMissing(trashed.RemovalJournalPath);
foreach (var frame in frames) Assert.Equal(frame.Sha256, Sha(trashed.File(frame.RelativePath[(sequence.Folder.Length + 1)..])));
Assert.False(Directory.Exists(entry));
Assert.FileMissing(FrameRemovalJournal.PendingRecord(record));
Assert.DoesNotContain(TrashKind.Photos, (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Select(e => e.Kind));
}
[Test]
public async Task ARestoreWhoseEntryIsBusyWaitsAndNothingGoesOnOverIt()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 5);
var folder = fx.Paths.Sequence(sequence.Folder);
var deleted = await DeleteAsync(fx, sequence, frames[1], frames[2]);
var other = await DeleteAsync(fx, (await fx.Db.Sequences.GetAsync(sequence.Id))!, frames[3]);
// A restore died after moving one original back, before the sidecar; the entry is being emptied meanwhile.
var journal = RestoreJournal(fx, deleted.Entry);
journal.Write(folder);
var moved = journal.Photos[0].Moves[0];
File.Move(fx.Paths.FromRelative(moved.To), folder.File(moved.From));
using (Assert.NotNull(LeaseFile.TryAcquire(fx.Paths.LocksDirectory, SequenceTrash.EntryLease(deleted.Entry.Name), "other")))
{
// Another writer leaves the journal for later: it never moves a file into an entry being erased.
await fx.Service.SetSequenceInfoAsync(sequence.Id, "Harbour", [], 0, null, fx.Ct);
Assert.FileExists(folder.RestoreJournalPath);
Assert.FileExists(folder.File(moved.From));
Assert.FileMissing(fx.Paths.FromRelative(moved.To));
// A scan does not adopt the photo that restore moved in.
File.SetLastWriteTimeUtc(folder.File(moved.From), DateTime.UtcNow);
await fx.ScanAsync();
Assert.Count(2, await fx.Db.Frames.ListBySequenceAsync(sequence.Id));
// Neither a restore of another entry into the sequence nor the sequence's deletion goes on over it.
await Assert.ThrowsAsync<LeaseUnavailableException>(() => fx.Service.RestoreEntryAsync(fx.Archive.Id, other.Entry.Name, null, fx.Ct));
await Assert.ThrowsAsync<LeaseUnavailableException>(() => DeleteSequenceAsync(fx, sequence.Id));
Assert.FileExists(folder.RestoreJournalPath);
Assert.FileExists(folder.ManifestPath);
}
// Once the entry is free, the next writer settles it: the original goes back into its entry, and both entries come back.
await fx.Service.SetSequenceInfoAsync(sequence.Id, "Harbour", [], 0, null, fx.Ct);
Assert.FileMissing(folder.RestoreJournalPath);
Assert.Equal(frames[1].Sha256, Sha(fx.Paths.FromRelative(moved.To)));
Assert.FileMissing(folder.File(moved.From));
Assert.Equal(2, (await fx.Service.RestoreEntryAsync(fx.Archive.Id, deleted.Entry.Name, null, fx.Ct)).Photos);
Assert.Equal(1, (await fx.Service.RestoreEntryAsync(fx.Archive.Id, other.Entry.Name, null, fx.Ct)).Photos);
Assert.SequenceEqual(frames.Select(f => f.Id), (await fx.Db.Frames.ListBySequenceAsync(sequence.Id)).Select(f => f.Id));
}
[Test]
public async Task ARestoreIntoANewSequenceStoppedBetweenPhotosKeepsItsRecordTrue()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 4);
var first = await DeleteAsync(fx, sequence, frames[1]);
var second = await DeleteAsync(fx, (await fx.Db.Sequences.GetAsync(sequence.Id))!, frames[2], frames[3]);
await DeleteSequenceAsync(fx, sequence.Id);
var made = await fx.Service.RestoreEntryAsync(fx.Archive.Id, first.Entry.Name, null, fx.Ct);
Assert.True(made.NewSequence);
var entryFolder = EntryFolder(fx, second.Entry);
var staged = Path.Combine(entryFolder, ".restoring", "originals", Path.GetFileName(frames[2].RelativePath));
using var cancel = CancellationTokenSource.CreateLinkedTokenSource(fx.Ct);
// The new sequence is held while the first photo waits to be filed into it, and the restore is cancelled meanwhile.
Task restore;
using (Assert.NotNull(LeaseFile.TryAcquire(fx.Paths.LocksDirectory, $"seq-{made.Sequence.Id:N}", "other")))
{
restore = fx.Service.RestoreEntryAsync(fx.Archive.Id, second.Entry.Name, null, cancel.Token);
var until = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(20));
while (!File.Exists(staged))
{
Assert.True(DateTime.UtcNow < until, "the first photo was never staged");
await Task.Delay(10, fx.Ct);
}
cancel.Cancel();
}
await Assert.ThrowsAsync<OperationCanceledException>(() => restore);
// The first photo is filed, the second stays, and the record lists exactly what is left.
Assert.SequenceEqual([frames[1].Sha256, frames[2].Sha256], (await fx.Db.Frames.ListBySequenceAsync(made.Sequence.Id)).Select(f => f.Sha256));
var record = Assert.NotNull(FrameTrash.ReadEntry(fx.Paths, second.Entry.Name));
Assert.SequenceEqual([frames[3].Id], record.Photos.Select(p => p.Frame.Id));
Assert.Equal(frames[3].Size, record.Bytes);
Assert.Equal(frames[3].Sha256, Sha(Path.Combine(entryFolder, "originals", Path.GetFileName(frames[3].RelativePath))));
Assert.False(Directory.Exists(Path.Combine(entryFolder, ".restoring")));
var rest = await fx.Service.RestoreEntryAsync(fx.Archive.Id, second.Entry.Name, null, fx.Ct);
Assert.Equal((1, made.Sequence.Id), (rest.Photos, rest.Sequence.Id));
Assert.Empty(rest.Kept);
Assert.False(Directory.Exists(entryFolder));
}
[Test]
public async Task AnIngestThatRefusesRemovedContentChecksTheTombstonesUnderTheLease()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 3);
await DeleteAsync(fx, sequence, frames[1]);
// The same photo staged again (an upload whose completion checked the index before the deletion landed).
var (path, size, sha) = fx.Stage(Start.AddSeconds(10), 101);
Assert.Equal(frames[1].Sha256, sha);
var request = new IngestRequest(fx.Archive.Id, sequence.Id, null, null, path, frames[1].OriginalFileName!, size, sha, null, null, RefuseRemoved: true);
var refused = await Assert.ThrowsAsync<PhotoRemovedException>(() => fx.Service.Ingest.CommitAsync(request, fx.Ct));
Assert.Equal(sequence.Id, refused.SequenceId);
Assert.FileExists(path);
Assert.Count(2, ManifestStore.ReadSequence(fx.Paths.Sequence(sequence.Folder).ManifestPath).Frames);
Assert.True(await fx.Db.FrameRemovals.IsRemovedAsync(sequence.Id, sha));
// Asked back, it is filed and its tombstone goes.
var back = await fx.Service.Ingest.CommitAsync(request with { RefuseRemoved = false }, fx.Ct);
Assert.False(back.Duplicate);
Assert.False(await fx.Db.FrameRemovals.IsRemovedAsync(sequence.Id, sha));
Assert.Count(3, await fx.Db.Frames.ListBySequenceAsync(sequence.Id));
}
/// <summary>An entry of originals a conversion replaced (a later phase), its one photo replaced by <paramref name="replacement"/>.</summary>
private static string WriteReplaced(ArchiveFixture fx, Sequence sequence, string stamp, string replacement)
{
@@ -4,6 +4,7 @@ using System.Net.Http.Json;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Protocol;
using Chronos.Server.Storage;
using Chronos.Testing;
@@ -274,6 +275,73 @@ public sealed class LibraryTests(TestContext context)
Assert.Null(await server.Database.Sequences.GetAsync(t));
}
[Test]
public async Task ARestoreSaysWhichPhotosStayedAndWhy()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var admin = await server.AdminAsync();
Guid id = default;
for (var i = 0; i < 4; i++) id = (await Uploads.UploadAsync(editor, Photo(120 + i), $"IMG_{i + 1:0000}.JPG", sessionKey: "kept")).SequenceId;
await UntilIdleAsync(server);
var frames = await server.Database.Frames.ListBySequenceAsync(id);
string name;
using (var deleted = await editor.PostAsJsonAsync($"/api/v1/sequences/{id}/frames/delete", new FrameDeleteRequest([frames[1].Id, frames[2].Id], null, false),
ProtocolJson.Default.FrameDeleteRequest))
name = Assert.NotNull((await deleted.ReadAsync(ProtocolJson.Default.FrameDeleteResultDto)).TrashEntry);
await UntilIdleAsync(server);
var trashed = Path.Combine(PhotoEntryFolder(server, name), "originals", Path.GetFileName(frames[2].RelativePath));
var bytes = await File.ReadAllBytesAsync(trashed, context.Cancellation);
bytes[^10] ^= 0x01;
await File.WriteAllBytesAsync(trashed, bytes, context.Cancellation);
using var restored = await admin.PostAsync($"/api/v1/archive/trash/{name}/restore", null);
var result = await restored.ReadAsync(ProtocolJson.Default.TrashRestoreDto);
Assert.Equal(1, result.Photos);
Assert.SequenceEqual([frames[2].OriginalFileName!], result.Kept);
Assert.SequenceEqual(["mismatch"], Assert.NotNull(result.KeptReasons));
Assert.Equal(KeptPhoto.Sentence(KeptReason.Mismatch, 1, System.Globalization.CultureInfo.GetCultureInfo("en")), result.Message);
}
[Test]
[WindowsOnly]
public async Task APhotoNeverHashedIsDeletedUnlessItCannotBeRead()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var admin = await server.AdminAsync();
// Photos copied into the archive by hand and scanned: adopted, never hashed.
var shoot = Path.Combine(server.Options.ArchivePath, "Shoot");
Directory.CreateDirectory(shoot);
for (var i = 0; i < 3; i++) await File.WriteAllBytesAsync(Path.Combine(shoot, $"IMG_{i + 1:0000}.JPG"), Photo(130 + i), context.Cancellation);
var archives = server.Services.GetRequiredService<ArchiveService>();
await archives.Indexer.ScanAsync(server.Services.GetRequiredService<ServerArchive>().Current, ScanMode.Incremental, null, _ => ValueTask.CompletedTask,
context.Cancellation);
await UntilIdleAsync(server);
var id = (await server.Database.Sequences.ListLocationsAsync(server.Services.GetRequiredService<ServerArchive>().Id)).Single(l => l.Folder == "Shoot").Id;
var frames = await server.Database.Frames.ListBySequenceAsync(id);
Assert.True(frames.All(f => f.Sha256 is null), "adopted, not verified");
var url = $"/api/v1/sequences/{id}/frames/delete";
// Another program holds one: it cannot be hashed for its tombstone, and the answer names it (no frames_conflict loop).
var held = Path.Combine(server.Options.ArchivePath, frames[1].RelativePath);
using (new FileStream(held, FileMode.Open, FileAccess.Read, FileShare.None))
{
using var refused = await admin.PostAsJsonAsync(url, new FrameDeleteRequest([frames[1].Id], null, false), ProtocolJson.Default.FrameDeleteRequest);
var error = await refused.ExpectErrorAsync(HttpStatusCode.Conflict, "photo_unreadable");
Assert.Equal("1", error.Details);
Assert.Contains("IMG_0002.JPG", error.Message);
}
Assert.FileExists(held);
// One whose original is gone has nothing left to hash: it goes, without a tombstone.
File.Delete(Path.Combine(server.Options.ArchivePath, frames[2].RelativePath));
using (var gone = await admin.PostAsJsonAsync(url, new FrameDeleteRequest([frames[2].Id], null, false), ProtocolJson.Default.FrameDeleteRequest))
Assert.NotNull((await gone.ReadAsync(ProtocolJson.Default.FrameDeleteResultDto)).TrashEntry);
Assert.Empty(await server.Database.FrameRemovals.ListBySequenceAsync(id));
Assert.SequenceEqual([frames[0].Id, frames[1].Id], (await server.Database.Frames.ListBySequenceAsync(id)).Select(f => f.Id));
}
[Test]
public async Task APhotoDeleteTakesAsManyIdsAsItsLimit()
{
@@ -8,6 +8,7 @@ using Microsoft.Extensions.DependencyInjection;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Protocol;
using Chronos.Server.Storage;
using Chronos.Testing;
@@ -228,6 +229,42 @@ public sealed class BrowserUploadTests(TestContext context)
Assert.SequenceEqual([keeper.FrameId], (await server.Database.Frames.ListBySequenceAsync(sequence.Id)).Select(f => f.Id));
}
[Test]
public async Task APhotoDeletedBetweenTheCompletionsCheckAndItsCommitIsNotFiled()
{
// The completion asks the index first; a deletion that lands after that and before the commit is caught by the
// ingest itself, which asks the sidecar's tombstones under the lease the deletion takes.
GatedIngest? gate = null;
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = Chunk, s =>
{
ArchiveModule.Register(s);
s.AddSingleton<IArchiveIngest>(sp => gate = new GatedIngest(sp.GetRequiredService<ArchiveService>().Ingest));
});
var browser = await Browser.SignInAsync(server);
var sequence = await CreateAsync(browser, "Roof");
var photo = Photo(17);
var sha = Uploads.Sha(photo);
var keeper = await UploadAsync(browser, sequence.Id, "IMG_0000.JPG", Photo(18));
var first = await UploadAsync(browser, sequence.Id, "IMG_0001.JPG", photo);
await UntilIdleAsync(server);
var frame = Assert.NotNull(await server.Database.Frames.GetAsync(first.FrameId));
File.Delete(Path.Combine(server.Options.ArchivePath, frame.RelativePath));
var repair = await StartAsync(browser, sequence.Id, "IMG_0001.JPG", photo, HttpStatusCode.Created);
var id = Assert.NotNull(repair.UploadId);
await SendChunksAsync(browser, id, photo);
Assert.NotNull(gate).BeforeCommit = () => DeleteAsync(server, browser, sequence.Id, first.FrameId);
using (var complete = await CompleteAsync(browser, id))
await complete.ExpectErrorAsync(HttpStatusCode.Conflict, UploadErrors.PhotoRemoved);
Assert.SequenceEqual([keeper.FrameId], (await server.Database.Frames.ListBySequenceAsync(sequence.Id)).Select(f => f.Id));
Assert.True(await server.Database.FrameRemovals.IsRemovedAsync(sequence.Id, sha), "the tombstone stays");
Assert.False(server.Services.GetRequiredService<UploadStore>().Exists(id), "the partial file is gone");
Assert.FileMissing(Path.Combine(server.Options.StagingPath, id.ToString("N") + ".jpg"));
using (var late = await CompleteAsync(browser, id))
await late.ExpectErrorAsync(HttpStatusCode.Conflict, "upload_state");
}
[Test]
public async Task AStaleTombstoneBesideAFrameOfTheSameContentRefusesNoRepair()
{
@@ -426,6 +463,22 @@ public sealed class BrowserUploadTests(TestContext context)
}
}
/// <summary>The archive's ingest with a step run once before the next commit (what lands between the completion's checks and it).</summary>
private sealed class GatedIngest(IArchiveIngest inner) : IArchiveIngest
{
public Func<Task>? BeforeCommit { get; set; }
public async Task<IngestResult> CommitAsync(IngestRequest request, CancellationToken cancellationToken = default)
{
if (BeforeCommit is { } step)
{
BeforeCommit = null;
await step();
}
return await inner.CommitAsync(request, cancellationToken);
}
}
/// <summary>A JPEG of a few chunks: noise does not compress below the chunk size.</summary>
private static byte[] Photo(int seed)
{