feat(copies): pure comparison, detection rules, details payload and comparison sides
Detection, Integrate and Merge need one comparison of two copies of a time-lapse, so this adds it: CopyComparer classifies every photo (same, converted, same unhashed, deleted here/there, differs, two versions, only here/there) with strict Differs and Versions rules so whole-second capture times and bursts never pair, unusable frames held as nothing and marked for repair, and the score of design 3.2. CopyRules ports 1.1's same-originals gate exactly for "Link when half shared" and holds the Decide table, ask-again thresholds, fingerprints, hints and the probe sample. CopyPayload compares details in portable form (same photo at another index is no line) and merges the chosen sides into one payload that must parse as a project. CopySides reads both sides from the index and a server and answers the last-copy check across every archive. SyncTombstones gains FromDtos for local pairs. Refs #73 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
283d04d9cd
commit
f6f81e2c37
9 files changed
+1465
No files matched your search
@@ -0,0 +1,139 @@
|
||||
using System.Globalization;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Copies;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Copies;
|
||||
|
||||
/// <summary>The details of two copies line by line and the one payload both get (owner review 6, Q4; design §4.3, §5e).</summary>
|
||||
[Category("sync")]
|
||||
public sealed class CopyPayloadTests
|
||||
{
|
||||
private static readonly DateTime Start = new(2026, 9, 28, 18, 0, 0, 250);
|
||||
|
||||
private static string Sha(int n) => Convert.ToHexStringLower(BitConverter.GetBytes((long)n)).PadLeft(64, 'b');
|
||||
|
||||
private static FramePhoto Photo(int n) => new(Sha(n), 1000 + n, Start.AddSeconds(5 * n));
|
||||
|
||||
/// <summary>Photos 0–19 at indices 0–19.</summary>
|
||||
private static readonly FramePhotos Here = new(Enumerable.Range(0, 20).Select(i => (i, Photo(i))));
|
||||
|
||||
/// <summary>Two photos more before them (100, 101): photo n at index n + 2.</summary>
|
||||
private static readonly FramePhotos There = new(new[] { (0, Photo(100)), (1, Photo(101)) }.Concat(Enumerable.Range(0, 20).Select(i => (i + 2, Photo(i)))));
|
||||
|
||||
private static SyncPayload Payload(ProjectSettings settings, string? title = "Harbour", params string[] tags) =>
|
||||
new(title, tags, 3, null, settings.ToJson());
|
||||
|
||||
private static IReadOnlyDictionary<string, CopySide> Choose(IEnumerable<DetailLine> lines, CopySide side, params (string Path, CopySide Side)[] except)
|
||||
{
|
||||
var choices = lines.ToDictionary(l => l.Path, _ => side, StringComparer.Ordinal);
|
||||
foreach (var (path, chosen) in except) choices[path] = chosen;
|
||||
return choices;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheSameExclusionAtAnotherIndexIsNoLine()
|
||||
{
|
||||
var here = Payload(new ProjectSettings { ExcludedFrames = [10], HeroFrame = 3 });
|
||||
var there = Payload(new ProjectSettings { ExcludedFrames = [12], HeroFrame = 5 });
|
||||
Assert.Empty(CopyPayload.Lines(here, Here, there, There));
|
||||
|
||||
// Another photo excluded there: one line, the frame positions.
|
||||
var other = Payload(new ProjectSettings { ExcludedFrames = [11], HeroFrame = 5 });
|
||||
var lines = CopyPayload.Lines(here, Here, other, There);
|
||||
var line = Assert.Contains(lines, l => l.Path == CopyPayload.PendingFramesPath);
|
||||
Assert.Count(1, lines);
|
||||
Assert.Contains(Sha(10), line.Here);
|
||||
Assert.Contains(Sha(9), line.There);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FramePositionsCollapseIntoOneLine()
|
||||
{
|
||||
var here = Payload(new ProjectSettings { ExcludedFrames = [1, 2], HeroFrame = 3 }, "Harbour", "dusk");
|
||||
var there = Payload(new ProjectSettings { ExcludedFrames = [9], HeroFrame = 7, Stack = new StackSettings { Length = 15 } }, "Harbour at dusk", "dusk", "sea");
|
||||
var lines = CopyPayload.Lines(here, Here, there, There);
|
||||
Assert.Count(4, lines);
|
||||
Assert.True(lines.Select(l => l.Path).ToHashSet().SetEquals(["sequence.title", "sequence.tags", CopyPayload.PendingFramesPath, "stack.length"]));
|
||||
var stack = lines.Single(l => l.Path == "stack.length");
|
||||
Assert.Equal(("9", "15"), (stack.Here, stack.There));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void MergeTakesTheChosenSideOfEachLine()
|
||||
{
|
||||
var here = Payload(new ProjectSettings { ExcludedFrames = [1], Stack = new StackSettings { Length = 9 }, Export = new ExportSettings { NameTemplate = "{title}" } },
|
||||
"Harbour", "dusk");
|
||||
var there = Payload(new ProjectSettings { ExcludedFrames = [9], Stack = new StackSettings { Length = 15 }, Export = new ExportSettings { NameTemplate = "{date}" } },
|
||||
"Harbour at dusk", "dusk", "sea");
|
||||
var lines = CopyPayload.Lines(here, Here, there, There);
|
||||
var choices = Choose(lines, CopySide.ThisPc, ("sequence.title", CopySide.Other), ("stack.length", CopySide.Other), (CopyPayload.PendingFramesPath, CopySide.Other));
|
||||
var merged = CopyPayload.Merge(CopyPayload.Portable(here, Here), CopyPayload.Portable(there, There), choices, lines);
|
||||
|
||||
Assert.Equal("Harbour at dusk", merged.Title);
|
||||
Assert.SequenceEqual(["dusk"], merged.Tags);
|
||||
var settings = ProjectSettings.FromJson(merged.SettingsJson!);
|
||||
Assert.Equal((15, "{title}"), (settings.Stack.Length, settings.Export.NameTemplate));
|
||||
// Portable: placed on this PC's frames, the exclusion is there's photo 7 (index 9 there).
|
||||
Assert.SequenceEqual([7], ProjectSettings.FromJson(ProjectContent.Place(merged.SettingsJson!, Here)).ExcludedFrames);
|
||||
Assert.SequenceEqual([9], ProjectSettings.FromJson(ProjectContent.Place(merged.SettingsJson!, There)).ExcludedFrames);
|
||||
|
||||
// Every line this PC's: the merged payload is this PC's.
|
||||
var mine = CopyPayload.Merge(CopyPayload.Portable(here, Here), CopyPayload.Portable(there, There), Choose(lines, CopySide.ThisPc), lines);
|
||||
Assert.Empty(CopyPayload.Lines(mine, new FramePhotos([]), CopyPayload.Portable(here, Here), new FramePhotos([])));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AnUnchosenLineThrows()
|
||||
{
|
||||
var here = Payload(new ProjectSettings(), "Harbour");
|
||||
var there = Payload(new ProjectSettings { Stack = new StackSettings { Length = 15 } }, "Harbour at dusk");
|
||||
var lines = CopyPayload.Lines(here, Here, there, There);
|
||||
var choices = new Dictionary<string, CopySide> { ["sequence.title"] = CopySide.Other };
|
||||
Assert.Throws<ArgumentException>(() => CopyPayload.Merge(here, there, choices, lines));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AMergeThatIsNoProjectIsRefused()
|
||||
{
|
||||
var here = Payload(new ProjectSettings());
|
||||
var there = new SyncPayload("Harbour", [], 3, null, "not a project");
|
||||
var lines = CopyPayload.Lines(here, Here, there, There);
|
||||
Assert.Equal("settings", Assert.Contains(lines, l => l.Path == "settings").Path);
|
||||
Assert.Throws<InvalidDataException>(() => CopyPayload.Merge(here, there, Choose(lines, CopySide.Other), lines));
|
||||
var kept = CopyPayload.Merge(here, there, Choose(lines, CopySide.ThisPc), lines);
|
||||
Assert.Equal(9, ProjectSettings.FromJson(kept.SettingsJson!).Stack.Length);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ExcludeVersionsExcludesByPhoto()
|
||||
{
|
||||
var portable = CopyPayload.Portable(Payload(new ProjectSettings { HeroFrame = 4 }), Here);
|
||||
var unhashed = string.Create(CultureInfo.InvariantCulture, $"u:777:{Start.AddSeconds(500).Ticks / TimeSpan.TicksPerMillisecond}");
|
||||
var excluded = CopyPayload.ExcludeVersions(portable, [Sha(99), Sha(4), unhashed]);
|
||||
var pending = ProjectSettings.FromJson(excluded.SettingsJson!).PendingFrames!;
|
||||
Assert.True(pending.Single(p => p.Sha256 == Sha(99)).Excluded);
|
||||
// The hero's photo keeps its hero flag and is excluded too.
|
||||
var hero = pending.Single(p => p.Sha256 == Sha(4));
|
||||
Assert.True(hero.Excluded && hero.Hero);
|
||||
var byTime = pending.Single(p => string.IsNullOrEmpty(p.Sha256));
|
||||
Assert.Equal((777L, Start.AddSeconds(500)), (byTime.Size, byTime.CapturedAt!.Value));
|
||||
|
||||
// Placed on frames holding the version, it is excluded there.
|
||||
var frames = new FramePhotos([(0, Photo(1)), (1, new FramePhoto(Sha(99), 5, Start)), (2, Photo(4))]);
|
||||
var placed = ProjectSettings.FromJson(ProjectContent.Place(excluded.SettingsJson!, frames));
|
||||
Assert.SequenceEqual([1, 2], placed.ExcludedFrames.Order());
|
||||
Assert.Equal(2, placed.HeroFrame);
|
||||
Assert.Same(portable, CopyPayload.ExcludeVersions(portable, []));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void MovedNamesThePathsThatChanged()
|
||||
{
|
||||
var before = CopyPayload.Portable(Payload(new ProjectSettings { ExcludedFrames = [1] }), Here);
|
||||
var after = CopyPayload.Portable(Payload(new ProjectSettings { ExcludedFrames = [2], Stack = new StackSettings { Length = 3 } }, "Pier"), Here);
|
||||
Assert.True(CopyPayload.Moved(before, after).SetEquals(["sequence.title", CopyPayload.PendingFramesPath, "stack.length"]));
|
||||
Assert.Empty(CopyPayload.Moved(before, before));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Copies;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Copies;
|
||||
|
||||
/// <summary>The detection rules (owner review 6, Q1; design §3.1, §3.2, §3.6): pairs, the Link matches setting, 1.1's gate, asking again.</summary>
|
||||
[Category("sync")]
|
||||
public sealed class CopyRulesTests
|
||||
{
|
||||
private static readonly DateTime First = new(2026, 9, 28, 18, 0, 0, 400);
|
||||
|
||||
private static CopyScore Identical(int shared = 10, int unhashed = 0) =>
|
||||
CopyScore.None with { Shared = shared, SharedUnhashed = unhashed, LocalPhotos = shared + unhashed, OtherPhotos = shared + unhashed, Containment = 1000, Overlap = 1000 };
|
||||
|
||||
private static CopyScore Partial(int shared, int onlyHere) =>
|
||||
CopyScore.None with { Shared = shared, OnlyHere = onlyHere, LocalPhotos = shared + onlyHere, OtherPhotos = shared, Containment = 1000 };
|
||||
|
||||
/// <summary>1.1's gate passing: both unlinked, same second, same camera, half of 10 shared.</summary>
|
||||
private static SameOriginalsInput Gate(int shared = 5) => new(true, First, First.AddMilliseconds(300), "EOS R5", "eos r5", 10, 10, shared);
|
||||
|
||||
private static readonly SameOriginalsInput Closed = new(false, null, null, null, null, 0, 0, 0);
|
||||
|
||||
private static FoundCopy KeptApart(int answeredShared, string? fingerprint = null) => new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Kind = CopyKind.LocalServer,
|
||||
LocalId = Guid.NewGuid(),
|
||||
Server = "https://nas.test:8443",
|
||||
RemoteId = Guid.NewGuid(),
|
||||
Evidence = CopyEvidence.Hashes,
|
||||
State = CopyState.KeptApart,
|
||||
Score = Partial(answeredShared, 5),
|
||||
Fingerprint = "f",
|
||||
AnsweredShared = answeredShared,
|
||||
AnsweredFingerprint = fingerprint,
|
||||
};
|
||||
|
||||
[Test]
|
||||
public void APairNeedsALinkASessionKeyOrEnoughShared()
|
||||
{
|
||||
Assert.True(CopyRules.IsCopy(CopyEvidence.Link, CopyScore.None));
|
||||
Assert.True(CopyRules.IsCopy(CopyEvidence.SessionKey, CopyScore.None));
|
||||
Assert.False(CopyRules.IsCopy(CopyEvidence.Hashes, CopyScore.None));
|
||||
Assert.True(CopyRules.IsCopy(CopyEvidence.Hashes, CopyScore.None with { Shared = 1, Containment = 100 }));
|
||||
Assert.False(CopyRules.IsCopy(CopyEvidence.Hashes, CopyScore.None with { Shared = 1, Containment = 99 }));
|
||||
// Tombstoned content is evidence too.
|
||||
Assert.True(CopyRules.IsCopy(CopyEvidence.Hashes, CopyScore.None with { SharedRemoved = 3, Containment = 300 }));
|
||||
Assert.True(CopyRules.IsCopy(CopyEvidence.SizeAndTime, CopyScore.None with { SharedUnhashed = 2, Containment = 1000 }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AskAlwaysNeverLinks()
|
||||
{
|
||||
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.AskAlways, CopyKind.LocalServer, Identical(), Gate()));
|
||||
Assert.Equal(CopyDecision.None, CopyRules.Decide(CopyLinking.AskAlways, CopyKind.LocalServer, CopyScore.None, Gate()));
|
||||
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.AskAlways, CopyKind.LocalServer, CopyScore.None, Closed, CopyEvidence.SessionKey));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void WhenIdenticalLinksOnlyTheSamePhotosKnownByHash()
|
||||
{
|
||||
Assert.Equal(CopyDecision.Link, CopyRules.Decide(CopyLinking.WhenIdentical, CopyKind.LocalServer, Identical(), Closed));
|
||||
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.WhenIdentical, CopyKind.LocalServer, Partial(10, 1), Gate()));
|
||||
// A size and time identity always asks.
|
||||
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.WhenIdentical, CopyKind.LocalServer, Identical(8, 2), Closed));
|
||||
// Photos deleted on one side only are no identity.
|
||||
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.WhenIdentical, CopyKind.LocalServer, Identical() with { DeletedThere = 1, SharedRemoved = 1 }, Closed));
|
||||
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.WhenIdentical, CopyKind.LocalServer, Identical() with { DeletedHere = 1, SharedRemoved = 1 }, Closed));
|
||||
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.WhenIdentical, CopyKind.LocalServer, Identical() with { Differs = 1 }, Closed));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void IdenticalNeedsNothingDeletedOnOneSide()
|
||||
{
|
||||
Assert.True(Identical().Identical);
|
||||
Assert.False((Identical() with { DeletedHere = 1 }).Identical);
|
||||
Assert.False((Identical() with { DeletedThere = 1 }).Identical);
|
||||
Assert.False(CopyScore.None.Identical);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void WhenHalfSharedKeeps11sGates()
|
||||
{
|
||||
Assert.Equal(CopyDecision.Link, CopyRules.Decide(CopyLinking.WhenHalfShared, CopyKind.LocalServer, Partial(5, 5), Gate()));
|
||||
// A different first-capture second, or another camera: asked.
|
||||
var otherSecond = Gate() with { RemoteFirst = First.AddSeconds(1) };
|
||||
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.WhenHalfShared, CopyKind.LocalServer, Partial(5, 5), otherSecond));
|
||||
var otherCamera = Gate() with { RemoteCamera = "EOS R6" };
|
||||
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.WhenHalfShared, CopyKind.LocalServer, Partial(5, 5), otherCamera));
|
||||
// Fewer than half of the smaller side, nothing hashed here, or a side linked already: asked.
|
||||
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.WhenHalfShared, CopyKind.LocalServer, Partial(4, 6), Gate(4)));
|
||||
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.WhenHalfShared, CopyKind.LocalServer, Partial(5, 5), Gate() with { LocalHashed = 0 }));
|
||||
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.WhenHalfShared, CopyKind.LocalServer, Partial(5, 5), Gate() with { BothUnlinked = false }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SameOriginalsIsThe11Rule()
|
||||
{
|
||||
Assert.True(CopyRules.SameOriginals(Gate()));
|
||||
// Half of the smaller side: 3 of a 6-frame server sequence is enough against 10 local hashes.
|
||||
Assert.True(CopyRules.SameOriginals(Gate(3) with { RemoteFrames = 6 }));
|
||||
Assert.False(CopyRules.SameOriginals(Gate(0) with { RemoteFrames = 0 }));
|
||||
Assert.False(CopyRules.SameOriginals(Gate() with { LocalFirst = null }));
|
||||
// Both without a camera model count as equal, as in 1.1.
|
||||
Assert.True(CopyRules.SameOriginals(Gate() with { LocalCamera = null, RemoteCamera = null }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ALocalPairIsNeverLinkedByItself()
|
||||
{
|
||||
foreach (var linking in Enum.GetValues<CopyLinking>())
|
||||
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(linking, CopyKind.LocalLocal, Identical(), Gate()));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AKeptApartPairAsksAgainOnlyWhenItGrewALotOrBecameIdentical()
|
||||
{
|
||||
// Ten more shared photos at least, and a quarter of the answered count.
|
||||
Assert.False(CopyRules.AsksAgain(KeptApart(20), Partial(29, 5)));
|
||||
Assert.True(CopyRules.AsksAgain(KeptApart(20), Partial(30, 5)));
|
||||
Assert.False(CopyRules.AsksAgain(KeptApart(100), Partial(124, 5)));
|
||||
Assert.True(CopyRules.AsksAgain(KeptApart(100), Partial(125, 5)));
|
||||
// Identical now, and not when answered.
|
||||
Assert.True(CopyRules.AsksAgain(KeptApart(20, CopyRules.Fingerprint(Partial(20, 5), 1, 1)), Identical(20)));
|
||||
// Kept apart while identical: an identity is no news.
|
||||
Assert.False(CopyRules.AsksAgain(KeptApart(20, CopyRules.Fingerprint(Identical(20), 1, 1)), Identical(20)));
|
||||
// Only kept-apart pairs ask again.
|
||||
Assert.False(CopyRules.AsksAgain(KeptApart(20) with { State = CopyState.Linked }, Partial(90, 5)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FingerprintsFollowTheScoreAndTheVersions()
|
||||
{
|
||||
var a = CopyRules.Fingerprint(Partial(5, 5), 3, 4);
|
||||
Assert.Equal(a, CopyRules.Fingerprint(Partial(5, 5), 3, 4));
|
||||
Assert.NotEqual(a, CopyRules.Fingerprint(Partial(5, 5), 3, 5));
|
||||
Assert.NotEqual(a, CopyRules.Fingerprint(Partial(6, 5), 3, 4));
|
||||
var plan = CopyRules.PlanFingerprint(["send a", "fetch b"]);
|
||||
Assert.Equal(64, plan.Length);
|
||||
Assert.Equal(plan, CopyRules.PlanFingerprint(["send a", "fetch b"]));
|
||||
Assert.NotEqual(plan, CopyRules.PlanFingerprint(["fetch b", "send a"]));
|
||||
Assert.Equal("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", CopyRules.PlanFingerprint([]));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AProbeIsEvenlySpacedWithTheFirstAndTheLast()
|
||||
{
|
||||
var photos = Enumerable.Range(0, 1000).Select(i => new FramePhoto(i.ToString("x64"), i, null)).ToList();
|
||||
var probe = CopyRules.Probe(photos);
|
||||
Assert.Count(64, probe);
|
||||
Assert.Same(photos[0], probe[0]);
|
||||
Assert.Same(photos[^1], probe[^1]);
|
||||
Assert.Count(64, probe.Distinct());
|
||||
var gaps = probe.Zip(probe.Skip(1), (a, b) => b.Size - a.Size).ToList();
|
||||
Assert.InRange(gaps.Min(), 15, 16);
|
||||
Assert.InRange(gaps.Max(), 15, 16);
|
||||
|
||||
Assert.Count(10, CopyRules.Probe(photos.Take(10).ToList()));
|
||||
Assert.SequenceEqual([photos[0], photos[999]], CopyRules.Probe(photos, 2));
|
||||
Assert.Empty(CopyRules.Probe([]));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HintsScoreRangeCameraIntervalAndTitle()
|
||||
{
|
||||
var start = new DateTime(2026, 9, 28, 18, 0, 0);
|
||||
var a = new CopyHintsInput(start, start.AddHours(2), "EOS R5", 5, "Harbour sunset");
|
||||
Assert.Equal(100, CopyRules.Hints(a, a with { Camera = "eos r5", Title = "harbour" }));
|
||||
// Half of the shorter range shared: 20.
|
||||
Assert.Equal(20, CopyRules.Hints(a, new CopyHintsInput(start.AddHours(1), start.AddHours(3), null, null, null)));
|
||||
Assert.Equal(25, CopyRules.Hints(a, new CopyHintsInput(null, null, "EOS R5", null, null)));
|
||||
Assert.Equal(20, CopyRules.Hints(a, new CopyHintsInput(null, null, null, 5.4, null)));
|
||||
Assert.Equal(0, CopyRules.Hints(a, new CopyHintsInput(null, null, null, 6, "Sun")));
|
||||
// A null Last reads as First: a sequence with its first capture inside the other's range overlaps fully.
|
||||
Assert.Equal(40, CopyRules.Hints(a, new CopyHintsInput(start.AddMinutes(30), null, null, null, null)));
|
||||
Assert.Equal(0, CopyRules.Hints(a, new CopyHintsInput(start.AddHours(3), null, null, null, null)));
|
||||
Assert.Equal(40, CopyRules.Hints(new CopyHintsInput(start, null, null, null, null), new CopyHintsInput(start, null, null, null, null)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Copies;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Data.Tests.Infrastructure;
|
||||
using Chronos.Data.Tests.Sync;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Copies;
|
||||
|
||||
/// <summary>The two sides of a comparison read from the index and from a server, and the last-copy check (owner review 6, #73; design §4.2).</summary>
|
||||
[Category("sync")]
|
||||
public abstract class CopySidesTests(TestContext context) : RepositoryTest(context)
|
||||
{
|
||||
private static string Sha(int n) => Convert.ToHexStringLower(BitConverter.GetBytes((long)n)).PadLeft(64, 'c');
|
||||
|
||||
private async Task<(Archive Archive, Sequence Sequence)> SequenceAsync(ChronosDatabase db, Archive? archive = null)
|
||||
{
|
||||
if (archive is null)
|
||||
{
|
||||
archive = TestData.Archive("A" + Guid.NewGuid().ToString("N")[..6]);
|
||||
await db.Archives.UpsertAsync(archive, Ct);
|
||||
}
|
||||
var sequence = TestData.Sequence(archive.Id);
|
||||
await db.Sequences.UpsertAsync(sequence, Ct);
|
||||
return (archive, sequence);
|
||||
}
|
||||
|
||||
private async Task<Frame> FrameAsync(ChronosDatabase db, Guid sequenceId, int index, string? sha, FrameFlags flags = FrameFlags.None)
|
||||
{
|
||||
var frame = TestData.Frame(sequenceId, index) with { Sha256 = sha, Flags = flags };
|
||||
await db.Frames.InsertAsync(frame, Ct);
|
||||
return frame;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ALocalSideHoldsItsFramesTombstonesAndUnusableFlags()
|
||||
{
|
||||
var db = await OpenChronosAsync();
|
||||
var (_, sequence) = await SequenceAsync(db);
|
||||
var frames = new[]
|
||||
{
|
||||
await FrameAsync(db, sequence.Id, 0, Sha(0)),
|
||||
await FrameAsync(db, sequence.Id, 1, Sha(1), FrameFlags.Missing),
|
||||
await FrameAsync(db, sequence.Id, 2, Sha(2), FrameFlags.Corrupt | FrameFlags.Excluded),
|
||||
await FrameAsync(db, sequence.Id, 3, null),
|
||||
await FrameAsync(db, sequence.Id, 4, Sha(4), FrameFlags.Excluded),
|
||||
};
|
||||
await db.FrameRemovals.SyncSequenceAsync(sequence.Id,
|
||||
[
|
||||
new FrameRemoval(sequence.Id, Sha(8), null, RemovalReason.Deleted, TestData.Now),
|
||||
new FrameRemoval(sequence.Id, Sha(9), Sha(4), RemovalReason.Replaced, TestData.Now.AddMinutes(1)),
|
||||
], Ct);
|
||||
|
||||
var side = await new CopySides(db).LocalAsync(sequence.Id, Ct);
|
||||
Assert.SequenceEqual(frames.Select(f => f.Id), side.Photos.Select(p => p.FrameId));
|
||||
Assert.SequenceEqual([false, true, true, false, false], side.Photos.Select(p => p.Unusable));
|
||||
Assert.Null(side.Photos[3].Sha256);
|
||||
Assert.Equal((frames[0].FileName, frames[0].Size, frames[0].CapturedAt), (side.Photos[0].FileName, side.Photos[0].Size, side.Photos[0].CapturedAt));
|
||||
Assert.SequenceEqual([(Sha(8), (string?)null, "deleted"), (Sha(9), Sha(4), "replaced")], side.Removed.Select(r => (r.Sha256, r.Replacement, r.Reason)));
|
||||
|
||||
// Compared with a copy holding every photo, the unusable frames are repaired and the converted one is the same photo.
|
||||
var there = new CopySideInput([.. Enumerable.Range(0, 5).Select(i => new CopyPhotoInput(Guid.NewGuid(), i, frames[i].FileName,
|
||||
i == 4 ? Sha(9) : Sha(i), frames[i].Size, frames[i].CapturedAt, false))], []);
|
||||
var result = CopyComparer.Compare(side, there);
|
||||
Assert.Equal((2, 1, 2), (result.Score.Shared, result.Score.SharedUnhashed, result.Score.OnlyThere));
|
||||
Assert.True(result.Of(PhotoClass.OnlyThere).All(p => p.RepairsHere));
|
||||
Assert.Equal(Sha(9), Assert.Contains(result.Photos, p => p.Class == PhotoClass.Converted).There!.Sha256);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ARemoteSideTakesCaptureTimesFromTheFrameRows()
|
||||
{
|
||||
var db = await OpenChronosAsync();
|
||||
using var remote = new FakeSyncRemote();
|
||||
var at = new DateTime(2026, 9, 28, 18, 0, 0, 120);
|
||||
var sequence = remote.Add("Harbour", []);
|
||||
sequence.AddFrame([1, 2, 3], "IMG_0001.JPG", at);
|
||||
sequence.AddFrame([4, 5, 6], "IMG_0002.JPG", at.AddSeconds(5));
|
||||
sequence.Removed.Add(new RemovedPhotoDto(Sha(7), null, "deleted", TestData.Now));
|
||||
|
||||
var side = await new CopySides(db).RemoteAsync(remote, sequence.Id, Ct);
|
||||
Assert.SequenceEqual(sequence.Frames.Select(f => (f.Id, f.FileName, f.Sha256, (long)f.Bytes.Length, f.CapturedAt)),
|
||||
side.Photos.Select(p => (p.FrameId, p.FileName, p.Sha256!, p.Size, p.CapturedAt)));
|
||||
Assert.True(side.Photos.All(p => !p.Unusable));
|
||||
Assert.SequenceEqual([Sha(7)], side.Removed.Select(r => r.Sha256));
|
||||
|
||||
// A server that never hashed its originals lists none: they compare by size and time.
|
||||
sequence.Unhashed = true;
|
||||
Assert.True((await new CopySides(db).RemoteAsync(remote, sequence.Id, Ct)).Photos.All(p => p.Sha256 is null));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task HeldElsewhereLooksAcrossEveryArchiveOfTheIndex()
|
||||
{
|
||||
var db = await OpenChronosAsync();
|
||||
var (_, mine) = await SequenceAsync(db);
|
||||
var (other, inOther) = await SequenceAsync(db);
|
||||
var (_, alsoInOther) = await SequenceAsync(db, other);
|
||||
await FrameAsync(db, mine.Id, 0, Sha(1));
|
||||
await FrameAsync(db, mine.Id, 1, Sha(2));
|
||||
await FrameAsync(db, mine.Id, 2, Sha(3));
|
||||
await FrameAsync(db, inOther.Id, 0, Sha(1));
|
||||
await FrameAsync(db, alsoInOther.Id, 0, Sha(2), FrameFlags.Missing);
|
||||
await FrameAsync(db, alsoInOther.Id, 1, Sha(4));
|
||||
|
||||
var sides = new CopySides(db);
|
||||
var held = await sides.HeldElsewhereAsync([Sha(1).ToUpperInvariant(), Sha(2), Sha(3), Sha(4), string.Empty], [mine.Id], Ct);
|
||||
// Photo 2's other frame is missing: it holds nothing. Photo 3 is only in the compared sequence.
|
||||
Assert.True(held.SetEquals([Sha(1), Sha(4)]));
|
||||
Assert.True((await sides.HeldElsewhereAsync([Sha(1), Sha(4)], [mine.Id, inOther.Id, alsoInOther.Id], Ct)).Count == 0);
|
||||
Assert.True((await sides.HeldElsewhereAsync([Sha(1)], [], Ct)).SetEquals([Sha(1)]));
|
||||
Assert.Empty(await sides.HeldElsewhereAsync([], [mine.Id], Ct));
|
||||
|
||||
// Batched: more hashes than one statement takes.
|
||||
var many = Enumerable.Range(100, 1200).Select(Sha).Append(Sha(4)).ToList();
|
||||
Assert.True((await sides.HeldElsewhereAsync(many, [mine.Id], Ct)).SetEquals([Sha(4)]));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SqliteCopySidesTests(TestContext context) : CopySidesTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.SqliteMemory;
|
||||
}
|
||||
|
||||
[RequiresEnvironment(PgTestServer.Variable)]
|
||||
public sealed class PostgresCopySidesTests(TestContext context) : CopySidesTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.Postgres;
|
||||
}
|
||||
Reference in new issue
Block a user