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,151 @@
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Input;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Sections;
|
||||
using Titano.App.Server;
|
||||
using Titano.App.Shell;
|
||||
using Titano.App.Tests.Windows;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Sync;
|
||||
using Titano.Testing;
|
||||
using Titano.Ui.Controls;
|
||||
|
||||
namespace Titano.App.Tests.Server;
|
||||
|
||||
/// <summary>The Server screen's sync table on the capture sample data: comparison, transfers, conflict and the Library's glyphs.</summary>
|
||||
[WindowsOnly]
|
||||
[Serial]
|
||||
[Timeout(300_000)]
|
||||
public sealed class ServerScreenSmokeTests
|
||||
{
|
||||
[Test]
|
||||
public Task TheSyncTableShowsEveryStateOfTheSample() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
|
||||
var shell = app.Shell;
|
||||
await app.Sample.FillAsync();
|
||||
await shell.Library.RefreshAsync();
|
||||
await shell.Services.Server.RestoreAsync();
|
||||
Assert.NotNull(await shell.Services.Sync.RefreshAsync());
|
||||
await app.Sample.CacheProxiesAsync();
|
||||
var table = shell.Server.Sync;
|
||||
await table.ReloadAsync();
|
||||
|
||||
// 36 sequences here (6 also on the server) and 2 only on the server; the conflict is listed first.
|
||||
Assert.True(table.IsActive);
|
||||
Assert.Equal(38, table.Rows.Count);
|
||||
Assert.Equal("Holy grail · Monviso", table.Rows[0].Title);
|
||||
Assert.True(table.Rows[0].IsConflict);
|
||||
Assert.Equal(1, Chip(table, SyncFilter.Conflicts).Count);
|
||||
Assert.Equal(2, Chip(table, SyncFilter.Remote).Count);
|
||||
Assert.Equal(30, Chip(table, SyncFilter.LocalOnly).Count);
|
||||
Assert.Equal(SyncStatus.InSync, Row(table, "Harbour sunset").Entry.Status);
|
||||
Assert.Equal(SyncStatus.ServerAhead, Row(table, "Construction cam · week 38").Entry.Status);
|
||||
Assert.SequenceEqual([SyncAction.DownloadOriginals], Actions(Row(table, "Construction cam · week 38")));
|
||||
Assert.SequenceEqual([SyncAction.Upload], Actions(Row(table, "Milan skyline dusk")));
|
||||
Assert.SequenceEqual([SyncAction.GetExports], Actions(Row(table, "Star trails, Colle del Nivolet")));
|
||||
var sunrise = Row(table, "Sunrise over Superga");
|
||||
Assert.Equal(SyncStatus.ProxiesOnly, sunrise.Entry.Status);
|
||||
Assert.Equal(Loc.L("Server.Sync.Proxies"), sunrise.LocalText);
|
||||
Assert.SequenceEqual([SyncAction.OpenWithProxies, SyncAction.DownloadOriginals], Actions(sunrise));
|
||||
Assert.SequenceEqual([SyncAction.Upload], Actions(Row(table, "Clouds over the Langhe")));
|
||||
var conflict = Row(table, "Holy grail · Monviso");
|
||||
Assert.Equal(StatusKind.Warning, conflict.StateKind);
|
||||
Assert.SequenceEqual([SyncAction.KeepMine, SyncAction.TakeServer, SyncAction.SaveBoth], Actions(conflict));
|
||||
Assert.Equal(Loc.L("Server.Conflict.Difference", Loc.L("Server.Setting.DeflickerWindow"), "41", "33"), conflict.StateToolTip);
|
||||
Assert.NotNull(table.LastSyncText);
|
||||
Assert.NotNull(table.ArchiveText);
|
||||
Assert.True(table.UploadAllCommand.CanExecute(null), "the table filled after the view bound");
|
||||
|
||||
// Resolving shows the plan first: what differs and which side is overwritten.
|
||||
var keepMine = SyncTableViewModel.ConflictRequest(conflict.Entry, SyncAction.KeepMine);
|
||||
Assert.True(keepMine.IsDestructive);
|
||||
Assert.Contains(Loc.L("Server.Setting.DeflickerWindow"), keepMine.Detail);
|
||||
Assert.False(SyncTableViewModel.ConflictRequest(conflict.Entry, SyncAction.SaveBoth).IsDestructive);
|
||||
|
||||
// The Library shows the real sync state of each local copy, in one word.
|
||||
var holyGrail = shell.Library.Items.Single(i => i.Title == "Holy grail · Monviso");
|
||||
Assert.Equal(SyncState.Conflict, holyGrail.Sequence.SyncState);
|
||||
Assert.Equal(StatusKind.Warning, holyGrail.Statuses[^1].Kind);
|
||||
Assert.Contains(shell.Library.Items.Single(i => i.Title == "Harbour sunset").Statuses, s => s.Kind == StatusKind.Synced);
|
||||
var milan = shell.Library.Items.Single(i => i.Title == "Milan skyline dusk").Statuses[^1];
|
||||
Assert.Equal((StatusKind.Synced, Loc.L("Library.Status.Synced")), (milan.Kind, milan.Text));
|
||||
|
||||
shell.Navigate(SectionKey.Server);
|
||||
await app.ExpectAsync<ServerView>("server");
|
||||
|
||||
// Tab walks the row buttons of every row: the rows take no focus, the list passes Tab on to their content.
|
||||
var list = app.FindAll<ListBox>().Single(l => l.Name == "SyncList");
|
||||
Assert.Equal(KeyboardNavigationMode.Continue, KeyboardNavigation.GetTabNavigation(list));
|
||||
var rowButtons = app.FindAll<Button>().Where(b => b.DataContext is SyncRowAction && b.IsVisible).ToList();
|
||||
Assert.True(rowButtons.Select(b => b.DataContext).OfType<SyncRowAction>().Count() > 3, "buttons of several rows are on screen");
|
||||
Assert.True(rowButtons.All(b => b.Focusable && b.IsTabStop), "every row button is a tab stop");
|
||||
|
||||
// Transfers in every state: the rows show what moves and offer Pause or Resume.
|
||||
await app.Sample.FillSyncAsync();
|
||||
await table.ReloadAsync();
|
||||
var comet = Row(table, "Comet over the ridge");
|
||||
Assert.Equal(SyncStatus.Transferring, comet.Entry.Status);
|
||||
Assert.SequenceEqual([SyncAction.Pause], Actions(comet));
|
||||
Assert.Contains("46", comet.ServerText);
|
||||
Assert.Equal(StatusKind.Queued, Row(table, "Fog lifting, Asti").StateKind);
|
||||
Assert.Equal((StatusKind.Running, Loc.L("Server.Sync.State.Downloading")), (Row(table, "Sunrise over Superga").StateKind, Row(table, "Sunrise over Superga").StateText));
|
||||
Assert.SequenceEqual([SyncAction.Resume], Actions(Row(table, "Lake Como storm")));
|
||||
await app.ExpectAsync<ServerView>("server-sync");
|
||||
|
||||
// A reload keeps the row's buttons (focus, tooltips and clicks survive progress and comparisons).
|
||||
var pause = comet.Actions[0];
|
||||
await table.ReloadAsync();
|
||||
Assert.Same(pause, Row(table, "Comet over the ridge").Actions[0]);
|
||||
|
||||
// The conflict filter leaves the one row waiting for a choice.
|
||||
Chip(table, SyncFilter.Conflicts).SelectCommand.Execute(null);
|
||||
Assert.Equal("Holy grail · Monviso", Assert.Contains(table.Rows, _ => true).Title);
|
||||
Assert.Count(1, table.Rows);
|
||||
await app.ExpectAsync<ServerView>("server-conflict");
|
||||
table.SearchText = "nothing like this";
|
||||
Assert.False(table.HasRows);
|
||||
Assert.NotNull(table.EmptyText);
|
||||
|
||||
// Another language relabels chips and rows at once.
|
||||
UiLanguage.Apply("it");
|
||||
try
|
||||
{
|
||||
Assert.Equal("Tutte · 38", Chip(table, SyncFilter.All).Text);
|
||||
}
|
||||
finally
|
||||
{
|
||||
UiLanguage.Apply("en");
|
||||
}
|
||||
});
|
||||
|
||||
[Test]
|
||||
public Task SigningOutEmptiesTheTable() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
|
||||
var shell = app.Shell;
|
||||
await app.Sample.FillAsync();
|
||||
await shell.Services.Server.RestoreAsync();
|
||||
await shell.Services.Sync.RefreshAsync();
|
||||
await shell.Server.Sync.ReloadAsync();
|
||||
Assert.True(shell.Server.Sync.HasRows);
|
||||
|
||||
await shell.Services.Server.SignOutAsync();
|
||||
Assert.Null(await shell.Services.Sync.RefreshAsync());
|
||||
await shell.Server.Sync.ReloadAsync();
|
||||
|
||||
Assert.False(shell.Server.Sync.IsActive);
|
||||
Assert.False(shell.Server.Sync.HasRows);
|
||||
Assert.False(shell.Server.Sync.UploadAllCommand.CanExecute(null));
|
||||
Assert.Equal(Loc.L("Tooltips.Server.Sync.UploadAll.NotConnected"), shell.Server.Sync.UploadAllToolTip);
|
||||
shell.Navigate(SectionKey.Server);
|
||||
await app.ExpectAsync<ServerView>("server-signedout-table");
|
||||
});
|
||||
|
||||
private static SyncFilterChip Chip(SyncTableViewModel table, SyncFilter filter) => table.Chips.Single(c => c.Filter == filter);
|
||||
|
||||
private static SyncRow Row(SyncTableViewModel table, string title) => table.Rows.Single(r => r.Title == title);
|
||||
|
||||
private static IEnumerable<SyncAction> Actions(SyncRow row) => row.Actions.Select(a => a.Action);
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
using Titano.App.Server;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Sync;
|
||||
using Titano.Testing;
|
||||
using Titano.Ui.Controls;
|
||||
|
||||
namespace Titano.App.Tests.Server;
|
||||
|
||||
/// <summary>Words, glyphs and actions of the sync table rows (Server.html).</summary>
|
||||
public sealed class SyncTextTests
|
||||
{
|
||||
private static readonly SyncRights Editor = SyncRights.Of((long)RolePermissions.Default(UserRole.Editor));
|
||||
private static readonly SyncRights Viewer = SyncRights.Of((long)RolePermissions.Default(UserRole.Viewer));
|
||||
|
||||
private static readonly Sequence Local = new()
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
ArchiveId = Guid.CreateVersion7(),
|
||||
Title = "Harbour sunset",
|
||||
Folder = "2026/harbour",
|
||||
FrameCount = 3_600,
|
||||
TotalBytes = 86_000_000_000,
|
||||
Status = SequenceStatus.ProxiesBuilt,
|
||||
SettingsJson = """{"exposure":{"deflickerWindow":{"isAuto":false,"manual":41}}}""",
|
||||
};
|
||||
|
||||
private static readonly SyncLink Link = new()
|
||||
{
|
||||
Server = "https://nas.local:8443",
|
||||
RemoteId = Guid.CreateVersion7(),
|
||||
Title = "Harbour sunset",
|
||||
TotalBytes = 61_000_000_000,
|
||||
RemoteStatus = SequenceStatus.ProxiesBuilt | SequenceStatus.ThumbsBuilt,
|
||||
RenderCount = 2,
|
||||
};
|
||||
|
||||
[Test]
|
||||
public void RightsFollowTheServerPermissions()
|
||||
{
|
||||
Assert.Equal(new SyncRights(true, true, true), Editor);
|
||||
Assert.Equal(new SyncRights(false, false, false), Viewer);
|
||||
Assert.Equal(new SyncRights(false, true, false), SyncRights.Of((long)Permissions.RenderNode));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EachStateOffersItsActions()
|
||||
{
|
||||
Assert.SequenceEqual([SyncAction.Upload], SyncText.Actions(Entry(SyncStatus.LocalOnly, link: null), Editor));
|
||||
Assert.Empty(SyncText.Actions(Entry(SyncStatus.LocalOnly, link: null), Viewer));
|
||||
Assert.SequenceEqual([SyncAction.OpenWithProxies, SyncAction.DownloadOriginals], SyncText.Actions(Entry(SyncStatus.RemoteOnly, local: null), Editor));
|
||||
Assert.SequenceEqual([SyncAction.OpenWithProxies], SyncText.Actions(Entry(SyncStatus.ProxiesOnly, local: null), Viewer));
|
||||
Assert.SequenceEqual([SyncAction.Upload], SyncText.Actions(Entry(SyncStatus.LocalAhead, Link with { MissingRemote = 4 }), Editor));
|
||||
Assert.SequenceEqual([SyncAction.DownloadOriginals], SyncText.Actions(Entry(SyncStatus.ServerAhead, Link with { MissingLocal = 2 }), Editor));
|
||||
Assert.SequenceEqual([SyncAction.SyncSettings], SyncText.Actions(Entry(SyncStatus.ServerAhead), Editor));
|
||||
Assert.SequenceEqual([SyncAction.KeepMine, SyncAction.TakeServer, SyncAction.SaveBoth], SyncText.Actions(Entry(SyncStatus.Conflict), Editor));
|
||||
Assert.Empty(SyncText.Actions(Entry(SyncStatus.InSync), Editor));
|
||||
|
||||
// Without the edit right nothing of this PC is sent: no "Keep mine", no settings push.
|
||||
Assert.SequenceEqual([SyncAction.TakeServer, SyncAction.SaveBoth], SyncText.Actions(Entry(SyncStatus.Conflict), Viewer));
|
||||
Assert.Empty(SyncText.Actions(Entry(SyncStatus.LocalAhead), Viewer));
|
||||
Assert.SequenceEqual([SyncAction.SyncSettings], SyncText.Actions(Entry(SyncStatus.ServerAhead), Viewer));
|
||||
|
||||
// Renders travel on request once the originals agree.
|
||||
var exports = Link with { ExportsToGet = 3, ExportsToGetBytes = 1_900_000_000, ExportsToSend = 1, ExportsToSendBytes = 600_000_000 };
|
||||
Assert.SequenceEqual([SyncAction.GetExports, SyncAction.SendExports], SyncText.Actions(Entry(SyncStatus.InSync, exports), Editor));
|
||||
Assert.SequenceEqual([SyncAction.GetExports], SyncText.Actions(Entry(SyncStatus.InSync, exports), Viewer));
|
||||
Assert.SequenceEqual([SyncAction.KeepMine, SyncAction.TakeServer, SyncAction.SaveBoth], SyncText.Actions(Entry(SyncStatus.Conflict, exports), Editor));
|
||||
Assert.Equal(Loc.Plural("Tooltips.Server.Sync.GetExports", 3, Titano.App.Infrastructure.Formatting.Bytes(1_900_000_000)),
|
||||
SyncText.ToolTip(Entry(SyncStatus.InSync, exports), SyncAction.GetExports));
|
||||
|
||||
Assert.SequenceEqual([SyncAction.Pause], SyncText.Actions(Entry(SyncStatus.Transferring, transfer: Upload(JobState.Running)), Editor));
|
||||
Assert.SequenceEqual([SyncAction.Pause], SyncText.Actions(Entry(SyncStatus.Transferring, transfer: Upload(JobState.Queued)), Editor));
|
||||
Assert.SequenceEqual([SyncAction.Resume], SyncText.Actions(Entry(SyncStatus.Transferring, transfer: Upload(JobState.Paused)), Editor));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ColumnsSayWhatEachSideHolds()
|
||||
{
|
||||
var originals = Loc.L("Server.Sync.Originals");
|
||||
var proxies = Loc.L("Server.Sync.Proxies");
|
||||
Assert.Equal($"{originals} · {proxies}", SyncText.Local(Entry(SyncStatus.InSync)));
|
||||
Assert.Equal(originals, SyncText.Local(Entry(SyncStatus.InSync, local: Local with { Status = SequenceStatus.None })));
|
||||
Assert.Equal(proxies, SyncText.Local(Entry(SyncStatus.ProxiesOnly, Link with { ProxiesCached = 10 }, local: null)));
|
||||
Assert.Equal(Loc.L("Server.Sync.None"), SyncText.Local(Entry(SyncStatus.RemoteOnly, local: null)));
|
||||
|
||||
Assert.Equal($"{originals} · {proxies} · {Loc.Plural("Server.Sync.Exports", 2)}", SyncText.Server(Entry(SyncStatus.InSync)));
|
||||
Assert.Equal(Loc.L("Server.Sync.None"), SyncText.Server(Entry(SyncStatus.LocalOnly, link: null)));
|
||||
var uploading = Entry(SyncStatus.Transferring, link: null, transfer: Upload(JobState.Running) with { ProgressDone = 462, ProgressTotal = 1_005 });
|
||||
Assert.Equal(Loc.L("Server.Sync.Received", Loc.L("Common.Percent", "46")), SyncText.Server(uploading));
|
||||
Assert.Equal(86_000_000_000, SyncText.Size(Entry(SyncStatus.LocalOnly, link: null), SyncAction.Upload));
|
||||
Assert.Equal(61_000_000_000, SyncText.Size(Entry(SyncStatus.RemoteOnly, local: null), SyncAction.DownloadOriginals));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void StatesPairAGlyphWithAWord()
|
||||
{
|
||||
Assert.Equal((StatusKind.Done, Loc.L("Server.Sync.State.InSync")), Kind(Entry(SyncStatus.InSync)));
|
||||
Assert.Equal((StatusKind.Offline, Loc.L("Server.Sync.State.LocalOnly")), Kind(Entry(SyncStatus.LocalOnly, link: null)));
|
||||
Assert.Equal((StatusKind.Remote, Loc.L("Server.Sync.State.RemoteOnly")), Kind(Entry(SyncStatus.RemoteOnly, local: null)));
|
||||
Assert.Equal((StatusKind.Warning, Loc.L("Server.Sync.State.Conflict")), Kind(Entry(SyncStatus.Conflict)));
|
||||
Assert.Equal((StatusKind.Running, Loc.L("Server.Sync.State.Uploading")), Kind(Entry(SyncStatus.Transferring, transfer: Upload(JobState.Running))));
|
||||
Assert.Equal((StatusKind.Paused, Loc.L("Server.Sync.State.Paused")), Kind(Entry(SyncStatus.Transferring, transfer: Upload(JobState.Paused))));
|
||||
Assert.Equal((StatusKind.Running, Loc.L("Server.Sync.State.Downloading")),
|
||||
Kind(Entry(SyncStatus.Transferring, transfer: Upload(JobState.Running) with { Kind = JobKind.Download })));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AConflictNamesTheSettingsThatDifferInWords()
|
||||
{
|
||||
var theirs = new SyncPayload(Local.Title, ["boats"], 0, null, """{"exposure":{"deflickerWindow":{"isAuto":false,"manual":33},"deflicker":{"isAuto":false,"manual":true}}}""");
|
||||
var conflict = Entry(SyncStatus.Conflict, Link with { ConflictRemote = theirs });
|
||||
|
||||
var lines = SyncText.Conflict(conflict, 10);
|
||||
|
||||
Assert.SequenceEqual(
|
||||
[
|
||||
Loc.L("Server.Conflict.Difference", Loc.L("Server.Setting.Tags"), Loc.L("Server.Sync.None"), "boats"),
|
||||
Loc.L("Server.Conflict.Difference", Loc.L("Server.Setting.Deflicker"), Loc.L("Server.Setting.Auto"), Loc.L("Server.Setting.Manual")),
|
||||
Loc.L("Server.Conflict.Difference", Loc.L("Server.Setting.DeflickerWindow"), "41", "33"),
|
||||
], lines);
|
||||
// The State tooltip is one line: the first difference and how many more.
|
||||
Assert.Equal(Loc.L("Server.Conflict.More", lines[0], "2"), SyncText.State(conflict).ToolTip);
|
||||
Assert.False(SyncText.State(conflict).ToolTip.Contains('\n', StringComparison.Ordinal), "one line");
|
||||
Assert.Equal(Loc.L("Tooltips.Server.Sync.State.Conflict"), SyncText.ConflictSummary(Entry(SyncStatus.Conflict)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ASequenceThatCouldNotBeComparedSaysWhy()
|
||||
{
|
||||
var (kind, text, tip) = SyncText.State(Entry(SyncStatus.InSync, Link with { Error = "403 forbidden" }));
|
||||
|
||||
Assert.Equal((StatusKind.Warning, Loc.L("Server.Sync.State.Failed")), (kind, text));
|
||||
Assert.Contains("403 forbidden", tip);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FiltersAndSearchSelectRows()
|
||||
{
|
||||
var rows = new[]
|
||||
{
|
||||
Entry(SyncStatus.LocalOnly, link: null),
|
||||
Entry(SyncStatus.RemoteOnly, local: null),
|
||||
Entry(SyncStatus.ProxiesOnly, local: null),
|
||||
Entry(SyncStatus.Conflict),
|
||||
Entry(SyncStatus.InSync, local: Local with { Title = "Comet over the ridge" }),
|
||||
};
|
||||
Assert.Equal(5, rows.Count(r => SyncText.Matches(r, SyncFilter.All, string.Empty)));
|
||||
Assert.Equal(1, rows.Count(r => SyncText.Matches(r, SyncFilter.LocalOnly, string.Empty)));
|
||||
Assert.Equal(2, rows.Count(r => SyncText.Matches(r, SyncFilter.Remote, string.Empty)));
|
||||
Assert.Equal(1, rows.Count(r => SyncText.Matches(r, SyncFilter.Conflicts, string.Empty)));
|
||||
Assert.Equal(1, rows.Count(r => SyncText.Matches(r, SyncFilter.All, "COMET")));
|
||||
Assert.Equal(0, rows.Count(r => SyncText.Matches(r, SyncFilter.Conflicts, "comet")));
|
||||
}
|
||||
|
||||
private static (StatusKind, string) Kind(SyncEntry entry)
|
||||
{
|
||||
var (kind, text, _) = SyncText.State(entry);
|
||||
return (kind, text);
|
||||
}
|
||||
|
||||
private static SyncEntry Entry(SyncStatus status, SyncLink? link = null, Sequence? local = null, Job? transfer = null) =>
|
||||
new(local ?? (status is SyncStatus.RemoteOnly or SyncStatus.ProxiesOnly ? null : Local), link ?? (status == SyncStatus.LocalOnly ? null : Link), status,
|
||||
transfer);
|
||||
|
||||
private static Job Upload(JobState state) => new() { Id = Guid.CreateVersion7(), Kind = JobKind.UploadCommit, State = state };
|
||||
}
|
||||
@@ -122,7 +122,7 @@ public sealed class ScreenSmokeTests
|
||||
});
|
||||
|
||||
/// <summary>A <see cref="MainWindow"/> on capture services and sample data, shown off screen like <c>--capture</c>.</summary>
|
||||
private sealed class SampleApp : IAsyncDisposable
|
||||
internal sealed class SampleApp : IAsyncDisposable
|
||||
{
|
||||
private const double Width = 1440;
|
||||
private const double Height = 900;
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
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;
|
||||
|
||||
/// <summary>A desktop client's sync side: its own index and archive, the sync engine and a job engine, signed in to a test server.</summary>
|
||||
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; }
|
||||
|
||||
/// <summary>The connection the table and the agent use (jobs get their own from the connector).</summary>
|
||||
public TitanoSyncRemote Remote { get; }
|
||||
|
||||
public string Server => Remote.Server;
|
||||
private CancellationToken Ct => _context.Cancellation;
|
||||
|
||||
public static async Task<SyncClient> 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);
|
||||
}
|
||||
|
||||
/// <summary>Distinct JPEGs larger than one 64 KiB chunk.</summary>
|
||||
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));
|
||||
|
||||
/// <summary>A local sequence committed through the archive ingest, optionally with project settings edited on this PC.</summary>
|
||||
public async Task<Sequence> LocalAsync(string title, IReadOnlyList<byte[]> 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!;
|
||||
}
|
||||
|
||||
/// <summary>A render of <paramref name="sequence"/> made on this PC: its file in the sequence's exports and its row.</summary>
|
||||
public async Task<Render> RenderAsync(Sequence sequence, string fileName, byte[] bytes)
|
||||
{
|
||||
var exports = Path.Combine(Archive.RootPath, sequence.Folder, "exports");
|
||||
Directory.CreateDirectory(exports);
|
||||
await File.WriteAllBytesAsync(Path.Combine(exports, fileName), bytes, Ct);
|
||||
var render = new Render
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
SequenceId = sequence.Id,
|
||||
PresetName = "4K HEVC",
|
||||
OutputPath = sequence.Folder + "/exports/" + fileName,
|
||||
Codec = "hevc",
|
||||
Width = 3840,
|
||||
Height = 2160,
|
||||
Fps = 30,
|
||||
DurationSeconds = 10,
|
||||
Bytes = bytes.Length,
|
||||
Created = DateTimeOffset.UtcNow,
|
||||
ProducedBy = "studio",
|
||||
};
|
||||
await Db.Renders.InsertAsync(render, Ct);
|
||||
return render;
|
||||
}
|
||||
|
||||
public string RenderFile(Render render) => Path.Combine(Archive.RootPath, render.OutputPath);
|
||||
|
||||
public async Task<Job> 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<SyncEntry> 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();
|
||||
}
|
||||
|
||||
/// <summary>Every job gets its own remote over the shared signed-in client.</summary>
|
||||
private sealed class Connector(TitanoClient client) : ISyncConnector
|
||||
{
|
||||
public ValueTask<ISyncRemote?> ConnectAsync(string server, CancellationToken cancellationToken)
|
||||
{
|
||||
ISyncRemote remote = new TitanoSyncRemote(client, ownsClient: false);
|
||||
return ValueTask.FromResult<ISyncRemote?>(remote.Server == server ? remote : null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
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;
|
||||
|
||||
/// <summary>The client's sync engine against the real server: uploads, downloads, proxies and live events through the API.</summary>
|
||||
[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<EventHub>();
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task RendersTravelOnRequestWithTheirIdAndAreVerified()
|
||||
{
|
||||
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(50, 2).Select(SyncClient.Photo).ToList();
|
||||
var local = await studio.LocalAsync("Star trails", photos);
|
||||
await studio.WaitAsync((await studio.Sync.EnqueueUploadAsync(studio.Engine, studio.Server, local)).Id);
|
||||
var remoteId = (await studio.EntryAsync("Star trails")).Link!.RemoteId;
|
||||
await ServerIdleAsync(server);
|
||||
|
||||
// A render made on the studio PC, larger than one chunk, is sent on request and keeps its id.
|
||||
var output = Enumerable.Range(0, 200_000).Select(i => (byte)(i * 31)).ToArray();
|
||||
var render = await studio.RenderAsync(local, "Star trails 4K.mp4", output);
|
||||
await studio.Sync.RefreshAsync(studio.Remote, new SyncPolicy(), context.Cancellation);
|
||||
Assert.Equal(1, (await studio.EntryAsync("Star trails")).Link!.ExportsToSend);
|
||||
await studio.WaitAsync((await studio.Sync.EnqueueSendExportsAsync(studio.Engine, studio.Server, local)).Id);
|
||||
|
||||
var filed = Assert.NotNull(await server.Database.Renders.GetAsync(render.Id));
|
||||
Assert.Equal(remoteId, filed.SequenceId);
|
||||
Assert.SequenceEqual(output, await File.ReadAllBytesAsync(Path.Combine(server.Options.ArchivePath, filed.OutputPath)));
|
||||
Assert.Equal(0, (await studio.EntryAsync("Star trails")).Link!.ExportsToSend);
|
||||
Assert.Null(await studio.Remote.UploadRenderAsync(remoteId, studio.RenderFile(render), new RenderUploadRequest(render.Id, "Star trails 4K.mp4",
|
||||
output.Length, SyncClient.Sha(output), "4K HEVC", "hevc", 3840, 2160, 30, 10, "studio"), context.Cancellation));
|
||||
|
||||
// A damaged transfer is refused at completion.
|
||||
var bad = new RenderUploadRequest(Guid.CreateVersion7(), "Damaged.mp4", output.Length, SyncClient.Sha(output), "4K HEVC", "hevc", 3840, 2160, 30, 10, null);
|
||||
var damaged = Path.Combine(context.CreateTempDirectory("damaged"), "Damaged.mp4");
|
||||
await File.WriteAllBytesAsync(damaged, [.. output.Select(b => (byte)~b)]);
|
||||
var refused = await Assert.ThrowsAsync<Titano.Protocol.Client.TitanoApiException>(() =>
|
||||
studio.Remote.UploadRenderAsync(remoteId, damaged, bad, context.Cancellation));
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, refused.Status);
|
||||
Assert.Null(await server.Database.Renders.GetAsync(bad.RenderId));
|
||||
|
||||
// Another PC with the originals gets the render into its own exports, byte-identical.
|
||||
await laptop.Sync.RefreshAsync(laptop.Remote, new SyncPolicy(), context.Cancellation);
|
||||
await laptop.WaitAsync((await laptop.Sync.EnqueueDownloadAsync(laptop.Engine, laptop.Server, remoteId, "Star trails", SyncDownloadMode.Originals,
|
||||
laptop.Archive.Id)).Id);
|
||||
Assert.Equal(1, (await laptop.EntryAsync("Star trails")).Link!.ExportsToGet);
|
||||
await laptop.WaitAsync((await laptop.Sync.EnqueueDownloadAsync(laptop.Engine, laptop.Server, remoteId, "Star trails", SyncDownloadMode.Exports, null)).Id);
|
||||
var copy = (await laptop.EntryAsync("Star trails")).Local!;
|
||||
var fetched = Assert.Contains(await laptop.Db.Renders.ListBySequenceAsync(copy.Id), r => r.Id == render.Id);
|
||||
Assert.SequenceEqual(output, await File.ReadAllBytesAsync(Path.Combine(laptop.Archive.RootPath, fetched.OutputPath)));
|
||||
Assert.Equal(0, (await laptop.EntryAsync("Star trails")).Link!.ExportsToGet);
|
||||
}
|
||||
|
||||
private Task<TestServer> StartServerAsync() => TestServer.StartAsync(context, o => o.ChunkSizeBytes = 64 * 1024, ArchiveModule.Register);
|
||||
|
||||
/// <summary>Waits until the server's engines finished what the commits queued (thumbnails, proxies, analysis, which may edit settings).</summary>
|
||||
private Task ServerIdleAsync(TestServer server) =>
|
||||
UntilAsync(async () => await server.Database.Jobs.CountAsync(DateTimeOffset.UtcNow) is { Queued: 0, Running: 0 }, "the server's jobs");
|
||||
|
||||
private async Task UntilAsync(Func<Task<bool>> condition, string what)
|
||||
{
|
||||
var until = DateTime.UtcNow.AddSeconds(60);
|
||||
while (!await condition())
|
||||
{
|
||||
if (DateTime.UtcNow > until) Assert.Fail("Timed out waiting for " + what);
|
||||
await Task.Delay(50, context.Cancellation);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user