merge: archive layout, sidecars, scan/rebuild/verify, card import and ingest

This commit is contained in:
Claude committed 2026-10-02 12:30:53 +00:00
commit e92568a7bb
65 files changed
+7197

No files matched your search

@@ -0,0 +1,182 @@
using Titano.Core.Archiving;
using Titano.Core.Codecs.Jpeg;
using Titano.Core.Imaging;
using Titano.Core.Metadata;
using Titano.Core.Model;
using Titano.Testing;
namespace Titano.Core.Tests.Archiving;
[Category("archive")]
public sealed class ArchiveFolderTests(TestContext context)
{
private static readonly DateTime Start = new(2026, 9, 28, 18, 0, 0);
private ArchivePaths NewArchive() => new(context.CreateTempDirectory("archive"));
[Test]
public void SequenceFoldersAreFoundInLayoutAndAdoptedForms()
{
var archive = NewArchive();
TestPhotos.WriteSeries(Path.Combine(archive.Root, "2026", "2026-09-28 Canon EOS R5", "originals"), Start, 3, TimeSpan.FromSeconds(10));
TestPhotos.WriteSeries(Path.Combine(archive.Root, "Trips", "Harbour"), Start, 2, TimeSpan.FromSeconds(10));
TestPhotos.WriteSeries(Path.Combine(archive.Root, "Trips", "Harbour", "selects"), Start, 1, TimeSpan.FromSeconds(10));
TestPhotos.WriteSeries(Path.Combine(archive.Root, ".hidden"), Start, 1, TimeSpan.FromSeconds(10));
File.WriteAllBytes(Path.Combine(archive.Root, "Trips", "._IMG_0001.JPG"), [1]);
Directory.CreateDirectory(Path.Combine(archive.Root, "empty"));
var folders = ArchiveScanner.FindSequenceFolders(archive);
Assert.SequenceEqual(["2026/2026-09-28 Canon EOS R5", "Trips/Harbour", "Trips/Harbour/selects"], folders.Select(f => f.RelativeFolder));
Assert.True(folders.All(f => f.Sidecar is null && f.Photos is not null));
Assert.SequenceEqual(["originals/IMG_0001.JPG", "originals/IMG_0002.JPG", "originals/IMG_0003.JPG"],
ArchiveScanner.ListPhotos(archive.Sequence("2026/2026-09-28 Canon EOS R5")));
}
[Test]
public void AdoptionBuildsASidecarInCaptureOrderWithoutTouchingPhotos()
{
var archive = NewArchive();
var folder = Path.Combine(archive.Root, "Harbour sunset");
// File names run against capture order: the sidecar follows capture time.
TestPhotos.Write(Path.Combine(folder, "a.jpg"), Start.AddSeconds(20), 1);
TestPhotos.Write(Path.Combine(folder, "b.jpg"), Start, 2);
TestPhotos.Write(Path.Combine(folder, "c.jpg"), Start.AddSeconds(10), 3);
var before = Directory.GetFiles(folder).ToDictionary(f => f, File.ReadAllBytes);
var manifest = SequenceAdopter.Build(Guid.CreateVersion7(), archive.Sequence("Harbour sunset"), "test");
Assert.SequenceEqual(["b.jpg", "c.jpg", "a.jpg"], manifest.Frames.Select(f => f.File));
Assert.SequenceEqual([0, 1, 2], manifest.Frames.Select(f => f.I));
Assert.Equal("Harbour sunset", manifest.Title);
Assert.Equal("Canon EOS R5", manifest.Camera!.Model);
Assert.True(manifest.Frames.All(f => f.Sha256 is null && f.Size > 0 && f.Format == ImageFileFormat.Jpeg && f.W == 48));
foreach (var (path, bytes) in before) Assert.BytesEqual(bytes, File.ReadAllBytes(path));
}
[Test]
public void ReconcileIndexesNewPhotosAndFlagsMissingOnes()
{
var archive = NewArchive();
var sequence = archive.Sequence("s");
var files = TestPhotos.WriteSeries(sequence.Originals, Start, 4, TimeSpan.FromSeconds(10));
var manifest = SequenceAdopter.Build(Guid.CreateVersion7(), sequence, null);
Assert.Null(SequenceAdopter.Reconcile(sequence, manifest));
File.Delete(files[1]);
TestPhotos.Write(Path.Combine(sequence.Originals, "IMG_0000.JPG"), Start.AddSeconds(-10), 9);
var orphans = SequenceAdopter.FindOrphans(sequence, manifest);
Assert.SequenceEqual(["originals/IMG_0000.JPG"], orphans.UnindexedFiles);
Assert.SequenceEqual(["originals/IMG_0002.JPG"], orphans.MissingFiles.Select(f => f.File));
var reconciled = SequenceAdopter.Reconcile(sequence, manifest)!;
Assert.SequenceEqual(["originals/IMG_0000.JPG", "originals/IMG_0001.JPG", "originals/IMG_0002.JPG", "originals/IMG_0003.JPG", "originals/IMG_0004.JPG"],
reconciled.Frames.Select(f => f.File));
Assert.Equal(FrameFlags.Missing, reconciled.Frames[2].Flags);
Assert.Equal(manifest.Frames[0].Id, reconciled.Frames[1].Id);
TestPhotos.Write(files[1], Start.AddSeconds(10), 2);
var restored = SequenceAdopter.Reconcile(sequence, reconciled)!;
Assert.Equal(FrameFlags.None, restored.Frames[2].Flags);
}
[Test]
public async Task VerifyDetectsAFlippedByteAMissingFileAndAChangedFile()
{
var archive = NewArchive();
var sequence = archive.Sequence("s");
var files = TestPhotos.WriteSeries(sequence.Originals, Start, 4, TimeSpan.FromSeconds(10));
var adopted = SequenceAdopter.Build(Guid.CreateVersion7(), sequence, null);
var hashed = new List<SidecarFrame>();
foreach (var frame in adopted.Frames)
{
var check = await FrameVerifier.CheckAsync(sequence, frame);
Assert.Equal(FrameHealth.Hashed, check.Health);
hashed.Add(check.Updated);
}
var bytes = File.ReadAllBytes(files[0]);
bytes[bytes.Length / 2] ^= 0x01;
File.WriteAllBytes(files[0], bytes);
File.Delete(files[1]);
File.AppendAllText(files[2], "edit");
var health = new List<FrameHealth>();
foreach (var frame in hashed) health.Add((await FrameVerifier.CheckAsync(sequence, frame)).Health);
Assert.SequenceEqual([FrameHealth.Corrupt, FrameHealth.Missing, FrameHealth.Changed, FrameHealth.Ok], health);
var corrupt = await FrameVerifier.CheckAsync(sequence, hashed[0]);
Assert.Equal(FrameFlags.Corrupt, corrupt.Flags);
Assert.Equal(hashed[0].Sha256, corrupt.Updated.Sha256);
}
[Test]
public void TheIndexSnapshotIsUsedOnlyForUnchangedSidecars()
{
var archive = NewArchive();
Directory.CreateDirectory(archive.MetaDirectory);
var stampA = new FileStamp(10, new DateTime(2026, 9, 1, 0, 0, 0, DateTimeKind.Utc));
using (var writer = new IndexSnapshot.Writer(archive.SnapshotPath))
{
writer.Add("a", stampA, "{\"a\":1}"u8);
writer.Add("b/ç", new FileStamp(20, stampA.ModifiedUtc), "{\"b\":2}"u8);
writer.Commit();
}
var snapshot = IndexSnapshot.TryLoad(archive.SnapshotPath)!;
Assert.Equal(2, snapshot.Count);
Assert.BytesEqual("{\"a\":1}"u8, snapshot.TryGet("a", stampA));
Assert.Null(snapshot.TryGet("a", stampA with { Size = 11 }));
Assert.NotNull(snapshot.TryGet("b/ç", new FileStamp(20, stampA.ModifiedUtc)));
var bytes = File.ReadAllBytes(archive.SnapshotPath);
bytes[12] ^= 0x40;
File.WriteAllBytes(archive.SnapshotPath, bytes);
Assert.Null(IndexSnapshot.TryLoad(archive.SnapshotPath));
}
[Test]
public void RenamePlansAvoidTakenFoldersAndMoveIdempotently()
{
var archive = NewArchive();
Directory.CreateDirectory(Path.Combine(archive.Root, "2026", "old a"));
Directory.CreateDirectory(Path.Combine(archive.Root, "2026", "old b"));
Directory.CreateDirectory(Path.Combine(archive.Root, "2026", "2026-09-28 Sunset"));
var a = new RenameSubject(Guid.NewGuid(), "2026/old a", null, Start, "Canon", "Canon EOS R5", null);
var b = new RenameSubject(Guid.NewGuid(), "2026/old b", "Dawn", Start, "Canon", "Canon EOS R5", null);
var plan = RenamePlanner.Plan(Guid.NewGuid(), [a, b], "{year}/{date} {title}", "Sunset",
["2026/old a", "2026/old b"], f => Directory.Exists(archive.FromRelative(f)));
Assert.SequenceEqual(["2026/2026-09-28 Sunset (2)", "2026/2026-09-28 Sunset (3)"], plan.Steps.Select(s => s.ToFolder));
Assert.True(plan.Steps.All(s => s.ToTitle == "Sunset"));
Assert.Equal("Dawn", plan.Steps[1].FromTitle);
RenamePlanner.MoveFolder(archive, plan.Steps[0]);
RenamePlanner.MoveFolder(archive, plan.Steps[0]);
Assert.False(Directory.Exists(archive.FromRelative("2026/old a")));
Assert.True(Directory.Exists(archive.FromRelative("2026/2026-09-28 Sunset (2)")));
var titleOnly = RenamePlanner.Plan(Guid.NewGuid(), [b], null, "{title} morning", ["2026/old b"], _ => false);
Assert.Equal("2026/old b", titleOnly.Steps.Single().ToFolder);
Assert.Equal("Dawn morning", titleOnly.Steps.Single().ToTitle);
Assert.Empty(RenamePlanner.Plan(Guid.NewGuid(), [b], "2026/old b", null, ["2026/old b"], _ => true).Steps);
}
[Test]
public void ThumbnailsAndProxiesAreRenderedFromTheFrame()
{
var archive = NewArchive();
var sequence = archive.Sequence("s");
Directory.CreateDirectory(sequence.Originals);
File.WriteAllBytes(Path.Combine(sequence.Originals, "big.jpg"), TestPhotos.Jpeg(Start, 7, width: 640, height: 480, orientation: 6));
var frame = SequenceAdopter.Build(Guid.CreateVersion7(), sequence, null).Frames.Single();
var renderer = new FrameImageRenderer(new ImageDecoder([]));
var thumb = renderer.Thumbnail(sequence, frame)!;
Assert.Equal((240, 320), (thumb.Width, thumb.Height));
Assert.Equal(DecodeTier.Native, thumb.Tier);
Assert.Equal(240, JpegDecoder.ReadInfo(thumb.Jpeg).Width);
var proxy = renderer.Proxy(sequence, frame, new SidecarCamera { Make = "Canon", Model = "Canon EOS R5" }, new ProxyPolicy { LongEdge = 400 })!;
Assert.Equal((300, 400), (proxy.Width, proxy.Height));
var exif = MetadataReader.Read(new MemoryStream(proxy.Jpeg), "p.jpg");
Assert.Equal(Start, exif.CapturedAt);
Assert.Equal("Canon EOS R5", exif.Model);
Assert.Equal(1, exif.Orientation);
}
}
@@ -0,0 +1,113 @@
using System.Text.Json;
using Titano.Core.Archiving;
using Titano.Testing;
namespace Titano.Core.Tests.Archiving;
[Category("archive")]
public sealed class LeaseFileTests(TestContext context)
{
private static void WriteRecord(string path, LeaseRecord record) =>
File.WriteAllBytes(path, JsonSerializer.SerializeToUtf8Bytes(record, ArchiveJson.Default.LeaseRecord));
[Test]
public void ALeaseIsExclusiveUntilReleased()
{
var locks = context.CreateTempDirectory();
using (var a = LeaseFile.TryAcquire(locks, "seq-1", "server"))
{
Assert.NotNull(a);
Assert.Null(LeaseFile.TryAcquire(locks, "seq-1", "client"));
using var other = LeaseFile.TryAcquire(locks, "seq-2", "client");
Assert.NotNull(other);
}
using var b = LeaseFile.TryAcquire(locks, "seq-1", "client");
Assert.NotNull(b);
Assert.Equal("client", LeaseFile.Read(LeaseFile.PathFor(locks, "seq-1"))!.Owner);
}
[Test]
public void AnExpiredLeaseOfACrashedHolderIsTakenOver()
{
var locks = context.CreateTempDirectory();
var past = DateTimeOffset.UtcNow.AddMinutes(-10);
WriteRecord(LeaseFile.PathFor(locks, "seq-1"), new LeaseRecord("dead", "crashed", "pc", 1, past, past.AddMinutes(2)));
using var lease = LeaseFile.TryAcquire(locks, "seq-1", "survivor");
Assert.NotNull(lease);
Assert.Equal("survivor", LeaseFile.Read(LeaseFile.PathFor(locks, "seq-1"))!.Owner);
Assert.Count(1, Directory.GetFiles(locks));
}
[Test]
public async Task AHeldLeaseIsRenewedPastItsDuration()
{
var locks = context.CreateTempDirectory();
using var lease = LeaseFile.TryAcquire(locks, "seq-1", "server", TimeSpan.FromMilliseconds(300));
Assert.NotNull(lease);
await Task.Delay(900);
Assert.True(lease.IsHeld);
Assert.Greater((LeaseFile.Read(lease.Path)!.Expires - DateTimeOffset.UtcNow).TotalMilliseconds, 0);
Assert.Null(LeaseFile.TryAcquire(locks, "seq-1", "client", TimeSpan.FromMilliseconds(300)));
}
[Test]
public void AFreshEmptyLeaseFileIsNotStaleButAnOldOneIs()
{
var locks = context.CreateTempDirectory();
var path = LeaseFile.PathFor(locks, "seq-1");
File.WriteAllBytes(path, []);
Assert.Null(LeaseFile.TryAcquire(locks, "seq-1", "client"));
File.SetLastWriteTimeUtc(path, DateTime.UtcNow.AddHours(-1));
using var lease = LeaseFile.TryAcquire(locks, "seq-1", "client");
Assert.NotNull(lease);
}
[Test]
public void ALostLeaseIsDetectedAndNotDeletedByItsFormerHolder()
{
var locks = context.CreateTempDirectory();
var lease = LeaseFile.TryAcquire(locks, "seq-1", "slow");
Assert.NotNull(lease);
var now = DateTimeOffset.UtcNow;
WriteRecord(lease.Path, new LeaseRecord("thief", "other", "pc", 2, now, now.AddMinutes(2)));
Assert.False(lease.Renew());
Assert.False(lease.IsHeld);
lease.Dispose();
Assert.Equal("thief", LeaseFile.Read(LeaseFile.PathFor(locks, "seq-1"))!.Token);
}
[Test]
public async Task WaitingForABusyLeaseTimesOutWithItsHolder()
{
var locks = context.CreateTempDirectory();
using var held = LeaseFile.TryAcquire(locks, "seq-1", "server");
var error = await Assert.ThrowsAsync<LeaseUnavailableException>(() =>
LeaseFile.AcquireAsync(locks, "seq-1", "client", TimeSpan.FromMilliseconds(200)));
Assert.Equal("server", error.Holder!.Owner);
}
[Test]
public async Task WaitingForALeaseSucceedsOnceItIsReleased()
{
var locks = context.CreateTempDirectory();
var held = LeaseFile.TryAcquire(locks, "seq-1", "server")!;
var waiting = LeaseFile.AcquireAsync(locks, "seq-1", "client", TimeSpan.FromSeconds(10));
await Task.Delay(100);
held.Dispose();
using var lease = await waiting;
Assert.Equal("client", lease.Record.Owner);
}
[Test]
public void CleanupRemovesOnlyStaleLeasesAndItsDryRunNothing()
{
var locks = context.CreateTempDirectory();
var past = DateTimeOffset.UtcNow.AddMinutes(-10);
WriteRecord(LeaseFile.PathFor(locks, "dead"), new LeaseRecord("t", "crashed", "pc", 1, past, past.AddMinutes(1)));
using var live = LeaseFile.TryAcquire(locks, "live", "server");
Assert.SequenceEqual(["dead"], LeaseFile.CleanupStale(locks, dryRun: true));
Assert.Count(2, Directory.GetFiles(locks));
Assert.SequenceEqual(["dead"], LeaseFile.CleanupStale(locks, dryRun: false));
Assert.SequenceEqual([LeaseFile.PathFor(locks, "live")], Directory.GetFiles(locks));
}
}
@@ -0,0 +1,157 @@
using System.Text;
using System.Text.Json;
using Titano.Core.Archiving;
using Titano.Core.Imaging;
using Titano.Core.IO;
using Titano.Core.Model;
using Titano.Testing;
namespace Titano.Core.Tests.Archiving;
[Category("archive")]
public sealed class ManifestStoreTests(TestContext context)
{
private static SequenceManifest Sample() => new()
{
Id = Guid.CreateVersion7(),
Title = "Harbour sunset",
Camera = new SidecarCamera { Make = "Canon", Model = "Canon EOS R5", Serial = "0431" },
Lens = "RF24-70mm F2.8 L IS USM",
Frames =
[
new SidecarFrame
{
Id = Guid.CreateVersion7(), I = 0, File = "originals/2026-09-28_18-02-11_0001.CR2", Original = "IMG_0001.CR2", Size = 25_000_000,
Sha256 = new string('a', 64), CapturedAt = new DateTime(2026, 9, 28, 18, 2, 11, 250), UtcOffset = 120,
TimeSource = TimestampSource.ExifOriginal, Exposure = 1.0 / 250, FNumber = 8, Iso = 100, Focal = 24, Bias = -0.3, Wb = 0,
Orientation = 6, W = 8192, H = 5464, Format = ImageFileFormat.Cr2, PreviewOffset = 1234, PreviewLength = 567_890,
Flags = FrameFlags.Excluded,
},
],
Tags = ["sunset", "harbour"],
Rating = 4,
Notes = "Windy",
Status = SequenceStatus.ThumbsBuilt | SequenceStatus.Verified,
Versions = new ManifestVersions { Settings = 3, Frames = 7 },
CreatedBy = "alberto",
Created = new DateTimeOffset(2026, 9, 28, 20, 0, 0, TimeSpan.Zero),
UpdatedAt = new DateTimeOffset(2026, 9, 29, 8, 0, 0, TimeSpan.Zero),
VerifiedAt = new DateTimeOffset(2026, 9, 30, 8, 0, 0, TimeSpan.Zero),
SessionKeys = ["card-1234abcd-20260928-180211"],
};
private string SidecarPath() => Path.Combine(context.CreateTempDirectory(), ".titano", "sequence.json");
private static string Canonical(SequenceManifest m) => JsonSerializer.Serialize(m, ArchiveJson.Default.SequenceManifest);
[Test]
public void SequenceSidecarRoundTripsEveryField()
{
var path = SidecarPath();
var original = Sample();
ManifestStore.WriteSequence(path, original);
var read = ManifestStore.ReadSequence(path);
Assert.Equal(Canonical(original), Canonical(read));
Assert.Equal(original.Frames[0], read.Frames[0] with { Extra = original.Frames[0].Extra });
var json = File.ReadAllText(path);
foreach (var field in new[] { "\"i\":", "\"file\":", "\"sha256\":", "\"capturedAt\":", "\"fNumber\":", "\"w\":", "\"previewOffset\":", "\"flags\":" })
Assert.Contains(field, json);
}
[Test]
public void UnknownFieldsAndEnumValuesFromANewerBuildAreReadAndKept()
{
var path = SidecarPath();
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
var id = Guid.CreateVersion7();
var frameId = Guid.CreateVersion7();
File.WriteAllText(path, $$"""
{
"schemaVersion": 1, "id": "{{id}}", "title": "Comet", "futureBlock": { "a": [1, 2] },
"camera": { "make": "Nikon", "sensorTemp": 31 },
"frames": [ { "id": "{{frameId}}", "i": 0, "file": "x.nef", "size": 10, "format": "Nef2030", "timeSource": "Atomic",
"flags": 4096, "aiScore": 0.9 } ],
"status": 1024, "versions": { "settings": 1, "frames": 2, "renders": 5 },
}
""");
var read = ManifestStore.ReadSequence(path);
Assert.Equal(id, read.Id);
Assert.Equal(ImageFileFormat.Unknown, read.Frames[0].Format);
Assert.Equal(TimestampSource.Unknown, read.Frames[0].TimeSource);
Assert.Equal((FrameFlags)4096, read.Frames[0].Flags);
ManifestStore.WriteSequence(path, read with { Title = "Comet 2026" });
var json = File.ReadAllText(path);
foreach (var kept in new[] { "futureBlock", "sensorTemp", "aiScore", "renders", "4096", "1024" }) Assert.Contains(kept, json);
Assert.Equal("Comet 2026", ManifestStore.ReadSequence(path).Title);
}
[Test]
public void ANewerSchemaIsReadableButNeverRewritten()
{
var path = SidecarPath();
ManifestStore.WriteSequence(path, Sample());
var newer = ManifestStore.ReadSequence(path) with { SchemaVersion = SequenceManifest.CurrentSchemaVersion + 1 };
var before = File.ReadAllBytes(path);
Assert.Throws<NewerFormatException>(() => ManifestStore.WriteSequence(path, newer));
Assert.BytesEqual(before, File.ReadAllBytes(path));
}
[Test]
public void DamagedJsonIsReportedAsInvalidData()
{
var path = SidecarPath();
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path, "{ \"id\": ");
Assert.Throws<InvalidDataException>(() => ManifestStore.ReadSequence(path));
File.WriteAllText(path, "{ \"title\": \"no id\" }");
Assert.Throws<InvalidDataException>(() => ManifestStore.ReadSequence(path));
}
[Test]
public void ACrashDuringAWriteLeavesThePreviousSidecarIntact()
{
var path = SidecarPath();
var first = Sample();
ManifestStore.WriteSequence(path, first);
// Simulated crash: the next version was half written to the temporary sibling and never renamed.
var torn = AtomicFile.TempPathFor(path);
File.WriteAllBytes(torn, Encoding.UTF8.GetBytes(Canonical(first with { Title = "Lost" })[..40]));
Assert.Equal(Canonical(first), Canonical(ManifestStore.ReadSequence(path)));
ManifestStore.WriteSequence(path, first with { Title = "Second" });
Assert.Equal("Second", ManifestStore.ReadSequence(path).Title);
Assert.FileExists(torn);
Assert.Equal(2, Directory.GetFiles(Path.GetDirectoryName(path)!).Length);
}
[Test]
public void CreatingASidecarClaimsTheFolderOnce()
{
var path = SidecarPath();
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
var a = Sample();
var b = Sample();
Assert.True(ManifestStore.TryCreateSequence(path, a));
Assert.False(ManifestStore.TryCreateSequence(path, b));
Assert.Equal(a.Id, ManifestStore.ReadSequence(path).Id);
Assert.Count(1, Directory.GetFiles(Path.GetDirectoryName(path)!));
}
[Test]
public void ArchiveManifestRoundTripsAndKeepsUnknownFields()
{
var path = Path.Combine(context.CreateTempDirectory(), "archive.json");
File.WriteAllText(path, $$"""
{ "schemaVersion": 1, "id": "{{Guid.CreateVersion7()}}", "name": "Main", "created": "2026-10-02T09:00:00+00:00",
"layoutTemplates": { "folder": "{year}/{title}", "file": "{n:00000}" }, "proxyPolicy": { "longEdge": 2560, "quality": 90 },
"syncPolicy": "mirror" }
""");
var read = ManifestStore.ReadArchive(path);
Assert.Equal("{year}/{title}", read.LayoutTemplates.Folder);
Assert.Equal(2560, read.ProxyPolicy.LongEdge);
ManifestStore.WriteArchive(path, read with { Name = "Studio" });
Assert.Contains("syncPolicy", File.ReadAllText(path));
Assert.Equal("Studio", ManifestStore.ReadArchive(path).Name);
}
}
@@ -0,0 +1,51 @@
using Titano.Core.Codecs.Jpeg;
using Titano.Core.Imaging;
using Titano.Core.Metadata;
namespace Titano.Core.Tests.Archiving;
/// <summary>Small real JPEGs with Exif (capture time, camera) made by the in-house encoder; each seed gives distinct bytes.</summary>
internal static class TestPhotos
{
public static byte[] Jpeg(DateTime captured, int seed, string make = "Canon", string model = "Canon EOS R5", string? serial = "0431",
int width = 48, int height = 32, int orientation = 1)
{
using var image = new ImageBuffer(width, height);
var random = new Random(seed);
for (var c = 0; c < 3; c++)
{
var plane = image.Plane(c);
var level = (float)random.NextDouble();
for (var i = 0; i < plane.Length; i++) plane[i] = level * (0.5f + 0.5f * (i % width) / width);
}
var exif = ExifWriter.BuildJpegApp1(new FrameMetadata
{
Make = make,
Model = model,
BodySerial = serial,
CapturedAt = captured,
ExposureTime = 1.0 / 125,
FNumber = 8,
Iso = 100,
Orientation = orientation,
});
return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 85, App1Segments = [exif[4..]] });
}
public static string Write(string path, DateTime captured, int seed, string make = "Canon", string model = "Canon EOS R5", string? serial = "0431")
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllBytes(path, Jpeg(captured, seed, make, model, serial));
return path;
}
/// <summary>Writes <paramref name="count"/> photos named IMG_0001.JPG… taken every <paramref name="interval"/>.</summary>
public static List<string> WriteSeries(string directory, DateTime start, int count, TimeSpan interval, int firstSeed = 1, string prefix = "IMG_",
string make = "Canon", string model = "Canon EOS R5", int firstNumber = 1)
{
var paths = new List<string>(count);
for (var i = 0; i < count; i++)
paths.Add(Write(Path.Combine(directory, $"{prefix}{firstNumber + i:0000}.JPG"), start + interval * i, firstSeed + i, make, model));
return paths;
}
}
@@ -0,0 +1,165 @@
using Titano.Core.Archiving;
using Titano.Testing;
namespace Titano.Core.Tests.Archiving;
[Category("archive")]
public sealed class ThumbPackTests(TestContext context)
{
private static byte[] Payload(int seed, int length = 300)
{
var data = new byte[length];
new Random(seed).NextBytes(data);
return data;
}
private static byte[] Hash(int seed) => ThumbPack.Fingerprint(null, $"originals/{seed}.jpg", seed);
private string NewPack() => Path.Combine(context.CreateTempDirectory(), ".titano", "thumbs.pack");
private static void Fill(string path, int count, int seedOffset = 0)
{
using var writer = ThumbPackWriter.Open(path);
for (var i = 0; i < count; i++) writer.Append(i, 320, 213, Hash(i + seedOffset), Payload(i + seedOffset));
}
[Test]
public void EntriesAreReadBackByFrameIndex()
{
var path = NewPack();
Fill(path, 100);
using var reader = ThumbPackReader.Open(path);
Assert.Equal(100, reader.Entries.Count);
Assert.BytesEqual(Payload(57), reader.Read(57));
Assert.BytesEqual(Hash(57), reader.Entries[57].SourceHash);
Assert.Equal(320, reader.Entries[57].Width);
Assert.Null(reader.Read(100));
}
[Test]
public void AppendingAgainReplacesAFrameAndKeepsTheOthers()
{
var path = NewPack();
Fill(path, 3);
using (var writer = ThumbPackWriter.Open(path))
{
Assert.Equal(3, writer.Entries.Count);
writer.Append(1, 200, 100, Hash(99), Payload(99));
writer.Append(3, 200, 100, Hash(3), Payload(3));
}
using var reader = ThumbPackReader.Open(path);
Assert.Equal(4, reader.Entries.Count);
Assert.BytesEqual(Payload(99), reader.Read(1));
Assert.BytesEqual(Payload(0), reader.Read(0));
Assert.BytesEqual(Payload(3), reader.Read(3));
}
[Test]
public void AnIncompleteTailIsIgnoredAndTruncatedByTheNextWriter()
{
var path = NewPack();
Fill(path, 2);
var committed = new FileInfo(path).Length;
// Simulated crash mid-append: an entry header and part of its payload, no index.
using (var stream = new FileStream(path, FileMode.Append))
{
stream.Write("TENT"u8);
stream.Write(BitConverter.GetBytes(2));
stream.Write(new byte[30]);
}
using (var reader = ThumbPackReader.Open(path))
{
Assert.Equal(2, reader.Entries.Count);
Assert.BytesEqual(Payload(1), reader.Read(1));
}
using (var writer = ThumbPackWriter.Open(path))
{
Assert.Equal(committed, new FileInfo(path).Length);
writer.Append(2, 320, 213, Hash(2), Payload(2));
}
using var after = ThumbPackReader.Open(path);
Assert.Equal(3, after.Entries.Count);
Assert.BytesEqual(Payload(2), after.Read(2));
}
[Test]
public void EntriesWrittenAfterTheLastIndexAreFoundWithoutIt()
{
var path = NewPack();
Fill(path, 5);
// Simulated crash after new entries overwrote the old index but before the new index was written.
var withoutIndex = File.ReadAllBytes(path);
using (var reader = ThumbPackReader.Open(path))
{
var end = reader.Entries.Values.Max(e => e.Offset + e.Length);
File.WriteAllBytes(path, withoutIndex[..(int)end]);
}
using var scanned = ThumbPackReader.Open(path);
Assert.Equal(5, scanned.Entries.Count);
for (var i = 0; i < 5; i++) Assert.BytesEqual(Payload(i), scanned.Read(i));
}
[Test]
public void ADamagedThumbnailReadsAsMissing()
{
var path = NewPack();
Fill(path, 3);
long offset;
using (var reader = ThumbPackReader.Open(path)) offset = reader.Entries[1].Offset;
using (var stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite))
{
stream.Position = offset + 10;
var b = stream.ReadByte();
stream.Position = offset + 10;
stream.WriteByte((byte)(b ^ 0xFF));
}
using var damaged = ThumbPackReader.Open(path);
Assert.Null(damaged.Read(1));
Assert.BytesEqual(Payload(2), damaged.Read(2));
}
[Test]
public void AnOpenReaderKeepsReadingWhileAWriterAppends()
{
var path = NewPack();
Fill(path, 3);
using var reader = ThumbPackReader.Open(path);
using (var writer = ThumbPackWriter.Open(path))
{
for (var i = 3; i < 50; i++) writer.Append(i, 320, 213, Hash(i), Payload(i, 2000));
}
Assert.BytesEqual(Payload(0), reader.Read(0));
Assert.BytesEqual(Payload(2), reader.Read(2));
using var fresh = ThumbPackReader.Open(path);
Assert.Equal(50, fresh.Entries.Count);
}
[Test]
public void CompactionDropsReplacedEntries()
{
var path = NewPack();
for (var round = 0; round < 4; round++) Fill(path, 20, seedOffset: round * 100);
long garbage;
using (var reader = ThumbPackReader.Open(path)) garbage = reader.GarbageBytes;
Assert.Greater(garbage, 0);
var before = new FileInfo(path).Length;
ThumbPackWriter.Compact(path);
Assert.Equal(before - garbage, new FileInfo(path).Length);
using var compacted = ThumbPackReader.Open(path);
Assert.Equal(0L, compacted.GarbageBytes);
for (var i = 0; i < 20; i++) Assert.BytesEqual(Payload(i + 300), compacted.Read(i));
}
[Test]
public void AMissingOrForeignFileReadsAsEmpty()
{
var path = NewPack();
using (var none = ThumbPackReader.Open(path)) Assert.Equal(0, none.Entries.Count);
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path, "not a pack");
using (var foreign = ThumbPackReader.Open(path)) Assert.Equal(0, foreign.Entries.Count);
Fill(path, 1);
using var rewritten = ThumbPackReader.Open(path);
Assert.Equal(1, rewritten.Entries.Count);
}
}
@@ -0,0 +1,179 @@
using Titano.Core.Archiving;
using Titano.Core.Import;
using Titano.Core.Tests.Archiving;
using Titano.Testing;
using static Titano.Core.Tests.Import.ImportTestKit;
namespace Titano.Core.Tests.Import;
[Category("import")]
public sealed class ImportExecutorTests(TestContext context)
{
private static readonly TimeSpan Interval = TimeSpan.FromSeconds(10);
private string Card(int frames = 70)
{
var card = context.CreateTempDirectory("card");
TestPhotos.WriteSeries(Path.Combine(card, "DCIM", "100CANON"), Start, frames, Interval);
return card;
}
private static Task<ImportProgress> RunAsync(ImportPlan plan, IImportSink sink, int startAt = 0, Func<ImportBatch, ValueTask>? committed = null,
CancellationToken cancellationToken = default) =>
new ImportExecutor(plan, sink).RunAsync(startAt, verify: true, committed ?? (_ => ValueTask.CompletedTask), null, cancellationToken);
[Test]
public async Task VerifiedCopyHashesPreservesTheTimeAndNeverOverwrites()
{
var dir = context.CreateTempDirectory();
var source = TestPhotos.Write(Path.Combine(dir, "a.jpg"), Start, 1);
File.SetLastWriteTimeUtc(source, new DateTime(2026, 9, 28, 16, 0, 0, DateTimeKind.Utc));
var target = Path.Combine(dir, "copy", "a.jpg");
var sha = await VerifiedCopy.CopyAsync(source, target, verify: true);
Assert.Equal(await ContentHash.Sha256Async(source), sha);
Assert.BytesEqual(File.ReadAllBytes(source), File.ReadAllBytes(target));
Assert.Equal(File.GetLastWriteTimeUtc(source), File.GetLastWriteTimeUtc(target));
var other = TestPhotos.Write(Path.Combine(dir, "b.jpg"), Start, 2);
await Assert.ThrowsAsync<IOException>(() => VerifiedCopy.CopyAsync(other, target, verify: true));
Assert.BytesEqual(File.ReadAllBytes(source), File.ReadAllBytes(target));
await Assert.ThrowsAsync<FileNotFoundException>(() => VerifiedCopy.CopyAsync(Path.Combine(dir, "gone.jpg"), Path.Combine(dir, "c.jpg"), true));
Assert.FileMissing(Path.Combine(dir, "c.jpg"));
}
[Test]
public async Task APlanIsCopiedExactlyIntoAFolder()
{
var card = Card();
var destination = context.CreateTempDirectory("dest");
var plan = await PlanAsync(card, destination);
var batches = new List<ImportBatch>();
var final = await RunAsync(plan, new FolderImportSink(destination), committed: b =>
{
batches.Add(b);
return ValueTask.CompletedTask;
});
Assert.Equal(70, final.Copied);
Assert.Equal(plan.CopyBytes, final.BytesDone);
Assert.SequenceEqual(plan.Items.Select(i => plan.Sessions[0].Folder + "/" + i.FileName).Order(StringComparer.Ordinal), Files(destination));
Assert.Equal(70, batches[^1].NextItem);
Assert.True(batches.Count >= 3);
Assert.Empty(Directory.EnumerateFiles(new FolderImportSink(destination).StagingDirectory));
foreach (var item in plan.Items)
{
Assert.BytesEqual(File.ReadAllBytes(Path.Combine(card, item.SourcePath)),
File.ReadAllBytes(Path.Combine(destination, plan.Sessions[0].Folder, item.FileName)));
}
}
[Test]
public async Task AnInterruptedImportResumesFromItsLastBatch()
{
var card = Card();
var destination = context.CreateTempDirectory("dest");
var plan = await PlanAsync(card, destination);
using var cts = new CancellationTokenSource();
var checkpoint = 0;
await Assert.ThrowsAsync<OperationCanceledException>(() => RunAsync(plan, new FolderImportSink(destination), committed: b =>
{
checkpoint = b.NextItem;
cts.Cancel();
return ValueTask.CompletedTask;
}, cancellationToken: cts.Token));
Assert.True(checkpoint is > 0 and < 70);
var final = await RunAsync(plan, new FolderImportSink(destination), startAt: checkpoint);
Assert.Equal(70 - checkpoint, final.Copied);
var reference = context.CreateTempDirectory("reference");
await RunAsync(await PlanAsync(card, reference), new FolderImportSink(reference));
Assert.SequenceEqual(Files(reference), Files(destination));
}
[Test]
public async Task RepeatingCommittedItemsYieldsDuplicatesNotSecondCopies()
{
var card = Card(20);
var destination = context.CreateTempDirectory("dest");
var plan = await PlanAsync(card, destination);
await RunAsync(plan, new FolderImportSink(destination));
var again = await RunAsync(plan, new FolderImportSink(destination), startAt: 10);
Assert.Equal(0, again.Copied);
Assert.Equal(10, again.Skipped);
Assert.Equal(20, Files(destination).Count);
}
[Test]
public async Task ARemovedCardStopsTheImportWhichResumesOnReinsertion()
{
var card = Card();
var destination = context.CreateTempDirectory("dest");
var plan = await PlanAsync(card, destination);
var aside = card + "-removed";
var checkpoint = 0;
await Assert.ThrowsAsync<ImportSourceUnavailableException>(() => RunAsync(plan, new FolderImportSink(destination), committed: b =>
{
checkpoint = b.NextItem;
if (Directory.Exists(card)) Directory.Move(card, aside); // the card is pulled after the first batch
return ValueTask.CompletedTask;
}));
Assert.Equal(checkpoint, Files(destination).Count);
Assert.Empty(Directory.EnumerateFiles(new FolderImportSink(destination).StagingDirectory));
Directory.Move(aside, card);
var final = await RunAsync(plan, new FolderImportSink(destination), startAt: checkpoint);
Assert.Equal(70 - checkpoint, final.Copied);
Assert.Equal(70, Files(destination).Count);
}
[Test]
public async Task AFileThatChangedSinceThePlanFailsAloneAndTheRestIsCopied()
{
var card = Card(20);
var destination = context.CreateTempDirectory("dest");
var plan = await PlanAsync(card, destination);
File.AppendAllText(Path.Combine(card, plan.Sessions[0].Items[5].SourcePath), "edited");
var failed = new List<ImportItemResult>();
var final = await RunAsync(plan, new FolderImportSink(destination), committed: b =>
{
failed.AddRange(b.Results.Where(r => r.Status == ImportItemStatus.Failed));
return ValueTask.CompletedTask;
});
Assert.Equal(19, final.Copied);
Assert.Equal(1, final.Failed);
Assert.Equal(plan.Sessions[0].Items[5].SourcePath, failed.Single().Item.SourcePath);
}
[Test]
public async Task ErasingDeletesOnlyFilesWhoseCardAndCopyStillMatch()
{
var card = Card(6);
var destination = context.CreateTempDirectory("dest");
var plan = await PlanAsync(card, destination, new ImportOptions { MinimumSessionFrames = 1 });
var results = new List<ImportItemResult>();
await RunAsync(plan, new FolderImportSink(destination), committed: b =>
{
results.AddRange(b.Results);
return ValueTask.CompletedTask;
});
var candidates = results.Select(r => new EraseCandidate(r.Item.SourcePath, r.Item.Size, r.Sha256!, Path.Combine(destination, r.Commit!.RelativePath)))
.ToList();
// Copy of item 1 damaged after import, card file of item 2 edited, copy of item 3 deleted.
var damaged = File.ReadAllBytes(candidates[1].CopyPath);
damaged[^10] ^= 0xFF;
File.WriteAllBytes(candidates[1].CopyPath, damaged);
File.AppendAllText(Path.Combine(card, candidates[2].SourcePath), "x");
File.Delete(candidates[3].CopyPath);
var erase = await CardEraser.PlanAsync(card, candidates);
Assert.SequenceEqual(
[EraseVerdict.Delete, EraseVerdict.CopyMismatch, EraseVerdict.SourceChanged, EraseVerdict.CopyMissing, EraseVerdict.Delete, EraseVerdict.Delete],
erase.Items.Select(i => i.Verdict));
Assert.Equal(6, Directory.EnumerateFiles(card, "*.JPG", SearchOption.AllDirectories).Count());
var done = CardEraser.Execute(erase);
Assert.Equal(3, done.Deleted);
Assert.Equal(3, done.Kept.Count);
var left = Directory.EnumerateFiles(card, "*.JPG", SearchOption.AllDirectories).Select(f => Path.GetRelativePath(card, f).Replace('\\', '/')).Order();
Assert.SequenceEqual(candidates.Skip(1).Take(3).Select(c => c.SourcePath).Order(), left);
}
}
@@ -0,0 +1,160 @@
using Titano.Core.Archiving;
using Titano.Core.Import;
using Titano.Core.Tests.Archiving;
using Titano.Testing;
using static Titano.Core.Tests.Import.ImportTestKit;
namespace Titano.Core.Tests.Import;
[Category("import")]
public sealed class ImportPlannerTests(TestContext context)
{
private static readonly TimeSpan Interval = TimeSpan.FromSeconds(10);
[Test]
public async Task ADcimCardIsPlannedWithTheDefaultTemplates()
{
var card = context.CreateTempDirectory("card");
TestPhotos.WriteSeries(Path.Combine(card, "DCIM", "100CANON"), Start, 10, Interval);
File.WriteAllBytes(Path.Combine(card, "DCIM", "100CANON", "._IMG_0001.JPG"), [0, 5, 22]);
File.WriteAllText(Path.Combine(card, "DCIM", "100CANON", "notes.txt"), "x");
TestPhotos.Write(Path.Combine(card, "MISC", "IMG_9999.JPG"), Start, 99);
var plan = await PlanAsync(card, context.CreateTempDirectory("archive"));
var session = plan.Sessions.Single();
Assert.Equal("2026/2026-09-28 Canon EOS R5", session.Folder);
Assert.Equal(10, plan.FileCount);
Assert.Equal(10, plan.CopyCount);
Assert.SequenceEqual(
["2026-09-28_18-00-00_0001.JPG", "2026-09-28_18-00-10_0002.JPG", "2026-09-28_18-00-20_0003.JPG"],
session.Items.Take(3).Select(i => i.FileName));
Assert.Equal("DCIM/100CANON/IMG_0001.JPG", session.Items[0].SourcePath);
Assert.Equal(plan.Items.Sum(i => i.Size), plan.CopyBytes);
Assert.NotNull(plan.AvailableBytes);
Assert.True(plan.HasEnoughSpace);
Assert.Empty(plan.Problems);
}
[Test]
public async Task AFlatFolderIncludesSubfoldersOnlyWhenAsked()
{
var card = context.CreateTempDirectory("card");
TestPhotos.WriteSeries(card, Start, 8, Interval);
TestPhotos.WriteSeries(Path.Combine(card, "more"), Start.AddSeconds(80), 8, Interval, firstSeed: 50, firstNumber: 9);
var destination = context.CreateTempDirectory("archive");
Assert.Equal(16, (await PlanAsync(card, destination)).FileCount);
Assert.Equal(8, (await PlanAsync(card, destination, new ImportOptions { IncludeSubfolders = false })).FileCount);
}
[Test]
public async Task SessionsAreSplitPerCameraBodyAndNumberedFromOne()
{
var card = context.CreateTempDirectory("card");
var dcim = Path.Combine(card, "DCIM", "100MEDIA");
TestPhotos.WriteSeries(dcim, Start, 10, Interval, prefix: "CAN_");
TestPhotos.WriteSeries(dcim, Start.AddHours(2), 10, Interval, firstSeed: 20, prefix: "CAN_", firstNumber: 11);
TestPhotos.WriteSeries(dcim, Start.AddSeconds(5), 9, Interval, firstSeed: 40, prefix: "NIK_", make: "NIKON CORPORATION", model: "NIKON Z 8");
var plan = await PlanAsync(card, context.CreateTempDirectory("archive"));
Assert.SequenceEqual(
["2026/2026-09-28 Canon EOS R5", "2026/2026-09-28 Nikon Z 8", "2026/2026-09-28 Canon EOS R5 (2)"],
plan.Sessions.Select(s => s.Folder));
Assert.SequenceEqual([1, 2, 3], plan.Sessions.Select(s => s.Number));
Assert.Equal("2026-09-28_20-00-00_0001.JPG", plan.Sessions[2].Items[0].FileName);
Assert.Equal(3, plan.Sessions.Select(s => s.SessionKey).Distinct().Count());
Assert.True(plan.Sessions.All(s => s.Items.All(i => i.SourcePath.Contains(s.CameraModel == "NIKON Z 8" ? "NIK_" : "CAN_"))));
}
[Test]
public async Task NamesTakenTwiceGetASuffix()
{
var card = context.CreateTempDirectory("card");
TestPhotos.WriteSeries(card, Start, 3, Interval);
var plan = await PlanAsync(card, context.CreateTempDirectory("archive"), new ImportOptions { FileTemplate = "{date}", MinimumSessionFrames = 1 });
Assert.SequenceEqual(["2026-09-28.JPG", "2026-09-28_2.JPG", "2026-09-28_3.JPG"], plan.Sessions[0].Items.Select(i => i.FileName));
}
[Test]
public async Task ImportedAndArchivedPhotosAreSkippedAfterAHashMatch()
{
var card = context.CreateTempDirectory("card");
var files = TestPhotos.WriteSeries(card, Start, 10, Interval);
var lookup = new FakeLookup();
lookup.Imported.Add("IMG_0001.JPG");
var archived = await ContentHash.Sha256Async(files[1]);
lookup.Archive.Add((new FileInfo(files[1]).Length, Start + Interval, new ArchiveMatch(Guid.NewGuid(), archived)));
lookup.Archive.Add((new FileInfo(files[2]).Length, Start + 2 * Interval, new ArchiveMatch(Guid.NewGuid(), new string('0', 64))));
var plan = await PlanAsync(card, context.CreateTempDirectory("archive"), lookup: lookup);
var items = plan.Sessions[0].Items;
Assert.Equal(ImportAction.SkipImported, items[0].Action);
Assert.Equal(ImportAction.SkipInArchive, items[1].Action);
Assert.Equal(lookup.Archive[0].Match.FrameId, items[1].ExistingFrameId);
Assert.Equal(ImportAction.Copy, items[2].Action);
Assert.Equal(await ContentHash.Sha256Async(files[2]), items[2].Sha256);
Assert.Null(items[3].Sha256);
Assert.Equal(8, plan.CopyCount);
Assert.Equal("2026-09-28_18-00-10_0002.JPG", items[1].FileName);
var again = await PlanAsync(card, context.CreateTempDirectory("archive"), new ImportOptions { Duplicates = DuplicatePolicy.ImportAgain }, lookup);
Assert.Equal(ImportAction.Copy, again.Sessions[0].Items[1].Action);
Assert.Equal(lookup.Archive[0].Match.FrameId, again.Sessions[0].Items[1].ExistingFrameId);
}
[Test]
public async Task ReplanningGivesStableKeysThatTitlesAndEarlierFoldersAttachTo()
{
var card = context.CreateTempDirectory("card");
TestPhotos.WriteSeries(card, Start, 10, Interval);
var destination = context.CreateTempDirectory("archive");
var first = await PlanAsync(card, destination);
var key = first.Sessions[0].SessionKey;
Assert.Equal(key, (await PlanAsync(card, destination)).Sessions[0].SessionKey);
var titled = await PlanAsync(card, destination, new ImportOptions
{
FolderTemplate = "{year}/{date} {title}",
Titles = new Dictionary<string, string> { [key] = "Harbour sunset" },
});
Assert.Equal("2026/2026-09-28 Harbour sunset", titled.Sessions[0].Folder);
Assert.Equal("Harbour sunset", titled.Sessions[0].Title);
var lookup = new FakeLookup();
lookup.SessionFolders[key] = "2026/earlier import";
Assert.Equal("2026/earlier import", (await PlanAsync(card, destination, lookup: lookup)).Sessions[0].Folder);
var taken = new FakeLookup();
taken.TakenFolders.Add("2026/2026-09-28 Canon EOS R5");
Assert.Equal("2026/2026-09-28 Canon EOS R5 (2)", (await PlanAsync(card, destination, lookup: taken)).Sessions[0].Folder);
}
[Test]
public async Task UserMergeAndSplitReshapeSessions()
{
var card = context.CreateTempDirectory("card");
TestPhotos.WriteSeries(card, Start, 10, Interval);
TestPhotos.WriteSeries(card, Start.AddHours(3), 10, Interval, firstSeed: 30, firstNumber: 11);
var destination = context.CreateTempDirectory("archive");
Assert.Equal(2, (await PlanAsync(card, destination)).Sessions.Count);
var merged = await PlanAsync(card, destination, new ImportOptions { MergeAt = new HashSet<string> { "IMG_0011.JPG" } });
Assert.Equal(20, merged.Sessions.Single().Items.Count);
Assert.Equal("2026-09-28_21-00-00_0011.JPG", merged.Sessions[0].Items[10].FileName);
var split = await PlanAsync(card, destination, new ImportOptions { SplitBefore = new HashSet<string> { "IMG_0006.JPG" } });
Assert.SequenceEqual([5, 5, 10], split.Sessions.Select(s => s.Items.Count));
}
[Test]
public async Task APhotoWithoutExifIsPlannedAtItsFileTime()
{
var card = context.CreateTempDirectory("card");
TestPhotos.WriteSeries(card, Start, 8, Interval);
var bare = Path.Combine(card, "BARE.JPG");
File.WriteAllBytes(bare, [0xFF, 0xD8, 0xFF, 0xD9]);
File.SetLastWriteTime(bare, Start.AddSeconds(85));
var plan = await PlanAsync(card, context.CreateTempDirectory("archive"));
var item = plan.Items.Single(i => i.SourcePath == "BARE.JPG");
Assert.Equal(Start.AddSeconds(85), item.CapturedAt);
// No camera identity: it forms its own body group rather than joining the Canon session.
Assert.SequenceEqual([8, 1], plan.Sessions.Select(s => s.Items.Count));
}
}
@@ -0,0 +1,48 @@
using Titano.Core.Import;
namespace Titano.Core.Tests.Import;
/// <summary>An <see cref="IImportLookup"/> answered from in-memory sets.</summary>
internal sealed class FakeLookup : IImportLookup
{
public HashSet<string> Imported { get; } = [];
public List<(long Size, DateTime Captured, ArchiveMatch Match)> Archive { get; } = [];
public Dictionary<string, string> SessionFolders { get; } = [];
public HashSet<string> TakenFolders { get; } = new(StringComparer.OrdinalIgnoreCase);
public int CandidateQueries { get; private set; }
public Task<bool> WasImportedAsync(CardFile file, CancellationToken cancellationToken) => Task.FromResult(Imported.Contains(file.RelativePath));
public Task<IReadOnlyList<ArchiveMatch>> FindCandidatesAsync(long size, DateTime capturedAt, CancellationToken cancellationToken)
{
CandidateQueries++;
return Task.FromResult<IReadOnlyList<ArchiveMatch>>(Archive.Where(a => a.Size == size && a.Captured == capturedAt).Select(a => a.Match).ToList());
}
public Task<string?> FindSessionFolderAsync(string sessionKey, CancellationToken cancellationToken) =>
Task.FromResult(SessionFolders.GetValueOrDefault(sessionKey));
public bool IsFolderTaken(string folder) => TakenFolders.Contains(folder);
}
internal static class ImportTestKit
{
public static readonly DateTime Start = new(2026, 9, 28, 18, 0, 0);
/// <summary>Plans an import of <paramref name="card"/> into <paramref name="destination"/>.</summary>
public static async Task<ImportPlan> PlanAsync(string card, string destination, ImportOptions? options = null, FakeLookup? lookup = null)
{
options ??= new ImportOptions();
var problems = new List<ImportProblem>();
var photos = CardScanner.ReadMetadata(card, CardScanner.Find(card, options.IncludeSubfolders), problems);
return await ImportPlanner.PlanAsync(card, destination, photos, problems, options, lookup ?? new FakeLookup());
}
/// <summary>Every file below <paramref name="root"/> (relative, forward slashes), excluding Titano's metadata folders.</summary>
public static List<string> Files(string root) =>
Directory.EnumerateFiles(root, "*", SearchOption.AllDirectories)
.Select(f => Path.GetRelativePath(root, f).Replace('\\', '/'))
.Where(f => !f.StartsWith(".titano/", StringComparison.Ordinal))
.Order(StringComparer.Ordinal)
.ToList();
}
@@ -0,0 +1,73 @@
using Titano.Core.Import;
using Titano.Testing;
namespace Titano.Core.Tests.Import;
[Category("import")]
public sealed class SessionSplitterTests
{
private static readonly DateTime Start = new(2026, 9, 28, 18, 0, 0);
private static readonly TimeSpan Gap = TimeSpan.FromMinutes(45);
/// <summary>Capture times from a compact description: runs of frames 10 s apart, separated by pauses in minutes.</summary>
private static List<DateTime> Times(params (int Frames, int PauseBeforeMinutes)[] runs)
{
var times = new List<DateTime>();
var t = Start;
foreach (var (frames, pause) in runs)
{
t = t.AddMinutes(pause);
for (var i = 0; i < frames; i++)
{
times.Add(t);
t = t.AddSeconds(10);
}
}
return times;
}
private static string Describe(IReadOnlyList<SessionRange> ranges) => string.Join(",", ranges.Select(r => r.Count));
[Theory]
[Case(new[] { 30 }, new[] { 0 }, "30", Name = "one session")]
[Case(new[] { 30, 40 }, new[] { 0, 60 }, "30,40", Name = "pause longer than the gap splits")]
[Case(new[] { 30, 40 }, new[] { 0, 44 }, "70", Name = "pause shorter than the gap does not")]
[Case(new[] { 3, 30 }, new[] { 0, 90 }, "33", Name = "leading test shots join the next session")]
[Case(new[] { 30, 3 }, new[] { 0, 90 }, "33", Name = "trailing test shots join the previous session")]
[Case(new[] { 30, 2, 30 }, new[] { 0, 90, 90 }, "32,30", Name = "small middle group joins the previous session")]
[Case(new[] { 2, 3 }, new[] { 0, 90 }, "5", Name = "only small groups make one session")]
public void AutomaticSessions(int[] frames, int[] pauses, string expected)
{
var times = Times(frames.Zip(pauses).ToArray());
Assert.Equal(expected, Describe(SessionSplitter.Split(times, Gap, 8)));
}
[Test]
public void APauseOfExactlyTheGapDoesNotSplit()
{
var times = new List<DateTime> { Start };
for (var i = 1; i < 10; i++) times.Add(Start.AddSeconds(i));
for (var i = 0; i < 10; i++) times.Add(times[9] + Gap + TimeSpan.FromSeconds(i));
Assert.Equal("20", Describe(SessionSplitter.Split(times, Gap, 8)));
}
[Test]
public void UserSplitsAndMergesOverrideTheRules()
{
var times = Times((30, 0), (40, 60));
// Split before frame 25 (a 5-frame group the user wants on its own) and merge the automatic break at 30.
var ranges = SessionSplitter.Split(times, Gap, 8, i => i == 25 ? true : i == 30 ? false : null);
Assert.Equal("25,45", Describe(ranges));
Assert.Equal(25, ranges[1].Start);
}
[Test]
public void AForcedSmallSessionIsNotMergedAway()
{
var times = Times((30, 0));
Assert.Equal("28,2", Describe(SessionSplitter.Split(times, Gap, 8, i => i == 28 ? true : null)));
}
[Test]
public void NoFramesNoSessions() => Assert.Empty(SessionSplitter.Split([], Gap, 8));
}
@@ -0,0 +1,162 @@
using System.Security.Cryptography;
using Titano.Core.Archiving;
using Titano.Core.Codecs.Jpeg;
using Titano.Core.Imaging;
using Titano.Core.Metadata;
using Titano.Core.Model;
using Titano.Data.Archiving;
using Titano.Data.Jobs;
using Titano.Testing;
namespace Titano.Data.Tests.Archiving;
/// <summary>A temporary archive root with its SQLite index and the archive service.</summary>
internal sealed class ArchiveFixture : IAsyncDisposable
{
public static readonly DateTime Start = new(2026, 9, 28, 18, 0, 0);
private readonly TestContext _context;
private readonly List<IAsyncDisposable> _owned = [];
private ArchiveFixture(TestContext context, TitanoDatabase db, ArchiveService service, Archive archive)
{
_context = context;
Db = db;
Service = service;
Archive = archive;
_owned.Add(db);
}
public TitanoDatabase Db { get; private set; }
public ArchiveService Service { get; private set; }
public Archive Archive { get; private set; }
public ArchivePaths Paths => new(Archive.RootPath);
public CancellationToken Ct => _context.Cancellation;
public static async Task<ArchiveFixture> CreateAsync(TestContext context, string? root = null)
{
var db = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory("db"), "titano.db")), context.Cancellation);
var service = new ArchiveService(db, new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) });
var archive = await service.AdoptAsync(root ?? context.CreateTempDirectory("archive"), "Main", context.Cancellation);
return new ArchiveFixture(context, db, service, archive);
}
/// <summary>Switches to a brand-new empty index of the same archive (the "lost database" case).</summary>
public async Task ReopenWithEmptyIndexAsync()
{
var db = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(_context.CreateTempDirectory("db2"), "titano.db")), Ct);
_owned.Add(db);
Db = db;
Service = new ArchiveService(db, new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) });
Archive = await Service.OpenAsync(Archive.RootPath, Ct);
}
public Task<ScanSummary> ScanAsync(ScanMode mode = ScanMode.Incremental) =>
Service.Indexer.ScanAsync(Archive, mode, null, _ => ValueTask.CompletedTask, Ct);
/// <summary>A job engine with the archive handlers, started; disposed with the fixture.</summary>
public async Task<JobEngine> StartEngineAsync()
{
var engine = new JobEngine(Db, Service.CreateJobHandlers(),
new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
_owned.Insert(0, engine);
await engine.StartAsync(Ct);
return engine;
}
public async Task<Job> WaitForAsync(Guid jobId, JobState state, int seconds = 30)
{
var until = DateTime.UtcNow.AddSeconds(seconds);
Job? job = null;
while (DateTime.UtcNow < until)
{
job = await Db.Jobs.GetAsync(jobId, Ct);
if (job?.State == state) return job;
if (job?.State is JobState.Failed && state != JobState.Failed) Assert.Fail($"Job failed: {job.Error}\n{job.LogTail}");
await Task.Delay(20, Ct);
}
Assert.Fail($"Job {jobId} did not reach {state} (now {job?.State}): {job?.Error}\n{job?.LogTail}");
return null!;
}
/// <summary>Queues a job directly with a checkpoint, as a crashed earlier attempt would have left it.</summary>
public async Task<Job> EnqueueWithCheckpointAsync(JobEngine engine, Titano.Data.Archiving.Jobs.ArchiveJobRequest request, string checkpoint)
{
var job = new Job
{
Id = Guid.CreateVersion7(),
Kind = request.Kind,
TargetIds = request.Targets,
ParametersJson = request.ParametersJson,
State = JobState.Queued,
Checkpoint = checkpoint,
Created = DateTimeOffset.UtcNow,
};
await Db.Jobs.EnqueueAsync(job, Ct);
engine.Wake();
return job;
}
/// <summary>Stages a verified upload-like file for ingest: returns its path, size and SHA-256.</summary>
public (string Path, long Size, string Sha256) Stage(DateTime captured, int seed, string make = "Canon", string model = "Canon EOS R5")
{
var staging = Path.Combine(Paths.StagingDirectory, "uploads");
Directory.CreateDirectory(staging);
var bytes = Photos.Jpeg(captured, seed, make, model);
var path = Path.Combine(staging, $"{Guid.NewGuid():N}.part");
File.WriteAllBytes(path, bytes);
return (path, bytes.Length, Convert.ToHexStringLower(SHA256.HashData(bytes)));
}
public async ValueTask DisposeAsync()
{
foreach (var owned in _owned) await owned.DisposeAsync();
}
}
/// <summary>Small real JPEGs with Exif made by the in-house encoder; each seed gives distinct bytes.</summary>
internal static class Photos
{
public static byte[] Jpeg(DateTime captured, int seed, string make = "Canon", string model = "Canon EOS R5")
{
using var image = new ImageBuffer(48, 32);
var random = new Random(seed);
for (var c = 0; c < 3; c++)
{
var plane = image.Plane(c);
var level = (float)random.NextDouble();
for (var i = 0; i < plane.Length; i++) plane[i] = level * (0.5f + 0.5f * (i % 48) / 48f);
}
var exif = ExifWriter.BuildJpegApp1(new FrameMetadata { Make = make, Model = model, BodySerial = "0431", CapturedAt = captured, Iso = 100 });
return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 85, App1Segments = [exif[4..]] });
}
public static List<string> WriteSeries(string directory, DateTime start, int count, int firstSeed = 1, string prefix = "IMG_", int firstNumber = 1,
string make = "Canon", string model = "Canon EOS R5")
{
Directory.CreateDirectory(directory);
var paths = new List<string>(count);
for (var i = 0; i < count; i++)
{
var path = Path.Combine(directory, $"{prefix}{firstNumber + i:0000}.JPG");
File.WriteAllBytes(path, Jpeg(start.AddSeconds(10 * i), firstSeed + i, make, model));
paths.Add(path);
}
return paths;
}
/// <summary>The index as comparable text: sequences and frames ordered by folder and index.</summary>
public static async Task<string> DumpIndexAsync(TitanoDatabase db, Guid archiveId)
{
var lines = new List<string>();
foreach (var location in await db.Sequences.ListLocationsAsync(archiveId))
{
var s = (await db.Sequences.GetAsync(location.Id))!;
lines.Add($"S {s.Id} {s.Folder} '{s.Title}' {s.CameraModel} {s.FirstCapture:O} {s.FrameCount} {s.TotalBytes} {s.Status} {s.VerifiedAt:O} " +
$"{string.Join('|', s.Tags)} {s.SettingsVersion}/{s.FramesVersion} {s.MedianInterval}");
foreach (var f in await db.Frames.ListBySequenceAsync(s.Id))
lines.Add($" F {f.Id} {f.Index} {f.RelativePath} {f.OriginalFileName} {f.Size} {f.Sha256} {f.CapturedAt:O} {f.Width}x{f.Height} {f.Format} {f.Flags}");
}
return string.Join('\n', lines);
}
}
@@ -0,0 +1,180 @@
using Titano.Core.Archiving;
using Titano.Core.Model;
using Titano.Data.Archiving;
using Titano.Testing;
using static Titano.Data.Tests.Archiving.ArchiveFixture;
namespace Titano.Data.Tests.Archiving;
[Category("archive")]
public sealed class ArchiveIndexTests(TestContext context)
{
/// <summary>Two folders adopted in place and one folder in the layout whose sidecar was lost.</summary>
private static void Populate(ArchivePaths paths)
{
Photos.WriteSeries(Path.Combine(paths.Root, "Trips", "Harbour sunset"), Start, 6);
Photos.WriteSeries(Path.Combine(paths.Root, "Trips", "Comet"), Start.AddDays(1), 4, firstSeed: 100);
Photos.WriteSeries(Path.Combine(paths.Root, "2026", "2026-09-30 Canon EOS R5", "originals"), Start.AddDays(2), 5, firstSeed: 200);
}
[Test]
public async Task AdoptionIndexesFoldersInPlaceWithoutTouchingPhotos()
{
await using var fx = await CreateAsync(context);
Populate(fx.Paths);
var photos = Directory.EnumerateFiles(fx.Paths.Root, "*.JPG", SearchOption.AllDirectories).ToDictionary(p => p, File.ReadAllBytes);
var summary = await fx.ScanAsync(ScanMode.Full);
Assert.Equal(3, summary.Adopted);
Assert.Empty(summary.Failed);
var stats = await fx.Db.Sequences.GetStatsAsync(fx.Archive.Id);
Assert.Equal(3, stats.Sequences);
Assert.Equal(15L, stats.Photos);
var harbour = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Single(l => l.Folder == "Trips/Harbour sunset");
Assert.Equal("Harbour sunset", harbour.Title);
var frames = await fx.Db.Frames.ListBySequenceAsync(harbour.Id);
Assert.Equal("Trips/Harbour sunset/IMG_0001.JPG", frames[0].RelativePath);
Assert.Equal(Start, frames[0].CapturedAt);
Assert.Equal(10.0, (await fx.Db.Sequences.GetAsync(harbour.Id))!.MedianInterval);
Assert.FileExists(Path.Combine(fx.Paths.Root, "Trips", "Harbour sunset", ".titano", "sequence.json"));
foreach (var (path, bytes) in photos) Assert.BytesEqual(bytes, File.ReadAllBytes(path));
}
[Test]
public async Task AnUnchangedArchiveRescansWithoutReadingSidecars()
{
await using var fx = await CreateAsync(context);
Populate(fx.Paths);
await fx.ScanAsync();
var again = await fx.ScanAsync();
Assert.Equal(3, again.Folders);
Assert.Equal(0, again.Indexed);
// A photo dropped into a folder and a title edited in a sidecar by another machine.
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "Trips", "Comet"), Start.AddDays(1).AddMinutes(1), 1, firstSeed: 150, firstNumber: 5);
var sidecar = fx.Paths.Sequence("Trips/Harbour sunset").ManifestPath;
var manifest = ManifestStore.ReadSequence(sidecar);
ManifestStore.WriteSequence(sidecar, manifest with { Title = "Harbour at dusk", Versions = manifest.Versions with { Settings = 5 } });
var changed = await fx.ScanAsync();
Assert.Equal(2, changed.Indexed);
var locations = await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id);
Assert.Equal("Harbour at dusk", locations.Single(l => l.Folder == "Trips/Harbour sunset").Title);
Assert.Equal(5, (await fx.Db.Sequences.GetAsync(locations.Single(l => l.Folder == "Trips/Comet").Id))!.FrameCount);
Assert.Equal(0, (await fx.ScanAsync()).Indexed);
}
[Test]
public async Task RebuildingFromSidecarsGivesTheSameIndex()
{
await using var fx = await CreateAsync(context);
Populate(fx.Paths);
await fx.ScanAsync(ScanMode.Full);
var comet = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Single(l => l.Folder == "Trips/Comet");
await fx.Service.SetSequenceInfoAsync(comet.Id, "Comet", ["sky", "night"], 5, "Clear", fx.Ct);
var before = await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id);
await fx.ReopenWithEmptyIndexAsync();
var rebuilt = await fx.Service.Indexer.ScanAsync(fx.Archive, ScanMode.Rebuild, null, _ => ValueTask.CompletedTask, fx.Ct);
Assert.Equal(0, rebuilt.Adopted);
Assert.Equal(before, await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id));
// A second rebuild reads the snapshot written by the first and still yields the same index.
Assert.NotNull(IndexSnapshot.TryLoad(fx.Paths.SnapshotPath));
await fx.ReopenWithEmptyIndexAsync();
await fx.Service.Indexer.ScanAsync(fx.Archive, ScanMode.Rebuild, null, _ => ValueTask.CompletedTask, fx.Ct);
Assert.Equal(before, await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id));
}
[Test]
public async Task RebuildDropsRowsWhoseSidecarIsGoneAndScanKeepsThem()
{
await using var fx = await CreateAsync(context);
Populate(fx.Paths);
await fx.ScanAsync();
Directory.Move(Path.Combine(fx.Paths.Root, "Trips", "Comet"), Path.Combine(context.CreateTempDirectory("elsewhere"), "Comet"));
await fx.ScanAsync();
Assert.Equal(3, (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Count);
var orphans = await fx.Service.FindOrphansAsync(fx.Archive.Id, fx.Ct);
Assert.Equal("Trips/Comet", orphans.MissingSequences.Single().Folder);
var summary = await fx.ScanAsync(ScanMode.Rebuild);
Assert.Equal(1, summary.Removed);
Assert.Equal(2, (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Count);
}
[Test]
public async Task ADamagedSidecarIsKeptAsideAndRebuiltWithTheSameIds()
{
await using var fx = await CreateAsync(context);
Populate(fx.Paths);
await fx.ScanAsync();
var harbour = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Single(l => l.Folder == "Trips/Harbour sunset");
var frameIds = (await fx.Db.Frames.ListBySequenceAsync(harbour.Id)).Select(f => f.Id).ToList();
var sidecar = fx.Paths.Sequence(harbour.Folder).ManifestPath;
File.WriteAllText(sidecar, "{ \"id\": \"broken");
var summary = await fx.ScanAsync();
Assert.Empty(summary.Failed);
Assert.Equal(harbour.Id, ManifestStore.ReadSequence(sidecar).Id);
Assert.SequenceEqual(frameIds, (await fx.Db.Frames.ListBySequenceAsync(harbour.Id)).Select(f => f.Id));
Assert.Count(1, Directory.GetFiles(Path.GetDirectoryName(sidecar)!, "sequence.json.damaged-*"));
}
[Test]
public async Task ACopiedSequenceFolderGetsItsOwnIdentity()
{
await using var fx = await CreateAsync(context);
Populate(fx.Paths);
await fx.ScanAsync();
var source = Path.Combine(fx.Paths.Root, "Trips", "Comet");
var copy = Path.Combine(fx.Paths.Root, "Trips", "Comet copy");
Directory.CreateDirectory(Path.Combine(copy, ".titano"));
foreach (var file in Directory.EnumerateFiles(source, "*", SearchOption.AllDirectories))
File.Copy(file, Path.Combine(copy, Path.GetRelativePath(source, file)));
await fx.ScanAsync();
var locations = await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id);
Assert.Equal(4, locations.Count);
var original = locations.Single(l => l.Folder == "Trips/Comet");
var copied = locations.Single(l => l.Folder == "Trips/Comet copy");
Assert.NotEqual(original.Id, copied.Id);
Assert.Equal(4, (await fx.Db.Frames.ListBySequenceAsync(original.Id)).Count);
Assert.Equal(4, (await fx.Db.Frames.ListBySequenceAsync(copied.Id)).Count);
Assert.Equal(copied.Id, ManifestStore.ReadSequence(fx.Paths.Sequence("Trips/Comet copy").ManifestPath).Id);
}
[Test]
public async Task AnOfflineArchiveIsLeftAsItWas()
{
var root = context.CreateTempDirectory("archive");
await using var fx = await CreateAsync(context, root);
Populate(fx.Paths);
await fx.ScanAsync();
var before = await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id);
var unplugged = root + "-unplugged";
Directory.Move(root, unplugged);
Assert.Equal(ArchiveAvailability.Offline, ArchiveService.GetAvailability(fx.Archive));
await Assert.ThrowsAsync<ArchiveOfflineException>(() => fx.ScanAsync(ScanMode.Rebuild));
Assert.Equal(before, await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id));
Directory.Move(unplugged, root);
Assert.Equal(ArchiveAvailability.Online, ArchiveService.GetAvailability(fx.Archive));
}
[Test]
public async Task SequenceInfoIsWrittenToSidecarAndIndexTogether()
{
await using var fx = await CreateAsync(context);
Populate(fx.Paths);
await fx.ScanAsync();
var comet = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Single(l => l.Folder == "Trips/Comet");
var updated = await fx.Service.SetSequenceInfoAsync(comet.Id, " Comet 2026 ", ["Night"], 4, "Tripod", fx.Ct);
Assert.Equal("Comet 2026", updated.Title);
var manifest = ManifestStore.ReadSequence(fx.Paths.Sequence(comet.Folder).ManifestPath);
Assert.Equal("Comet 2026", manifest.Title);
Assert.SequenceEqual(["Night"], manifest.Tags);
Assert.Equal(updated.SettingsVersion, manifest.Versions.Settings);
Assert.SequenceEqual(["Night"], (await fx.Db.Sequences.GetAsync(comet.Id))!.Tags);
Assert.Equal(0, (await fx.ScanAsync()).Indexed);
}
}
@@ -0,0 +1,124 @@
using Titano.Core.Archiving;
using Titano.Data.Archiving;
using Titano.Testing;
using static Titano.Data.Tests.Archiving.ArchiveFixture;
namespace Titano.Data.Tests.Archiving;
[Category("archive")]
public sealed class ArchiveIngestTests(TestContext context)
{
private static IngestRequest Request(ArchiveFixture fx, (string Path, long Size, string Sha256) staged, string? sessionKey = "upload-1",
Guid? sequenceId = null, string? title = null, string name = "IMG_0001.JPG") =>
new(fx.Archive.Id, sequenceId, title, sequenceId is null && title is null ? sessionKey : null, staged.Path, name, staged.Size, staged.Sha256, null, null);
[Test]
public async Task ASessionKeyCreatesOneSequenceNamedByTheTemplates()
{
await using var fx = await CreateAsync(context);
var first = fx.Stage(Start, 1);
var a = await fx.Service.Ingest.CommitAsync(Request(fx, first), fx.Ct);
var b = await fx.Service.Ingest.CommitAsync(Request(fx, fx.Stage(Start.AddSeconds(10), 2), name: "IMG_0002.JPG"), fx.Ct);
Assert.Equal(a.SequenceId, b.SequenceId);
Assert.Equal("2026/2026-09-28 Canon EOS R5/originals/2026-09-28_18-00-00_0001.JPG", a.RelativePath);
Assert.Equal("2026/2026-09-28 Canon EOS R5/originals/2026-09-28_18-00-10_0002.JPG", b.RelativePath);
Assert.Equal((0, 1), (a.Index, b.Index));
Assert.False(a.Duplicate);
Assert.FileMissing(first.Path);
var manifest = ManifestStore.ReadSequence(fx.Paths.Sequence("2026/2026-09-28 Canon EOS R5").ManifestPath);
Assert.Equal(a.SequenceId, manifest.Id);
Assert.SequenceEqual(["upload-1"], manifest.SessionKeys);
Assert.Equal("IMG_0002.JPG", manifest.Frames[1].Original);
Assert.Equal(first.Sha256, manifest.Frames[0].Sha256);
Assert.Equal(2, (await fx.Db.Sequences.GetAsync(a.SequenceId))!.FrameCount);
Assert.Equal(0, (await fx.ScanAsync()).Indexed);
}
[Test]
public async Task TheSameContentIsReportedAsDuplicateAndNotCopiedTwice()
{
await using var fx = await CreateAsync(context);
var original = await fx.Service.Ingest.CommitAsync(Request(fx, fx.Stage(Start, 7)), fx.Ct);
var again = fx.Stage(Start, 7);
var duplicate = await fx.Service.Ingest.CommitAsync(Request(fx, again), fx.Ct);
Assert.True(duplicate.Duplicate);
Assert.Equal(original.FrameId, duplicate.FrameId);
Assert.Equal(original.RelativePath, duplicate.RelativePath);
Assert.FileExists(again.Path);
Assert.Equal(1, (await fx.Db.Sequences.GetAsync(original.SequenceId))!.FrameCount);
}
[Test]
public async Task ParallelCommitsToOneSequenceGiveGapFreeIndexesAndAValidSidecar()
{
await using var fx = await CreateAsync(context);
const int count = 40;
var staged = Enumerable.Range(0, count).Select(i => fx.Stage(Start.AddSeconds(10 * i), 1000 + i)).ToList();
// Arrival order differs from capture order, as with parallel chunked uploads.
var order = Enumerable.Range(0, count).OrderBy(i => (i * 17) % count).ToList();
var results = await Task.WhenAll(order.Select(i => Task.Run(() =>
fx.Service.Ingest.CommitAsync(Request(fx, staged[i], name: $"IMG_{i:0000}.JPG"), fx.Ct))));
Assert.Count(1, results.Select(r => r.SequenceId).Distinct());
Assert.False(results.Any(r => r.Duplicate));
var sequenceId = results[0].SequenceId;
var row = (await fx.Db.Sequences.GetAsync(sequenceId))!;
var manifest = ManifestStore.ReadSequence(fx.Paths.Sequence(row.Folder).ManifestPath);
Assert.SequenceEqual(Enumerable.Range(0, count), manifest.Frames.Select(f => f.I));
Assert.SequenceEqual(Enumerable.Range(0, count).Select(i => Start.AddSeconds(10 * i)), manifest.Frames.Select(f => f.CapturedAt!.Value));
Assert.Count(count, manifest.Frames.Select(f => f.File).Distinct());
Assert.True(manifest.Frames.All(f => File.Exists(fx.Paths.Sequence(row.Folder).File(f.File))));
var frames = await fx.Db.Frames.ListBySequenceAsync(sequenceId);
Assert.SequenceEqual(manifest.Frames.Select(f => (f.Id, f.I)), frames.Select(f => (f.Id, f.Index)));
Assert.Equal(count, row.FrameCount);
Assert.Empty(Directory.EnumerateFiles(Path.Combine(fx.Paths.StagingDirectory, "uploads")));
}
[Test]
public async Task ExplicitTargetsUseTheGivenSequenceOrTitle()
{
await using var fx = await CreateAsync(context);
var titled = await fx.Service.Ingest.CommitAsync(Request(fx, fx.Stage(Start, 1), title: "Harbour"), fx.Ct);
var sameTitle = await fx.Service.Ingest.CommitAsync(Request(fx, fx.Stage(Start.AddSeconds(5), 2), title: "harbour "), fx.Ct);
var byId = await fx.Service.Ingest.CommitAsync(Request(fx, fx.Stage(Start.AddSeconds(9), 3), sequenceId: titled.SequenceId), fx.Ct);
Assert.Equal(titled.SequenceId, sameTitle.SequenceId);
Assert.Equal(titled.SequenceId, byId.SequenceId);
Assert.Equal("Harbour", (await fx.Db.Sequences.GetAsync(titled.SequenceId))!.Title);
await Assert.ThrowsAsync<ArgumentException>(() => fx.Service.Ingest.CommitAsync(
new IngestRequest(fx.Archive.Id, titled.SequenceId, "Both", null, fx.Stage(Start, 4).Path, "x.jpg", 1, "00", null, null), fx.Ct));
}
[Test]
public async Task AFrameCapturedEarlierIsInsertedInOrderAndTheIndexFollows()
{
await using var fx = await CreateAsync(context);
var late = await fx.Service.Ingest.CommitAsync(Request(fx, fx.Stage(Start.AddMinutes(1), 1)), fx.Ct);
var early = await fx.Service.Ingest.CommitAsync(Request(fx, fx.Stage(Start, 2)), fx.Ct);
Assert.Equal(0, early.Index);
var frames = await fx.Db.Frames.ListBySequenceAsync(late.SequenceId);
Assert.SequenceEqual([early.FrameId, late.FrameId], frames.Select(f => f.Id));
Assert.SequenceEqual([0, 1], frames.Select(f => f.Index));
}
[Test]
public async Task ABatchInterruptedBetweenMoveAndSidecarIsCompletedOnTheNextCommit()
{
await using var fx = await CreateAsync(context);
var first = await fx.Service.Ingest.CommitAsync(Request(fx, fx.Stage(Start, 1)), fx.Ct);
var row = (await fx.Db.Sequences.GetAsync(first.SequenceId))!;
var sequence = fx.Paths.Sequence(row.Folder);
// Simulated crash: the journal was written and the file moved, but sequence.json was not rewritten.
var bytes = Photos.Jpeg(Start.AddSeconds(10), 2);
File.WriteAllBytes(sequence.File("originals/moved.JPG"), bytes);
var orphan = new SidecarFrame { Id = Guid.CreateVersion7(), File = "originals/moved.JPG", Size = bytes.Length, CapturedAt = Start.AddSeconds(10) };
IngestJournal.Write(sequence, new IngestJournal([orphan]));
var next = await fx.Service.Ingest.CommitAsync(Request(fx, fx.Stage(Start.AddSeconds(20), 3)), fx.Ct);
Assert.Equal(2, next.Index);
var manifest = ManifestStore.ReadSequence(sequence.ManifestPath);
Assert.SequenceEqual([first.FrameId, orphan.Id, next.FrameId], manifest.Frames.Select(f => f.Id));
Assert.FileMissing(sequence.IngestJournalPath);
Assert.Equal(3, (await fx.Db.Frames.ListBySequenceAsync(first.SequenceId)).Count);
}
}
@@ -0,0 +1,160 @@
using Titano.Core.Archiving;
using Titano.Core.Model;
using Titano.Data.Archiving;
using Titano.Testing;
using static Titano.Data.Tests.Archiving.ArchiveFixture;
namespace Titano.Data.Tests.Archiving;
[Category("archive")]
public sealed class ArchiveIntegrityTests(TestContext context)
{
private static Task<VerifyReport> VerifyAsync(ArchiveFixture fx, IReadOnlyList<Guid>? ids = null) =>
fx.Service.Verifier.VerifyAsync(fx.Archive, ids, default, (_, _, _) => ValueTask.CompletedTask, null, fx.Ct);
private static async Task<Guid> IngestSeriesAsync(ArchiveFixture fx, string key, int count, int seed)
{
Guid sequence = default;
for (var i = 0; i < count; i++)
{
var staged = fx.Stage(Start.AddSeconds(10 * i), seed + i);
sequence = (await fx.Service.Ingest.CommitAsync(new IngestRequest(fx.Archive.Id, null, null, key, staged.Path, $"IMG_{i:0000}.JPG",
staged.Size, staged.Sha256, null, null), fx.Ct)).SequenceId;
}
return sequence;
}
[Test]
public async Task VerifyFlagsAFlippedByteAndAMissingFileInSidecarAndIndex()
{
await using var fx = await CreateAsync(context);
var id = await IngestSeriesAsync(fx, "a", 5, 1);
var clean = await VerifyAsync(fx);
Assert.Equal(5L, clean.Ok);
Assert.Empty(clean.Problems);
Assert.True((await fx.Db.Sequences.GetAsync(id))!.Status.HasFlag(SequenceStatus.Verified));
var folder = fx.Paths.Sequence((await fx.Db.Sequences.GetAsync(id))!.Folder);
var manifest = ManifestStore.ReadSequence(folder.ManifestPath);
var damaged = folder.File(manifest.Frames[1].File);
var bytes = File.ReadAllBytes(damaged);
bytes[bytes.Length / 3] ^= 0x10;
File.WriteAllBytes(damaged, bytes);
File.Delete(folder.File(manifest.Frames[3].File));
var report = await VerifyAsync(fx);
Assert.SequenceEqual([(manifest.Frames[1].Id, FrameHealth.Corrupt), (manifest.Frames[3].Id, FrameHealth.Missing)],
report.Problems.Select(p => (p.FrameId, p.Health)));
var frames = await fx.Db.Frames.ListBySequenceAsync(id);
Assert.Equal(FrameFlags.Corrupt, frames[1].Flags);
Assert.Equal(FrameFlags.Missing, frames[3].Flags);
var after = ManifestStore.ReadSequence(folder.ManifestPath);
Assert.Equal(FrameFlags.Corrupt, after.Frames[1].Flags);
Assert.False(after.Status.HasFlag(SequenceStatus.Verified));
var row = (await fx.Db.Sequences.GetAsync(id))!;
Assert.True(row.Status.HasFlag(SequenceStatus.HasErrors));
Assert.NotNull(row.VerifiedAt);
var health = (await fx.Db.Sequences.GetStatsAsync(fx.Archive.Id)).Health;
Assert.Equal((1L, 1L), (health.MissingFrames, health.CorruptFrames));
}
[Test]
public async Task VerifyGivesAdoptedPhotosTheirFirstHash()
{
await using var fx = await CreateAsync(context);
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "Adopted"), Start, 3);
await fx.ScanAsync();
var report = await VerifyAsync(fx);
Assert.Equal(3L, report.Hashed);
var manifest = ManifestStore.ReadSequence(fx.Paths.Sequence("Adopted").ManifestPath);
Assert.True(manifest.Frames.All(f => f.Sha256 is { Length: 64 }));
var frames = await fx.Db.Frames.ListBySequenceAsync(manifest.Id);
Assert.SequenceEqual(manifest.Frames.Select(f => f.Sha256), frames.Select(f => f.Sha256));
Assert.Equal(3L, (await VerifyAsync(fx)).Ok);
}
[Test]
public async Task DuplicatesAcrossSequencesAreFoundAndFlaggedAfterADryRun()
{
await using var fx = await CreateAsync(context);
var a = await IngestSeriesAsync(fx, "a", 3, 1);
var b = await IngestSeriesAsync(fx, "b", 2, 1); // the same two photos again, in another sequence
var groups = await fx.Service.FindDuplicatesAsync(fx.Archive.Id, fx.Ct);
Assert.Equal(2, groups.Count);
Assert.True(groups.All(g => g.Frames.Count == 2 && g.Frames[0].SequenceId == a && g.Frames[1].SequenceId == b));
var dry = await fx.Service.Maintenance.RunAsync(fx.Archive, dryRun: true, 0, _ => ValueTask.CompletedTask, fx.Ct);
Assert.Equal(2, dry.DuplicateFlagChanges);
Assert.Equal(0L, (await fx.Db.Sequences.GetStatsAsync(fx.Archive.Id)).Health.DuplicateFrames);
var run = await fx.Service.Maintenance.RunAsync(fx.Archive, dryRun: false, 0, _ => ValueTask.CompletedTask, fx.Ct);
Assert.Equal(2, run.DuplicateFlagChanges);
Assert.Equal(2L, (await fx.Db.Sequences.GetStatsAsync(fx.Archive.Id)).Health.DuplicateFrames);
var folder = (await fx.Db.Sequences.GetAsync(b))!.Folder;
Assert.True(ManifestStore.ReadSequence(fx.Paths.Sequence(folder).ManifestPath).Frames.All(f => f.Flags.HasFlag(FrameFlags.Duplicate)));
Assert.Equal(0, (await fx.Service.Maintenance.RunAsync(fx.Archive, false, 0, _ => ValueTask.CompletedTask, fx.Ct)).DuplicateFlagChanges);
}
[Test]
public async Task OrphansListUnindexedAndMissingFilesAndTheFixIndexesThem()
{
await using var fx = await CreateAsync(context);
var id = await IngestSeriesAsync(fx, "a", 3, 1);
var folder = fx.Paths.Sequence((await fx.Db.Sequences.GetAsync(id))!.Folder);
var manifest = ManifestStore.ReadSequence(folder.ManifestPath);
File.Delete(folder.File(manifest.Frames[0].File));
File.WriteAllBytes(Path.Combine(folder.Originals, "dropped.JPG"), Photos.Jpeg(Start.AddMinutes(5), 50));
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "New folder"), Start, 1, firstSeed: 60);
var report = await fx.Service.FindOrphansAsync(fx.Archive.Id, fx.Ct);
var orphans = report.Sequences.Single();
Assert.SequenceEqual(["originals/dropped.JPG"], orphans.UnindexedFiles);
Assert.Equal(manifest.Frames[0].Id, orphans.MissingFiles.Single().Id);
Assert.SequenceEqual(["New folder"], report.UnindexedFolders);
await fx.Service.ReconcileAsync(id, fx.Ct);
var frames = await fx.Db.Frames.ListBySequenceAsync(id);
Assert.Equal(4, frames.Count);
Assert.Equal(FrameFlags.Missing, frames[0].Flags);
Assert.Equal("dropped.JPG", frames[^1].FileName);
Assert.Empty((await fx.Service.FindOrphansAsync(fx.Archive.Id, fx.Ct)).Sequences.Where(s => s.UnindexedFiles.Count > 0));
}
[Test]
public async Task MaintenanceRemovesOnlyStaleLeftovers()
{
await using var fx = await CreateAsync(context);
var id = await IngestSeriesAsync(fx, "a", 2, 1);
var folder = fx.Paths.Sequence((await fx.Db.Sequences.GetAsync(id))!.Folder);
var oldTemp = Path.Combine(folder.MetaDirectory, ".sequence.json.1234abcd.tmp");
var freshTemp = Path.Combine(folder.MetaDirectory, ".sequence.json.5678abcd.tmp");
var oldStaged = Path.Combine(fx.Paths.StagingDirectory, "old.part");
File.WriteAllText(oldTemp, "x");
File.WriteAllText(freshTemp, "x");
File.WriteAllText(oldStaged, "x");
File.SetLastWriteTimeUtc(oldTemp, DateTime.UtcNow.AddHours(-2));
File.SetLastWriteTimeUtc(oldStaged, DateTime.UtcNow.AddDays(-2));
var past = DateTimeOffset.UtcNow.AddHours(-1);
File.WriteAllText(Path.Combine(fx.Paths.LocksDirectory, "seq-dead.lease"),
$$"""{"token":"t","owner":"crashed","host":"h","processId":1,"acquired":"{{past:O}}","expires":"{{past.AddMinutes(2):O}}"}""");
var dry = await fx.Service.Maintenance.RunAsync(fx.Archive, dryRun: true, 0, _ => ValueTask.CompletedTask, fx.Ct);
Assert.Equal(2, dry.TemporaryFiles.Count);
Assert.SequenceEqual(["seq-dead"], dry.StaleLeases);
Assert.FileExists(oldTemp);
await fx.Service.Maintenance.RunAsync(fx.Archive, dryRun: false, 0, _ => ValueTask.CompletedTask, fx.Ct);
Assert.FileMissing(oldTemp);
Assert.FileMissing(oldStaged);
Assert.FileExists(freshTemp);
Assert.FileMissing(Path.Combine(fx.Paths.LocksDirectory, "seq-dead.lease"));
Assert.True(folder.Frames().All(File.Exists));
}
}
internal static class SequencePathsExtensions
{
/// <summary>Absolute paths of every frame listed in the sidecar.</summary>
public static IEnumerable<string> Frames(this SequencePaths sequence) =>
ManifestStore.ReadSequence(sequence.ManifestPath).Frames.Select(f => sequence.File(f.File));
}
@@ -0,0 +1,130 @@
using Titano.Core.Archiving;
using Titano.Core.Import;
using Titano.Core.Model;
using Titano.Data.Archiving;
using Titano.Data.Archiving.Jobs;
using Titano.Data.Repositories;
using Titano.Testing;
using static Titano.Data.Tests.Archiving.ArchiveFixture;
namespace Titano.Data.Tests.Archiving;
/// <summary>Every archive job handler run through the engine, resuming from a checkpoint a crashed attempt left.</summary>
[Category("archive")]
public sealed class ArchiveJobTests(TestContext context)
{
private static void Populate(ArchiveFixture fx)
{
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "a"), Start, 6);
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "b"), Start.AddDays(1), 6, firstSeed: 50);
}
private static async Task<IReadOnlyList<SequenceLocation>> LocationsAsync(ArchiveFixture fx) =>
await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id);
[Test]
public async Task ScanAndRebuildJobsRunAndAScanResumesAfterItsCheckpoint()
{
await using var fx = await CreateAsync(context);
Populate(fx);
var engine = await fx.StartEngineAsync();
var resumed = await fx.EnqueueWithCheckpointAsync(engine, ArchiveJobs.Scan(fx.Archive), "after:a");
await fx.WaitForAsync(resumed.Id, JobState.Done);
Assert.SequenceEqual(["b"], (await LocationsAsync(fx)).Select(l => l.Folder));
var full = await engine.EnqueueAsync(ArchiveJobs.Scan(fx.Archive, full: true), cancellationToken: fx.Ct);
var done = await fx.WaitForAsync(full.Id, JobState.Done);
Assert.Contains("2 folders", done.LogTail);
Assert.SequenceEqual(["a", "b"], (await LocationsAsync(fx)).Select(l => l.Folder));
var rebuild = await engine.EnqueueAsync(ArchiveJobs.Rebuild(fx.Archive), cancellationToken: fx.Ct);
await fx.WaitForAsync(rebuild.Id, JobState.Done);
Assert.Equal(2, (await LocationsAsync(fx)).Count);
}
[Test]
public async Task AVerifyJobResumesAtTheNextSequence()
{
await using var fx = await CreateAsync(context);
Populate(fx);
await fx.ScanAsync();
var engine = await fx.StartEngineAsync();
var job = await fx.EnqueueWithCheckpointAsync(engine, ArchiveJobs.Verify(fx.Archive), "1:2");
var done = await fx.WaitForAsync(job.Id, JobState.Done);
var (a, b) = ((await LocationsAsync(fx))[0], (await LocationsAsync(fx))[1]);
Assert.Null((await fx.Db.Sequences.GetAsync(a.Id))!.VerifiedAt);
Assert.NotNull((await fx.Db.Sequences.GetAsync(b.Id))!.VerifiedAt);
var hashes = (await fx.Db.Frames.ListBySequenceAsync(b.Id)).Select(f => f.Sha256).ToList();
Assert.True(hashes.Take(2).All(h => h is null) && hashes.Skip(2).All(h => h is not null));
Assert.Contains("4 photos checked", done.LogTail);
}
[Test]
public async Task ThumbnailAndProxyJobsResumeInsideASequence()
{
await using var fx = await CreateAsync(context);
Populate(fx);
await fx.ScanAsync();
var a = (await LocationsAsync(fx))[0];
var engine = await fx.StartEngineAsync();
var thumbs = await fx.EnqueueWithCheckpointAsync(engine, ArchiveJobs.Thumbnails([a.Id]), "0:3");
await fx.WaitForAsync(thumbs.Id, JobState.Done);
var proxies = await fx.EnqueueWithCheckpointAsync(engine, ArchiveJobs.Proxies([a.Id]), "0:3");
await fx.WaitForAsync(proxies.Id, JobState.Done);
var sequence = fx.Paths.Sequence(a.Folder);
using (var pack = ThumbPackReader.Open(sequence.ThumbsPackPath))
{
Assert.SequenceEqual([3, 4, 5], pack.Entries.Keys.Order());
Assert.NotNull(pack.Read(4));
}
Assert.SequenceEqual(["0004.jpg", "0005.jpg", "0006.jpg"], Directory.GetFiles(sequence.Proxies).Select(Path.GetFileName).Order());
var status = (await fx.Db.Sequences.GetAsync(a.Id))!.Status;
Assert.True(status.HasFlag(SequenceStatus.ThumbsBuilt) && status.HasFlag(SequenceStatus.ProxiesBuilt));
// A full pass reuses what is current and builds the rest.
var all = await engine.EnqueueAsync(ArchiveJobs.Thumbnails([a.Id]), cancellationToken: fx.Ct);
var done = await fx.WaitForAsync(all.Id, JobState.Done);
Assert.Contains("3 made, 3 reused", done.LogTail);
}
[Test]
public async Task AMaintenanceJobResumesAfterItsDoneSteps()
{
await using var fx = await CreateAsync(context);
Populate(fx);
await fx.ScanAsync();
Directory.CreateDirectory(fx.Paths.LocksDirectory);
var past = DateTimeOffset.UtcNow.AddHours(-1);
var lease = Path.Combine(fx.Paths.LocksDirectory, "seq-dead.lease");
File.WriteAllText(lease, $$"""{"token":"t","owner":"x","host":"h","processId":1,"acquired":"{{past:O}}","expires":"{{past:O}}"}""");
var temp = Path.Combine(fx.Paths.MetaDirectory, ".archive.json.0badf00d.tmp");
File.WriteAllText(temp, "x");
File.SetLastWriteTimeUtc(temp, DateTime.UtcNow.AddHours(-3));
var engine = await fx.StartEngineAsync();
var job = await fx.EnqueueWithCheckpointAsync(engine, ArchiveJobs.Maintenance(fx.Archive), "1");
await fx.WaitForAsync(job.Id, JobState.Done);
Assert.FileExists(lease);
Assert.FileMissing(temp);
}
[Test]
public async Task AnImportJobResumesAtItsCheckpoint()
{
await using var fx = await CreateAsync(context);
var card = context.CreateTempDirectory("card");
Photos.WriteSeries(Path.Combine(card, "DCIM", "100CANON"), Start, 40);
var media = await fx.Service.Imports.RegisterCardAsync(new CardVolume("1-A-1", 1, "A", 1), fx.Ct);
var plan = await fx.Service.PlanImportAsync(fx.Archive.Id, card, new ImportOptions(), media.Id, null, fx.Ct);
var engine = await fx.StartEngineAsync();
var job = await fx.EnqueueWithCheckpointAsync(engine, ArchiveJobs.Import(fx.Archive, plan, media.Id), "32");
var done = await fx.WaitForAsync(job.Id, JobState.Done);
Assert.Equal("40", done.Checkpoint);
var id = (await fx.Db.Sequences.FindBySessionKeyAsync(fx.Archive.Id, plan.Sessions[0].SessionKey))!.Value;
var frames = await fx.Db.Frames.ListBySequenceAsync(id);
Assert.SequenceEqual(plan.Items.Skip(32).Select(i => i.FileName), frames.Select(f => f.FileName));
Assert.Equal(8, (await fx.Db.MediaCards.GetImportedKeysAsync(media.Id)).Count);
Assert.Contains("8 copied", done.LogTail);
}
}
@@ -0,0 +1,135 @@
using Titano.Core.Archiving;
using Titano.Core.Import;
using Titano.Core.Model;
using Titano.Data.Archiving;
using Titano.Data.Archiving.Jobs;
using Titano.Testing;
using static Titano.Data.Tests.Archiving.ArchiveFixture;
namespace Titano.Data.Tests.Archiving;
[Category("import")]
public sealed class ImportServiceTests(TestContext context)
{
private static readonly CardVolume Volume = new("3F2A9C11-EOS_DIGITAL-127865454592", 0x3F2A9C11, "EOS_DIGITAL", 127_865_454_592);
private string Card(int frames)
{
var card = context.CreateTempDirectory("card");
Photos.WriteSeries(Path.Combine(card, "DCIM", "100CANON"), Start, frames);
return card;
}
private static async Task<List<Frame>> FramesAsync(ArchiveFixture fx, PlannedSession session)
{
var id = await fx.Db.Sequences.FindBySessionKeyAsync(fx.Archive.Id, session.SessionKey);
Assert.NotNull(id);
return [.. await fx.Db.Frames.ListBySequenceAsync(id.Value)];
}
[Test]
public async Task AnImportJobCopiesThePlanAndRemembersTheCard()
{
await using var fx = await CreateAsync(context);
var card = Card(12);
var media = await fx.Service.Imports.RegisterCardAsync(Volume, fx.Ct);
Assert.Null(media.Nickname);
Assert.Equal(media.Id, (await fx.Service.Imports.RegisterCardAsync(Volume, fx.Ct)).Id);
await fx.Service.Imports.SaveCardAsync(media.Id, "EOS R5 card A", new CardProfile { SessionGapMinutes = 30 }, autoImport: true, fx.Ct);
var plan = await fx.Service.PlanImportAsync(fx.Archive.Id, card, new ImportOptions(), media.Id, null, fx.Ct);
var engine = await fx.StartEngineAsync();
var job = await engine.EnqueueAsync(ArchiveJobs.Import(fx.Archive, plan, media.Id), cancellationToken: fx.Ct);
var done = await fx.WaitForAsync(job.Id, JobState.Done);
Assert.Equal(plan.CopyBytes, done.ProgressDone);
var session = plan.Sessions.Single();
var frames = await FramesAsync(fx, session);
Assert.SequenceEqual(session.Items.Select(i => $"{session.Folder}/originals/{i.FileName}"), frames.Select(f => f.RelativePath));
Assert.SequenceEqual(session.Items.Select(i => Path.GetFileName(i.SourcePath)), frames.Select(f => f.OriginalFileName!));
foreach (var (item, frame) in session.Items.Zip(frames))
Assert.BytesEqual(File.ReadAllBytes(Path.Combine(card, item.SourcePath)), File.ReadAllBytes(fx.Paths.FromRelative(frame.RelativePath)));
var remembered = (await fx.Db.MediaCards.GetAsync(media.Id))!;
Assert.Equal("EOS R5 card A", remembered.Nickname);
Assert.Equal("Canon EOS R5", remembered.CameraModel);
Assert.Equal(30, ImportService.ProfileOf(remembered).SessionGapMinutes);
Assert.Equal(12, (await fx.Db.MediaCards.GetImportedKeysAsync(media.Id)).Count);
var again = await fx.Service.PlanImportAsync(fx.Archive.Id, card, new ImportOptions(), media.Id, null, fx.Ct);
Assert.True(again.Items.All(i => i.Action == ImportAction.SkipImported));
Assert.Equal(session.Folder, again.Sessions[0].Folder);
var elsewhere = await fx.Service.PlanImportAsync(fx.Archive.Id, card, new ImportOptions(), null, null, fx.Ct);
Assert.True(elsewhere.Items.All(i => i.Action == ImportAction.SkipInArchive && i.ExistingFrameId is not null));
}
[Test]
public async Task ACardPulledMidImportResumesWithoutGapsOrDoubles()
{
await using var fx = await CreateAsync(context);
var card = Card(70);
var media = await fx.Service.Imports.RegisterCardAsync(Volume, fx.Ct);
var plan = await fx.Service.PlanImportAsync(fx.Archive.Id, card, new ImportOptions(), media.Id, null, fx.Ct);
var parameters = new ImportJobParameters(fx.Archive.Id, plan, media.Id, true, null);
var jobId = Guid.CreateVersion7();
var checkpoint = 0;
await Assert.ThrowsAsync<ImportSourceUnavailableException>(() => fx.Service.Imports.ExecuteAsync(parameters, jobId, 0, batch =>
{
checkpoint = batch.NextItem;
if (Directory.Exists(card)) Directory.Move(card, card + "-out");
return ValueTask.CompletedTask;
}, null, fx.Ct));
Assert.True(checkpoint is > 0 and < 70);
Directory.Move(card + "-out", card);
var final = await fx.Service.Imports.ExecuteAsync(parameters, jobId, checkpoint, _ => ValueTask.CompletedTask, null, fx.Ct);
Assert.Equal(70 - checkpoint, final.Copied);
var frames = await FramesAsync(fx, plan.Sessions.Single());
Assert.SequenceEqual(Enumerable.Range(0, 70), frames.Select(f => f.Index));
Assert.SequenceEqual(plan.Items.Select(i => i.FileName), frames.Select(f => f.FileName));
Assert.Equal(70, (await fx.Db.MediaCards.GetImportedKeysAsync(media.Id)).Count);
Assert.Empty(Directory.EnumerateFiles(fx.Paths.StagingDirectory));
}
[Test]
public async Task RepeatingAnImportAfterACrashCommitsNothingTwice()
{
await using var fx = await CreateAsync(context);
var card = Card(20);
var plan = await fx.Service.PlanImportAsync(fx.Archive.Id, card, new ImportOptions(), null, null, fx.Ct);
var parameters = new ImportJobParameters(fx.Archive.Id, plan, null, true, null);
await fx.Service.Imports.ExecuteAsync(parameters, Guid.NewGuid(), 0, _ => ValueTask.CompletedTask, null, fx.Ct);
// The checkpoint of the last batch was lost: the run repeats from the start.
var repeat = await fx.Service.Imports.ExecuteAsync(parameters, Guid.NewGuid(), 0, _ => ValueTask.CompletedTask, null, fx.Ct);
Assert.Equal(0, repeat.Copied);
Assert.Equal(20, repeat.Skipped);
Assert.Equal(20, (await FramesAsync(fx, plan.Sessions.Single())).Count);
}
[Test]
public async Task ErasingTheCardDeletesOnlyVerifiedImports()
{
await using var fx = await CreateAsync(context);
var card = Card(6);
File.WriteAllText(Path.Combine(card, "DCIM", "100CANON", "notes.txt"), "keep me");
var media = await fx.Service.Imports.RegisterCardAsync(Volume, 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 frame = (await FramesAsync(fx, plan.Sessions.Single()))[2];
var copy = fx.Paths.FromRelative(frame.RelativePath);
var bytes = File.ReadAllBytes(copy);
bytes[^20] ^= 0x01;
File.WriteAllBytes(copy, bytes);
var erase = await fx.Service.PlanCardEraseAsync(fx.Archive.Id, media.Id, card, null, fx.Ct);
Assert.Equal(5, erase.ToDelete.Count());
Assert.Equal(EraseVerdict.CopyMismatch, erase.Items.Single(i => i.Candidate.SourcePath == plan.Items.ElementAt(2).SourcePath).Verdict);
Assert.Equal(6, Directory.EnumerateFiles(card, "*.JPG", SearchOption.AllDirectories).Count());
var result = CardEraser.Execute(erase);
Assert.Equal(5, result.Deleted);
Assert.SequenceEqual([plan.Items.ElementAt(2).SourcePath],
Directory.EnumerateFiles(card, "*.JPG", SearchOption.AllDirectories).Select(f => Path.GetRelativePath(card, f).Replace('\\', '/')));
Assert.FileExists(Path.Combine(card, "DCIM", "100CANON", "notes.txt"));
}
}
@@ -0,0 +1,113 @@
using Titano.Core.Archiving;
using Titano.Data.Archiving;
using Titano.Testing;
using static Titano.Data.Tests.Archiving.ArchiveFixture;
namespace Titano.Data.Tests.Archiving;
[Category("archive")]
public sealed class MassRenameTests(TestContext context)
{
private static async Task<List<Guid>> PopulateAsync(ArchiveFixture fx)
{
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "inbox", "a"), Start, 3);
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "inbox", "b"), Start.AddDays(1), 3, firstSeed: 10);
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "inbox", "c"), Start.AddDays(2), 3, firstSeed: 20);
await fx.ScanAsync();
return (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).OrderBy(l => l.Folder).Select(l => l.Id).ToList();
}
/// <summary>Folder, title and every frame path of each sequence as the index and the disk see them.</summary>
private static async Task<List<string>> StateAsync(ArchiveFixture fx, IEnumerable<Guid> ids)
{
var state = new List<string>();
foreach (var id in ids)
{
var s = (await fx.Db.Sequences.GetAsync(id))!;
var sidecar = ManifestStore.ReadSequence(fx.Paths.Sequence(s.Folder).ManifestPath);
Assert.Equal(id, sidecar.Id);
Assert.Equal(s.Title, sidecar.Title);
foreach (var f in await fx.Db.Frames.ListBySequenceAsync(id)) Assert.FileExists(fx.Paths.FromRelative(f.RelativePath));
state.Add($"{s.Folder}|{s.Title}|{string.Join(',', (await fx.Db.Frames.ListBySequenceAsync(id)).Select(f => f.RelativePath))}");
}
return state;
}
private static List<string> Expected(RenamePlan plan, IEnumerable<string> before) =>
before.Select(line =>
{
var folder = line.Split('|')[0];
var step = plan.Steps.SingleOrDefault(s => s.FromFolder == folder);
return step is null ? line : $"{step.ToFolder}|{step.ToTitle}|{line.Split('|')[2].Replace(step.FromFolder + "/", step.ToFolder + "/")}";
}).ToList();
[Test]
public async Task ApplyingAPlanDoesExactlyWhatTheDryRunSaid()
{
await using var fx = await CreateAsync(context);
var ids = await PopulateAsync(fx);
var before = await StateAsync(fx, ids);
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, ids, "{year}/{date} {title}", "Trip", fx.Ct);
Assert.SequenceEqual(["2026/2026-09-28 Trip", "2026/2026-09-29 Trip", "2026/2026-09-30 Trip"], plan.Steps.Select(s => s.ToFolder));
Assert.SequenceEqual(before, await StateAsync(fx, ids));
await fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
Assert.SequenceEqual(Expected(plan, before), await StateAsync(fx, ids));
Assert.Empty(RenameJournal.ListPending(fx.Paths));
Assert.False(Directory.Exists(Path.Combine(fx.Paths.Root, "inbox", "a")));
Assert.Equal(0, (await fx.ScanAsync()).Indexed);
}
[Test]
public async Task AnInterruptedRenameResumesFromItsJournal()
{
await using var fx = await CreateAsync(context);
var ids = await PopulateAsync(fx);
var before = await StateAsync(fx, ids);
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, ids, "renamed/{date}", null, fx.Ct);
using var cts = new CancellationTokenSource();
await Assert.ThrowsAsync<OperationCanceledException>(() => fx.Service.ApplyRenameAsync(plan, new SyncProgress(_ => cts.Cancel()), cts.Token));
var journal = RenameJournal.ListPending(fx.Paths).Single();
Assert.Count(1, journal.Completed);
// Crash in the middle of the next step: its folder moved, the index not yet updated.
var next = plan.Steps[1];
Directory.CreateDirectory(Path.GetDirectoryName(fx.Paths.FromRelative(next.ToFolder))!);
Directory.Move(fx.Paths.FromRelative(next.FromFolder), fx.Paths.FromRelative(next.ToFolder));
await fx.Service.OpenAsync(fx.Archive.RootPath, fx.Ct); // the next start finds the journal
Assert.Empty(RenameJournal.ListPending(fx.Paths));
Assert.SequenceEqual(Expected(plan, before), await StateAsync(fx, ids));
}
[Test]
public async Task AResumedRenameOnTheSameIndexMatchesThePlan()
{
await using var fx = await CreateAsync(context);
var ids = await PopulateAsync(fx);
var before = await StateAsync(fx, ids);
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, ids, "renamed/{date}", "{title} 2026", fx.Ct);
using var cts = new CancellationTokenSource();
await Assert.ThrowsAsync<OperationCanceledException>(() => fx.Service.ApplyRenameAsync(plan, new SyncProgress(_ => cts.Cancel()), cts.Token));
Assert.Equal(1, await fx.Service.Renamer.ResumePendingAsync(fx.Archive, fx.Ct));
Assert.SequenceEqual(Expected(plan, before), await StateAsync(fx, ids));
}
[Test]
public async Task AStalePlanIsRefused()
{
await using var fx = await CreateAsync(context);
var ids = await PopulateAsync(fx);
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, [ids[0]], "x/{date}", null, fx.Ct);
var other = await fx.Service.PlanRenameAsync(fx.Archive.Id, [ids[0]], "y/{date}", null, fx.Ct);
await fx.Service.ApplyRenameAsync(other, null, fx.Ct);
await Assert.ThrowsAsync<StaleRenamePlanException>(() => fx.Service.ApplyRenameAsync(plan, null, fx.Ct));
Assert.True(Directory.Exists(fx.Paths.FromRelative(other.Steps[0].ToFolder)));
}
/// <summary>Reports synchronously (Progress&lt;T&gt; would post to the thread pool).</summary>
private sealed class SyncProgress(Action<int> report) : IProgress<int>
{
public void Report(int value) => report(value);
}
}