test(sync): state, settings conflicts, transfers and agent against an in-memory server

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 22:29:49 +00:00
1 parent b79e4ed6d9
commit 7f542646b4
10 files changed
+1006

No files matched your search

+7
View File
@@ -18,6 +18,13 @@
<data name="Errors.Render.Sequence" xml:space="preserve"><value>The sequence to render is no longer in the archive.</value></data>
<data name="Errors.Server.Address" xml:space="preserve"><value>Enter a server address such as nas.local:8443 or https://titano.example.com.</value></data>
<data name="Errors.Settings.Import" xml:space="preserve"><value>This file does not contain Titano settings.</value></data>
<data name="Errors.Sync.DiskFull" xml:space="preserve"><value>The archive disk needs {0} GB more for these originals.</value><comment>{0} gigabytes missing</comment></data>
<data name="Errors.Sync.Hash" xml:space="preserve"><value>{0} did not arrive intact; download it again.</value><comment>{0} file name</comment></data>
<data name="Errors.Sync.LocalMissing" xml:space="preserve"><value>The sequence is no longer in this PC's archive index.</value></data>
<data name="Errors.Sync.NoArchive" xml:space="preserve"><value>Open or create an archive on this PC to receive the originals.</value></data>
<data name="Errors.Sync.NotConnected" xml:space="preserve"><value>Not connected to this server; connect and retry the job.</value></data>
<data name="Errors.Sync.Unreadable.one" xml:space="preserve"><value>{0} original is missing or changed since it was archived; verify the archive.</value><comment>{0} count</comment></data>
<data name="Errors.Sync.Unreadable.other" xml:space="preserve"><value>{0} originals are missing or changed since they were archived; verify the archive.</value><comment>{0} count</comment></data>
<data name="Errors.Template.Empty" xml:space="preserve"><value>The template is empty.</value></data>
<data name="Errors.Template.EmptyToken" xml:space="preserve"><value>Empty token at position {1}: write a name between the braces.</value></data>
<data name="Errors.Template.FileSeparator" xml:space="preserve"><value>File names cannot contain a slash; put folders in the folder template.</value></data>
+1
View File
@@ -33,6 +33,7 @@
<data name="Jobs.History.other" xml:space="preserve"><value>History keeps {0} days</value></data>
<data name="Jobs.Kind.Adopt" xml:space="preserve"><value>Adopt folder</value></data>
<data name="Jobs.Kind.DeepAnalyse" xml:space="preserve"><value>Deep analysis</value></data>
<data name="Jobs.Kind.Download" xml:space="preserve"><value>Download</value></data>
<data name="Jobs.Kind.Duplicates" xml:space="preserve"><value>Duplicates</value></data>
<data name="Jobs.Kind.Import" xml:space="preserve"><value>Import</value></data>
<data name="Jobs.Kind.LightAnalyse" xml:space="preserve"><value>Light analysis</value></data>
+7
View File
@@ -18,6 +18,13 @@
<data name="Errors.Render.Sequence" xml:space="preserve"><value>La sequenza da renderizzare non è più nell'archivio.</value></data>
<data name="Errors.Server.Address" xml:space="preserve"><value>Inserisci l'indirizzo di un server, ad esempio nas.local:8443 o https://titano.example.com.</value></data>
<data name="Errors.Settings.Import" xml:space="preserve"><value>Questo file non contiene impostazioni di Titano.</value></data>
<data name="Errors.Sync.DiskFull" xml:space="preserve"><value>Al disco dell'archivio servono altri {0} GB per questi originali.</value></data>
<data name="Errors.Sync.Hash" xml:space="preserve"><value>{0} non è arrivato integro; scaricalo di nuovo.</value></data>
<data name="Errors.Sync.LocalMissing" xml:space="preserve"><value>La sequenza non è più nell'indice dell'archivio di questo PC.</value></data>
<data name="Errors.Sync.NoArchive" xml:space="preserve"><value>Apri o crea un archivio su questo PC per ricevere gli originali.</value></data>
<data name="Errors.Sync.NotConnected" xml:space="preserve"><value>Non connesso a questo server; collegati e riprova l'attività.</value></data>
<data name="Errors.Sync.Unreadable.one" xml:space="preserve"><value>{0} originale manca o è cambiato dopo l'archiviazione; verifica l'archivio.</value></data>
<data name="Errors.Sync.Unreadable.other" xml:space="preserve"><value>{0} originali mancano o sono cambiati dopo l'archiviazione; verifica l'archivio.</value></data>
<data name="Errors.Template.Empty" xml:space="preserve"><value>Il modello è vuoto.</value></data>
<data name="Errors.Template.EmptyToken" xml:space="preserve"><value>Segnaposto vuoto alla posizione {1}: scrivi un nome tra le parentesi graffe.</value></data>
<data name="Errors.Template.FileSeparator" xml:space="preserve"><value>I nomi dei file non possono contenere la barra; metti le cartelle nel modello delle cartelle.</value></data>
+1
View File
@@ -33,6 +33,7 @@
<data name="Jobs.History.other" xml:space="preserve"><value>Cronologia di {0} giorni</value></data>
<data name="Jobs.Kind.Adopt" xml:space="preserve"><value>Adozione cartella</value></data>
<data name="Jobs.Kind.DeepAnalyse" xml:space="preserve"><value>Analisi approfondita</value></data>
<data name="Jobs.Kind.Download" xml:space="preserve"><value>Scaricamento</value></data>
<data name="Jobs.Kind.Duplicates" xml:space="preserve"><value>Duplicati</value></data>
<data name="Jobs.Kind.Import" xml:space="preserve"><value>Importazione</value></data>
<data name="Jobs.Kind.LightAnalyse" xml:space="preserve"><value>Analisi rapida</value></data>
@@ -0,0 +1,205 @@
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>();
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; }
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.Select(s => s.Dto())]);
}
}
public Task<SequenceDto> GetSequenceAsync(Guid id, CancellationToken cancellationToken)
{
lock (_gate) return Task.FromResult(Find(id).Dto());
}
public Task<SequenceManifest> GetManifestAsync(Guid id, CancellationToken cancellationToken)
{
lock (_gate)
{
ManifestCalls++;
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> CreateSequenceAsync(CreateSequenceRequest request, CancellationToken cancellationToken)
{
var sequence = Add(request.Title, []);
return Task.FromResult(sequence.Dto());
}
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());
}
}
public async Task<CompleteUploadResponse?> UploadFileAsync(string path, Guid sequenceId, string sha256, DateTime? capturedAt, CancellationToken cancellationToken)
{
var bytes = await File.ReadAllBytesAsync(path, cancellationToken);
if (Convert.ToHexStringLower(SHA256.HashData(bytes)) != sha256)
throw new TitanoApiException(HttpStatusCode.BadRequest, new ApiError("hash_mismatch", "hash"));
lock (_gate)
{
var s = Find(sequenceId);
var existing = s.Frames.FindIndex(f => f.Sha256 == sha256);
if (existing >= 0) return new CompleteUploadResponse(s.Frames[existing].Id, sequenceId, existing);
var frame = s.AddFrame(bytes, Path.GetFileName(path), capturedAt);
return new CompleteUploadResponse(frame.Id, sequenceId, s.Frames.Count - 1);
}
}
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" 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 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 List<FakeFrame> Frames { 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", "Canon EOS R5", null, null, null, Frames.Count, 10,
Frames.Sum(f => (long)f.Bytes.Length), (long)Status, 0, 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))], []);
}
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,99 @@
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 KeepingProxiesOfflineQueuesThemForRemoteSequences()
{
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 remote = f.Remote.Add("Construction cam", f.NewPhotos(2));
f.Remote.Add("No proxies yet", f.NewPhotos(1), status: SequenceStatus.ThumbsBuilt);
var engine = await f.StartEngineAsync();
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.Null(f.Sync.OpenRemote(f.Server, remote.Id));
keep = true;
await agent.RefreshAsync(f.Ct);
await WaitAsync(() => f.Sync.OpenRemote(f.Server, remote.Id) is { CachedCount: 2 }, "proxies of the remote sequence");
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 == "No proxies yet").Status);
Assert.Equal(SyncStatus.InSync, entries.Single(e => e.Title == "Harbour").Status);
}
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);
}
}
}
+108
View File
@@ -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,97 @@
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 MetadataMergeUnitesTagsAndTakesTheRestFromTheNewerSide()
{
var mine = new SyncPayload("Harbour", ["sunset", "Harbour"], 3, "mine", SyncFixture.Window41);
var theirs = new SyncPayload("Harbour at dusk", ["harbour", "boats"], 5, null, SyncFixture.Window41);
var newerHere = SyncRules.Merge(mine, theirs, localIsNewer: true);
Assert.Equal("Harbour", newerHere.Title);
Assert.Equal(3, newerHere.Rating);
Assert.SequenceEqual(["sunset", "Harbour", "boats"], newerHere.Tags);
var newerThere = SyncRules.Merge(mine, theirs, localIsNewer: false);
Assert.Equal("Harbour at dusk", newerThere.Title);
Assert.Null(newerThere.Notes);
Assert.True(newerThere.SameMetadata(newerThere with { Tags = ["BOATS", "harbour", "SUNSET"] }), "tags ignore case and order");
}
}
@@ -0,0 +1,285 @@
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, f.Ct);
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, remote.SettingsJson));
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status);
}
[Test]
public async Task OnlyMetadataChangedOnBothSidesIsMergedWithoutAConflict()
{
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();
// The server is edited first, so this PC's later title and rating win; tags are united.
await f.Remote.UpdateSequenceAsync(remote.Id, new UpdateSequenceRequest(null, ["boats"], 2, null, null, null), f.Ct);
await Task.Delay(20, f.Ct);
await f.Archive.Service.SetSequenceInfoAsync(local.Id, "Harbour", ["sunset"], 4, null, f.Ct);
await f.RefreshAsync();
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status);
var merged = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
Assert.True(merged.Tags.ToHashSet().SetEquals(["sunset", "boats"]), string.Join(",", merged.Tags));
Assert.True(remote.Tags.ToHashSet().SetEquals(["sunset", "boats"]), string.Join(",", remote.Tags));
Assert.Equal(4, remote.Rating);
}
[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!.ConflictSettingsJson), "the server's side is kept for display");
Assert.Equal("exposure.deflickerWindow.manual", SyncRules.Differences(entry.Local.SettingsJson, entry.Link.ConflictSettingsJson)[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.local-*.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);
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));
var copy = Assert.Contains(Directory.GetFiles(f.Archive.Paths.Sequence(taken.Folder).MetaDirectory, "project.local-*.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 KeepMineRefusesWhenTheServerChangedAgainMeanwhile()
{
await using var f = await SyncFixture.CreateAsync(context);
var (_, remote) = await ConflictAsync(f);
var racing = new RacingRemote(f.Remote, () => f.Remote.EditSettings(remote.Id, SyncFixture.Window33.Replace("33", "35", StringComparison.Ordinal)));
var error = await Assert.ThrowsAsync<TitanoApiException>(() => f.Sync.ResolveAsync(racing, remote.Id, SyncResolution.KeepMine, f.Ct));
Assert.Equal(System.Net.HttpStatusCode.Conflict, error.Status);
Assert.True(SyncRules.SameSettings(SyncFixture.Window33.Replace("33", "35", StringComparison.Ordinal), remote.SettingsJson), "nothing overwritten");
}
[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);
}
/// <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.</summary>
private sealed class RacingRemote(FakeSyncRemote inner, Action race) : 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);
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> CreateSequenceAsync(CreateSequenceRequest request, CancellationToken cancellationToken) => inner.CreateSequenceAsync(request, cancellationToken);
public Task<SequenceDto> UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken) => inner.UpdateSequenceAsync(id, request, cancellationToken);
public Task<CompleteUploadResponse?> UploadFileAsync(string path, Guid sequenceId, string sha256, DateTime? capturedAt, CancellationToken cancellationToken) =>
inner.UploadFileAsync(path, sequenceId, sha256, capturedAt, cancellationToken);
public Task DownloadFrameAsync(Guid frameId, string kind, Stream destination, CancellationToken cancellationToken) =>
inner.DownloadFrameAsync(frameId, kind, destination, cancellationToken);
public IAsyncEnumerable<ServerEvent> EventsAsync(CancellationToken cancellationToken) => inner.EventsAsync(cancellationToken);
public void Dispose()
{
}
}
}
@@ -0,0 +1,196 @@
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.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 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 string Sha(byte[] bytes) => Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(bytes));
}