feat(archive): photo delete, tombstones, trash kinds and emptying, library API

Owner review 2, R6: the web panel manages the library without editing it, so
the engine and the server must delete single photos safely, keep them out of
sync afterwards, and let an administrator restore or finally erase the trash.

- Migration 0008: frame_removals (tombstones by sequence and SHA-256, reason,
  replacement); the sidecar gains "removed" (omitted when empty) and frames a
  reserved "source"; the indexer writes the tombstones on every sync, so a
  rebuild keeps them, and drops a hero frame that is gone.
- FrameTrash: dry run (busy, frames changed, offline, would empty), delete under
  the sequence lease with a write-ahead journal that the next writer undoes
  after a crash, files to trash/photos/<seq>-<time>/originals with a record,
  sidecar without the frames plus tombstones, index sync clearing analyses,
  thumbnails and proxies, proxies renamed to follow their frames, follow-up
  jobs. Restore re-hashes every file, keeps mismatches in the trash, puts the
  same frame records back and drops their tombstones, or files the photos into
  a new sequence through the ingest when theirs is gone.
- Project positions on vanished photos are translated by photo and wait as
  pending frames, so they come back with a restore.
- Trash entries have a kind (sequence, photos, replaced); emptying is a dry run
  with a fingerprint and a new EmptyTrash job (18) that erases exactly the
  planned entries, refuses a stale plan and erases replaced originals only
  while their replacements still hash right.
- Sync honours tombstones: nothing one side deleted is offered back, local
  files are never deleted, replaced photos count as their replacement; the
  server answers an upload of a tombstoned SHA-256 as already there.
- Server: sequence thumbnail, photo delete, bulk delete/retag/jobs, trash
  list/restore/empty endpoints with their error messages; a verify of
  sequences now targets their archive (POST /jobs failed before).
- Desktop trash dialog lists photo entries and empties the trash after a
  typed confirmation through the same job.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 35bb56690a1d69eae57153d036e1409201cd73f7)
This commit is contained in:
Alby96 committed 2026-10-27 10:49:34 +01:00
1 parent 4b9ba04fe4
commit 51782a3ada
63 files changed
+3303 -60

No files matched your search

