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
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,126 @@
|
||||
using Chronos.Core.Import;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Tests.Infrastructure;
|
||||
using Chronos.Testing;
|
||||
using static Chronos.Data.Tests.Archiving.ArchiveFixture;
|
||||
|
||||
namespace Chronos.Data.Tests.Archiving;
|
||||
|
||||
/// <summary>
|
||||
/// Trash steps run inside the job that holds the sequence (an Integrate or a merge, owner review 6, #73): the job's own hold
|
||||
/// does not make the sequence busy, another job's still does, and a frames version that moved refuses the step.
|
||||
/// </summary>
|
||||
[Category("archive")]
|
||||
public abstract class TrashExceptJobTests(TestContext context) : DatabaseTest(context)
|
||||
{
|
||||
private async Task<ArchiveFixture> FixtureAsync() => Own(await CreateAsync(Context, database: await NewOptionsAsync(multiConnection: true)));
|
||||
|
||||
private static async Task<Sequence> UploadedAsync(ArchiveFixture fx, int count, string session, int seed)
|
||||
{
|
||||
Guid? id = null;
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var (path, size, sha) = fx.Stage(Start.AddSeconds(10 * i), seed + i);
|
||||
var result = await fx.Service.Ingest.CommitAsync(new IngestRequest(fx.Archive.Id, id, null, id is null ? session : null, path, $"IMG_{i + 1:0000}.JPG",
|
||||
size, sha, null, null), fx.Ct);
|
||||
id = result.SequenceId;
|
||||
}
|
||||
return (await fx.Db.Sequences.GetAsync(id!.Value))!;
|
||||
}
|
||||
|
||||
private static async Task<Job> RunningAsync(ArchiveFixture fx, JobKind kind, params Guid[] targets)
|
||||
{
|
||||
var job = new Job
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Kind = kind,
|
||||
TargetIds = targets,
|
||||
State = JobState.Running,
|
||||
NodeId = "test#0",
|
||||
Created = DateTimeOffset.UtcNow,
|
||||
Started = DateTimeOffset.UtcNow,
|
||||
};
|
||||
await fx.Db.Jobs.EnqueueAsync(job);
|
||||
return job;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task APhotoTrashStepInsideItsOwnJobIsNotBusyAnotherJobsTargetIs()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var sequence = await UploadedAsync(fx, 3, "upload-1", 100);
|
||||
var frames = await fx.Db.Frames.ListBySequenceAsync(sequence.Id);
|
||||
var trash = fx.Service.FrameTrash;
|
||||
var integrate = await RunningAsync(fx, JobKind.Integrate, sequence.Id);
|
||||
|
||||
Assert.SequenceEqual([FrameDeleteBlock.Busy], (await trash.PlanDeleteAsync(sequence.Id, [frames[0].Id], sequence.FramesVersion, fx.Ct)).Blocked);
|
||||
var plan = await trash.PlanDeleteAsync(sequence.Id, [frames[0].Id], sequence.FramesVersion, fx.Ct, exceptJob: integrate.Id);
|
||||
Assert.True(plan.CanDelete, string.Join(", ", plan.Blocked));
|
||||
// The re-plan of the deletion itself must not count the job either.
|
||||
await Assert.ThrowsAsync<StaleDeletePlanException>(() => trash.DeleteAsync(plan, "alberto", null, fx.Ct));
|
||||
var result = await trash.DeleteAsync(plan, "alberto", null, fx.Ct, exceptJob: integrate.Id);
|
||||
Assert.Equal(sequence.Id, result.Sequence.Id);
|
||||
Assert.Count(2, await fx.Db.Frames.ListBySequenceAsync(sequence.Id));
|
||||
|
||||
await RunningAsync(fx, JobKind.Render, sequence.Id);
|
||||
var now = (await fx.Db.Sequences.GetAsync(sequence.Id))!;
|
||||
var held = await trash.PlanDeleteAsync(sequence.Id, [frames[1].Id], now.FramesVersion, fx.Ct, exceptJob: integrate.Id);
|
||||
Assert.SequenceEqual([FrameDeleteBlock.Busy], held.Blocked);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ASequenceTrashStepInsideItsOwnJobIsNotBusyAnotherJobsTargetIs()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var keep = await UploadedAsync(fx, 2, "upload-1", 100);
|
||||
var drop = await UploadedAsync(fx, 2, "upload-2", 200);
|
||||
var merge = await RunningAsync(fx, JobKind.MergeSequences, keep.Id, drop.Id);
|
||||
|
||||
Assert.Equal(DeleteBlock.Busy, (await fx.Service.Trash.PlanAsync([drop.Id], null, fx.Ct)).Blocked.Single().Reason);
|
||||
var plan = await fx.Service.Trash.PlanAsync([drop.Id], null, fx.Ct, exceptJob: merge.Id);
|
||||
Assert.Empty(plan.Blocked);
|
||||
// Revalidated without the job's own hold too.
|
||||
await Assert.ThrowsAsync<StaleDeletePlanException>(() => fx.Service.Trash.DeleteAsync(plan, null, null, fx.Ct));
|
||||
Assert.NotNull(await fx.Db.Sequences.GetAsync(drop.Id));
|
||||
var entries = await fx.Service.Trash.DeleteAsync(plan, "alberto", null, fx.Ct, exceptJob: merge.Id,
|
||||
expectedFramesVersions: new Dictionary<Guid, int> { [drop.Id] = drop.FramesVersion });
|
||||
Assert.Count(1, entries);
|
||||
Assert.Null(await fx.Db.Sequences.GetAsync(drop.Id));
|
||||
|
||||
await RunningAsync(fx, JobKind.Render, keep.Id);
|
||||
Assert.Equal(DeleteBlock.Busy, (await fx.Service.Trash.PlanAsync([keep.Id], null, fx.Ct, exceptJob: merge.Id)).Blocked.Single().Reason);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AFramesVersionThatMovedRefusesTheStepUnderItsLeaseAndNothingMoves()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var drop = await UploadedAsync(fx, 2, "upload-1", 100);
|
||||
var plan = await fx.Service.Trash.PlanAsync([drop.Id], null, fx.Ct);
|
||||
var folder = fx.Paths.Sequence(drop.Folder).Folder;
|
||||
|
||||
// A photo added since the version the caller verified.
|
||||
await Assert.ThrowsAsync<StaleDeletePlanException>(() => fx.Service.Trash.DeleteAsync(plan, null, null, fx.Ct,
|
||||
expectedFramesVersions: new Dictionary<Guid, int> { [drop.Id] = drop.FramesVersion - 1 }));
|
||||
Assert.NotNull(await fx.Db.Sequences.GetAsync(drop.Id));
|
||||
Assert.True(Directory.Exists(folder));
|
||||
|
||||
// A sequence the map does not name is not checked; the one it names at its version goes.
|
||||
var entries = await fx.Service.Trash.DeleteAsync(plan, null, null, fx.Ct,
|
||||
expectedFramesVersions: new Dictionary<Guid, int> { [Guid.CreateVersion7()] = 99, [drop.Id] = drop.FramesVersion });
|
||||
Assert.Count(1, entries);
|
||||
Assert.False(Directory.Exists(folder));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SqliteTrashExceptJobTests(TestContext context) : TrashExceptJobTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.SqliteFile;
|
||||
}
|
||||
|
||||
[RequiresEnvironment(PgTestServer.Variable)]
|
||||
public sealed class PostgresTrashExceptJobTests(TestContext context) : TrashExceptJobTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.Postgres;
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Copies;
|
||||
using Chronos.Data.Homes;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Data.Sync;
|
||||
@@ -202,6 +203,105 @@ public abstract class HomeRekeyLinkTests(TestContext context) : RepositoryTest(c
|
||||
Assert.Count(1, await store.ListAsync(HomeFixtures.Other, Ct));
|
||||
Assert.Empty(await store.ListAsync(HomeFixtures.Nas, Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheMatchesAndProbesOfAnAliasMoveWithItsLinks()
|
||||
{
|
||||
var db = await OpenChronosAsync();
|
||||
var (linked, found) = await TwoSequencesAsync(db);
|
||||
var store = new SyncLinkStore(db);
|
||||
var copies = new FoundCopyStore(db);
|
||||
var (r1, r2) = (Guid.CreateVersion7(), Guid.CreateVersion7());
|
||||
await store.UpsertAsync(Link(HomeFixtures.Nas, r1, linked, TestData.Now), Ct);
|
||||
await copies.EnsureLinkedAsync(HomeFixtures.Nas, r1, linked, Ct);
|
||||
await copies.UpsertFoundAsync(Candidate(HomeFixtures.Nas, r2, found), Ct);
|
||||
await copies.SetProbeAsync(new CopyProbe(found, HomeFixtures.Nas, 3, 3, TestData.Now), Ct);
|
||||
|
||||
var migration = new HomeLayoutMigration(new HomeLayoutOptions { DataDirectory = Context.CreateTempDirectory("data"), Database = db });
|
||||
var result = await migration.RekeyAsync(Id, [HomeFixtures.Nas, HomeFixtures.NasByIp], Ct);
|
||||
|
||||
Assert.Equal((1, 0), (result.LinksMoved, result.LinksDropped));
|
||||
var key = ServerIdentity.IdKey(Id);
|
||||
Assert.Empty(await copies.ListByServerAsync(HomeFixtures.Nas, Ct));
|
||||
var moved = await copies.ListByServerAsync(key, Ct);
|
||||
Assert.Count(2, moved);
|
||||
Assert.Equal(CopyState.Linked, moved.Single(c => c.RemoteId == r1).State);
|
||||
Assert.Equal(CopyState.Candidate, moved.Single(c => c.RemoteId == r2).State);
|
||||
Assert.Null(await copies.GetProbeAsync(found, HomeFixtures.Nas, Ct));
|
||||
Assert.Equal(3, (await copies.GetProbeAsync(found, key, Ct))!.FramesVersion);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task OnAClashThePairOfTheSurvivingLinkWinsElseTheHigherState()
|
||||
{
|
||||
var db = await OpenChronosAsync();
|
||||
var (linked, found) = await TwoSequencesAsync(db);
|
||||
var key = ServerIdentity.IdKey(Id);
|
||||
var store = new SyncLinkStore(db);
|
||||
var copies = new FoundCopyStore(db);
|
||||
var (r1, r2) = (Guid.CreateVersion7(), Guid.CreateVersion7());
|
||||
// The same link under both keys: the one compared last (the alias's) survives, and so does its pair, though the pair
|
||||
// under the id is further on.
|
||||
await store.UpsertAsync(Link(HomeFixtures.Nas, r1, linked, TestData.Now), Ct);
|
||||
await store.UpsertAsync(Link(key, r1, linked, TestData.Now.AddHours(-1)), Ct);
|
||||
var aliasPair = await copies.EnsureLinkedAsync(HomeFixtures.Nas, r1, linked, Ct);
|
||||
var idPair = await copies.EnsureLinkedAsync(key, r1, linked, Ct);
|
||||
Assert.True(await copies.SetStateAsync(idPair.Id, CopyState.Linked, CopyState.Integrated, new CopyAnswer(null, null, null, true, TestData.Now), Ct));
|
||||
// A match without a link under both keys: the answered one wins over the newer candidate.
|
||||
var keptApart = await copies.UpsertFoundAsync(Candidate(HomeFixtures.Nas, r2, found), Ct);
|
||||
Assert.True(await copies.SetStateAsync(keptApart.Id, CopyState.Candidate, CopyState.KeptApart, new CopyAnswer("f", 4, null, null, TestData.Now), Ct));
|
||||
var candidate = await copies.UpsertFoundAsync(Candidate(key, r2, found), Ct);
|
||||
await copies.SetProbeAsync(new CopyProbe(found, HomeFixtures.Nas, 1, 1, TestData.Now), Ct);
|
||||
await copies.SetProbeAsync(new CopyProbe(found, key, 2, 2, TestData.Now), Ct);
|
||||
|
||||
var (moved, dropped) = await store.RekeyAsync(HomeFixtures.Nas, key, Ct);
|
||||
|
||||
Assert.Equal((1, 1), (moved, dropped));
|
||||
var rows = await copies.ListByServerAsync(key, Ct);
|
||||
Assert.Count(2, rows);
|
||||
var pair = rows.Single(c => c.RemoteId == r1);
|
||||
Assert.Equal(aliasPair.Id, pair.Id);
|
||||
Assert.Equal(CopyState.Linked, pair.State);
|
||||
var match = rows.Single(c => c.RemoteId == r2);
|
||||
Assert.Equal(keptApart.Id, match.Id);
|
||||
Assert.NotEqual(candidate.Id, match.Id);
|
||||
Assert.Equal(CopyState.KeptApart, match.State);
|
||||
Assert.Empty(await copies.ListByServerAsync(HomeFixtures.Nas, Ct));
|
||||
Assert.Equal(2, (await copies.GetProbeAsync(found, key, Ct))!.FramesVersion);
|
||||
Assert.Null(await copies.GetProbeAsync(found, HomeFixtures.Nas, Ct));
|
||||
}
|
||||
|
||||
private async Task<(Guid Linked, Guid Found)> TwoSequencesAsync(ChronosDatabase db)
|
||||
{
|
||||
var archive = TestData.Archive();
|
||||
await db.Archives.UpsertAsync(archive, Ct);
|
||||
var linked = TestData.Sequence(archive.Id);
|
||||
var found = TestData.Sequence(archive.Id);
|
||||
await db.Sequences.UpsertAsync(linked, Ct);
|
||||
await db.Sequences.UpsertAsync(found, Ct);
|
||||
return (linked.Id, found.Id);
|
||||
}
|
||||
|
||||
private static SyncLink Link(string server, Guid remoteId, Guid localId, DateTimeOffset synced) => new()
|
||||
{
|
||||
Server = server,
|
||||
RemoteId = remoteId,
|
||||
LocalId = localId,
|
||||
Title = "Harbour",
|
||||
RemoteUpdatedAt = TestData.Now,
|
||||
SyncedAt = synced,
|
||||
};
|
||||
|
||||
private static FoundCopy Candidate(string server, Guid remoteId, Guid localId) => new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Kind = CopyKind.LocalServer,
|
||||
LocalId = localId,
|
||||
Server = server,
|
||||
RemoteId = remoteId,
|
||||
Evidence = CopyEvidence.Hashes,
|
||||
Fingerprint = "f",
|
||||
};
|
||||
}
|
||||
|
||||
public sealed class SqliteHomeRekeyLinkTests(TestContext context) : HomeRekeyLinkTests(context)
|
||||
|
||||
@@ -462,6 +462,34 @@ public sealed class JobEngineTests(TestContext context)
|
||||
foreach (var id in new[] { analysing.Id, followUp.Id, drawing.Id, other.Id }) await WaitForStateAsync(db, id, JobState.Done, TimeSpan.FromSeconds(10));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ABackgroundJobNeverInterruptsEvenAtAHigherLevel()
|
||||
{
|
||||
// Owner review 6 (#73): an Integrate queued by itself at the end of a sync is High but Background; it waits for the
|
||||
// running job instead of pausing it.
|
||||
await using var db = await OpenAsync();
|
||||
var release = new SemaphoreSlim(0);
|
||||
var scan = new GatedHandler(JobKind.Scan, release);
|
||||
var download = new GatedHandler(JobKind.Download, release);
|
||||
var queue = new JobPriorityQueue { Enabled = true };
|
||||
Assert.True(queue.Interrupts(JobKind.Download, JobKind.Scan));
|
||||
await using var engine = new JobEngine(db, [scan, download],
|
||||
new JobEngineOptions { WorkerId = "pc", PollInterval = TimeSpan.FromMilliseconds(50), PriorityQueue = () => queue });
|
||||
await engine.StartAsync();
|
||||
var scanning = await engine.EnqueueAsync(JobKind.Scan, []);
|
||||
await UntilAsync(() => Volatile.Read(ref scan.Running) == 1, "the scan runs");
|
||||
var downloading = await engine.EnqueueAsync(JobKind.Download, [], priority: JobPriority.Background);
|
||||
await Task.Delay(400);
|
||||
Assert.Equal((1, 0), (Volatile.Read(ref scan.Running), Volatile.Read(ref download.Started)));
|
||||
Assert.Equal(JobState.Running, (await db.Jobs.GetAsync(scanning.Id))!.State);
|
||||
Assert.False(await engine.ReviewAsync(context.Cancellation));
|
||||
|
||||
release.Release(10);
|
||||
await WaitForStateAsync(db, scanning.Id, JobState.Done, TimeSpan.FromSeconds(10));
|
||||
await WaitForStateAsync(db, downloading.Id, JobState.Done, TimeSpan.FromSeconds(10));
|
||||
Assert.Equal(1, Volatile.Read(ref scan.Started));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task RequeueingAYieldedJobLeavesPausesAndOtherNodesAlone()
|
||||
{
|
||||
|
||||
@@ -15,6 +15,8 @@ public sealed class JobWireTests
|
||||
[Case(JobKind.WorkspaceSend, 22, "workspace-send")]
|
||||
[Case(JobKind.WorkspaceMove, 23, "workspace-move")]
|
||||
[Case(JobKind.VideoCopy, 24, "video-copy")]
|
||||
[Case(JobKind.Integrate, 25, "integrate")]
|
||||
[Case(JobKind.MergeSequences, 26, "merge-sequences")]
|
||||
public void TheWorkspaceJobsKeepTheirValueAndName(JobKind kind, int value, string name)
|
||||
{
|
||||
Assert.Equal(value, (int)kind);
|
||||
@@ -40,6 +42,9 @@ public sealed class JobWireTests
|
||||
[Case(JobStep.CopyOriginal, 13, "copy-original")]
|
||||
[Case(JobStep.FollowUps, 22, "follow-ups")]
|
||||
[Case(JobStep.Process, 23, "process")]
|
||||
[Case(JobStep.Details, 24, "details")]
|
||||
[Case(JobStep.Projects, 25, "projects")]
|
||||
[Case(JobStep.Trash, 26, "trash")]
|
||||
public void StepsKeepTheirValueAndName(JobStep step, int value, string name)
|
||||
{
|
||||
Assert.Equal(value, (int)step);
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
using Chronos.Data.Migrations;
|
||||
using Chronos.Data.Tests.Infrastructure;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Migrations;
|
||||
|
||||
/// <summary>Migration 0012 (owner review 6, #73): found copies beside the links, every existing link a linked pair.</summary>
|
||||
public abstract class FoundCopiesMigrationTests(TestContext context) : RepositoryTest(context)
|
||||
{
|
||||
[Test]
|
||||
public async Task EveryLinkWithALocalSequenceBecomesOneLinkedPair()
|
||||
{
|
||||
var chronos = await OpenChronosAsync();
|
||||
var database = chronos.Database;
|
||||
var all = MigrationRunner.Load(Dialect);
|
||||
Assert.Equal(12, all.Single(m => m.Name == "found_copies").Version);
|
||||
|
||||
var archive = TestData.Archive();
|
||||
await chronos.Archives.UpsertAsync(archive, Ct);
|
||||
var first = TestData.Sequence(archive.Id);
|
||||
var second = TestData.Sequence(archive.Id);
|
||||
await chronos.Sequences.UpsertAsync(first, Ct);
|
||||
await chronos.Sequences.UpsertAsync(second, Ct);
|
||||
var (r1, r2, r3) = (Guid.CreateVersion7(), Guid.CreateVersion7(), Guid.CreateVersion7());
|
||||
await using (var session = await database.OpenAsync(Ct))
|
||||
{
|
||||
// Back to an index of 1.1 (schema 11) holding these links, then migrated again.
|
||||
await session.ExecuteAsync("DROP TABLE copy_probes", [], Ct);
|
||||
await session.ExecuteAsync("DROP TABLE found_copies", [], Ct);
|
||||
await session.ExecuteAsync("DELETE FROM schema_migrations WHERE version = 12", [], Ct);
|
||||
await Link(session, "https://nas.test:8443", r1, first.Id);
|
||||
await Link(session, "id:server-b", r2, second.Id);
|
||||
// An observation-only link (a server sequence this PC does not hold) is no pair.
|
||||
await Link(session, "https://nas.test:8443", r3, null);
|
||||
}
|
||||
|
||||
Assert.Equal(all[^1].Version, await MigrationRunner.MigrateAsync(database, Ct));
|
||||
await using var after = await database.OpenAsync(Ct);
|
||||
var rows = await after.QueryListAsync(
|
||||
"SELECT id, kind, local_id, server, remote_id, other_id, evidence, state, fingerprint, auto_photos, remote_gone_hits, found_at FROM found_copies ORDER BY server",
|
||||
[], r => r, Ct);
|
||||
Assert.Equal(2, rows.Count);
|
||||
Assert.Equal(2, rows.Select(r => r.GetGuid(0)).Distinct().Count());
|
||||
foreach (var row in rows)
|
||||
{
|
||||
Assert.NotEqual(Guid.Empty, row.GetGuid(0));
|
||||
Assert.Equal(0, row.GetInt32(1));
|
||||
Assert.True(row.IsNull(5));
|
||||
Assert.Equal(0, row.GetInt32(6));
|
||||
Assert.Equal(2, row.GetInt32(7));
|
||||
Assert.Equal("link", row.GetString(8));
|
||||
Assert.False(row.GetBool(9));
|
||||
Assert.Equal(0, row.GetInt32(10));
|
||||
Assert.True(row.GetDateTimeOffset(11) > DateTimeOffset.UtcNow.AddMinutes(-5));
|
||||
}
|
||||
var pairs = rows.Select(r => (r.GetString(3), r.GetGuid(4), r.GetGuid(2))).ToHashSet();
|
||||
Assert.Contains(("https://nas.test:8443", r1, first.Id), pairs);
|
||||
Assert.Contains(("id:server-b", r2, second.Id), pairs);
|
||||
// The ids are random version 4 UUIDs, in the form the binding writes.
|
||||
foreach (var row in rows) Assert.Equal(4, row.GetGuid(0).Version);
|
||||
// No change to the links.
|
||||
Assert.Equal(3L, await after.ScalarAsync<long>("SELECT count(*) FROM sync_links", [], Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheCheckRefusesAServerPairWithoutServerAndALocalPairOfOneSequence()
|
||||
{
|
||||
var chronos = await OpenChronosAsync();
|
||||
var archive = TestData.Archive();
|
||||
await chronos.Archives.UpsertAsync(archive, Ct);
|
||||
var sequence = TestData.Sequence(archive.Id);
|
||||
await chronos.Sequences.UpsertAsync(sequence, Ct);
|
||||
await using var session = await chronos.Database.OpenAsync(Ct);
|
||||
const string insert = "INSERT INTO found_copies (id, kind, local_id, server, remote_id, other_id, evidence, fingerprint, found_at, updated_at) " +
|
||||
"VALUES ($1, $2, $3, $4, $5, $6, 2, 'f', $7, $7)";
|
||||
await Assert.ThrowsAsync<DatabaseException>(() => session.ExecuteAsync(insert,
|
||||
[Guid.NewGuid(), 0, sequence.Id, DbParam.Text(null), Guid.CreateVersion7(), (Guid?)null, TestData.Now], Ct));
|
||||
await Assert.ThrowsAsync<DatabaseException>(() => session.ExecuteAsync(insert,
|
||||
[Guid.NewGuid(), 1, sequence.Id, DbParam.Text(null), (Guid?)null, sequence.Id, TestData.Now], Ct));
|
||||
await Assert.ThrowsAsync<DatabaseException>(() => session.ExecuteAsync(insert,
|
||||
[Guid.NewGuid(), 1, sequence.Id, "https://nas.test:8443", (Guid?)null, Guid.CreateVersion7(), TestData.Now], Ct));
|
||||
// A pair names existing sequences: a found copy goes with its sequence.
|
||||
await Assert.ThrowsAsync<DatabaseException>(() => session.ExecuteAsync(insert,
|
||||
[Guid.NewGuid(), 0, Guid.CreateVersion7(), "https://nas.test:8443", Guid.CreateVersion7(), (Guid?)null, TestData.Now], Ct));
|
||||
await session.ExecuteAsync(insert, [Guid.NewGuid(), 0, sequence.Id, "https://nas.test:8443", Guid.CreateVersion7(), (Guid?)null, TestData.Now], Ct);
|
||||
Assert.Equal(1L, await session.ScalarAsync<long>("SELECT count(*) FROM found_copies", [], Ct));
|
||||
}
|
||||
|
||||
private static Task<int> Link(IDbSession session, string server, Guid remoteId, Guid? localId) =>
|
||||
session.ExecuteAsync("INSERT INTO sync_links (server, remote_id, local_id, title, remote_updated_at) VALUES ($1, $2, $3, $4, $5)",
|
||||
[server, remoteId, localId, "Remote", TestData.Now], CancellationToken.None);
|
||||
}
|
||||
|
||||
public sealed class SqliteFoundCopiesMigrationTests(TestContext context) : FoundCopiesMigrationTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.SqliteMemory;
|
||||
}
|
||||
|
||||
[RequiresEnvironment(PgTestServer.Variable)]
|
||||
public sealed class PostgresFoundCopiesMigrationTests(TestContext context) : FoundCopiesMigrationTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.Postgres;
|
||||
}
|
||||
@@ -11,7 +11,7 @@ public abstract class MigrationTests(TestContext context) : RepositoryTest(conte
|
||||
[
|
||||
"archives", "sequences", "frames", "renders", "jobs", "media_cards", "import_history", "users", "tokens",
|
||||
"render_nodes", "settings", "tags", "sequence_tags", "audit_log", "uploads", "schedules", "frame_removals", "projects", "project_versions",
|
||||
"render_copies",
|
||||
"render_copies", "found_copies", "copy_probes",
|
||||
];
|
||||
|
||||
[Test]
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
using Chronos.Data.Copies;
|
||||
using Chronos.Data.Tests.Infrastructure;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Perf;
|
||||
|
||||
/// <summary>
|
||||
/// Owner review 6 (#73), design §3.4: local detection's SHA-256 join over the 500,000-photo library answers in under 2 s
|
||||
/// (every photo unique: the join finds no pair, which is the whole index read). Opt-in: <c>CHRONOS_PERF=1</c>.
|
||||
/// </summary>
|
||||
[Category("perf")]
|
||||
[RequiresEnvironment(PerfGate.Variable)]
|
||||
[Serial]
|
||||
[Timeout(3_600_000)]
|
||||
public abstract class CopyOverlapPerfTests(TestContext context) : RepositoryTest(context)
|
||||
{
|
||||
public const double BudgetMs = 2_000;
|
||||
|
||||
[Test]
|
||||
public async Task LocalOverlapsAreFoundWithinTheGate()
|
||||
{
|
||||
var options = await NewOptionsAsync(multiConnection: true);
|
||||
await using (var build = await ChronosDatabase.OpenAsync(options, Ct)) await SyntheticLibrary.BuildAsync(build, Context);
|
||||
|
||||
var db = Own(await ChronosDatabase.OpenAsync(options, Ct));
|
||||
var store = new FoundCopyStore(db);
|
||||
IReadOnlyList<LocalOverlap> overlaps = [];
|
||||
var first = await PerfGate.TimeAsync(async () => overlaps = await store.LocalOverlapsAsync(Ct));
|
||||
var again = await PerfGate.MedianAsync(() => store.LocalOverlapsAsync(Ct));
|
||||
Context.Log($"perf: {Dialect} local overlaps {first:F0} ms first, {again:F0} ms again (budget {BudgetMs:F0} ms), {overlaps.Count} pairs");
|
||||
|
||||
Assert.Empty(overlaps);
|
||||
Assert.LessOrEqual(first, BudgetMs);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SqliteCopyOverlapPerfTests(TestContext context) : CopyOverlapPerfTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.SqliteFile;
|
||||
}
|
||||
|
||||
[RequiresEnvironment(PgTestServer.Variable)]
|
||||
public sealed class PostgresCopyOverlapPerfTests(TestContext context) : CopyOverlapPerfTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.Postgres;
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Copies;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Data.Tests.Archiving;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Projects;
|
||||
|
||||
/// <summary>
|
||||
/// A project copied with its whole history from one home to another (owner review 6, #73; design §5c): content hashes
|
||||
/// kept, a free name, a cut finished from its journal, a copy somebody took left alone, a newer format refused.
|
||||
/// </summary>
|
||||
[Category("projects")]
|
||||
public sealed class ProjectTransplantTests(TestContext context)
|
||||
{
|
||||
private sealed record Homes(ArchiveFixture Fx, ArchiveProjectHome From, ArchiveProjectHome To, SequenceProject Source, List<Frame> FromFrames,
|
||||
List<Frame> ToFrames);
|
||||
|
||||
/// <summary>Two sequences; the first has "Vertical" with two versions after its first.</summary>
|
||||
private async Task<Homes> HomesAsync()
|
||||
{
|
||||
var fx = await ArchiveFixture.CreateAsync(context);
|
||||
var (a, aFrames) = await ProjectServiceTests.UploadedAsync(fx, 3, 100);
|
||||
var (b, bFrames) = await ProjectServiceTests.UploadedAsync(fx, 3, 200);
|
||||
var projects = fx.Service.Projects;
|
||||
var vertical = await projects.CreateAsync(a.Id, "Vertical", cancellationToken: fx.Ct);
|
||||
var head = await projects.HeadAsync(vertical.Id, fx.Ct);
|
||||
head = (await projects.PushAsync(vertical.Id, ProjectServiceTests.Draft(head, new ProjectSettings { ExcludedFrames = [1] }, aFrames, "one"), fx.Ct)).Version!;
|
||||
await projects.PushAsync(vertical.Id, ProjectServiceTests.Draft(head, new ProjectSettings { HeroFrame = 2 }, aFrames, "two"), fx.Ct);
|
||||
var source = (await projects.ListAsync(a.Id, fx.Ct)).Single(p => p.Id == vertical.Id);
|
||||
return new Homes(fx, new ArchiveProjectHome(fx.Db, projects, a.Id), new ArchiveProjectHome(fx.Db, projects, b.Id), source, aFrames, bFrames);
|
||||
}
|
||||
|
||||
private static async Task<List<string>> HashesAsync(IProjectHome home, Guid projectId, CancellationToken ct) =>
|
||||
[.. (await home.VersionsAfterAsync(projectId, 0, 100, ct)).Select(v => v.ContentHash)];
|
||||
|
||||
[Test]
|
||||
public async Task TheWholeHistoryIsCopiedWithItsContentHashes()
|
||||
{
|
||||
var h = await HomesAsync();
|
||||
await using var _ = h.Fx;
|
||||
var saved = new List<TransplantStep>();
|
||||
|
||||
var copy = await new ProjectTransplant().CopyAsync(h.From, h.Source, h.To, "Vertical", null, s => { saved.Add(s); return ValueTask.CompletedTask; }, h.Fx.Ct);
|
||||
|
||||
Assert.Equal("Vertical", copy.Name);
|
||||
var source = await HashesAsync(h.From, h.Source.Id, h.Fx.Ct);
|
||||
var copied = await HashesAsync(h.To, copy.Id, h.Fx.Ct);
|
||||
// The copy's first version is the one it was made from, then the source's history in order.
|
||||
Assert.SequenceEqual(source, copied.Skip(1));
|
||||
Assert.Equal(source.Count + 1, copy.HeadNumber);
|
||||
Assert.Equal(copy.Id, saved[^1].TargetId);
|
||||
Assert.Equal(source.Count, saved[^1].Moves.Count);
|
||||
// The source is untouched.
|
||||
Assert.Equal(source.Count, (await h.From.HeadAsync(h.Source.Id, h.Fx.Ct)).Number);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ANameTakenGetsTheNextFreeOne()
|
||||
{
|
||||
var h = await HomesAsync();
|
||||
await using var _ = h.Fx;
|
||||
await h.To.CreateAsync("Vertical", null, null, h.Fx.Ct);
|
||||
|
||||
var copy = await new ProjectTransplant().CopyAsync(h.From, h.Source, h.To, "Vertical", null, _ => ValueTask.CompletedTask, h.Fx.Ct);
|
||||
|
||||
Assert.Equal("Vertical (2)", copy.Name);
|
||||
Assert.Equal("Vertical", ProjectTransplant.FreeName("Vertical", "STUDIO-PC", new HashSet<string> { "Main" }));
|
||||
Assert.Equal("Vertical (STUDIO-PC)", ProjectTransplant.FreeName("Vertical", "STUDIO-PC", new HashSet<string> { "vertical" }));
|
||||
Assert.Equal("Vertical (STUDIO-PC) (2)", ProjectTransplant.FreeName("Vertical", "STUDIO-PC", new HashSet<string> { "Vertical", "Vertical (studio-pc)" }));
|
||||
var longName = new string('x', ProjectService.MaxNameLength);
|
||||
Assert.True(ProjectTransplant.FreeName(longName, "STUDIO-PC", new HashSet<string> { longName }).Length <= ProjectService.MaxNameLength);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ACutAfterTheCopyWasAskedForIsFinishedOnTheCopyFoundByItsName()
|
||||
{
|
||||
var h = await HomesAsync();
|
||||
await using var _ = h.Fx;
|
||||
TransplantStep? journal = null;
|
||||
ValueTask Save(TransplantStep s)
|
||||
{
|
||||
journal = s;
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
var cut = new ProjectTransplant { Step = s => { if (s == "created") throw new IOException("cut"); } };
|
||||
|
||||
await Assert.ThrowsAsync<IOException>(() => cut.CopyAsync(h.From, h.Source, h.To, "Vertical", null, Save, h.Fx.Ct));
|
||||
Assert.Null(journal!.TargetId);
|
||||
|
||||
var copy = await new ProjectTransplant().CopyAsync(h.From, h.Source, h.To, "Vertical", journal, Save, h.Fx.Ct);
|
||||
|
||||
Assert.Count(1, (await h.To.ListAsync(h.Fx.Ct)).Where(p => !p.IsMain));
|
||||
Assert.Equal("Vertical", copy.Name);
|
||||
Assert.SequenceEqual(await HashesAsync(h.From, h.Source.Id, h.Fx.Ct), (await HashesAsync(h.To, copy.Id, h.Fx.Ct)).Skip(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ACutResumedSendsNoVersionTwice()
|
||||
{
|
||||
var h = await HomesAsync();
|
||||
await using var _ = h.Fx;
|
||||
TransplantStep? journal = null;
|
||||
ValueTask Save(TransplantStep s)
|
||||
{
|
||||
journal = s;
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
var pushes = 0;
|
||||
var cut = new ProjectTransplant { Step = s => { if (s == "pushed" && ++pushes == 2) throw new IOException("cut"); } };
|
||||
await Assert.ThrowsAsync<IOException>(() => cut.CopyAsync(h.From, h.Source, h.To, "Vertical", null, Save, h.Fx.Ct));
|
||||
|
||||
var copy = await new ProjectTransplant().CopyAsync(h.From, h.Source, h.To, "Vertical", journal, Save, h.Fx.Ct);
|
||||
|
||||
Assert.Equal(journal!.TargetId, copy.Id);
|
||||
var copied = await HashesAsync(h.To, copy.Id, h.Fx.Ct);
|
||||
Assert.SequenceEqual(await HashesAsync(h.From, h.Source.Id, h.Fx.Ct), copied.Skip(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ACopySomebodyTookIsLeftAloneAndANewNameIsTaken()
|
||||
{
|
||||
var h = await HomesAsync();
|
||||
await using var _ = h.Fx;
|
||||
TransplantStep? journal = null;
|
||||
ValueTask Save(TransplantStep s)
|
||||
{
|
||||
journal = s;
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
var cut = new ProjectTransplant { Step = s => { if (s == "pushed") throw new IOException("cut"); } };
|
||||
await Assert.ThrowsAsync<IOException>(() => cut.CopyAsync(h.From, h.Source, h.To, "Vertical", null, Save, h.Fx.Ct));
|
||||
var taken = journal!.TargetId!.Value;
|
||||
// Somebody works on the copy meanwhile.
|
||||
var theirs = ProjectServiceTests.Draft(await h.To.HeadAsync(taken, h.Fx.Ct), new ProjectSettings { HeroFrame = 0 }, h.ToFrames, "mine");
|
||||
Assert.Equal(PushOutcome.Stored, (await h.To.PushAsync(taken, theirs, h.Fx.Ct)).Outcome);
|
||||
|
||||
var copy = await new ProjectTransplant().CopyAsync(h.From, h.Source, h.To, "Vertical", journal, Save, h.Fx.Ct);
|
||||
|
||||
Assert.NotEqual(taken, copy.Id);
|
||||
Assert.Equal("Vertical (2)", copy.Name);
|
||||
Assert.Equal(theirs.Id, (await h.To.HeadAsync(taken, h.Fx.Ct)).Id);
|
||||
Assert.SequenceEqual(await HashesAsync(h.From, h.Source.Id, h.Fx.Ct), (await HashesAsync(h.To, copy.Id, h.Fx.Ct)).Skip(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AHomeThatReadsAnOlderFormatGetsNothing()
|
||||
{
|
||||
var h = await HomesAsync();
|
||||
await using var _ = h.Fx;
|
||||
var needed = (await h.From.VersionsAfterAsync(h.Source.Id, 0, 100, h.Fx.Ct)).Max(v => int.Max(v.SettingsFormat, ProjectContent.FormatOf(v.SettingsJson)));
|
||||
Assert.True(needed > 0);
|
||||
var older = new OlderHome(h.To, needed - 1);
|
||||
var before = (await h.To.ListAsync(h.Fx.Ct)).Count;
|
||||
|
||||
var refused = await Assert.ThrowsAsync<TransplantFormatException>(() =>
|
||||
new ProjectTransplant().CopyAsync(h.From, h.Source, older, "Vertical", null, _ => ValueTask.CompletedTask, h.Fx.Ct));
|
||||
|
||||
Assert.Equal((needed, needed - 1), (refused.Needed, refused.Reads));
|
||||
Assert.Equal(before, (await h.To.ListAsync(h.Fx.Ct)).Count);
|
||||
}
|
||||
|
||||
/// <summary>A home that stores an older settings format than this Chronos writes (an older server).</summary>
|
||||
private sealed class OlderHome(IProjectHome inner, int format) : IProjectHome
|
||||
{
|
||||
public int SettingsFormat => format;
|
||||
|
||||
public Task<HomeSequence> SequenceAsync(CancellationToken cancellationToken) => inner.SequenceAsync(cancellationToken);
|
||||
|
||||
public Task<IReadOnlyList<SequenceProject>> ListAsync(CancellationToken cancellationToken) => inner.ListAsync(cancellationToken);
|
||||
|
||||
public Task<SequenceProject> CreateAsync(string name, Guid? fromVersionId, string? author, CancellationToken cancellationToken) =>
|
||||
inner.CreateAsync(name, fromVersionId, author, cancellationToken);
|
||||
|
||||
public Task<ProjectVersion> HeadAsync(Guid projectId, CancellationToken cancellationToken) => inner.HeadAsync(projectId, cancellationToken);
|
||||
|
||||
public Task<ProjectVersion?> GetVersionAsync(Guid projectId, Guid versionId, CancellationToken cancellationToken) =>
|
||||
inner.GetVersionAsync(projectId, versionId, cancellationToken);
|
||||
|
||||
public Task<IReadOnlyList<ProjectVersion>> VersionsAfterAsync(Guid projectId, int afterNumber, int limit, CancellationToken cancellationToken) =>
|
||||
inner.VersionsAfterAsync(projectId, afterNumber, limit, cancellationToken);
|
||||
|
||||
public Task<IReadOnlyList<ProjectVersion>> HistoryAsync(Guid projectId, int? beforeNumber, int limit, CancellationToken cancellationToken) =>
|
||||
inner.HistoryAsync(projectId, beforeNumber, limit, cancellationToken);
|
||||
|
||||
public Task<PushResult> PushAsync(Guid projectId, ProjectVersion version, CancellationToken cancellationToken) =>
|
||||
inner.PushAsync(projectId, version, cancellationToken);
|
||||
|
||||
public Task<HomeFrames> FramesAsync(CancellationToken cancellationToken) => inner.FramesAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Sync;
|
||||
|
||||
/// <summary>The photo-by-photo comparison of two copies (owner review 6, #73; design §4.1).</summary>
|
||||
[Category("sync")]
|
||||
public sealed class CopyComparisonTests
|
||||
{
|
||||
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, 'a');
|
||||
|
||||
/// <summary>Photo n: its own SHA-256, size and a sub-second capture time 5 s after the one before.</summary>
|
||||
private static CopyPhotoInput Photo(int n, int index = -1, bool hashed = true, bool unusable = false, string? name = null, DateTime? at = null, long? size = null) =>
|
||||
new(Guid.NewGuid(), index < 0 ? n : index, name ?? $"IMG_{n:0000}.JPG", hashed ? Sha(n) : null, size ?? 1000 + n, at ?? Start.AddSeconds(5 * n), unusable);
|
||||
|
||||
private static CopySideInput Side(params CopyPhotoInput[] photos) => new(photos, []);
|
||||
|
||||
private static CopySideInput Side(IEnumerable<CopyPhotoInput> photos, params RemovedPhotoDto[] removed) => new([.. photos], removed);
|
||||
|
||||
private static RemovedPhotoDto Deleted(int n) => new(Sha(n), null, "deleted", DateTimeOffset.UnixEpoch);
|
||||
|
||||
private static RemovedPhotoDto Replaced(int n, int by) => new(Sha(n), Sha(by), "replaced", DateTimeOffset.UnixEpoch);
|
||||
|
||||
private static int Count(CopyComparisonResult result, PhotoClass c) => result.Of(c).Count();
|
||||
|
||||
[Test]
|
||||
public void IdenticalCopiesAreAllSame()
|
||||
{
|
||||
var result = CopyComparer.Compare(Side(Photo(1), Photo(2), Photo(3)), Side(Photo(1), Photo(2), Photo(3)));
|
||||
Assert.Equal(3, Count(result, PhotoClass.Same));
|
||||
Assert.Equal((3, 0, 0, 1000, 1000), (result.Score.Shared, result.Score.OnlyHere, result.Score.OnlyThere, result.Score.Containment, result.Score.Overlap));
|
||||
Assert.True(result.Score.Identical);
|
||||
Assert.True(result.Score.ByHash);
|
||||
Assert.Count(9, result.Totals);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ASubsetReadsFullyContainedAndASupersetToo()
|
||||
{
|
||||
// The Uploader sent part of the card: the server holds a subset.
|
||||
var all = Enumerable.Range(1, 10).Select(n => Photo(n)).ToArray();
|
||||
var part = Enumerable.Range(1, 4).Select(n => Photo(n)).ToArray();
|
||||
var subset = CopyComparer.Compare(Side(all), Side(part));
|
||||
Assert.Equal((4, 6, 0, 1000, 400), (subset.Score.Shared, subset.Score.OnlyHere, subset.Score.OnlyThere, subset.Score.Containment, subset.Score.Overlap));
|
||||
Assert.False(subset.Score.Identical);
|
||||
var superset = CopyComparer.Compare(Side(part), Side(all));
|
||||
Assert.Equal((4, 0, 6, 1000), (superset.Score.Shared, superset.Score.OnlyHere, superset.Score.OnlyThere, superset.Score.Containment));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AConvertedPhotoIsConvertedNotOnlyOnOneSide()
|
||||
{
|
||||
// This PC replaced photo 2 by a converted file (photo 50's content); the server still holds the original.
|
||||
var here = Side([Photo(1), Photo(50, index: 1, at: Start.AddSeconds(10))], Replaced(2, 50));
|
||||
var result = CopyComparer.Compare(here, Side(Photo(1), Photo(2)));
|
||||
var converted = Assert.Contains(result.Photos, p => p.Class == PhotoClass.Converted);
|
||||
Assert.Equal((Sha(50), Sha(2)), (converted.Here!.Sha256, converted.There!.Sha256));
|
||||
Assert.Equal((2, 0, 0), (result.Score.Shared, result.Score.OnlyHere, result.Score.OnlyThere));
|
||||
Assert.True(result.Score.Identical);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ATombstonedPhotoIsDeletedOnThatSideNotOnlyOnTheOther()
|
||||
{
|
||||
var result = CopyComparer.Compare(Side([Photo(1), Photo(2)], Deleted(3)), Side([Photo(1), Photo(3)], Deleted(2)));
|
||||
Assert.Equal(Sha(2), Assert.Contains(result.Photos, p => p.Class == PhotoClass.DeletedThere).Key);
|
||||
Assert.Equal(Sha(3), Assert.Contains(result.Photos, p => p.Class == PhotoClass.DeletedHere).Key);
|
||||
Assert.Equal((0, 0, 1, 1, 2), (result.Score.OnlyHere, result.Score.OnlyThere, result.Score.DeletedHere, result.Score.DeletedThere, result.Score.SharedRemoved));
|
||||
Assert.False(result.Score.Identical);
|
||||
Assert.Equal(1000, result.Score.Containment);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CopiesOfOnePhotoInsideASideCountOnce()
|
||||
{
|
||||
var copy = Photo(2) with { FrameId = Guid.NewGuid(), Index = 5, FileName = "IMG_0002 (1).JPG" };
|
||||
var result = CopyComparer.Compare(Side(Photo(1), Photo(2), copy), Side(Photo(1), Photo(2)));
|
||||
Assert.Equal((2, 2, 2), (result.Score.Shared, result.Score.LocalPhotos, result.Score.OtherPhotos));
|
||||
var same = Assert.Contains(result.Photos, p => p.Key == Sha(2));
|
||||
Assert.Equal((2, 1), (same.HereOccurrences, same.ThereOccurrences));
|
||||
Assert.True(result.Score.Identical);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AnUnhashedPhotoMatchesBySizeAndMillisecond()
|
||||
{
|
||||
var result = CopyComparer.Compare(Side(Photo(1), Photo(2, hashed: false)), Side(Photo(1), Photo(2)));
|
||||
var unhashed = Assert.Contains(result.Photos, p => p.Class == PhotoClass.SameUnhashed);
|
||||
Assert.Equal(Sha(2), unhashed.Key);
|
||||
Assert.Equal((1, 1), (result.Score.Shared, result.Score.SharedUnhashed));
|
||||
Assert.True(result.Score.Identical);
|
||||
Assert.False(result.Score.ByHash);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UnhashedLeftoversStayOnTheirSide()
|
||||
{
|
||||
// Another size at the same time is another photo: unlike CompareOriginals, nothing is assumed to match.
|
||||
var result = CopyComparer.Compare(Side(Photo(1), Photo(2, hashed: false, size: 7)), Side(Photo(1), Photo(3, hashed: false)));
|
||||
Assert.Equal((1, 0, 1, 1), (result.Score.Shared, result.Score.SharedUnhashed, result.Score.OnlyHere, result.Score.OnlyThere));
|
||||
Assert.True(Assert.Contains(result.Photos, p => p.Class == PhotoClass.OnlyHere).Key.StartsWith("u:7:", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DiffersPairsOnePhotoPerSideWithTheSameNameAndSubSecondInstant()
|
||||
{
|
||||
// Photo 2 edited on one side: another SHA-256, same name, same sub-second capture time.
|
||||
var edited = Photo(2) with { Sha256 = Sha(99), Size = 4242 };
|
||||
var result = CopyComparer.Compare(Side(Photo(1), Photo(2)), Side(Photo(1), edited));
|
||||
var differs = Assert.Contains(result.Photos, p => p.Class == PhotoClass.Differs);
|
||||
Assert.Equal((Sha(2), Sha(99), 1002L), (differs.Here!.Sha256, differs.There!.Sha256, differs.Bytes));
|
||||
Assert.Equal((1, 0, 0), (result.Score.Differs, result.Score.OnlyHere, result.Score.OnlyThere));
|
||||
Assert.False(result.Score.Identical);
|
||||
var total = Assert.Contains(result.Totals, t => t.Class == PhotoClass.Differs);
|
||||
Assert.Equal((1002L, 4242L), (total.HereBytes, total.ThereBytes));
|
||||
|
||||
// Another name, or another millisecond, is no pair.
|
||||
Assert.Equal(0, CopyComparer.Compare(Side(Photo(2)), Side(edited with { FileName = "DSC_0002.JPG" })).Score.Differs);
|
||||
Assert.Equal(0, CopyComparer.Compare(Side(Photo(2)), Side(edited with { CapturedAt = edited.CapturedAt!.Value.AddMilliseconds(1) })).Score.Differs);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void WholeSecondCaptureTimesNeverPairAsDiffers()
|
||||
{
|
||||
// A camera that records whole seconds: two different photos at one second with one name are not one photo edited.
|
||||
var at = new DateTime(2026, 9, 28, 18, 0, 0);
|
||||
var result = CopyComparer.Compare(Side(Photo(1, at: at, name: "IMG_0001.JPG")), Side(Photo(2, at: at, name: "IMG_0001.JPG")));
|
||||
Assert.Equal((0, 1, 1), (result.Score.Differs, result.Score.OnlyHere, result.Score.OnlyThere));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void BurstsNeverPairAsDiffers()
|
||||
{
|
||||
// Two photos of a burst at one instant on each side: which is which cannot be told, so nothing pairs.
|
||||
var at = Start.AddMilliseconds(130);
|
||||
var result = CopyComparer.Compare(
|
||||
Side(Photo(1, at: at, name: "IMG_0001.JPG"), Photo(2, at: at, name: "IMG_0001.JPG")),
|
||||
Side(Photo(3, at: at, name: "IMG_0001.JPG"), Photo(4, at: at, name: "IMG_0001.JPG")));
|
||||
Assert.Equal((0, 2, 2), (result.Score.Differs, result.Score.OnlyHere, result.Score.OnlyThere));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TwoVersionsAfterAKeepBothAreVersions()
|
||||
{
|
||||
// A Union keep-both left both versions of photo 2 on both sides, at its one capture instant.
|
||||
var version = Photo(2) with { FrameId = Guid.NewGuid(), Index = 3, Sha256 = Sha(99), Size = 4242 };
|
||||
var result = CopyComparer.Compare(Side(Photo(1), Photo(2), version), Side(Photo(1), Photo(2), version with { FrameId = Guid.NewGuid() }));
|
||||
Assert.Equal(2, Count(result, PhotoClass.Versions));
|
||||
Assert.Equal((3, 2), (result.Score.Shared, result.Score.Versions));
|
||||
Assert.True(result.Score.Identical);
|
||||
|
||||
// At a whole second they stay Same.
|
||||
var at = new DateTime(2026, 9, 28, 18, 0, 10);
|
||||
var whole = CopyComparer.Compare(Side(Photo(2, at: at), version with { CapturedAt = at }), Side(Photo(2, at: at), version with { CapturedAt = at }));
|
||||
Assert.Equal((2, 0), (Count(whole, PhotoClass.Same), whole.Score.Versions));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AnUnusableFrameHoldsNothingAndMarksTheRepair()
|
||||
{
|
||||
var result = CopyComparer.Compare(Side(Photo(1), Photo(2, unusable: true)), Side(Photo(1), Photo(2), Photo(3, unusable: true)));
|
||||
var brought = Assert.Contains(result.Photos, p => p.Key == Sha(2));
|
||||
Assert.Equal((PhotoClass.OnlyThere, true, false), (brought.Class, brought.RepairsHere, brought.RepairsThere));
|
||||
Assert.DoesNotContain(Sha(3), result.Photos.Select(p => p.Key));
|
||||
Assert.Equal((1, 2), (result.Score.LocalPhotos, result.Score.OtherPhotos));
|
||||
|
||||
// A Missing or Corrupt frame there is repaired by this PC's copy.
|
||||
var other = CopyComparer.Compare(Side(Photo(1), Photo(2)), Side(Photo(1), Photo(2, unusable: true)));
|
||||
var sent = Assert.Contains(other.Photos, p => p.Key == Sha(2));
|
||||
Assert.Equal((PhotoClass.OnlyHere, true), (sent.Class, sent.RepairsThere));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void BytesArePerClassAndSide()
|
||||
{
|
||||
var result = CopyComparer.Compare(Side(Photo(1), Photo(2)), Side(Photo(1), Photo(3)));
|
||||
Assert.Equal((1001L, 1001L), Totals(PhotoClass.Same));
|
||||
Assert.Equal((1002L, 0L), Totals(PhotoClass.OnlyHere));
|
||||
Assert.Equal((0L, 1003L), Totals(PhotoClass.OnlyThere));
|
||||
Assert.Equal(1003L, Assert.Contains(result.Photos, p => p.Class == PhotoClass.OnlyThere).Bytes);
|
||||
|
||||
(long, long) Totals(PhotoClass c)
|
||||
{
|
||||
var total = result.Totals.Single(t => t.Class == c);
|
||||
return (total.HereBytes, total.ThereBytes);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheResultDoesNotDependOnTheOrderOfTheInputs()
|
||||
{
|
||||
var edited = Photo(7) with { Sha256 = Sha(97) };
|
||||
CopyPhotoInput[] here = [Photo(1), Photo(2), Photo(3, hashed: false), Photo(4), Photo(5), Photo(6), Photo(7), Photo(8, unusable: true)];
|
||||
CopyPhotoInput[] there = [Photo(1), Photo(3), Photo(4, hashed: false), Photo(6), edited, Photo(8), Photo(9)];
|
||||
var removedHere = new[] { Deleted(9) };
|
||||
var removedThere = new[] { Deleted(5) };
|
||||
var a = CopyComparer.Compare(Side(here, removedHere), Side(there, removedThere));
|
||||
var b = CopyComparer.Compare(Side(Enumerable.Reverse(here), removedHere), Side(Enumerable.Reverse(there), removedThere));
|
||||
Assert.Equal(a.Score, b.Score);
|
||||
Assert.SequenceEqual(a.Photos.Select(p => (p.Class, p.Key, p.Here?.FrameId, p.There?.FrameId)), b.Photos.Select(p => (p.Class, p.Key, p.Here?.FrameId, p.There?.FrameId)));
|
||||
Assert.Equal((2, 2, 1, 1, 1, 1, 1), (a.Score.Shared, a.Score.SharedUnhashed, a.Score.Differs, a.Score.DeletedHere, a.Score.DeletedThere, a.Score.OnlyHere, a.Score.OnlyThere));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeletionsCountWhatTheOtherSideTombstonedAndNoLongerHolds()
|
||||
{
|
||||
var tombstones = SyncTombstones.FromDtos([Deleted(3)], [Deleted(2), Deleted(1)]);
|
||||
FramePhoto[] here = [new(Sha(1), 1, null), new(Sha(2), 2, null), new(Sha(2), 2, null)];
|
||||
FramePhoto[] there = [new(Sha(1), 1, null), new(Sha(3), 3, null)];
|
||||
Assert.Equal((1, 1), CopyComparer.Deletions(here, there, tombstones));
|
||||
Assert.Equal((0, 0), CopyComparer.Deletions(here, there, SyncTombstones.None));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TombstonesFromDtosReadBothSides()
|
||||
{
|
||||
var tombstones = SyncTombstones.FromDtos([Replaced(2, 50), Deleted(4)], [Deleted(5)]);
|
||||
Assert.Equal(tombstones.Canonical(Sha(50)), tombstones.Canonical(Sha(2)));
|
||||
Assert.True(tombstones.DeletedLocally(Sha(4)));
|
||||
Assert.False(tombstones.DeletedLocally(Sha(2)));
|
||||
Assert.True(tombstones.DeletedRemotely(Sha(5)));
|
||||
Assert.True(SyncTombstones.FromDtos([], null).IsEmpty);
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,8 @@ internal sealed class FakeSyncRemote : ISyncRemote
|
||||
private readonly Channel<ServerEvent> _events = Channel.CreateUnbounded<ServerEvent>();
|
||||
private readonly Dictionary<string, FakeSequence> _sessions = [];
|
||||
|
||||
public string Server => "https://nas.test:8443";
|
||||
/// <summary>The server's key: an address key unless a test names one by id (<c>id:<N></c>).</summary>
|
||||
public string Server { get; init; } = "https://nas.test:8443";
|
||||
|
||||
public Dictionary<Guid, FakeSequence> Sequences { get; } = [];
|
||||
|
||||
@@ -59,6 +60,155 @@ internal sealed class FakeSyncRemote : ISyncRemote
|
||||
|
||||
public Task<int> SettingsFormatAsync(CancellationToken cancellationToken) => Task.FromResult(SettingsFormat);
|
||||
|
||||
/// <summary>
|
||||
/// The capabilities the server announces (<see cref="ServerCapabilities"/>): none by default, an older server's path
|
||||
/// (owner review 6, #73); tests of the lookup and of uploads into a target opt in.
|
||||
/// </summary>
|
||||
public HashSet<string> Capabilities { get; } = new(StringComparer.Ordinal);
|
||||
|
||||
public Task<IReadOnlySet<string>> CapabilitiesAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
lock (_gate) return Task.FromResult<IReadOnlySet<string>>(new HashSet<string>(Capabilities, StringComparer.Ordinal));
|
||||
}
|
||||
|
||||
/// <summary>Lookup requests so far, as received.</summary>
|
||||
public List<PhotoLookupRequest> Lookups { get; } = [];
|
||||
|
||||
/// <summary>Uploads into a target so far (<see cref="UploadFileIntoAsync"/>), and how many the server filed from a copy it held elsewhere.</summary>
|
||||
public int IntoUploads { get; private set; }
|
||||
|
||||
public int CopiedInto { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Uploads into a target refused with 403, as for an account with Read and Upload but not Edit that does not own the
|
||||
/// target; <see cref="RefusedInto"/> counts them.
|
||||
/// </summary>
|
||||
public bool ForbidInto { get; set; }
|
||||
|
||||
public int RefusedInto { get; private set; }
|
||||
|
||||
/// <summary>Runs once, before the next frame deletion is answered (the server sequence changing meanwhile).</summary>
|
||||
public Action? OnceBeforeDelete { get; set; }
|
||||
|
||||
/// <summary>Frame deletions refused with 403, as for an account that is neither the owner nor an admin.</summary>
|
||||
public bool ForbidFrameDeletes { get; set; }
|
||||
|
||||
/// <summary>Frames moved to the server's trash so far, by sequence.</summary>
|
||||
public List<(Guid SequenceId, FakeFrame Frame)> Trashed { get; } = [];
|
||||
|
||||
/// <summary>Files <paramref name="sequence"/> under <paramref name="sessionKey"/>, as an upload with that key would.</summary>
|
||||
public void FileUnder(string sessionKey, FakeSequence sequence)
|
||||
{
|
||||
lock (_gate) _sessions[sessionKey] = sequence;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Like the server (owner review 6, #73): per probe, the sequences holding its hashes in a frame (a sequence it never
|
||||
/// hashed lists none), tombstoning them (by the photo's or its replacement's SHA-256), holding a frame of its unhashed keys
|
||||
/// by size and capture millisecond, or filed under its session key. 404 without <see cref="ServerCapabilities.PhotoLookup"/>,
|
||||
/// 413 beyond the limits.
|
||||
/// </summary>
|
||||
public Task<PhotoLookupResponse> LookupPhotosAsync(PhotoLookupRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (!Capabilities.Contains(ServerCapabilities.PhotoLookup)) throw new ChronosApiException(HttpStatusCode.NotFound, new ApiError("not_found", "route"));
|
||||
if (request.Probes.Count > PhotoLookupRequest.MaxProbes || request.CountItems() > PhotoLookupRequest.MaxItems)
|
||||
throw new ChronosApiException(HttpStatusCode.RequestEntityTooLarge, new ApiError("too_many", "probes"));
|
||||
Lookups.Add(request);
|
||||
var results = new List<ProbeResult>();
|
||||
foreach (var probe in request.Probes)
|
||||
{
|
||||
var hashes = probe.Sha256.Select(h => h.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
|
||||
var keys = (probe.Unhashed ?? []).Select(k => (k.Size, Ms(k.CapturedAt))).ToHashSet();
|
||||
var filed = probe.SessionKey is { } key && _sessions.TryGetValue(key, out var held) ? held : null;
|
||||
var hits = new List<PhotoLookupHit>();
|
||||
foreach (var sequence in Sequences.Values)
|
||||
{
|
||||
var inFrames = sequence.Unhashed ? 0 : sequence.Frames.Select(f => f.Sha256).Where(hashes.Contains).Distinct(StringComparer.Ordinal).Count();
|
||||
var removed = hashes.Count(h => sequence.Removed.Any(r => r.Sha256 == h || r.Replacement == h));
|
||||
var unhashed = keys.Count(k => sequence.Frames.Any(f => f.CapturedAt is { } at && f.Bytes.Length == k.Size && Ms(at) == k.Item2));
|
||||
var session = ReferenceEquals(filed, sequence);
|
||||
if (inFrames + removed + unhashed > 0 || session) hits.Add(new PhotoLookupHit(sequence.Id, inFrames, removed, unhashed, session));
|
||||
}
|
||||
results.Add(new ProbeResult(probe.Key, hits));
|
||||
}
|
||||
return Task.FromResult(new PhotoLookupResponse(results));
|
||||
}
|
||||
|
||||
static long Ms(DateTime at) => at.Ticks / TimeSpan.TicksPerMillisecond;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Like the server with <see cref="ServerCapabilities.UploadInto"/>: the photo is filed into the target even when another
|
||||
/// sequence holds it (a server-side copy, counted in <see cref="CopiedInto"/>); one the target holds answers its frame, one
|
||||
/// it tombstoned answers none. Without the capability the server ignores the flag: an upload as before.
|
||||
/// </summary>
|
||||
public async Task<CompleteUploadResponse?> UploadFileIntoAsync(string path, Guid sequenceId, string sha256, DateTime? capturedAt,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
bool capable;
|
||||
lock (_gate) capable = Capabilities.Contains(ServerCapabilities.UploadInto);
|
||||
if (!capable) return await UploadFileAsync(path, sequenceId, null, sha256, capturedAt, cancellationToken);
|
||||
if (ForbidInto)
|
||||
{
|
||||
lock (_gate) RefusedInto++;
|
||||
throw new ChronosApiException(HttpStatusCode.Forbidden, new ApiError("forbidden", "into"));
|
||||
}
|
||||
var bytes = await File.ReadAllBytesAsync(path, cancellationToken);
|
||||
if (Convert.ToHexStringLower(SHA256.HashData(bytes)) != sha256)
|
||||
throw new ChronosApiException(HttpStatusCode.BadRequest, new ApiError("hash_mismatch", "hash"));
|
||||
lock (_gate)
|
||||
{
|
||||
IntoUploads++;
|
||||
var target = Find(sequenceId);
|
||||
if (target.Removed.Any(r => r.Sha256 == sha256)) return null;
|
||||
var index = target.Frames.FindIndex(f => f.Sha256 == sha256);
|
||||
if (index >= 0) return new CompleteUploadResponse(target.Frames[index].Id, target.Id, index);
|
||||
if (Sequences.Values.Where(s => !s.Unhashed && s != target).SelectMany(s => s.Frames).Any(f => f.Sha256 == sha256)) CopiedInto++;
|
||||
var frame = target.AddFrame(bytes, Path.GetFileName(path), capturedAt);
|
||||
return new CompleteUploadResponse(frame.Id, target.Id, target.Frames.IndexOf(frame));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Like the server's <c>frames/delete</c>: 404 for an unknown sequence, 403 with <see cref="ForbidFrameDeletes"/>, 409
|
||||
/// <c>frames_conflict</c> when a frame is not there or the frames version moved, 409 <c>would_empty</c>; a dry run answers
|
||||
/// the plan; else the frames go to the trash, each leaving a tombstone, and the frames version moves.
|
||||
/// </summary>
|
||||
public Task<FrameDeleteResultDto> DeleteFramesAsync(Guid sequenceId, FrameDeleteRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (OnceBeforeDelete is { } before)
|
||||
{
|
||||
OnceBeforeDelete = null;
|
||||
before();
|
||||
}
|
||||
lock (_gate)
|
||||
{
|
||||
var sequence = Find(sequenceId);
|
||||
if (ForbidFrameDeletes) throw new ChronosApiException(HttpStatusCode.Forbidden, new ApiError("forbidden", "delete"));
|
||||
var wanted = request.FrameIds.ToHashSet();
|
||||
var frames = sequence.Frames.Where(f => wanted.Contains(f.Id)).ToList();
|
||||
if (frames.Count != wanted.Count || (request.ExpectedFramesVersion is { } expected && expected != sequence.FramesVersion))
|
||||
throw new ChronosApiException(HttpStatusCode.Conflict, new ApiError("frames_conflict", "changed"));
|
||||
if (frames.Count == sequence.Frames.Count) throw new ChronosApiException(HttpStatusCode.Conflict, new ApiError("would_empty", "empty"));
|
||||
var bytes = frames.Sum(f => (long)f.Bytes.Length);
|
||||
if (request.DryRun)
|
||||
return Task.FromResult(new FrameDeleteResultDto(sequenceId, frames.Count, bytes, sequence.FramesVersion, sequence.Frames.Count, null, true));
|
||||
var at = DateTimeOffset.UtcNow;
|
||||
foreach (var frame in frames)
|
||||
{
|
||||
sequence.Frames.Remove(frame);
|
||||
Trashed.Add((sequenceId, frame));
|
||||
if (!sequence.Removed.Any(r => r.Sha256 == frame.Sha256)) sequence.Removed.Add(new RemovedPhotoDto(frame.Sha256, null, "deleted", at));
|
||||
}
|
||||
sequence.FramesVersion++;
|
||||
sequence.UpdatedAt = at;
|
||||
return Task.FromResult(new FrameDeleteResultDto(sequenceId, frames.Count, bytes, sequence.FramesVersion, sequence.Frames.Count,
|
||||
$"trash/photos-{Guid.NewGuid():N}", false));
|
||||
}
|
||||
}
|
||||
|
||||
public FakeSequence Add(string? title, IEnumerable<byte[]> originals, string? settingsJson = null,
|
||||
SequenceStatus status = SequenceStatus.ProxiesBuilt | SequenceStatus.ThumbsBuilt)
|
||||
{
|
||||
@@ -68,6 +218,12 @@ internal sealed class FakeSyncRemote : ISyncRemote
|
||||
return sequence;
|
||||
}
|
||||
|
||||
/// <summary>Someone deletes the sequence on the server: every later call for it answers 404.</summary>
|
||||
public void Drop(Guid id)
|
||||
{
|
||||
lock (_gate) Sequences.Remove(id);
|
||||
}
|
||||
|
||||
/// <summary>Someone else edits the settings on the server.</summary>
|
||||
public void EditSettings(Guid id, string settingsJson)
|
||||
{
|
||||
@@ -357,7 +513,10 @@ internal sealed class FakeSequence
|
||||
}
|
||||
|
||||
public SequenceDto Dto() => new(Id, Title, Title ?? "Untitled", "2026/" + Id.ToString("N"), "Canon", CameraModel, null, FirstCapture, null, Frames.Count, 10,
|
||||
Frames.Sum(f => (long)f.Bytes.Length), (long)Status, Renders.Count, null, Tags, Rating, Notes, SettingsVersion, FramesVersion, 0, null, UpdatedAt);
|
||||
Frames.Sum(f => (long)f.Bytes.Length), (long)Status, Renders.Count, null, Tags, Rating, Notes, SettingsVersion, FramesVersion, 0, OwnerUserId, UpdatedAt);
|
||||
|
||||
/// <summary>The server account that owns the sequence (none by default).</summary>
|
||||
public Guid? OwnerUserId { get; set; }
|
||||
|
||||
public SequenceManifest Manifest(Func<Guid, bool> proxySent) => new(Id, FramesVersion, SettingsVersion, SettingsJson, Tags,
|
||||
[.. Frames.Select((f, i) => new ManifestFrame(f.Id, i, f.FileName, f.Bytes.Length, Unhashed ? string.Empty : f.Sha256,
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Copies;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Sync;
|
||||
|
||||
/// <summary>
|
||||
/// The new photos of a pair integrated with automatic photos (owner review 6, #73; design §7.3): after a comparison the
|
||||
/// agent queues them both ways in the background; never for a pair only linked or integrated without automatic photos; a
|
||||
/// failed transfer counts, waits for its backoff, and three in a row are told.
|
||||
/// </summary>
|
||||
[Category("sync")]
|
||||
public sealed class SyncAgentCopyTests(TestContext context)
|
||||
{
|
||||
private static readonly SyncAgentOptions Quick = new()
|
||||
{
|
||||
RefreshInterval = TimeSpan.FromHours(1),
|
||||
EventDelay = TimeSpan.FromMilliseconds(20),
|
||||
MinBackoff = TimeSpan.FromMilliseconds(20),
|
||||
MaxBackoff = TimeSpan.FromMilliseconds(200),
|
||||
};
|
||||
|
||||
/// <summary>An engine that queues but never runs, so the queued jobs can be read and settled by the test.</summary>
|
||||
private static JobEngine Queue(SyncFixture f) => new(f.Db, [.. f.Sync.CreateJobHandlers(new SyncFixture.Connector(f.Remote))],
|
||||
new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50) });
|
||||
|
||||
/// <summary>A local sequence and a server sequence sharing two photos, each with one the other lacks, linked, in <paramref name="state"/>.</summary>
|
||||
private static async Task<(Sequence Local, FakeSequence Remote)> PairAsync(SyncFixture f, string title, CopyState state, bool autoPhotos)
|
||||
{
|
||||
var photos = f.NewPhotos(4);
|
||||
var local = await f.LocalAsync(title, photos.Take(3).ToList());
|
||||
var remote = f.Remote.Add(title + " NAS", [photos[0], photos[1], photos[3]]);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
var row = await f.Sync.Copies.EnsureLinkedAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
if (state != CopyState.Linked)
|
||||
Assert.True(await f.Sync.Copies.SetStateAsync(row.Id, null, state, new CopyAnswer(null, null, null, autoPhotos, DateTimeOffset.UtcNow), f.Ct));
|
||||
return (local, remote);
|
||||
}
|
||||
|
||||
private static async Task<List<Job>> QueuedAsync(SyncFixture f, JobKind kind) =>
|
||||
[.. (await f.Db.Jobs.ListAsync(JobState.Queued, kind, 50, cancellationToken: f.Ct)).Items];
|
||||
|
||||
[Test]
|
||||
public async Task AnIntegratedPairWithAutomaticPhotosQueuesBothWaysInTheBackground()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var (local, remote) = await PairAsync(f, "Comet", CopyState.Integrated, autoPhotos: true);
|
||||
await using var engine = Queue(f);
|
||||
await using var agent = new SyncAgent(f.Sync, f.Remote, () => new SyncPolicy(), engine, Quick);
|
||||
|
||||
await agent.RefreshAsync(f.Ct);
|
||||
await agent.RefreshAsync(f.Ct);
|
||||
|
||||
var upload = (await QueuedAsync(f, JobKind.UploadCommit)).Single();
|
||||
var download = (await QueuedAsync(f, JobKind.Download)).Single();
|
||||
Assert.Equal((local.Id, JobPriority.Background), (upload.TargetIds.Single(), upload.Priority));
|
||||
Assert.Equal((remote.Id, JobPriority.Background), (download.TargetIds.Single(), download.Priority));
|
||||
Assert.Contains(local.ArchiveId.ToString(), download.ParametersJson ?? string.Empty);
|
||||
Assert.Count(0, agent.PhotoFailures);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task APairOnlyLinkedOrWithoutAutomaticPhotosQueuesNothing()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
await PairAsync(f, "Linked", CopyState.Linked, autoPhotos: false);
|
||||
await PairAsync(f, "Manual", CopyState.Integrated, autoPhotos: false);
|
||||
await using var engine = Queue(f);
|
||||
await using var agent = new SyncAgent(f.Sync, f.Remote, () => new SyncPolicy(), engine, Quick);
|
||||
|
||||
await agent.RefreshAsync(f.Ct);
|
||||
|
||||
Assert.Count(0, await QueuedAsync(f, JobKind.UploadCommit));
|
||||
Assert.Count(0, await QueuedAsync(f, JobKind.Download));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task APairWhoseServerCopyIsGoneQueuesNoAutomaticPhotos()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
// A server keyed by its id, so a 404 counts against the pair (design §7.5).
|
||||
var nas = new FakeSyncRemote { Server = HomeFolders.IdKey(Guid.NewGuid()) };
|
||||
var photos = f.NewPhotos(3);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var remote = nas.Add("Comet NAS", photos.Take(2));
|
||||
await f.Sync.LinkAsync(nas.Server, remote.Id, local.Id, f.Ct);
|
||||
var row = await f.Sync.Copies.EnsureLinkedAsync(nas.Server, remote.Id, local.Id, f.Ct);
|
||||
Assert.True(await f.Sync.Copies.SetStateAsync(row.Id, null, CopyState.Integrated,
|
||||
new CopyAnswer(null, null, null, true, DateTimeOffset.UtcNow), f.Ct));
|
||||
nas.Drop(remote.Id);
|
||||
await using var engine = new JobEngine(f.Db, [.. f.Sync.CreateJobHandlers(new SyncFixture.Connector(nas))],
|
||||
new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50) });
|
||||
await using var agent = new SyncAgent(f.Sync, nas, () => new SyncPolicy(), engine, Quick);
|
||||
|
||||
await agent.RefreshAsync(f.Ct);
|
||||
await using (var session = await f.Db.Database.OpenAsync(f.Ct))
|
||||
await session.ExecuteAsync("UPDATE found_copies SET remote_gone_at = $1 WHERE id = $2", [DateTimeOffset.UtcNow.AddMinutes(-11), row.Id], f.Ct);
|
||||
await agent.RefreshAsync(f.Ct);
|
||||
|
||||
var pair = (await f.Sync.Copies.GetAsync(row.Id, f.Ct))!;
|
||||
Assert.True(pair.RemoteGoneHits > 0);
|
||||
Assert.Equal((CopyState.Integrated, true), (pair.State, pair.AutoPhotos));
|
||||
Assert.Count(0, await QueuedAsync(f, JobKind.UploadCommit));
|
||||
Assert.Count(0, await QueuedAsync(f, JobKind.Download));
|
||||
Assert.Count(0, agent.PhotoFailures);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task FailedTransfersCountWaitForTheirBackoffAndThreeInARowAreTold()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(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.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
var row = await f.Sync.Copies.EnsureLinkedAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.Sync.Copies.SetStateAsync(row.Id, null, CopyState.Integrated, new CopyAnswer(null, null, null, true, DateTimeOffset.UtcNow), f.Ct);
|
||||
await using var engine = Queue(f);
|
||||
await using var agent = new SyncAgent(f.Sync, f.Remote, () => new SyncPolicy(), engine, Quick);
|
||||
var told = new List<(Guid, AutoPhotoFailure)>();
|
||||
agent.PhotosNotSent += (id, failure) => told.Add((id, failure));
|
||||
|
||||
for (var attempt = 1; attempt <= SyncAgent.NotSentAfter; attempt++)
|
||||
{
|
||||
await agent.RefreshAsync(f.Ct);
|
||||
var upload = (await QueuedAsync(f, JobKind.UploadCommit)).Single();
|
||||
await f.Db.Jobs.SetStateAsync(upload.Id, JobState.Failed, "Quota reached", f.Ct);
|
||||
|
||||
await agent.RefreshAsync(f.Ct);
|
||||
Assert.Equal(new AutoPhotoFailure(attempt, "Quota reached"), agent.PhotoFailures[local.Id]);
|
||||
// Within its backoff nothing new is queued.
|
||||
Assert.Count(0, await QueuedAsync(f, JobKind.UploadCommit));
|
||||
await Task.Delay(Quick.MaxBackoff + TimeSpan.FromMilliseconds(50), f.Ct);
|
||||
}
|
||||
Assert.Equal((local.Id, SyncAgent.NotSentAfter), (told.Single().Item1, told.Single().Item2.Count));
|
||||
|
||||
await agent.RefreshAsync(f.Ct);
|
||||
var last = (await QueuedAsync(f, JobKind.UploadCommit)).Single();
|
||||
await f.Db.Jobs.SetStateAsync(last.Id, JobState.Done, null, f.Ct);
|
||||
await agent.RefreshAsync(f.Ct);
|
||||
Assert.Count(0, agent.PhotoFailures);
|
||||
}
|
||||
}
|
||||
@@ -30,13 +30,15 @@ internal sealed class SyncFixture : IAsyncDisposable
|
||||
public string Server => Remote.Server;
|
||||
public CancellationToken Ct => Archive.Ct;
|
||||
|
||||
public static async Task<SyncFixture> CreateAsync(TestContext context)
|
||||
/// <param name="identity">The servers known by id and the address keys they were reached under (default: none).</param>
|
||||
public static async Task<SyncFixture> CreateAsync(TestContext context, Func<ServerIdentity>? identity = null)
|
||||
{
|
||||
var archive = await ArchiveFixture.CreateAsync(context);
|
||||
var sync = new SyncService(archive.Db, archive.Service, new SyncOptions
|
||||
{
|
||||
Archive = new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) },
|
||||
ProxyCacheDirectory = context.CreateTempDirectory("proxies"),
|
||||
Identity = identity,
|
||||
});
|
||||
return new SyncFixture(archive, sync);
|
||||
}
|
||||
@@ -54,8 +56,11 @@ internal sealed class SyncFixture : IAsyncDisposable
|
||||
return photos;
|
||||
}
|
||||
|
||||
/// <summary>A local sequence made through the archive ingest (hashed frames, a real sidecar).</summary>
|
||||
public async Task<Sequence> LocalAsync(string title, IReadOnlyList<byte[]> originals, string? settingsJson = null)
|
||||
/// <summary>
|
||||
/// A local sequence made through the archive ingest (hashed frames, a real sidecar), each frame captured 10 s after the
|
||||
/// one before from <see cref="ArchiveFixture.Start"/>, or at <paramref name="capturedAt"/>.
|
||||
/// </summary>
|
||||
public async Task<Sequence> LocalAsync(string title, IReadOnlyList<byte[]> originals, string? settingsJson = null, IReadOnlyList<DateTime>? capturedAt = null)
|
||||
{
|
||||
Guid? id = null;
|
||||
var staging = Path.Combine(Archive.Paths.StagingDirectory, "test");
|
||||
@@ -66,7 +71,7 @@ internal sealed class SyncFixture : IAsyncDisposable
|
||||
await File.WriteAllBytesAsync(path, originals[i], Ct);
|
||||
var sha = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(originals[i]));
|
||||
var result = await Archive.Service.Ingest.CommitAsync(new IngestRequest(Archive.Archive.Id, id, id is null ? title : null, null, path,
|
||||
$"IMG_{i + 1:0000}.JPG", originals[i].Length, sha, ArchiveFixture.Start.AddSeconds(10 * i), null), Ct);
|
||||
$"IMG_{i + 1:0000}.JPG", originals[i].Length, sha, capturedAt?[i] ?? ArchiveFixture.Start.AddSeconds(10 * i), null), Ct);
|
||||
id = result.SequenceId;
|
||||
}
|
||||
var sequence = (await Db.Sequences.GetAsync(id!.Value, Ct))!;
|
||||
|
||||
@@ -0,0 +1,535 @@
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Copies;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Sync;
|
||||
|
||||
/// <summary>
|
||||
/// Sync with found copies (owner review 6, #73): no silent link, links by setting outside the gate, unlink, 404 marks,
|
||||
/// deletion counts and the agreed details of an Integrate.
|
||||
/// </summary>
|
||||
[Category("sync")]
|
||||
public sealed class SyncServiceCopyTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public async Task ARefreshLinksNothingByDefaultAndAsks()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(3);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var remote = f.Remote.Add("2026-09-28 Canon", photos);
|
||||
remote.FirstCapture = local.FirstCapture;
|
||||
remote.CameraModel = local.CameraModel;
|
||||
var raised = new List<CopyFindResult>();
|
||||
f.Sync.CopiesFound += (_, result) => raised.Add(result);
|
||||
|
||||
await f.RefreshAsync();
|
||||
|
||||
Assert.Null((await f.EntryAsync("Comet")).Link);
|
||||
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single();
|
||||
Assert.Equal(CopyState.Candidate, pair.State);
|
||||
Assert.Equal((local.Id, remote.Id), (pair.LocalId, pair.RemoteId!.Value));
|
||||
Assert.Equal(CopyEvidence.Hashes, pair.Evidence);
|
||||
Assert.Equal(3, pair.Score.Shared);
|
||||
Assert.Equal(pair.Id, raised.Single().New.Single().Id);
|
||||
Assert.Empty(raised.Single().AutoLinked);
|
||||
|
||||
// Nothing moved: nothing is compared or announced again.
|
||||
var manifests = f.Remote.ManifestCalls;
|
||||
await f.RefreshAsync();
|
||||
Assert.Equal(manifests, f.Remote.ManifestCalls);
|
||||
Assert.Count(1, raised);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task IdenticalCopiesAreLinkedByThemselvesWhenTheSettingSaysSo()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
f.Remote.Capabilities.Add(ServerCapabilities.PhotoLookup);
|
||||
var photos = f.NewPhotos(3);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var remote = f.Remote.Add("Comet", photos);
|
||||
var raised = new List<CopyFindResult>();
|
||||
f.Sync.CopiesFound += (_, result) => raised.Add(result);
|
||||
|
||||
await f.RefreshAsync(new SyncPolicy { Linking = CopyLinking.WhenIdentical });
|
||||
|
||||
var entry = await f.EntryAsync("Comet");
|
||||
Assert.Equal(remote.Id, entry.Link?.RemoteId);
|
||||
Assert.Equal(SyncStatus.InSync, entry.Status);
|
||||
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single();
|
||||
Assert.Equal(CopyState.Linked, pair.State);
|
||||
Assert.Equal(pair.Id, raised.Single().AutoLinked.Single().Id);
|
||||
Assert.Equal(local.Id, pair.LocalId);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AKeepApartAnsweredMeanwhileWinsOverTheLink()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var remote = f.Remote.Add("Comet", photos);
|
||||
remote.FirstCapture = local.FirstCapture;
|
||||
remote.CameraModel = local.CameraModel;
|
||||
await f.RefreshAsync();
|
||||
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).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 linked = await f.Sync.AutoLinkAsync(f.Remote, new SyncPolicy { Linking = CopyLinking.WhenIdentical }, pair, remote.Dto(), local, null, f.Ct);
|
||||
|
||||
Assert.False(linked);
|
||||
Assert.Null(await f.Sync.LinkOfAsync(f.Server, local.Id, f.Ct));
|
||||
Assert.Equal(CopyState.KeptApart, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task EveryLinkHasItsPair()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var local = await f.LocalAsync("Comet", f.NewPhotos(2));
|
||||
var remote = f.Remote.Add("Harbour", f.NewPhotos(1));
|
||||
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
|
||||
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single();
|
||||
Assert.Equal((CopyEvidence.Link, CopyState.Linked), (pair.Evidence, pair.State));
|
||||
Assert.Equal((local.Id, remote.Id), (pair.LocalId, pair.RemoteId!.Value));
|
||||
Assert.False(pair.IsListed);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnUploadForAnIntegratedPairCanWaitInTheBackground()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var local = await f.LocalAsync("Comet", f.NewPhotos(1));
|
||||
await using var engine = new JobEngine(f.Db, f.Sync.CreateJobHandlers(new SyncFixture.Connector(f.Remote)));
|
||||
|
||||
var background = await f.Sync.EnqueueUploadAsync(engine, f.Server, local, JobPriority.Background, f.Ct);
|
||||
Assert.Equal(JobPriority.Background, background.Priority);
|
||||
Assert.Equal(SyncTransferKind.Upload, SyncService.TransferKind(background));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task UnlinkKeepsTheServerSequenceAndKeepsThePairApart()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var remote = f.Remote.Add("Comet", photos);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.RefreshAsync();
|
||||
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Comet")).Status);
|
||||
|
||||
await f.Sync.UnlinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
|
||||
var link = await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct);
|
||||
Assert.NotNull(link);
|
||||
Assert.Null(link.LocalId);
|
||||
Assert.Null(await f.Sync.LinkOfAsync(f.Server, local.Id, f.Ct));
|
||||
Assert.Equal(SyncState.LocalOnly, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SyncState);
|
||||
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single();
|
||||
Assert.Equal(CopyState.KeptApart, pair.State);
|
||||
Assert.Equal(2, pair.AnsweredShared);
|
||||
|
||||
// Asked again only by a large later change: the next refresh leaves the two apart.
|
||||
await f.RefreshAsync(new SyncPolicy { Linking = CopyLinking.WhenHalfShared });
|
||||
Assert.Null((await f.Sync.ListAsync(f.Server, f.Ct)).Single(e => e.Local?.Id == local.Id).Link);
|
||||
Assert.Equal(CopyState.KeptApart, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task A404IsCountedOncePerRefreshAndTwiceReadsDeleted()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var nas = new FakeSyncRemote { Server = HomeFolders.IdKey(Guid.NewGuid()) };
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var remote = nas.Add("Comet", photos);
|
||||
await f.Sync.LinkAsync(nas.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
|
||||
nas.Sequences.Remove(remote.Id);
|
||||
|
||||
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
|
||||
|
||||
Assert.Null(await f.Sync.LinkOfAsync(nas.Server, local.Id, f.Ct));
|
||||
var pair = (await f.Sync.Copies.ListByServerAsync(nas.Server, f.Ct)).Single();
|
||||
Assert.Equal(1, pair.RemoteGoneHits);
|
||||
Assert.False(pair.RemoteGone);
|
||||
|
||||
// Asked again no sooner than ten minutes after the first 404.
|
||||
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
|
||||
Assert.Equal(1, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.RemoteGoneHits);
|
||||
await using (var session = await f.Db.Database.OpenAsync(f.Ct))
|
||||
await session.ExecuteAsync("UPDATE found_copies SET remote_gone_at = $1 WHERE id = $2", [DateTimeOffset.UtcNow.AddMinutes(-11), pair.Id], f.Ct);
|
||||
|
||||
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
|
||||
|
||||
pair = (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!;
|
||||
Assert.Equal(2, pair.RemoteGoneHits);
|
||||
Assert.True(pair.RemoteGone);
|
||||
Assert.True(pair.NeedsAttention);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AMatchWhoseServerSequenceIsDeletedIsGoneAfterTheRefreshAndUploadAllSendsTheLocalOne()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var nas = new FakeSyncRemote { Server = HomeFolders.IdKey(Guid.NewGuid()) };
|
||||
var photos = f.NewPhotos(3);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var remote = nas.Add("2026-09-28 Canon", photos);
|
||||
remote.FirstCapture = local.FirstCapture;
|
||||
remote.CameraModel = local.CameraModel;
|
||||
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
|
||||
var pair = (await f.Sync.Copies.ListByServerAsync(nas.Server, f.Ct)).Single();
|
||||
Assert.Equal((CopyState.Candidate, local.Id), (pair.State, pair.LocalId));
|
||||
Assert.Null((await f.Sync.Links.GetAsync(nas.Server, remote.Id, f.Ct))!.LocalId);
|
||||
|
||||
// Deleted on the server: no longer listed, and a 404 when asked for.
|
||||
nas.Sequences.Remove(remote.Id);
|
||||
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
|
||||
|
||||
Assert.Null(await f.Sync.Copies.GetAsync(pair.Id, f.Ct));
|
||||
var entries = (await f.Sync.ListAsync(nas.Server, f.Ct)).Where(e => e.Local?.Id == local.Id).ToList();
|
||||
var (upload, skipped) = UploadAllRule.Select(entries, await f.Sync.Copies.ListAsync(f.Ct), new HashSet<Guid>(), new HashSet<Guid>());
|
||||
Assert.Empty(skipped);
|
||||
Assert.Equal(local.Id, upload.Single().Local!.Id);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AKeptApartServerSequenceAnswering404OnceKeepsTheAnswerAndIsNeverLinkedByItself()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var nas = new FakeSyncRemote { Server = HomeFolders.IdKey(Guid.NewGuid()) };
|
||||
var photos = f.NewPhotos(3);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var remote = nas.Add("2026-09-28 Canon", photos);
|
||||
remote.FirstCapture = local.FirstCapture;
|
||||
remote.CameraModel = local.CameraModel;
|
||||
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
|
||||
var pair = (await f.Sync.Copies.ListByServerAsync(nas.Server, f.Ct)).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));
|
||||
|
||||
// Moved to the server's trash and restored: one refresh gets a 404, the next lists it again.
|
||||
nas.Sequences.Remove(remote.Id);
|
||||
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
|
||||
Assert.Equal((CopyState.KeptApart, 1), ((await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.RemoteGoneHits));
|
||||
nas.Sequences[remote.Id] = remote;
|
||||
await f.Sync.RefreshAsync(nas, new SyncPolicy { Linking = CopyLinking.WhenIdentical }, f.Ct);
|
||||
|
||||
// Keep separate is remembered (owner Q1): not asked again, and not linked although the photos are identical.
|
||||
var after = (await f.Sync.Copies.ListByServerAsync(nas.Server, f.Ct)).Single();
|
||||
Assert.Equal((pair.Id, CopyState.KeptApart, 0), (after.Id, after.State, after.RemoteGoneHits));
|
||||
Assert.Null(await f.Sync.LinkOfAsync(nas.Server, local.Id, f.Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ASequenceReadAsDeletedOnTheServerIsClearedWhenItIsListedAgainOrLinkedAgain()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var nas = new FakeSyncRemote { Server = HomeFolders.IdKey(Guid.NewGuid()) };
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var remote = nas.Add("Comet", photos);
|
||||
await f.Sync.LinkAsync(nas.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
|
||||
nas.Sequences.Remove(remote.Id);
|
||||
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
|
||||
var pair = (await f.Sync.Copies.ListByServerAsync(nas.Server, f.Ct)).Single();
|
||||
await using (var session = await f.Db.Database.OpenAsync(f.Ct))
|
||||
await session.ExecuteAsync("UPDATE found_copies SET remote_gone_at = $1 WHERE id = $2", [DateTimeOffset.UtcNow.AddMinutes(-11), pair.Id], f.Ct);
|
||||
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
|
||||
Assert.True((await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.RemoteGone);
|
||||
|
||||
// Restored from the server's trash: listed again, it no longer reads "deleted on server".
|
||||
nas.Sequences[remote.Id] = remote;
|
||||
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
|
||||
pair = (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!;
|
||||
Assert.Equal((0, (DateTimeOffset?)null, false), (pair.RemoteGoneHits, pair.RemoteGoneAt, pair.RemoteGone));
|
||||
Assert.Equal(CopyState.Candidate, pair.State);
|
||||
|
||||
// A pair still marked (the listing missed it) is cleared by a link to that very sequence: automatic photos may move again.
|
||||
await using (var session = await f.Db.Database.OpenAsync(f.Ct))
|
||||
await session.ExecuteAsync("UPDATE found_copies SET remote_gone_hits = 2, remote_gone_at = $1 WHERE id = $2", [DateTimeOffset.UtcNow, pair.Id], f.Ct);
|
||||
await f.Sync.LinkAsync(nas.Server, remote.Id, local.Id, f.Ct);
|
||||
pair = (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!;
|
||||
Assert.Equal((0, false, CopyState.Linked), (pair.RemoteGoneHits, pair.RemoteGone, pair.State));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ASequenceBackOnTheServerIsAskedAboutAgain()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var nas = new FakeSyncRemote { Server = HomeFolders.IdKey(Guid.NewGuid()) };
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var remote = nas.Add("Comet", photos);
|
||||
await f.Sync.LinkAsync(nas.Server, remote.Id, local.Id, f.Ct);
|
||||
nas.Unlisted.Add(remote.Id);
|
||||
nas.Sequences.Remove(remote.Id);
|
||||
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
|
||||
Assert.Equal(1, (await f.Sync.Copies.ListByServerAsync(nas.Server, f.Ct)).Single().RemoteGoneHits);
|
||||
|
||||
nas.Sequences[remote.Id] = remote;
|
||||
nas.Unlisted.Remove(remote.Id);
|
||||
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
|
||||
|
||||
var pair = (await f.Sync.Copies.ListByServerAsync(nas.Server, f.Ct)).Single();
|
||||
Assert.Equal(0, pair.RemoteGoneHits);
|
||||
Assert.Null(pair.RemoteGoneAt);
|
||||
Assert.Equal(CopyState.Candidate, pair.State);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ASequenceBackAfterAJobs404StaysLinked()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var nas = new FakeSyncRemote { Server = HomeFolders.IdKey(Guid.NewGuid()) };
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var remote = nas.Add("Comet", photos);
|
||||
await f.Sync.LinkAsync(nas.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
|
||||
// A transfer's 404: the pair is marked once, the link stays.
|
||||
await f.Sync.Copies.MarkRemoteGoneAsync(nas.Server, remote.Id, local.Id, Guid.NewGuid(), DateTimeOffset.UtcNow, f.Ct);
|
||||
Assert.Equal(1, (await f.Sync.Copies.ListByServerAsync(nas.Server, f.Ct)).Single().RemoteGoneHits);
|
||||
|
||||
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
|
||||
|
||||
var pair = (await f.Sync.Copies.ListByServerAsync(nas.Server, f.Ct)).Single();
|
||||
Assert.Equal((0, CopyState.Linked), (pair.RemoteGoneHits, pair.State));
|
||||
Assert.Equal(local.Id, (await f.Sync.LinkOfAsync(nas.Server, local.Id, f.Ct))?.LocalId);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task EveryLinkAnswering404AtOnceMarksNothing()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var nas = new FakeSyncRemote { Server = HomeFolders.IdKey(Guid.NewGuid()) };
|
||||
var remotes = new List<FakeSequence>();
|
||||
for (var i = 0; i < 5; i++)
|
||||
{
|
||||
var photos = f.NewPhotos(1);
|
||||
var local = await f.LocalAsync($"Card {i}", photos);
|
||||
var remote = nas.Add($"Card {i}", photos);
|
||||
await f.Sync.LinkAsync(nas.Server, remote.Id, local.Id, f.Ct);
|
||||
remotes.Add(remote);
|
||||
}
|
||||
foreach (var remote in remotes) nas.Sequences.Remove(remote.Id);
|
||||
|
||||
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
|
||||
|
||||
Assert.Empty(await f.Sync.Links.ListAsync(nas.Server, f.Ct));
|
||||
Assert.True((await f.Sync.Copies.ListByServerAsync(nas.Server, f.Ct)).All(p => p.RemoteGoneHits == 0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ASweepOf404sConfirmsNoEarlierHitEither()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var nas = new FakeSyncRemote { Server = HomeFolders.IdKey(Guid.NewGuid()) };
|
||||
// One pair with a 404 counted more than ten minutes ago (its link already forgotten).
|
||||
var first = f.NewPhotos(2);
|
||||
var gone = await f.LocalAsync("Comet", first);
|
||||
var goneRemote = nas.Add("Comet", first);
|
||||
await f.Sync.LinkAsync(nas.Server, goneRemote.Id, gone.Id, f.Ct);
|
||||
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
|
||||
nas.Sequences.Remove(goneRemote.Id);
|
||||
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
|
||||
var pair = (await f.Sync.Copies.ListByServerAsync(nas.Server, f.Ct)).Single(p => p.LocalId == gone.Id);
|
||||
Assert.Equal(1, pair.RemoteGoneHits);
|
||||
await using (var session = await f.Db.Database.OpenAsync(f.Ct))
|
||||
await session.ExecuteAsync("UPDATE found_copies SET remote_gone_at = $1 WHERE id = $2", [DateTimeOffset.UtcNow.AddMinutes(-11), pair.Id], f.Ct);
|
||||
|
||||
// Then the server serves something else: every linked sequence answers 404 at once.
|
||||
var remotes = new List<FakeSequence>();
|
||||
for (var i = 0; i < 5; i++)
|
||||
{
|
||||
var photos = f.NewPhotos(1);
|
||||
var local = await f.LocalAsync($"Card {i}", photos);
|
||||
var remote = nas.Add($"Card {i}", photos);
|
||||
await f.Sync.LinkAsync(nas.Server, remote.Id, local.Id, f.Ct);
|
||||
remotes.Add(remote);
|
||||
}
|
||||
foreach (var remote in remotes) nas.Sequences.Remove(remote.Id);
|
||||
|
||||
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
|
||||
|
||||
pair = (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!;
|
||||
Assert.Equal(1, pair.RemoteGoneHits);
|
||||
Assert.False(pair.RemoteGone);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AServerKnownOnlyByItsAddressMarksNothing()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var remote = f.Remote.Add("Comet", photos);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
f.Remote.Sequences.Remove(remote.Id);
|
||||
|
||||
await f.RefreshAsync();
|
||||
|
||||
Assert.Null(await f.Sync.LinkOfAsync(f.Server, local.Id, f.Ct));
|
||||
Assert.True((await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).All(p => p.RemoteGoneHits == 0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ASequenceForgottenOnAServerKnownByItsAddressIsFoundAgainWhenItIsBack()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
f.Remote.Capabilities.Add(ServerCapabilities.PhotoLookup);
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var remote = f.Remote.Add("Comet", photos);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.RefreshAsync();
|
||||
f.Remote.Sequences.Remove(remote.Id);
|
||||
await f.RefreshAsync();
|
||||
Assert.Null(await f.Sync.LinkOfAsync(f.Server, local.Id, f.Ct));
|
||||
|
||||
// Back on the server: nothing remembers the forgotten link, so the two are found and asked about again.
|
||||
f.Remote.Sequences[remote.Id] = remote;
|
||||
await f.RefreshAsync();
|
||||
|
||||
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single();
|
||||
Assert.Equal((local.Id, remote.Id, CopyState.Candidate), (pair.LocalId, pair.RemoteId!.Value, pair.State));
|
||||
Assert.Null(await f.Sync.LinkOfAsync(f.Server, local.Id, f.Ct));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ALinkedPairWhoseLinkIsGoneIsAskedAboutAgain()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
f.Remote.Capabilities.Add(ServerCapabilities.PhotoLookup);
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var remote = f.Remote.Add("Comet", photos);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.RefreshAsync();
|
||||
// The link removed by another hand, the pair's row left as it was.
|
||||
await f.Sync.Links.DeleteAsync(f.Server, remote.Id, f.Ct);
|
||||
var raised = new List<CopyFindResult>();
|
||||
f.Sync.CopiesFound += (_, result) => raised.Add(result);
|
||||
|
||||
await f.RefreshAsync();
|
||||
|
||||
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single();
|
||||
Assert.Equal((CopyState.Candidate, false), (pair.State, pair.AutoPhotos));
|
||||
Assert.Contains(pair.Id, raised.SelectMany(r => r.New).Select(p => p.Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DeletionCountsFollowEachComparison()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(3);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var remote = f.Remote.Add("Comet", photos);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.RefreshAsync();
|
||||
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single();
|
||||
Assert.Equal((3, 0, 0), (pair.Score.Shared, pair.Score.DeletedHere, pair.Score.DeletedThere));
|
||||
|
||||
// The server deletes a photo this PC still holds.
|
||||
var gone = remote.Frames[1];
|
||||
remote.Frames.Remove(gone);
|
||||
remote.FramesVersion++;
|
||||
remote.Removed.Add(new RemovedPhotoDto(gone.Sha256, null, "deleted", DateTimeOffset.UtcNow));
|
||||
await f.RefreshAsync();
|
||||
|
||||
pair = (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!;
|
||||
Assert.Equal((0, 1), (pair.Score.DeletedHere, pair.Score.DeletedThere));
|
||||
Assert.True(pair.IsListed);
|
||||
Assert.True(pair.NeedsAttention);
|
||||
|
||||
// A photo deleted on this PC only: counted, never a warning (the user's own cull).
|
||||
var culled = pair with { Score = pair.Score with { DeletedHere = 2, DeletedThere = 0 } };
|
||||
Assert.False(culled.NeedsAttention);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AgreedDetailsTakeTheServersOwnChangeSinceThePlan()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var (local, remote, planLocal, planRemote) = await PlannedAsync(f);
|
||||
var final = planLocal with { Title = "Comet agreed" };
|
||||
// The server's light analysis of the photos just filed changes its settings after the plan.
|
||||
f.Remote.EditSettings(remote.Id, SyncFixture.Window41);
|
||||
|
||||
var (applied, updated) = await f.Sync.ApplyAgreedAsync(f.Remote, remote.Id, final, planLocal, planRemote, local.SettingsVersion, f.Ct);
|
||||
|
||||
Assert.Equal("Comet agreed", remote.Title);
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, remote.SettingsJson));
|
||||
var stored = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
|
||||
Assert.Equal("Comet agreed", stored.Title);
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, stored.SettingsJson));
|
||||
Assert.Equal((stored.SettingsVersion, remote.SettingsVersion), (applied.SettingsVersion, updated.SettingsVersion));
|
||||
var link = (await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct))!;
|
||||
Assert.Equal((stored.SettingsVersion, remote.SettingsVersion), (link.BaseLocalSettings, link.BaseRemoteSettings));
|
||||
Assert.Count(1, f.Remote.Updates);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AgreedDetailsAreSentAgainAfterARefusedEdit()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var (local, remote, planLocal, planRemote) = await PlannedAsync(f);
|
||||
var final = planLocal with { Title = "Comet agreed" };
|
||||
// Unhashed on the server: its frames are read after the manifest, and the server changes right then.
|
||||
remote.Unhashed = true;
|
||||
f.Remote.OnceBeforeFrames = () =>
|
||||
{
|
||||
f.Remote.EditSettings(remote.Id, SyncFixture.Window41);
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
|
||||
await f.Sync.ApplyAgreedAsync(f.Remote, remote.Id, final, planLocal, planRemote, local.SettingsVersion, f.Ct);
|
||||
|
||||
Assert.Equal("Comet agreed", remote.Title);
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, remote.SettingsJson));
|
||||
Assert.Equal("Comet agreed", (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.Title);
|
||||
Assert.Count(1, f.Remote.Updates);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AgreedDetailsAreRefusedAfterAnEditOnThisPc()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var (local, remote, planLocal, planRemote) = await PlannedAsync(f);
|
||||
var final = planLocal with { Title = "Comet agreed" };
|
||||
var edited = await f.EditLocalSettingsAsync(local.Id, SyncFixture.Window41);
|
||||
|
||||
await Assert.ThrowsAsync<SyncConflictChangedException>(() =>
|
||||
f.Sync.ApplyAgreedAsync(f.Remote, remote.Id, final, planLocal, planRemote, local.SettingsVersion, f.Ct));
|
||||
// Shown at the new version, the content still moved since the plan.
|
||||
await Assert.ThrowsAsync<SyncConflictChangedException>(() =>
|
||||
f.Sync.ApplyAgreedAsync(f.Remote, remote.Id, final, planLocal, planRemote, edited.SettingsVersion, f.Ct));
|
||||
|
||||
Assert.Empty(f.Remote.Updates);
|
||||
Assert.Equal("Comet", remote.Title);
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson));
|
||||
}
|
||||
|
||||
/// <summary>A linked pair with the same settings on both sides, and each side's portable payload as an Integrate's plan reads it.</summary>
|
||||
private static async Task<(Sequence Local, FakeSequence Remote, SyncPayload PlanLocal, SyncPayload PlanRemote)> PlannedAsync(SyncFixture f)
|
||||
{
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Comet", photos, SyncFixture.Window33);
|
||||
var remote = f.Remote.Add("Comet", photos, SyncFixture.Window33);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
local = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
|
||||
var none = new FramePhotos([]);
|
||||
return (local, remote, CopyPayload.Portable(SyncPayload.Of(local), none), CopyPayload.Portable(SyncPayload.Of(remote.Dto(), remote.SettingsJson), none));
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Copies;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Data.Tests.Archiving;
|
||||
using Chronos.Protocol;
|
||||
@@ -763,14 +764,14 @@ public sealed class SyncServiceTests(TestContext context)
|
||||
other.FirstCapture = local.FirstCapture;
|
||||
other.CameraModel = local.CameraModel;
|
||||
|
||||
await f.RefreshAsync();
|
||||
await f.RefreshAsync(new SyncPolicy { Linking = CopyLinking.WhenHalfShared });
|
||||
|
||||
var entry = await f.EntryAsync("Comet");
|
||||
Assert.Equal(remote.Id, entry.Link?.RemoteId);
|
||||
Assert.Equal((0, 0), (entry.Link!.MissingRemote, entry.Link.MissingLocal));
|
||||
Assert.Null((await f.EntryAsync("Other card")).Local);
|
||||
var manifests = f.Remote.ManifestCalls;
|
||||
await f.RefreshAsync();
|
||||
await f.RefreshAsync(new SyncPolicy { Linking = CopyLinking.WhenHalfShared });
|
||||
Assert.Equal(manifests, f.Remote.ManifestCalls);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,555 @@
|
||||
using System.Security.Cryptography;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Copies;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Repositories;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Sync;
|
||||
|
||||
/// <summary>
|
||||
/// The filtered transfers an Integrate runs (owner review 6, #73; design §5c): only the photos asked for, each once even
|
||||
/// when resumed, a server sequence gone marks the pair, and a linked upload files into its target when the server can.
|
||||
/// </summary>
|
||||
[Category("sync")]
|
||||
public sealed class SyncTransferCopyTests(TestContext context)
|
||||
{
|
||||
private static string Sha(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes));
|
||||
|
||||
private static async Task<JobContext> ContextAsync(SyncFixture f)
|
||||
{
|
||||
var engine = new JobEngine(f.Db, [], new JobEngineOptions { WorkerId = "t" });
|
||||
await f.Db.Jobs.EnqueueAsync(new Job { Id = Guid.CreateVersion7(), Kind = JobKind.Verify, State = JobState.Queued, Created = DateTimeOffset.UtcNow }, f.Ct);
|
||||
var claimed = Assert.NotNull(await f.Db.Jobs.ClaimNextAsync("t", [JobKind.Verify], f.Ct));
|
||||
return new JobContext(engine, claimed, f.Ct);
|
||||
}
|
||||
|
||||
private static async Task<HashSet<string>> LocalHashesAsync(SyncFixture f, Guid id) =>
|
||||
(await f.Db.Frames.ListBySequenceAsync(id, cancellationToken: f.Ct)).Select(fr => fr.Sha256!).ToHashSet(StringComparer.Ordinal);
|
||||
|
||||
private static SyncFixture Capable(SyncFixture f)
|
||||
{
|
||||
f.Remote.Capabilities.Add(ServerCapabilities.UploadInto);
|
||||
f.Remote.Capabilities.Add(ServerCapabilities.PhotoLookup);
|
||||
return f;
|
||||
}
|
||||
|
||||
/// <summary>Waits until no pass a download queued works on <paramref name="sequenceId"/>.</summary>
|
||||
private static async Task WaitIdleAsync(SyncFixture f, Guid sequenceId)
|
||||
{
|
||||
var until = DateTime.UtcNow.AddSeconds(30);
|
||||
while (DateTime.UtcNow < until)
|
||||
{
|
||||
var held = await f.Db.Jobs.ListPendingTargetsAsync(JobKind.Thumbs, f.Ct);
|
||||
held.UnionWith(await f.Db.Jobs.ListPendingTargetsAsync(JobKind.LightAnalyse, f.Ct));
|
||||
if (!held.Contains(sequenceId)) return;
|
||||
await Task.Delay(20, f.Ct);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task OnlyThePhotosAskedForGoEachWay()
|
||||
{
|
||||
await using var f = Capable(await SyncFixture.CreateAsync(context));
|
||||
var photos = f.NewPhotos(5);
|
||||
var local = await f.LocalAsync("Comet", [photos[0], photos[1], photos[2]]);
|
||||
var remote = f.Remote.Add("Comet", [photos[0], photos[3], photos[4]]);
|
||||
var job = await ContextAsync(f);
|
||||
var transfers = new SyncTransfers(f.Sync);
|
||||
|
||||
Assert.Equal(1, await transfers.SendPhotosAsync(job, f.Remote, local.Id, remote.Id, [Sha(photos[1])]));
|
||||
Assert.Equal(1, await transfers.FetchPhotosAsync(job, f.Remote, remote.Id, local.Id, [Sha(photos[3])]));
|
||||
|
||||
Assert.True(remote.Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals([Sha(photos[0]), Sha(photos[1]), Sha(photos[3]), Sha(photos[4])]));
|
||||
Assert.True((await LocalHashesAsync(f, local.Id)).SetEquals([Sha(photos[0]), Sha(photos[1]), Sha(photos[2]), Sha(photos[3])]));
|
||||
Assert.Equal(1, f.Remote.IntoUploads);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ARunAgainSendsAndFetchesNothingTwice()
|
||||
{
|
||||
await using var f = Capable(await SyncFixture.CreateAsync(context));
|
||||
var photos = f.NewPhotos(4);
|
||||
var local = await f.LocalAsync("Comet", [photos[0], photos[1]]);
|
||||
var remote = f.Remote.Add("Comet", [photos[2], photos[3]]);
|
||||
var job = await ContextAsync(f);
|
||||
var transfers = new SyncTransfers(f.Sync);
|
||||
var sent = new List<string>();
|
||||
var fetched = new List<string>();
|
||||
string[] send = [Sha(photos[0]), Sha(photos[1])], fetch = [Sha(photos[2]), Sha(photos[3])];
|
||||
|
||||
Assert.Equal(2, await transfers.SendPhotosAsync(job, f.Remote, local.Id, remote.Id, send, k => { sent.Add(k); return ValueTask.CompletedTask; }));
|
||||
Assert.Equal(2, await transfers.FetchPhotosAsync(job, f.Remote, remote.Id, local.Id, fetch, k => { fetched.Add(k); return ValueTask.CompletedTask; }));
|
||||
var uploads = f.Remote.IntoUploads;
|
||||
|
||||
Assert.Equal(0, await transfers.SendPhotosAsync(job, f.Remote, local.Id, remote.Id, send, k => { sent.Add(k); return ValueTask.CompletedTask; }));
|
||||
Assert.Equal(0, await transfers.FetchPhotosAsync(job, f.Remote, remote.Id, local.Id, fetch, k => { fetched.Add(k); return ValueTask.CompletedTask; }));
|
||||
|
||||
Assert.Equal(uploads, f.Remote.IntoUploads);
|
||||
Assert.Count(4, remote.Frames);
|
||||
Assert.Count(4, await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct));
|
||||
// Every key is reported done, the second time without moving a file.
|
||||
Assert.SequenceEqual([.. send, .. send], sent);
|
||||
Assert.SequenceEqual([.. fetch, .. fetch], fetched);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AServerSequenceGoneMarksThePairAndSendsNowhereElse()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
// A server known by its id: a 404 there is that server's word (an address may name another server tomorrow).
|
||||
var nas = new FakeSyncRemote { Server = ServerIdentity.IdKey(Guid.NewGuid()) };
|
||||
nas.Capabilities.Add(ServerCapabilities.UploadInto);
|
||||
nas.Capabilities.Add(ServerCapabilities.PhotoLookup);
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var remote = nas.Add("Comet", [photos[0]]);
|
||||
var pair = await PairAsync(f, nas.Server, local.Id, remote.Id);
|
||||
nas.Sequences.Remove(remote.Id);
|
||||
var job = await ContextAsync(f);
|
||||
var transfers = new SyncTransfers(f.Sync);
|
||||
|
||||
await Assert.ThrowsAsync<RemoteGoneException>(() => transfers.SendPhotosAsync(job, nas, local.Id, remote.Id, [Sha(photos[1])]));
|
||||
await Assert.ThrowsAsync<RemoteGoneException>(() => transfers.FetchPhotosAsync(job, nas, remote.Id, local.Id, [Sha(photos[0])]));
|
||||
|
||||
Assert.Empty(nas.Sequences);
|
||||
Assert.Equal(0, nas.IntoUploads);
|
||||
Assert.Equal(1, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.RemoteGoneHits);
|
||||
|
||||
// A refresh right after asks again but does not count a second 404 within the recheck interval.
|
||||
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
|
||||
Assert.Equal(1, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.RemoteGoneHits);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AGoneAnswerFromAServerKnownByItsAddressMarksNothing()
|
||||
{
|
||||
await using var f = Capable(await SyncFixture.CreateAsync(context));
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var remote = f.Remote.Add("Comet", [photos[0]]);
|
||||
var pair = await PairAsync(f, f.Server, local.Id, remote.Id);
|
||||
f.Remote.Sequences.Remove(remote.Id);
|
||||
var job = await ContextAsync(f);
|
||||
|
||||
await Assert.ThrowsAsync<RemoteGoneException>(() => new SyncTransfers(f.Sync).SendPhotosAsync(job, f.Remote, local.Id, remote.Id, [Sha(photos[1])]));
|
||||
|
||||
Assert.Equal(0, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.RemoteGoneHits);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AFirstUploadWhoseFirstPhotoTheServerHoldsElsewhereEndsWithEveryPhotoInTheNewSequence()
|
||||
{
|
||||
await using var f = Capable(await SyncFixture.CreateAsync(context));
|
||||
var photos = f.NewPhotos(3);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
// The first photo is already on the server, in another sequence.
|
||||
f.Remote.Add("Elsewhere", [photos[0]]);
|
||||
var engine = await f.StartEngineAsync();
|
||||
|
||||
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
|
||||
var link = Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct));
|
||||
var target = f.Remote.Sequences[link.RemoteId];
|
||||
Assert.True(target.Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnUploadOfASequenceKeptApartMakesANewServerSequenceAndLeavesTheOtherAlone()
|
||||
{
|
||||
await using var f = Capable(await SyncFixture.CreateAsync(context));
|
||||
var photos = f.NewPhotos(3);
|
||||
var local = await f.LocalAsync("Comet", [photos[0], photos[1]]);
|
||||
var engine = await f.StartEngineAsync();
|
||||
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
var first = Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct)).RemoteId;
|
||||
// Unlinked ("Stop syncing these sequences"): the pair is kept apart.
|
||||
await f.Sync.UnlinkAsync(f.Server, first, local.Id, f.Ct);
|
||||
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single(c => c.RemoteId == first);
|
||||
Assert.Equal(CopyState.KeptApart, pair.State);
|
||||
|
||||
// A new photo, then a plain Upload.
|
||||
await f.AddLocalAsync(local.Id, photos[2]);
|
||||
job = await f.Sync.EnqueueUploadAsync(engine, f.Server, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
|
||||
// The sequence kept apart gets nothing, and stays apart and unlinked; a new one holds every photo.
|
||||
Assert.True(f.Remote.Sequences[first].Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals([Sha(photos[0]), Sha(photos[1])]));
|
||||
Assert.Equal(CopyState.KeptApart, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State);
|
||||
Assert.Null((await f.Sync.Links.GetAsync(f.Server, first, f.Ct))!.LocalId);
|
||||
var link = Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct));
|
||||
Assert.NotEqual(first, link.RemoteId);
|
||||
Assert.True(f.Remote.Sequences[link.RemoteId].Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ARetriedUploadNeverLinksAgainTheServerSequenceItsFirstAttemptMadeAndTheUserKeptApart()
|
||||
{
|
||||
await using var f = Capable(await SyncFixture.CreateAsync(context));
|
||||
var photos = f.NewPhotos(3);
|
||||
var local = await f.LocalAsync("Comet", [photos[0], photos[1]]);
|
||||
var engine = await f.StartEngineAsync();
|
||||
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
var started = Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct)).RemoteId;
|
||||
// The user keeps the pair apart while a run of the upload that made it is still to be retried.
|
||||
await f.Sync.UnlinkAsync(f.Server, started, local.Id, f.Ct);
|
||||
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single(c => c.RemoteId == started);
|
||||
await f.AddLocalAsync(local.Id, photos[2]);
|
||||
|
||||
// The retry resumes from the checkpoint naming the sequence that run made.
|
||||
var row = new Job
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Kind = JobKind.UploadCommit,
|
||||
TargetIds = [local.Id],
|
||||
State = JobState.Running,
|
||||
NodeId = "t#0",
|
||||
Created = DateTimeOffset.UtcNow,
|
||||
Started = DateTimeOffset.UtcNow,
|
||||
Checkpoint = started.ToString(),
|
||||
};
|
||||
await f.Db.Jobs.EnqueueAsync(row, f.Ct);
|
||||
var retry = new JobContext(new JobEngine(f.Db, [], new JobEngineOptions { WorkerId = "t" }), row, f.Ct);
|
||||
await new SyncTransfers(f.Sync).UploadAsync(retry, f.Remote, local.Id);
|
||||
|
||||
// The sequence kept apart stays apart, unlinked and as it was; a new one holds every photo.
|
||||
Assert.Equal(CopyState.KeptApart, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State);
|
||||
Assert.Null((await f.Sync.Links.GetAsync(f.Server, started, f.Ct))!.LocalId);
|
||||
Assert.True(f.Remote.Sequences[started].Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals([Sha(photos[0]), Sha(photos[1])]));
|
||||
var link = Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct));
|
||||
Assert.NotEqual(started, link.RemoteId);
|
||||
Assert.True(f.Remote.Sequences[link.RemoteId].Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DownloadingAgainAServerSequenceUnlinkedFromItsDownloadMakesANewLocalSequence()
|
||||
{
|
||||
await using var f = Capable(await SyncFixture.CreateAsync(context));
|
||||
var photos = f.NewPhotos(3);
|
||||
var remote = f.Remote.Add("Comet", photos);
|
||||
var engine = await f.StartEngineAsync();
|
||||
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Comet", SyncDownloadMode.Originals, f.Archive.Archive.Id);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
var local = Assert.NotNull(Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct)).LocalId);
|
||||
await WaitIdleAsync(f, local);
|
||||
|
||||
// Here: one photo deleted, the title edited; then the pair is unlinked (kept apart).
|
||||
var sequence = (await f.Db.Sequences.GetAsync(local, f.Ct))!;
|
||||
var gone = (await f.Db.Frames.ListBySequenceAsync(local, cancellationToken: f.Ct))[0];
|
||||
var delete = await f.Archive.Service.FrameTrash.PlanDeleteAsync(local, [gone.Id], sequence.FramesVersion, f.Ct);
|
||||
await f.Archive.Service.FrameTrash.DeleteAsync(delete, cancellationToken: f.Ct);
|
||||
await f.Db.Sequences.EditAsync(local, new SequenceEdit { Title = "Mine" }, null, f.Ct);
|
||||
await f.Sync.UnlinkAsync(f.Server, remote.Id, local, f.Ct);
|
||||
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single(c => c.RemoteId == remote.Id && c.LocalId == local);
|
||||
Assert.Equal(CopyState.KeptApart, pair.State);
|
||||
|
||||
// Download originals again: a separate local copy.
|
||||
job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Comet", SyncDownloadMode.Originals, f.Archive.Archive.Id);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
|
||||
// The sequence kept apart is as the user left it: its photos, its deletion, its title, its pair.
|
||||
var after = (await f.Db.Sequences.GetAsync(local, f.Ct))!;
|
||||
Assert.Equal("Mine", after.Title);
|
||||
Assert.Count(2, await f.Db.Frames.ListBySequenceAsync(local, cancellationToken: f.Ct));
|
||||
Assert.Contains(gone.Sha256, (await f.Db.FrameRemovals.ListBySequenceAsync(local, f.Ct)).Select(r => r.Sha256));
|
||||
Assert.Equal(CopyState.KeptApart, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State);
|
||||
var copy = Assert.NotNull(Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct)).LocalId);
|
||||
Assert.NotEqual(local, copy);
|
||||
Assert.True((await LocalHashesAsync(f, copy)).SetEquals(photos.Select(Sha)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DownloadingAgainAServerSequenceWhoseLinkA404ForgotRefillsAndLinksItsOwnLocalCopy()
|
||||
{
|
||||
await using var f = Capable(await SyncFixture.CreateAsync(context));
|
||||
var photos = f.NewPhotos(3);
|
||||
var remote = f.Remote.Add("Comet", photos);
|
||||
var engine = await f.StartEngineAsync();
|
||||
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Comet", SyncDownloadMode.Originals, f.Archive.Archive.Id);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
var local = Assert.NotNull(Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct)).LocalId);
|
||||
await WaitIdleAsync(f, local);
|
||||
|
||||
// A refresh's 404 forgot the link (the archive was briefly offline); listed again, the pair is asked about again.
|
||||
await f.Sync.Links.DeleteAsync(f.Server, remote.Id, f.Ct);
|
||||
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single(c => c.RemoteId == remote.Id && c.LocalId == local);
|
||||
Assert.True(await f.Sync.Copies.SetStateAsync(pair.Id, pair.State, CopyState.Candidate, null, f.Ct));
|
||||
|
||||
// Download originals of the server-only sequence: it goes back into its own local copy, linked again.
|
||||
job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Comet", SyncDownloadMode.Originals, f.Archive.Archive.Id);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
|
||||
Assert.Equal(local, Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct)).LocalId);
|
||||
Assert.Count(3, await f.Db.Frames.ListBySequenceAsync(local, cancellationToken: f.Ct));
|
||||
Assert.True((await LocalHashesAsync(f, local)).SetEquals(photos.Select(Sha)));
|
||||
var keys = await f.Db.Sequences.ListSessionKeysAsync(f.Archive.Archive.Id, SyncService.SessionKey(remote.Id) + "%", f.Ct);
|
||||
Assert.True(keys.All(k => k.SequenceId == local), "no second local sequence holds a key of the server sequence");
|
||||
Assert.Equal(1, (await f.Db.Sequences.ListAsync(new SequenceQuery(), f.Ct)).Items.Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DownloadingAgainIntoTheOwnLocalCopyOfAPairAskedAgainKeepsItsDeletionsAndDetails()
|
||||
{
|
||||
await using var f = Capable(await SyncFixture.CreateAsync(context));
|
||||
var photos = f.NewPhotos(3);
|
||||
var remote = f.Remote.Add("Comet", photos);
|
||||
var engine = await f.StartEngineAsync();
|
||||
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Comet", SyncDownloadMode.Originals, f.Archive.Archive.Id);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
var local = Assert.NotNull(Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct)).LocalId);
|
||||
await WaitIdleAsync(f, local);
|
||||
|
||||
// While linked: one photo deleted here (the server keeps it, owner Q6) and the title edited; then unlinked and
|
||||
// asked about again (Ask again, or a Keep apart undone).
|
||||
var sequence = (await f.Db.Sequences.GetAsync(local, f.Ct))!;
|
||||
var gone = (await f.Db.Frames.ListBySequenceAsync(local, cancellationToken: f.Ct))[0];
|
||||
var delete = await f.Archive.Service.FrameTrash.PlanDeleteAsync(local, [gone.Id], sequence.FramesVersion, f.Ct);
|
||||
await f.Archive.Service.FrameTrash.DeleteAsync(delete, cancellationToken: f.Ct);
|
||||
await f.Db.Sequences.EditAsync(local, new SequenceEdit { Title = "Mine" }, null, f.Ct);
|
||||
await f.Sync.UnlinkAsync(f.Server, remote.Id, local, f.Ct);
|
||||
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single(c => c.RemoteId == remote.Id && c.LocalId == local);
|
||||
Assert.True(await f.Sync.Copies.SetStateAsync(pair.Id, CopyState.KeptApart, CopyState.Candidate, null, f.Ct));
|
||||
|
||||
// Download originals of the server sequence: it refills its own local copy, as a linked copy.
|
||||
job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Comet", SyncDownloadMode.Originals, f.Archive.Archive.Id);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
|
||||
// The photo deleted here stays deleted, and the title is not overwritten by the server's.
|
||||
Assert.Equal(local, Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct)).LocalId);
|
||||
Assert.Count(2, await f.Db.Frames.ListBySequenceAsync(local, cancellationToken: f.Ct));
|
||||
Assert.Contains(gone.Sha256, (await f.Db.FrameRemovals.ListBySequenceAsync(local, f.Ct)).Select(r => r.Sha256));
|
||||
Assert.Equal("Mine", (await f.Db.Sequences.GetAsync(local, f.Ct))!.Title);
|
||||
Assert.Equal("Comet", remote.Title);
|
||||
Assert.Equal(1, (await f.Db.Sequences.ListAsync(new SequenceQuery(), f.Ct)).Items.Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnUploadOfASequenceAskedAboutAgainMakesANewServerSequenceAndLeavesTheOtherAlone()
|
||||
{
|
||||
await using var f = Capable(await SyncFixture.CreateAsync(context));
|
||||
var photos = f.NewPhotos(3);
|
||||
var local = await f.LocalAsync("Comet", [photos[0], photos[1]]);
|
||||
var engine = await f.StartEngineAsync();
|
||||
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
var first = Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct)).RemoteId;
|
||||
// Unlinked, then asked about again: the pair is a Candidate and nothing links the two.
|
||||
await f.Sync.UnlinkAsync(f.Server, first, local.Id, f.Ct);
|
||||
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single(c => c.RemoteId == first);
|
||||
Assert.True(await f.Sync.Copies.SetStateAsync(pair.Id, CopyState.KeptApart, CopyState.Candidate, null, f.Ct));
|
||||
// Renamed on the server (the web, another desktop); a new photo here.
|
||||
var server = f.Remote.Sequences[first];
|
||||
server.Title = "Comet NAS";
|
||||
server.SettingsVersion++;
|
||||
server.UpdatedAt = DateTimeOffset.UtcNow;
|
||||
await f.AddLocalAsync(local.Id, photos[2]);
|
||||
|
||||
job = await f.Sync.EnqueueUploadAsync(engine, f.Server, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
|
||||
// The other is not joined through the key, linked unasked or overwritten: a new server sequence holds every photo.
|
||||
Assert.Equal("Comet NAS", server.Title);
|
||||
Assert.True(server.Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals([Sha(photos[0]), Sha(photos[1])]));
|
||||
Assert.Equal(CopyState.Candidate, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State);
|
||||
Assert.Null((await f.Sync.Links.GetAsync(f.Server, first, f.Ct))!.LocalId);
|
||||
var link = Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct));
|
||||
Assert.NotEqual(first, link.RemoteId);
|
||||
Assert.True(f.Remote.Sequences[link.RemoteId].Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnUploadThatJoinsAServerSequenceItKnowsAlreadyComparesItsDetailsInsteadOfOverwritingThem()
|
||||
{
|
||||
await using var f = Capable(await SyncFixture.CreateAsync(context));
|
||||
var photos = f.NewPhotos(3);
|
||||
var local = await f.LocalAsync("Comet", [photos[0], photos[1]]);
|
||||
var engine = await f.StartEngineAsync();
|
||||
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
var first = Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct)).RemoteId;
|
||||
// The link and its pair were forgotten (a sweep of 404s: the server served another archive for a while); the
|
||||
// server sequence is listed again, as an observation.
|
||||
var observed = Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, first, f.Ct)) with { LocalId = null };
|
||||
await f.Sync.Links.UpsertAsync(observed, f.Ct);
|
||||
await using (var session = await f.Db.Database.OpenAsync(f.Ct))
|
||||
await session.ExecuteAsync("DELETE FROM found_copies WHERE remote_id = $1", [first], f.Ct);
|
||||
var server = f.Remote.Sequences[first];
|
||||
server.Title = "Comet NAS";
|
||||
server.SettingsVersion++;
|
||||
server.UpdatedAt = DateTimeOffset.UtcNow;
|
||||
await f.AddLocalAsync(local.Id, photos[2]);
|
||||
|
||||
job = await f.Sync.EnqueueUploadAsync(engine, f.Server, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
|
||||
// Joined through this sequence's key, not made by this upload: the server's title is not overwritten unseen.
|
||||
Assert.Equal(first, Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct)).RemoteId);
|
||||
Assert.True(server.Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
|
||||
Assert.Equal("Comet NAS", server.Title);
|
||||
Assert.Equal("Comet", (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.Title);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ARetriedUploadThatJoinedAServerSequenceItKnewStillComparesItsDetails()
|
||||
{
|
||||
await using var f = Capable(await SyncFixture.CreateAsync(context));
|
||||
var photos = f.NewPhotos(4);
|
||||
var local = await f.LocalAsync("Comet", [photos[0], photos[1]]);
|
||||
var engine = await f.StartEngineAsync();
|
||||
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
var first = Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct)).RemoteId;
|
||||
// The link and its pair were forgotten; the server sequence is listed again and renamed there.
|
||||
var observed = Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, first, f.Ct)) with { LocalId = null };
|
||||
await f.Sync.Links.UpsertAsync(observed, f.Ct);
|
||||
await using (var session = await f.Db.Database.OpenAsync(f.Ct))
|
||||
await session.ExecuteAsync("DELETE FROM found_copies WHERE remote_id = $1", [first], f.Ct);
|
||||
var server = f.Remote.Sequences[first];
|
||||
server.Title = "Comet NAS";
|
||||
server.SettingsVersion++;
|
||||
server.UpdatedAt = DateTimeOffset.UtcNow;
|
||||
await f.AddLocalAsync(local.Id, photos[2]);
|
||||
await f.AddLocalAsync(local.Id, photos[3]);
|
||||
// One original unreadable for the first attempt: it fails after joining the known sequence.
|
||||
var damaged = (await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct)).Single(fr => fr.Sha256 == Sha(photos[3]));
|
||||
var path = f.Archive.Paths.FromRelative(damaged.RelativePath);
|
||||
var bytes = await File.ReadAllBytesAsync(path, f.Ct);
|
||||
var broken = bytes.ToArray();
|
||||
broken[^3] ^= 0xFF;
|
||||
await File.WriteAllBytesAsync(path, broken, f.Ct);
|
||||
|
||||
var row = new Job
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Kind = JobKind.UploadCommit,
|
||||
TargetIds = [local.Id],
|
||||
State = JobState.Running,
|
||||
NodeId = "t#0",
|
||||
Created = DateTimeOffset.UtcNow,
|
||||
Started = DateTimeOffset.UtcNow,
|
||||
};
|
||||
await f.Db.Jobs.EnqueueAsync(row, f.Ct);
|
||||
var jobs = new JobEngine(f.Db, [], new JobEngineOptions { WorkerId = "t" });
|
||||
var attempt = new JobContext(jobs, row, f.Ct);
|
||||
await Assert.ThrowsAsync<InvalidDataException>(() => new SyncTransfers(f.Sync).UploadAsync(attempt, f.Remote, local.Id));
|
||||
Assert.Equal(first, Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct)).RemoteId);
|
||||
|
||||
// Retried from that attempt's checkpoint, the original readable again.
|
||||
await File.WriteAllBytesAsync(path, bytes, f.Ct);
|
||||
var retry = new JobContext(jobs, row with { Checkpoint = attempt.Checkpoint }, f.Ct);
|
||||
await new SyncTransfers(f.Sync).UploadAsync(retry, f.Remote, local.Id);
|
||||
|
||||
// Still joined, not made by this upload: the server's title is not overwritten unseen.
|
||||
Assert.True(server.Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
|
||||
Assert.Equal("Comet NAS", server.Title);
|
||||
Assert.Equal("Comet", (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.Title);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnAutomaticUploadAfterTheServerCopyIsGoneFailsAndCreatesNothing()
|
||||
{
|
||||
await using var f = Capable(await SyncFixture.CreateAsync(context));
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var remote = f.Remote.Add("Comet", [photos[0]]);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
var pair = await PairAsync(f, f.Server, local.Id, remote.Id);
|
||||
Assert.True(await f.Sync.Copies.SetStateAsync(pair.Id, null, CopyState.Integrated, new CopyAnswer(null, null, null, true, DateTimeOffset.UtcNow), f.Ct));
|
||||
f.Remote.Sequences.Remove(remote.Id);
|
||||
var engine = await f.StartEngineAsync();
|
||||
|
||||
var job = await f.Sync.EnqueueAutomaticUploadAsync(engine, f.Server, local, f.Ct);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Failed);
|
||||
|
||||
// Never a new server sequence: the automatic photos move only between the two the pair joins.
|
||||
Assert.Empty(f.Remote.Sequences);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnAutomaticUploadOfAPairNoLongerIntegratedSendsNothing()
|
||||
{
|
||||
await using var f = Capable(await SyncFixture.CreateAsync(context));
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var remote = f.Remote.Add("Comet", [photos[0]]);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await PairAsync(f, f.Server, local.Id, remote.Id, CopyState.Linked);
|
||||
var engine = await f.StartEngineAsync();
|
||||
|
||||
var job = await f.Sync.EnqueueAutomaticUploadAsync(engine, f.Server, local, f.Ct);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Failed);
|
||||
|
||||
Assert.Count(1, remote.Frames);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnAutomaticDownloadWithoutTheLocalCopyFailsAndCreatesNoSequence()
|
||||
{
|
||||
await using var f = Capable(await SyncFixture.CreateAsync(context));
|
||||
var remote = f.Remote.Add("Comet", f.NewPhotos(2));
|
||||
var engine = await f.StartEngineAsync();
|
||||
|
||||
var job = await f.Sync.EnqueueAutomaticDownloadAsync(engine, f.Server, remote.Id, "Comet", f.Archive.Archive.Id, f.Ct);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Failed);
|
||||
|
||||
Assert.Equal(0, await f.Db.Sequences.CountAsync(new() { ArchiveId = f.Archive.Archive.Id }, f.Ct));
|
||||
}
|
||||
|
||||
private static Task<FoundCopy> PairAsync(SyncFixture f, string server, Guid localId, Guid remoteId, CopyState state = CopyState.Candidate) =>
|
||||
f.Sync.Copies.UpsertFoundAsync(new FoundCopy
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Kind = CopyKind.LocalServer,
|
||||
LocalId = localId,
|
||||
Server = server,
|
||||
RemoteId = remoteId,
|
||||
Evidence = CopyEvidence.Hashes,
|
||||
Fingerprint = "f",
|
||||
State = state,
|
||||
}, f.Ct);
|
||||
|
||||
[Test]
|
||||
public async Task ALinkedUploadFilesIntoItsTargetWhenTheServerCan()
|
||||
{
|
||||
await using var f = Capable(await SyncFixture.CreateAsync(context));
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var remote = f.Remote.Add("Comet", [photos[0]]);
|
||||
// The server holds the second photo in another sequence: filed into the target all the same.
|
||||
f.Remote.Add("Elsewhere", [photos[1]]);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
var engine = await f.StartEngineAsync();
|
||||
|
||||
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
|
||||
Assert.True(remote.Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
|
||||
Assert.Equal((1, 1), (f.Remote.IntoUploads, f.Remote.CopiedInto));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ALinkedUploadTheServerRefusesIntoItsTargetStillFilesEveryOriginal()
|
||||
{
|
||||
await using var f = Capable(await SyncFixture.CreateAsync(context));
|
||||
// An account with Read and Upload but not Edit, whose local sequence is linked to another account's: 403 for "into".
|
||||
f.Remote.ForbidInto = true;
|
||||
var photos = f.NewPhotos(4);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
var remote = f.Remote.Add("Comet", [photos[0]]);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
var engine = await f.StartEngineAsync();
|
||||
|
||||
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
|
||||
// The refusal falls back to the upload as before the server could file into a target: every original is there.
|
||||
Assert.True(remote.Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
|
||||
Assert.True(f.Remote.RefusedInto >= 1);
|
||||
Assert.Equal(0, f.Remote.IntoUploads);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Render;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Copies;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Data.Tests.Archiving;
|
||||
using Chronos.Protocol;
|
||||
@@ -879,7 +880,7 @@ public sealed class SyncTransferTests(TestContext context)
|
||||
theirs.FirstCapture = mine.FirstCapture;
|
||||
theirs.CameraModel = mine.CameraModel;
|
||||
|
||||
await f.RefreshAsync();
|
||||
await f.RefreshAsync(new SyncPolicy { Linking = CopyLinking.WhenHalfShared });
|
||||
|
||||
var comet = await f.EntryAsync("Comet");
|
||||
Assert.Equal(remote.Id, comet.Link?.RemoteId);
|
||||
|
||||
Reference in new issue
Block a user