refactor!: rename Titano to Chronos and move CI and releases to Gitea
CI / Build and test (pull_request) Failing after 2m3s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / Docker image (pull_request) Skipped
CI / Windows tests and installer (pull_request) Skipped
CI / YAML check (pull_request) Successful in 4s

The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout. The release cross-compiles the Windows programs, checks their
  icon, version and DPI manifest, packs installers and zips, publishes the
  Gitea release and pushes the server image (REGISTRY_TOKEN). Windows-only
  tests run in an opt-in job on a Windows runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow) and
  pe-check.

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-10-23 11:34:48 +02:00
1 parent c99842cc86
commit 5f27a86406
1799 files changed
+11728 -10668

No files matched your search

@@ -0,0 +1,201 @@
using Chronos.Core.Archiving;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Imaging;
using Chronos.Core.Metadata;
using Chronos.Core.Model;
using Chronos.Testing;
namespace Chronos.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 void APhotoThatCannotBeReadYetChangesNothing()
{
var archive = NewArchive();
var sequence = archive.Sequence("s");
TestPhotos.WriteSeries(sequence.Originals, Start, 3, TimeSpan.FromSeconds(10));
var manifest = SequenceAdopter.Build(Guid.CreateVersion7(), sequence, null);
var added = Path.Combine(sequence.Originals, "IMG_0009.JPG");
TestPhotos.Write(added, Start.AddSeconds(60), 9);
// Held open by another program (or without read permission): it stays unindexed, and the sidecar is as it was.
using (new FileStream(added, FileMode.Open, FileAccess.Read, FileShare.None))
{
Assert.SequenceEqual(["originals/IMG_0009.JPG"], SequenceAdopter.FindOrphans(sequence, manifest).UnindexedFiles);
Assert.Null(SequenceAdopter.Reconcile(sequence, manifest));
}
Assert.Equal(4, SequenceAdopter.Reconcile(sequence, manifest)!.Frames.Count);
}
[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,259 @@
using System.Text;
using Chronos.Core.Advice;
using Chronos.Core.Analysis;
using Chronos.Core.Analysis.Deep;
using Chronos.Core.Archiving;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Metadata;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Tests.Analysis.Deep;
using Chronos.Core.Tests.Raw;
using Chronos.Testing;
namespace Chronos.Core.Tests.Archiving;
/// <summary>Decode tiers of frames (BRIEF §8.2): sidecar fields, flags, thumbnails from previews, and what the advisor reads.</summary>
[Category("archive")]
public sealed class DecodeTierTests(TestContext context)
{
private static readonly DateTime Start = new(2026, 9, 28, 18, 0, 0);
private static SidecarFrame Sidecar(int orientation = 1, int? previewW = null, int? previewH = null) => new()
{
Id = Guid.CreateVersion7(),
File = "originals/IMG_0001.CR2",
Format = ImageFileFormat.Cr2,
W = 6000,
H = 4000,
Orientation = orientation,
PreviewW = previewW,
PreviewH = previewH,
};
[Test]
public void TheTierSetsItsFlagsAndThePreviewSize()
{
var frame = Sidecar(orientation: 6) with { Flags = FrameFlags.Duplicate };
// FileTier sizes are oriented; the sidecar keeps them like W and H, before orientation.
var preview = SequenceFrames.WithTier(frame, new FileTier(ImageFileFormat.Cr2, DecodeTier.EmbeddedPreview, "managed-preview", "body", 1080, 1620));
Assert.Equal((DecodeTier.EmbeddedPreview, FrameFlags.Duplicate | FrameFlags.PreviewOnly, (int?)1620, (int?)1080),
(preview.Tier, preview.Flags, preview.PreviewW, preview.PreviewH));
var none = SequenceFrames.WithTier(preview, new FileTier(ImageFileFormat.Cr2, DecodeTier.Unavailable, null, "nothing", 0, 0));
Assert.Equal((FrameFlags.Duplicate | FrameFlags.Undecodable, (int?)1620), (none.Flags, none.PreviewW));
var native = SequenceFrames.WithTier(none, new FileTier(ImageFileFormat.Cr2, DecodeTier.Native, "wic", null, 4000, 6000));
Assert.Equal((DecodeTier.Native, FrameFlags.Duplicate, (int?)1620), (native.Tier, native.Flags, native.PreviewW));
// A host without a native decoder for the format proves nothing about the file: tier kept, flag left as it was.
var beyond = SequenceFrames.WithTier(native, new FileTier(ImageFileFormat.Cr2, DecodeTier.Unavailable, null, "nothing here", 0, 0), damaged: false);
Assert.Equal((DecodeTier.Unavailable, FrameFlags.Duplicate), (beyond.Tier, beyond.Flags));
Assert.Equal(FrameFlags.Duplicate | FrameFlags.Undecodable,
SequenceFrames.WithTier(none, new FileTier(ImageFileFormat.Cr2, DecodeTier.Unavailable, null, "nothing here", 0, 0), damaged: false).Flags);
}
[Test]
public void AFrameReadFromItsProxyKeepsItsPreviewTierButIsNotPreviewOnly()
{
// A HEIF on the server: its decoders find only the Exif thumbnail, but renders read the proxy a client sent.
var heif = Sidecar() with { File = "originals/IMG_0001.HEIC", Format = ImageFileFormat.Heif, Flags = FrameFlags.Duplicate };
var thumbnail = new FileTier(ImageFileFormat.Heif, DecodeTier.EmbeddedPreview, "managed-preview", "no managed decoder for Heif", 160, 120);
var proxied = SequenceFrames.WithTier(heif, thumbnail, damaged: false, proxied: true);
Assert.Equal((DecodeTier.EmbeddedPreview, FrameFlags.Duplicate, (int?)160, (int?)120), (proxied.Tier, proxied.Flags, proxied.PreviewW, proxied.PreviewH));
// The flag follows the proxy, the tier and preview size stay the original's.
var gone = SequenceFrames.WithProxy(proxied, proxied: false);
Assert.Equal((DecodeTier.EmbeddedPreview, FrameFlags.Duplicate | FrameFlags.PreviewOnly, (int?)160), (gone.Tier, gone.Flags, gone.PreviewW));
Assert.Equal(FrameFlags.Duplicate, SequenceFrames.WithProxy(gone, proxied: true).Flags);
// Other tiers have no preview-only flag to follow.
var unavailable = SequenceFrames.WithTier(heif, new FileTier(ImageFileFormat.Heif, DecodeTier.Unavailable, null, "nothing", 0, 0), damaged: false);
Assert.Same(unavailable, SequenceFrames.WithProxy(unavailable, proxied: false));
}
[Test]
public void SidecarsKeepTheTierAndThePreviewSizeAndOlderOnesReadAsUnknown()
{
var path = Path.Combine(context.CreateTempDirectory(), "sequence.json");
var frame = SequenceFrames.WithTier(Sidecar(previewW: 1620, previewH: 1080),
new FileTier(ImageFileFormat.Cr2, DecodeTier.EmbeddedPreview, "managed-preview", null, 1620, 1080));
ManifestStore.WriteSequence(path, new SequenceManifest { Id = Guid.CreateVersion7(), Frames = [frame] });
var json = File.ReadAllText(path);
Assert.Contains("\"tier\":\"EmbeddedPreview\"", json);
Assert.Contains("\"previewW\":1620", json);
var read = ManifestStore.ReadSequence(path).Frames.Single();
Assert.Equal((DecodeTier.EmbeddedPreview, FrameFlags.PreviewOnly, (int?)1620, (int?)1080), (read.Tier, read.Flags, read.PreviewW, read.PreviewH));
// A frame never probed writes no tier, and a sidecar from before tiers reads as unknown.
ManifestStore.WriteSequence(path, new SequenceManifest { Id = Guid.CreateVersion7(), Frames = [Sidecar()] });
Assert.DoesNotContain("tier", File.ReadAllText(path).Split('"'));
var older = ManifestStore.ParseSequence(Encoding.UTF8.GetBytes(
"""{"id":"0192f7a0-0000-7000-8000-000000000001","frames":[{"id":"0192f7a0-0000-7000-8000-000000000002","file":"a.jpg","tier":"SomethingNew"}]}"""), "test");
Assert.Equal((DecodeTier)0, older.Frames.Single().Tier);
}
[Test]
public void IndexingKeepsTheSizeOfTheLargestPreview()
{
var metadata = new FrameMetadata
{
Format = ImageFileFormat.Cr2,
Width = 6000,
Height = 4000,
Previews = [new EmbeddedPreview(4096, 90_000, 1620, 1080, PreviewKind.Preview), new EmbeddedPreview(100, 4000, 160, 120, PreviewKind.Thumbnail)],
};
var frame = SequenceFrames.FromMetadata(Guid.CreateVersion7(), "a.cr2", "a.cr2", 10, null, metadata);
Assert.Equal((4096L, (int?)1620, (int?)1080, (DecodeTier)0), (frame.PreviewOffset!.Value, frame.PreviewW, frame.PreviewH, frame.Tier));
Assert.Null(SequenceFrames.FromMetadata(Guid.CreateVersion7(), "b.jpg", "b.jpg", 10, null, new FrameMetadata { Format = ImageFileFormat.Jpeg }).PreviewW);
}
[Test]
public void ThumbnailsUseAStoredPreviewOnlyWhenItReachesTheThumbnailSize()
{
var archive = new ArchivePaths(context.CreateTempDirectory("archive"));
var sequence = archive.Sequence("s");
Directory.CreateDirectory(sequence.Originals);
using var scene = SyntheticRaw.Smooth(640, 480);
var dng = SyntheticDng.Write(scene, new DngSpec());
var renderer = new FrameImageRenderer(DecoderFactory.CreateServer());
EncodedImage Thumbnail(string name, int previewWidth, bool sizeKnown, int? storedWidth = null)
{
// The preview is appended after the DNG, which the TIFF offsets never reach.
var preview = TestPhotos.Jpeg(Start, 3, width: previewWidth, height: previewWidth * 3 / 4);
File.WriteAllBytes(Path.Combine(sequence.Originals, name), [.. dng, .. preview]);
var stored = storedWidth ?? previewWidth;
var frame = new SidecarFrame
{
Id = Guid.CreateVersion7(),
File = "originals/" + name,
Format = ImageFileFormat.Dng,
W = 640,
H = 480,
PreviewOffset = dng.Length,
PreviewLength = preview.Length,
PreviewW = sizeKnown ? stored : null,
PreviewH = sizeKnown ? stored * 3 / 4 : null,
};
return renderer.Thumbnail(sequence, frame)!;
}
// A 200 px preview would leave the thumbnail short of 320 px (ENG-10): the RAW is developed instead.
var small = Thumbnail("small.dng", 200, sizeKnown: true);
Assert.Equal((320, 240, DecodeTier.Native), (small.Width, small.Height, small.Tier));
var unknown = Thumbnail("unknown.dng", 200, sizeKnown: false);
Assert.Equal((320, DecodeTier.Native), (unknown.Width, unknown.Tier));
// The stored size can be a GPR companion's, larger than the embedded preview: the JPEG's own header decides.
var companionSized = Thumbnail("companion.dng", 200, sizeKnown: true, storedWidth: 4000);
Assert.Equal((320, DecodeTier.Native), (companionSized.Width, companionSized.Tier));
var large = Thumbnail("large.dng", 400, sizeKnown: true);
Assert.Equal((320, 240, DecodeTier.EmbeddedPreview), (large.Width, large.Height, large.Tier));
Assert.Equal(320, JpegDecoder.ReadInfo(large.Jpeg).Width);
}
[Test]
public void TheAdvisorCapsTheOutputAtThePreviewsOfPreviewOnlyFrames()
{
var sequence = Guid.CreateVersion7();
Frame Row(int index, FrameFlags flags, int previewW, int previewH) => new()
{
Id = Guid.CreateVersion7(),
SequenceId = sequence,
Index = index,
RelativePath = $"s/{index}.cr3",
FileName = $"{index}.cr3",
CapturedAt = Start.AddSeconds(5 * index),
ExposureTime = 1.0 / 250,
FNumber = 8,
Iso = 100,
Width = 6000,
Height = 4000,
Orientation = 6,
Flags = flags,
PreviewWidth = previewW,
PreviewHeight = previewH,
};
var rows = Enumerable.Range(0, 20)
.Select(i => Row(i, i == 19 ? FrameFlags.Undecodable : i < 15 ? FrameFlags.PreviewOnly : FrameFlags.None, i == 3 ? 1280 : 1620, i == 3 ? 960 : 1080))
.ToList();
var context = SequenceContext.FromFrames(rows);
// Portrait frames: the previews are oriented like the main image; the most common preview size wins.
Assert.Equal((4000, 6000, 15, 1080, 1620), (context.SourceWidth, context.SourceHeight, context.PreviewOnlyCount, context.PreviewWidth, context.PreviewHeight));
var light = LightAnalyzer.Analyze(rows);
Assert.SequenceEqual(Enumerable.Range(0, 15), light.PreviewOnlyFrames);
Assert.SequenceEqual([19], light.UndecodableFrames);
var preview = light.Findings.Single(f => f.Key == FindingKeys.PreviewOnly);
Assert.Equal((FindingSeverity.Info, (object)15), (preview.Severity, preview.Arguments[0]));
Assert.Equal(FindingSeverity.Warning, light.Findings.Single(f => f.Key == DeepFindingKeys.UnreadableFrames).Severity);
var result = Advisor.Recommend(light, null, context);
var resolution = result.Find(AdvisorParameters.Resolution)!;
Assert.Equal(AdvisorKeys.ResolutionPreview, resolution.ReasonKey);
Assert.SequenceEqual([15, 1080, 1620], resolution.ReasonArgs.Select(Convert.ToInt32));
}
[Test]
public async Task FramesBothAnalysesFoundUndecodableAreListedOnce()
{
// Frame 4 does not decode; frame 7 is not read either (missing, or beyond this host), which never flags it.
var source = new SyntheticFrameSource(SyntheticSequence.Create(new SyntheticSequenceOptions { Width = 96, Height = 64, FrameCount = 12 }))
{
Undecodable = [4, 7],
};
var deep = await DeepAnalyzer.AnalyzeAsync(source, DeepScenes.Options);
var metadata = Enumerable.Range(0, source.Count).Select(source.Metadata).ToList();
var context = new SequenceContext { FrameCount = source.Count, SourceWidth = 96, SourceHeight = 64 };
// Before the deep pass flagged the frame, only its own finding names them.
var unflagged = Advisor.Recommend(LightAnalyzer.Analyze(metadata), deep, context).Findings.Where(f => f.Key == DeepFindingKeys.UnreadableFrames).ToList();
Assert.SequenceEqual([4, 7], unflagged.Single().Frames);
// Once frame 4 is flagged both analyses report it: one finding over both lists, counted once.
var flagged = metadata.Select(m => m.Index == 4 ? m with { Flags = FrameFlags.Undecodable } : m).ToList();
var light = LightAnalyzer.Analyze(flagged);
Assert.SequenceEqual([4], light.Findings.Single(f => f.Key == DeepFindingKeys.UnreadableFrames).Frames);
var merged = Advisor.Recommend(light, deep, context).Findings.Single(f => f.Key == DeepFindingKeys.UnreadableFrames);
Assert.SequenceEqual([4, 7], merged.Frames);
Assert.Equal((FindingSeverity.Warning, 2), (merged.Severity, Convert.ToInt32(merged.Arguments.Single())));
// A frame flagged since the deep pass (a render found it broken) joins the list too.
var later = LightAnalyzer.Analyze(flagged.Select(m => m.Index == 9 ? m with { Flags = FrameFlags.Undecodable } : m).ToList());
var all = Advisor.Recommend(later, deep, context).Findings.Single(f => f.Key == DeepFindingKeys.UnreadableFrames);
Assert.Equal((3, 3), (all.Frames.Count, Convert.ToInt32(all.Arguments.Single())));
}
[Test]
public void FramesTheCamerasIntervalometerShotTimeTheirGapsAdaptively()
{
var metadata = new FrameMetadata { Format = ImageFileFormat.Rw2, IntervalShooting = true };
Assert.Equal(FrameFlags.Intervalometer, SequenceFrames.FromMetadata(Guid.CreateVersion7(), "a.rw2", "a.rw2", 10, null, metadata).Flags);
Assert.Equal(FrameFlags.None, SequenceFrames.FromMetadata(Guid.CreateVersion7(), "b.rw2", "b.rw2", 10, null, metadata with { IntervalShooting = false }).Flags);
// 60 frames 10 s apart with one 40 s gap: a sparse gap alone keeps the timing constant (motion unmeasured).
LightFrame Frame(int i, FrameFlags flags) => new()
{
Index = i,
CapturedAt = Start.AddSeconds(10 * i + (i >= 30 ? 30 : 0)),
Width = 6000,
Height = 4000,
Flags = flags,
};
var context = new SequenceContext { FrameCount = 60, SourceWidth = 6000, SourceHeight = 4000 };
var plain = LightAnalyzer.Analyze([.. Enumerable.Range(0, 60).Select(i => Frame(i, FrameFlags.None))]);
Assert.Equal(0, plain.IntervalometerFrames);
var free = Advisor.Recommend(plain, null, context).Find(AdvisorParameters.TimingMode)!;
Assert.Equal((AdvisorKeys.TimingSparseGaps, (object?)TimingMode.Constant), (free.ReasonKey, free.Value));
// The camera's own intervalometer shot them: its pause was deliberate, so adaptive timing keeps it short.
var shot = LightAnalyzer.Analyze([.. Enumerable.Range(0, 60).Select(i => Frame(i, FrameFlags.Intervalometer))]);
Assert.Equal(60, shot.IntervalometerFrames);
var advice = Advisor.Recommend(shot, null, context).Find(AdvisorParameters.TimingMode)!;
Assert.Equal((AdvisorKeys.TimingIntervalometer, (object?)TimingMode.Adaptive), (advice.ReasonKey, advice.Value));
Assert.Equal(1, Convert.ToInt32(advice.ReasonArgs.Single()));
}
}
@@ -0,0 +1,137 @@
using System.Text.Json;
using Chronos.Core.Archiving;
using Chronos.Testing;
namespace Chronos.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 ALeaseReleasedWhileAReaderHoldsItIsTakenOnceTheReaderLetsGo()
{
// Found under load while testing owner review 1: on Windows the released file stays pending deletion while a reader
// has it open, and creating the name answers "access denied" meanwhile instead of succeeding or saying "taken".
var locks = context.CreateTempDirectory();
var held = LeaseFile.TryAcquire(locks, "seq-1", "server")!;
var path = LeaseFile.PathFor(locks, "seq-1");
using var opened = new ManualResetEventSlim();
var reader = new Thread(() =>
{
using var reading = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
opened.Set();
Thread.Sleep(30);
});
reader.Start();
Assert.True(opened.Wait(TimeSpan.FromSeconds(10)), "the reader opened the lease");
held.Dispose();
using var taken = LeaseFile.TryAcquire(locks, "seq-1", "client");
reader.Join();
Assert.NotNull(taken);
Assert.Equal("client", LeaseFile.Read(path)!.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,210 @@
using System.Text;
using System.Text.Json;
using Chronos.Core.Archiving;
using Chronos.Core.Imaging;
using Chronos.Core.IO;
using Chronos.Core.Model;
using Chronos.Testing;
namespace Chronos.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(), ".chronos", "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 ASidecarBeingReadIsReplacedOnceTheReaderIsDone()
{
// A thumbnail pass reads a sidecar without a lease while an upload commits to it (owner review 1). Windows refuses
// to rename over a file someone has open, so the write tries again for a moment instead of failing the upload.
var path = SidecarPath();
var first = Sample();
ManifestStore.WriteSequence(path, first);
// The reader runs on its own thread, so it lets go on time however busy the thread pool is.
using var opened = new ManualResetEventSlim();
string? read = null;
var reader = new Thread(() =>
{
using var reading = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete);
opened.Set();
Thread.Sleep(150);
using var old = new StreamReader(reading);
read = old.ReadToEnd();
});
reader.Start();
Assert.True(opened.Wait(TimeSpan.FromSeconds(10)), "the reader opened the sidecar");
ManifestStore.WriteSequence(path, first with { Title = "Rooftop" });
reader.Join();
Assert.Contains("Harbour sunset", read);
Assert.Equal("Rooftop", ManifestStore.ReadSequence(path).Title);
Assert.Contains("Rooftop", AtomicFile.ReadAllText(path));
}
[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);
}
[Test]
public void TheThumbnailSizeIsTheArchivesOwnAndDefaultsTo320()
{
// An archive.json written before the thumbnail policy existed reads with the BRIEF §8.5 default.
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" }
""");
var read = ManifestStore.ReadArchive(path);
Assert.Equal((320, 80), (read.ThumbnailPolicy.LongEdge, read.ThumbnailPolicy.Quality));
ManifestStore.WriteArchive(path, read with { ThumbnailPolicy = read.ThumbnailPolicy with { LongEdge = 480 } });
Assert.Contains("\"thumbnailPolicy\"", File.ReadAllText(path));
Assert.Equal(480, ManifestStore.ReadArchive(path).ThumbnailPolicy.LongEdge);
File.WriteAllText(path, $$"""
{ "schemaVersion": 1, "id": "{{Guid.CreateVersion7()}}", "name": "Main", "thumbnailPolicy": { "longEdge": 240 } }
""");
Assert.Equal((240, 80), (ManifestStore.ReadArchive(path).ThumbnailPolicy.LongEdge, ManifestStore.ReadArchive(path).ThumbnailPolicy.Quality));
Assert.True(ThumbnailPolicy.IsValidLongEdge(160) && ThumbnailPolicy.IsValidLongEdge(1024));
Assert.False(ThumbnailPolicy.IsValidLongEdge(100) || ThumbnailPolicy.IsValidLongEdge(2048));
Assert.True(ProxyPolicy.IsValidLongEdge(ProxyPolicy.Disabled) && ProxyPolicy.IsValidLongEdge(ProxyPolicy.FullSize) && ProxyPolicy.IsValidLongEdge(1920));
Assert.False(ProxyPolicy.IsValidLongEdge(100) || ProxyPolicy.IsValidLongEdge(10_000));
}
}
@@ -0,0 +1,51 @@
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Imaging;
using Chronos.Core.Metadata;
namespace Chronos.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,184 @@
using Chronos.Core.Archiving;
using Chronos.Testing;
namespace Chronos.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(), ".chronos", "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 AThumbnailIsFromItsOriginalAlsoAfterTheOriginalWasHashed()
{
var sha = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData("photo"u8));
var other = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData("another photo"u8));
var drawnUnhashed = ThumbPack.Fingerprint(null, "IMG_0001.JPG", 1000);
var drawnHashed = ThumbPack.Fingerprint(sha, "IMG_0001.JPG", 1000);
Assert.True(ThumbPack.IsFrom(drawnUnhashed, null, "IMG_0001.JPG", 1000), "unhashed");
Assert.True(ThumbPack.IsFrom(drawnHashed, sha, "IMG_0001.JPG", 1000), "hashed");
// Drawn before a verify hashed the photo: the hash changes nothing about it.
Assert.True(ThumbPack.IsFrom(drawnUnhashed, sha, "IMG_0001.JPG", 1000), "hashed since");
// Another photo: another hash, or another file or size at that frame index.
Assert.False(ThumbPack.IsFrom(drawnHashed, other, "IMG_0001.JPG", 1000), "another hash");
Assert.False(ThumbPack.IsFrom(drawnUnhashed, sha, "IMG_0002.JPG", 1000), "another file");
Assert.False(ThumbPack.IsFrom(drawnUnhashed, null, "IMG_0001.JPG", 1001), "another size");
Assert.False(ThumbPack.IsFrom(drawnHashed, null, "IMG_0001.JPG", 1000), "a hash the frame no longer has");
}
[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);
}
}