merge: client server mode (sync engine, Server screen sync table and conflicts, Library sync glyphs, render transfers)
Keeps the render node host from the processing branch and disposes the sync host after it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
56 files changed
+6777
-25
No files matched your search
@@ -0,0 +1,265 @@
|
||||
using System.Net;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Security.Cryptography;
|
||||
using System.Threading.Channels;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Sync;
|
||||
using Titano.Protocol;
|
||||
using Titano.Protocol.Client;
|
||||
|
||||
namespace Titano.Data.Tests.Sync;
|
||||
|
||||
/// <summary>An in-memory Titano Server for the sync engine: sequences with versions, originals, proxies, thumbnails and events.</summary>
|
||||
internal sealed class FakeSyncRemote : ISyncRemote
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private readonly Channel<ServerEvent> _events = Channel.CreateUnbounded<ServerEvent>();
|
||||
private readonly Dictionary<string, FakeSequence> _sessions = [];
|
||||
|
||||
public string Server => "https://nas.test:8443";
|
||||
|
||||
public Dictionary<Guid, FakeSequence> Sequences { get; } = [];
|
||||
|
||||
/// <summary>Manifest requests so far (comparisons skip them while frame counters stand still).</summary>
|
||||
public int ManifestCalls { get; private set; }
|
||||
|
||||
/// <summary>Listings still to fail with a network error.</summary>
|
||||
public int FailingListings { get; set; }
|
||||
|
||||
/// <summary>The next original download of this frame returns damaged bytes.</summary>
|
||||
public Guid? CorruptOnce { get; set; }
|
||||
|
||||
/// <summary>Sequences the listing skips (a page boundary moved while it was read); they are still there.</summary>
|
||||
public HashSet<Guid> Unlisted { get; } = [];
|
||||
|
||||
/// <summary>Sequences whose manifest the server refuses (403), as for an account that lost a right.</summary>
|
||||
public HashSet<Guid> Refused { get; } = [];
|
||||
|
||||
/// <summary>Proxy and thumbnail downloads fail with a server error.</summary>
|
||||
public bool FailAssets { get; set; }
|
||||
|
||||
public FakeSequence Add(string? title, IEnumerable<byte[]> originals, string? settingsJson = null,
|
||||
SequenceStatus status = SequenceStatus.ProxiesBuilt | SequenceStatus.ThumbsBuilt)
|
||||
{
|
||||
var sequence = new FakeSequence { Id = Guid.CreateVersion7(), Title = title, SettingsJson = settingsJson, Status = status };
|
||||
foreach (var bytes in originals) sequence.AddFrame(bytes);
|
||||
lock (_gate) Sequences[sequence.Id] = sequence;
|
||||
return sequence;
|
||||
}
|
||||
|
||||
/// <summary>Someone else edits the settings on the server.</summary>
|
||||
public void EditSettings(Guid id, string settingsJson)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
var s = Sequences[id];
|
||||
s.SettingsJson = settingsJson;
|
||||
s.SettingsVersion++;
|
||||
s.UpdatedAt = DateTimeOffset.UtcNow;
|
||||
}
|
||||
}
|
||||
|
||||
public void Publish(ServerEvent e) => _events.Writer.TryWrite(e);
|
||||
|
||||
public Task<IReadOnlyList<SequenceDto>> ListSequencesAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (FailingListings > 0)
|
||||
{
|
||||
FailingListings--;
|
||||
throw new HttpRequestException("connection refused");
|
||||
}
|
||||
return Task.FromResult<IReadOnlyList<SequenceDto>>([.. Sequences.Values.Where(s => !Unlisted.Contains(s.Id)).Select(s => s.Dto())]);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The next request for this sequence times out (HttpClient reports a timeout as a cancellation).</summary>
|
||||
public Guid? TimeoutOnce { get; set; }
|
||||
|
||||
public Task<SequenceDto> GetSequenceAsync(Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (TimeoutOnce == id)
|
||||
{
|
||||
TimeoutOnce = null;
|
||||
throw new TaskCanceledException("The request timed out.");
|
||||
}
|
||||
return Task.FromResult(Find(id).Dto());
|
||||
}
|
||||
}
|
||||
|
||||
public Task<SequenceManifest> GetManifestAsync(Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
ManifestCalls++;
|
||||
if (Refused.Contains(id)) throw new TitanoApiException(HttpStatusCode.Forbidden, new ApiError("forbidden", "refused"));
|
||||
return Task.FromResult(Find(id).Manifest());
|
||||
}
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<FrameDto>> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken)
|
||||
{
|
||||
lock (_gate) return Task.FromResult<IReadOnlyList<FrameDto>>([.. Find(sequenceId).Frames.Select((f, i) => f.Dto(sequenceId, i))]);
|
||||
}
|
||||
|
||||
public Task<SequenceDto> UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
var s = Find(id);
|
||||
if (request.ExpectedSettingsVersion is { } expected && expected != s.SettingsVersion)
|
||||
throw new TitanoApiException(HttpStatusCode.Conflict, new ApiError("settings_conflict", "changed"));
|
||||
if (request.Title is not null) s.Title = request.Title.Length == 0 ? null : request.Title;
|
||||
if (request.Tags is not null) s.Tags = [.. request.Tags];
|
||||
if (request.Rating is { } rating) s.Rating = rating;
|
||||
if (request.Notes is not null) s.Notes = request.Notes.Length == 0 ? null : request.Notes;
|
||||
if (request.SettingsJson is not null) s.SettingsJson = request.SettingsJson;
|
||||
s.SettingsVersion++;
|
||||
s.UpdatedAt = DateTimeOffset.UtcNow;
|
||||
return Task.FromResult(s.Dto());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Like the server: content it already holds anywhere is not stored again; a session key files the first original into a new sequence.</summary>
|
||||
public async Task<CompleteUploadResponse?> 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)
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task DownloadFrameAsync(Guid frameId, string kind, Stream destination, CancellationToken cancellationToken)
|
||||
{
|
||||
byte[] bytes;
|
||||
lock (_gate)
|
||||
{
|
||||
var (sequence, frame) = Sequences.Values.SelectMany(s => s.Frames.Select(f => (s, f))).FirstOrDefault(p => p.f.Id == frameId);
|
||||
if (frame is null) throw NotFound();
|
||||
bytes = kind switch
|
||||
{
|
||||
"original" when CorruptOnce == frameId => [.. frame.Bytes.Select(b => (byte)~b)],
|
||||
"original" => frame.Bytes,
|
||||
"proxy" or "thumb" when FailAssets => throw new TitanoApiException(HttpStatusCode.InternalServerError, new ApiError("internal", "failed")),
|
||||
"proxy" when (sequence.Status & SequenceStatus.ProxiesBuilt) != 0 => frame.Proxy,
|
||||
"thumb" when (sequence.Status & SequenceStatus.ThumbsBuilt) != 0 => frame.Proxy[..Math.Min(frame.Proxy.Length, 64)],
|
||||
_ => throw NotFound(),
|
||||
};
|
||||
if (kind == "original" && CorruptOnce == frameId) CorruptOnce = null;
|
||||
}
|
||||
// Range: continue after what the destination already holds, like the real endpoint.
|
||||
var offset = destination.CanSeek ? (int)Math.Min(destination.Length, bytes.Length) : 0;
|
||||
if (destination.CanSeek) destination.Seek(0, SeekOrigin.End);
|
||||
await destination.WriteAsync(bytes.AsMemory(offset), cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<string?> DownloadRenderAsync(Guid renderId, Stream destination, CancellationToken cancellationToken)
|
||||
{
|
||||
FakeRender render;
|
||||
lock (_gate) render = Sequences.Values.SelectMany(s => s.Renders).FirstOrDefault(r => r.Id == renderId) ?? throw NotFound();
|
||||
var offset = destination.CanSeek ? (int)Math.Min(destination.Length, render.Bytes.Length) : 0;
|
||||
if (destination.CanSeek) destination.Seek(0, SeekOrigin.End);
|
||||
await destination.WriteAsync(render.Bytes.AsMemory(offset), cancellationToken);
|
||||
return render.FileName;
|
||||
}
|
||||
|
||||
/// <summary>Like the server: the SHA-256 is checked and a render keeps its id; one it already has is not sent again.</summary>
|
||||
public async Task<RenderDto?> UploadRenderAsync(Guid sequenceId, string path, RenderUploadRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
var bytes = await File.ReadAllBytesAsync(path, cancellationToken);
|
||||
if (Convert.ToHexStringLower(SHA256.HashData(bytes)) != request.Sha256 || bytes.Length != request.Size)
|
||||
throw new TitanoApiException(HttpStatusCode.UnprocessableEntity, new ApiError("hash_mismatch", "hash"));
|
||||
lock (_gate)
|
||||
{
|
||||
var sequence = Find(sequenceId);
|
||||
if (sequence.Renders.Any(r => r.Id == request.RenderId)) return null;
|
||||
var render = new FakeRender(request.RenderId, request.FileName, request.PresetName, bytes);
|
||||
sequence.Renders.Add(render);
|
||||
return render.Dto();
|
||||
}
|
||||
}
|
||||
|
||||
public async IAsyncEnumerable<ServerEvent> EventsAsync([EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
{
|
||||
while (await _events.Reader.WaitToReadAsync(cancellationToken))
|
||||
{
|
||||
while (_events.Reader.TryRead(out var e)) yield return e;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
|
||||
private FakeSequence Find(Guid id) => Sequences.TryGetValue(id, out var s) ? s : throw NotFound();
|
||||
|
||||
private static TitanoApiException NotFound() => new(HttpStatusCode.NotFound, new ApiError("not_found", "sequence"));
|
||||
}
|
||||
|
||||
internal sealed class FakeSequence
|
||||
{
|
||||
public required Guid Id { get; init; }
|
||||
public string? Title { get; set; }
|
||||
public List<string> Tags { get; set; } = [];
|
||||
public int Rating { get; set; }
|
||||
public string? Notes { get; set; }
|
||||
public string? SettingsJson { get; set; }
|
||||
public int SettingsVersion { get; set; } = 1;
|
||||
public int FramesVersion { get; set; }
|
||||
public SequenceStatus Status { get; set; }
|
||||
public DateTimeOffset UpdatedAt { get; set; } = DateTimeOffset.UtcNow;
|
||||
public DateTime? FirstCapture { get; set; }
|
||||
public string? CameraModel { get; set; } = "Canon EOS R5";
|
||||
public List<FakeFrame> Frames { get; } = [];
|
||||
public List<FakeRender> Renders { get; } = [];
|
||||
|
||||
public FakeFrame AddFrame(byte[] bytes, string? name = null, DateTime? capturedAt = null)
|
||||
{
|
||||
var frame = new FakeFrame(Guid.CreateVersion7(), name ?? $"IMG_{Frames.Count + 1:0000}.JPG", bytes, capturedAt);
|
||||
Frames.Add(frame);
|
||||
FramesVersion++;
|
||||
UpdatedAt = DateTimeOffset.UtcNow;
|
||||
return frame;
|
||||
}
|
||||
|
||||
public SequenceDto Dto() => new(Id, Title, Title ?? "Untitled", "2026/" + Id.ToString("N"), "Canon", CameraModel, null, FirstCapture, null, Frames.Count, 10,
|
||||
Frames.Sum(f => (long)f.Bytes.Length), (long)Status, Renders.Count, null, Tags, Rating, Notes, SettingsVersion, FramesVersion, 0, null, UpdatedAt);
|
||||
|
||||
public SequenceManifest Manifest() => new(Id, FramesVersion, SettingsVersion, SettingsJson, Tags,
|
||||
[.. Frames.Select((f, i) => new ManifestFrame(f.Id, i, f.FileName, f.Bytes.Length, f.Sha256, (Status & SequenceStatus.ProxiesBuilt) != 0,
|
||||
(Status & SequenceStatus.ThumbsBuilt) != 0))], [.. Renders.Select(r => r.Dto())]);
|
||||
}
|
||||
|
||||
internal sealed record FakeRender(Guid Id, string FileName, string PresetName, byte[] Bytes)
|
||||
{
|
||||
public RenderDto Dto() => new(Id, PresetName, "hevc", 3840, 2160, 30, 12, Bytes.Length, new DateTimeOffset(2026, 9, 20, 21, 0, 0, TimeSpan.Zero), "Studio NAS");
|
||||
}
|
||||
|
||||
internal sealed record FakeFrame(Guid Id, string FileName, byte[] Bytes, DateTime? CapturedAt)
|
||||
{
|
||||
public string Sha256 { get; } = Convert.ToHexStringLower(SHA256.HashData(Bytes));
|
||||
|
||||
/// <summary>The original stands in for its proxy: a real JPEG the decoders read.</summary>
|
||||
public byte[] Proxy => Bytes;
|
||||
|
||||
public FrameDto Dto(Guid sequenceId, int index) =>
|
||||
new(Id, sequenceId, index, FileName, Bytes.Length, Sha256, CapturedAt, null, 1.0 / 250, 8, 100, 24, 1, 48, 32, "jpeg", 0);
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Sync;
|
||||
using Titano.Protocol;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Data.Tests.Sync;
|
||||
|
||||
/// <summary>The background agent: event-driven comparisons, retries with backoff, proxies kept offline.</summary>
|
||||
[Category("sync")]
|
||||
public sealed class SyncAgentTests(TestContext context)
|
||||
{
|
||||
/// <summary>Full comparisons only at start, so anything later comes from events or explicit requests.</summary>
|
||||
private static readonly SyncAgentOptions EventsOnly = new()
|
||||
{
|
||||
RefreshInterval = TimeSpan.FromHours(1),
|
||||
EventDelay = TimeSpan.FromMilliseconds(20),
|
||||
MinBackoff = TimeSpan.FromMilliseconds(20),
|
||||
MaxBackoff = TimeSpan.FromMilliseconds(200),
|
||||
};
|
||||
|
||||
[Test]
|
||||
public async Task ServerEventsBringChangesWithoutAFullComparison()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Harbour", photos);
|
||||
var remote = f.Remote.Add("Harbour", photos);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await using var agent = new SyncAgent(f.Sync, f.Remote, () => new SyncPolicy(), null, EventsOnly);
|
||||
agent.Start();
|
||||
await WaitAsync(() => agent.Snapshot is not null, "first comparison");
|
||||
var first = agent.Snapshot!;
|
||||
|
||||
f.Remote.EditSettings(remote.Id, SyncFixture.Window33);
|
||||
f.Remote.Publish(new SequenceChangedEvent(remote.Id, "settings", remote.FramesVersion, remote.SettingsVersion));
|
||||
await WaitAsync(async () => SyncRules.SameSettings(SyncFixture.Window33, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson),
|
||||
"the server's edit reached this PC");
|
||||
|
||||
var created = f.Remote.Add("New on the server", f.NewPhotos(1));
|
||||
f.Remote.Publish(new SequenceChangedEvent(created.Id, "created", 1, 1));
|
||||
await WaitAsync(async () => (await f.Sync.ListAsync(f.Server, f.Ct)).Any(e => e.Title == "New on the server"), "a sequence created on the server");
|
||||
Assert.Same(first, agent.Snapshot);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task FailedComparisonsAreRetriedWithBackoff()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
f.Remote.Add("Harbour", f.NewPhotos(1));
|
||||
f.Remote.FailingListings = 3;
|
||||
var changes = 0;
|
||||
await using var agent = new SyncAgent(f.Sync, f.Remote, () => new SyncPolicy(), null, EventsOnly);
|
||||
agent.Changed += () => Interlocked.Increment(ref changes);
|
||||
agent.Start();
|
||||
|
||||
await WaitAsync(() => agent.Snapshot is not null, "a comparison after the failures");
|
||||
Assert.Null(agent.LastError);
|
||||
Assert.Equal(0, f.Remote.FailingListings);
|
||||
Assert.GreaterOrEqual(changes, 4);
|
||||
Assert.Equal(1, agent.Snapshot!.ServerSequences);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ATimedOutComparisonIsRecordedAndLiveUpdatesGoOn()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(1);
|
||||
var local = await f.LocalAsync("Harbour", photos);
|
||||
var remote = f.Remote.Add("Harbour", photos);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await using var agent = new SyncAgent(f.Sync, f.Remote, () => new SyncPolicy(), null, EventsOnly);
|
||||
agent.Start();
|
||||
await WaitAsync(() => agent.Snapshot is not null, "first comparison");
|
||||
|
||||
f.Remote.TimeoutOnce = remote.Id;
|
||||
f.Remote.Publish(new SequenceChangedEvent(remote.Id, "settings", remote.FramesVersion, remote.SettingsVersion));
|
||||
await WaitAsync(async () => (await f.EntryAsync("Harbour")).Link!.Error is not null, "the timeout recorded on the sequence");
|
||||
|
||||
f.Remote.EditSettings(remote.Id, SyncFixture.Window33);
|
||||
f.Remote.Publish(new SequenceChangedEvent(remote.Id, "settings", remote.FramesVersion, remote.SettingsVersion));
|
||||
await WaitAsync(async () => SyncRules.SameSettings(SyncFixture.Window33, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson),
|
||||
"a later event still reaches this PC");
|
||||
Assert.Null((await f.EntryAsync("Harbour")).Link!.Error);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task KeepingProxiesOfflineRefreshesTheCachesThisPcOpened()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Harbour", photos);
|
||||
await f.Sync.LinkAsync(f.Server, f.Remote.Add("Harbour", photos).Id, local.Id, f.Ct);
|
||||
var opened = f.Remote.Add("Construction cam", f.NewPhotos(2));
|
||||
var never = f.Remote.Add("Never opened", f.NewPhotos(1));
|
||||
var engine = await f.StartEngineAsync();
|
||||
await f.RefreshAsync();
|
||||
var first = await f.Sync.EnqueueDownloadAsync(engine, f.Server, opened.Id, "Construction cam", SyncDownloadMode.Proxies, null);
|
||||
await f.Archive.WaitForAsync(first.Id, JobState.Done);
|
||||
opened.AddFrame(f.NewPhotos(1)[0]);
|
||||
var keep = false;
|
||||
await using var agent = new SyncAgent(f.Sync, f.Remote, () => new SyncPolicy(KeepProxiesOffline: keep), engine, EventsOnly);
|
||||
agent.Start();
|
||||
await WaitAsync(() => agent.Snapshot is not null, "first comparison");
|
||||
Assert.True((await f.EntryAsync("Construction cam")).Link!.ProxiesStale);
|
||||
|
||||
keep = true;
|
||||
await agent.RefreshAsync(f.Ct);
|
||||
await WaitAsync(() => f.Sync.OpenRemote(f.Server, opened.Id) is { CachedCount: 3 }, "the stale cache brought up to date");
|
||||
Assert.Null(f.Sync.OpenRemote(f.Server, never.Id));
|
||||
var entries = await f.Sync.ListAsync(f.Server, f.Ct);
|
||||
Assert.Equal(SyncStatus.ProxiesOnly, entries.Single(e => e.Title == "Construction cam").Status);
|
||||
Assert.Equal(SyncStatus.RemoteOnly, entries.Single(e => e.Title == "Never opened").Status);
|
||||
Assert.Equal(SyncStatus.InSync, entries.Single(e => e.Title == "Harbour").Status);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AFailedProxyRefreshWaitsForItsBackoff()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var opened = f.Remote.Add("Construction cam", f.NewPhotos(2));
|
||||
var engine = await f.StartEngineAsync();
|
||||
await f.RefreshAsync();
|
||||
await f.Archive.WaitForAsync((await f.Sync.EnqueueDownloadAsync(engine, f.Server, opened.Id, "Construction cam", SyncDownloadMode.Proxies, null)).Id,
|
||||
JobState.Done);
|
||||
opened.AddFrame(f.NewPhotos(1)[0]);
|
||||
f.Remote.FailAssets = true;
|
||||
await using var agent = new SyncAgent(f.Sync, f.Remote, () => new SyncPolicy(KeepProxiesOffline: true), engine,
|
||||
EventsOnly with { MinBackoff = TimeSpan.FromHours(1), MaxBackoff = TimeSpan.FromHours(2) });
|
||||
agent.Start();
|
||||
await WaitAsync(async () => (await DownloadsAsync(f)).Any(j => j.State == JobState.Failed), "the background refresh failing");
|
||||
|
||||
await agent.RefreshAsync(f.Ct);
|
||||
await agent.RefreshAsync(f.Ct);
|
||||
|
||||
Assert.Equal(2, (await DownloadsAsync(f)).Count);
|
||||
}
|
||||
|
||||
private static async Task<IReadOnlyList<Job>> DownloadsAsync(SyncFixture f) =>
|
||||
(await f.Db.Jobs.ListAsync(null, JobKind.Download, 100, null, f.Ct)).Items;
|
||||
|
||||
private async Task WaitAsync(Func<bool> condition, string what) => await WaitAsync(() => Task.FromResult(condition()), what);
|
||||
|
||||
private async Task WaitAsync(Func<Task<bool>> condition, string what)
|
||||
{
|
||||
var until = DateTime.UtcNow.AddSeconds(30);
|
||||
while (!await condition())
|
||||
{
|
||||
if (DateTime.UtcNow > until) Assert.Fail("Timed out waiting for " + what);
|
||||
await Task.Delay(20, context.Cancellation);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Archiving;
|
||||
using Titano.Data.Jobs;
|
||||
using Titano.Data.Sync;
|
||||
using Titano.Data.Tests.Archiving;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Data.Tests.Sync;
|
||||
|
||||
/// <summary>A local archive and index, the sync engine over them and an in-memory server.</summary>
|
||||
internal sealed class SyncFixture : IAsyncDisposable
|
||||
{
|
||||
public const string Window41 = """{"exposure":{"deflickerWindow":{"isAuto":false,"manual":41}}}""";
|
||||
public const string Window33 = """{"exposure":{"deflickerWindow":{"isAuto":false,"manual":33}}}""";
|
||||
|
||||
private readonly List<IAsyncDisposable> _owned = [];
|
||||
private int _seed;
|
||||
|
||||
private SyncFixture(ArchiveFixture archive, SyncService sync)
|
||||
{
|
||||
Archive = archive;
|
||||
Sync = sync;
|
||||
_owned.Add(archive);
|
||||
}
|
||||
|
||||
public ArchiveFixture Archive { get; }
|
||||
public SyncService Sync { get; }
|
||||
public FakeSyncRemote Remote { get; } = new();
|
||||
public TitanoDatabase Db => Archive.Db;
|
||||
public string Server => Remote.Server;
|
||||
public CancellationToken Ct => Archive.Ct;
|
||||
|
||||
public static async Task<SyncFixture> CreateAsync(TestContext context)
|
||||
{
|
||||
var archive = await ArchiveFixture.CreateAsync(context);
|
||||
var sync = new SyncService(archive.Db, archive.Service, new SyncOptions
|
||||
{
|
||||
Archive = new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) },
|
||||
ProxyCacheDirectory = context.CreateTempDirectory("proxies"),
|
||||
});
|
||||
return new SyncFixture(archive, sync);
|
||||
}
|
||||
|
||||
public Task<SyncSnapshot> RefreshAsync(SyncPolicy? policy = null) => Sync.RefreshAsync(Remote, policy ?? new SyncPolicy(), Ct);
|
||||
|
||||
public async Task<SyncEntry> EntryAsync(string title) =>
|
||||
(await Sync.ListAsync(Server, Ct)).Single(e => e.Title == title);
|
||||
|
||||
/// <summary>Distinct photos (the same bytes on both sides make the same original).</summary>
|
||||
public List<byte[]> NewPhotos(int count)
|
||||
{
|
||||
var photos = new List<byte[]>(count);
|
||||
for (var i = 0; i < count; i++, _seed++) photos.Add(Photos.Jpeg(ArchiveFixture.Start.AddSeconds(10 * _seed), 1000 + _seed));
|
||||
return photos;
|
||||
}
|
||||
|
||||
/// <summary>A local sequence made through the archive ingest (hashed frames, a real sidecar).</summary>
|
||||
public async Task<Sequence> LocalAsync(string title, IReadOnlyList<byte[]> originals, string? settingsJson = null)
|
||||
{
|
||||
Guid? id = null;
|
||||
var staging = Path.Combine(Archive.Paths.StagingDirectory, "test");
|
||||
Directory.CreateDirectory(staging);
|
||||
for (var i = 0; i < originals.Count; i++)
|
||||
{
|
||||
var path = Path.Combine(staging, $"{Guid.NewGuid():N}.part");
|
||||
await File.WriteAllBytesAsync(path, originals[i], Ct);
|
||||
var sha = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(originals[i]));
|
||||
var result = await Archive.Service.Ingest.CommitAsync(new IngestRequest(Archive.Archive.Id, id, id is null ? title : null, null, path,
|
||||
$"IMG_{i + 1:0000}.JPG", originals[i].Length, sha, ArchiveFixture.Start.AddSeconds(10 * i), null), Ct);
|
||||
id = result.SequenceId;
|
||||
}
|
||||
var sequence = (await Db.Sequences.GetAsync(id!.Value, Ct))!;
|
||||
if (settingsJson is not null) sequence = await EditLocalSettingsAsync(sequence.Id, settingsJson);
|
||||
return sequence;
|
||||
}
|
||||
|
||||
/// <summary>An edit on this PC, as the editor makes it (project file and index, settings version + 1).</summary>
|
||||
public async Task<Sequence> EditLocalSettingsAsync(Guid id, string settingsJson)
|
||||
{
|
||||
var sequence = (await Db.Sequences.GetAsync(id, Ct))!;
|
||||
var folder = Archive.Paths.Sequence(sequence.Folder);
|
||||
await File.WriteAllTextAsync(folder.ProjectPath, settingsJson, Ct);
|
||||
var result = await Db.Sequences.EditAsync(id, new Titano.Data.Repositories.SequenceEdit { SettingsJson = settingsJson }, sequence.SettingsVersion, Ct);
|
||||
return result.Sequence!;
|
||||
}
|
||||
|
||||
/// <summary>A started engine with the archive and sync handlers; jobs reach the server through <paramref name="connector"/> (the fake by default).</summary>
|
||||
public async Task<JobEngine> StartEngineAsync(ISyncConnector? connector = null)
|
||||
{
|
||||
var engine = new JobEngine(Db, [.. Archive.Service.CreateJobHandlers(), .. Sync.CreateJobHandlers(connector ?? new Connector(Remote))],
|
||||
new JobEngineOptions { Workers = 2, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
|
||||
_owned.Insert(0, engine);
|
||||
await engine.StartAsync(Ct);
|
||||
return engine;
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
foreach (var owned in _owned) await owned.DisposeAsync();
|
||||
}
|
||||
|
||||
/// <summary>Hands out <paramref name="remote"/> for its own server; null for any other, or always when <paramref name="remote"/> is null.</summary>
|
||||
public sealed class Connector(ISyncRemote? remote) : ISyncConnector
|
||||
{
|
||||
public ValueTask<ISyncRemote?> ConnectAsync(string server, CancellationToken cancellationToken) =>
|
||||
ValueTask.FromResult(remote is not null && remote.Server == server ? remote : null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Sync;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Data.Tests.Sync;
|
||||
|
||||
public sealed class SyncRulesTests
|
||||
{
|
||||
private static readonly Sequence Local = new() { Id = Guid.CreateVersion7(), ArchiveId = Guid.CreateVersion7(), Folder = "2026/a", SettingsVersion = 4 };
|
||||
|
||||
private static readonly SyncLink Agreed = new()
|
||||
{
|
||||
Server = "https://nas",
|
||||
RemoteId = Guid.CreateVersion7(),
|
||||
Title = "Harbour",
|
||||
RemoteSettingsVersion = 7,
|
||||
BaseLocalSettings = 4,
|
||||
BaseRemoteSettings = 7,
|
||||
};
|
||||
|
||||
[Test]
|
||||
public void StateFollowsLinksOriginalsAndSettingsVersions()
|
||||
{
|
||||
Assert.Equal(SyncStatus.LocalOnly, SyncRules.Status(Local, null));
|
||||
Assert.Equal(SyncStatus.RemoteOnly, SyncRules.Status(null, Agreed));
|
||||
Assert.Equal(SyncStatus.ProxiesOnly, SyncRules.Status(null, Agreed with { ProxiesCached = 3 }));
|
||||
Assert.Equal(SyncStatus.InSync, SyncRules.Status(Local, Agreed));
|
||||
|
||||
Assert.Equal(SyncStatus.LocalAhead, SyncRules.Status(Local, Agreed with { MissingRemote = 2 }));
|
||||
Assert.Equal(SyncStatus.LocalAhead, SyncRules.Status(Local with { SettingsVersion = 5 }, Agreed));
|
||||
Assert.Equal(SyncStatus.ServerAhead, SyncRules.Status(Local, Agreed with { MissingLocal = 1 }));
|
||||
Assert.Equal(SyncStatus.ServerAhead, SyncRules.Status(Local, Agreed with { RemoteSettingsVersion = 8 }));
|
||||
// Originals never conflict: what this PC lacks is downloaded after what the server lacks is uploaded.
|
||||
Assert.Equal(SyncStatus.LocalAhead, SyncRules.Status(Local, Agreed with { MissingRemote = 1, MissingLocal = 1 }));
|
||||
|
||||
Assert.Equal(SyncStatus.Conflict, SyncRules.Status(Local with { SettingsVersion = 5 }, Agreed with { RemoteSettingsVersion = 8 }));
|
||||
// A link nothing was agreed on yet: both sides count as changed until the content is compared.
|
||||
Assert.Equal(SyncStatus.Conflict, SyncRules.Status(Local, Agreed with { BaseLocalSettings = null, BaseRemoteSettings = null }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheLibraryStoresOnlyStatesOfLocalCopies()
|
||||
{
|
||||
Assert.Equal(SyncState.InSync, SyncRules.ToSequenceState(SyncStatus.InSync));
|
||||
Assert.Equal(SyncState.Conflict, SyncRules.ToSequenceState(SyncStatus.Conflict));
|
||||
Assert.Equal(SyncState.LocalAhead, SyncRules.ToSequenceState(SyncStatus.LocalAhead));
|
||||
Assert.Equal(SyncState.ServerAhead, SyncRules.ToSequenceState(SyncStatus.ServerAhead));
|
||||
Assert.Equal(SyncState.LocalOnly, SyncRules.ToSequenceState(SyncStatus.LocalOnly));
|
||||
Assert.Null(SyncRules.ToSequenceState(SyncStatus.Transferring));
|
||||
Assert.Null(SyncRules.ToSequenceState(SyncStatus.RemoteOnly));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void OriginalsAreComparedByContent()
|
||||
{
|
||||
Assert.Equal((0, 0), SyncRules.CompareOriginals(["AA", "bb"], ["aa", "BB"]));
|
||||
Assert.Equal((1, 0), SyncRules.CompareOriginals(["aa", "bb", "cc"], ["aa", "bb"]));
|
||||
Assert.Equal((0, 2), SyncRules.CompareOriginals(["aa"], ["aa", "bb", "cc"]));
|
||||
Assert.Equal((1, 1), SyncRules.CompareOriginals(["aa", "dd"], ["aa", "ee"]));
|
||||
// Frames not hashed yet (adopted, not verified) stand for server frames no hash matched.
|
||||
Assert.Equal((0, 0), SyncRules.CompareOriginals(["aa", null, null], ["aa", "bb", "cc"]));
|
||||
Assert.Equal((0, 1), SyncRules.CompareOriginals([null], ["bb", "cc"]));
|
||||
Assert.Equal((1, 0), SyncRules.CompareOriginals([null, null], ["bb"]));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SettingsAreComparedAsProjectsNotAsText()
|
||||
{
|
||||
Assert.True(SyncRules.SameSettings(null, "{}"), "no settings is the default project");
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, "{ \"exposure\": { \"deflickerWindow\": { \"manual\": 41, \"isAuto\": false } } }"));
|
||||
Assert.False(SyncRules.SameSettings(SyncFixture.Window41, SyncFixture.Window33));
|
||||
|
||||
var difference = Assert.Contains(SyncRules.Differences(SyncFixture.Window41, SyncFixture.Window33), d => d.Path.StartsWith("exposure.deflickerWindow", StringComparison.Ordinal));
|
||||
Assert.Equal("exposure.deflickerWindow.manual", difference.Path);
|
||||
Assert.Equal("41", difference.Mine);
|
||||
Assert.Equal("33", difference.Theirs);
|
||||
Assert.Count(1, SyncRules.Differences("""{"exposure":{"exposureOffsetEv":1},"stack":{"length":3}}""", "{}", max: 1));
|
||||
Assert.Empty(SyncRules.Differences(SyncFixture.Window33, SyncFixture.Window33));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PayloadDifferencesListTheSequenceFieldsBeforeTheSettings()
|
||||
{
|
||||
var mine = new SyncPayload("Harbour", ["sunset", "Harbour"], 3, "mine", SyncFixture.Window41);
|
||||
var theirs = new SyncPayload("Harbour at dusk", ["harbour", "SUNSET"], 3, " mine ", SyncFixture.Window33);
|
||||
|
||||
var differences = SyncRules.Differences(mine, theirs, 10);
|
||||
|
||||
Assert.SequenceEqual(["sequence.title", "exposure.deflickerWindow.manual"], differences.Select(d => d.Path));
|
||||
Assert.Equal(("Harbour", "Harbour at dusk"), (differences[0].Mine, differences[0].Theirs));
|
||||
Assert.Count(1, SyncRules.Differences(mine, theirs, 1));
|
||||
Assert.True(mine.SameMetadata(mine with { Tags = ["HARBOUR", "sunset"], Notes = "mine " }), "tags ignore case and order, blanks are trimmed");
|
||||
Assert.Empty(SyncRules.Differences(mine, mine with { Tags = ["harbour", "SUNSET"] }));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,477 @@
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Sync;
|
||||
using Titano.Protocol;
|
||||
using Titano.Protocol.Client;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Data.Tests.Sync;
|
||||
|
||||
/// <summary>Comparison, settings exchange and conflict resolution against an in-memory server.</summary>
|
||||
[Category("sync")]
|
||||
public sealed class SyncServiceTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public async Task TheTableListsLocalAndServerSequences()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
await f.LocalAsync("Comet", f.NewPhotos(2));
|
||||
f.Remote.Add("Construction cam", f.NewPhotos(3));
|
||||
|
||||
var snapshot = await f.RefreshAsync();
|
||||
|
||||
Assert.Equal(2, snapshot.Entries.Count);
|
||||
Assert.Equal(1, snapshot.ServerSequences);
|
||||
Assert.Equal(SyncStatus.LocalOnly, (await f.EntryAsync("Comet")).Status);
|
||||
var remote = await f.EntryAsync("Construction cam");
|
||||
Assert.Equal(SyncStatus.RemoteOnly, remote.Status);
|
||||
Assert.Null(remote.Local);
|
||||
Assert.Equal(3, remote.Link!.FrameCount);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task LinkedCopiesWithTheSameOriginalsAreInSyncAndTheLibraryKnows()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(3);
|
||||
var local = await f.LocalAsync("Harbour", photos);
|
||||
var remote = f.Remote.Add("Harbour", photos);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
|
||||
await f.RefreshAsync();
|
||||
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status);
|
||||
Assert.Equal(SyncState.InSync, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SyncState);
|
||||
|
||||
// Nothing moved: the manifest is not fetched again.
|
||||
var manifests = f.Remote.ManifestCalls;
|
||||
await f.RefreshAsync();
|
||||
Assert.Equal(manifests, f.Remote.ManifestCalls);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task OriginalsMissingOnEitherSideAreCountedFromTheManifest()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(4);
|
||||
var local = await f.LocalAsync("Harbour", photos[..3]);
|
||||
var remote = f.Remote.Add("Harbour", photos[..2]);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
|
||||
await f.RefreshAsync();
|
||||
var ahead = await f.EntryAsync("Harbour");
|
||||
Assert.Equal(SyncStatus.LocalAhead, ahead.Status);
|
||||
Assert.Equal(1, ahead.Link!.MissingRemote);
|
||||
Assert.Equal(SyncState.LocalAhead, ahead.Local!.SyncState);
|
||||
|
||||
remote.AddFrame(photos[2]);
|
||||
remote.AddFrame(photos[3]);
|
||||
await f.RefreshAsync();
|
||||
var behind = await f.EntryAsync("Harbour");
|
||||
Assert.Equal(SyncStatus.ServerAhead, behind.Status);
|
||||
Assert.Equal((0, 1), (behind.Link!.MissingRemote, behind.Link.MissingLocal));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SettingsChangedOnOneSideAreSentOrTaken()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Harbour", photos);
|
||||
var remote = f.Remote.Add("Harbour", photos);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.RefreshAsync();
|
||||
|
||||
await f.EditLocalSettingsAsync(local.Id, SyncFixture.Window41);
|
||||
await f.RefreshAsync();
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, remote.SettingsJson), "this PC's edit reached the server");
|
||||
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status);
|
||||
|
||||
f.Remote.EditSettings(remote.Id, SyncFixture.Window33);
|
||||
await f.RefreshAsync();
|
||||
var taken = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, taken.SettingsJson), "the server's edit reached this PC");
|
||||
var project = await File.ReadAllTextAsync(f.Archive.Paths.Sequence(taken.Folder).ProjectPath, f.Ct);
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, project), "project.json follows the index");
|
||||
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WithoutAutomaticSyncAnEditWaitsForTheUser()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(1);
|
||||
var local = await f.LocalAsync("Harbour", photos);
|
||||
var remote = f.Remote.Add("Harbour", photos);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.RefreshAsync();
|
||||
|
||||
await f.EditLocalSettingsAsync(local.Id, SyncFixture.Window41);
|
||||
await f.RefreshAsync(new SyncPolicy(AutoSyncSettings: false));
|
||||
Assert.Equal(SyncStatus.LocalAhead, (await f.EntryAsync("Harbour")).Status);
|
||||
Assert.Null(remote.SettingsJson);
|
||||
|
||||
await f.Sync.SyncSettingsAsync(f.Remote, remote.Id, new SyncPolicy(AutoSyncSettings: false), f.Ct);
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, remote.SettingsJson));
|
||||
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TagsChangedDifferentlyOnBothSidesAreAConflictToo()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(1);
|
||||
var local = await f.LocalAsync("Harbour", photos);
|
||||
var remote = f.Remote.Add("Harbour", photos);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.RefreshAsync();
|
||||
|
||||
await f.Remote.UpdateSequenceAsync(remote.Id, new UpdateSequenceRequest(null, ["boats"], null, null, null, null), f.Ct);
|
||||
await f.Archive.Service.SetSequenceInfoAsync(local.Id, "Harbour", ["sunset"], 0, null, f.Ct);
|
||||
await f.RefreshAsync();
|
||||
|
||||
// No side wins silently: a tag removed on one side must not come back, and an edit must not be lost.
|
||||
var entry = await f.EntryAsync("Harbour");
|
||||
Assert.Equal(SyncStatus.Conflict, entry.Status);
|
||||
Assert.SequenceEqual(["boats"], entry.Link!.ConflictRemote!.Tags);
|
||||
Assert.Equal("sequence.tags", SyncRules.Differences(SyncPayload.Of(entry.Local!), entry.Link.ConflictRemote)[0].Path);
|
||||
Assert.SequenceEqual(["boats"], remote.Tags);
|
||||
Assert.SequenceEqual(["sunset"], (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.Tags);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheSameEditOnBothSidesIsAgreedWithoutAConflict()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(1);
|
||||
var local = await f.LocalAsync("Harbour", photos);
|
||||
var remote = f.Remote.Add("Harbour", photos);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.RefreshAsync();
|
||||
|
||||
await f.Remote.UpdateSequenceAsync(remote.Id, new UpdateSequenceRequest(null, ["sunset"], null, null, SyncFixture.Window41, null), f.Ct);
|
||||
await f.Archive.Service.SetSequenceInfoAsync(local.Id, "Harbour", ["SUNSET"], 0, null, f.Ct);
|
||||
await f.EditLocalSettingsAsync(local.Id, SyncFixture.Window41);
|
||||
await f.RefreshAsync();
|
||||
|
||||
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SettingsChangedOnBothSidesAreAConflictUntilTheUserPicks()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var (local, remote) = await ConflictAsync(f);
|
||||
|
||||
var entry = await f.EntryAsync("Holy grail");
|
||||
Assert.Equal(SyncStatus.Conflict, entry.Status);
|
||||
Assert.Equal(SyncState.Conflict, entry.Local!.SyncState);
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, entry.Link!.ConflictRemote!.SettingsJson), "the server's side is kept for display");
|
||||
Assert.Equal("exposure.deflickerWindow.manual", SyncRules.Differences(entry.Local.SettingsJson, entry.Link.ConflictRemote.SettingsJson)[0].Path);
|
||||
|
||||
// Neither side is overwritten while the conflict stands, and the comparison does not fetch it again.
|
||||
var manifests = f.Remote.ManifestCalls;
|
||||
await f.RefreshAsync();
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, remote.SettingsJson));
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson));
|
||||
Assert.Equal(manifests, f.Remote.ManifestCalls);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task KeepMineSendsThisPcsSettings()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var (local, remote) = await ConflictAsync(f);
|
||||
|
||||
await f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.KeepMine, f.Ct);
|
||||
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, remote.SettingsJson));
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson));
|
||||
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Holy grail")).Status);
|
||||
await f.RefreshAsync();
|
||||
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Holy grail")).Status);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TakeServerReplacesThisPcsSettings()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var (local, remote) = await ConflictAsync(f);
|
||||
|
||||
await f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.TakeServer, f.Ct);
|
||||
|
||||
var taken = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, taken.SettingsJson));
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, await File.ReadAllTextAsync(f.Archive.Paths.Sequence(taken.Folder).ProjectPath, f.Ct)));
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, remote.SettingsJson));
|
||||
Assert.Empty(Directory.GetFiles(f.Archive.Paths.Sequence(taken.Folder).MetaDirectory, "project.this-pc-*.json"));
|
||||
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Holy grail")).Status);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SaveBothKeepsThisPcsSettingsNextToTheServers()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var (local, remote) = await ConflictAsync(f);
|
||||
|
||||
var copy = await f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.SaveBoth, f.Ct);
|
||||
|
||||
var taken = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, taken.SettingsJson));
|
||||
Assert.Equal(copy, Assert.Contains(Directory.GetFiles(f.Archive.Paths.Sequence(taken.Folder).MetaDirectory, "project.this-pc-*.json"), _ => true));
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, await File.ReadAllTextAsync(copy!, f.Ct)), "this PC's version is kept");
|
||||
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Holy grail")).Status);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task KeepMineRefusesWhenTheServerChangedAfterTheConflictWasShown()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var (_, remote) = await ConflictAsync(f);
|
||||
var later = SyncFixture.Window33.Replace("33", "35", StringComparison.Ordinal);
|
||||
f.Remote.EditSettings(remote.Id, later);
|
||||
|
||||
await Assert.ThrowsAsync<SyncConflictChangedException>(() => f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.KeepMine, f.Ct));
|
||||
|
||||
Assert.True(SyncRules.SameSettings(later, remote.SettingsJson), "the edit the user never saw is not overwritten");
|
||||
var entry = await f.EntryAsync("Holy grail");
|
||||
Assert.Equal(SyncStatus.Conflict, entry.Status);
|
||||
Assert.True(SyncRules.SameSettings(later, entry.Link!.ConflictRemote!.SettingsJson), "the conflict now shows the server's latest edit");
|
||||
await f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.KeepMine, f.Ct);
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, remote.SettingsJson));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task KeepMineRefusesWhenTheServerChangesWhileItIsSent()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var (_, remote) = await ConflictAsync(f);
|
||||
var later = SyncFixture.Window33.Replace("33", "35", StringComparison.Ordinal);
|
||||
var racing = new RacingRemote(f.Remote, () => f.Remote.EditSettings(remote.Id, later), beforeUpdate: true);
|
||||
|
||||
await Assert.ThrowsAsync<SyncConflictChangedException>(() => f.Sync.ResolveAsync(racing, remote.Id, SyncResolution.KeepMine, f.Ct));
|
||||
Assert.True(SyncRules.SameSettings(later, remote.SettingsJson), "nothing overwritten");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TakeServerRefusesWhenThisPcChangedAfterTheConflictWasShown()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var (local, remote) = await ConflictAsync(f);
|
||||
var later = SyncFixture.Window41.Replace("41", "45", StringComparison.Ordinal);
|
||||
await f.EditLocalSettingsAsync(local.Id, later);
|
||||
|
||||
await Assert.ThrowsAsync<SyncConflictChangedException>(() => f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.TakeServer, f.Ct));
|
||||
|
||||
Assert.True(SyncRules.SameSettings(later, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson), "this PC's later edit is kept");
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, remote.SettingsJson));
|
||||
var entry = await f.EntryAsync("Holy grail");
|
||||
Assert.Equal(SyncStatus.Conflict, entry.Status);
|
||||
Assert.Equal(entry.Local!.SettingsVersion, entry.Link!.ConflictLocalSettings);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TakeServerRefusesWhenTheServerChangedAfterTheConflictWasShown()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var (local, remote) = await ConflictAsync(f);
|
||||
f.Remote.EditSettings(remote.Id, SyncFixture.Window33.Replace("33", "35", StringComparison.Ordinal));
|
||||
|
||||
await Assert.ThrowsAsync<SyncConflictChangedException>(() => f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.SaveBoth, f.Ct));
|
||||
|
||||
var kept = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, kept.SettingsJson), "nothing taken that the user did not see");
|
||||
Assert.Empty(Directory.GetFiles(f.Archive.Paths.Sequence(kept.Folder).MetaDirectory, "project.this-pc-*.json"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SequencesDeletedOnTheServerAreForgotten()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(1);
|
||||
var local = await f.LocalAsync("Harbour", photos);
|
||||
var remote = f.Remote.Add("Harbour", photos);
|
||||
f.Remote.Add("Gone", f.NewPhotos(1));
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.RefreshAsync();
|
||||
|
||||
f.Remote.Sequences.Clear();
|
||||
var snapshot = await f.RefreshAsync();
|
||||
|
||||
Assert.Equal(0, snapshot.ServerSequences);
|
||||
Assert.Equal(SyncStatus.LocalOnly, (await f.EntryAsync("Harbour")).Status);
|
||||
Assert.Equal(SyncState.LocalOnly, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SyncState);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ALinkIsForgottenOnlyWhenTheServerSaysTheSequenceIsGone()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Harbour", photos);
|
||||
var remote = f.Remote.Add("Harbour", photos);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.RefreshAsync();
|
||||
|
||||
// A listing whose pages moved while they were read misses the sequence: it is asked for by id instead.
|
||||
f.Remote.Unlisted.Add(remote.Id);
|
||||
await f.RefreshAsync();
|
||||
var kept = await f.EntryAsync("Harbour");
|
||||
Assert.Equal(SyncStatus.InSync, kept.Status);
|
||||
Assert.Equal(remote.Id, kept.Link!.RemoteId);
|
||||
|
||||
f.Remote.Sequences.Remove(remote.Id);
|
||||
await f.RefreshAsync();
|
||||
Assert.Equal(SyncStatus.LocalOnly, (await f.EntryAsync("Harbour")).Status);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AServerRefusalOnOneSequenceIsRecordedAndTheOthersAreStillCompared()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(4);
|
||||
var harbour = await f.LocalAsync("Harbour", photos[..2]);
|
||||
var aurora = await f.LocalAsync("Aurora", photos[2..]);
|
||||
var refused = f.Remote.Add("Harbour", photos[..2]);
|
||||
var fine = f.Remote.Add("Aurora", photos[2..]);
|
||||
await f.Sync.LinkAsync(f.Server, refused.Id, harbour.Id, f.Ct);
|
||||
await f.Sync.LinkAsync(f.Server, fine.Id, aurora.Id, f.Ct);
|
||||
f.Remote.Refused.Add(refused.Id);
|
||||
|
||||
await f.RefreshAsync();
|
||||
|
||||
Assert.NotNull((await f.EntryAsync("Harbour")).Link!.Error);
|
||||
var compared = await f.EntryAsync("Aurora");
|
||||
Assert.Equal(SyncStatus.InSync, compared.Status);
|
||||
Assert.Null(compared.Link!.Error);
|
||||
|
||||
f.Remote.Refused.Clear();
|
||||
await f.RefreshAsync();
|
||||
var recovered = await f.EntryAsync("Harbour");
|
||||
Assert.Null(recovered.Link!.Error);
|
||||
Assert.Equal(SyncStatus.InSync, recovered.Status);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WithoutTheEditRightThisPcsEditsWaitInsteadOfFailing()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(1);
|
||||
var local = await f.LocalAsync("Harbour", photos);
|
||||
var remote = f.Remote.Add("Harbour", photos);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.RefreshAsync();
|
||||
|
||||
await f.EditLocalSettingsAsync(local.Id, SyncFixture.Window41);
|
||||
await f.RefreshAsync(new SyncPolicy(CanEdit: false));
|
||||
|
||||
Assert.Null(remote.SettingsJson);
|
||||
var entry = await f.EntryAsync("Harbour");
|
||||
Assert.Equal(SyncStatus.LocalAhead, entry.Status);
|
||||
Assert.Null(entry.Link!.Error);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CopiesHoldingTheSameOriginalsAreLinkedByContent()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(3);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
// The Uploader sent the same card to the server; nothing links the two yet.
|
||||
var remote = f.Remote.Add("2026-09-28 Canon", photos);
|
||||
remote.FirstCapture = local.FirstCapture;
|
||||
remote.CameraModel = local.CameraModel;
|
||||
var other = f.Remote.Add("Other card", f.NewPhotos(2));
|
||||
other.FirstCapture = local.FirstCapture;
|
||||
other.CameraModel = local.CameraModel;
|
||||
|
||||
await f.RefreshAsync();
|
||||
|
||||
var entry = await f.EntryAsync("Comet");
|
||||
Assert.Equal(remote.Id, entry.Link?.RemoteId);
|
||||
Assert.Equal((0, 0), (entry.Link!.MissingRemote, entry.Link.MissingLocal));
|
||||
Assert.Null((await f.EntryAsync("Other card")).Local);
|
||||
var manifests = f.Remote.ManifestCalls;
|
||||
await f.RefreshAsync();
|
||||
Assert.Equal(manifests, f.Remote.ManifestCalls);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ABackgroundProxyDownloadGivesWayToTheUsersRequest()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var remote = f.Remote.Add("Construction cam", f.NewPhotos(1));
|
||||
await f.RefreshAsync();
|
||||
await using var engine = new Titano.Data.Jobs.JobEngine(f.Db, f.Sync.CreateJobHandlers(new SyncFixture.Connector(f.Remote)));
|
||||
|
||||
var background = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Construction cam", SyncDownloadMode.Proxies, null, JobPriority.Background);
|
||||
Assert.Equal(background.Id, (await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Construction cam", SyncDownloadMode.Proxies, null,
|
||||
JobPriority.Background)).Id);
|
||||
var opened = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Construction cam", SyncDownloadMode.Proxies, null);
|
||||
Assert.NotEqual(background.Id, opened.Id);
|
||||
Assert.Equal(JobPriority.User, opened.Priority);
|
||||
Assert.Equal(JobState.Cancelled, (await f.Db.Jobs.GetAsync(background.Id, f.Ct))!.State);
|
||||
|
||||
var originals = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Construction cam", SyncDownloadMode.Originals, f.Archive.Archive.Id);
|
||||
Assert.NotEqual(opened.Id, originals.Id);
|
||||
Assert.Equal(SyncTransferKind.DownloadOriginals, SyncService.TransferKind(originals));
|
||||
Assert.Equal(originals.Id, (await f.EntryAsync("Construction cam")).Transfer!.Id);
|
||||
}
|
||||
|
||||
/// <summary>A linked sequence whose settings changed differently on both sides since they last agreed (41 here, 33 on the server).</summary>
|
||||
private static async Task<(Sequence Local, FakeSequence Remote)> ConflictAsync(SyncFixture f)
|
||||
{
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Holy grail", photos);
|
||||
var remote = f.Remote.Add("Holy grail", photos);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.RefreshAsync();
|
||||
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Holy grail")).Status);
|
||||
|
||||
local = await f.EditLocalSettingsAsync(local.Id, SyncFixture.Window41);
|
||||
f.Remote.EditSettings(remote.Id, SyncFixture.Window33);
|
||||
await f.RefreshAsync();
|
||||
return (local, remote);
|
||||
}
|
||||
|
||||
/// <summary>A remote where someone else edits the settings right after the first read of a sequence, or right before the first edit.</summary>
|
||||
private sealed class RacingRemote(FakeSyncRemote inner, Action race, bool beforeUpdate = false) : ISyncRemote
|
||||
{
|
||||
private Action? _race = race;
|
||||
|
||||
public string Server => inner.Server;
|
||||
|
||||
public async Task<SequenceDto> GetSequenceAsync(Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
var dto = await inner.GetSequenceAsync(id, cancellationToken);
|
||||
if (!beforeUpdate) Interlocked.Exchange(ref _race, null)?.Invoke();
|
||||
return dto;
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<SequenceDto>> ListSequencesAsync(CancellationToken cancellationToken) => inner.ListSequencesAsync(cancellationToken);
|
||||
public Task<SequenceManifest> GetManifestAsync(Guid id, CancellationToken cancellationToken) => inner.GetManifestAsync(id, cancellationToken);
|
||||
public Task<IReadOnlyList<FrameDto>> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken) => inner.ListFramesAsync(sequenceId, cancellationToken);
|
||||
public Task<SequenceDto> UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (beforeUpdate) Interlocked.Exchange(ref _race, null)?.Invoke();
|
||||
return inner.UpdateSequenceAsync(id, request, cancellationToken);
|
||||
}
|
||||
|
||||
public Task<CompleteUploadResponse?> 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);
|
||||
|
||||
public Task<string?> DownloadRenderAsync(Guid renderId, Stream destination, CancellationToken cancellationToken) =>
|
||||
inner.DownloadRenderAsync(renderId, destination, cancellationToken);
|
||||
|
||||
public Task<RenderDto?> UploadRenderAsync(Guid sequenceId, string path, RenderUploadRequest request, CancellationToken cancellationToken) =>
|
||||
inner.UploadRenderAsync(sequenceId, path, request, cancellationToken);
|
||||
|
||||
public IAsyncEnumerable<ServerEvent> EventsAsync(CancellationToken cancellationToken) => inner.EventsAsync(cancellationToken);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Imaging.Decoders;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Render;
|
||||
using Titano.Data.Sync;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Data.Tests.Sync;
|
||||
|
||||
/// <summary>Upload, download and proxy jobs on the job engine against an in-memory server.</summary>
|
||||
[Category("sync")]
|
||||
public sealed class SyncTransferTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public async Task UploadSendsTheOriginalsAndSettingsOfALocalSequence()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(3);
|
||||
var local = await f.LocalAsync("Comet", photos, SyncFixture.Window41);
|
||||
var engine = await f.StartEngineAsync();
|
||||
|
||||
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
|
||||
Assert.Equal(job.Id, (await f.Sync.EnqueueUploadAsync(engine, f.Server, local)).Id);
|
||||
var done = await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
|
||||
Assert.Equal((3L, 3L), (done.ProgressDone, done.ProgressTotal));
|
||||
var remote = Assert.Contains(f.Remote.Sequences.Values, s => s.Title == "Comet");
|
||||
Assert.True(remote.Frames.Select(r => r.Sha256).ToHashSet().SetEquals(photos.Select(Sha)), "every original arrived");
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, remote.SettingsJson), "the settings travel with the originals");
|
||||
var entry = await f.EntryAsync("Comet");
|
||||
Assert.Equal(SyncStatus.InSync, entry.Status);
|
||||
Assert.Equal(remote.Id, entry.Link!.RemoteId);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AResumedUploadSendsOnlyWhatTheServerLacks()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(4);
|
||||
var local = await f.LocalAsync("Comet", photos);
|
||||
// A crashed attempt had created the server sequence and sent two originals.
|
||||
var remote = f.Remote.Add("Comet", photos[..2]);
|
||||
var engine = await f.StartEngineAsync();
|
||||
var job = await f.Archive.EnqueueWithCheckpointAsync(engine,
|
||||
new(JobKind.UploadCommit, [local.Id], "Comet", """{"server":"https://nas.test:8443"}""", JobPriority.User), remote.Id.ToString());
|
||||
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
|
||||
Assert.Count(1, f.Remote.Sequences.Values);
|
||||
Assert.Equal(4, remote.Frames.Count);
|
||||
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Comet")).Status);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task OriginalsChangedSinceTheyWereArchivedAreNeverUploaded()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var local = await f.LocalAsync("Comet", f.NewPhotos(3));
|
||||
var damaged = (await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct))[1];
|
||||
var path = f.Archive.Paths.FromRelative(damaged.RelativePath);
|
||||
var bytes = await File.ReadAllBytesAsync(path, f.Ct);
|
||||
bytes[^3] ^= 0xFF;
|
||||
await File.WriteAllBytesAsync(path, bytes, f.Ct);
|
||||
var engine = await f.StartEngineAsync();
|
||||
|
||||
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
|
||||
var failed = await f.Archive.WaitForAsync(job.Id, JobState.Failed);
|
||||
|
||||
Assert.Contains("1", failed.Error);
|
||||
var remote = Assert.Contains(f.Remote.Sequences.Values, s => s.Title == "Comet");
|
||||
Assert.Equal(2, remote.Frames.Count);
|
||||
Assert.DoesNotContain(damaged.Sha256!, remote.Frames.Select(r => r.Sha256));
|
||||
Assert.Equal(SyncStatus.LocalAhead, (await f.EntryAsync("Comet")).Status);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DownloadedOriginalsAreVerifiedAndCommittedThroughTheArchive()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(3);
|
||||
var remote = f.Remote.Add("Construction cam", photos, SyncFixture.Window33);
|
||||
remote.Tags = ["site"];
|
||||
f.Remote.CorruptOnce = remote.Frames[1].Id;
|
||||
await f.RefreshAsync();
|
||||
var engine = await f.StartEngineAsync();
|
||||
|
||||
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Construction cam", SyncDownloadMode.Originals, f.Archive.Archive.Id);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
|
||||
var entry = await f.EntryAsync("Construction cam");
|
||||
Assert.Equal(SyncStatus.InSync, entry.Status);
|
||||
var local = Assert.NotNull(entry.Local);
|
||||
Assert.Equal(SequenceOrigin.Server, local.Origin);
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, local.SettingsJson), "the server's settings came along");
|
||||
Assert.SequenceEqual(["site"], local.Tags);
|
||||
var frames = await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct);
|
||||
Assert.Equal(3, frames.Count);
|
||||
foreach (var frame in frames)
|
||||
{
|
||||
var bytes = await File.ReadAllBytesAsync(f.Archive.Paths.FromRelative(frame.RelativePath), f.Ct);
|
||||
Assert.Equal(frame.Sha256, Sha(bytes));
|
||||
}
|
||||
Assert.True(frames.Select(r => r.Sha256).ToHashSet().SetEquals(photos.Select(Sha)), "the damaged transfer was fetched again");
|
||||
Assert.FileExists(f.Archive.Paths.Sequence(local.Folder).ManifestPath);
|
||||
Assert.False(Directory.Exists(Path.Combine(f.Archive.Paths.StagingDirectory, "sync-" + remote.Id.ToString("N"))), "staging cleaned up");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DownloadFillsInWhatALocalCopyLacks()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(3);
|
||||
var local = await f.LocalAsync("Harbour", photos[..1], SyncFixture.Window41);
|
||||
var remote = f.Remote.Add("Harbour", photos);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.RefreshAsync();
|
||||
await f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.KeepMine, f.Ct);
|
||||
var engine = await f.StartEngineAsync();
|
||||
|
||||
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Harbour", SyncDownloadMode.Originals, null);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
|
||||
Assert.Equal(3, (await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct)).Count);
|
||||
var entry = await f.EntryAsync("Harbour");
|
||||
Assert.Equal(SyncStatus.InSync, entry.Status);
|
||||
Assert.Equal(SequenceOrigin.Local, entry.Local!.Origin);
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, entry.Local.SettingsJson), "an existing copy keeps its settings");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DownloadingIntoAnUnverifiedCopyHashesItFirstAndFetchesOnlyWhatItLacks()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(5);
|
||||
// An adopted folder: indexed by a scan, never verified, so its frames have no hash yet.
|
||||
var folder = Path.Combine(f.Archive.Paths.Root, "Adopted");
|
||||
Directory.CreateDirectory(folder);
|
||||
for (var i = 0; i < 3; i++) await File.WriteAllBytesAsync(Path.Combine(folder, $"IMG_{i + 1:0000}.JPG"), photos[i], f.Ct);
|
||||
await f.Archive.ScanAsync();
|
||||
var local = Assert.Contains((await f.Db.Sequences.ListAsync(new Titano.Data.Repositories.SequenceQuery(), f.Ct)).Items, s => s.Folder == "Adopted");
|
||||
Assert.True((await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct)).All(fr => fr.Sha256 is null), "adopted frames are unhashed");
|
||||
var remote = f.Remote.Add("Adopted", photos);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.RefreshAsync();
|
||||
Assert.Equal(2, (await f.EntryAsync(local.DisplayTitle)).Link!.MissingLocal);
|
||||
var engine = await f.StartEngineAsync();
|
||||
|
||||
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Adopted", SyncDownloadMode.Originals, null);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
|
||||
var frames = await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct);
|
||||
Assert.Equal(5, frames.Count);
|
||||
Assert.True(frames.Select(fr => fr.Sha256).ToHashSet().SetEquals(photos.Select(Sha)), "no original arrived twice");
|
||||
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync(local.DisplayTitle)).Status);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DownloadingOriginalsRestoresTheOnesMissingHere()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(3);
|
||||
var local = await f.LocalAsync("Harbour", photos);
|
||||
var lost = (await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct))[1];
|
||||
var place = f.Archive.Paths.FromRelative(lost.RelativePath);
|
||||
File.Delete(place);
|
||||
await f.Archive.Service.Verifier.VerifyAsync(f.Archive.Archive, [local.Id], default, (_, _, _) => ValueTask.CompletedTask, cancellationToken: f.Ct);
|
||||
var remote = f.Remote.Add("Harbour", photos);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.RefreshAsync();
|
||||
var behind = await f.EntryAsync("Harbour");
|
||||
Assert.Equal((SyncStatus.ServerAhead, 1), (behind.Status, behind.Link!.MissingLocal));
|
||||
var engine = await f.StartEngineAsync();
|
||||
|
||||
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Harbour", SyncDownloadMode.Originals, null);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
|
||||
Assert.Equal(lost.Sha256, Sha(await File.ReadAllBytesAsync(place, f.Ct)));
|
||||
var frames = await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct);
|
||||
Assert.Equal(3, frames.Count);
|
||||
Assert.True(frames.All(fr => (fr.Flags & FrameFlags.Missing) == 0), "the restored original is no longer missing");
|
||||
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheServersRendersAreFetchedIntoTheLocalExports()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Star trails", photos);
|
||||
var remote = f.Remote.Add("Star trails", photos);
|
||||
var render = new FakeRender(Guid.CreateVersion7(), "Star trails 4K.mp4", "4K HEVC", [.. Enumerable.Range(0, 5000).Select(i => (byte)i)]);
|
||||
remote.Renders.Add(render);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
await f.RefreshAsync();
|
||||
var entry = await f.EntryAsync("Star trails");
|
||||
Assert.Equal((SyncStatus.InSync, 1, 5000L), (entry.Status, entry.Link!.ExportsToGet, entry.Link.ExportsToGetBytes));
|
||||
var engine = await f.StartEngineAsync();
|
||||
|
||||
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Star trails", SyncDownloadMode.Exports, null);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
|
||||
var fetched = Assert.Contains(await f.Db.Renders.ListBySequenceAsync(local.Id, f.Ct), r => r.Id == render.Id);
|
||||
Assert.Equal("4K HEVC", fetched.PresetName);
|
||||
var file = f.Archive.Paths.FromRelative(fetched.OutputPath);
|
||||
Assert.Equal(Path.Combine(f.Archive.Paths.Sequence(local.Folder).Exports, "Star trails 4K.mp4"), file);
|
||||
Assert.SequenceEqual(render.Bytes, await File.ReadAllBytesAsync(file, f.Ct));
|
||||
Assert.Equal(0, (await f.EntryAsync("Star trails")).Link!.ExportsToGet);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task RendersMadeHereAreSentOnRequestAndAGoneFileIsReported()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var photos = f.NewPhotos(2);
|
||||
var local = await f.LocalAsync("Harbour", photos);
|
||||
var remote = f.Remote.Add("Harbour", photos);
|
||||
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
|
||||
var exports = f.Archive.Paths.Sequence(local.Folder).Exports;
|
||||
Directory.CreateDirectory(exports);
|
||||
var bytes = Enumerable.Range(0, 3000).Select(i => (byte)(i * 7)).ToArray();
|
||||
await File.WriteAllBytesAsync(Path.Combine(exports, "Harbour 1080p.mp4"), bytes, f.Ct);
|
||||
var made = await AddRenderAsync(f, local, "Harbour 1080p.mp4", bytes.Length);
|
||||
var gone = await AddRenderAsync(f, local, "Harbour draft.mp4", 10);
|
||||
await f.RefreshAsync();
|
||||
Assert.Equal((1, 3000L), ((await f.EntryAsync("Harbour")).Link!.ExportsToSend, (await f.EntryAsync("Harbour")).Link!.ExportsToSendBytes));
|
||||
var engine = await f.StartEngineAsync();
|
||||
|
||||
var job = await f.Sync.EnqueueSendExportsAsync(engine, f.Server, local);
|
||||
Assert.Equal(SyncTransferKind.SendExports, SyncService.TransferKind(job));
|
||||
var failed = await f.Archive.WaitForAsync(job.Id, JobState.Failed);
|
||||
|
||||
Assert.Contains("1", failed.Error);
|
||||
var sent = Assert.Contains(remote.Renders, r => r.Id == made.Id);
|
||||
Assert.SequenceEqual(bytes, sent.Bytes);
|
||||
Assert.DoesNotContain(gone.Id, remote.Renders.Select(r => r.Id));
|
||||
Assert.Equal(0, (await f.EntryAsync("Harbour")).Link!.ExportsToSend);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ProxiesOpenARemoteSequenceForTheEditor()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var remote = f.Remote.Add("Milan skyline", f.NewPhotos(3), SyncFixture.Window33);
|
||||
await f.RefreshAsync();
|
||||
Assert.Null(f.Sync.OpenRemote(f.Server, remote.Id));
|
||||
var engine = await f.StartEngineAsync();
|
||||
|
||||
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Milan skyline", SyncDownloadMode.Proxies, null);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
|
||||
var entry = await f.EntryAsync("Milan skyline");
|
||||
Assert.Equal(SyncStatus.ProxiesOnly, entry.Status);
|
||||
Assert.Equal(3, entry.Link!.ProxiesCached);
|
||||
Assert.False(entry.Link.ProxiesStale);
|
||||
var opened = Assert.NotNull(f.Sync.OpenRemote(f.Server, remote.Id));
|
||||
Assert.Equal(remote.Id, opened.Sequence.Id);
|
||||
Assert.Equal(SequenceOrigin.Server, opened.Sequence.Origin);
|
||||
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, opened.Sequence.SettingsJson));
|
||||
Assert.Equal(3, opened.CachedCount);
|
||||
|
||||
var source = opened.OpenFrames(DecoderFactory.CreateServer());
|
||||
await using (source as IAsyncDisposable)
|
||||
{
|
||||
Assert.Equal(3, source.FrameCount);
|
||||
using var frame = await source.GetFrameAsync(2, 0, DecodePurpose.Render, f.Ct);
|
||||
Assert.Equal((48, 32), (frame.Width, frame.Height));
|
||||
}
|
||||
|
||||
// Nothing local was created, and a frame added on the server makes the cache stale.
|
||||
Assert.Null(entry.Local);
|
||||
remote.AddFrame(f.NewPhotos(1)[0]);
|
||||
await f.RefreshAsync();
|
||||
Assert.True((await f.EntryAsync("Milan skyline")).Link!.ProxiesStale);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ThumbnailsStandInWhenTheServerHasNoProxies()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var remote = f.Remote.Add("Fog", f.NewPhotos(2), status: SequenceStatus.ThumbsBuilt);
|
||||
var engine = await f.StartEngineAsync();
|
||||
|
||||
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Fog", SyncDownloadMode.Proxies, null);
|
||||
await f.Archive.WaitForAsync(job.Id, JobState.Done);
|
||||
|
||||
var opened = Assert.NotNull(f.Sync.OpenRemote(f.Server, remote.Id));
|
||||
Assert.Equal(2, opened.CachedCount);
|
||||
Assert.True(opened.Files.All(file => new FileInfo(file!).Length == 64), "thumbnails");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TransfersFailWithAReasonWhenThisPcIsNotConnected()
|
||||
{
|
||||
await using var f = await SyncFixture.CreateAsync(context);
|
||||
var local = await f.LocalAsync("Comet", f.NewPhotos(1));
|
||||
var engine = await f.StartEngineAsync(new SyncFixture.Connector(null));
|
||||
|
||||
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
|
||||
var failed = await f.Archive.WaitForAsync(job.Id, JobState.Failed);
|
||||
|
||||
Assert.Equal(Titano.Core.Localization.Loc.L("Errors.Sync.NotConnected"), failed.Error);
|
||||
Assert.Empty(f.Remote.Sequences);
|
||||
}
|
||||
|
||||
private static async Task<Render> AddRenderAsync(SyncFixture f, Sequence local, string name, long bytes)
|
||||
{
|
||||
var render = new Render
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
SequenceId = local.Id,
|
||||
PresetName = "1080p H.264",
|
||||
OutputPath = local.Folder + "/exports/" + name,
|
||||
Codec = "h264",
|
||||
Width = 1920,
|
||||
Height = 1080,
|
||||
Fps = 30,
|
||||
DurationSeconds = 10,
|
||||
Bytes = bytes,
|
||||
Created = DateTimeOffset.UtcNow,
|
||||
ProducedBy = "studio",
|
||||
};
|
||||
await f.Db.Renders.InsertAsync(render, f.Ct);
|
||||
return render;
|
||||
}
|
||||
|
||||
private static string Sha(byte[] bytes) => Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(bytes));
|
||||
}
|
||||
Reference in new issue
Block a user