feat: found copies foundation (contracts, migration 0012, store, wire, trash and job hooks, keys)
Owner review 6 asks Chronos to recognise the same time-lapse held under different ids on the server and on this PC, compare the copies, and keep them apart or integrate and sync them. This lays the shared foundation the later parcels build on, without any UI or detection yet. - Migration 0012 adds found_copies (local-server and local-local pairs with evidence, scores, answer, policy and the 404 record) and copy_probes; every existing link with a local sequence becomes a Linked pair, so a server deletion and the per-link policy have a place. - FoundCopyStore keeps the pairs: upserts that never touch the answer, a compare-and-set of the state with an Integrating backstop (a failed or cancelled job reads as the previous state), link promotion and demotion, the once-per-refresh 404 count, the merge's links stage (session keys, links reset, pairs moved, refused when both are linked on one server), the local overlap queries and the probes. SyncLinkStore.RekeyAsync moves pairs and probes with the links in the same transaction. - Contracts for detection, review, plans, the Integrate and MergeSequences jobs (kinds 25/26, High level, new detail steps) and the Upload all rule that keeps suspected, kept-apart, deleted, busy and server-born sequences here. - Wire: POST photos/lookup, uploads into a target (IntoTarget/Copied, trailing and optional), frames/delete on the client, capabilities photo-lookup and upload-into, cached per remote. - The trash plans and deletes accept the job that holds the sequence (its own hold is not Busy) and a frames version checked under the lease; a Background job never interrupts a running one. - Settings for linking, the photo policy and projects; the en and it keys of design section 9. Refs #73 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
43719bb5c5
commit
283d04d9cd
57 files changed
+3302
-26
No files matched your search
@@ -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,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,355 @@
|
||||
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 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 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 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;
|
||||
}
|
||||
@@ -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]
|
||||
|
||||
@@ -59,6 +59,134 @@ 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>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);
|
||||
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)
|
||||
{
|
||||
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)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Api;
|
||||
|
||||
/// <summary>
|
||||
/// The wire shapes of found copies (owner review 6, #73): the photo lookup in camelCase with nulls left out, and the upload
|
||||
/// members added trailing and optional, so a client or server of before reads and writes them as it did.
|
||||
/// </summary>
|
||||
public sealed class CopyContractTests
|
||||
{
|
||||
private static readonly Guid SequenceId = Guid.Parse("01890000-0000-7000-8000-000000000002");
|
||||
private static readonly DateTime Captured = new(2026, 10, 1, 18, 0, 0, 123, DateTimeKind.Unspecified);
|
||||
|
||||
[Test]
|
||||
public void ALookupTravelsAsProbesAndHits()
|
||||
{
|
||||
var hash = new string('a', 64);
|
||||
var request = new PhotoLookupRequest(
|
||||
[
|
||||
new PhotoProbe("p1", [hash], [new PhotoKeyDto(25_000_001, Captured)], "upload-1"),
|
||||
new PhotoProbe("p2", [hash]),
|
||||
]);
|
||||
var json = JsonNode.Parse(JsonSerializer.Serialize(request, ProtocolJson.Default.PhotoLookupRequest))!.AsObject();
|
||||
Assert.SequenceEqual(["probes"], json.Select(p => p.Key));
|
||||
Assert.SequenceEqual(["key", "sha256", "unhashed", "sessionKey"], json["probes"]![0]!.AsObject().Select(p => p.Key));
|
||||
Assert.SequenceEqual(["key", "sha256"], json["probes"]![1]!.AsObject().Select(p => p.Key));
|
||||
Assert.SequenceEqual(["size", "capturedAt"], json["probes"]![0]!["unhashed"]![0]!.AsObject().Select(p => p.Key));
|
||||
var back = JsonSerializer.Deserialize(json.ToJsonString(), ProtocolJson.Default.PhotoLookupRequest)!;
|
||||
Assert.Equal(2, back.Probes.Count);
|
||||
Assert.Equal(("p1", "upload-1", Captured), (back.Probes[0].Key, back.Probes[0].SessionKey, back.Probes[0].Unhashed![0].CapturedAt));
|
||||
Assert.Null(back.Probes[1].Unhashed);
|
||||
// The limit counts hashes, unhashed keys and session keys; the count is never sent.
|
||||
Assert.Equal(4, request.CountItems());
|
||||
Assert.Equal((200, 20_000), (PhotoLookupRequest.MaxProbes, PhotoLookupRequest.MaxItems));
|
||||
|
||||
var response = new PhotoLookupResponse([new ProbeResult("p1", [new PhotoLookupHit(SequenceId, 1, 0, 1, true)]), new ProbeResult("p2", [])]);
|
||||
var answer = JsonNode.Parse(JsonSerializer.Serialize(response, ProtocolJson.Default.PhotoLookupResponse))!.AsObject();
|
||||
Assert.SequenceEqual(["sequenceId", "hashes", "removed", "unhashed", "sessionKey"], answer["results"]![0]!["hits"]![0]!.AsObject().Select(p => p.Key));
|
||||
var read = JsonSerializer.Deserialize(answer.ToJsonString(), ProtocolJson.Default.PhotoLookupResponse)!;
|
||||
Assert.Equal(response.Results[0].Hits[0], read.Results[0].Hits[0]);
|
||||
Assert.Empty(read.Results[1].Hits);
|
||||
Assert.Equal(("photo-lookup", "upload-into"), (ServerCapabilities.PhotoLookup, ServerCapabilities.UploadInto));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AnUploadIntoATargetIsAnOptionalTrailingFlag()
|
||||
{
|
||||
// A client of before sends no flag: an upload as before.
|
||||
var old = JsonSerializer.Deserialize(
|
||||
"""{ "sequenceId": null, "fileName": "IMG_0001.JPG", "size": 10, "sha256": "ab", "capturedAt": null, "sessionKey": "upload-1" }""",
|
||||
ProtocolJson.Default.StartUploadRequest)!;
|
||||
Assert.Equal((false, false), (old.Restore, old.IntoTarget));
|
||||
var into = new StartUploadRequest(SequenceId, "IMG_0001.JPG", 10, "ab", null, null, IntoTarget: true);
|
||||
var json = JsonNode.Parse(JsonSerializer.Serialize(into, ProtocolJson.Default.StartUploadRequest))!.AsObject();
|
||||
Assert.Equal("intoTarget", json.Last().Key);
|
||||
Assert.True(json["intoTarget"]!.GetValue<bool>());
|
||||
Assert.True(JsonSerializer.Deserialize(json.ToJsonString(), ProtocolJson.Default.StartUploadRequest)!.IntoTarget);
|
||||
|
||||
// A server of before answers without Copied.
|
||||
var answer = JsonSerializer.Deserialize("""{ "uploadId": null, "chunkSize": 0, "received": [], "alreadyExists": true, "frameId": null }""",
|
||||
ProtocolJson.Default.StartUploadResponse)!;
|
||||
Assert.False(answer.Copied);
|
||||
var copied = new StartUploadResponse(null, 0, [], true, SequenceId, Copied: true);
|
||||
var copiedJson = JsonNode.Parse(JsonSerializer.Serialize(copied, ProtocolJson.Default.StartUploadResponse))!.AsObject();
|
||||
Assert.Equal("copied", copiedJson.Last().Key);
|
||||
var back = JsonSerializer.Deserialize(copiedJson.ToJsonString(), ProtocolJson.Default.StartUploadResponse)!;
|
||||
Assert.Equal(((Guid?)SequenceId, true, true), (back.FrameId, back.AlreadyExists, back.Copied));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user