feat(copies): matches between this PC and the server, Integrate and merge (owner review 6, v1.2.0) (#74)
CI / Build and test (push) Successful in 13m44s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 16s
Release / Build, test and publish (push) Successful in 26m34s
CI / PostgreSQL 16 integration (push) Failing after 17m36s
CI / PostgreSQL 17 integration (push) Failing after 15m36s
CI / Docker image (push) Successful in 1m12s
Release / Server image (push) Failing after 15s
CI / Build and test (push) Successful in 13m44s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 16s
Release / Build, test and publish (push) Successful in 26m34s
CI / PostgreSQL 16 integration (push) Failing after 17m36s
CI / PostgreSQL 17 integration (push) Failing after 15m36s
CI / Docker image (push) Successful in 1m12s
Release / Server image (push) Failing after 15s
The same time-lapse on a server and on this PC under different ids, or twice on this PC, is recognised, compared and settled as the owner asked in owner review 6. Matches are found after each sync refresh, through the server's new photo lookup, and after the jobs that change photos. The default is to ask every time. Server › Matches offers: - Keep apart, which is remembered; - Link only and Unlink; - the Compare dialog: photos, details line by line, projects and the plan. Integrate completes both sides. Photos default to Union, projects are copied across, and a losing version goes to the trash only after a hash check. Afterwards new photos move by themselves, and deletions wait for the user. A merge of two local sequences verifies every photo before the other sequence goes to its archive's trash. Upload all local skips suspected matches and flags them. Migration 0012 adds the found_copies and copy_probes tables. Jobs 25 (Integrate) and 26 (MergeSequences) are new, and so are the server capabilities photo-lookup and upload-into. Refs #73 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #74.
This commit is contained in:
1 parent
43719bb5c5
commit
f33bcac32e
586 files changed
+41546
-280
No files matched your search
@@ -0,0 +1,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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Configuration;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Api;
|
||||
|
||||
/// <summary><c>POST /api/v1/photos/lookup</c> (owner review 6, #73): counts per probe, scoped to the served archive.</summary>
|
||||
[Category("server")]
|
||||
public sealed class PhotoLookupTests(TestContext context)
|
||||
{
|
||||
private static readonly DateTime Shot = new DateTime(2026, 9, 28, 18, 2, 11, 123, DateTimeKind.Unspecified).AddTicks(4560);
|
||||
|
||||
[Test]
|
||||
public async Task EachProbeCountsTheSequencesThatHoldItsPhotos()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
await CountsAsync(server, context);
|
||||
}
|
||||
|
||||
[Test]
|
||||
[RequiresEnvironment("CHRONOS_TEST_PG")]
|
||||
public async Task EachProbeCountsTheSequencesThatHoldItsPhotosOnPostgres()
|
||||
{
|
||||
await using var schema = await PgSchema.CreateAsync(context);
|
||||
await using var server = await schema.StartAsync(context);
|
||||
Assert.Equal(Dialect.Postgres, server.Database.Dialect);
|
||||
await CountsAsync(server, context);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task OnlyTheServedArchiveIsLookedAt()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
await ScopedAsync(server, context);
|
||||
}
|
||||
|
||||
[Test]
|
||||
[RequiresEnvironment("CHRONOS_TEST_PG")]
|
||||
public async Task OnlyTheServedArchiveIsLookedAtOnPostgres()
|
||||
{
|
||||
await using var schema = await PgSchema.CreateAsync(context);
|
||||
await using var server = await schema.StartAsync(context);
|
||||
await ScopedAsync(server, context);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheLookupNeedsTheReadRight()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var (uploader, _, _) = await server.UserAsync("roof-cam", "uploader");
|
||||
using (var refused = await LookupAsync(uploader, new PhotoLookupRequest([new PhotoProbe("a", [Hash('a')])])))
|
||||
await refused.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
|
||||
using (var anonymous = await LookupAsync(server.Client, new PhotoLookupRequest([new PhotoProbe("a", [Hash('a')])])))
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, anonymous.StatusCode);
|
||||
var (viewer, _, _) = await server.UserAsync("guest", "viewer");
|
||||
using var allowed = await LookupAsync(viewer, new PhotoLookupRequest([new PhotoProbe("a", [Hash('a')])]));
|
||||
Assert.Empty(Assert.NotNull(await allowed.ReadAsync(ProtocolJson.Default.PhotoLookupResponse)).Results.Single().Hits);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task MoreThan200ProbesOr20000ItemsAreRefused()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
|
||||
var most = Enumerable.Range(0, PhotoLookupRequest.MaxProbes).Select(i => new PhotoProbe("p" + i, [Hash('b')])).ToList();
|
||||
using (var ok = await LookupAsync(editor, new PhotoLookupRequest(most)))
|
||||
Assert.Equal(PhotoLookupRequest.MaxProbes, (await ok.ReadAsync(ProtocolJson.Default.PhotoLookupResponse)).Results.Count);
|
||||
using (var probes = await LookupAsync(editor, new PhotoLookupRequest([.. most, new PhotoProbe("one more", [Hash('b')])])))
|
||||
await probes.ExpectErrorAsync(HttpStatusCode.RequestEntityTooLarge, "too_many");
|
||||
|
||||
// 20,000 items fit in one request (a body larger than the other JSON calls take); one more does not.
|
||||
var hashes = Enumerable.Range(0, PhotoLookupRequest.MaxItems - 100).Select(i => i.ToString("x64", System.Globalization.CultureInfo.InvariantCulture)).ToList();
|
||||
var unhashed = Enumerable.Range(0, 99).Select(i => new PhotoKeyDto(1000 + i, Shot.AddSeconds(i))).ToList();
|
||||
var full = new PhotoProbe("full", hashes, unhashed, "chronos-sync:" + Guid.NewGuid().ToString("N"));
|
||||
Assert.Equal(PhotoLookupRequest.MaxItems, new PhotoLookupRequest([full]).CountItems());
|
||||
using (var ok = await LookupAsync(editor, new PhotoLookupRequest([full])))
|
||||
Assert.Empty((await ok.ReadAsync(ProtocolJson.Default.PhotoLookupResponse)).Results.Single().Hits);
|
||||
var over = full with { Unhashed = [.. unhashed, new PhotoKeyDto(5, Shot)] };
|
||||
using (var items = await LookupAsync(editor, new PhotoLookupRequest([over])))
|
||||
await items.ExpectErrorAsync(HttpStatusCode.RequestEntityTooLarge, "too_many");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheServerAnnouncesTheLookupAndUploadsIntoATarget()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
using var response = await server.Client.GetAsync("/api/v1/server/info");
|
||||
var info = await response.ReadAsync(ProtocolJson.Default.ServerInfo);
|
||||
Assert.Contains(ServerCapabilities.PhotoLookup, info.Capabilities);
|
||||
Assert.Contains(ServerCapabilities.UploadInto, info.Capabilities);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sequence A holds p1, p2 and p3 (p3 captured at <see cref="Shot"/>); B holds p4, tombstoned p5, replaced p6 by p7 and
|
||||
/// is filed under a session key. One probe counts both, another hits nothing.
|
||||
/// </summary>
|
||||
internal static async Task CountsAsync(TestServer server, TestContext context)
|
||||
{
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var photos = Enumerable.Range(1, 7).Select(i => Uploads.Photo(3000 + i, 700 + i)).ToArray();
|
||||
var a = (await Uploads.UploadAsync(editor, photos[0], "IMG_0001.JPG", sessionKey: "a")).SequenceId;
|
||||
await Uploads.UploadAsync(editor, photos[1], "IMG_0002.JPG", sessionKey: "a");
|
||||
await Uploads.UploadAsync(editor, photos[2], "IMG_0003.JPG", sessionKey: "a", capturedAt: Shot);
|
||||
var b = (await Uploads.UploadAsync(editor, photos[3], "IMG_0004.JPG", sessionKey: "b")).SequenceId;
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
await server.Database.FrameRemovals.SyncSequenceAsync(b,
|
||||
[
|
||||
new FrameRemoval(b, Uploads.Sha(photos[4]), null, RemovalReason.Deleted, now),
|
||||
new FrameRemoval(b, Uploads.Sha(photos[5]), Uploads.Sha(photos[6]), RemovalReason.Replaced, now),
|
||||
// A stale tombstone: B still holds p4, which counts once, as held.
|
||||
new FrameRemoval(b, Uploads.Sha(photos[3]), null, RemovalReason.Deleted, now),
|
||||
], context.Cancellation);
|
||||
var archive = (await server.Database.Sequences.GetAsync(b, context.Cancellation))!.ArchiveId;
|
||||
var key = "chronos-sync:" + Guid.NewGuid().ToString("N");
|
||||
await server.Database.Sequences.MapSessionKeyAsync(archive, key, b, context.Cancellation);
|
||||
|
||||
var probe = new PhotoProbe("local-1",
|
||||
[Uploads.Sha(photos[0]).ToUpperInvariant(), Uploads.Sha(photos[1]), Uploads.Sha(photos[1]), Uploads.Sha(photos[3]), Uploads.Sha(photos[4]),
|
||||
Uploads.Sha(photos[6]), Hash('c')],
|
||||
[
|
||||
// The same millisecond as p3 (the index keeps microseconds); the next millisecond, another size: no match.
|
||||
new PhotoKeyDto(photos[2].Length, new DateTime(2026, 9, 28, 18, 2, 11, 123).AddTicks(9999)),
|
||||
new PhotoKeyDto(photos[2].Length, new DateTime(2026, 9, 28, 18, 2, 11, 124)),
|
||||
new PhotoKeyDto(photos[2].Length + 1, Shot),
|
||||
],
|
||||
key);
|
||||
var nothing = new PhotoProbe("local-2", [Hash('d')], [new PhotoKeyDto(photos[2].Length, Shot.AddDays(1))], "chronos-sync:" + Guid.NewGuid().ToString("N"));
|
||||
using var response = await LookupAsync(editor, new PhotoLookupRequest([probe, nothing]));
|
||||
var results = (await response.ReadAsync(ProtocolJson.Default.PhotoLookupResponse)).Results;
|
||||
|
||||
Assert.SequenceEqual(["local-1", "local-2"], results.Select(r => r.Key));
|
||||
var hits = results[0].Hits.ToDictionary(h => h.SequenceId);
|
||||
Assert.Equal(2, hits.Count);
|
||||
Assert.Equal(new PhotoLookupHit(a, Hashes: 2, Removed: 0, Unhashed: 1, SessionKey: false), hits[a]);
|
||||
Assert.Equal(new PhotoLookupHit(b, Hashes: 1, Removed: 2, Unhashed: 0, SessionKey: true), hits[b]);
|
||||
Assert.Empty(results[1].Hits);
|
||||
}
|
||||
|
||||
/// <summary>A sequence of another archive of the index holding the same photo and session key is never answered.</summary>
|
||||
internal static async Task ScopedAsync(TestServer server, TestContext context)
|
||||
{
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var photo = Uploads.Photo(4000, 801);
|
||||
var mine = (await Uploads.UploadAsync(editor, photo, sessionKey: "mine", capturedAt: Shot)).SequenceId;
|
||||
var key = "chronos-sync:" + Guid.NewGuid().ToString("N");
|
||||
var foreign = await ForeignFrameAsync(server, context, photo, Shot, key);
|
||||
|
||||
using var response = await LookupAsync(editor, new PhotoLookupRequest([new PhotoProbe("x", [Uploads.Sha(photo)], [new PhotoKeyDto(photo.Length, Shot)], key)]));
|
||||
var hit = (await response.ReadAsync(ProtocolJson.Default.PhotoLookupResponse)).Results.Single().Hits.Single();
|
||||
Assert.Equal(new PhotoLookupHit(mine, 1, 0, 1, false), hit);
|
||||
Assert.NotEqual(foreign.SequenceId, hit.SequenceId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A frame of <paramref name="data"/> in a sequence of a second archive of the index (as a desktop sharing its library
|
||||
/// keeps other archives' sequences), its file under that archive's root; optionally filed under <paramref name="sessionKey"/>.
|
||||
/// </summary>
|
||||
internal static async Task<Frame> ForeignFrameAsync(TestServer server, TestContext context, byte[] data, DateTime? capturedAt = null, string? sessionKey = null)
|
||||
{
|
||||
var db = server.Database;
|
||||
var other = new Archive { Id = Guid.CreateVersion7(), Name = "Another archive", RootPath = context.CreateTempDirectory("other-archive"), Created = DateTimeOffset.UtcNow };
|
||||
await db.Archives.UpsertAsync(other, context.Cancellation);
|
||||
var sequence = new Sequence { Id = Guid.CreateVersion7(), ArchiveId = other.Id, Folder = "2026/other", UpdatedAt = DateTimeOffset.UtcNow };
|
||||
await db.Sequences.UpsertAsync(sequence, context.Cancellation);
|
||||
const string relative = "2026/other/originals/0000_IMG_0001.CR3";
|
||||
var path = Path.Combine(other.RootPath, relative);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
await File.WriteAllBytesAsync(path, data, context.Cancellation);
|
||||
var frame = new Frame
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
SequenceId = sequence.Id,
|
||||
Index = 0,
|
||||
RelativePath = relative,
|
||||
FileName = Path.GetFileName(relative),
|
||||
OriginalFileName = "IMG_0001.CR3",
|
||||
Size = data.Length,
|
||||
Sha256 = Uploads.Sha(data),
|
||||
CapturedAt = capturedAt,
|
||||
};
|
||||
await db.Frames.InsertAsync(frame, context.Cancellation);
|
||||
await db.Sequences.RefreshStatsAsync(sequence.Id, context.Cancellation);
|
||||
if (sessionKey is not null) await db.Sequences.MapSessionKeyAsync(other.Id, sessionKey, sequence.Id, context.Cancellation);
|
||||
return frame;
|
||||
}
|
||||
|
||||
internal static Task<HttpResponseMessage> LookupAsync(HttpClient client, PhotoLookupRequest request) =>
|
||||
client.PostAsJsonAsync("/api/v1/photos/lookup", request, ProtocolJson.Default.PhotoLookupRequest);
|
||||
|
||||
private static string Hash(char c) => new(c, 64);
|
||||
}
|
||||
|
||||
/// <summary>A throw-away schema on the PostgreSQL test server (<c>CHRONOS_TEST_PG</c>), selected through <c>Search Path</c>.</summary>
|
||||
internal sealed class PgSchema : IAsyncDisposable
|
||||
{
|
||||
private readonly IDatabase _admin;
|
||||
private readonly string _name;
|
||||
|
||||
private PgSchema(IDatabase admin, string name, string connectionString)
|
||||
{
|
||||
_admin = admin;
|
||||
_name = name;
|
||||
ConnectionString = connectionString;
|
||||
}
|
||||
|
||||
public string ConnectionString { get; }
|
||||
|
||||
public static async Task<PgSchema> CreateAsync(TestContext context)
|
||||
{
|
||||
var baseConnection = Environment.GetEnvironmentVariable("CHRONOS_TEST_PG")!;
|
||||
var admin = DatabaseFactory.Open(DatabaseOptions.Postgres(baseConnection));
|
||||
var name = "chronos_l_" + Guid.NewGuid().ToString("N")[..16];
|
||||
await using (var session = await admin.OpenAsync(context.Cancellation))
|
||||
await session.ExecuteScriptAsync($"CREATE SCHEMA {name}", context.Cancellation);
|
||||
return new PgSchema(admin, name, baseConnection.TrimEnd(';', ' ') + $";Search Path={name}");
|
||||
}
|
||||
|
||||
/// <summary>A test server on this schema.</summary>
|
||||
public Task<TestServer> StartAsync(TestContext context, Action<ServerOptions>? configure = null,
|
||||
Action<Microsoft.Extensions.DependencyInjection.IServiceCollection>? services = null) =>
|
||||
TestServer.StartAsync(context, o =>
|
||||
{
|
||||
o.Database = DatabaseKind.Postgres;
|
||||
o.DbConnectionString = ConnectionString;
|
||||
configure?.Invoke(o);
|
||||
}, services);
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await using (var session = await _admin.OpenAsync(CancellationToken.None))
|
||||
await session.ExecuteScriptAsync($"DROP SCHEMA IF EXISTS {_name} CASCADE", CancellationToken.None);
|
||||
await _admin.DisposeAsync();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Events;
|
||||
using Chronos.Server.Tests.Api;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="StartUploadRequest.IntoTarget"/> (owner review 6, #73): a photo another sequence of the served archive holds is
|
||||
/// copied into the target by the server itself, authorised and scoped on the server.
|
||||
/// </summary>
|
||||
[Category("server")]
|
||||
public sealed class UploadIntoTests(TestContext context)
|
||||
{
|
||||
private static readonly DateTime Shot = new(2026, 9, 28, 18, 2, 11, 250, DateTimeKind.Unspecified);
|
||||
|
||||
[Test]
|
||||
public async Task APhotoHeldElsewhereIsCopiedIntoTheTargetAndChargedOnce()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
await CopiedAsync(server, context);
|
||||
}
|
||||
|
||||
[Test]
|
||||
[RequiresEnvironment("CHRONOS_TEST_PG")]
|
||||
public async Task APhotoHeldElsewhereIsCopiedIntoTheTargetAndChargedOnceOnPostgres()
|
||||
{
|
||||
await using var schema = await PgSchema.CreateAsync(context);
|
||||
await using var server = await schema.StartAsync(context);
|
||||
Assert.Equal(Dialect.Postgres, server.Database.Dialect);
|
||||
await CopiedAsync(server, context);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ACommitThatFindsThePhotoFiledMeanwhileChargesNothing()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: s =>
|
||||
{
|
||||
s.AddSingleton<RacingIngest>();
|
||||
s.AddSingleton<IArchiveIngest>(sp => sp.GetRequiredService<RacingIngest>());
|
||||
});
|
||||
var scene = await SceneAsync(server);
|
||||
var racing = server.Services.GetRequiredService<RacingIngest>();
|
||||
Guid? raced = null;
|
||||
// Another writer files the same photo into the target just before this commit: the ingest answers a duplicate.
|
||||
racing.Before = async request =>
|
||||
{
|
||||
var copy = request.StagedPath + ".race";
|
||||
File.Copy(request.StagedPath, copy);
|
||||
raced = (await racing.Inner.CommitAsync(request with { StagedPath = copy }, context.Cancellation)).FrameId;
|
||||
};
|
||||
var used = await UsedAsync(scene.Editor);
|
||||
|
||||
using var response = await StartIntoAsync(scene.Editor, scene.Photo, scene.Target);
|
||||
var answer = await response.ReadAsync(ProtocolJson.Default.StartUploadResponse);
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.True(answer.AlreadyExists && answer.Copied);
|
||||
Assert.Equal(Assert.NotNull(raced), answer.FrameId);
|
||||
Assert.Equal(used, await UsedAsync(scene.Editor));
|
||||
Assert.Empty(Directory.EnumerateFiles(server.Options.StagingPath));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheCopyIsRefusedBeyondTheQuota()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
// The two uploads of the scene take 9,000 bytes; copying the 5,000-byte photo would take the account beyond 10,000.
|
||||
var scene = await SceneAsync(server, quota: 10_000);
|
||||
using var response = await StartIntoAsync(scene.Editor, scene.Photo, scene.Target);
|
||||
await response.ExpectErrorAsync(HttpStatusCode.Forbidden, "quota_exceeded");
|
||||
Assert.Empty(await FramesOfAsync(server, scene.Target, scene.Photo));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task OnlyTheOwnerAnAdminOrAnEditorMayUploadIntoATarget()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var scene = await SceneAsync(server);
|
||||
var (uploader, _, _) = await server.UserAsync("roof-cam", "uploader");
|
||||
|
||||
// An upload-only account may not file into another account's sequence.
|
||||
using (var refused = await StartIntoAsync(uploader, scene.Photo, scene.Target))
|
||||
await refused.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
|
||||
Assert.Empty(await FramesOfAsync(server, scene.Target, scene.Photo));
|
||||
|
||||
// Into its own sequence it may: the server copies the photo the editor's sequence holds.
|
||||
var own = (await Uploads.UploadAsync(uploader, Uploads.Photo(3000, 903), "IMG_0200.CR3", sessionKey: "roof")).SequenceId;
|
||||
using (var allowed = await StartIntoAsync(uploader, scene.Photo, own))
|
||||
Assert.True((await allowed.ReadAsync(ProtocolJson.Default.StartUploadResponse)).Copied);
|
||||
Assert.Count(1, await FramesOfAsync(server, own, scene.Photo));
|
||||
|
||||
// An administrator may.
|
||||
var admin = await server.AdminAsync();
|
||||
using (var byAdmin = await StartIntoAsync(admin, scene.Photo, scene.Target))
|
||||
Assert.True((await byAdmin.ReadAsync(ProtocolJson.Default.StartUploadResponse)).Copied);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ATargetOfAnotherArchiveIsUnknown()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var scene = await SceneAsync(server);
|
||||
var foreign = await PhotoLookupTests.ForeignFrameAsync(server, context, Uploads.Photo(2000, 904));
|
||||
using (var other = await StartIntoAsync(scene.Editor, scene.Photo, foreign.SequenceId))
|
||||
Assert.Equal("sequence", (await other.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found")).Details);
|
||||
using (var unknown = await StartIntoAsync(scene.Editor, scene.Photo, Guid.CreateVersion7()))
|
||||
await unknown.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
|
||||
Assert.Empty(await FramesOfAsync(server, foreign.SequenceId, scene.Photo));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnUploadIntoATargetNamesItAndNeverRestores()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var scene = await SceneAsync(server);
|
||||
using (var restore = await StartIntoAsync(scene.Editor, scene.Photo, scene.Target, restore: true))
|
||||
Assert.Equal("restore", (await restore.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request")).Details);
|
||||
using (var none = await StartIntoAsync(scene.Editor, scene.Photo, null))
|
||||
Assert.Equal("sequenceId", (await none.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request")).Details);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ATargetThatHoldsThePhotoAnswersItsFrame()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var scene = await SceneAsync(server);
|
||||
using var response = await StartIntoAsync(scene.Editor, scene.Photo, scene.Held.SequenceId);
|
||||
var answer = await response.ReadAsync(ProtocolJson.Default.StartUploadResponse);
|
||||
Assert.True(answer.AlreadyExists);
|
||||
Assert.False(answer.Copied);
|
||||
Assert.Equal(scene.Held.FrameId, answer.FrameId);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task APhotoTheTargetDeletedStaysDeleted()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var scene = await SceneAsync(server);
|
||||
await server.Database.FrameRemovals.SyncSequenceAsync(scene.Target,
|
||||
[new FrameRemoval(scene.Target, Uploads.Sha(scene.Photo), null, RemovalReason.Deleted, DateTimeOffset.UtcNow)], context.Cancellation);
|
||||
var requests = server.Services.GetRequiredService<FakeArchiveIngest>().Requests.Count;
|
||||
|
||||
using var response = await StartIntoAsync(scene.Editor, scene.Photo, scene.Target);
|
||||
var answer = await response.ReadAsync(ProtocolJson.Default.StartUploadResponse);
|
||||
Assert.True(answer.AlreadyExists);
|
||||
Assert.Null(answer.FrameId);
|
||||
Assert.False(answer.Copied);
|
||||
Assert.Empty(await FramesOfAsync(server, scene.Target, scene.Photo));
|
||||
Assert.Equal(requests, server.Services.GetRequiredService<FakeArchiveIngest>().Requests.Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task APhotoOnlyAnotherArchiveHoldsIsUploaded()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var scene = await SceneAsync(server);
|
||||
var elsewhere = Uploads.Photo(2500, 905);
|
||||
await PhotoLookupTests.ForeignFrameAsync(server, context, elsewhere);
|
||||
|
||||
using var response = await StartIntoAsync(scene.Editor, elsewhere, scene.Target);
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
var answer = await response.ReadAsync(ProtocolJson.Default.StartUploadResponse);
|
||||
Assert.NotNull(answer.UploadId);
|
||||
Assert.False(answer.AlreadyExists || answer.Copied);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ADamagedSourceLeavesTheClientToSendThePhoto()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var scene = await SceneAsync(server);
|
||||
// The file keeps its size, so the frame reads as intact; its bytes are no longer the photo.
|
||||
var source = Assert.NotNull(await server.Database.Frames.GetAsync(scene.Held.FrameId));
|
||||
await File.WriteAllBytesAsync(Path.Combine(server.Options.ArchivePath, source.RelativePath), Uploads.Photo(scene.Photo.Length, 906), context.Cancellation);
|
||||
|
||||
using (var response = await StartIntoAsync(scene.Editor, scene.Photo, scene.Target))
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
var answer = await response.ReadAsync(ProtocolJson.Default.StartUploadResponse);
|
||||
Assert.NotNull(answer.UploadId);
|
||||
Assert.False(answer.Copied);
|
||||
}
|
||||
Assert.Empty(Directory.EnumerateFiles(server.Options.StagingPath));
|
||||
Assert.Empty(await FramesOfAsync(server, scene.Target, scene.Photo));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WithoutIntoTargetACopyElsewhereStillStandsIn()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var scene = await SceneAsync(server);
|
||||
var used = await UsedAsync(scene.Editor);
|
||||
var answer = await Uploads.StartAsync(scene.Editor, scene.Photo, sequenceId: scene.Target, expected: HttpStatusCode.OK);
|
||||
Assert.True(answer.AlreadyExists);
|
||||
Assert.False(answer.Copied);
|
||||
Assert.Equal(scene.Held.FrameId, answer.FrameId);
|
||||
Assert.Empty(await FramesOfAsync(server, scene.Target, scene.Photo));
|
||||
Assert.Equal(used, await UsedAsync(scene.Editor));
|
||||
}
|
||||
|
||||
/// <summary>The copy lands in the target with the photo's bytes, charged once, announced, and answered from the target after.</summary>
|
||||
internal static async Task CopiedAsync(TestServer server, TestContext context)
|
||||
{
|
||||
var scene = await SceneAsync(server);
|
||||
var used = await UsedAsync(scene.Editor);
|
||||
using var events = server.Services.GetRequiredService<EventHub>().Subscribe();
|
||||
|
||||
StartUploadResponse answer;
|
||||
using (var response = await StartIntoAsync(scene.Editor, scene.Photo, scene.Target))
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
answer = await response.ReadAsync(ProtocolJson.Default.StartUploadResponse);
|
||||
}
|
||||
Assert.True(answer.AlreadyExists && answer.Copied);
|
||||
Assert.Null(answer.UploadId);
|
||||
var frame = Assert.NotNull(await server.Database.Frames.GetAsync(Assert.NotNull(answer.FrameId), context.Cancellation));
|
||||
Assert.Equal(scene.Target, frame.SequenceId);
|
||||
Assert.Equal(Uploads.Sha(scene.Photo), frame.Sha256);
|
||||
await Http.BytesEqualAsync(scene.Photo, File.ReadAllBytesAsync(Path.Combine(server.Options.ArchivePath, frame.RelativePath)));
|
||||
Assert.NotNull(await server.Database.Frames.GetAsync(scene.Held.FrameId, context.Cancellation));
|
||||
var request = Assert.NotNull(server.Services.GetRequiredService<FakeArchiveIngest>().Requests.LastOrDefault());
|
||||
Assert.Equal(scene.Target, request.SequenceId);
|
||||
Assert.True(request.RefuseRemoved, "the copy refuses a photo the target deleted");
|
||||
Assert.Equal(scene.Photo.Length, request.Size);
|
||||
Assert.True(request.StagedPath.StartsWith(server.Options.StagingPath, StringComparison.Ordinal), request.StagedPath);
|
||||
Assert.Empty(Directory.EnumerateFiles(server.Options.StagingPath));
|
||||
Assert.Equal(used + scene.Photo.Length, await UsedAsync(scene.Editor));
|
||||
|
||||
using (var wait = CancellationTokenSource.CreateLinkedTokenSource(context.Cancellation))
|
||||
{
|
||||
wait.CancelAfter(TimeSpan.FromSeconds(10));
|
||||
while (await events.Reader.ReadAsync(wait.Token) is var e)
|
||||
{
|
||||
if (e is SequenceChangedEvent { Change: "frames" } changed && changed.SequenceId == scene.Target) break;
|
||||
}
|
||||
}
|
||||
|
||||
// Asked again, the target answers with its own copy, charged nothing more.
|
||||
using (var again = await StartIntoAsync(scene.Editor, scene.Photo, scene.Target))
|
||||
{
|
||||
var repeated = await again.ReadAsync(ProtocolJson.Default.StartUploadResponse);
|
||||
Assert.True(repeated.AlreadyExists);
|
||||
Assert.False(repeated.Copied);
|
||||
Assert.Equal(frame.Id, repeated.FrameId);
|
||||
}
|
||||
Assert.Equal(used + scene.Photo.Length, await UsedAsync(scene.Editor));
|
||||
Assert.Count(1, await FramesOfAsync(server, scene.Target, scene.Photo));
|
||||
}
|
||||
|
||||
/// <summary>An editor's sequence A holding a 5,000-byte photo, and the editor's sequence B (the target) holding another photo.</summary>
|
||||
private static async Task<Scene> SceneAsync(TestServer server, long quota = 0)
|
||||
{
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor", quotaBytes: quota);
|
||||
var photo = Uploads.Photo(5000, 901);
|
||||
var held = await Uploads.UploadAsync(editor, photo, "IMG_0001.CR3", sessionKey: "a", capturedAt: Shot);
|
||||
var target = (await Uploads.UploadAsync(editor, Uploads.Photo(4000, 902), "IMG_0100.CR3", sessionKey: "b")).SequenceId;
|
||||
return new Scene(editor, photo, held, target);
|
||||
}
|
||||
|
||||
private static Task<HttpResponseMessage> StartIntoAsync(HttpClient client, byte[] data, Guid? target, bool restore = false) =>
|
||||
client.PostAsJsonAsync("/api/v1/uploads", new StartUploadRequest(target, "IMG_0001.CR3", data.Length, Uploads.Sha(data), Shot, null, restore, IntoTarget: true),
|
||||
ProtocolJson.Default.StartUploadRequest);
|
||||
|
||||
private static async Task<long> UsedAsync(HttpClient client)
|
||||
{
|
||||
using var me = await client.GetAsync("/api/v1/auth/me");
|
||||
return (await me.ReadAsync(ProtocolJson.Default.UserDto)).UsedBytes;
|
||||
}
|
||||
|
||||
private static async Task<IReadOnlyList<Frame>> FramesOfAsync(TestServer server, Guid sequenceId, byte[] photo) =>
|
||||
[.. (await server.Database.Frames.FindBySha256Async(Uploads.Sha(photo))).Where(f => f.SequenceId == sequenceId)];
|
||||
|
||||
private sealed record Scene(HttpClient Editor, byte[] Photo, CompleteUploadResponse Held, Guid Target);
|
||||
|
||||
/// <summary>The fake ingest, with a step that runs once just before the next commit (another writer filing the same photo).</summary>
|
||||
private sealed class RacingIngest(FakeArchiveIngest inner) : IArchiveIngest
|
||||
{
|
||||
public FakeArchiveIngest Inner => inner;
|
||||
|
||||
public Func<IngestRequest, Task>? Before { get; set; }
|
||||
|
||||
public async Task<IngestResult> CommitAsync(IngestRequest request, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (Before is { } before)
|
||||
{
|
||||
Before = null;
|
||||
await before(request);
|
||||
}
|
||||
return await inner.CommitAsync(request, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
using System.Security.Cryptography;
|
||||
using Chronos.Core.Codecs.Jpeg;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Metadata;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Copies;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Data.Repositories;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Protocol.Client;
|
||||
using Chronos.Server.Storage;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Sync;
|
||||
|
||||
/// <summary>
|
||||
/// The owner's scenario of review 6 (#73) end to end, against a real in-process server: a time-lapse uploaded from this PC,
|
||||
/// an old copy of it found again on a disk adopted as an archive, compared, kept apart, integrated (Union) both ways with
|
||||
/// the details settled line by line and the projects copied across, its new photos moving by themselves unless the
|
||||
/// connection is metered, Upload all local leaving a suspected copy out, and two copies on this PC merged into one.
|
||||
/// </summary>
|
||||
[Category("server")]
|
||||
[Timeout(300_000)]
|
||||
public sealed class CopyScenarioTests(TestContext context)
|
||||
{
|
||||
private const string PcName = "STUDIO";
|
||||
private const string ServerName = "Test server";
|
||||
private static readonly DateTime Start = new(2026, 9, 28, 18, 0, 0);
|
||||
private static readonly TimeSpan Deadline = TimeSpan.FromSeconds(60);
|
||||
|
||||
private CancellationToken Ct => context.Cancellation;
|
||||
|
||||
[Test]
|
||||
public async Task AnOldCopyFoundOnAnAdoptedDiskIsIntegratedWithTheServerAndMergedOnThisPc()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = 64 * 1024, ArchiveModule.Register);
|
||||
var (_, _, token) = await server.UserAsync("alberto", "editor");
|
||||
await using var pc = await Pc.StartAsync(context, server, token);
|
||||
|
||||
// 1. A time-lapse of eight photos, rated 4, uploaded from this PC.
|
||||
// Photo 3 carries the camera's sub-second time: two versions of it at that instant under one name are one photo that differs.
|
||||
static DateTime Captured(int i) => Start.AddSeconds(10 * i).AddMilliseconds(i == 3 ? 250 : 0);
|
||||
var photos = Enumerable.Range(1, 8).Select(i => Jpeg(Captured(i), i)).ToList();
|
||||
var original = await pc.LocalAsync(pc.Main, "Comet over the ridge", photos.Select((p, i) => (p, Captured(i + 1))).ToList());
|
||||
original = (await pc.Db.Sequences.EditAsync(original.Id, new SequenceEdit { Rating = 4 }, null, Ct)).Sequence!;
|
||||
await pc.WaitAsync((await pc.Sync.EnqueueUploadAsync(pc.Jobs, pc.Server, original, Ct)).Id);
|
||||
var remoteId = (await pc.Sync.LinkOfAsync(pc.Server, original.Id, Ct))!.RemoteId;
|
||||
var onServer = Assert.NotNull(await server.Database.Sequences.GetAsync(remoteId));
|
||||
Assert.True((await server.Database.Frames.ListBySequenceAsync(remoteId)).Select(f => f.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
|
||||
await ServerIdleAsync(server);
|
||||
// Freed on this PC since: the server holds it.
|
||||
await pc.Archives.DeleteAsync(await pc.Archives.PlanDeleteAsync([original.Id], cancellationToken: Ct), "alberto", cancellationToken: Ct);
|
||||
await pc.Sync.RefreshAsync(pc.Remote, Policy, Ct);
|
||||
Assert.Null(await pc.Sync.LinkOfAsync(pc.Server, original.Id, Ct));
|
||||
|
||||
// 2. An old disk adopted as an archive: photos 1-6 (photo 3 in another version), two more of its own, another title and rating.
|
||||
var manifest = await pc.Remote.GetManifestAsync(remoteId, Ct);
|
||||
var names = manifest.Frames.OrderBy(f => f.Index).Select(f => f.FileName).ToList();
|
||||
var diskRoot = context.CreateTempDirectory("old-disk");
|
||||
var folder = Path.Combine(diskRoot, "2026-09-28 comet");
|
||||
Directory.CreateDirectory(folder);
|
||||
var differing = Jpeg(Captured(3), 103);
|
||||
var extras = new[] { Jpeg(Start.AddSeconds(5), 201), Jpeg(Start.AddSeconds(75), 202) };
|
||||
for (var i = 0; i < 6; i++) await File.WriteAllBytesAsync(Path.Combine(folder, names[i]), i == 2 ? differing : photos[i], Ct);
|
||||
await File.WriteAllBytesAsync(Path.Combine(folder, "IMG_9001.JPG"), extras[0], Ct);
|
||||
await File.WriteAllBytesAsync(Path.Combine(folder, "IMG_9002.JPG"), extras[1], Ct);
|
||||
var disk = await pc.Archives.AdoptAsync(diskRoot, "Old disk", Ct);
|
||||
await pc.Archives.Indexer.ScanAsync(disk, ScanMode.Full, null, _ => ValueTask.CompletedTask, Ct);
|
||||
var old = Assert.NotNull((await pc.Db.Sequences.ListAsync(new SequenceQuery { ArchiveId = disk.Id }, Ct)).Items.SingleOrDefault());
|
||||
old = (await pc.Db.Sequences.EditAsync(old.Id, new SequenceEdit { Title = "Old disk comet", Rating = 2 }, null, Ct)).Sequence!;
|
||||
Assert.Equal(8, old.FrameCount);
|
||||
|
||||
// 3. Detection with Ask always (a refresh in the background): the match is listed, told, and not linked.
|
||||
var told = new List<CopyFindResult>();
|
||||
pc.Copies.Found += told.Add;
|
||||
await pc.Sync.RefreshAsync(pc.Remote, Policy, Ct);
|
||||
var pair = Assert.Contains(await pc.Copies.ListAsync(Ct), v => v.Copy.LocalId == old.Id).Copy;
|
||||
Assert.Equal((CopyKind.LocalServer, CopyState.Candidate, (Guid?)remoteId), (pair.Kind, pair.State, pair.RemoteId));
|
||||
Assert.Contains(told.SelectMany(r => r.New), c => c.Id == pair.Id);
|
||||
Assert.Empty(told.SelectMany(r => r.AutoLinked));
|
||||
Assert.Null(await pc.Sync.LinkOfAsync(pc.Server, old.Id, Ct));
|
||||
|
||||
// 4. Verified (an adopted folder holds no hashes until then), the comparison shows each class of photo.
|
||||
await pc.Archives.Verifier.VerifyAsync(disk, [old.Id], default, (_, _, _) => ValueTask.CompletedTask, cancellationToken: Ct);
|
||||
var review = await pc.Copies.CompareAsync(pair.Id, pc.Remote, Ct);
|
||||
int Count(PhotoClass c) => review.Photos.Photos.Count(p => p.Class == c);
|
||||
Assert.Equal((5, 2, 2, 1), (Count(PhotoClass.Same), Count(PhotoClass.OnlyHere), Count(PhotoClass.OnlyThere), Count(PhotoClass.Differs)));
|
||||
Assert.True(review.Photos.Photos.Where(p => p.Class == PhotoClass.OnlyThere).Select(p => p.There!.Sha256).ToHashSet().SetEquals([Sha(photos[6]), Sha(photos[7])]));
|
||||
Assert.True(review.Photos.Photos.Where(p => p.Class == PhotoClass.OnlyHere).Select(p => p.Here!.Sha256).ToHashSet().SetEquals(extras.Select(Sha)));
|
||||
var differs = review.Photos.Photos.Single(p => p.Class == PhotoClass.Differs);
|
||||
Assert.Equal((Sha(differing), Sha(photos[2])), (differs.Here!.Sha256, differs.There!.Sha256));
|
||||
Assert.Contains(review.Details, d => d.Path == "sequence.title" && d.Here == "Old disk comet" && d.There == onServer.Title);
|
||||
Assert.Contains(review.Details, d => d.Path == "sequence.rating" && d.Here == "2" && d.There == onServer.Rating.ToString(System.Globalization.CultureInfo.InvariantCulture));
|
||||
|
||||
// 5. Keep apart is remembered across refreshes; Ask again brings it back.
|
||||
await pc.Copies.KeepApartAsync(pair.Id, Ct);
|
||||
for (var i = 0; i < 2; i++)
|
||||
{
|
||||
await pc.Sync.Finder.ResetProbesAsync(pc.Server, Ct);
|
||||
await pc.Sync.RefreshAsync(pc.Remote, Policy, Ct);
|
||||
}
|
||||
Assert.Equal(CopyState.KeptApart, (await pc.Sync.Copies.GetAsync(pair.Id, Ct))!.State);
|
||||
Assert.Null(await pc.Sync.LinkOfAsync(pc.Server, old.Id, Ct));
|
||||
await pc.Copies.AskAgainAsync(pair.Id, Ct);
|
||||
|
||||
// 6. A project other than Main on each side, under one name, each edited its own way.
|
||||
await ProjectAsync(new ArchiveProjectHome(pc.Db, pc.Archives.Projects, old.Id), "Vertical", 41);
|
||||
await ProjectAsync(pc.ServerHome(remoteId), "Vertical", 33);
|
||||
|
||||
// 7. Integrate with Union: the server's title, this PC's rating, the rest the server's; the projects copied across.
|
||||
review = await pc.Copies.CompareAsync(pair.Id, pc.Remote, Ct);
|
||||
var details = review.Details.Select(d => d.Path).Distinct()
|
||||
.ToDictionary(p => p, p => p == "sequence.rating" ? CopySide.ThisPc : CopySide.Other);
|
||||
var plan = await pc.Copies.PlanIntegrateAsync(pair.Id, pc.Remote,
|
||||
new IntegrateChoices(CopyPhotoPolicy.Union, new Dictionary<string, PhotoChoice>(), details, CopyProjects.CopyAcross), Ct);
|
||||
Assert.True(plan.CanApply, string.Join(", ", plan.Blocks));
|
||||
Assert.Equal((0, true, false), (plan.LeftOut, plan.AutoPhotos, plan.Destructive));
|
||||
Assert.SequenceEqual(["Other:Vertical (Test server)", "ThisPc:Vertical (STUDIO)"],
|
||||
plan.Projects.Select(p => $"{p.From}:{p.TargetName}").Order(StringComparer.Ordinal));
|
||||
await pc.WaitAsync((await pc.Copies.EnqueueIntegrateAsync(pc.Jobs, plan, Ct)).Id);
|
||||
|
||||
var union = photos.Select(Sha).Concat(extras.Select(Sha)).Append(Sha(differing)).ToHashSet(StringComparer.Ordinal);
|
||||
Assert.True((await LocalHashesAsync(pc, old.Id)).SetEquals(union), "this PC holds every photo of both, both versions of photo 3");
|
||||
Assert.True((await server.Database.Frames.ListBySequenceAsync(remoteId)).Select(f => f.Sha256!).ToHashSet().SetEquals(union), "and so does the server");
|
||||
var here = (await pc.Db.Sequences.GetAsync(old.Id, Ct))!;
|
||||
var there = (await server.Database.Sequences.GetAsync(remoteId))!;
|
||||
Assert.Equal((onServer.Title, 2), (here.Title, here.Rating));
|
||||
Assert.Equal((onServer.Title, 2), (there.Title, there.Rating));
|
||||
static List<string> Names(IEnumerable<SequenceProject> list) => [.. list.Where(p => !p.IsMain).Select(p => p.Name).Order(StringComparer.Ordinal)];
|
||||
Assert.SequenceEqual(["Vertical", "Vertical (Test server)"], Names(await pc.Archives.Projects.ListAsync(old.Id, Ct)));
|
||||
Assert.SequenceEqual(["Vertical", "Vertical (STUDIO)"], Names(await pc.ServerHome(remoteId).ListAsync(Ct)));
|
||||
var integrated = (await pc.Sync.Copies.GetAsync(pair.Id, Ct))!;
|
||||
Assert.Equal((CopyState.Integrated, true), (integrated.State, integrated.AutoPhotos));
|
||||
Assert.Equal(remoteId, (await pc.Sync.LinkOfAsync(pc.Server, old.Id, Ct))?.RemoteId);
|
||||
await ServerIdleAsync(server);
|
||||
|
||||
// 8. A new photo on this PC moves to the server by itself, but not while the connection is metered.
|
||||
var later = Jpeg(Start.AddSeconds(200), 301);
|
||||
await pc.AddPhotoAsync(disk, old.Id, later, Start.AddSeconds(200));
|
||||
var held = await pc.StopJobsAsync();
|
||||
await using (var agent = new SyncAgent(pc.Sync, pc.Remote, () => Policy, held, new SyncAgentOptions
|
||||
{
|
||||
RefreshInterval = TimeSpan.FromHours(1),
|
||||
EventDelay = TimeSpan.FromMilliseconds(20),
|
||||
MinBackoff = TimeSpan.FromMilliseconds(20),
|
||||
MaxBackoff = TimeSpan.FromMilliseconds(200),
|
||||
}))
|
||||
{
|
||||
await agent.RefreshAsync(Ct);
|
||||
var automatic = (await pc.Db.Jobs.ListAsync(JobState.Queued, JobKind.UploadCommit, 10, cancellationToken: Ct)).Items.Single();
|
||||
Assert.Equal((old.Id, JobPriority.Background), (automatic.TargetIds.Single(), automatic.Priority));
|
||||
// Metered: the hold pauses the transfers with the server (UploadHold, the desktop's, does this on Windows).
|
||||
await held.PauseAsync(automatic.Id, Ct);
|
||||
await held.StartAsync(Ct);
|
||||
await Task.Delay(TimeSpan.FromSeconds(1), Ct);
|
||||
Assert.Equal(JobState.Paused, (await pc.Db.Jobs.GetAsync(automatic.Id, Ct))!.State);
|
||||
Assert.DoesNotContain(Sha(later), (await server.Database.Frames.ListBySequenceAsync(remoteId)).Select(f => f.Sha256));
|
||||
// No longer metered: it goes on.
|
||||
await held.ResumeAsync(automatic.Id, Ct);
|
||||
await pc.WaitAsync(automatic.Id);
|
||||
Assert.Contains(Sha(later), (await server.Database.Frames.ListBySequenceAsync(remoteId)).Select(f => f.Sha256));
|
||||
}
|
||||
|
||||
// 9. Upload all local: a copy filed again from the card is a suspected duplicate, skipped and flagged; the rest goes.
|
||||
var card = await pc.LocalAsync(pc.Main, "Comet from the card", [(photos[0], Start.AddSeconds(10)), (photos[1], Start.AddSeconds(20)),
|
||||
(Jpeg(Start.AddSeconds(210), 401), Start.AddSeconds(210))]);
|
||||
var other = await pc.LocalAsync(pc.Main, "Harbour", [(Jpeg(Start.AddDays(1), 501), Start.AddDays(1)), (Jpeg(Start.AddDays(1).AddSeconds(10), 502), Start.AddDays(1).AddSeconds(10))]);
|
||||
await pc.Copies.FindAsync(pc.Remote, Ct);
|
||||
var local = Assert.Contains(await pc.Copies.ListAsync(Ct), v => v.Copy.Kind == CopyKind.LocalLocal).Copy;
|
||||
Assert.True(new[] { local.LocalId, local.OtherId!.Value }.ToHashSet().SetEquals([old.Id, card.Id]));
|
||||
Assert.Equal(CopyState.Candidate, local.State);
|
||||
var entries = (await pc.Sync.ListAsync(pc.Server, Ct)).Where(e => e.Status == SyncStatus.LocalOnly);
|
||||
var (upload, skipped) = UploadAllRule.Select(entries, await pc.Copies.ListAllPairsAsync(Ct), new HashSet<Guid>(), new HashSet<Guid>());
|
||||
Assert.Equal((card.Id, UploadSkip.SuspectedCopy), (skipped.Single().Entry.Local!.Id, skipped.Single().Why));
|
||||
Assert.Equal(other.Id, upload.Single().Local!.Id);
|
||||
await pc.WaitAsync((await pc.Sync.EnqueueUploadAsync(held, pc.Server, upload.Single().Local!, Ct)).Id);
|
||||
Assert.NotNull(await pc.Sync.LinkOfAsync(pc.Server, other.Id, Ct));
|
||||
Assert.Null(await pc.Sync.LinkOfAsync(pc.Server, card.Id, Ct));
|
||||
|
||||
// 10. The two copies on this PC merge into the linked one; the other goes to the archive trash once every photo is verified there.
|
||||
review = await pc.Copies.CompareAsync(local.Id, null, Ct);
|
||||
var merge = await pc.Copies.PlanMergeAsync(local.Id, old.Id,
|
||||
new MergeChoices(CopyPhotoPolicy.Union, new Dictionary<string, PhotoChoice>(), review.Details.Select(d => d.Path).Distinct().ToDictionary(p => p, _ => CopySide.ThisPc)), Ct);
|
||||
Assert.True(merge.CanApply, string.Join(", ", merge.Blocks));
|
||||
Assert.Equal((old.Id, card.Id), (merge.KeepId, merge.DropId));
|
||||
await pc.WaitAsync((await pc.Copies.EnqueueMergeAsync(held, merge, Ct)).Id);
|
||||
Assert.Null(await pc.Db.Sequences.GetAsync(card.Id, Ct));
|
||||
var kept = await pc.Db.Frames.ListBySequenceAsync(old.Id, cancellationToken: Ct);
|
||||
Assert.Contains(Sha(Jpeg(Start.AddSeconds(210), 401)), kept.Select(f => f.Sha256));
|
||||
foreach (var frame in kept) Assert.Equal(frame.Sha256, Sha(await File.ReadAllBytesAsync(Path.Combine(disk.RootPath, frame.RelativePath), Ct)));
|
||||
Assert.Contains(await pc.Archives.ListTrashAsync(pc.Main.Id, Ct), t => t.SequenceId == card.Id);
|
||||
Assert.Equal(remoteId, (await pc.Sync.LinkOfAsync(pc.Server, old.Id, Ct))?.RemoteId);
|
||||
}
|
||||
|
||||
private static readonly SyncPolicy Policy = new(Linking: CopyLinking.AskAlways);
|
||||
|
||||
private static string Sha(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes));
|
||||
|
||||
/// <summary>A project named <paramref name="name"/> at <paramref name="home"/> with one version of its own (a deflicker window).</summary>
|
||||
private async Task ProjectAsync(IProjectHome home, string name, int window)
|
||||
{
|
||||
var project = await home.CreateAsync(name, null, "alberto", Ct);
|
||||
var head = await home.HeadAsync(project.Id, Ct);
|
||||
var portable = ProjectContent.ToPortable(ProjectSettings.FromJson("""{"exposure":{"deflickerWindow":{"isAuto":false,"manual":""" + window + "}}}"), new FramePhotos([]));
|
||||
var pushed = await home.PushAsync(project.Id, new ProjectVersion
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
ProjectId = project.Id,
|
||||
ParentId = head.Id,
|
||||
Number = head.Number + 1,
|
||||
Kind = ProjectVersionKind.Commit,
|
||||
Author = "alberto",
|
||||
ClientName = PcName,
|
||||
SettingsJson = portable,
|
||||
ContentHash = ProjectContent.Hash(portable),
|
||||
FramesVersion = head.FramesVersion,
|
||||
CreatedAt = DateTimeOffset.UtcNow,
|
||||
}, Ct);
|
||||
Assert.NotNull(pushed.Version);
|
||||
}
|
||||
|
||||
/// <summary>A small real JPEG with Exif (camera and capture time); each seed gives distinct bytes.</summary>
|
||||
private static byte[] Jpeg(DateTime captured, int seed)
|
||||
{
|
||||
using var image = new ImageBuffer(48, 32);
|
||||
var random = new Random(seed);
|
||||
for (var c = 0; c < 3; c++)
|
||||
{
|
||||
var plane = image.Plane(c);
|
||||
var level = (float)random.NextDouble();
|
||||
for (var i = 0; i < plane.Length; i++) plane[i] = level * (0.5f + 0.5f * (i % 48) / 48f);
|
||||
}
|
||||
var exif = ExifWriter.BuildJpegApp1(new FrameMetadata { Make = "Canon", Model = "Canon EOS R5", BodySerial = "0431", CapturedAt = captured, Iso = 100 });
|
||||
return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 85, App1Segments = [exif[4..]] });
|
||||
}
|
||||
|
||||
private static async Task<HashSet<string>> LocalHashesAsync(Pc pc, Guid id) =>
|
||||
(await pc.Db.Frames.ListBySequenceAsync(id, cancellationToken: pc.Ct)).Select(f => f.Sha256!).ToHashSet(StringComparer.Ordinal);
|
||||
|
||||
private Task ServerIdleAsync(TestServer server) =>
|
||||
UntilAsync(async () => await server.Database.Jobs.CountAsync(DateTimeOffset.UtcNow) is { Queued: 0, Running: 0 }, "the server's jobs");
|
||||
|
||||
private async Task UntilAsync(Func<Task<bool>> condition, string what)
|
||||
{
|
||||
var until = DateTime.UtcNow + Deadline;
|
||||
while (!await condition())
|
||||
{
|
||||
if (DateTime.UtcNow > until) Assert.Fail("Timed out waiting for " + what);
|
||||
await Task.Delay(50, Ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This PC as the desktop composes it (AppServices): its index and archive, the sync engine, the matches engine with its
|
||||
/// planners and the server's project homes, and a job engine with the archive, sync, Integrate and Merge handlers.
|
||||
/// </summary>
|
||||
private sealed class Pc : IAsyncDisposable
|
||||
{
|
||||
private readonly TestContext _context;
|
||||
private readonly ChronosClient _client;
|
||||
private readonly Connector _connector;
|
||||
|
||||
private Pc(TestContext context, ChronosDatabase db, ArchiveService archives, Archive main, SyncService sync, ChronosClient client)
|
||||
{
|
||||
_context = context;
|
||||
Db = db;
|
||||
Archives = archives;
|
||||
Main = main;
|
||||
Sync = sync;
|
||||
_client = client;
|
||||
Remote = new ChronosSyncRemote(client, ownsClient: false);
|
||||
_connector = new Connector(client);
|
||||
var sides = new CopySides(db);
|
||||
var homes = CopyJobs.ServerHomes(_connector);
|
||||
Copies = new CopyEngine(sync, archives, new IntegratePlanner(sync, sides, archives.Projects, homes), new SequenceMerger(db, archives, sides),
|
||||
new CopyReviewBuilder(db, archives.Projects, sides, homes), remote => new CopyPlanContext(PcName, remote is null ? null : ServerName,
|
||||
true, true, true, false, false, remote is not null, null, new HashSet<Guid>(), new HashSet<Guid>()),
|
||||
serverNames: _ => ServerName);
|
||||
Jobs = NewJobs();
|
||||
}
|
||||
|
||||
public ChronosDatabase Db { get; }
|
||||
public ArchiveService Archives { get; }
|
||||
public Archive Main { get; }
|
||||
public SyncService Sync { get; }
|
||||
public ChronosSyncRemote Remote { get; }
|
||||
public CopyEngine Copies { get; }
|
||||
public JobEngine Jobs { get; private set; }
|
||||
public string Server => Remote.Server;
|
||||
public CancellationToken Ct => _context.Cancellation;
|
||||
|
||||
public static async Task<Pc> StartAsync(TestContext context, TestServer server, string token)
|
||||
{
|
||||
var ct = context.Cancellation;
|
||||
var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory("studio-db"), "chronos.db")), ct);
|
||||
var options = new ArchiveServiceOptions { Owner = PcName, LeaseWait = TimeSpan.FromSeconds(20) };
|
||||
var archives = new ArchiveService(db, options);
|
||||
var main = await archives.CreateAsync(context.CreateTempDirectory("studio-archive"), "Main", cancellationToken: ct);
|
||||
var sync = new SyncService(db, archives, new SyncOptions { Archive = options, ProxyCacheDirectory = context.CreateTempDirectory("studio-proxies") });
|
||||
var client = new ChronosClient(server.HttpBase, new CertificatePinning([]), PcName) { Token = token };
|
||||
var pc = new Pc(context, db, archives, main, sync, client);
|
||||
await pc.Jobs.StartAsync(ct);
|
||||
return pc;
|
||||
}
|
||||
|
||||
/// <summary>A job engine over this index with every handler the desktop registers for these jobs (not started).</summary>
|
||||
public JobEngine NewJobs() => new(Db,
|
||||
[
|
||||
.. Archives.CreateJobHandlers(), .. Sync.CreateJobHandlers(_connector),
|
||||
CopyJobs.CreateIntegrateHandler(Sync, Archives, _connector, Sync.Copies),
|
||||
SequenceMerger.CreateHandler(Db, new SequenceMerger(Db, Archives, new CopySides(Db)), Archives, new ProjectTransplant(), new NoWorkspace()),
|
||||
],
|
||||
new JobEngineOptions { Workers = 2, WorkerId = PcName, PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
|
||||
|
||||
/// <summary>Stops the engine that runs jobs as they come and puts one not started in its place: the next jobs wait for it.</summary>
|
||||
public async Task<JobEngine> StopJobsAsync()
|
||||
{
|
||||
await Jobs.DisposeAsync();
|
||||
return Jobs = NewJobs();
|
||||
}
|
||||
|
||||
public IProjectHome ServerHome(Guid remoteId) => new ServerProjectHome(_client, remoteId, ServerName, null, Server);
|
||||
|
||||
/// <summary>A local sequence filed photo by photo through the archive ingest.</summary>
|
||||
public async Task<Sequence> LocalAsync(Archive archive, string title, IReadOnlyList<(byte[] Bytes, DateTime Captured)> photos)
|
||||
{
|
||||
Guid? id = null;
|
||||
for (var i = 0; i < photos.Count; i++)
|
||||
{
|
||||
var result = await IngestAsync(archive, id, id is null ? title : null, photos[i].Bytes, $"IMG_{photos[i].Captured:HHmmss}.JPG", photos[i].Captured);
|
||||
id = result.SequenceId;
|
||||
}
|
||||
return (await Db.Sequences.GetAsync(id!.Value, Ct))!;
|
||||
}
|
||||
|
||||
public Task<IngestResult> AddPhotoAsync(Archive archive, Guid sequenceId, byte[] photo, DateTime captured) =>
|
||||
IngestAsync(archive, sequenceId, null, photo, $"IMG_{captured:HHmmss}.JPG", captured);
|
||||
|
||||
private async Task<IngestResult> IngestAsync(Archive archive, Guid? sequenceId, string? title, byte[] photo, string name, DateTime captured)
|
||||
{
|
||||
var staging = Path.Combine(archive.RootPath, ".chronos", "staging", "test");
|
||||
Directory.CreateDirectory(staging);
|
||||
var path = Path.Combine(staging, $"{Guid.NewGuid():N}.part");
|
||||
await File.WriteAllBytesAsync(path, photo, Ct);
|
||||
return await Archives.Ingest.CommitAsync(new IngestRequest(archive.Id, sequenceId, title, null, path, name, photo.Length, Sha(photo), captured, null), Ct);
|
||||
}
|
||||
|
||||
public async Task<Job> WaitAsync(Guid jobId)
|
||||
{
|
||||
var until = DateTime.UtcNow.AddSeconds(TestTiming.Budget(60));
|
||||
while (true)
|
||||
{
|
||||
var job = await Db.Jobs.GetAsync(jobId, Ct);
|
||||
if (job?.State == JobState.Done) return job;
|
||||
if (job?.State is JobState.Failed or JobState.Cancelled) Assert.Fail($"Job {job.Kind} {job.State}: {job.Error}\n{job.LogTail}");
|
||||
if (DateTime.UtcNow > until) Assert.Fail($"Job {jobId} did not finish (now {job?.State})");
|
||||
await Task.Delay(25, Ct);
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await Jobs.DisposeAsync();
|
||||
Copies.Dispose();
|
||||
Remote.Dispose();
|
||||
_client.Dispose();
|
||||
await Db.DisposeAsync();
|
||||
}
|
||||
|
||||
/// <summary>No workspace here: no sequence has workspace work not sent home.</summary>
|
||||
private sealed class NoWorkspace : IWorkspaceGuard
|
||||
{
|
||||
public Task<bool> HasUnsentAsync(Guid sequenceId, CancellationToken ct) => Task.FromResult(false);
|
||||
}
|
||||
|
||||
/// <summary>The signed-in session: a remote per job and the server's project homes (Settings › Server's server keeps projects).</summary>
|
||||
private sealed class Connector(ChronosClient client) : ISyncConnector
|
||||
{
|
||||
public ValueTask<ISyncRemote?> ConnectAsync(string server, CancellationToken cancellationToken)
|
||||
{
|
||||
ISyncRemote remote = new ChronosSyncRemote(client, ownsClient: false);
|
||||
return ValueTask.FromResult<ISyncRemote?>(remote.Server == server ? remote : null);
|
||||
}
|
||||
|
||||
public IProjectHome? ProjectHome(BundleHome home) =>
|
||||
home.IsArchive ? null : new ServerProjectHome(client, home.SequenceId, ServerName, null, home.Server);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user