@@ -0,0 +1,123 @@
using System.Globalization;
using System.IO;
using Chronos.App.Archiving;
using Chronos.App.Infrastructure;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Testing;
namespace Chronos.App.Tests.Archiving;
/// <summary>The trash dialog (owner review 2, R6): photo entries next to sequences, and Empty… behind a dry run and a typed confirmation.</summary>
public sealed class TrashDialogTests(TestContext context)
{
private static readonly DateTimeOffset Deleted = new(2026, 10, 27, 9, 30, 0, TimeSpan.Zero);
private static TrashEntry Entry(string title, TrashKind kind, int photos, long bytes) =>
new(Guid.CreateVersion7(), (kind == TrashKind.Sequence ? string.Empty : FrameTrash.EntryPrefix) + Guid.CreateVersion7().ToString("N"),
Guid.CreateVersion7(), title, "2026/" + title, photos, photos, bytes, Deleted, "alberto", kind);
[Test]
public void EveryKindOfEntryHasWordsAndTheRowSaysWhatItHolds()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
foreach (var kind in Enum.GetValues<TrashKind>())
Assert.NotEqual("Archive.Trash.Kind." + kind, TrashEmptyPlans.KindText(kind), "every kind has words");
var row = new TrashRowViewModel(Entry("Harbour sunset", TrashKind.Photos, 12, 340_000_000), new Chronos.Ui.Mvvm.RelayCommand(() => { }));
Assert.Equal(Loc.L("Archive.Trash.Kind.Photos"), row.KindText);
Assert.True(row.Detail.StartsWith(row.KindText, StringComparison.Ordinal), row.Detail);
Assert.Contains(Loc.Plural("Shell.Status.Photos", 12), row.Detail);
}
[Test]
public void EmptyingAsksToTypeHowManyEntriesAreErased()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var entries = new[] { Entry("Harbour sunset", TrashKind.Photos, 12, 340_000_000), Entry("Comet", TrashKind.Sequence, 1_005, 21_000_000_000) };
var plan = new TrashEmptyPlan(Guid.CreateVersion7(), entries, 21_340_000_000, "f1", []);
var request = Assert.NotNull(TrashEmptyPlans.Request(plan));
Assert.True(request.IsDestructive, "the action is outlined, never primary");
Assert.Equal("2", request.TypedConfirmation);
Assert.Equal(Loc.L("Archive.Delete.Type", "2"), request.TypedPrompt);
Assert.Equal(Loc.Plural("Archive.Trash.EmptyHeading", 2), request.Heading);
Assert.Equal(Loc.L("Archive.Trash.EmptyMessage", Loc.Plural("Shell.Status.Photos", 1_017), Loc.Plural("Archive.Delete.Files", 1_017),
Formatting.Bytes(21_340_000_000)), request.Message);
Assert.Equal(Loc.L("Archive.Trash.Erase"), request.ActionText);
Assert.Equal(Loc.L("Archive.Delete.Keep"), request.SafeText);
var lines = request.Detail!.Split(Environment.NewLine);
Assert.Equal(2, lines.Length);
Assert.Contains(Loc.L("Archive.Trash.Kind.Photos"), lines[0]);
Assert.Null(TrashEmptyPlans.Request(plan with { Entries = [] }), "nothing to erase: no confirmation");
}
[Test]
public async Task EmptyQueuesTheJobOfTheConfirmedPlanOnly()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var directory = context.CreateTempDirectory("trash-dialog");
await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(directory, "index.db")));
var archives = new ArchiveService(db, new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(TestTiming.Budget(20)) });
var archive = await archives.CreateAsync(Path.Combine(directory, "archive"), "Main");
// A sequence deleted earlier: its folder and its record in the archive's trash.
var id = Guid.CreateVersion7();
var trash = SequenceTrash.TrashDirectory(new Core.Archiving.ArchivePaths(archive.RootPath));
Directory.CreateDirectory(Path.Combine(trash, id.ToString("N")));
await File.WriteAllBytesAsync(Path.Combine(trash, id.ToString("N"), "IMG_0001.JPG"), [1, 2, 3]);
await File.WriteAllTextAsync(Path.Combine(trash, id.ToString("N") + ".json"),
$$"""{"sequence":{"id":"{{id}}","archiveId":"{{archive.Id}}","title":"Harbour sunset","folder":"2026/Harbour","frameCount":1},"renders":[],"files":1,"bytes":3,"deletedAt":"2026-10-27T09:30:00+00:00","deletedBy":"alberto"}""");
var plain = new TrashDialogViewModel(archives, archive, () => Task.CompletedTask, _ => { });
await plain.LoadAsync();
Assert.Count(1, plain.Rows);
Assert.False(plain.CanEmpty, "a host without a job engine offers no emptying");
ConfirmRequest? asked = null;
var answer = false;
var queued = new TaskCompletionSource<ArchiveJobRequest>(TaskCreationOptions.RunContinuationsAsynchronously);
var closed = false;
var dialog = new TrashDialogViewModel(archives, archive, () => Task.CompletedTask, _ => closed = true, r =>
{
asked = r;
return answer;
}, r =>
{
queued.TrySetResult(r);
return Task.CompletedTask;
});
await dialog.LoadAsync();
Assert.True(dialog.CanEmpty);
Assert.Equal(Loc.Plural("Archive.Trash.Entries", 1) + Loc.Separator + Formatting.Bytes(3), dialog.SummaryText);
// Kept: the confirmation was dismissed, nothing is queued.
dialog.EmptyCommand.Execute(null);
await UntilAsync(() => asked is not null && !dialog.IsBusy);
Assert.Equal("1", asked!.TypedConfirmation);
Assert.False(queued.Task.IsCompleted);
Assert.False(closed);
answer = true;
dialog.EmptyCommand.Execute(null);
var request = await queued.Task.WaitAsync(TimeSpan.FromSeconds(TestTiming.Budget(20)));
Assert.Equal(JobKind.EmptyTrash, request.Kind);
Assert.SequenceEqual([archive.Id], request.Targets);
Assert.Contains(id.ToString("N"), request.ParametersJson);
await UntilAsync(() => closed);
Assert.Count(1, await archives.ListTrashAsync(archive.Id), "the job erases, not the dialog");
}
private static async Task UntilAsync(Func<bool> condition)
{
var until = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(20));
while (!condition())
{
Assert.True(DateTime.UtcNow < until, "timed out");
await Task.Delay(20);
}
}
}
@@ -118,7 +118,7 @@ public sealed class LibraryScreenSmokeTests
await ArchiveScenes.ShowAsync(app.Shell, "trash");
var trash = Assert.NotNull(app.Shell.Archive.Dialog as TrashDialogViewModel, "Maintenance › Trash… opens the trash");
Assert.Equal(2, trash.Rows.Count, "the sample's deleted sequences");
Assert.Equal(2, trash.Rows.Count, "the sample's deleted sequence and photos");
Assert.True(trash.HasRows);
await app.ExpectAsync<ArchiveView>("archive-trash-sample");
trash.CloseCommand.Execute(null);
@@ -58,6 +58,43 @@ public sealed class ManifestStoreTests(TestContext context)
Assert.Contains(field, json);
}
[Test]
public void TombstonesAndConversionSourcesRoundTripWhileASidecarWithoutThemStaysAsItWas()
{
var path = SidecarPath();
var plain = Sample();
ManifestStore.WriteSequence(path, plain);
var before = File.ReadAllText(path);
Assert.False(before.Contains("\"removed\"", StringComparison.Ordinal), "no tombstones, no field");
Assert.False(before.Contains("\"source\"", StringComparison.Ordinal), "an original has no source");
var at = new DateTimeOffset(2026, 10, 27, 10, 0, 0, TimeSpan.Zero);
var changed = plain with
{
Removed =
[
new RemovedPhoto { Sha256 = new string('b', 64), Reason = RemovalReason.Deleted, At = at },
new RemovedPhoto { Sha256 = new string('c', 64), Replacement = new string('d', 64), Reason = RemovalReason.Replaced, At = at },
],
Frames =
[
plain.Frames[0] with
{
Source = new FrameSource { Sha256 = new string('e', 64), Format = ImageFileFormat.Cr2, File = "originals/IMG_0001.CR2", Size = 25_000_000 },
},
],
};
ManifestStore.WriteSequence(path, changed);
var read = ManifestStore.ReadSequence(path);
Assert.Equal(Canonical(changed), Canonical(read));
Assert.Equal(RemovalReason.Replaced, Assert.NotNull(read.Removed)[1].Reason);
Assert.Equal(new string('d', 64), read.Removed[1].Replacement);
Assert.Equal(ImageFileFormat.Cr2, Assert.NotNull(read.Frames[0].Source).Format);
var json = File.ReadAllText(path);
foreach (var field in new[] { "\"removed\":", "\"replacement\":", "\"reason\":\"Replaced\"", "\"at\":", "\"source\":" }) Assert.Contains(field, json);
}
[Test]
public void ASidecarBeingReadIsReplacedOnceTheReaderIsDone()
{
@@ -0,0 +1,456 @@
using System.Security.Cryptography;
using System.Text.Json;
using Chronos.Core.Archiving;
using Chronos.Core.Import;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Repositories;
using Chronos.Data.Tests.Infrastructure;
using Chronos.Testing;
using static Chronos.Data.Tests.Archiving.ArchiveFixture;
namespace Chronos.Data.Tests.Archiving;
/// <summary>Deleting photos of a sequence into the archive's trash, restoring them and emptying the trash (owner review 2, R6).</summary>
[Category("archive")]
public abstract class FrameTrashTests(TestContext context) : DatabaseTest(context)
{
private async Task<ArchiveFixture> FixtureAsync() => Own(await CreateAsync(Context, database: await NewOptionsAsync(multiConnection: true)));
/// <summary>A sequence of <paramref name="count"/> uploaded photos (hashed, under <c>originals/</c>), ten seconds apart.</summary>
private static async Task<(Sequence Sequence, List<Frame> Frames)> UploadedAsync(ArchiveFixture fx, int count, string session = "upload-1", int seed = 100)
{
Guid? id = null;
for (var i = 0; i < count; i++)
{
var (path, size, sha) = fx.Stage(Start.AddSeconds(10 * i), seed + i);
var result = await fx.Service.Ingest.CommitAsync(new IngestRequest(fx.Archive.Id, id, null, id is null ? session : null, path, $"IMG_{i + 1:0000}.JPG",
size, sha, null, null), fx.Ct);
id = result.SequenceId;
}
return ((await fx.Db.Sequences.GetAsync(id!.Value))!, [.. await fx.Db.Frames.ListBySequenceAsync(id.Value)]);
}
private static async Task<FrameDeleteResult> DeleteAsync(ArchiveFixture fx, Sequence sequence, params Frame[] frames)
{
var plan = await fx.Service.FrameTrash.PlanDeleteAsync(sequence.Id, [.. frames.Select(f => f.Id)], sequence.FramesVersion, fx.Ct);
Assert.True(plan.CanDelete, string.Join(", ", plan.Blocked));
return await fx.Service.FrameTrash.DeleteAsync(plan, "alberto", null, fx.Ct);
}
private static Job Running(JobKind kind, IReadOnlyList<Guid> targets) => new()
{
Id = Guid.CreateVersion7(),
Kind = kind,
TargetIds = targets,
State = JobState.Running,
NodeId = "test#0",
Created = DateTimeOffset.UtcNow,
Started = DateTimeOffset.UtcNow,
};
private static string Sha(string path) => Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(path)));
[Test]
public async Task TheDryRunCountsThePhotosAndChangesNothing()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 5);
var before = await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id);
var plan = await fx.Service.FrameTrash.PlanDeleteAsync(sequence.Id, [frames[1].Id, frames[3].Id], sequence.FramesVersion, fx.Ct);
Assert.True(plan.CanDelete);
Assert.SequenceEqual([frames[1].Id, frames[3].Id], plan.Frames.Select(f => f.Id));
Assert.Equal(frames[1].Size + frames[3].Size, plan.Bytes);
Assert.Equal(before, await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id));
Assert.False(Directory.Exists(FrameTrash.Directory(fx.Paths)), "a dry run moves nothing");
foreach (var frame in frames) Assert.FileExists(fx.Paths.FromRelative(frame.RelativePath));
}
[Test]
public async Task APlanSaysWhyPhotosCannotGo()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 3);
var trash = fx.Service.FrameTrash;
Assert.SequenceEqual([FrameDeleteBlock.WouldEmpty], (await trash.PlanDeleteAsync(sequence.Id, [.. frames.Select(f => f.Id)], null, fx.Ct)).Blocked);
Assert.SequenceEqual([FrameDeleteBlock.FramesChanged], (await trash.PlanDeleteAsync(sequence.Id, [frames[0].Id], sequence.FramesVersion - 1, fx.Ct)).Blocked);
Assert.SequenceEqual([FrameDeleteBlock.FramesChanged], (await trash.PlanDeleteAsync(sequence.Id, [frames[0].Id, Guid.CreateVersion7()], null, fx.Ct)).Blocked);
await Assert.ThrowsAsync<ArgumentException>(() => trash.PlanDeleteAsync(Guid.CreateVersion7(), [frames[0].Id], null, fx.Ct));
// A job on the sequence, or on its whole archive, holds it.
await fx.Db.Jobs.EnqueueAsync(Running(JobKind.Render, [sequence.Id]));
var busy = await trash.PlanDeleteAsync(sequence.Id, [frames[0].Id], null, fx.Ct);
Assert.SequenceEqual([FrameDeleteBlock.Busy], busy.Blocked);
Assert.False(busy.CanDelete);
await Assert.ThrowsAsync<StaleDeletePlanException>(() => trash.DeleteAsync(busy, null, null, fx.Ct));
Assert.Count(3, await fx.Db.Frames.ListBySequenceAsync(sequence.Id));
}
[Test]
public async Task DeletingMovesThePhotosToTheTrashAndTombstonesThem()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 5);
var folder = fx.Paths.Sequence(sequence.Folder);
// Proxies are named by frame index: they follow their frames.
Directory.CreateDirectory(folder.Proxies);
for (var i = 0; i < frames.Count; i++) File.WriteAllBytes(folder.Proxy(i), [(byte)i]);
await fx.Db.Sequences.UpdateStatusAsync(sequence.Id, SequenceStatus.AnalyzedLight | SequenceStatus.ThumbsBuilt, SequenceStatus.None);
var result = await DeleteAsync(fx, sequence, frames[1], frames[3]);
foreach (var gone in new[] { frames[1], frames[3] }) Assert.FileMissing(fx.Paths.FromRelative(gone.RelativePath));
var entry = result.Entry;
Assert.Equal(TrashKind.Photos, entry.Kind);
Assert.True(FrameTrash.IsPhotoEntry(entry.Name));
Assert.Equal(2, entry.Frames);
Assert.Equal(frames[1].Size + frames[3].Size, entry.Bytes);
var entryFolder = Path.Combine(FrameTrash.Directory(fx.Paths), entry.Name[FrameTrash.EntryPrefix.Length..]);
Assert.Equal(frames[1].Sha256, Sha(Path.Combine(entryFolder, "originals", Path.GetFileName(frames[1].RelativePath))));
Assert.FileMissing(folder.RemovalJournalPath);
var manifest = ManifestStore.ReadSequence(folder.ManifestPath);
Assert.SequenceEqual([frames[0].Id, frames[2].Id, frames[4].Id], manifest.Frames.Select(f => f.Id));
Assert.SequenceEqual([0, 1, 2], manifest.Frames.Select(f => f.I));
Assert.Equal(sequence.FramesVersion + 1, manifest.Versions.Frames);
Assert.SequenceEqual([frames[1].Sha256, frames[3].Sha256], Assert.NotNull(manifest.Removed).Select(r => r.Sha256));
Assert.True(manifest.Removed.All(r => r.Reason == RemovalReason.Deleted));
var row = result.Sequence;
Assert.Equal(3, row.FrameCount);
Assert.Equal(manifest.Versions.Frames, row.FramesVersion);
Assert.Equal(SequenceStatus.None, row.Status & (SequenceStatus.AnalyzedLight | SequenceStatus.ThumbsBuilt));
Assert.SequenceEqual([frames[0].Id, frames[2].Id, frames[4].Id], (await fx.Db.Frames.ListBySequenceAsync(sequence.Id)).Select(f => f.Id));
Assert.SequenceEqual([frames[1].Sha256, frames[3].Sha256], (await fx.Db.FrameRemovals.ListBySequenceAsync(sequence.Id)).Select(r => r.Sha256).Order());
Assert.True(await fx.Db.FrameRemovals.IsRemovedAsync(sequence.Id, frames[3].Sha256!.ToUpperInvariant()));
Assert.SequenceEqual<byte>([0, 2, 4], Enumerable.Range(0, 3).Select(i => File.ReadAllBytes(folder.Proxy(i))[0]));
Assert.FileMissing(folder.Proxy(3));
Assert.FileMissing(folder.Proxy(4));
var listed = Assert.Contains(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct), e => e.Name == entry.Name);
Assert.Equal(sequence.DisplayTitle, listed.Title);
Assert.Equal("alberto", listed.DeletedBy);
}
[Test]
public async Task PositionsOnDeletedPhotosWaitAndComeBackWithThem()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 5);
var folder = fx.Paths.Sequence(sequence.Folder);
var project = new ProjectSettings { ExcludedFrames = [1, 4], HeroFrame = 3 }.ToJson();
var version = (await fx.Db.Sequences.EditAsync(sequence.Id, new SequenceEdit { SettingsJson = project, HeroFrameId = frames[3].Id }, null, fx.Ct))
.Sequence!.SettingsVersion;
var deleted = await DeleteAsync(fx, (await fx.Db.Sequences.GetAsync(sequence.Id))!, frames[1], frames[3]);
var row = deleted.Sequence;
var parked = ProjectSettings.FromJson(row.SettingsJson!);
Assert.SequenceEqual([2], parked.ExcludedFrames, "the exclusion of the fifth photo follows it");
Assert.Null(parked.HeroFrame);
Assert.Count(2, Assert.NotNull(parked.PendingFrames));
Assert.True(parked.HeroPending, "the hero waits for its photo");
Assert.Null(row.HeroFrameId);
Assert.Equal(version, row.SettingsVersion);
Assert.True(File.Exists(folder.ProjectPath), "project.json mirrors the index");
var restored = await fx.Service.RestoreEntryAsync(fx.Archive.Id, deleted.Entry.Name, null, fx.Ct);
Assert.Equal(TrashKind.Photos, restored.Kind);
Assert.Equal(2, restored.Photos);
Assert.Empty(restored.Kept);
var back = (await fx.Db.Sequences.GetAsync(sequence.Id))!;
var placed = ProjectSettings.FromJson(back.SettingsJson!);
Assert.SequenceEqual([1, 4], placed.ExcludedFrames);
Assert.Equal(3, placed.HeroFrame);
Assert.Null(placed.PendingFrames);
Assert.Equal(frames[3].Id, back.HeroFrameId);
Assert.Equal(version, back.SettingsVersion);
}
[Test]
public async Task ARestorePutsThePhotosBackWithTheirIdsAndDropsTheirTombstones()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 4);
var folder = fx.Paths.Sequence(sequence.Folder);
Directory.CreateDirectory(folder.Proxies);
for (var i = 0; i < frames.Count; i++) File.WriteAllBytes(folder.Proxy(i), [(byte)i]);
var deleted = await DeleteAsync(fx, sequence, frames[0], frames[2]);
var restored = await fx.Service.RestoreEntryAsync(fx.Archive.Id, deleted.Entry.Name, null, fx.Ct);
Assert.False(restored.NewSequence);
Assert.Equal(sequence.Id, restored.Sequence.Id);
var now = await fx.Db.Frames.ListBySequenceAsync(sequence.Id);
Assert.SequenceEqual(frames.Select(f => f.Id), now.Select(f => f.Id));
Assert.SequenceEqual(frames.Select(f => f.RelativePath), now.Select(f => f.RelativePath));
Assert.SequenceEqual(frames.Select(f => f.Sha256), now.Select(f => f.Sha256));
foreach (var frame in frames) Assert.Equal(frame.Sha256, Sha(fx.Paths.FromRelative(frame.RelativePath)));
Assert.Null(ManifestStore.ReadSequence(folder.ManifestPath).Removed);
Assert.Empty(await fx.Db.FrameRemovals.ListBySequenceAsync(sequence.Id));
Assert.Equal(sequence.FramesVersion + 2, restored.Sequence.FramesVersion);
Assert.DoesNotContain(deleted.Entry.Name, (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Select(e => e.Name));
Assert.False(Directory.Exists(Path.Combine(FrameTrash.Directory(fx.Paths), deleted.Entry.Name[FrameTrash.EntryPrefix.Length..])));
// The proxies of the frames that stayed are back at their index; those of the photos that went are made again.
Assert.SequenceEqual<byte>([1], File.ReadAllBytes(folder.Proxy(1)));
Assert.SequenceEqual<byte>([3], File.ReadAllBytes(folder.Proxy(3)));
Assert.FileMissing(folder.Proxy(0));
}
[Test]
public async Task ARestoreKeepsAPhotoWhoseFileNoLongerMatchesItsRecord()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 4);
var deleted = await DeleteAsync(fx, sequence, frames[1], frames[2]);
var entryFolder = Path.Combine(FrameTrash.Directory(fx.Paths), deleted.Entry.Name[FrameTrash.EntryPrefix.Length..]);
var damaged = Path.Combine(entryFolder, "originals", Path.GetFileName(frames[2].RelativePath));
var bytes = File.ReadAllBytes(damaged);
bytes[^10] ^= 0x01;
File.WriteAllBytes(damaged, bytes);
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([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);
Assert.Equal(1, left.Frames);
Assert.FileExists(damaged);
// Nothing left that matches: the entry stays as it is.
await Assert.ThrowsAsync<InvalidDataException>(() => fx.Service.RestoreEntryAsync(fx.Archive.Id, deleted.Entry.Name, null, fx.Ct));
Assert.FileExists(damaged);
}
[Test]
public async Task PhotosOfASequenceThatIsGoneComeBackAsANewOne()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 3);
var deleted = await DeleteAsync(fx, sequence, frames[1]);
var whole = await fx.Service.PlanDeleteAsync([sequence.Id], null, fx.Ct);
await fx.Service.DeleteAsync(whole, null, null, fx.Ct);
var restored = await fx.Service.RestoreEntryAsync(fx.Archive.Id, deleted.Entry.Name, null, fx.Ct);
Assert.True(restored.NewSequence);
Assert.NotEqual(sequence.Id, restored.Sequence.Id);
Assert.Equal(sequence.DisplayTitle, restored.Sequence.DisplayTitle);
var frame = (await fx.Db.Frames.ListBySequenceAsync(restored.Sequence.Id)).Single();
Assert.Equal(frames[1].Sha256, frame.Sha256);
Assert.Equal(frames[1].Sha256, Sha(fx.Paths.FromRelative(frame.RelativePath)));
// The whole sequence is still in the trash, restorable on its own.
Assert.Contains(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct), e => e.Kind == TrashKind.Sequence && e.SequenceId == sequence.Id);
}
[Test]
public async Task TombstonesSurviveARebuildFromTheSidecars()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 3);
await DeleteAsync(fx, sequence, frames[0]);
await fx.ReopenWithEmptyIndexAsync();
await fx.ScanAsync(ScanMode.Rebuild);
var removals = await fx.Db.FrameRemovals.ListBySequenceAsync(sequence.Id);
Assert.SequenceEqual([frames[0].Sha256], removals.Select(r => r.Sha256));
Assert.Equal(RemovalReason.Deleted, removals[0].Reason);
Assert.Count(2, await fx.Db.Frames.ListBySequenceAsync(sequence.Id));
}
[Test]
public async Task TombstonesAreReplacedWholeAndGoWithTheirSequence()
{
var fx = await FixtureAsync();
var (sequence, _) = await UploadedAsync(fx, 1);
var at = new DateTimeOffset(2026, 10, 27, 10, 0, 0, TimeSpan.Zero);
var many = Enumerable.Range(0, 450).Select(i => new FrameRemoval(sequence.Id, i.ToString("x64", System.Globalization.CultureInfo.InvariantCulture),
i % 2 == 0 ? null : new string('A', 64), i % 2 == 0 ? RemovalReason.Deleted : RemovalReason.Replaced, at)).ToList();
Assert.Equal(450, await fx.Db.FrameRemovals.SyncSequenceAsync(sequence.Id, many, fx.Ct));
var stored = await fx.Db.FrameRemovals.ListBySequenceAsync(sequence.Id, fx.Ct);
Assert.Count(450, stored);
Assert.Equal((new string('a', 64), RemovalReason.Replaced), (stored.Single(r => r.Sha256 == many[1].Sha256).ReplacementSha256, stored[1].Reason));
Assert.Equal(1, await fx.Db.FrameRemovals.SyncSequenceAsync(sequence.Id, [many[3], many[3]], fx.Ct));
Assert.Count(1, await fx.Db.FrameRemovals.ListBySequenceAsync(sequence.Id, fx.Ct));
await fx.Db.Sequences.DeleteAsync(sequence.Id, fx.Ct);
Assert.Empty(await fx.Db.FrameRemovals.ListBySequenceAsync(sequence.Id, fx.Ct));
}
[Test]
public async Task ADeletionACrashInterruptedIsUndoneByTheNextWriter()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 3);
var folder = fx.Paths.Sequence(sequence.Folder);
// The journal was written and one of two files moved when the process died; the sidecar still lists both frames.
var entry = Path.Combine(FrameTrash.Directory(fx.Paths), $"{sequence.Id:N}-20261027120000");
var record = entry + ".json";
Directory.CreateDirectory(Path.Combine(entry, "originals"));
File.WriteAllText(record, "{}");
var moves = frames.Take(2).Select(f => new FrameRemovalMove(f.RelativePath[(sequence.Folder.Length + 1)..],
fx.Paths.ToRelative(Path.Combine(entry, "originals", Path.GetFileName(f.RelativePath))))).ToList();
FrameRemovalJournal.Write(folder, new FrameRemovalJournal(fx.Paths.ToRelative(record), fx.Paths.ToRelative(entry), [frames[0].Id, frames[1].Id], moves));
File.Move(fx.Paths.FromRelative(frames[0].RelativePath), fx.Paths.FromRelative(moves[0].To));
// Any writer of the sequence reads its sidecar under the lease first.
await fx.Service.SetSequenceInfoAsync(sequence.Id, "Harbour", [], 0, null, fx.Ct);
foreach (var frame in frames) Assert.Equal(frame.Sha256, Sha(fx.Paths.FromRelative(frame.RelativePath)));
Assert.FileMissing(folder.RemovalJournalPath);
Assert.FileMissing(record);
Assert.False(Directory.Exists(entry));
Assert.Count(3, ManifestStore.ReadSequence(folder.ManifestPath).Frames);
}
[Test]
public async Task ErasingTheCardKeepsTheCardCopyOfADeletedPhoto()
{
var fx = await FixtureAsync();
var card = Context.CreateTempDirectory("card");
Photos.WriteSeries(Path.Combine(card, "DCIM", "100CANON"), Start, 4);
var media = await fx.Service.Imports.RegisterCardAsync(new CardVolume("3F2A9C11-EOS_DIGITAL-127865454592", 0x3F2A9C11, "EOS_DIGITAL", 127_865_454_592), fx.Ct);
var plan = await fx.Service.PlanImportAsync(fx.Archive.Id, card, new ImportOptions(), media.Id, null, fx.Ct);
await fx.Service.Imports.ExecuteAsync(new ImportJobParameters(fx.Archive.Id, plan, media.Id, true, null), Guid.NewGuid(), 0,
_ => ValueTask.CompletedTask, null, fx.Ct);
var id = (await fx.Db.Sequences.FindBySessionKeyAsync(fx.Archive.Id, plan.Sessions.Single().SessionKey))!.Value;
var frames = await fx.Db.Frames.ListBySequenceAsync(id);
await DeleteAsync(fx, (await fx.Db.Sequences.GetAsync(id))!, frames[2]);
var erase = await fx.Service.PlanCardEraseAsync(fx.Archive.Id, media.Id, card, null, fx.Ct);
CardEraser.Execute(erase);
// The deleted photo has no frame any more: nothing in the archive vouches for its card copy, which stays.
Assert.Equal(3, erase.ToDelete.Count());
var left = Directory.EnumerateFiles(card, "*.JPG", SearchOption.AllDirectories).Select(f => Path.GetFileName(f)).ToList();
Assert.SequenceEqual([frames[2].OriginalFileName!], left);
}
[Test]
public async Task EmptyingErasesExactlyThePlannedEntries()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 3);
var (other, _) = await UploadedAsync(fx, 2, "upload-2", 200);
var photos = await DeleteAsync(fx, sequence, frames[1]);
await fx.Service.DeleteAsync(await fx.Service.PlanDeleteAsync([other.Id], null, fx.Ct), null, null, fx.Ct);
var engine = await fx.StartEngineAsync();
var plan = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
Assert.Count(2, plan.Entries);
Assert.Equal(3, plan.Photos);
Assert.True(plan.Bytes > 0);
Assert.Equal(plan.Fingerprint, (await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct)).Fingerprint, "the plan reads only");
Assert.SequenceEqual(["nope"], (await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, [photos.Entry.Name, "nope"], fx.Ct)).Unknown);
var job = await engine.EnqueueAsync(ArchiveJobs.EmptyTrash(fx.Archive, plan), cancellationToken: fx.Ct);
var done = await fx.WaitForAsync(job.Id, JobState.Done);
Assert.Empty(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct));
Assert.Empty(Directory.EnumerateFileSystemEntries(FrameTrash.Directory(fx.Paths)));
Assert.Empty(Directory.EnumerateFiles(SequenceTrash.TrashDirectory(fx.Paths), "*", SearchOption.AllDirectories));
Assert.Contains(Chronos.Core.Localization.Loc.L("Archive.Log.TrashEmptied", 2, Housekeeping.CleanupSteps.Megabytes(plan.Bytes)), done.LogTail);
// Tombstones outlive the trash: the deleted photo is still not offered back.
Assert.True(await fx.Db.FrameRemovals.IsRemovedAsync(sequence.Id, frames[1].Sha256!));
}
[Test]
public async Task AnEmptyingPlannedBeforeTheTrashChangedErasesNothing()
{
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]);
var plan = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
var engine = await fx.StartEngineAsync();
// A planned entry came back (restored) before the job ran.
await fx.Service.RestoreEntryAsync(fx.Archive.Id, first.Entry.Name, null, fx.Ct);
var job = await engine.EnqueueAsync(ArchiveJobs.EmptyTrash(fx.Archive, plan), cancellationToken: fx.Ct);
var failed = await fx.WaitForAsync(job.Id, JobState.Failed);
Assert.Equal(Chronos.Core.Localization.Loc.L("Archive.Error.TrashChanged"), failed.Error);
Assert.Contains(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct), e => e.Name == second.Entry.Name);
// A planned entry whose folder changed since makes the plan stale too.
var again = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
var folder = Path.Combine(FrameTrash.Directory(fx.Paths), second.Entry.Name[FrameTrash.EntryPrefix.Length..]);
File.WriteAllBytes(Path.Combine(folder, "added.bin"), [1, 2, 3]);
Assert.NotEqual(again.Fingerprint, (await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct)).Fingerprint);
var stale = await engine.EnqueueAsync(ArchiveJobs.EmptyTrash(fx.Archive, again), cancellationToken: fx.Ct);
await fx.WaitForAsync(stale.Id, JobState.Failed);
Assert.Contains(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct), e => e.Name == second.Entry.Name);
Assert.FileExists(Path.Combine(folder, "added.bin"));
}
[Test]
public async Task AReplacedEntryIsErasedOnlyWhileItsReplacementMatches()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 2);
var replacement = frames[1];
var good = WriteReplaced(fx, sequence, "20261027100000", replacement.Sha256!);
var bad = WriteReplaced(fx, sequence, "20261027110000", new string('a', 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));
var plan = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
var job = await engine.EnqueueAsync(ArchiveJobs.EmptyTrash(fx.Archive, plan), cancellationToken: fx.Ct);
var failed = await fx.WaitForAsync(job.Id, JobState.Failed);
Assert.Equal(Chronos.Core.Localization.Loc.Plural("Archive.Error.TrashKept", 1), failed.Error);
var left = Assert.Contains(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct), e => e.Name == FrameTrash.EntryPrefix + bad);
Assert.Equal(TrashKind.Replaced, left.Kind);
Assert.DoesNotContain(FrameTrash.EntryPrefix + good, (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Select(e => e.Name));
// A replacement whose file no longer hashes to it keeps its originals too.
var other = WriteReplaced(fx, sequence, "20261027120000", replacement.Sha256!);
var file = fx.Paths.FromRelative(replacement.RelativePath);
var bytes = File.ReadAllBytes(file);
bytes[^10] ^= 0x01;
File.WriteAllBytes(file, bytes);
var again = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, [FrameTrash.EntryPrefix + other], fx.Ct);
var second = await engine.EnqueueAsync(ArchiveJobs.EmptyTrash(fx.Archive, again), cancellationToken: fx.Ct);
await fx.WaitForAsync(second.Id, JobState.Failed);
Assert.Contains(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct), e => e.Name == FrameTrash.EntryPrefix + other);
}
/// <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)
{
var name = $"{sequence.Id:N}-{stamp}";
var folder = Path.Combine(FrameTrash.Directory(fx.Paths), name);
Directory.CreateDirectory(Path.Combine(folder, "originals"));
var bytes = Photos.Jpeg(Start, 999);
File.WriteAllBytes(Path.Combine(folder, "originals", "IMG_0001.CR2"), bytes);
var sha = Convert.ToHexStringLower(SHA256.HashData(bytes));
var frame = new SidecarFrame { Id = Guid.CreateVersion7(), File = "originals/IMG_0001.CR2", Size = bytes.Length, Sha256 = sha };
var record = new PhotoTrashRecord(TrashKind.Replaced, sequence.Id, sequence.DisplayTitle, sequence.Folder,
[new TrashedPhoto(frame, [new TrashedFile(frame.File, "originals/IMG_0001.CR2", bytes.Length, sha)], replacement)], bytes.Length,
DateTimeOffset.UtcNow, "converter");
File.WriteAllText(folder + ".json", JsonSerializer.Serialize(record, TrashJson.Default.PhotoTrashRecord));
return name;
}
}
public sealed class SqliteFrameTrashTests(TestContext context) : FrameTrashTests(context)
{
protected override Backend Backend => Backend.SqliteFile;
}
[RequiresEnvironment(PgTestServer.Variable)]
public sealed class PostgresFrameTrashTests(TestContext context) : FrameTrashTests(context)
{
protected override Backend Backend => Backend.Postgres;
}
@@ -9,7 +9,7 @@ public abstract class MigrationTests(TestContext context) : RepositoryTest(conte
private static readonly string[] Tables =
[
"archives", "sequences", "frames", "renders", "jobs", "media_cards", "import_history", "users", "tokens",
"render_nodes", "settings", "tags", "sequence_tags", "audit_log", "uploads", "schedules",
"render_nodes", "settings", "tags", "sequence_tags", "audit_log", "uploads", "schedules", "frame_removals",
];
[Test]
@@ -274,6 +274,9 @@ internal sealed class FakeSequence
public List<FakeFrame> Frames { get; } = [];
public List<FakeRender> Renders { get; } = [];
/// <summary>Tombstones of photos removed on the server (owner review 2, R6), as its manifest lists them.</summary>
public List<RemovedPhotoDto> Removed { get; } = [];
/// <summary>Like the server, the capture time comes from the photo's Exif data when none is given.</summary>
public FakeFrame AddFrame(byte[] bytes, string? name = null, DateTime? capturedAt = null) => InsertFrame(Frames.Count, bytes, name, capturedAt);
@@ -295,7 +298,7 @@ internal sealed class FakeSequence
public SequenceManifest Manifest(Func<Guid, bool> proxySent) => new(Id, FramesVersion, SettingsVersion, SettingsJson, Tags,
[.. Frames.Select((f, i) => new ManifestFrame(f.Id, i, f.FileName, f.Bytes.Length, Unhashed ? string.Empty : f.Sha256,
(Status & SequenceStatus.ProxiesBuilt) != 0 || proxySent(f.Id), (Status & SequenceStatus.ThumbsBuilt) != 0, WantsProxy: Undecodable && !proxySent(f.Id)))],
[.. Renders.Select(r => r.Dto())], Undecodable ? new ProxySpec(1280, 90) : null);
[.. Renders.Select(r => r.Dto())], Undecodable ? new ProxySpec(1280, 90) : null, Removed.Count == 0 ? null : [.. Removed]);
public FrameDto FrameDto(FakeFrame frame) => frame.Dto(Id, Frames.IndexOf(frame), Unhashed);
}
@@ -67,6 +67,36 @@ public sealed class SyncRulesTests
Assert.Equal((1, 0), SyncRules.CompareOriginals([null, null], ["bb"]));
}
[Test]
public void PhotosEitherSideRemovedAreNotOfferedBack()
{
static FramePhoto Photo(string sha) => new(sha, 100, null);
var at = new DateTimeOffset(2026, 10, 27, 10, 0, 0, TimeSpan.Zero);
var localId = Guid.CreateVersion7();
// The server deleted "cc", which this PC still holds; this PC deleted "dd", which the server still holds.
var tombstones = new SyncTombstones([new FrameRemoval(localId, "DD", null, RemovalReason.Deleted, at)],
[new RemovedPhotoDto("cc", null, "deleted", at)]);
Assert.Equal((0, 0), SyncRules.CompareOriginals([Photo("aa"), Photo("bb"), Photo("cc")], [Photo("aa"), Photo("bb"), Photo("dd")], tombstones));
Assert.Equal((1, 1), SyncRules.CompareOriginals([Photo("aa"), Photo("cc")], [Photo("aa"), Photo("dd")], SyncTombstones.None));
Assert.True(tombstones.DeletedRemotely("CC"));
Assert.True(tombstones.DeletedLocally("dd"));
Assert.False(tombstones.DeletedLocally("cc"));
// A photo replaced by a converted file on either side is the same photo as its replacement, and so is a chain of them.
var replaced = new SyncTombstones([], [new RemovedPhotoDto("aa", "a2", "replaced", at), new RemovedPhotoDto("a2", "a3", "replaced", at)]);
Assert.Equal("a3", replaced.Canonical("AA"));
Assert.Equal((0, 0), SyncRules.CompareOriginals([Photo("aa"), Photo("bb")], [Photo("a3"), Photo("bb")], replaced));
Assert.False(replaced.DeletedRemotely("aa"), "a replaced photo is there as its replacement");
var replacedHere = new SyncTombstones([new FrameRemoval(localId, "bb", "b2", RemovalReason.Replaced, at)], null);
Assert.Equal((0, 0), SyncRules.CompareOriginals([Photo("b2")], [Photo("bb")], replacedHere));
// A replacement deleted since: neither the photo nor its replacement is offered back.
var gone = new SyncTombstones([], [new RemovedPhotoDto("aa", "a2", "replaced", at), new RemovedPhotoDto("a2", null, "deleted", at)]);
Assert.Equal((0, 0), SyncRules.CompareOriginals([Photo("aa")], [], gone));
Assert.True(SyncTombstones.None.IsEmpty);
Assert.SequenceEqual(["deleted", "replaced"], SyncTombstones.ToDto([new FrameRemoval(localId, "aa", null, RemovalReason.Deleted, at),
new FrameRemoval(localId, "bb", "b2", RemovalReason.Replaced, at)]).Select(r => r.Reason));
}
[Test]
public void FramesEitherSideHasNotHashedAreMatchedBySizeAndCaptureTime()
{
@@ -6,6 +6,7 @@ using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Data.Sync;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.Data.Tests.Sync;
@@ -116,6 +117,40 @@ public sealed class SyncTransferTests(TestContext context)
Assert.Equal((SyncStatus.InSync, 0), (entry.Status, entry.Link!.MissingRemote));
}
[Test]
public async Task PhotosOneSideDeletedAreNeitherSentNorFetchedAgain()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(4);
var local = await f.LocalAsync("Comet", photos);
// The server holds the first three and deleted the fourth, which this PC still holds.
var remote = f.Remote.Add("Comet", photos[..3]);
remote.Removed.Add(new RemovedPhotoDto(Sha(photos[3]), null, "deleted", DateTimeOffset.UtcNow));
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
Assert.Equal(0, (await f.EntryAsync("Comet")).Link!.MissingRemote);
var engine = await f.StartEngineAsync();
var upload = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
await f.Archive.WaitForAsync(upload.Id, JobState.Done);
Assert.Equal(3, remote.Frames.Count);
Assert.Count(4, await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct));
// This PC deletes the first photo, which the server still holds: it is not fetched back, and nothing local is deleted.
var frames = await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct);
var sequence = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
var plan = await f.Archive.Service.FrameTrash.PlanDeleteAsync(local.Id, [frames[0].Id], sequence.FramesVersion, f.Ct);
await f.Archive.Service.FrameTrash.DeleteAsync(plan, null, null, f.Ct);
await f.RefreshAsync();
var entry = await f.EntryAsync("Comet");
Assert.Equal((0, 0), (entry.Link!.MissingRemote, entry.Link.MissingLocal));
var download = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Comet", SyncDownloadMode.Originals, null);
await f.Archive.WaitForAsync(download.Id, JobState.Done);
var kept = await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct);
Assert.SequenceEqual(photos[1..].Select(Sha), kept.Select(k => k.Sha256!));
}
[Test]
public async Task AResumedUploadSendsOnlyWhatTheServerLacks()
{
@@ -0,0 +1,293 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Model;
using Chronos.Protocol;
using Chronos.Server.Storage;
using Chronos.Testing;
namespace Chronos.Server.Tests.Api;
/// <summary>
/// The library the admin panel manages (owner review 2, R6): sequence thumbnails, photos deleted into the trash, the trash
/// listed, restored and emptied, and bulk operations, against the real archive engine.
/// </summary>
[Category("server")]
public sealed class LibraryTests(TestContext context)
{
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(TestTiming.Budget(30));
[Test]
public async Task PhotosAreDeletedIntoTheTrashAndRestoredThroughTheApi()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var (other, _, _) = await server.UserAsync("giulia", "editor");
var admin = await server.AdminAsync();
var photos = Enumerable.Range(0, 3).Select(Photo).ToList();
Guid? id = null;
for (var i = 0; i < photos.Count; i++) id = (await Uploads.UploadAsync(editor, photos[i], $"IMG_{i + 1:0000}.JPG", sessionKey: "roof")).SequenceId;
await UntilIdleAsync(server);
var sequence = (await server.Database.Sequences.GetAsync(id!.Value))!;
var frames = await server.Database.Frames.ListBySequenceAsync(sequence.Id);
var url = $"/api/v1/sequences/{sequence.Id}/frames/delete";
using (var forbidden = await other.PostAsJsonAsync(url, new FrameDeleteRequest([frames[1].Id], null, false), ProtocolJson.Default.FrameDeleteRequest))
await forbidden.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
using (var none = await editor.PostAsJsonAsync(url, new FrameDeleteRequest([], null, false), ProtocolJson.Default.FrameDeleteRequest))
await none.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request");
using (var stale = await editor.PostAsJsonAsync(url, new FrameDeleteRequest([frames[1].Id], sequence.FramesVersion - 1, false),
ProtocolJson.Default.FrameDeleteRequest))
Assert.Equal(sequence.FramesVersion.ToString(System.Globalization.CultureInfo.InvariantCulture),
(await stale.ExpectErrorAsync(HttpStatusCode.Conflict, "frames_conflict")).Details);
using (var all = await editor.PostAsJsonAsync(url, new FrameDeleteRequest([.. frames.Select(f => f.Id)], null, false), ProtocolJson.Default.FrameDeleteRequest))
await all.ExpectErrorAsync(HttpStatusCode.Conflict, "would_empty");
using (var dry = await editor.PostAsJsonAsync(url, new FrameDeleteRequest([frames[1].Id], sequence.FramesVersion, true), ProtocolJson.Default.FrameDeleteRequest))
{
var plan = await dry.ReadAsync(ProtocolJson.Default.FrameDeleteResultDto);
Assert.True(plan.DryRun);
Assert.Equal((1, frames[1].Size, 3), (plan.Photos, plan.Bytes, plan.FrameCount));
Assert.Null(plan.TrashEntry);
}
Assert.Count(3, await server.Database.Frames.ListBySequenceAsync(sequence.Id));
FrameDeleteResultDto done;
using (var deleted = await editor.PostAsJsonAsync(url, new FrameDeleteRequest([frames[1].Id], sequence.FramesVersion, false),
ProtocolJson.Default.FrameDeleteRequest))
done = await deleted.ReadAsync(ProtocolJson.Default.FrameDeleteResultDto);
Assert.False(done.DryRun);
Assert.Equal((2, sequence.FramesVersion + 1), (done.FrameCount, done.FramesVersion));
var name = Assert.NotNull(done.TrashEntry);
Assert.FileMissing(Path.Combine(server.Options.ArchivePath, frames[1].RelativePath));
// The manifest names the deleted photo, so clients do not send it back; an upload of it is answered as already there.
using (var manifest = await editor.GetAsync($"/api/v1/sequences/{sequence.Id}/manifest"))
Assert.SequenceEqual([Uploads.Sha(photos[1])], Assert.NotNull((await manifest.ReadAsync(ProtocolJson.Default.SequenceManifest)).Removed).Select(r => r.Sha256));
var again = await Uploads.StartAsync(editor, photos[1], "IMG_0002.JPG", sequence.Id, expected: HttpStatusCode.OK);
Assert.True(again.AlreadyExists);
Assert.Null(again.FrameId);
Assert.Count(2, await server.Database.Frames.ListBySequenceAsync(sequence.Id));
using (var notAdmin = await editor.GetAsync("/api/v1/archive/trash")) await notAdmin.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
using (var list = await admin.GetAsync("/api/v1/archive/trash"))
{
var trash = await list.ReadAsync(ProtocolJson.Default.TrashListDto);
var entry = Assert.Contains(trash.Entries, e => e.Name == name);
Assert.Equal(("photos", 1, sequence.Id, "alberto"), (entry.Kind, entry.Photos, entry.SequenceId, entry.DeletedBy));
Assert.Equal(frames[1].Size, trash.Bytes);
}
await UntilIdleAsync(server);
using (var restored = await admin.PostAsync($"/api/v1/archive/trash/{name}/restore", null))
{
var result = await restored.ReadAsync(ProtocolJson.Default.TrashRestoreDto);
Assert.Equal(("photos", sequence.Id, 1, false), (result.Kind, result.SequenceId, result.Photos, result.NewSequence));
Assert.Empty(result.Kept);
}
Assert.SequenceEqual(frames.Select(f => f.Id), (await server.Database.Frames.ListBySequenceAsync(sequence.Id)).Select(f => f.Id));
using (var gone = await admin.PostAsync($"/api/v1/archive/trash/{name}/restore", null)) await gone.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
using (var bad = await admin.PostAsync("/api/v1/archive/trash/..%2F..%2Fsecret/restore", null)) Assert.Equal(HttpStatusCode.NotFound, bad.StatusCode);
}
[Test]
public async Task TheTrashIsEmptiedByAJobAfterADryRunAndItsFingerprint()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var admin = await server.AdminAsync();
var a = (await Uploads.UploadAsync(editor, Photo(10), "a.jpg", sessionKey: "a")).SequenceId;
Guid b = default;
for (var i = 0; i < 2; i++) b = (await Uploads.UploadAsync(editor, Photo(20 + i), $"b{i}.jpg", sessionKey: "b")).SequenceId;
await UntilIdleAsync(server);
using (var deleted = await editor.DeleteAsync($"/api/v1/sequences/{a}")) await deleted.ExpectAsync(HttpStatusCode.OK);
var frames = await server.Database.Frames.ListBySequenceAsync(b);
using (var photo = await editor.PostAsJsonAsync($"/api/v1/sequences/{b}/frames/delete", new FrameDeleteRequest([frames[0].Id], null, false),
ProtocolJson.Default.FrameDeleteRequest))
await photo.ExpectAsync(HttpStatusCode.OK);
await UntilIdleAsync(server);
TrashEmptyPlanDto plan;
using (var dry = await admin.PostAsJsonAsync("/api/v1/archive/trash/empty", new TrashEmptyRequest(null, true, null), ProtocolJson.Default.TrashEmptyRequest))
plan = await dry.ReadAsync(ProtocolJson.Default.TrashEmptyPlanDto);
Assert.Equal(2, plan.Entries.Count);
Assert.SequenceEqual(["photos", "sequence"], plan.Entries.Select(e => e.Kind).Order());
Assert.Equal(2, plan.Photos);
using (var noPrint = await admin.PostAsJsonAsync("/api/v1/archive/trash/empty", new TrashEmptyRequest(null, false, null), ProtocolJson.Default.TrashEmptyRequest))
await noPrint.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request");
using (var wrong = await admin.PostAsJsonAsync("/api/v1/archive/trash/empty", new TrashEmptyRequest(null, false, "0123"), ProtocolJson.Default.TrashEmptyRequest))
Assert.Equal(plan.Fingerprint, (await wrong.ExpectErrorAsync(HttpStatusCode.Conflict, "trash_changed")).Details);
using (var names = await admin.PostAsJsonAsync("/api/v1/archive/trash/empty", new TrashEmptyRequest(["../x"], true, null), ProtocolJson.Default.TrashEmptyRequest))
await names.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request");
JobDto job;
using (var empty = await admin.PostAsJsonAsync("/api/v1/archive/trash/empty", new TrashEmptyRequest(null, false, plan.Fingerprint),
ProtocolJson.Default.TrashEmptyRequest))
{
await empty.ExpectAsync(HttpStatusCode.Accepted);
job = await empty.ReadAsync(ProtocolJson.Default.JobDto);
}
Assert.Equal("empty-trash", job.Kind);
await UntilJobAsync(admin, job.Id, "done");
using (var list = await admin.GetAsync("/api/v1/archive/trash")) Assert.Empty((await list.ReadAsync(ProtocolJson.Default.TrashListDto)).Entries);
Assert.Empty(Directory.EnumerateFiles(server.Options.TrashPath, "*", SearchOption.AllDirectories));
Assert.Count(1, await server.Database.Frames.ListBySequenceAsync(b));
}
[Test]
public async Task BulkOperationsAnswerForEachSequence()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var archive = server.Services.GetRequiredService<ServerArchive>();
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var (other, _, _) = await server.UserAsync("giulia", "editor");
var a = (await Uploads.UploadAsync(editor, Photo(30), "a.jpg", sessionKey: "a")).SequenceId;
var b = (await Uploads.UploadAsync(editor, Photo(31), "b.jpg", sessionKey: "b")).SequenceId;
var c = (await Uploads.UploadAsync(other, Photo(32), "c.jpg", sessionKey: "c")).SequenceId;
var unknown = Guid.CreateVersion7();
await UntilIdleAsync(server);
using (var retag = await editor.PostAsJsonAsync("/api/v1/sequences/bulk/retag", new BulkRetagRequest([a, b, unknown], ["Night", "roof"], null),
ProtocolJson.Default.BulkRetagRequest))
{
var result = await retag.ReadAsync(ProtocolJson.Default.BulkResultDto);
Assert.Equal((2, 1), (result.Ok, result.Skipped));
Assert.Equal("not_found", result.Items.Single(i => i.Id == unknown).Reason);
}
using (var untag = await editor.PostAsJsonAsync("/api/v1/sequences/bulk/retag", new BulkRetagRequest([a], ["sky"], ["NIGHT"]),
ProtocolJson.Default.BulkRetagRequest))
await untag.ExpectAsync(HttpStatusCode.OK);
Assert.SequenceEqual(["roof", "sky"], (await server.Database.Sequences.GetAsync(a))!.Tags.Order());
Assert.SequenceEqual(["Night", "roof"], (await server.Database.Sequences.GetAsync(b))!.Tags.Order());
using (var noTags = await editor.PostAsJsonAsync("/api/v1/sequences/bulk/retag", new BulkRetagRequest([a], null, null), ProtocolJson.Default.BulkRetagRequest))
await noTags.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request");
// A verify of sequences targets their archive (it once targeted the sequences, which its handler cannot read).
using (var verify = await editor.PostAsJsonAsync("/api/v1/sequences/bulk/jobs", new BulkJobsRequest([a, b, unknown], "verify"),
ProtocolJson.Default.BulkJobsRequest))
{
await verify.ExpectAsync(HttpStatusCode.Accepted);
var result = await verify.ReadAsync(ProtocolJson.Default.BulkResultDto);
var job = Assert.NotNull(result.Job);
Assert.Equal(("verify", 2, 1), (job.Kind, result.Ok, result.Skipped));
Assert.SequenceEqual([archive.Id], job.TargetIds);
await UntilJobAsync(editor, job.Id, "done");
}
using (var single = await editor.PostAsJsonAsync("/api/v1/jobs", new CreateJobRequest("verify", [a], null), ProtocolJson.Default.CreateJobRequest))
{
var job = await single.ReadAsync(ProtocolJson.Default.JobDto);
Assert.SequenceEqual([archive.Id], job.TargetIds);
await UntilJobAsync(editor, job.Id, "done");
}
using (var thumbs = await editor.PostAsJsonAsync("/api/v1/sequences/bulk/jobs", new BulkJobsRequest([a, b], "thumbnails"), ProtocolJson.Default.BulkJobsRequest))
{
var job = Assert.NotNull((await thumbs.ReadAsync(ProtocolJson.Default.BulkResultDto)).Job);
Assert.Equal("thumbs", job.Kind);
Assert.SequenceEqual([a, b], job.TargetIds);
}
using (var bogus = await editor.PostAsJsonAsync("/api/v1/sequences/bulk/jobs", new BulkJobsRequest([a], "render"), ProtocolJson.Default.BulkJobsRequest))
await bogus.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_job_kind");
await UntilIdleAsync(server);
using (var dry = await editor.PostAsJsonAsync("/api/v1/sequences/bulk/delete", new BulkDeleteRequest([a, c, unknown], true), ProtocolJson.Default.BulkDeleteRequest))
{
var result = await dry.ReadAsync(ProtocolJson.Default.BulkResultDto);
Assert.True(result.DryRun);
Assert.Equal(".chronos/trash/" + a.ToString("N"), result.Items[0].TrashFolder);
Assert.SequenceEqual(["ok", "skipped", "skipped"], result.Items.Select(i => i.Outcome));
Assert.SequenceEqual<string?>([null, "forbidden", "not_found"], result.Items.Select(i => i.Reason));
Assert.Equal(1, result.Photos);
}
Assert.NotNull(await server.Database.Sequences.GetAsync(a));
using (var deleted = await editor.PostAsJsonAsync("/api/v1/sequences/bulk/delete", new BulkDeleteRequest([a, b], false), ProtocolJson.Default.BulkDeleteRequest))
Assert.Equal(2, (await deleted.ReadAsync(ProtocolJson.Default.BulkResultDto)).Ok);
Assert.Null(await server.Database.Sequences.GetAsync(a));
Assert.Null(await server.Database.Sequences.GetAsync(b));
Assert.NotNull(await server.Database.Sequences.GetAsync(c));
}
[Test]
public async Task ASequenceThumbnailIsItsHeroFramesOrItsFirst()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var first = await Uploads.UploadAsync(editor, Photo(40), "IMG_0001.JPG", sessionKey: "t");
var second = await Uploads.UploadAsync(editor, Photo(41), "IMG_0002.JPG", sessionKey: "t");
var id = first.SequenceId;
var thumbs = new Dictionary<Guid, byte[]>();
foreach (var frame in new[] { first.FrameId, second.FrameId }) thumbs[frame] = await ThumbnailAsync(editor, $"/api/v1/frames/{frame}/thumb");
using (var cover = await editor.GetAsync($"/api/v1/sequences/{id}/thumb"))
{
await cover.ExpectAsync(HttpStatusCode.OK);
var bytes = await cover.Content.ReadAsByteArrayAsync();
Assert.BytesEqual(thumbs[first.FrameId], bytes);
var etag = Assert.NotNull(cover.Headers.ETag);
using var request = new HttpRequestMessage(HttpMethod.Get, $"/api/v1/sequences/{id}/thumb");
request.Headers.IfNoneMatch.Add(etag);
using var cached = await editor.SendAsync(request);
Assert.Equal(HttpStatusCode.NotModified, cached.StatusCode);
}
using (var hero = await editor.PatchAsJsonAsync($"/api/v1/sequences/{id}", new UpdateSequenceRequest(null, null, null, null, null, null, second.FrameId),
ProtocolJson.Default.UpdateSequenceRequest))
await hero.ExpectAsync(HttpStatusCode.OK);
var heroThumb = await ThumbnailAsync(editor, $"/api/v1/sequences/{id}/thumb");
Assert.BytesEqual(thumbs[second.FrameId], heroThumb);
using var created = await editor.PostAsJsonAsync("/api/v1/sequences", new CreateSequenceRequest("Empty", null), ProtocolJson.Default.CreateSequenceRequest);
var empty = await created.ReadAsync(ProtocolJson.Default.SequenceDto);
using (var none = await editor.GetAsync($"/api/v1/sequences/{empty.Id}/thumb")) await none.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
using (var unknown = await editor.GetAsync($"/api/v1/sequences/{Guid.CreateVersion7()}/thumb")) await unknown.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
}
/// <summary>A thumbnail once its pass has drawn it (404 until then).</summary>
private static async Task<byte[]> ThumbnailAsync(HttpClient client, string url)
{
var until = DateTime.UtcNow + Wait;
while (true)
{
using var response = await client.GetAsync(url);
if (response.StatusCode == HttpStatusCode.OK) return await response.Content.ReadAsByteArrayAsync();
Assert.True(DateTime.UtcNow < until, $"{url}: {(int)response.StatusCode}");
await Task.Delay(50);
}
}
private static async Task UntilJobAsync(HttpClient client, Guid id, string state)
{
var until = DateTime.UtcNow + Wait;
while (true)
{
using var response = await client.GetAsync($"/api/v1/jobs/{id}");
var job = await response.ReadAsync(ProtocolJson.Default.JobDto);
if (job.State == state) return;
if (job.State is "failed" or "cancelled") Assert.Fail($"job {job.Kind} {job.State}: {job.Error}\n{job.LogTail}");
Assert.True(DateTime.UtcNow < until, $"job {job.Kind} still {job.State}");
await Task.Delay(50);
}
}
/// <summary>Waits until no job is queued or running (the thumbnails, proxies and analyses uploads queue).</summary>
private static async Task UntilIdleAsync(TestServer server)
{
var until = DateTime.UtcNow + Wait;
foreach (var state in new[] { JobState.Queued, JobState.Running, JobState.Queued, JobState.Running })
{
while ((await server.Database.Jobs.ListAsync(state)).Items.Count > 0)
{
Assert.True(DateTime.UtcNow < until, $"jobs still {state}");
await Task.Delay(50);
}
}
}
private static byte[] Photo(int seed)
{
const int width = 96, height = 64;
var pixels = new byte[width * height * 3];
for (var i = 0; i < pixels.Length; i++) pixels[i] = (byte)((i * 7 + seed * 31) % 251);
return JpegEncoder.Encode(pixels, width, height, 3, new JpegEncodeOptions { Quality = 90 });
}
}