feat(copies): matches between this PC and the server, Integrate and merge (owner review 6, v1.2.0) (#74)
CI / Build and test (push) Successful in 13m44s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 16s
Release / Build, test and publish (push) Successful in 26m34s
CI / PostgreSQL 16 integration (push) Failing after 17m36s
CI / PostgreSQL 17 integration (push) Failing after 15m36s
CI / Docker image (push) Successful in 1m12s
Release / Server image (push) Failing after 15s
CI / Build and test (push) Successful in 13m44s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 16s
Release / Build, test and publish (push) Successful in 26m34s
CI / PostgreSQL 16 integration (push) Failing after 17m36s
CI / PostgreSQL 17 integration (push) Failing after 15m36s
CI / Docker image (push) Successful in 1m12s
Release / Server image (push) Failing after 15s
The same time-lapse on a server and on this PC under different ids, or twice on this PC, is recognised, compared and settled as the owner asked in owner review 6. Matches are found after each sync refresh, through the server's new photo lookup, and after the jobs that change photos. The default is to ask every time. Server › Matches offers: - Keep apart, which is remembered; - Link only and Unlink; - the Compare dialog: photos, details line by line, projects and the plan. Integrate completes both sides. Photos default to Union, projects are copied across, and a losing version goes to the trash only after a hash check. Afterwards new photos move by themselves, and deletions wait for the user. A merge of two local sequences verifies every photo before the other sequence goes to its archive's trash. Upload all local skips suspected matches and flags them. Migration 0012 adds the found_copies and copy_probes tables. Jobs 25 (Integrate) and 26 (MergeSequences) are new, and so are the server capabilities photo-lookup and upload-into. Refs #73 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #74.
This commit is contained in:
1 parent
43719bb5c5
commit
f33bcac32e
586 files changed
+41546
-280
No files matched your search
@@ -0,0 +1,592 @@
|
||||
using System.Security.Cryptography;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Copies;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Data.Tests.Archiving;
|
||||
using Chronos.Data.Tests.Sync;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Copies;
|
||||
|
||||
/// <summary>
|
||||
/// The matches engine of a PC (owner review 6, #73; design §5, §6): what Find matches finds and tells, the facts listed,
|
||||
/// Link, Unlink, Keep apart and Ask again, and the trash steps of photos one side deleted, re-checked when applied.
|
||||
/// </summary>
|
||||
[Category("sync")]
|
||||
public sealed class CopyEngineTests(TestContext context)
|
||||
{
|
||||
private static readonly CopyPlanContext Context =
|
||||
new("STUDIO-PC", "NAS", true, true, true, true, true, false, null, new HashSet<Guid>(), new HashSet<Guid>());
|
||||
|
||||
private static async Task<SyncFixture> FixtureAsync(TestContext context)
|
||||
{
|
||||
var f = await SyncFixture.CreateAsync(context);
|
||||
f.Remote.Capabilities.Add(ServerCapabilities.UploadInto);
|
||||
f.Remote.Capabilities.Add(ServerCapabilities.PhotoLookup);
|
||||
return f;
|
||||
}
|
||||
|
||||
private static CopyEngine Engine(SyncFixture f)
|
||||
{
|
||||
var sides = new CopySides(f.Db);
|
||||
return new CopyEngine(f.Sync, f.Archive.Service, new IntegratePlanner(f.Sync, sides, f.Archive.Service.Projects),
|
||||
new SequenceMerger(f.Db, f.Archive.Service, sides), new CopyReviewBuilder(f.Db, f.Archive.Service.Projects, sides), _ => Context,
|
||||
serverNames: key => key == f.Server ? "NAS" : null);
|
||||
}
|
||||
|
||||
private static string Sha(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes));
|
||||
|
||||
private static Task<FoundCopy> PairAsync(SyncFixture f, Guid localId, Guid remoteId) =>
|
||||
f.Sync.Copies.UpsertFoundAsync(new FoundCopy
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Kind = CopyKind.LocalServer,
|
||||
LocalId = localId,
|
||||
Server = f.Server,
|
||||
RemoteId = remoteId,
|
||||
Evidence = CopyEvidence.Hashes,
|
||||
Fingerprint = "f",
|
||||
}, f.Ct);
|
||||
|
||||
/// <summary>A paused Integrate job of <paramref name="localId"/>: a pair naming it reads Integrating.</summary>
|
||||
private static async Task<Guid> PausedIntegrateAsync(SyncFixture f, Guid localId)
|
||||
{
|
||||
var id = Guid.CreateVersion7();
|
||||
await f.Db.Jobs.EnqueueAsync(new Job
|
||||
{
|
||||
Id = id,
|
||||
Kind = JobKind.Integrate,
|
||||
TargetIds = [localId],
|
||||
State = JobState.Paused,
|
||||
Created = DateTimeOffset.UtcNow,
|
||||
}, f.Ct);
|
||||
return id;
|
||||
}
|
||||
|
||||
private static async Task<CopyState> StateAsync(SyncFixture f, Guid copyId) => (await f.Sync.Copies.GetAsync(copyId, f.Ct))!.State;
|
||||
|
||||
[Test]
|
||||
public async Task FindMatchesTellsAndListsTheServerPairWithTheFactsOfBothSides()
|
||||
{
|
||||
await using var f = await FixtureAsync(context);
|
||||
var photos = f.NewPhotos(4);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var remote = f.Remote.Add("Comet (selection)", photos.Take(2));
|
||||
using var engine = Engine(f);
|
||||
var told = new List<CopyFindResult>();
|
||||
engine.Found += told.Add;
|
||||
|
||||
var result = await engine.FindAsync(f.Remote, f.Ct);
|
||||
|
||||
var pair = result.New.Single();
|
||||
Assert.Equal((local.Id, remote.Id), (pair.LocalId, pair.RemoteId!.Value));
|
||||
Assert.True(told.Any(t => t.New.Any(n => n.Id == pair.Id)));
|
||||
var view = (await engine.ListAsync(f.Ct)).Single();
|
||||
Assert.Equal(("Comet", 4, 4), (view.Here.Title, view.Here.Photos, view.Here.Hashed));
|
||||
Assert.Equal(("Comet (selection)", "NAS", 2), (view.There.Title, view.There.Where, view.There.Photos));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task FindMatchesWithoutAServerLooksAmongThisPcsArchives()
|
||||
{
|
||||
await using var f = await FixtureAsync(context);
|
||||
var photos = f.NewPhotos(3);
|
||||
var first = await f.LocalAsync("Comet", photos);
|
||||
var second = await f.LocalAsync("Comet copy", photos);
|
||||
using var engine = Engine(f);
|
||||
|
||||
var result = await engine.FindAsync(null, f.Ct);
|
||||
|
||||
var pair = result.New.Single();
|
||||
Assert.Equal(CopyKind.LocalLocal, pair.Kind);
|
||||
Assert.SequenceEqual(new[] { first.Id, second.Id }.Order(), new[] { pair.LocalId, pair.OtherId!.Value }.Order());
|
||||
// Asked again later, the pair already known is not new.
|
||||
Assert.True((await engine.FindLocalAsync(f.Ct)).New.Count == 0);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task LinkUnlinkKeepApartAndAskAgainMoveThePair()
|
||||
{
|
||||
await using var f = await FixtureAsync(context);
|
||||
var photos = f.NewPhotos(3);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var remote = f.Remote.Add("Comet NAS", photos.Take(2));
|
||||
await f.RefreshAsync(new SyncPolicy { Linking = CopyLinking.AskAlways });
|
||||
var pair = (await f.Sync.Copies.ListAsync(f.Ct)).Single();
|
||||
using var engine = Engine(f);
|
||||
|
||||
await engine.LinkAsync(pair.Id, f.Remote, f.Ct);
|
||||
Assert.Equal(CopyState.Linked, await StateAsync(f, pair.Id));
|
||||
Assert.Equal(remote.Id, (await f.Sync.LinkOfAsync(f.Server, local.Id, f.Ct))!.RemoteId);
|
||||
|
||||
await engine.UnlinkAsync(pair.Id, f.Remote, f.Ct);
|
||||
Assert.Equal(CopyState.KeptApart, await StateAsync(f, pair.Id));
|
||||
Assert.Null(await f.Sync.LinkOfAsync(f.Server, local.Id, f.Ct));
|
||||
|
||||
await engine.AskAgainAsync(pair.Id, f.Ct);
|
||||
Assert.Equal(CopyState.Candidate, await StateAsync(f, pair.Id));
|
||||
|
||||
await engine.KeepApartAsync(pair.Id, f.Ct);
|
||||
var kept = (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!;
|
||||
Assert.Equal(CopyState.KeptApart, kept.State);
|
||||
Assert.False(kept.IsListed && kept.State == CopyState.Candidate);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task UnlinkOfAPairThatNoLongerHoldsTheLinkLeavesTheOtherPairsLinkAndIntegration()
|
||||
{
|
||||
await using var f = await FixtureAsync(context);
|
||||
var photos = f.NewPhotos(2);
|
||||
var first = await f.LocalAsync("Comet", photos);
|
||||
var second = await f.LocalAsync("Comet copy", photos);
|
||||
var remote = f.Remote.Add("Comet NAS", photos);
|
||||
// (second, R) was unlinked earlier; then (first, R) was linked and its Integrate began.
|
||||
var old = await PairAsync(f, second.Id, remote.Id);
|
||||
await f.Sync.Copies.SetStateAsync(old.Id, null, CopyState.KeptApart, null, f.Ct);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, first.Id, f.Ct);
|
||||
var linked = await f.Sync.Copies.EnsureLinkedAsync(f.Server, remote.Id, first.Id, f.Ct);
|
||||
var job = await PausedIntegrateAsync(f, first.Id);
|
||||
Assert.True(await f.Sync.Copies.SetStateAsync(linked.Id, null, CopyState.Integrating, new CopyAnswer(null, null, job, null, DateTimeOffset.UtcNow), f.Ct));
|
||||
using var engine = Engine(f);
|
||||
|
||||
// The stale row still offers Unlink.
|
||||
await engine.UnlinkAsync(old.Id, f.Remote, f.Ct);
|
||||
|
||||
Assert.Equal(CopyState.KeptApart, await StateAsync(f, old.Id));
|
||||
Assert.Equal(first.Id, (await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct))!.LocalId);
|
||||
var integrating = (await f.Sync.Copies.GetAsync(linked.Id, f.Ct))!;
|
||||
Assert.Equal((CopyState.Integrating, (Guid?)job), (integrating.State, integrating.JobId));
|
||||
// The pair being integrated refuses an Unlink of its own.
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => engine.UnlinkAsync(linked.Id, f.Remote, f.Ct));
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => f.Sync.UnlinkAsync(f.Server, remote.Id, first.Id, f.Ct));
|
||||
Assert.Equal(first.Id, (await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct))!.LocalId);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task KeepApartOfALinkedPairUnlinksIt()
|
||||
{
|
||||
await using var f = await FixtureAsync(context);
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var remote = f.Remote.Add("Comet NAS", photos);
|
||||
await f.RefreshAsync(new SyncPolicy { Linking = CopyLinking.AskAlways });
|
||||
var pair = (await f.Sync.Copies.ListAsync(f.Ct)).Single();
|
||||
using var engine = Engine(f);
|
||||
await engine.LinkAsync(pair.Id, f.Remote, f.Ct);
|
||||
|
||||
await engine.KeepApartAsync(pair.Id, f.Ct);
|
||||
|
||||
Assert.Equal(CopyState.KeptApart, await StateAsync(f, pair.Id));
|
||||
Assert.Null(await f.Sync.LinkOfAsync(f.Server, local.Id, f.Ct));
|
||||
Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task KeepHereOfASequenceDeletedOnTheServerIsLeftOutOfUploadAllLocal()
|
||||
{
|
||||
await using var f = await FixtureAsync(context);
|
||||
var local = await f.LocalAsync("Comet", f.NewPhotos(2));
|
||||
var gone = Guid.CreateVersion7();
|
||||
var pair = await f.Sync.Copies.EnsureLinkedAsync(f.Server, gone, local.Id, f.Ct);
|
||||
// Deleted on the server: two 404s the re-check apart, read as deleted on server.
|
||||
var at = DateTimeOffset.UtcNow.AddHours(-2);
|
||||
await f.Sync.Copies.MarkRemoteGoneAsync(f.Server, gone, local.Id, Guid.NewGuid(), at, f.Ct);
|
||||
await f.Sync.Copies.MarkRemoteGoneAsync(f.Server, gone, local.Id, Guid.NewGuid(), at.AddHours(1), f.Ct);
|
||||
using var engine = Engine(f);
|
||||
|
||||
await engine.KeepHereAsync(pair.Id, f.Ct);
|
||||
|
||||
// Kept here: Upload all local leaves it out, and the answer stays.
|
||||
var row = (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!;
|
||||
Assert.Equal((CopyState.KeptApart, true), (row.State, row.RemoteGone));
|
||||
var entry = new SyncEntry(local, null, SyncStatus.LocalOnly);
|
||||
var (upload, skipped) = UploadAllRule.Select([entry], await f.Sync.Copies.ListAsync(f.Ct), new HashSet<Guid>(), new HashSet<Guid>());
|
||||
Assert.Empty(upload);
|
||||
Assert.Equal(local.Id, skipped.Single().Entry.Local!.Id);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task LinkIsRefusedWhenTheLocalCopyIsLinkedToAnotherServerSequence()
|
||||
{
|
||||
await using var f = await FixtureAsync(context);
|
||||
var photos = f.NewPhotos(3);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var linked = f.Remote.Add("Comet", photos);
|
||||
var other = f.Remote.Add("Comet selection", photos.Take(2));
|
||||
await f.RefreshAsync(new SyncPolicy { Linking = CopyLinking.AskAlways });
|
||||
await f.Sync.LinkAsync(f.Server, linked.Id, local.Id, f.Ct);
|
||||
var pair = await PairAsync(f, local.Id, other.Id);
|
||||
using var engine = Engine(f);
|
||||
|
||||
await Assert.ThrowsAsync<CopyLinkTakenException>(() => engine.LinkAsync(pair.Id, f.Remote, f.Ct));
|
||||
|
||||
Assert.Equal(linked.Id, (await f.Sync.LinkOfAsync(f.Server, local.Id, f.Ct))!.RemoteId);
|
||||
Assert.Equal(CopyState.Candidate, await StateAsync(f, pair.Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TrashHereMovesWhatTheServerDeletedAndRefusesAPhotoRestoredThere()
|
||||
{
|
||||
await using var f = await FixtureAsync(context);
|
||||
var photos = f.NewPhotos(3);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var remote = f.Remote.Add("Comet NAS", photos);
|
||||
var pair = await PairAsync(f, local.Id, remote.Id);
|
||||
using var engine = Engine(f);
|
||||
var (gone, restored) = (remote.Frames[1], remote.Frames[2]);
|
||||
await f.Remote.DeleteFramesAsync(remote.Id, new FrameDeleteRequest([gone.Id, restored.Id], null, false), f.Ct);
|
||||
|
||||
var trash = await engine.PlanTrashHereAsync(pair.Id, local.Id, [Sha(photos[1]), Sha(photos[2])], f.Ct);
|
||||
var (plan, lasts) = trash;
|
||||
Assert.Equal(2, plan.Frames.Count);
|
||||
// No other sequence of this PC holds them: the trash takes their last copies, and the confirmation says so.
|
||||
Assert.SequenceEqual(new[] { Sha(photos[1]), Sha(photos[2]) }.Order(StringComparer.Ordinal), lasts.Select(l => l.Key).Order(StringComparer.Ordinal));
|
||||
// Restored on the server after the dry run: nothing moves, all or nothing.
|
||||
remote.AddFrame(photos[2], restored.FileName);
|
||||
await Assert.ThrowsAsync<StaleCopyPlanException>(() => engine.TrashHereAsync(pair.Id, trash, f.Remote, f.Ct));
|
||||
Assert.Count(3, await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct));
|
||||
|
||||
var again = await engine.PlanTrashHereAsync(pair.Id, local.Id, [Sha(photos[1])], f.Ct);
|
||||
Assert.Equal(1, await engine.TrashHereAsync(pair.Id, again, f.Remote, f.Ct));
|
||||
var left = await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct);
|
||||
Assert.SequenceEqual(new[] { Sha(photos[0]), Sha(photos[2]) }.Order(StringComparer.Ordinal), left.Select(fr => fr.Sha256!).Order(StringComparer.Ordinal));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TrashThereSendsThePlansVersionAndAStalePlanMovesNothing()
|
||||
{
|
||||
await using var f = await FixtureAsync(context);
|
||||
var photos = f.NewPhotos(3);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var remote = f.Remote.Add("Comet NAS", photos);
|
||||
var pair = await PairAsync(f, local.Id, remote.Id);
|
||||
using var engine = Engine(f);
|
||||
var frames = await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct);
|
||||
var deleted = frames.Single(fr => fr.Sha256 == Sha(photos[2]));
|
||||
var sequence = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
|
||||
var local3 = await f.Archive.Service.FrameTrash.PlanDeleteAsync(local.Id, [deleted.Id], sequence.FramesVersion, f.Ct);
|
||||
await f.Archive.Service.FrameTrash.DeleteAsync(local3, "test", null, f.Ct);
|
||||
|
||||
var plan = await engine.PlanTrashThereAsync(pair.Id, f.Remote, [Sha(photos[2])], f.Ct);
|
||||
Assert.Equal((1, remote.FramesVersion), (plan.Photos, plan.FramesVersion));
|
||||
// The photo is in this PC's trash only: the server's is its last copy.
|
||||
Assert.Count(1, plan.LastCopies);
|
||||
|
||||
remote.AddFrame(f.NewPhotos(1)[0], "IMG_0009.JPG");
|
||||
await Assert.ThrowsAsync<StaleCopyPlanException>(() => engine.TrashThereAsync(plan, f.Remote, f.Ct));
|
||||
Assert.Count(0, f.Remote.Trashed);
|
||||
|
||||
var fresh = await engine.PlanTrashThereAsync(pair.Id, f.Remote, [Sha(photos[2])], f.Ct);
|
||||
Assert.Equal(1, await engine.TrashThereAsync(fresh, f.Remote, f.Ct));
|
||||
Assert.Equal(Sha(photos[2]), f.Remote.Trashed.Single().Frame.Sha256);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TrashHereNamesNoLastCopyForAPhotoAnotherSequenceHolds()
|
||||
{
|
||||
await using var f = await FixtureAsync(context);
|
||||
var photos = f.NewPhotos(3);
|
||||
var local = await f.LocalAsync("Comet", photos[..2]);
|
||||
// The backup holds photo 1 and one of its own (a sequence keeps at least one frame).
|
||||
var backup = await f.LocalAsync("Comet backup", [photos[1], photos[2]]);
|
||||
var remote = f.Remote.Add("Comet NAS", photos[..2]);
|
||||
var pair = await PairAsync(f, local.Id, remote.Id);
|
||||
using var engine = Engine(f);
|
||||
await f.Remote.DeleteFramesAsync(remote.Id, new FrameDeleteRequest([remote.Frames[1].Id], null, false), f.Ct);
|
||||
|
||||
var plan = await engine.PlanTrashHereAsync(pair.Id, local.Id, [Sha(photos[1])], f.Ct);
|
||||
|
||||
Assert.Equal((1, 0), (plan.Plan.Frames.Count, plan.LastCopies.Count));
|
||||
|
||||
// The other sequence goes to the trash while the confirmation is open: the photo is a last copy now, never moved unnamed.
|
||||
var held = (await f.Db.Frames.ListBySequenceAsync(backup.Id, cancellationToken: f.Ct)).Single(r => r.Sha256 == Sha(photos[1]));
|
||||
var other = await f.Archive.Service.FrameTrash.PlanDeleteAsync(backup.Id, [held.Id], (await f.Db.Sequences.GetAsync(backup.Id, f.Ct))!.FramesVersion, f.Ct);
|
||||
await f.Archive.Service.FrameTrash.DeleteAsync(other, "test", null, f.Ct);
|
||||
await Assert.ThrowsAsync<StaleCopyPlanException>(() => engine.TrashHereAsync(pair.Id, plan, f.Remote, f.Ct));
|
||||
Assert.Count(2, await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct));
|
||||
Assert.Count(1, (await engine.PlanTrashHereAsync(pair.Id, local.Id, [Sha(photos[1])], f.Ct)).LastCopies);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TrashHereOfTwoLocalCopiesTrashesFromTheSequenceAsked()
|
||||
{
|
||||
await using var f = await FixtureAsync(context);
|
||||
var photos = f.NewPhotos(3);
|
||||
var first = await f.LocalAsync("Comet", photos);
|
||||
var second = await f.LocalAsync("Comet copy", photos);
|
||||
using var engine = Engine(f);
|
||||
var pair = (await engine.FindAsync(null, f.Ct)).New.Single();
|
||||
// The pair's first deletes a photo the second still holds (a merge keeping the second reads it "Deleted in other").
|
||||
var (deleter, keeper) = pair.LocalId == first.Id ? (first, second) : (second, first);
|
||||
var gone = (await f.Db.Frames.ListBySequenceAsync(deleter.Id, cancellationToken: f.Ct)).Single(fr => fr.Sha256 == Sha(photos[1]));
|
||||
var deletion = await f.Archive.Service.FrameTrash.PlanDeleteAsync(deleter.Id, [gone.Id], (await f.Db.Sequences.GetAsync(deleter.Id, f.Ct))!.FramesVersion, f.Ct);
|
||||
await f.Archive.Service.FrameTrash.DeleteAsync(deletion, "test", null, f.Ct);
|
||||
|
||||
var plan = await engine.PlanTrashHereAsync(pair.Id, keeper.Id, [Sha(photos[1])], f.Ct);
|
||||
Assert.Equal(keeper.Id, plan.Plan.Sequence.Id);
|
||||
Assert.Equal(1, await engine.TrashHereAsync(pair.Id, plan, null, f.Ct));
|
||||
|
||||
Assert.DoesNotContain(Sha(photos[1]), (await f.Db.Frames.ListBySequenceAsync(keeper.Id, cancellationToken: f.Ct)).Select(fr => fr.Sha256));
|
||||
Assert.Count(2, await f.Db.Frames.ListBySequenceAsync(deleter.Id, cancellationToken: f.Ct));
|
||||
// The sequence that deleted it holds nothing to trash: its own photos are refused.
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => engine.PlanTrashHereAsync(pair.Id, deleter.Id, [Sha(photos[1])], f.Ct));
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => engine.PlanTrashHereAsync(pair.Id, Guid.NewGuid(), [Sha(photos[1])], f.Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task UnlinkKeepsApartAgainstWhatTheTwoHoldNowNotAtTheLastComparison()
|
||||
{
|
||||
await using var f = await FixtureAsync(context);
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var remote = f.Remote.Add("Comet NAS", [photos[0]]);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.Sync.Copies.EnsureLinkedAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.RefreshAsync(new SyncPolicy { Linking = CopyLinking.AskAlways });
|
||||
// The server copy grows to hold every photo: the pair's score follows at the next comparison.
|
||||
remote.AddFrame(photos[1], "IMG_0002.JPG");
|
||||
await f.RefreshAsync(new SyncPolicy { Linking = CopyLinking.AskAlways });
|
||||
var pair = (await f.Sync.Copies.FindRemoteAsync(local.Id, f.Server, remote.Id, f.Ct))!;
|
||||
Assert.Equal((2, 0, 0), (pair.Score.Shared, pair.Score.OnlyHere, pair.Score.OnlyThere));
|
||||
using var engine = Engine(f);
|
||||
|
||||
await engine.UnlinkAsync(pair.Id, f.Remote, f.Ct);
|
||||
await f.RefreshAsync(new SyncPolicy { Linking = CopyLinking.AskAlways });
|
||||
|
||||
// Answered against two identical copies: nothing grew since, so the pair is not asked about again.
|
||||
var kept = (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!;
|
||||
Assert.Equal((CopyState.KeptApart, 2), (kept.State, kept.AnsweredShared ?? -1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DropVersionTrashesOneVersionOnBothSidesAndIsRefusedOnceTheOtherIsGone()
|
||||
{
|
||||
await using var f = await FixtureAsync(context);
|
||||
var (local, remote, a, b) = await VersionsAsync(f);
|
||||
var pair = await PairAsync(f, local.Id, remote.Id);
|
||||
using var engine = Engine(f);
|
||||
var review = await engine.CompareAsync(pair.Id, f.Remote, f.Ct);
|
||||
Assert.Count(2, review.Photos.Of(PhotoClass.Versions));
|
||||
|
||||
var plan = await engine.PlanDropVersionAsync(pair.Id, Sha(a), f.Remote, f.Ct);
|
||||
Assert.Equal((Sha(b), 2), (plan.PartnerKey, plan.Photos));
|
||||
Assert.Equal(2, await engine.DropVersionAsync(plan, f.Remote, f.Ct));
|
||||
|
||||
var left = await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct);
|
||||
Assert.SequenceEqual(new[] { Sha(b) }, left.Select(fr => fr.Sha256!).Where(s => s == Sha(a) || s == Sha(b)));
|
||||
Assert.False(remote.Frames.Any(fr => fr.Sha256 == Sha(a)));
|
||||
Assert.True(remote.Frames.Any(fr => fr.Sha256 == Sha(b)));
|
||||
Assert.Equal(Sha(a), f.Remote.Trashed.Single().Frame.Sha256);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DropVersionIsRefusedWhenTheOtherVersionLeftOneSide()
|
||||
{
|
||||
await using var f = await FixtureAsync(context);
|
||||
var (local, remote, a, b) = await VersionsAsync(f);
|
||||
var pair = await PairAsync(f, local.Id, remote.Id);
|
||||
using var engine = Engine(f);
|
||||
var plan = await engine.PlanDropVersionAsync(pair.Id, Sha(a), f.Remote, f.Ct);
|
||||
|
||||
// The other version leaves the server after the dry run: dropping this one would leave the server without the photo.
|
||||
await f.Remote.DeleteFramesAsync(remote.Id, new FrameDeleteRequest([remote.Frames.Single(fr => fr.Sha256 == Sha(b)).Id], null, false), f.Ct);
|
||||
|
||||
await Assert.ThrowsAsync<StaleCopyPlanException>(() => engine.DropVersionAsync(plan, f.Remote, f.Ct));
|
||||
Assert.True(remote.Frames.Any(fr => fr.Sha256 == Sha(a)));
|
||||
Assert.Count(1, f.Remote.Trashed);
|
||||
Assert.True((await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct)).Any(fr => fr.Sha256 == Sha(a)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DropOwnVersionTrashesOneVersionOfALocalSequenceAndIsRefusedOnceTheOtherIsGone()
|
||||
{
|
||||
// Two versions a Union merge left in one sequence, its pair gone (owner Q3): listed, and each can be dropped.
|
||||
await using var f = await FixtureAsync(context);
|
||||
var (local, _, a, b) = await VersionsAsync(f);
|
||||
using var engine = Engine(f);
|
||||
var photo = (await engine.VersionsAsync(local.Id, f.Ct)).Single();
|
||||
var (frameA, frameB) = photo.FirstSha256 == Sha(a) ? (photo.FirstFrameId, photo.SecondFrameId) : (photo.SecondFrameId, photo.FirstFrameId);
|
||||
Assert.True(photo.CapturedAt is not null && photo.FirstSize > 0 && photo.SecondSize > 0);
|
||||
|
||||
var dropA = await engine.PlanDropOwnVersionAsync(local.Id, frameA, f.Ct);
|
||||
Assert.Equal((1, frameB, Sha(b)), (dropA.Plan.Frames.Count, dropA.PartnerFrameId, dropA.PartnerSha256));
|
||||
Assert.Equal(Sha(a), dropA.LastCopies.Single().Key);
|
||||
var dropB = await engine.PlanDropOwnVersionAsync(local.Id, frameB, f.Ct);
|
||||
|
||||
Assert.Equal(1, await engine.DropOwnVersionAsync(dropB, f.Ct));
|
||||
var left = await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct);
|
||||
Assert.True(left.Any(fr => fr.Sha256 == Sha(a)) && !left.Any(fr => fr.Sha256 == Sha(b)));
|
||||
Assert.Empty(await engine.VersionsAsync(local.Id, f.Ct));
|
||||
|
||||
// The other version is gone now: dropping this one too would lose the photo, so nothing moves.
|
||||
await Assert.ThrowsAsync<StaleCopyPlanException>(() => engine.DropOwnVersionAsync(dropA, f.Ct));
|
||||
Assert.True((await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct)).Any(fr => fr.Sha256 == Sha(a)));
|
||||
}
|
||||
|
||||
/// <summary>The photos Main leaves out of <paramref name="sequenceId"/>, by content.</summary>
|
||||
private static async Task<IReadOnlySet<string>> ExcludedAsync(SyncFixture f, Guid sequenceId)
|
||||
{
|
||||
var row = (await f.Db.Sequences.GetAsync(sequenceId))!;
|
||||
return CopyPayload.ExcludedKeys(CopyPayload.Portable(SyncPayload.Of(row), await SequencePayloadWriter.PhotosAsync(f.Db, sequenceId, null, f.Ct)));
|
||||
}
|
||||
|
||||
/// <summary>Main of <paramref name="sequenceId"/> leaves out <paramref name="key"/>, as a Union keep-both leaves the incoming version.</summary>
|
||||
private static async Task ExcludeAsync(SyncFixture f, Guid sequenceId, string key)
|
||||
{
|
||||
var row = (await f.Db.Sequences.GetAsync(sequenceId))!;
|
||||
var portable = CopyPayload.Portable(SyncPayload.Of(row), await SequencePayloadWriter.PhotosAsync(f.Db, sequenceId, null, f.Ct));
|
||||
await new SequencePayloadWriter(f.Db, f.Archive.Service).ApplyAsync(sequenceId, CopyPayload.ExcludeVersions(portable, [key]), row.SettingsVersion, f.Ct);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DroppingTheVersionMainUsesLetsMainUseTheOneThatStays()
|
||||
{
|
||||
// A Union keep-both excluded version B in Main; the user drops A, the one Main used: Main must not be left without
|
||||
// the photo (owner review 6, verification round 5).
|
||||
await using var f = await FixtureAsync(context);
|
||||
var (local, _, a, b) = await VersionsAsync(f);
|
||||
await ExcludeAsync(f, local.Id, Sha(b));
|
||||
Assert.SequenceEqual([Sha(b)], await ExcludedAsync(f, local.Id));
|
||||
using var engine = Engine(f);
|
||||
var photo = (await engine.VersionsAsync(local.Id, f.Ct)).Single();
|
||||
var (frameA, aExcluded, bExcluded) = photo.FirstSha256 == Sha(a)
|
||||
? (photo.FirstFrameId, photo.FirstExcluded, photo.SecondExcluded)
|
||||
: (photo.SecondFrameId, photo.SecondExcluded, photo.FirstExcluded);
|
||||
Assert.Equal((false, true), (aExcluded, bExcluded));
|
||||
|
||||
var plan = await engine.PlanDropOwnVersionAsync(local.Id, frameA, f.Ct);
|
||||
Assert.Equal(1, await engine.DropOwnVersionAsync(plan, f.Ct));
|
||||
|
||||
Assert.Empty(await ExcludedAsync(f, local.Id));
|
||||
Assert.True((await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct)).Any(fr => fr.Sha256 == Sha(b)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task KeepVersionMovesTheExclusionHeroAndKeyframesToTheVersionThatStays()
|
||||
{
|
||||
await using var f = await FixtureAsync(context);
|
||||
var (local, _, a, b) = await VersionsAsync(f);
|
||||
await ExcludeAsync(f, local.Id, Sha(b));
|
||||
var row = (await f.Db.Sequences.GetAsync(local.Id))!;
|
||||
var portable = CopyPayload.Portable(SyncPayload.Of(row), await SequencePayloadWriter.PhotosAsync(f.Db, local.Id, null, f.Ct));
|
||||
|
||||
// Main used A and left B out: once A goes, B is used.
|
||||
var kept = CopyPayload.KeepVersion(portable, Sha(b), Sha(a));
|
||||
Assert.NotNull(kept);
|
||||
Assert.Empty(CopyPayload.ExcludedKeys(kept!));
|
||||
// Dropping the excluded one changes nothing in Main.
|
||||
Assert.Null(CopyPayload.KeepVersion(portable, Sha(a), Sha(b)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DropVersionOfTwoLocalSequencesCountsAPhotoOnEachSide()
|
||||
{
|
||||
// Finding 9 said a pair of this PC's sequences listed "0 photos": the plan counts each local side's version.
|
||||
await using var f = await FixtureAsync(context);
|
||||
var (local, _, a, b) = await VersionsAsync(f);
|
||||
var at = ArchiveFixture.Start.AddSeconds(5).AddMilliseconds(250);
|
||||
var plainAt = ArchiveFixture.Start;
|
||||
var other = await f.LocalAsync("Comet copy", [Photos.Jpeg(plainAt, 7001), a, b], capturedAt: [plainAt, at, at]);
|
||||
var pair = await f.Sync.Copies.UpsertFoundAsync(new FoundCopy
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Kind = CopyKind.LocalLocal,
|
||||
LocalId = local.Id,
|
||||
OtherId = other.Id,
|
||||
Evidence = CopyEvidence.Hashes,
|
||||
Fingerprint = "f",
|
||||
}, f.Ct);
|
||||
await ExcludeAsync(f, local.Id, Sha(b));
|
||||
await ExcludeAsync(f, other.Id, Sha(b));
|
||||
using var engine = Engine(f);
|
||||
|
||||
var plan = await engine.PlanDropVersionAsync(pair.Id, Sha(a), null, f.Ct);
|
||||
Assert.Equal((Sha(b), 2), (plan.PartnerKey, plan.Photos));
|
||||
Assert.Equal(2, await engine.DropVersionAsync(plan, null, f.Ct));
|
||||
|
||||
// Both sides' Main now use the version that stays.
|
||||
Assert.Empty(await ExcludedAsync(f, local.Id));
|
||||
Assert.Empty(await ExcludedAsync(f, other.Id));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A pair holding one photo in two versions (a Union keep-both): two files of one sub-second capture time, on both sides,
|
||||
/// besides one plain photo.
|
||||
/// </summary>
|
||||
private static async Task<(Sequence Local, FakeSequence Remote, byte[] A, byte[] B)> VersionsAsync(SyncFixture f)
|
||||
{
|
||||
var plainAt = ArchiveFixture.Start;
|
||||
var at = ArchiveFixture.Start.AddSeconds(5).AddMilliseconds(250);
|
||||
var (plain, a, b) = (Photos.Jpeg(plainAt, 7001), Photos.Jpeg(at, 7002), Photos.Jpeg(at, 7003));
|
||||
var local = await f.LocalAsync("Comet", [plain, a, b], capturedAt: [plainAt, at, at]);
|
||||
var remote = f.Remote.Add("Comet NAS", []);
|
||||
remote.AddFrame(plain, "IMG_0001.JPG", plainAt);
|
||||
remote.AddFrame(a, "IMG_0002.JPG", at);
|
||||
remote.AddFrame(b, "IMG_0003.JPG", at);
|
||||
return (local, remote, a, b);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TrashThereIsRefusedForAPhotoThisPcStillHolds()
|
||||
{
|
||||
await using var f = await FixtureAsync(context);
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var remote = f.Remote.Add("Comet NAS", photos);
|
||||
var pair = await PairAsync(f, local.Id, remote.Id);
|
||||
using var engine = Engine(f);
|
||||
|
||||
var plan = await engine.PlanTrashThereAsync(pair.Id, f.Remote, [Sha(photos[1])], f.Ct);
|
||||
|
||||
await Assert.ThrowsAsync<StaleCopyPlanException>(() => engine.TrashThereAsync(plan, f.Remote, f.Ct));
|
||||
Assert.Count(0, f.Remote.Trashed);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TwinsNameTheProjectsOfBothHomesOfALinkedPairEvenUnderTheServersIdKey()
|
||||
{
|
||||
// Owner Q5's alternative: projects left where they are; Edit's picker marks the two homes' projects as twins. The
|
||||
// server home is keyed by the server's id while the pair still carries the address key it was found under.
|
||||
var serverId = Guid.NewGuid();
|
||||
var address = string.Empty;
|
||||
await using var f = await SyncFixture.CreateAsync(context, () => new ServerIdentity([new KnownServerKey(serverId, [address])]));
|
||||
address = f.Server;
|
||||
var photos = f.NewPhotos(2);
|
||||
var linked = await f.LocalAsync("Comet", photos);
|
||||
var apart = await f.LocalAsync("Lighthouse", f.NewPhotos(2));
|
||||
var linkedRemote = f.Remote.Add("Comet NAS", photos);
|
||||
var apartRemote = f.Remote.Add("Lighthouse NAS", photos);
|
||||
var pair = await PairAsync(f, linked.Id, linkedRemote.Id);
|
||||
Assert.True(await f.Sync.Copies.SetStateAsync(pair.Id, CopyState.Candidate, CopyState.Linked, null, f.Ct));
|
||||
await PairAsync(f, apart.Id, apartRemote.Id);
|
||||
var sides = new CopySides(f.Db);
|
||||
IReadOnlyList<(Chronos.Core.Project.BundleHome Home, string Name)> projects =
|
||||
[
|
||||
(new(Chronos.Core.Project.BundleHome.ArchiveKind, linked.Id), "Grade"),
|
||||
(new(Chronos.Core.Project.BundleHome.ArchiveKind, linked.Id), "Vertical"),
|
||||
(new(Chronos.Core.Project.BundleHome.ArchiveKind, linked.Id), "Slow pan"),
|
||||
(new(Chronos.Core.Project.BundleHome.ServerKind, linkedRemote.Id, Server: ServerIdentity.IdKey(serverId)), "Grade"),
|
||||
(new(Chronos.Core.Project.BundleHome.ServerKind, linkedRemote.Id, Server: ServerIdentity.IdKey(serverId)), "Slow pan (STUDIO-PC)"),
|
||||
(new(Chronos.Core.Project.BundleHome.ArchiveKind, apart.Id), "Unpaired"),
|
||||
];
|
||||
using var engine = new CopyEngine(f.Sync, f.Archive.Service, new IntegratePlanner(f.Sync, sides, f.Archive.Service.Projects),
|
||||
new SequenceMerger(f.Db, f.Archive.Service, sides), new CopyReviewBuilder(f.Db, f.Archive.Service.Projects, sides), _ => Context,
|
||||
serverNames: key => key == f.Server ? "Studio NAS" : null, workspaceProjects: _ => Task.FromResult(projects));
|
||||
|
||||
var twin = (await engine.TwinsAsync(f.Ct)).Single();
|
||||
|
||||
Assert.Equal((pair.Id, linked.Id, linkedRemote.Id), (twin.CopyId, twin.LocalId, twin.RemoteId));
|
||||
Assert.SequenceEqual(["Grade", "Vertical", "Slow pan"], twin.LocalProjects);
|
||||
Assert.SequenceEqual(["Grade", "Slow pan (STUDIO-PC)"], twin.ServerProjects);
|
||||
// A project is a twin only with its sibling: the same name, or the name Copy across gave it at the other home.
|
||||
Assert.Equal("Grade", twin.CounterpartOf("Grade", atServerHome: false));
|
||||
Assert.Null(twin.CounterpartOf("Vertical", atServerHome: false));
|
||||
Assert.Equal("Slow pan (STUDIO-PC)", twin.CounterpartOf("Slow pan", atServerHome: false));
|
||||
Assert.Equal("Slow pan", twin.CounterpartOf("Slow pan (STUDIO-PC)", atServerHome: true));
|
||||
Assert.Equal(f.Server, twin.Server);
|
||||
// The Edit picker shows the server by its name, never by its key.
|
||||
Assert.Equal("Studio NAS", twin.ServerName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Copies;
|
||||
using Chronos.Data.Tests.Sync;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Copies;
|
||||
|
||||
/// <summary>Detection on this PC (owner review 6, #73; design §3.4): two local copies are asked about, never linked.</summary>
|
||||
[Category("sync")]
|
||||
public sealed class CopyFinderLocalTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public async Task TwoLocalCopiesAreAskedAndNeverLinked()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(4);
|
||||
var first = await f.LocalAsync("Comet", photos);
|
||||
var second = await f.LocalAsync("Comet (card)", photos.Take(3).ToList());
|
||||
await f.LocalAsync("Harbour", f.NewPhotos(2));
|
||||
|
||||
var result = await f.Sync.Finder.FindLocalAsync(f.Ct);
|
||||
|
||||
var pair = result.New.Single();
|
||||
Assert.Equal((CopyKind.LocalLocal, CopyState.Candidate, CopyEvidence.Hashes), (pair.Kind, pair.State, pair.Evidence));
|
||||
Assert.Equal(FoundCopyStore.Order(first.Id, second.Id), (pair.LocalId, pair.OtherId!.Value));
|
||||
Assert.Equal(3, pair.Score.Shared);
|
||||
Assert.Empty(result.AutoLinked);
|
||||
Assert.Count(1, await f.Sync.Copies.ListAsync(f.Ct));
|
||||
|
||||
// Nothing moved: nothing is compared or announced again.
|
||||
Assert.True((await f.Sync.Finder.FindLocalAsync(f.Ct)).IsEmpty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnUnhashedCopyIsFoundBySizeAndCaptureTime()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(3);
|
||||
await f.LocalAsync("Comet", photos);
|
||||
var adopted = await f.LocalAsync("Comet (adopted)", photos);
|
||||
await using (var session = await f.Db.Database.OpenAsync(f.Ct))
|
||||
await session.ExecuteAsync("UPDATE frames SET sha256 = NULL WHERE sequence_id = $1", [adopted.Id], f.Ct);
|
||||
|
||||
var pair = (await f.Sync.Finder.FindLocalAsync(f.Ct)).New.Single();
|
||||
|
||||
Assert.Equal(CopyEvidence.SizeAndTime, pair.Evidence);
|
||||
Assert.Equal(3, pair.Score.SharedUnhashed);
|
||||
Assert.Equal(CopyState.Candidate, pair.State);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AKeptApartPairStaysApartAndAMergeTargetIsLeftAlone()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(3);
|
||||
var first = await f.LocalAsync("Comet", photos);
|
||||
await f.LocalAsync("Comet (card)", photos);
|
||||
var pair = (await f.Sync.Finder.FindLocalAsync(f.Ct)).New.Single();
|
||||
Assert.True(await f.Sync.Copies.SetStateAsync(pair.Id, CopyState.Candidate, CopyState.KeptApart,
|
||||
new CopyAnswer(pair.Fingerprint, pair.Score.Shared, null, false, DateTimeOffset.UtcNow), f.Ct));
|
||||
|
||||
await f.Sync.Finder.ResetProbesAsync(CopyFinder.LocalScope, f.Ct);
|
||||
Assert.True((await f.Sync.Finder.FindLocalAsync(f.Ct)).IsEmpty);
|
||||
Assert.Equal(CopyState.KeptApart, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State);
|
||||
|
||||
// A third copy while a merge waits on the first: the first is left out until the merge ends.
|
||||
var third = await f.LocalAsync("Comet (again)", photos);
|
||||
await f.Db.Jobs.EnqueueAsync(new Job
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Kind = JobKind.MergeSequences,
|
||||
TargetIds = [first.Id],
|
||||
State = JobState.Queued,
|
||||
Created = DateTimeOffset.UtcNow,
|
||||
}, f.Ct);
|
||||
var result = await f.Sync.Finder.FindLocalAsync(f.Ct);
|
||||
Assert.False(result.New.Any(p => p.Names(first.Id)));
|
||||
Assert.True(result.New.Single().Names(third.Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task APairThatSharesNothingAnyMoreIsNoLongerAsked()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(2);
|
||||
await f.LocalAsync("Comet", photos);
|
||||
var second = await f.LocalAsync("Comet (card)", photos);
|
||||
var pair = (await f.Sync.Finder.FindLocalAsync(f.Ct)).New.Single();
|
||||
|
||||
await using (var session = await f.Db.Database.OpenAsync(f.Ct))
|
||||
await session.ExecuteAsync("UPDATE frames SET sha256 = NULL, captured_at = NULL WHERE sequence_id = $1", [second.Id], f.Ct);
|
||||
await f.Sync.Finder.FindLocalAsync(f.Ct);
|
||||
|
||||
Assert.Null(await f.Sync.Copies.GetAsync(pair.Id, f.Ct));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Copies;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Data.Tests.Sync;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Copies;
|
||||
|
||||
/// <summary>
|
||||
/// Detection against a server (owner review 6, #73; design §3.3): the photo lookup and its follow-ups, the exact comparison,
|
||||
/// what is left alone, the probes kept across refreshes and restarts, and the limits of one refresh.
|
||||
/// </summary>
|
||||
[Category("sync")]
|
||||
public sealed class CopyFinderServerTests(TestContext context)
|
||||
{
|
||||
private static async Task<SyncFixture> LookupAsync(TestContext context)
|
||||
{
|
||||
var f = await SyncFixture.CreateAsync(context);
|
||||
f.Remote.Capabilities.Add(ServerCapabilities.PhotoLookup);
|
||||
return f;
|
||||
}
|
||||
|
||||
private static Task<IReadOnlyList<FoundCopy>> PairsAsync(SyncFixture f) => f.Sync.Copies.ListAsync(f.Ct);
|
||||
|
||||
[Test]
|
||||
public async Task AServerSequenceHoldingSomeOfThePhotosIsAsked()
|
||||
{
|
||||
await using var f = await LookupAsync(context);
|
||||
var photos = f.NewPhotos(4);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var remote = f.Remote.Add("Comet (selection)", photos.Take(2));
|
||||
f.Remote.Add("Other card", f.NewPhotos(2));
|
||||
|
||||
await f.RefreshAsync();
|
||||
|
||||
var pair = (await PairsAsync(f)).Single();
|
||||
Assert.Equal((CopyKind.LocalServer, local.Id, remote.Id), (pair.Kind, pair.LocalId, pair.RemoteId!.Value));
|
||||
Assert.Equal((CopyState.Candidate, CopyEvidence.Hashes), (pair.State, pair.Evidence));
|
||||
Assert.Equal((2, 2, 0), (pair.Score.Shared, pair.Score.OnlyHere, pair.Score.OnlyThere));
|
||||
Assert.Count(1, f.Remote.Lookups);
|
||||
Assert.Equal(1, f.Remote.ManifestCalls);
|
||||
Assert.Equal("chronos-sync:" + local.Id.ToString("N"), f.Remote.Lookups[0].Probes.Single().SessionKey);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnUploadFiledUnderThisCopysKeyIsFoundByIt()
|
||||
{
|
||||
await using var f = await LookupAsync(context);
|
||||
var photos = f.NewPhotos(3);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var remote = f.Remote.Add("2026-09-28 Canon", photos);
|
||||
f.Remote.FileUnder("chronos-sync:" + local.Id.ToString("N"), remote);
|
||||
|
||||
await f.RefreshAsync();
|
||||
|
||||
var pair = (await PairsAsync(f)).Single();
|
||||
Assert.Equal((CopyEvidence.SessionKey, remote.Id), (pair.Evidence, pair.RemoteId!.Value));
|
||||
Assert.Equal(CopyState.Candidate, pair.State);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ADownloadWhoseLinkWasLostIsFoundByItsKey()
|
||||
{
|
||||
await using var f = await LookupAsync(context);
|
||||
var photos = f.NewPhotos(2);
|
||||
var remote = f.Remote.Add("Comet", photos);
|
||||
var local = await LocalUnderAsync(f, photos, SyncService.SessionKey(remote.Id));
|
||||
|
||||
await f.RefreshAsync();
|
||||
|
||||
var pair = (await PairsAsync(f)).Single();
|
||||
Assert.Equal((CopyEvidence.SessionKey, local.Id, remote.Id), (pair.Evidence, pair.LocalId, pair.RemoteId!.Value));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ASecondLocalCopyOfALinkedServerSequenceMakesALocalPair()
|
||||
{
|
||||
await using var f = await LookupAsync(context);
|
||||
var photos = f.NewPhotos(3);
|
||||
var first = await f.LocalAsync("Comet", photos);
|
||||
var second = await f.LocalAsync("Comet copy", photos);
|
||||
var remote = f.Remote.Add("Comet", photos);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, first.Id, f.Ct);
|
||||
|
||||
await f.RefreshAsync(new SyncPolicy { Linking = CopyLinking.WhenHalfShared });
|
||||
|
||||
Assert.Null(await f.Sync.LinkOfAsync(f.Server, second.Id, f.Ct));
|
||||
var local = (await PairsAsync(f)).Single(p => p.Kind == CopyKind.LocalLocal);
|
||||
Assert.Equal(FoundCopyStore.Order(first.Id, second.Id), (local.LocalId, local.OtherId!.Value));
|
||||
Assert.Equal(CopyState.Candidate, local.State);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SequencesAnIntegrateWaitsForAreLeftAlone()
|
||||
{
|
||||
await using var f = await LookupAsync(context);
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
f.Remote.Add("Comet", photos);
|
||||
await f.Db.Jobs.EnqueueAsync(new Job
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Kind = JobKind.Integrate,
|
||||
TargetIds = [local.Id],
|
||||
State = JobState.Queued,
|
||||
Created = DateTimeOffset.UtcNow,
|
||||
}, f.Ct);
|
||||
|
||||
await f.RefreshAsync();
|
||||
|
||||
Assert.Empty(await PairsAsync(f));
|
||||
Assert.Empty(f.Remote.Lookups);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AKeptApartPairIsNotAskedAgainForTheSamePhotos()
|
||||
{
|
||||
await using var f = await LookupAsync(context);
|
||||
var photos = f.NewPhotos(3);
|
||||
await f.LocalAsync("Comet", photos);
|
||||
f.Remote.Add("Comet", photos);
|
||||
await f.RefreshAsync();
|
||||
var pair = (await PairsAsync(f)).Single();
|
||||
Assert.True(await f.Sync.Copies.SetStateAsync(pair.Id, CopyState.Candidate, CopyState.KeptApart,
|
||||
new CopyAnswer(pair.Fingerprint, pair.Score.Shared, null, false, DateTimeOffset.UtcNow), f.Ct));
|
||||
var raised = new List<CopyFindResult>();
|
||||
f.Sync.CopiesFound += (_, result) => raised.Add(result);
|
||||
|
||||
await f.Sync.Finder.ResetProbesAsync(f.Server, f.Ct);
|
||||
await f.RefreshAsync(new SyncPolicy { Linking = CopyLinking.WhenIdentical });
|
||||
|
||||
Assert.Count(2, f.Remote.Lookups);
|
||||
Assert.Equal(CopyState.KeptApart, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State);
|
||||
Assert.Empty(raised);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task NothingIsLookedUpAgainUntilTheCopyChanges()
|
||||
{
|
||||
await using var f = await LookupAsync(context);
|
||||
var photos = f.NewPhotos(3);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
f.Remote.Add("Harbour", f.NewPhotos(2));
|
||||
await f.RefreshAsync();
|
||||
await f.RefreshAsync();
|
||||
Assert.Count(1, f.Remote.Lookups);
|
||||
|
||||
// A restart keeps what was probed.
|
||||
var restarted = new SyncService(f.Db, f.Archive.Service, new SyncOptions
|
||||
{
|
||||
Archive = new ArchiveServiceOptions { Owner = "test" },
|
||||
ProxyCacheDirectory = context.CreateTempDirectory("proxies-again"),
|
||||
});
|
||||
await restarted.RefreshAsync(f.Remote, new SyncPolicy(), f.Ct);
|
||||
Assert.Count(1, f.Remote.Lookups);
|
||||
|
||||
// Hashes lost and given back by Verify change what the copy can be found by.
|
||||
await SetHashesAsync(f, local.Id, null);
|
||||
await f.RefreshAsync();
|
||||
Assert.Count(2, f.Remote.Lookups);
|
||||
Assert.Empty(f.Remote.Lookups[1].Probes.Single().Sha256);
|
||||
Assert.Equal(3, f.Remote.Lookups[1].Probes.Single().Unhashed!.Count);
|
||||
|
||||
// A sequence uploaded to the server later is looked for too.
|
||||
f.Remote.Add("Comet", photos);
|
||||
await f.RefreshAsync();
|
||||
Assert.Count(3, f.Remote.Lookups);
|
||||
Assert.Equal(CopyEvidence.SizeAndTime, (await PairsAsync(f)).Single().Evidence);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AServerCopyNotHashedYetIsFoundByTheSizeAndTimeOfHashedPhotos()
|
||||
{
|
||||
await using var f = await LookupAsync(context);
|
||||
var photos = f.NewPhotos(3);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
// Adopted on the server and not verified there: it lists no hash, so only size and capture time can find it.
|
||||
var remote = f.Remote.Add("Comet", photos);
|
||||
remote.Unhashed = true;
|
||||
|
||||
await f.RefreshAsync();
|
||||
|
||||
var pair = (await PairsAsync(f)).Single();
|
||||
Assert.Equal((local.Id, remote.Id), (pair.LocalId, pair.RemoteId!.Value));
|
||||
Assert.Equal(CopyState.Candidate, pair.State);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ASequenceAddedOnAServerWhoseClockIsBehindIsStillLookedFor()
|
||||
{
|
||||
await using var f = await LookupAsync(context);
|
||||
var photos = f.NewPhotos(3);
|
||||
await f.LocalAsync("Comet", photos);
|
||||
var other = f.Remote.Add("Harbour", f.NewPhotos(2));
|
||||
other.UpdatedAt = DateTimeOffset.UtcNow.AddHours(-3);
|
||||
await f.RefreshAsync();
|
||||
Assert.Count(1, f.Remote.Lookups);
|
||||
|
||||
// Added after the probe by a server whose clock is three hours behind this PC's: later than the newest it showed.
|
||||
var remote = f.Remote.Add("Comet", photos);
|
||||
remote.UpdatedAt = other.UpdatedAt.AddMinutes(1);
|
||||
await f.RefreshAsync();
|
||||
|
||||
Assert.Count(2, f.Remote.Lookups);
|
||||
Assert.Equal(remote.Id, (await PairsAsync(f)).Single().RemoteId!.Value);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task OneRefreshComparesAtMostFiftyPairs()
|
||||
{
|
||||
await using var f = await LookupAsync(context);
|
||||
for (var i = 0; i < CopyFinder.MaxExact + 1; i++)
|
||||
{
|
||||
var photos = f.NewPhotos(1);
|
||||
await f.LocalAsync($"Card {i}", photos);
|
||||
f.Remote.Add($"Card {i}", photos);
|
||||
}
|
||||
|
||||
await f.RefreshAsync();
|
||||
Assert.Equal(CopyFinder.MaxExact, f.Remote.ManifestCalls);
|
||||
Assert.Count(CopyFinder.MaxExact, await PairsAsync(f));
|
||||
|
||||
await f.RefreshAsync();
|
||||
Assert.Equal(CopyFinder.MaxExact + 1, f.Remote.ManifestCalls);
|
||||
Assert.Count(CopyFinder.MaxExact + 1, await PairsAsync(f));
|
||||
Assert.True(f.Remote.Lookups.All(l => l.Probes.Count <= PhotoLookupRequest.MaxProbes && l.CountItems() <= PhotoLookupRequest.MaxItems));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnOlderServerIsComparedByTheGateTwentyManifestsAtATime()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
FakeSequence? copy = null;
|
||||
for (var i = 0; i <= CopyFinder.MaxExactOlderServer; i++)
|
||||
{
|
||||
// The same first second and camera: each one passes 1.1's gate; only the last holds the photos.
|
||||
var remote = f.Remote.Add($"Card {i}", i == CopyFinder.MaxExactOlderServer ? photos : f.NewPhotos(1));
|
||||
remote.FirstCapture = local.FirstCapture;
|
||||
remote.CameraModel = local.CameraModel;
|
||||
copy = remote;
|
||||
}
|
||||
|
||||
await f.RefreshAsync();
|
||||
Assert.Equal(CopyFinder.MaxExactOlderServer, f.Remote.ManifestCalls);
|
||||
|
||||
await f.RefreshAsync();
|
||||
Assert.Equal(CopyFinder.MaxExactOlderServer + 1, f.Remote.ManifestCalls);
|
||||
var pair = (await PairsAsync(f)).Single();
|
||||
Assert.Equal((copy!.Id, CopyState.Candidate), (pair.RemoteId!.Value, pair.State));
|
||||
Assert.Empty(f.Remote.Lookups);
|
||||
|
||||
await f.RefreshAsync();
|
||||
Assert.Equal(CopyFinder.MaxExactOlderServer + 1, f.Remote.ManifestCalls);
|
||||
}
|
||||
|
||||
private static async Task SetHashesAsync(SyncFixture f, Guid sequenceId, string? sha256)
|
||||
{
|
||||
await using var session = await f.Db.Database.OpenAsync(f.Ct);
|
||||
await session.ExecuteAsync("UPDATE frames SET sha256 = $1 WHERE sequence_id = $2", [sha256, sequenceId], f.Ct);
|
||||
}
|
||||
|
||||
/// <summary>A local sequence filed under <paramref name="sessionKey"/> (a download of a server sequence keeps its back-reference).</summary>
|
||||
private static async Task<Sequence> LocalUnderAsync(SyncFixture f, IReadOnlyList<byte[]> originals, string sessionKey)
|
||||
{
|
||||
Guid? id = null;
|
||||
var staging = Path.Combine(f.Archive.Paths.StagingDirectory, "session");
|
||||
Directory.CreateDirectory(staging);
|
||||
for (var i = 0; i < originals.Count; i++)
|
||||
{
|
||||
var path = Path.Combine(staging, $"{Guid.NewGuid():N}.part");
|
||||
await File.WriteAllBytesAsync(path, originals[i], f.Ct);
|
||||
var sha = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(originals[i]));
|
||||
var result = await f.Archive.Service.Ingest.CommitAsync(new IngestRequest(f.Archive.Archive.Id, id, null, id is null ? sessionKey : null, path,
|
||||
$"IMG_{i + 1:0000}.JPG", originals[i].Length, sha, null, null), f.Ct);
|
||||
id = result.SequenceId;
|
||||
}
|
||||
return (await f.Db.Sequences.GetAsync(id!.Value, f.Ct))!;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using Chronos.Data.Copies;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Copies;
|
||||
|
||||
/// <summary>The parameters of the Integrate and MergeSequences jobs (owner review 6, #73) survive the job row, and junk reads as none.</summary>
|
||||
[Category("jobs")]
|
||||
public sealed class CopyJobParametersTests
|
||||
{
|
||||
[Test]
|
||||
public void IntegrateParametersRoundTrip()
|
||||
{
|
||||
var choices = new IntegrateChoices(CopyPhotoPolicy.ChoosePerPhoto, new Dictionary<string, PhotoChoice> { ["h:ab"] = PhotoChoice.KeepBoth },
|
||||
new Dictionary<string, CopySide> { ["title"] = CopySide.Other }, CopyProjects.Leave);
|
||||
var parameters = new IntegrateJobParameters(Guid.NewGuid(), "https://nas.test:8443", Guid.CreateVersion7(), Guid.CreateVersion7(), choices, "fp", true);
|
||||
var json = parameters.ToJson();
|
||||
// Enums are written by name: a value appended later never shifts what a queued job meant.
|
||||
Assert.Contains("\"ChoosePerPhoto\"", json);
|
||||
Assert.Contains("\"autoPhotos\":true", json);
|
||||
var back = IntegrateJobParameters.Read(json)!;
|
||||
Assert.Equal((parameters.CopyId, parameters.Server, parameters.LocalId, parameters.RemoteId, "fp", true),
|
||||
(back.CopyId, back.Server, back.LocalId, back.RemoteId, back.Fingerprint, back.AutoPhotos));
|
||||
Assert.Equal((CopyPhotoPolicy.ChoosePerPhoto, PhotoChoice.KeepBoth, CopySide.Other, CopyProjects.Leave),
|
||||
(back.Choices.Photos, back.Choices.PerPhoto["h:ab"], back.Choices.Details["title"], back.Choices.Projects));
|
||||
Assert.Null(IntegrateJobParameters.Read(null));
|
||||
Assert.Null(IntegrateJobParameters.Read("{not json"));
|
||||
Assert.Null(IntegrateJobParameters.Read("{}"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void MergeParametersRoundTrip()
|
||||
{
|
||||
var choices = new MergeChoices(CopyPhotoPolicy.Union, new Dictionary<string, PhotoChoice>(), new Dictionary<string, CopySide>());
|
||||
var parameters = new MergeJobParameters(Guid.NewGuid(), Guid.CreateVersion7(), Guid.CreateVersion7(), choices, "fp");
|
||||
var back = MergeJobParameters.Read(parameters.ToJson())!;
|
||||
Assert.Equal((parameters.CopyId, parameters.KeepId, parameters.DropId, "fp", CopyPhotoPolicy.Union),
|
||||
(back.CopyId, back.KeepId, back.DropId, back.Fingerprint, back.Choices.Photos));
|
||||
Assert.Null(MergeJobParameters.Read(" "));
|
||||
Assert.Null(MergeJobParameters.Read("[1]"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Copies;
|
||||
using Chronos.Data.Tests.Archiving;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Copies;
|
||||
|
||||
/// <summary>
|
||||
/// What a merge or an integration leaves in the archive's journal folder (owner review 6, #73): the maintenance pass keeps
|
||||
/// the journal a retry can use and clears the one no job will read again, as it does for conversions.
|
||||
/// </summary>
|
||||
[Category("archive")]
|
||||
public sealed class CopyJournalMaintenanceTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public async Task MaintenanceClearsTheJournalOfAMergeOrIntegrateNoJobWillReadAgain()
|
||||
{
|
||||
await using var fx = await ArchiveFixture.CreateAsync(context);
|
||||
var failed = Guid.CreateVersion7();
|
||||
var done = Guid.CreateVersion7();
|
||||
var cancelled = Guid.CreateVersion7();
|
||||
var paused = Guid.CreateVersion7();
|
||||
foreach (var (id, kind, state) in new[]
|
||||
{
|
||||
(failed, JobKind.MergeSequences, JobState.Failed), (done, JobKind.Integrate, JobState.Done),
|
||||
(cancelled, JobKind.MergeSequences, JobState.Cancelled), (paused, JobKind.Integrate, JobState.Paused),
|
||||
})
|
||||
await fx.Db.Jobs.EnqueueAsync(new Job { Id = id, Kind = kind, State = state, Created = DateTimeOffset.UtcNow }, fx.Ct);
|
||||
// Deleted without a cancel: the index no longer knows the job.
|
||||
var deleted = Guid.CreateVersion7();
|
||||
var recent = Guid.CreateVersion7();
|
||||
|
||||
const int Old = Housekeeping.CleanupSteps.DefaultHistoryDays + 1;
|
||||
string Write(string path, int daysOld)
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
File.WriteAllText(path, "{}");
|
||||
File.SetLastWriteTimeUtc(path, DateTime.UtcNow.AddDays(-daysOld));
|
||||
return path;
|
||||
}
|
||||
var failedJournal = Write(MergeJournal.PathFor(fx.Paths, failed), Old);
|
||||
var doneJournal = Write(IntegrateJournal.PathFor(fx.Paths, done), 0);
|
||||
var cancelledJournal = Write(MergeJournal.PathFor(fx.Paths, cancelled), 0);
|
||||
var pausedJournal = Write(IntegrateJournal.PathFor(fx.Paths, paused), Old);
|
||||
var deletedJournal = Write(MergeJournal.PathFor(fx.Paths, deleted), Old);
|
||||
var recentJournal = Write(IntegrateJournal.PathFor(fx.Paths, recent), 1);
|
||||
var other = Write(Path.Combine(fx.Paths.JournalDirectory, "merge-notes.json"), Old);
|
||||
|
||||
var dry = await fx.Service.Maintenance.RunAsync(fx.Archive, dryRun: true, 0, _ => ValueTask.CompletedTask, fx.Ct);
|
||||
Assert.SequenceEqual(new[] { doneJournal, cancelledJournal, deletedJournal }.Select(fx.Paths.ToRelative).Order(), dry.TemporaryFiles.Order());
|
||||
Assert.FileExists(deletedJournal);
|
||||
|
||||
await fx.Service.Maintenance.RunAsync(fx.Archive, dryRun: false, 0, _ => ValueTask.CompletedTask, fx.Ct);
|
||||
|
||||
Assert.FileMissing(doneJournal);
|
||||
Assert.FileMissing(cancelledJournal);
|
||||
Assert.FileMissing(deletedJournal);
|
||||
// A retry still reads these: the failed and the paused job's, and one another host may still be writing.
|
||||
Assert.FileExists(failedJournal);
|
||||
Assert.FileExists(pausedJournal);
|
||||
Assert.FileExists(recentJournal);
|
||||
Assert.FileExists(other);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void OnlyTheJournalsOfMergesAndIntegrationsAreRecognised()
|
||||
{
|
||||
var job = Guid.CreateVersion7();
|
||||
Assert.Equal(job, ArchiveMaintenance.CopyJournalJob($"merge-{job:N}.json"));
|
||||
Assert.Equal(job, ArchiveMaintenance.CopyJournalJob($"integrate-{job:N}.json"));
|
||||
Assert.Null(ArchiveMaintenance.CopyJournalJob($"convert-{job:N}.json"));
|
||||
Assert.Null(ArchiveMaintenance.CopyJournalJob($"merge-{job:N}.json.tmp"));
|
||||
Assert.Null(ArchiveMaintenance.CopyJournalJob($"merge-{job:D}.json"));
|
||||
}
|
||||
}
|
||||
@@ -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,111 @@
|
||||
using Chronos.Data.Copies;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Data.Tests.Sync;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Copies;
|
||||
|
||||
/// <summary>What the Compare dialog shows of a pair (owner review 6, #73; design §4.4): facts, photos, details and what can be done.</summary>
|
||||
[Category("sync")]
|
||||
public sealed class CopyReviewBuilderTests(TestContext context)
|
||||
{
|
||||
private static CopyPlanContext Context(bool canUpload = true, bool canDelete = false) =>
|
||||
new("PC", "NAS", canUpload, true, true, canDelete, canDelete, false, null, new HashSet<Guid>(), new HashSet<Guid>());
|
||||
|
||||
private static CopyReviewBuilder Builder(SyncFixture f) => new(f.Db, f.Archive.Service.Projects, new CopySides(f.Db));
|
||||
|
||||
/// <summary>A local copy and a server copy sharing two photos, each holding one more, with different settings; asked about.</summary>
|
||||
private static async Task<(FoundCopy Pair, Guid LocalId, FakeSequence Remote)> AskedAsync(SyncFixture f)
|
||||
{
|
||||
var photos = f.NewPhotos(4);
|
||||
var local = await f.LocalAsync("Comet", photos.Take(3).ToList(), SyncFixture.Window33);
|
||||
var remote = f.Remote.Add("Comet", [photos[0], photos[1], photos[3]], SyncFixture.Window41);
|
||||
await f.RefreshAsync();
|
||||
return ((await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single(), local.Id, remote);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AServerPairShowsBothSidesAndCanBeIntegrated()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
f.Remote.Capabilities.Add(ServerCapabilities.PhotoLookup);
|
||||
f.Remote.Capabilities.Add(ServerCapabilities.UploadInto);
|
||||
var (pair, localId, remote) = await AskedAsync(f);
|
||||
|
||||
var review = await Builder(f).BuildAsync(pair, f.Remote, Context(), f.Ct);
|
||||
|
||||
Assert.Equal(("Comet", f.Archive.Archive.Id, 3, 3), (review.Here.Title, review.Here.ArchiveId, review.Here.Photos, review.Here.Hashed));
|
||||
Assert.Equal((3, (Guid?)null), (review.There.Photos, review.There.ArchiveId));
|
||||
Assert.Equal((2, 1, 1), (review.Photos.Score.Shared, review.Photos.Score.OnlyHere, review.Photos.Score.OnlyThere));
|
||||
Assert.True(review.Details.Any(d => d.Path.StartsWith("exposure", StringComparison.Ordinal)));
|
||||
Assert.Empty(review.Can.Blocks);
|
||||
Assert.True(review.Can.Integrate);
|
||||
Assert.True(review.Can.LinkOnly);
|
||||
Assert.False(review.Can.DeleteThere);
|
||||
Assert.Equal(pair.Id, review.Copy.Id);
|
||||
Assert.Equal(localId, review.Copy.LocalId);
|
||||
Assert.Equal(remote.Id, review.Copy.RemoteId);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnOlderServerOrMissingRightsBlockIntegrateButNotLinkOnly()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var (pair, _, _) = await AskedAsync(f);
|
||||
|
||||
var review = await Builder(f).BuildAsync(pair, f.Remote, Context(canUpload: false, canDelete: true), f.Ct);
|
||||
|
||||
Assert.SequenceEqual([CopyBlock.NeedsNewerServer, CopyBlock.NoUploadRight], review.Can.Blocks);
|
||||
Assert.False(review.Can.Integrate);
|
||||
Assert.True(review.Can.LinkOnly);
|
||||
Assert.True(review.Can.DeleteThere);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ALinkToAnotherCopyIsTaken()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
f.Remote.Capabilities.Add(ServerCapabilities.PhotoLookup);
|
||||
f.Remote.Capabilities.Add(ServerCapabilities.UploadInto);
|
||||
var (pair, localId, _) = await AskedAsync(f);
|
||||
var other = f.Remote.Add("Harbour", f.NewPhotos(1));
|
||||
await f.Sync.LinkAsync(f.Server, other.Id, localId, f.Ct);
|
||||
|
||||
var review = await Builder(f).BuildAsync(pair, f.Remote, Context(), f.Ct);
|
||||
|
||||
Assert.Contains(CopyBlock.LinkTaken, review.Can.Blocks);
|
||||
Assert.False(review.Can.Integrate);
|
||||
Assert.False(review.Can.LinkOnly);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TwoLocalCopiesCanBeMergedNeverLinked()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(3);
|
||||
await f.LocalAsync("Comet", photos);
|
||||
await f.LocalAsync("Comet (card)", photos.Take(2).ToList(), SyncFixture.Window41);
|
||||
var pair = (await f.Sync.Finder.FindLocalAsync(f.Ct)).New.Single();
|
||||
|
||||
var review = await Builder(f).BuildAsync(pair, null, Context(), f.Ct);
|
||||
|
||||
Assert.Equal((2, 1, 0), (review.Photos.Score.Shared, review.Photos.Score.OnlyHere + review.Photos.Score.OnlyThere, review.Photos.Score.Differs));
|
||||
Assert.Equal(f.Archive.Archive.Id, review.There.ArchiveId);
|
||||
Assert.NotEmpty(review.Details);
|
||||
Assert.True(review.Can.Integrate);
|
||||
Assert.False(review.Can.LinkOnly);
|
||||
Assert.False(review.Can.DeleteThere);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AServerPairNeedsItsServer()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var (pair, _, _) = await AskedAsync(f);
|
||||
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => Builder(f).BuildAsync(pair, null, Context(), f.Ct));
|
||||
await Assert.ThrowsAsync<ArgumentException>(() =>
|
||||
Builder(f).BuildAsync(pair, new FakeSyncRemote { Server = "https://other.test:8443" }, Context(), f.Ct));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,446 @@
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Copies;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Data.Tests.Infrastructure;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Copies;
|
||||
|
||||
/// <summary>The found copies store (owner review 6, #73, migration 0012): pairs, answers, the Integrating backstop, merges and 404s.</summary>
|
||||
[Category("sync")]
|
||||
public abstract class FoundCopyStoreTests(TestContext context) : RepositoryTest(context)
|
||||
{
|
||||
private const string Nas = "https://nas.test:8443";
|
||||
private const string Other = "id:server-b";
|
||||
|
||||
private async Task<(ChronosDatabase Db, Archive Archive, Sequence[] Sequences)> SetupAsync(int count)
|
||||
{
|
||||
var db = await OpenChronosAsync();
|
||||
var archive = TestData.Archive();
|
||||
await db.Archives.UpsertAsync(archive, Ct);
|
||||
var sequences = new Sequence[count];
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
sequences[i] = TestData.Sequence(archive.Id);
|
||||
await db.Sequences.UpsertAsync(sequences[i], Ct);
|
||||
}
|
||||
return (db, archive, sequences);
|
||||
}
|
||||
|
||||
private static FoundCopy Remote(Guid localId, Guid remoteId, string server = Nas, CopyEvidence evidence = CopyEvidence.Hashes) => new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Kind = CopyKind.LocalServer,
|
||||
LocalId = localId,
|
||||
Server = server,
|
||||
RemoteId = remoteId,
|
||||
Evidence = evidence,
|
||||
Fingerprint = "f1",
|
||||
};
|
||||
|
||||
private static FoundCopy Local(Guid a, Guid b) => new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Kind = CopyKind.LocalLocal,
|
||||
LocalId = a,
|
||||
OtherId = b,
|
||||
Evidence = CopyEvidence.Hashes,
|
||||
Fingerprint = "f1",
|
||||
};
|
||||
|
||||
private static SyncLink Link(string server, Guid remoteId, Guid localId) => new()
|
||||
{
|
||||
Server = server,
|
||||
RemoteId = remoteId,
|
||||
LocalId = localId,
|
||||
Title = "Harbour",
|
||||
RemoteUpdatedAt = TestData.Now,
|
||||
DiffLocalFrames = 3,
|
||||
BaseLocalSettings = 2,
|
||||
MissingRemote = 4,
|
||||
};
|
||||
|
||||
private static CopyAnswer Answer(Guid? job = null, bool? auto = null, string? fingerprint = null, int? shared = null) =>
|
||||
new(fingerprint, shared, job, auto, TestData.Now);
|
||||
|
||||
private async Task<Job> JobAsync(ChronosDatabase db, JobKind kind = JobKind.Integrate)
|
||||
{
|
||||
var job = TestData.Job(kind);
|
||||
await db.Jobs.EnqueueAsync(job, Ct);
|
||||
return job;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ThePruneOfAStaleCandidateLeavesARowAnsweredMeanwhile()
|
||||
{
|
||||
var (db, _, s) = await SetupAsync(2);
|
||||
var store = new FoundCopyStore(db);
|
||||
var stale = await store.UpsertFoundAsync(Remote(s[0].Id, Guid.CreateVersion7()), Ct);
|
||||
var answered = await store.UpsertFoundAsync(Remote(s[1].Id, Guid.CreateVersion7()), Ct);
|
||||
// Detection read both as candidates; the user keeps one apart before the prune runs.
|
||||
Assert.True(await store.SetStateAsync(answered.Id, CopyState.Candidate, CopyState.KeptApart, Answer(), Ct));
|
||||
|
||||
Assert.True(await store.DeleteCandidateAsync(stale.Id, Ct));
|
||||
Assert.False(await store.DeleteCandidateAsync(answered.Id, Ct));
|
||||
|
||||
Assert.Null(await store.GetAsync(stale.Id, Ct));
|
||||
Assert.Equal(CopyState.KeptApart, (await store.GetAsync(answered.Id, Ct))!.State);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnUpsertUpdatesScoresAndKeepsTheStateAndTheStrongerEvidence()
|
||||
{
|
||||
var (db, _, s) = await SetupAsync(1);
|
||||
var store = new FoundCopyStore(db);
|
||||
var remote = Guid.CreateVersion7();
|
||||
var found = await store.UpsertFoundAsync(Remote(s[0].Id, remote) with { Score = CopyScore.None with { Shared = 3 } }, Ct);
|
||||
Assert.Equal((CopyState.Candidate, CopyEvidence.Hashes, 3), (found.State, found.Evidence, found.Score.Shared));
|
||||
Assert.True(await store.SetStateAsync(found.Id, CopyState.Candidate, CopyState.KeptApart, Answer(fingerprint: "f1", shared: 3), Ct));
|
||||
|
||||
var again = await store.UpsertFoundAsync(Remote(s[0].Id, remote, evidence: CopyEvidence.SizeAndTime) with
|
||||
{
|
||||
Score = CopyScore.None with { Shared = 5 },
|
||||
Fingerprint = "f2",
|
||||
LocalFramesVersion = 7,
|
||||
}, Ct);
|
||||
Assert.Equal(found.Id, again.Id);
|
||||
Assert.Equal((CopyState.KeptApart, CopyEvidence.Hashes, 5, "f2", 7), (again.State, again.Evidence, again.Score.Shared, again.Fingerprint, again.LocalFramesVersion));
|
||||
Assert.Equal(("f1", (int?)3), (again.AnsweredFingerprint, again.AnsweredShared));
|
||||
Assert.Count(1, await store.ListAsync(Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ALocalPairIsStoredOnceInOrder()
|
||||
{
|
||||
var (db, _, s) = await SetupAsync(2);
|
||||
var store = new FoundCopyStore(db);
|
||||
var (low, high) = FoundCopyStore.Order(s[0].Id, s[1].Id);
|
||||
var stored = await store.UpsertFoundAsync(Local(high, low) with { LocalFramesVersion = 1, OtherFramesVersion = 2 }, Ct);
|
||||
Assert.Equal((low, (Guid?)high), (stored.LocalId, stored.OtherId));
|
||||
// The sides swap with the ids.
|
||||
Assert.Equal((2, 1), (stored.LocalFramesVersion, stored.OtherFramesVersion));
|
||||
var same = await store.UpsertFoundAsync(Local(low, high), Ct);
|
||||
Assert.Equal(stored.Id, same.Id);
|
||||
Assert.Equal(stored.Id, (await store.FindLocalAsync(high, low, Ct))!.Id);
|
||||
Assert.Count(1, await store.ListByLocalAsync(high, Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SetStateIsACompareAndSetAndIntegratingKeepsWhereItCameFrom()
|
||||
{
|
||||
var (db, _, s) = await SetupAsync(1);
|
||||
var store = new FoundCopyStore(db);
|
||||
var row = await store.UpsertFoundAsync(Remote(s[0].Id, Guid.CreateVersion7()), Ct);
|
||||
Assert.False(await store.SetStateAsync(row.Id, CopyState.Linked, CopyState.KeptApart, null, Ct));
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => store.SetStateAsync(row.Id, null, CopyState.Integrating, Answer(), Ct));
|
||||
Assert.False(await store.SetStateAsync(Guid.NewGuid(), null, CopyState.KeptApart, null, Ct));
|
||||
|
||||
var job = await JobAsync(db);
|
||||
Assert.True(await store.SetStateAsync(row.Id, CopyState.Candidate, CopyState.Integrating, Answer(job.Id), Ct));
|
||||
var integrating = (await store.GetAsync(row.Id, Ct))!;
|
||||
Assert.Equal((CopyState.Integrating, (CopyState?)CopyState.Candidate, (Guid?)job.Id), (integrating.State, integrating.PreviousState, integrating.JobId));
|
||||
|
||||
Assert.True(await store.SetStateAsync(row.Id, CopyState.Integrating, CopyState.Integrated, Answer(auto: true), Ct));
|
||||
var done = (await store.GetAsync(row.Id, Ct))!;
|
||||
Assert.Equal((CopyState.Integrated, (CopyState?)null, (Guid?)null, true), (done.State, done.PreviousState, done.JobId, done.AutoPhotos));
|
||||
// Auto photos hold only while Integrated.
|
||||
Assert.True(await store.SetStateAsync(row.Id, null, CopyState.Linked, null, Ct));
|
||||
Assert.False((await store.GetAsync(row.Id, Ct))!.AutoPhotos);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnIntegratingRowWhoseJobFailedOrWasCancelledReadsAsItsPreviousState()
|
||||
{
|
||||
var (db, _, s) = await SetupAsync(2);
|
||||
var store = new FoundCopyStore(db);
|
||||
foreach (var (sequence, end) in new[] { (s[0], JobState.Failed), (s[1], JobState.Cancelled) })
|
||||
{
|
||||
var row = await store.UpsertFoundAsync(Remote(sequence.Id, Guid.CreateVersion7()), Ct);
|
||||
Assert.True(await store.SetStateAsync(row.Id, null, CopyState.KeptApart, Answer(fingerprint: "f1"), Ct));
|
||||
var job = await JobAsync(db);
|
||||
Assert.True(await store.SetStateAsync(row.Id, CopyState.KeptApart, CopyState.Integrating, Answer(job.Id), Ct));
|
||||
Assert.Equal(CopyState.Integrating, (await store.GetAsync(row.Id, Ct))!.State);
|
||||
|
||||
await db.Jobs.SetStateAsync(job.Id, end, null, Ct);
|
||||
var read = (await store.GetAsync(row.Id, Ct))!;
|
||||
Assert.Equal((CopyState.KeptApart, (Guid?)null, (CopyState?)null), (read.State, read.JobId, read.PreviousState));
|
||||
// The compare-and-set sees the state it reads as.
|
||||
Assert.False(await store.SetStateAsync(row.Id, CopyState.Integrating, CopyState.Integrated, null, Ct));
|
||||
Assert.True(await store.SetStateAsync(row.Id, CopyState.KeptApart, CopyState.Candidate, null, Ct));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task PairsGoWithTheirSequenceAndSurviveItsUpsert()
|
||||
{
|
||||
var (db, _, s) = await SetupAsync(3);
|
||||
var store = new FoundCopyStore(db);
|
||||
await store.UpsertFoundAsync(Remote(s[0].Id, Guid.CreateVersion7()), Ct);
|
||||
await store.UpsertFoundAsync(Local(s[0].Id, s[1].Id), Ct);
|
||||
await store.UpsertFoundAsync(Local(s[1].Id, s[2].Id), Ct);
|
||||
await store.SetProbeAsync(new CopyProbe(s[0].Id, Nas, 1, 1, TestData.Now), Ct);
|
||||
|
||||
// A Rebuild writes the sequence row again: its pairs stay.
|
||||
await db.Sequences.UpsertAsync(s[0] with { Title = "Harbour" }, Ct);
|
||||
Assert.Count(3, await store.ListAsync(Ct));
|
||||
|
||||
Assert.True(await db.Sequences.DeleteAsync(s[0].Id, Ct));
|
||||
var left = await store.ListAsync(Ct);
|
||||
Assert.Count(1, left);
|
||||
Assert.True(left[0].Names(s[1].Id) && left[0].Names(s[2].Id));
|
||||
Assert.Null(await store.GetProbeAsync(s[0].Id, Nas, Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task EnsureLinkedPromotesACandidateAndDemotesTheRowsTheLinkNoLongerBacks()
|
||||
{
|
||||
var (db, _, s) = await SetupAsync(2);
|
||||
var store = new FoundCopyStore(db);
|
||||
var (r1, r2) = (Guid.CreateVersion7(), Guid.CreateVersion7());
|
||||
var candidate = await store.UpsertFoundAsync(Remote(s[0].Id, r1), Ct);
|
||||
var linked = await store.EnsureLinkedAsync(Nas, r1, s[0].Id, Ct);
|
||||
Assert.Equal(candidate.Id, linked.Id);
|
||||
Assert.Equal((CopyState.Linked, CopyEvidence.Hashes), (linked.State, linked.Evidence));
|
||||
var other = await store.EnsureLinkedAsync(Other, r1, s[0].Id, Ct);
|
||||
Assert.Equal((CopyState.Linked, CopyEvidence.Link, "link"), (other.State, other.Evidence, other.Fingerprint));
|
||||
|
||||
// The link is pointed at another local copy: the old pair is a candidate again; the other server's stays.
|
||||
var moved = await store.EnsureLinkedAsync(Nas, r1, s[1].Id, Ct);
|
||||
Assert.Equal(CopyState.Linked, moved.State);
|
||||
Assert.Equal(CopyState.Candidate, (await store.GetAsync(linked.Id, Ct))!.State);
|
||||
Assert.Equal(CopyState.Linked, (await store.GetAsync(other.Id, Ct))!.State);
|
||||
|
||||
// The local copy is linked to another server sequence: the same.
|
||||
await store.EnsureLinkedAsync(Nas, r2, s[1].Id, Ct);
|
||||
Assert.Equal(CopyState.Candidate, (await store.GetAsync(moved.Id, Ct))!.State);
|
||||
Assert.Count(4, await store.ListAsync(Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task UploadAgainDeletesTheGoneRowLinkedOrKeptHere()
|
||||
{
|
||||
var (db, _, s) = await SetupAsync(2);
|
||||
var store = new FoundCopyStore(db);
|
||||
foreach (var (sequence, keptHere) in new[] { (s[0], false), (s[1], true) })
|
||||
{
|
||||
var (gone, fresh) = (Guid.CreateVersion7(), Guid.CreateVersion7());
|
||||
var linked = await store.EnsureLinkedAsync(Nas, gone, sequence.Id, Ct);
|
||||
// A refresh's 404 forgets the link (hit 1); the recheck counts the second.
|
||||
await store.MarkRemoteGoneAsync(Nas, gone, sequence.Id, Guid.NewGuid(), TestData.Now, Ct);
|
||||
await store.MarkRemoteGoneAsync(Nas, gone, sequence.Id, Guid.NewGuid(), TestData.Now.AddHours(1), Ct);
|
||||
if (keptHere) Assert.True(await store.SetStateAsync(linked.Id, null, CopyState.KeptApart, Answer(), Ct));
|
||||
Assert.True((await store.GetAsync(linked.Id, Ct))!.RemoteGone);
|
||||
|
||||
// Upload again: the first original creates a new server sequence and the link points at it.
|
||||
var uploaded = await store.EnsureLinkedAsync(Nas, fresh, sequence.Id, Ct);
|
||||
|
||||
Assert.Null(await store.GetAsync(linked.Id, Ct));
|
||||
var left = await store.ListByLocalAsync(sequence.Id, Ct);
|
||||
Assert.Equal((uploaded.Id, CopyState.Linked, (Guid?)fresh, 0), (left.Single().Id, left.Single().State, left.Single().RemoteId, left.Single().RemoteGoneHits));
|
||||
// Upload all local no longer reads it as deleted on the server.
|
||||
var entry = new SyncEntry(sequence, null, SyncStatus.LocalOnly);
|
||||
var (upload, skipped) = UploadAllRule.Select([entry], left, new HashSet<Guid>(), new HashSet<Guid>());
|
||||
Assert.Empty(skipped);
|
||||
Assert.Count(1, upload);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task A404CountsOncePerRefreshAndDeletesTheCandidatesOfThatRemote()
|
||||
{
|
||||
var (db, _, s) = await SetupAsync(2);
|
||||
var store = new FoundCopyStore(db);
|
||||
var remote = Guid.CreateVersion7();
|
||||
// An observation-only link has no pair: nothing happens.
|
||||
await store.MarkRemoteGoneAsync(Nas, remote, null, Guid.NewGuid(), TestData.Now, Ct);
|
||||
Assert.Empty(await store.ListAsync(Ct));
|
||||
|
||||
var candidate = await store.UpsertFoundAsync(Remote(s[1].Id, remote), Ct);
|
||||
var (first, second) = (Guid.NewGuid(), Guid.NewGuid());
|
||||
await store.MarkRemoteGoneAsync(Nas, remote, s[0].Id, first, TestData.Now, Ct);
|
||||
await store.MarkRemoteGoneAsync(Nas, remote, s[0].Id, first, TestData.Now.AddMinutes(1), Ct);
|
||||
var row = (await store.FindRemoteAsync(s[0].Id, Nas, remote, Ct))!;
|
||||
Assert.Equal((1, (DateTimeOffset?)TestData.Now, CopyEvidence.Link, false), (row.RemoteGoneHits, row.RemoteGoneAt, row.Evidence, row.RemoteGone));
|
||||
Assert.Null(await store.GetAsync(candidate.Id, Ct));
|
||||
|
||||
await store.MarkRemoteGoneAsync(Nas, remote, s[0].Id, second, TestData.Now.AddHours(1), Ct);
|
||||
row = (await store.GetAsync(row.Id, Ct))!;
|
||||
Assert.Equal((2, (DateTimeOffset?)TestData.Now, true), (row.RemoteGoneHits, row.RemoteGoneAt, row.RemoteGone));
|
||||
|
||||
await store.ClearRemoteGoneAsync(Nas, remote, Ct);
|
||||
row = (await store.GetAsync(row.Id, Ct))!;
|
||||
Assert.Equal((0, (DateTimeOffset?)null), (row.RemoteGoneHits, row.RemoteGoneAt));
|
||||
// After a clear the same refresh counts again.
|
||||
await store.MarkRemoteGoneAsync(Nas, remote, s[0].Id, second, TestData.Now, Ct);
|
||||
Assert.Equal(1, (await store.GetAsync(row.Id, Ct))!.RemoteGoneHits);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task A404OfAServerSequenceNoLocalCopyIsLinkedToDeletesItsCandidatesAndCountsOnItsKeptApartAnswers()
|
||||
{
|
||||
var (db, _, s) = await SetupAsync(4);
|
||||
var store = new FoundCopyStore(db);
|
||||
var remote = Guid.CreateVersion7();
|
||||
var candidate = await store.UpsertFoundAsync(Remote(s[0].Id, remote), Ct);
|
||||
var apart = await store.UpsertFoundAsync(Remote(s[1].Id, remote), Ct);
|
||||
Assert.True(await store.SetStateAsync(apart.Id, CopyState.Candidate, CopyState.KeptApart, Answer(), Ct));
|
||||
var linked = await store.UpsertFoundAsync(Remote(s[2].Id, remote), Ct);
|
||||
Assert.True(await store.SetStateAsync(linked.Id, CopyState.Candidate, CopyState.Linked, Answer(), Ct));
|
||||
var elsewhere = await store.UpsertFoundAsync(Remote(s[3].Id, Guid.CreateVersion7()), Ct);
|
||||
|
||||
// After the answers, an observation-only link answers 404: no local copy is linked to it.
|
||||
var first = Guid.NewGuid();
|
||||
await store.MarkRemoteGoneAsync(Nas, remote, null, first, TestData.Now.AddMinutes(1), Ct);
|
||||
await store.MarkRemoteGoneAsync(Nas, remote, null, first, TestData.Now.AddMinutes(2), Ct);
|
||||
|
||||
// The unanswered match is gone; the Keep apart answer stays and counts the 404 once, not read as deleted yet.
|
||||
Assert.Null(await store.GetAsync(candidate.Id, Ct));
|
||||
var row = (await store.GetAsync(apart.Id, Ct))!;
|
||||
Assert.Equal((CopyState.KeptApart, 1, false), (row.State, row.RemoteGoneHits, row.RemoteGone));
|
||||
Assert.Equal(CopyState.Linked, (await store.GetAsync(linked.Id, Ct))!.State);
|
||||
Assert.Equal(CopyState.Candidate, (await store.GetAsync(elsewhere.Id, Ct))!.State);
|
||||
var entries = s[..2].Select(q => new SyncEntry(q, null, SyncStatus.LocalOnly)).ToList();
|
||||
var (upload, skipped) = UploadAllRule.Select(entries, await store.ListAsync(Ct), new HashSet<Guid>(), new HashSet<Guid>());
|
||||
Assert.Equal(s[0].Id, upload.Single().Local!.Id);
|
||||
Assert.Equal((s[1].Id, UploadSkip.DeletedOnServer), (skipped.Single().Entry.Local!.Id, skipped.Single().Why));
|
||||
|
||||
// A second 404 within the re-check is the same moment; one after it confirms the deletion.
|
||||
await store.MarkRemoteGoneAsync(Nas, remote, null, Guid.NewGuid(), TestData.Now.AddMinutes(5), Ct);
|
||||
Assert.Equal(1, (await store.GetAsync(apart.Id, Ct))!.RemoteGoneHits);
|
||||
await store.MarkRemoteGoneAsync(Nas, remote, null, Guid.NewGuid(), TestData.Now.AddHours(1), Ct);
|
||||
row = (await store.GetAsync(apart.Id, Ct))!;
|
||||
Assert.Equal((CopyState.KeptApart, true), (row.State, row.RemoteGone));
|
||||
(upload, skipped) = UploadAllRule.Select(entries, await store.ListAsync(Ct), new HashSet<Guid>(), new HashSet<Guid>());
|
||||
Assert.Empty(skipped);
|
||||
Assert.Count(2, upload);
|
||||
|
||||
// Listed again: the count clears and the answer is the user's as before.
|
||||
await store.ClearRemoteGoneAsync(Nas, remote, Ct);
|
||||
row = (await store.GetAsync(apart.Id, Ct))!;
|
||||
Assert.Equal((CopyState.KeptApart, 0), (row.State, row.RemoteGoneHits));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task MoveToKeptMovesKeysLinksAndPairsAndIsIdempotent()
|
||||
{
|
||||
var (db, archive, s) = await SetupAsync(4);
|
||||
var (keep, drop, third, fourth) = (s[0], s[1], s[2], s[3]);
|
||||
var store = new FoundCopyStore(db);
|
||||
var links = new SyncLinkStore(db);
|
||||
var (r1, r2, r3) = (Guid.CreateVersion7(), Guid.CreateVersion7(), Guid.CreateVersion7());
|
||||
await db.Sequences.MapSessionKeyAsync(archive.Id, "upload-a", drop.Id, Ct);
|
||||
await db.Sequences.MapSessionKeyAsync(archive.Id, "upload-c", third.Id, Ct);
|
||||
await links.UpsertAsync(Link(Nas, r1, drop.Id), Ct);
|
||||
var dropLink = await store.EnsureLinkedAsync(Nas, r1, drop.Id, Ct);
|
||||
Assert.True(await store.SetStateAsync(dropLink.Id, CopyState.Linked, CopyState.Integrated, Answer(auto: true), Ct));
|
||||
// keep already pairs with r2: drop's pair of r2 is the clash, deleted.
|
||||
await store.UpsertFoundAsync(Remote(keep.Id, r2), Ct);
|
||||
var clash = await store.UpsertFoundAsync(Remote(drop.Id, r2), Ct);
|
||||
var self = await store.UpsertFoundAsync(Local(keep.Id, drop.Id), Ct);
|
||||
var withThird = await store.UpsertFoundAsync(Local(drop.Id, third.Id), Ct);
|
||||
await store.UpsertFoundAsync(Local(keep.Id, fourth.Id), Ct);
|
||||
var withFourth = await store.UpsertFoundAsync(Local(drop.Id, fourth.Id), Ct);
|
||||
var own = await store.UpsertFoundAsync(Remote(drop.Id, r3, Other), Ct);
|
||||
|
||||
var result = await store.MoveToKeptAsync(drop.Id, keep.Id, archive.Id, ["upload-a", "upload-b", "upload-c"], own.Id, Ct);
|
||||
|
||||
Assert.Equal((2, 1, 2), (result.SessionKeys, result.Links, result.Pairs));
|
||||
Assert.SequenceEqual(["upload-c"], result.SkippedKeys);
|
||||
Assert.Equal(keep.Id, await db.Sequences.FindBySessionKeyAsync(archive.Id, "upload-a", Ct));
|
||||
Assert.Equal(keep.Id, await db.Sequences.FindBySessionKeyAsync(archive.Id, "upload-b", Ct));
|
||||
Assert.Equal(third.Id, await db.Sequences.FindBySessionKeyAsync(archive.Id, "upload-c", Ct));
|
||||
var link = (await links.GetAsync(Nas, r1, Ct))!;
|
||||
Assert.Equal((keep.Id, (int?)null, (int?)null, 0), (link.LocalId!.Value, link.DiffLocalFrames, link.BaseLocalSettings, link.MissingRemote));
|
||||
|
||||
var moved = (await store.GetAsync(dropLink.Id, Ct))!;
|
||||
Assert.Equal((keep.Id, CopyState.Linked, false, -1), (moved.LocalId, moved.State, moved.AutoPhotos, moved.LocalFramesVersion));
|
||||
Assert.Null(await store.GetAsync(clash.Id, Ct));
|
||||
Assert.Null(await store.GetAsync(self.Id, Ct));
|
||||
Assert.Null(await store.GetAsync(withFourth.Id, Ct));
|
||||
var third2 = (await store.GetAsync(withThird.Id, Ct))!;
|
||||
Assert.True(third2.Names(keep.Id) && third2.Names(third.Id));
|
||||
Assert.Equal((-1, -1), (third2.LocalFramesVersion, third2.OtherFramesVersion));
|
||||
Assert.Equal(drop.Id, (await store.GetAsync(own.Id, Ct))!.LocalId);
|
||||
|
||||
var again = await store.MoveToKeptAsync(drop.Id, keep.Id, archive.Id, ["upload-a", "upload-b", "upload-c"], own.Id, Ct);
|
||||
Assert.Equal((0, 0), (again.Links, again.Pairs));
|
||||
Assert.SequenceEqual(["upload-c"], again.SkippedKeys);
|
||||
Assert.Equal(keep.Id, await db.Sequences.FindBySessionKeyAsync(archive.Id, "upload-a", Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task MoveToKeptIsRefusedBeforeAnyChangeWhenBothAreLinkedOnOneServer()
|
||||
{
|
||||
var (db, archive, s) = await SetupAsync(2);
|
||||
var (keep, drop) = (s[0], s[1]);
|
||||
var store = new FoundCopyStore(db);
|
||||
var links = new SyncLinkStore(db);
|
||||
await db.Sequences.MapSessionKeyAsync(archive.Id, "upload-a", drop.Id, Ct);
|
||||
await links.UpsertAsync(Link(Nas, Guid.CreateVersion7(), keep.Id), Ct);
|
||||
var dropRemote = Guid.CreateVersion7();
|
||||
await links.UpsertAsync(Link(Nas, dropRemote, drop.Id), Ct);
|
||||
var pair = await store.UpsertFoundAsync(Local(keep.Id, drop.Id), Ct);
|
||||
|
||||
await Assert.ThrowsAsync<CopyLinkTakenException>(() => store.MoveToKeptAsync(drop.Id, keep.Id, archive.Id, ["upload-a"], null, Ct));
|
||||
Assert.Equal(drop.Id, await db.Sequences.FindBySessionKeyAsync(archive.Id, "upload-a", Ct));
|
||||
Assert.Equal(drop.Id, (await links.GetAsync(Nas, dropRemote, Ct))!.LocalId);
|
||||
Assert.NotNull(await store.GetAsync(pair.Id, Ct));
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => store.MoveToKeptAsync(keep.Id, keep.Id, archive.Id, [], null, Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task LocalOverlapsCountHashesTombstonesAndSizeAndTime()
|
||||
{
|
||||
var (db, _, s) = await SetupAsync(4);
|
||||
var store = new FoundCopyStore(db);
|
||||
// s0 and s1 share frames 1 and 2 by hash (TestData.Frame's hash is its index's).
|
||||
foreach (var i in new[] { 1, 2, 3 }) await db.Frames.InsertAsync(TestData.Frame(s[0].Id, i), Ct);
|
||||
foreach (var i in new[] { 1, 2, 4 }) await db.Frames.InsertAsync(TestData.Frame(s[1].Id, i), Ct);
|
||||
// s2 tombstoned frame 3 of s0.
|
||||
await db.FrameRemovals.SyncSequenceAsync(s[2].Id, [new FrameRemoval(s[2].Id, TestData.Frame(s[0].Id, 3).Sha256!, null, RemovalReason.Deleted, TestData.Now)], Ct);
|
||||
Assert.Empty((await store.LocalOverlapsAsync(Ct)).Where(o => o.SharedUnhashed > 0));
|
||||
|
||||
// s3 holds an unhashed frame of s1's size and capture time.
|
||||
var unhashed = TestData.Frame(s[3].Id, 4) with { Sha256 = null };
|
||||
await db.Frames.InsertAsync(unhashed, Ct);
|
||||
var overlaps = (await store.LocalOverlapsAsync(Ct)).ToDictionary(o => (o.Low, o.High));
|
||||
Assert.Equal(3, overlaps.Count);
|
||||
Assert.Equal((2, 0, 0), Counts(overlaps[FoundCopyStore.Order(s[0].Id, s[1].Id)]));
|
||||
Assert.Equal((0, 1, 0), Counts(overlaps[FoundCopyStore.Order(s[0].Id, s[2].Id)]));
|
||||
Assert.Equal((0, 0, 1), Counts(overlaps[FoundCopyStore.Order(s[1].Id, s[3].Id)]));
|
||||
foreach (var o in overlaps.Values) Assert.True(string.CompareOrdinal(o.Low.ToString("D"), o.High.ToString("D")) < 0);
|
||||
|
||||
static (int, int, int) Counts(LocalOverlap o) => (o.SharedHashes, o.SharedRemoved, o.SharedUnhashed);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ProbesAndSyncSessionKeysRoundTrip()
|
||||
{
|
||||
var (db, archive, s) = await SetupAsync(2);
|
||||
var store = new FoundCopyStore(db);
|
||||
await store.SetProbeAsync(new CopyProbe(s[0].Id, Nas, 1, 1, TestData.Now), Ct);
|
||||
await store.SetProbeAsync(new CopyProbe(s[0].Id, Nas, 2, 5, TestData.Now.AddMinutes(1)), Ct);
|
||||
await store.SetProbeAsync(new CopyProbe(s[0].Id, string.Empty, 9, 9, TestData.Now), Ct);
|
||||
Assert.Equal(new CopyProbe(s[0].Id, Nas, 2, 5, TestData.Now.AddMinutes(1)), await store.GetProbeAsync(s[0].Id, Nas, Ct));
|
||||
await store.ResetProbesAsync(Nas, Ct);
|
||||
Assert.Null(await store.GetProbeAsync(s[0].Id, Nas, Ct));
|
||||
Assert.NotNull(await store.GetProbeAsync(s[0].Id, string.Empty, Ct));
|
||||
|
||||
var remote = Guid.CreateVersion7();
|
||||
await db.Sequences.MapSessionKeyAsync(archive.Id, $"chronos-sync:{remote:N}", s[1].Id, Ct);
|
||||
await db.Sequences.MapSessionKeyAsync(archive.Id, "chronos-sync:not-a-guid", s[1].Id, Ct);
|
||||
await db.Sequences.MapSessionKeyAsync(archive.Id, "upload-1", s[0].Id, Ct);
|
||||
Assert.SequenceEqual([(s[1].Id, remote)], await store.SyncSessionKeysAsync(Ct));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SqliteFoundCopyStoreTests(TestContext context) : FoundCopyStoreTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.SqliteMemory;
|
||||
}
|
||||
|
||||
[RequiresEnvironment(PgTestServer.Variable)]
|
||||
public sealed class PostgresFoundCopyStoreTests(TestContext context) : FoundCopyStoreTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.Postgres;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,91 @@
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Copies;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Data.Tests.Infrastructure;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Copies;
|
||||
|
||||
/// <summary>Upload all local (owner review 6, Q8): suspected, kept-apart, deleted, busy and server-born sequences stay here.</summary>
|
||||
[Category("sync")]
|
||||
public sealed class UploadAllRuleTests
|
||||
{
|
||||
private const string Nas = "https://nas.test:8443";
|
||||
|
||||
private static readonly Guid Archive = Guid.CreateVersion7();
|
||||
|
||||
private static SyncEntry Entry(Guid? archiveId = null) =>
|
||||
new(TestData.Sequence(archiveId ?? Archive) with { FrameCount = 3 }, null, SyncStatus.LocalOnly);
|
||||
|
||||
private static FoundCopy Remote(Guid localId, CopyState state, int goneHits = 0) => new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Kind = CopyKind.LocalServer,
|
||||
LocalId = localId,
|
||||
Server = Nas,
|
||||
RemoteId = Guid.CreateVersion7(),
|
||||
Evidence = CopyEvidence.Hashes,
|
||||
State = state,
|
||||
Fingerprint = "f",
|
||||
RemoteGoneHits = goneHits,
|
||||
};
|
||||
|
||||
private static FoundCopy Local(Guid a, Guid b, CopyState state) => new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Kind = CopyKind.LocalLocal,
|
||||
LocalId = a,
|
||||
OtherId = b,
|
||||
Evidence = CopyEvidence.Hashes,
|
||||
State = state,
|
||||
Fingerprint = "f",
|
||||
};
|
||||
|
||||
[Test]
|
||||
public void APlainLocalSequenceUploads()
|
||||
{
|
||||
var plain = Entry();
|
||||
var linked = Entry();
|
||||
var (upload, skipped) = UploadAllRule.Select([plain, linked], [Remote(linked.Local!.Id, CopyState.Linked)], new HashSet<Guid>(), new HashSet<Guid>());
|
||||
Assert.SequenceEqual([plain.Local!.Id, linked.Local!.Id], upload.Select(e => e.Local!.Id));
|
||||
Assert.Empty(skipped);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EachReasonKeepsTheSequenceHereWithItsReason()
|
||||
{
|
||||
var (suspected, keptApart, other, gone, busy, integrating, born) = (Entry(), Entry(), Entry(), Entry(), Entry(), Entry(), Entry(Guid.CreateVersion7()));
|
||||
FoundCopy[] copies =
|
||||
[
|
||||
Remote(suspected.Local!.Id, CopyState.Candidate),
|
||||
// A local pair names its second sequence too.
|
||||
Local(other.Local!.Id, keptApart.Local!.Id, CopyState.KeptApart),
|
||||
// One 404 is enough to stay here: it is not uploaded as a new server sequence.
|
||||
Remote(gone.Local!.Id, CopyState.Linked, goneHits: 1),
|
||||
Remote(integrating.Local!.Id, CopyState.Integrating),
|
||||
];
|
||||
var (upload, skipped) = UploadAllRule.Select([suspected, keptApart, other, gone, busy, integrating, born], copies,
|
||||
new HashSet<Guid> { born.Local!.ArchiveId }, new HashSet<Guid> { busy.Local!.Id });
|
||||
|
||||
Assert.Empty(upload);
|
||||
var why = skipped.ToDictionary(s => s.Entry.Local!.Id, s => s.Why);
|
||||
Assert.Equal(UploadSkip.SuspectedCopy, why[suspected.Local.Id]);
|
||||
Assert.Equal(UploadSkip.KeptApart, why[keptApart.Local.Id]);
|
||||
Assert.Equal(UploadSkip.KeptApart, why[other.Local.Id]);
|
||||
Assert.Equal(UploadSkip.DeletedOnServer, why[gone.Local.Id]);
|
||||
Assert.Equal(UploadSkip.Busy, why[busy.Local.Id]);
|
||||
Assert.Equal(UploadSkip.Busy, why[integrating.Local.Id]);
|
||||
Assert.Equal(UploadSkip.ServerOriginals, why[born.Local.Id]);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void BusyComesFirstAndAnEntryWithoutALocalSequenceIsNeither()
|
||||
{
|
||||
var entry = Entry();
|
||||
var serverOnly = new SyncEntry(null, new SyncLink { Server = Nas, RemoteId = Guid.CreateVersion7(), Title = "Harbour" }, SyncStatus.RemoteOnly);
|
||||
var (upload, skipped) = UploadAllRule.Select([entry, serverOnly], [Remote(entry.Local!.Id, CopyState.Candidate, goneHits: 2)],
|
||||
new HashSet<Guid> { Archive }, new HashSet<Guid> { entry.Local.Id });
|
||||
Assert.Empty(upload);
|
||||
Assert.Equal((entry.Local.Id, UploadSkip.Busy), (skipped.Single().Entry.Local!.Id, skipped.Single().Why));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user