diff --git a/i18n/en/Errors.resx b/i18n/en/Errors.resx index 6018a270..7391b68d 100644 --- a/i18n/en/Errors.resx +++ b/i18n/en/Errors.resx @@ -23,6 +23,7 @@ The sequence is no longer in this PC's archive index. Open or create an archive on this PC to receive the originals. Not connected to this server; connect and retry the job. + No original reached the server: they are missing here or already in another server sequence. {0} original is missing or changed since it was archived; verify the archive.{0} count {0} originals are missing or changed since they were archived; verify the archive.{0} count The template is empty. diff --git a/i18n/it/Errors.it.resx b/i18n/it/Errors.it.resx index aee44508..7bc74c12 100644 --- a/i18n/it/Errors.it.resx +++ b/i18n/it/Errors.it.resx @@ -23,6 +23,7 @@ La sequenza non è più nell'indice dell'archivio di questo PC. Apri o crea un archivio su questo PC per ricevere gli originali. Non connesso a questo server; collegati e riprova l'attività. + Nessun originale è arrivato al server: mancano qui o sono già in un'altra sequenza del server. {0} originale manca o è cambiato dopo l'archiviazione; verifica l'archivio. {0} originali mancano o sono cambiati dopo l'archiviazione; verifica l'archivio. Il modello è vuoto. diff --git a/src/Titano.Data/Sync/SyncRemote.cs b/src/Titano.Data/Sync/SyncRemote.cs index a4b8a8fc..70194202 100644 --- a/src/Titano.Data/Sync/SyncRemote.cs +++ b/src/Titano.Data/Sync/SyncRemote.cs @@ -23,16 +23,17 @@ public interface ISyncRemote : IDisposable /// Every frame row of a sequence, in index order. Task> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken); - Task CreateSequenceAsync(CreateSequenceRequest request, CancellationToken cancellationToken); - /// A 409 means the settings version moved on the server. Task UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken); /// - /// Chunked, resumable upload of one original that the server verifies against before - /// committing it (BRIEF §14.4); see . + /// Chunked, resumable upload of one original into , or into the sequence the server + /// files under (created by the first one); the server verifies + /// before committing it (BRIEF §14.4). An original the server already holds is not sent again: the response then + /// names ( without one). See . /// - Task UploadFileAsync(string path, Guid sequenceId, string sha256, DateTime? capturedAt, CancellationToken cancellationToken); + Task UploadFileAsync(string path, Guid? sequenceId, string? sessionKey, string sha256, DateTime? capturedAt, + CancellationToken cancellationToken); /// Streams a frame's original, proxy or thumb, resuming with Range from the destination's length. Task DownloadFrameAsync(Guid frameId, string kind, Stream destination, CancellationToken cancellationToken); @@ -88,14 +89,12 @@ public sealed class TitanoSyncRemote(TitanoClient client, bool ownsClient) : ISy return all; } - public Task CreateSequenceAsync(CreateSequenceRequest request, CancellationToken cancellationToken) => - client.CreateSequenceAsync(request, cancellationToken); - public Task UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken) => client.UpdateSequenceAsync(id, request, cancellationToken); - public Task UploadFileAsync(string path, Guid sequenceId, string sha256, DateTime? capturedAt, CancellationToken cancellationToken) => - client.UploadFileAsync(path, sequenceId, capturedAt, null, sha256, null, cancellationToken); + public Task UploadFileAsync(string path, Guid? sequenceId, string? sessionKey, string sha256, DateTime? capturedAt, + CancellationToken cancellationToken) => + client.UploadFileAsync(path, sequenceId, capturedAt, sessionKey, sha256, null, cancellationToken); public Task DownloadFrameAsync(Guid frameId, string kind, Stream destination, CancellationToken cancellationToken) => client.DownloadFrameAsync(frameId, kind, destination, null, cancellationToken); diff --git a/src/Titano.Data/Sync/SyncService.cs b/src/Titano.Data/Sync/SyncService.cs index 72121690..dce35e76 100644 --- a/src/Titano.Data/Sync/SyncService.cs +++ b/src/Titano.Data/Sync/SyncService.cs @@ -260,17 +260,32 @@ public sealed class SyncService return link; } - /// Makes the server's copy equal to this PC's (an upload sends the settings with the originals). + /// + /// Makes the server's copy equal to this PC's (an upload sends the settings with the originals of the sequence it + /// created); the server's own processing may edit the new sequence meanwhile, so a refused edit is sent again. + /// internal async Task PushAllAsync(ISyncRemote remote, Guid remoteId, CancellationToken cancellationToken) { await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); try { var (link, local) = await LinkedAsync(remote.Server, remoteId, cancellationToken).ConfigureAwait(false); - var dto = await remote.GetSequenceAsync(remoteId, cancellationToken).ConfigureAwait(false); - var updated = await remote.UpdateSequenceAsync(remoteId, SyncPayload.Of(local).ToRequest(dto.SettingsVersion), cancellationToken).ConfigureAwait(false); - await _links.UpsertAsync(Agreed(Observe(link, remote.Server, updated), local.SettingsVersion, updated.SettingsVersion), cancellationToken) - .ConfigureAwait(false); + for (var attempt = 1; ; attempt++) + { + var dto = await remote.GetSequenceAsync(remoteId, cancellationToken).ConfigureAwait(false); + try + { + var updated = await remote.UpdateSequenceAsync(remoteId, SyncPayload.Of(local).ToRequest(dto.SettingsVersion), cancellationToken) + .ConfigureAwait(false); + await _links.UpsertAsync(Agreed(Observe(link, remote.Server, updated), local.SettingsVersion, updated.SettingsVersion), cancellationToken) + .ConfigureAwait(false); + return; + } + catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.Conflict && attempt < 3) + { + Log.Info(LogCategory, $"{local.DisplayTitle} changed on the server while its settings were sent; sending again"); + } + } } finally { diff --git a/src/Titano.Data/Sync/SyncTransfers.cs b/src/Titano.Data/Sync/SyncTransfers.cs index 4747f117..9f993d92 100644 --- a/src/Titano.Data/Sync/SyncTransfers.cs +++ b/src/Titano.Data/Sync/SyncTransfers.cs @@ -38,22 +38,41 @@ internal sealed class SyncTransfers(SyncService sync) var paths = new ArchivePaths(archive.RootPath); var (remoteId, created) = await TargetAsync(context, remote, local).ConfigureAwait(false); - var manifest = await remote.GetManifestAsync(remoteId, ct).ConfigureAwait(false); - var present = manifest.Frames.Select(f => f.Sha256.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal); var frames = (await SequenceFrames.ListAsync(db, local.Id, ct).ConfigureAwait(false)).Where(f => (f.Flags & FrameFlags.Missing) == 0).ToList(); - var pending = frames.Where(f => f.Sha256 is null || !present.Contains(f.Sha256.ToLowerInvariant())).ToList(); + var present = remoteId is { } known + ? (await remote.GetManifestAsync(known, ct).ConfigureAwait(false)).Frames.Select(f => f.Sha256.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal) + : []; + var pending = new Queue(frames.Where(f => f.Sha256 is null || !present.Contains(f.Sha256.ToLowerInvariant()))); var progress = new TransferProgress(context, frames.Count, frames.Count - pending.Count); await progress.ReportAsync().ConfigureAwait(false); var skipped = 0; + + // Without a server sequence the originals go out one by one under this sequence's session key until the + // server has filed one, which creates the sequence (an original it already holds elsewhere creates nothing). + while (remoteId is null && pending.TryDequeue(out var first)) + { + var sent = await UploadFrameAsync(context, remote, null, SyncService.SessionKey(local.Id), paths.FromRelative(first.RelativePath), first, ct) + .ConfigureAwait(false); + if (sent is null) skipped++; + else if (sent.SequenceId != Guid.Empty) + { + remoteId = sent.SequenceId; + await context.CheckpointAsync(sent.SequenceId.ToString(), progress.Done + 1, frames.Count).ConfigureAwait(false); + await sync.LinkAsync(remote.Server, sent.SequenceId, local, ct).ConfigureAwait(false); + } + await progress.StepAsync().ConfigureAwait(false); + } + if (remoteId is not { } target) throw new InvalidOperationException(Loc.L("Errors.Sync.NothingSent")); + await Parallel.ForEachAsync(pending, Workers(sync.Options.Uploads, ct), async (frame, token) => { - if (!await UploadFrameAsync(context, remote, remoteId, paths.FromRelative(frame.RelativePath), frame, token).ConfigureAwait(false)) + if (await UploadFrameAsync(context, remote, target, null, paths.FromRelative(frame.RelativePath), frame, token).ConfigureAwait(false) is null) Interlocked.Increment(ref skipped); await progress.StepAsync().ConfigureAwait(false); }).ConfigureAwait(false); - if (created) await sync.PushAllAsync(remote, remoteId, ct).ConfigureAwait(false); - await sync.RefreshSequencesAsync(remote, [remoteId], CompareOnly, ct).ConfigureAwait(false); + if (created) await sync.PushAllAsync(remote, target, ct).ConfigureAwait(false); + await sync.RefreshSequencesAsync(remote, [target], CompareOnly, ct).ConfigureAwait(false); if (skipped > 0) throw new InvalidDataException(Loc.Plural("Errors.Sync.Unreadable", skipped)); } @@ -139,8 +158,11 @@ internal sealed class SyncTransfers(SyncService sync) if (cached < frames.Count) context.Log($"{frames.Count - cached} frame(s) have neither proxy nor thumbnail on the server"); } - /// The server sequence an upload fills and whether this job created it: the linked one, one an interrupted attempt created, or a new one. - private async Task<(Guid RemoteId, bool Created)> TargetAsync(JobContext context, ISyncRemote remote, Sequence local) + /// + /// The server sequence an upload fills and whether this job creates it: the linked one, the one an interrupted + /// attempt created, or none yet (the first original creates it). + /// + private async Task<(Guid? RemoteId, bool Created)> TargetAsync(JobContext context, ISyncRemote remote, Sequence local) { var ct = context.Cancellation; Guid? started = Guid.TryParse(context.Checkpoint, out var saved) ? saved : null; @@ -153,13 +175,10 @@ internal sealed class SyncTransfers(SyncService sync) if (link?.RemoteId != id) await sync.LinkAsync(remote.Server, id, local, ct).ConfigureAwait(false); return (id, id == started); } - // Deleted on the server meanwhile: upload into a new sequence. + // Deleted on the server meanwhile: the originals go into a new sequence. if (id == link?.RemoteId) await sync.Links.DeleteAsync(remote.Server, id, ct).ConfigureAwait(false); } - var dto = await remote.CreateSequenceAsync(new CreateSequenceRequest(local.Title, local.CameraModel), ct).ConfigureAwait(false); - await context.CheckpointAsync(dto.Id.ToString(), 0, local.FrameCount).ConfigureAwait(false); - await sync.LinkAsync(remote.Server, dto.Id, local, ct).ConfigureAwait(false); - return (dto.Id, true); + return (null, true); } private static async Task ExistsAsync(ISyncRemote remote, Guid id, CancellationToken cancellationToken) @@ -175,22 +194,26 @@ internal sealed class SyncTransfers(SyncService sync) } } - /// Hashes the original again and sends it; false (logged) when it is gone or no longer the archived file. - private static async Task UploadFrameAsync(JobContext context, ISyncRemote remote, Guid remoteId, string path, Frame frame, CancellationToken cancellationToken) + /// + /// Hashes the original again and sends it into (or the sequence of + /// ); null (logged) when it is gone or no longer the archived file. + /// + private static async Task UploadFrameAsync(JobContext context, ISyncRemote remote, Guid? sequenceId, string? sessionKey, string path, + Frame frame, CancellationToken cancellationToken) { if (!File.Exists(path)) { context.Log($"{frame.FileName}: missing, not uploaded"); - return false; + return null; } var sha = await TitanoClient.HashFileAsync(path, cancellationToken).ConfigureAwait(false); if (frame.Sha256 is { } archived && !archived.Equals(sha, StringComparison.OrdinalIgnoreCase)) { context.Log($"{frame.FileName}: changed since it was archived, not uploaded"); - return false; + return null; } - await remote.UploadFileAsync(path, remoteId, sha, frame.CapturedAt, cancellationToken).ConfigureAwait(false); - return true; + return await remote.UploadFileAsync(path, sequenceId, sessionKey, sha, frame.CapturedAt, cancellationToken).ConfigureAwait(false) + ?? new CompleteUploadResponse(Guid.Empty, sequenceId ?? Guid.Empty, -1); } /// Downloads one original into staging and commits it into the local sequence (created from the server id when null). @@ -325,6 +348,8 @@ internal sealed class SyncTransfers(SyncService sync) } } + public long Done => done; + public ValueTask ReportAsync() => context.ReportAsync(done, total); } } diff --git a/tests/Titano.Data.Tests/Sync/FakeSyncRemote.cs b/tests/Titano.Data.Tests/Sync/FakeSyncRemote.cs index 14d7ee67..50d497cc 100644 --- a/tests/Titano.Data.Tests/Sync/FakeSyncRemote.cs +++ b/tests/Titano.Data.Tests/Sync/FakeSyncRemote.cs @@ -14,6 +14,7 @@ internal sealed class FakeSyncRemote : ISyncRemote { private readonly Lock _gate = new(); private readonly Channel _events = Channel.CreateUnbounded(); + private readonly Dictionary _sessions = []; public string Server => "https://nas.test:8443"; @@ -83,12 +84,6 @@ internal sealed class FakeSyncRemote : ISyncRemote lock (_gate) return Task.FromResult>([.. Find(sequenceId).Frames.Select((f, i) => f.Dto(sequenceId, i))]); } - public Task CreateSequenceAsync(CreateSequenceRequest request, CancellationToken cancellationToken) - { - var sequence = Add(request.Title, []); - return Task.FromResult(sequence.Dto()); - } - public Task UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken) { lock (_gate) @@ -107,18 +102,27 @@ internal sealed class FakeSyncRemote : ISyncRemote } } - public async Task UploadFileAsync(string path, Guid sequenceId, string sha256, DateTime? capturedAt, CancellationToken cancellationToken) + /// Like the server: content it already holds anywhere is not stored again; a session key files the first original into a new sequence. + public async Task UploadFileAsync(string path, Guid? sequenceId, string? sessionKey, string sha256, DateTime? capturedAt, + CancellationToken cancellationToken) { var bytes = await File.ReadAllBytesAsync(path, cancellationToken); if (Convert.ToHexStringLower(SHA256.HashData(bytes)) != sha256) throw new TitanoApiException(HttpStatusCode.BadRequest, new ApiError("hash_mismatch", "hash")); lock (_gate) { - var s = Find(sequenceId); - var existing = s.Frames.FindIndex(f => f.Sha256 == sha256); - if (existing >= 0) return new CompleteUploadResponse(s.Frames[existing].Id, sequenceId, existing); - var frame = s.AddFrame(bytes, Path.GetFileName(path), capturedAt); - return new CompleteUploadResponse(frame.Id, sequenceId, s.Frames.Count - 1); + if (Sequences.Values.SelectMany(s => s.Frames).FirstOrDefault(f => f.Sha256 == sha256) is { } existing) + return new CompleteUploadResponse(existing.Id, sequenceId ?? Guid.Empty, -1); + FakeSequence target; + if (sequenceId is { } id) target = Find(id); + else if (!_sessions.TryGetValue(sessionKey!, out target!)) + { + target = new FakeSequence { Id = Guid.CreateVersion7() }; + Sequences[target.Id] = target; + _sessions[sessionKey!] = target; + } + var frame = target.AddFrame(bytes, Path.GetFileName(path), capturedAt); + return new CompleteUploadResponse(frame.Id, target.Id, target.Frames.Count - 1); } } diff --git a/tests/Titano.Data.Tests/Sync/SyncServiceTests.cs b/tests/Titano.Data.Tests/Sync/SyncServiceTests.cs index f82f3ee3..7e5a71fc 100644 --- a/tests/Titano.Data.Tests/Sync/SyncServiceTests.cs +++ b/tests/Titano.Data.Tests/Sync/SyncServiceTests.cs @@ -267,11 +267,11 @@ public sealed class SyncServiceTests(TestContext context) public Task> ListSequencesAsync(CancellationToken cancellationToken) => inner.ListSequencesAsync(cancellationToken); public Task GetManifestAsync(Guid id, CancellationToken cancellationToken) => inner.GetManifestAsync(id, cancellationToken); public Task> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken) => inner.ListFramesAsync(sequenceId, cancellationToken); - public Task CreateSequenceAsync(CreateSequenceRequest request, CancellationToken cancellationToken) => inner.CreateSequenceAsync(request, cancellationToken); public Task UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken) => inner.UpdateSequenceAsync(id, request, cancellationToken); - public Task UploadFileAsync(string path, Guid sequenceId, string sha256, DateTime? capturedAt, CancellationToken cancellationToken) => - inner.UploadFileAsync(path, sequenceId, sha256, capturedAt, cancellationToken); + public Task UploadFileAsync(string path, Guid? sequenceId, string? sessionKey, string sha256, DateTime? capturedAt, + CancellationToken cancellationToken) => + inner.UploadFileAsync(path, sequenceId, sessionKey, sha256, capturedAt, cancellationToken); public Task DownloadFrameAsync(Guid frameId, string kind, Stream destination, CancellationToken cancellationToken) => inner.DownloadFrameAsync(frameId, kind, destination, cancellationToken); diff --git a/tests/Titano.Server.Tests/Sync/SyncClient.cs b/tests/Titano.Server.Tests/Sync/SyncClient.cs new file mode 100644 index 00000000..9b642c99 --- /dev/null +++ b/tests/Titano.Server.Tests/Sync/SyncClient.cs @@ -0,0 +1,120 @@ +using System.Security.Cryptography; +using Titano.Core.Codecs.Jpeg; +using Titano.Core.Model; +using Titano.Data; +using Titano.Data.Archiving; +using Titano.Data.Jobs; +using Titano.Data.Sync; +using Titano.Protocol.Client; +using Titano.Testing; + +namespace Titano.Server.Tests.Sync; + +/// A desktop client's sync side: its own index and archive, the sync engine and a job engine, signed in to a test server. +internal sealed class SyncClient : IAsyncDisposable +{ + private readonly TestContext _context; + private readonly TitanoClient _client; + + private SyncClient(TestContext context, TitanoDatabase db, ArchiveService archives, Archive archive, SyncService sync, TitanoClient client, JobEngine engine) + { + _context = context; + Db = db; + Archives = archives; + Archive = archive; + Sync = sync; + _client = client; + Engine = engine; + Remote = new TitanoSyncRemote(client, ownsClient: false); + } + + public TitanoDatabase Db { get; } + public ArchiveService Archives { get; } + public Archive Archive { get; } + public SyncService Sync { get; } + public JobEngine Engine { get; } + + /// The connection the table and the agent use (jobs get their own from the connector). + public TitanoSyncRemote Remote { get; } + + public string Server => Remote.Server; + private CancellationToken Ct => _context.Cancellation; + + public static async Task StartAsync(TestContext context, TestServer server, string token, string name) + { + var db = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory(name + "-db"), "titano.db")), context.Cancellation); + var options = new ArchiveServiceOptions { Owner = name, LeaseWait = TimeSpan.FromSeconds(20) }; + var archives = new ArchiveService(db, options); + var archive = await archives.CreateAsync(context.CreateTempDirectory(name + "-archive"), "Main", cancellationToken: context.Cancellation); + var sync = new SyncService(db, archives, new SyncOptions { Archive = options, ProxyCacheDirectory = context.CreateTempDirectory(name + "-proxies") }); + var client = new TitanoClient(server.HttpBase, new CertificatePinning([]), name) { Token = token }; + var engine = new JobEngine(db, [.. archives.CreateJobHandlers(), .. sync.CreateJobHandlers(new Connector(client))], + new JobEngineOptions { Workers = 2, WorkerId = name, PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) }); + await engine.StartAsync(context.Cancellation); + return new SyncClient(context, db, archives, archive, sync, client, engine); + } + + /// Distinct JPEGs larger than one 64 KiB chunk. + public static byte[] Photo(int seed) + { + const int width = 512, height = 384; + var pixels = new byte[width * height * 3]; + new Random(seed).NextBytes(pixels); + return JpegEncoder.Encode(pixels, width, height, 3, new JpegEncodeOptions { Quality = 95 }); + } + + public static string Sha(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes)); + + /// A local sequence committed through the archive ingest, optionally with project settings edited on this PC. + public async Task LocalAsync(string title, IReadOnlyList photos, string? settingsJson = null) + { + var staging = Path.Combine(Archive.RootPath, ".titano", "staging", "test"); + Directory.CreateDirectory(staging); + Guid? id = null; + for (var i = 0; i < photos.Count; i++) + { + var path = Path.Combine(staging, $"{Guid.NewGuid():N}.part"); + await File.WriteAllBytesAsync(path, photos[i], Ct); + var result = await Archives.Ingest.CommitAsync(new IngestRequest(Archive.Id, id, id is null ? title : null, null, path, $"IMG_{i + 1:0000}.JPG", + photos[i].Length, Sha(photos[i]), new DateTime(2026, 9, 28, 18, 0, 0).AddSeconds(10 * i), null), Ct); + id = result.SequenceId; + } + var sequence = (await Db.Sequences.GetAsync(id!.Value, Ct))!; + if (settingsJson is null) return sequence; + var edited = await Db.Sequences.EditAsync(sequence.Id, new Titano.Data.Repositories.SequenceEdit { SettingsJson = settingsJson }, null, Ct); + return edited.Sequence!; + } + + public async Task WaitAsync(Guid jobId, JobState state = JobState.Done) + { + var until = DateTime.UtcNow.AddSeconds(60); + while (true) + { + var job = await Db.Jobs.GetAsync(jobId, Ct); + if (job?.State == state) return job; + if (job?.State is JobState.Failed && state != JobState.Failed) Assert.Fail($"Job failed: {job.Error}\n{job.LogTail}"); + if (DateTime.UtcNow > until) Assert.Fail($"Job {jobId} did not reach {state} (now {job?.State})"); + await Task.Delay(25, Ct); + } + } + + public async Task EntryAsync(string title) => (await Sync.ListAsync(Server, Ct)).Single(e => e.Title == title); + + public async ValueTask DisposeAsync() + { + await Engine.DisposeAsync(); + Remote.Dispose(); + _client.Dispose(); + await Db.DisposeAsync(); + } + + /// Every job gets its own remote over the shared signed-in client. + private sealed class Connector(TitanoClient client) : ISyncConnector + { + public ValueTask ConnectAsync(string server, CancellationToken cancellationToken) + { + ISyncRemote remote = new TitanoSyncRemote(client, ownsClient: false); + return ValueTask.FromResult(remote.Server == server ? remote : null); + } + } +} diff --git a/tests/Titano.Server.Tests/Sync/SyncServerTests.cs b/tests/Titano.Server.Tests/Sync/SyncServerTests.cs new file mode 100644 index 00000000..e5ce7857 --- /dev/null +++ b/tests/Titano.Server.Tests/Sync/SyncServerTests.cs @@ -0,0 +1,206 @@ +using System.Net; +using System.Net.Http.Json; +using Microsoft.Extensions.DependencyInjection; +using Titano.Core.Imaging; +using Titano.Core.Imaging.Decoders; +using Titano.Core.Model; +using Titano.Core.Project; +using Titano.Data.Repositories; +using Titano.Data.Sync; +using Titano.Protocol; +using Titano.Server.Events; +using Titano.Server.Storage; +using Titano.Testing; + +namespace Titano.Server.Tests.Sync; + +/// The client's sync engine against the real server: uploads, downloads, proxies and live events through the API. +[Category("server")] +[Timeout(180_000)] +public sealed class SyncServerTests(TestContext context) +{ + private const string Window41 = """{"exposure":{"deflickerWindow":{"isAuto":false,"manual":41}}}"""; + private const string Window33 = """{"exposure":{"deflickerWindow":{"isAuto":false,"manual":33}}}"""; + + [Test] + public async Task ASequenceUploadedFromOnePcDownloadsIdenticallyOnAnother() + { + await using var server = await StartServerAsync(); + var (_, _, token) = await server.UserAsync("alberto", "editor"); + await using var studio = await SyncClient.StartAsync(context, server, token, "studio"); + await using var laptop = await SyncClient.StartAsync(context, server, token, "laptop"); + var photos = Enumerable.Range(1, 3).Select(SyncClient.Photo).ToList(); + var local = await studio.LocalAsync("Comet over the ridge", photos, Window41); + + var upload = await studio.Sync.EnqueueUploadAsync(studio.Engine, studio.Server, local); + await studio.WaitAsync(upload.Id); + + var uploaded = await studio.EntryAsync("Comet over the ridge"); + Assert.Equal((0, 0), (uploaded.Link!.MissingRemote, uploaded.Link.MissingLocal)); + var remoteId = uploaded.Link!.RemoteId; + var onServer = Assert.NotNull(await server.Database.Sequences.GetAsync(remoteId)); + Assert.Equal(41, ProjectSettings.FromJson(onServer.SettingsJson!).Exposure.DeflickerWindow.Manual, "settings travel with the originals"); + var serverFrames = await server.Database.Frames.ListBySequenceAsync(remoteId); + Assert.True(serverFrames.Select(f => f.Sha256).ToHashSet().SetEquals(photos.Select(SyncClient.Sha)), "every original was committed"); + + await ServerIdleAsync(server); + await laptop.Sync.RefreshAsync(laptop.Remote, new SyncPolicy(), context.Cancellation); + Assert.Equal(SyncStatus.RemoteOnly, (await laptop.EntryAsync("Comet over the ridge")).Status); + var download = await laptop.Sync.EnqueueDownloadAsync(laptop.Engine, laptop.Server, remoteId, "Comet over the ridge", SyncDownloadMode.Originals, + laptop.Archive.Id); + await laptop.WaitAsync(download.Id); + + var copy = await laptop.EntryAsync("Comet over the ridge"); + Assert.Equal(SyncStatus.InSync, copy.Status); + Assert.Equal(SequenceOrigin.Server, copy.Local!.Origin); + // The server's analysis may have added its advice meanwhile; the copy has what the server has, the user's edit included. + Assert.True(SyncRules.SameSettings((await server.Database.Sequences.GetAsync(remoteId))!.SettingsJson, copy.Local.SettingsJson)); + Assert.Equal(41, ProjectSettings.FromJson(copy.Local.SettingsJson!).Exposure.DeflickerWindow.Manual); + var files = (await laptop.Db.Frames.ListBySequenceAsync(copy.Local.Id)) + .Select(f => File.ReadAllBytes(Path.Combine(laptop.Archive.RootPath, f.RelativePath))).ToList(); + Assert.True(files.Select(SyncClient.Sha).ToHashSet().SetEquals(photos.Select(SyncClient.Sha)), "byte-identical originals"); + + await studio.Sync.RefreshAsync(studio.Remote, new SyncPolicy(), context.Cancellation); + Assert.Equal(SyncStatus.InSync, (await studio.EntryAsync("Comet over the ridge")).Status); + } + + [Test] + public async Task AnUploadInterruptedMidFileResumesTheServersPartialUpload() + { + await using var server = await StartServerAsync(); + var (http, _, token) = await server.UserAsync("alberto", "editor"); + await using var studio = await SyncClient.StartAsync(context, server, token, "studio"); + var photos = Enumerable.Range(10, 2).Select(SyncClient.Photo).ToList(); + var local = await studio.LocalAsync("Clouds", photos); + // The crashed attempt had sent the first original (which created the server sequence) and one chunk of the second. + var first = await Uploads.UploadAsync(http, photos[0], "IMG_0001.JPG", sessionKey: "crashed-attempt"); + var partial = await Uploads.StartAsync(http, photos[1], "IMG_0002.JPG", first.SequenceId); + Assert.True(photos[1].Length > partial.ChunkSize, "the photo spans several chunks"); + using (var chunk = await Uploads.PutChunkAsync(http, partial.UploadId!.Value, 0, Uploads.Chunk(photos[1], partial.ChunkSize, 0))) + await chunk.ExpectAsync(HttpStatusCode.OK); + + var job = new Job + { + Id = Guid.CreateVersion7(), + Kind = JobKind.UploadCommit, + TargetIds = [local.Id], + TargetLabel = "Clouds", + ParametersJson = $$"""{"server":"{{studio.Server}}"}""", + Checkpoint = first.SequenceId.ToString(), + State = JobState.Queued, + Created = DateTimeOffset.UtcNow, + }; + await studio.Db.Jobs.EnqueueAsync(job, context.Cancellation); + studio.Engine.Wake(); + await studio.WaitAsync(job.Id); + + var resumed = Assert.NotNull(await server.Database.Uploads.GetAsync(partial.UploadId!.Value)); + Assert.Equal(Titano.Data.Repositories.UploadState.Committed, resumed.State); + Assert.Equal(2, (await server.Database.Frames.ListBySequenceAsync(first.SequenceId)).Count); + // Every original is on both sides (the server's analysis may still be editing the settings). + var link = (await studio.EntryAsync("Clouds")).Link!; + Assert.Equal((first.SequenceId, 0, 0), (link.RemoteId, link.MissingRemote, link.MissingLocal)); + } + + [Test] + public async Task ADownloadResumesPartialFilesAndRefusesDamagedOnes() + { + await using var server = await StartServerAsync(); + var (_, _, token) = await server.UserAsync("alberto", "editor"); + await using var studio = await SyncClient.StartAsync(context, server, token, "studio"); + await using var laptop = await SyncClient.StartAsync(context, server, token, "laptop"); + var photos = Enumerable.Range(20, 3).Select(SyncClient.Photo).ToList(); + var local = await studio.LocalAsync("Aurora", photos); + await studio.WaitAsync((await studio.Sync.EnqueueUploadAsync(studio.Engine, studio.Server, local)).Id); + var remoteId = (await studio.EntryAsync("Aurora")).Link!.RemoteId; + + // An earlier attempt left half of one original, and a damaged half of another. + var staging = Path.Combine(laptop.Archive.RootPath, ".titano", "staging", "sync-" + remoteId.ToString("N")); + Directory.CreateDirectory(staging); + await File.WriteAllBytesAsync(Path.Combine(staging, SyncClient.Sha(photos[0]) + ".jpg.part"), photos[0][..(photos[0].Length / 2)]); + await File.WriteAllBytesAsync(Path.Combine(staging, SyncClient.Sha(photos[1]) + ".jpg.part"), new byte[photos[1].Length / 2]); + + await laptop.Sync.RefreshAsync(laptop.Remote, new SyncPolicy(), context.Cancellation); + var download = await laptop.Sync.EnqueueDownloadAsync(laptop.Engine, laptop.Server, remoteId, "Aurora", SyncDownloadMode.Originals, laptop.Archive.Id); + await laptop.WaitAsync(download.Id); + + var copy = Assert.NotNull((await laptop.EntryAsync("Aurora")).Local); + var hashes = (await laptop.Db.Frames.ListBySequenceAsync(copy.Id)) + .Select(f => SyncClient.Sha(File.ReadAllBytes(Path.Combine(laptop.Archive.RootPath, f.RelativePath)))).ToHashSet(); + Assert.True(hashes.SetEquals(photos.Select(SyncClient.Sha)), "every original arrived intact"); + Assert.False(Directory.Exists(staging), "staging cleaned up"); + } + + [Test] + public async Task ServerEventsUpdateThisPcWithoutWaitingForTheNextComparison() + { + await using var server = await StartServerAsync(); + var (http, _, token) = await server.UserAsync("alberto", "editor"); + await using var studio = await SyncClient.StartAsync(context, server, token, "studio"); + var local = await studio.LocalAsync("Harbour sunset", [SyncClient.Photo(30)]); + await studio.WaitAsync((await studio.Sync.EnqueueUploadAsync(studio.Engine, studio.Server, local)).Id); + var remoteId = (await studio.EntryAsync("Harbour sunset")).Link!.RemoteId; + await ServerIdleAsync(server); + await using var agent = new SyncAgent(studio.Sync, studio.Remote, () => new SyncPolicy(), studio.Engine, + new SyncAgentOptions { RefreshInterval = TimeSpan.FromHours(1), EventDelay = TimeSpan.FromMilliseconds(50) }); + agent.Start(); + var hub = server.Services.GetRequiredService(); + await UntilAsync(() => Task.FromResult(agent.Snapshot is not null && hub.SubscriberCount > 0), "the agent's first comparison and event socket"); + + // Someone edits the project on the server (web or another PC). + using (var patch = await http.PatchAsJsonAsync($"/api/v1/sequences/{remoteId}", + new UpdateSequenceRequest(null, null, null, null, Window33, null), ProtocolJson.Default.UpdateSequenceRequest)) + await patch.ExpectAsync(HttpStatusCode.OK); + + await UntilAsync(async () => ProjectSettings.FromJson((await studio.Db.Sequences.GetAsync(local.Id))!.SettingsJson ?? "{}").Exposure.DeflickerWindow.Manual == 33, + "the edit reached this PC"); + Assert.Equal(SyncStatus.InSync, (await studio.EntryAsync("Harbour sunset")).Status); + } + + [Test] + public async Task ARemoteSequenceOpensWithProxiesOnly() + { + await using var server = await StartServerAsync(); + var (_, _, token) = await server.UserAsync("alberto", "editor"); + await using var studio = await SyncClient.StartAsync(context, server, token, "studio"); + await using var laptop = await SyncClient.StartAsync(context, server, token, "laptop"); + var photos = Enumerable.Range(40, 2).Select(SyncClient.Photo).ToList(); + var local = await studio.LocalAsync("Milan skyline dusk", photos, Window41); + await studio.WaitAsync((await studio.Sync.EnqueueUploadAsync(studio.Engine, studio.Server, local)).Id); + var remoteId = (await studio.EntryAsync("Milan skyline dusk")).Link!.RemoteId; + await ServerIdleAsync(server); + Assert.True(((await server.Database.Sequences.GetAsync(remoteId))!.Status & SequenceStatus.ThumbsBuilt) != 0, "thumbnails on the server"); + + await laptop.Sync.RefreshAsync(laptop.Remote, new SyncPolicy(), context.Cancellation); + var job = await laptop.Sync.EnqueueDownloadAsync(laptop.Engine, laptop.Server, remoteId, "Milan skyline dusk", SyncDownloadMode.Proxies, null); + await laptop.WaitAsync(job.Id); + + Assert.Equal(SyncStatus.ProxiesOnly, (await laptop.EntryAsync("Milan skyline dusk")).Status); + Assert.Empty((await laptop.Db.Sequences.ListAsync(new SequenceQuery())).Items); + var opened = Assert.NotNull(laptop.Sync.OpenRemote(laptop.Server, remoteId)); + Assert.Equal(2, opened.CachedCount); + Assert.Equal(41, ProjectSettings.FromJson(opened.Sequence.SettingsJson!).Exposure.DeflickerWindow.Manual); + var source = opened.OpenFrames(DecoderFactory.CreateServer()); + await using (source as IAsyncDisposable) + { + using var frame = await source.GetFrameAsync(0, 0, DecodePurpose.Render, context.Cancellation); + Assert.True(frame.Width > 0 && frame.Height > 0, "a proxy decodes"); + } + } + + private Task StartServerAsync() => TestServer.StartAsync(context, o => o.ChunkSizeBytes = 64 * 1024, ArchiveModule.Register); + + /// Waits until the server's engines finished what the commits queued (thumbnails, proxies, analysis, which may edit settings). + 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> condition, string what) + { + var until = DateTime.UtcNow.AddSeconds(60); + while (!await condition()) + { + if (DateTime.UtcNow > until) Assert.Fail("Timed out waiting for " + what); + await Task.Delay(50, context.Cancellation); + } + } +}