refactor!: rename Titano to Chronos and move CI and releases to Gitea
CI / Build and test (pull_request) Failing after 2m3s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / Docker image (pull_request) Skipped
CI / Windows tests and installer (pull_request) Skipped
CI / YAML check (pull_request) Successful in 4s

The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout. The release cross-compiles the Windows programs, checks their
  icon, version and DPI manifest, packs installers and zips, publishes the
  Gitea release and pushes the server image (REGISTRY_TOKEN). Windows-only
  tests run in an opt-in job on a Windows runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow) and
  pe-check.

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-10-23 11:34:48 +02:00
1 parent c99842cc86
commit 5f27a86406
1799 files changed
+11728 -10668

No files matched your search

@@ -0,0 +1,317 @@
using System.Net;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Threading.Channels;
using Chronos.Core.Metadata;
using Chronos.Core.Model;
using Chronos.Data.Sync;
using Chronos.Protocol;
using Chronos.Protocol.Client;
namespace Chronos.Data.Tests.Sync;
/// <summary>An in-memory Chronos 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; }
/// <summary>
/// Assets (frame id, kind) the sequence's flags offer that the server has not drawn yet: frames added since its last
/// thumbnail or proxy pass answer 404 until that pass ends, as the real endpoints do.
/// </summary>
public HashSet<(Guid Frame, string Kind)> Undrawn { get; } = [];
/// <summary>Proxies clients sent, by frame id (for sequences the server cannot decode).</summary>
public Dictionary<Guid, byte[]> SentProxies { get; } = [];
/// <summary>Edits the server accepted, in order.</summary>
public List<UpdateSequenceRequest> Updates { get; } = [];
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 ChronosApiException(HttpStatusCode.Forbidden, new ApiError("forbidden", "refused"));
return Task.FromResult(Find(id).Manifest(SentProxies.ContainsKey));
}
}
public Task<IReadOnlyList<FrameDto>> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken)
{
lock (_gate)
{
var sequence = Find(sequenceId);
return Task.FromResult<IReadOnlyList<FrameDto>>([.. sequence.Frames.Select(sequence.FrameDto)]);
}
}
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 ChronosApiException(HttpStatusCode.Conflict, new ApiError("settings_conflict", "changed"));
if (request.ExpectedFramesVersion is { } frames && frames != s.FramesVersion)
throw new ChronosApiException(HttpStatusCode.Conflict, new ApiError("frames_conflict", "changed"));
Updates.Add(request);
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 ChronosApiException(HttpStatusCode.BadRequest, new ApiError("hash_mismatch", "hash"));
lock (_gate)
{
// Originals it never hashed are not recognised by content.
if (Sequences.Values.Where(s => !s.Unhashed).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 ChronosApiException(HttpStatusCode.InternalServerError, new ApiError("internal", "failed")),
"proxy" or "thumb" when Undrawn.Contains((frameId, kind)) => throw NotFound(),
// A proxy a client or render node sent is served as soon as it is filed, like the manifest says.
"proxy" when SentProxies.TryGetValue(frameId, out var sent) => sent,
"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);
}
/// <summary>Like the server: only a frame whose proxy it asks for takes one, and only a JPEG.</summary>
public Task UploadProxyAsync(Guid frameId, byte[] jpeg, CancellationToken cancellationToken)
{
lock (_gate)
{
if (!Sequences.Values.Any(s => s.Undecodable && s.Frames.Any(f => f.Id == frameId))) throw NotFound();
if (jpeg is not [0xFF, 0xD8, ..]) throw new ChronosApiException(HttpStatusCode.UnprocessableEntity, new ApiError("invalid_proxy", "not a JPEG"));
SentProxies[frameId] = jpeg;
}
return Task.CompletedTask;
}
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 ChronosApiException(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 ChronosApiException 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; }
/// <summary>The server cannot decode these originals (HEIF): its manifest asks for proxies of them.</summary>
public bool Undecodable { get; set; }
/// <summary>The server adopted these originals and never verified them: it lists no SHA-256 for them.</summary>
public bool Unhashed { 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; } = [];
/// <summary>Like the server, the capture time comes from the photo's Exif data when none is given.</summary>
public FakeFrame AddFrame(byte[] bytes, string? name = null, DateTime? capturedAt = null) => InsertFrame(Frames.Count, bytes, name, capturedAt);
/// <summary>A photo filed at <paramref name="index"/> (captured before the frames after it): those move up by one.</summary>
public FakeFrame InsertFrame(int index, byte[] bytes, string? name = null, DateTime? capturedAt = null)
{
name ??= $"IMG_{Frames.Count + 1:0000}.JPG";
using var stream = new MemoryStream(bytes);
var frame = new FakeFrame(Guid.CreateVersion7(), name, bytes, capturedAt ?? MetadataReader.Read(stream, name).CapturedAt);
Frames.Insert(index, 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(Func<Guid, bool> proxySent) => new(Id, FramesVersion, SettingsVersion, SettingsJson, Tags,
[.. Frames.Select((f, i) => new ManifestFrame(f.Id, i, f.FileName, f.Bytes.Length, Unhashed ? string.Empty : f.Sha256,
(Status & SequenceStatus.ProxiesBuilt) != 0 || proxySent(f.Id), (Status & SequenceStatus.ThumbsBuilt) != 0, WantsProxy: Undecodable && !proxySent(f.Id)))],
[.. Renders.Select(r => r.Dto())], Undecodable ? new ProxySpec(1280, 90) : null);
public FrameDto FrameDto(FakeFrame frame) => frame.Dto(Id, Frames.IndexOf(frame), Unhashed);
}
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, bool unhashed = false) =>
new(Id, sequenceId, index, FileName, Bytes.Length, unhashed ? null : Sha256, CapturedAt, null, 1.0 / 250, 8, 100, 24, 1, 48, 32, "jpeg", 0);
}
@@ -0,0 +1,318 @@
using Chronos.Core.Model;
using Chronos.Data.Sync;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.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>How long any wait may take on a loaded runner; every wait ends as soon as what it waits for happened.</summary>
private static readonly TimeSpan Deadline = TimeSpan.FromSeconds(30);
/// <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!;
await ComparedAfterAsync(f, () =>
{
f.Remote.EditSettings(remote.Id, SyncFixture.Window33);
f.Remote.Publish(new SequenceChangedEvent(remote.Id, "settings", remote.FramesVersion, remote.SettingsVersion));
}, "the comparison of the server's edit");
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson),
"the server's edit reached this PC");
await ComparedAfterAsync(f, () =>
{
var created = f.Remote.Add("New on the server", f.NewPhotos(1));
f.Remote.Publish(new SequenceChangedEvent(created.Id, "created", 1, 1));
}, "the comparison of a sequence created on the server");
Assert.Contains(await f.Sync.ListAsync(f.Server, f.Ct), e => e.Title == "New 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;
var compared = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using var agent = new SyncAgent(f.Sync, f.Remote, () => new SyncPolicy(), null, EventsOnly);
// The agent stores the snapshot, then clears the last error, then raises Changed: only Changed sees both.
agent.Changed += () =>
{
Interlocked.Increment(ref changes);
if (agent.Snapshot is not null) compared.TrySetResult();
};
agent.Start();
await SignalAsync(compared.Task, "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");
await ComparedAfterAsync(f, () =>
{
f.Remote.TimeoutOnce = remote.Id;
f.Remote.Publish(new SequenceChangedEvent(remote.Id, "settings", remote.FramesVersion, remote.SettingsVersion));
}, "the comparison that timed out");
Assert.NotNull((await f.EntryAsync("Harbour")).Link!.Error);
await ComparedAfterAsync(f, () =>
{
f.Remote.EditSettings(remote.Id, SyncFixture.Window33);
f.Remote.Publish(new SequenceChangedEvent(remote.Id, "settings", remote.FramesVersion, remote.SettingsVersion));
}, "the comparison of a later event");
Assert.True(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);
// The download writes the cache, then the link, and only then ends: until it ends its row shows a transfer.
var refresh = Assert.Contains(await DownloadsAsync(f), j => j.Id != first.Id);
await f.Archive.WaitForAsync(refresh.Id, JobState.Done);
Assert.Equal(3, Assert.NotNull(f.Sync.OpenRemote(f.Server, opened.Id)).CachedCount, "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);
}
[Test]
public async Task ThumbnailsStandingInAreReplacedOnceTheServerOffersTheirProxies()
{
await using var f = await SyncFixture.CreateAsync(context);
// The server cannot decode these originals and waits for their proxies; one frame (missing or damaged) never gets
// one, so the sequence's proxy flag never comes.
var remote = f.Remote.Add("Fog", f.NewPhotos(3), status: SequenceStatus.ThumbsBuilt);
remote.Undecodable = true;
var engine = await f.StartEngineAsync();
await f.RefreshAsync();
var first = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Fog", SyncDownloadMode.Proxies, null);
await f.Archive.WaitForAsync(first.Id, JobState.Done);
Assert.True(Assert.NotNull(f.Sync.OpenRemote(f.Server, remote.Id)).Files.All(file => new FileInfo(file!).Length == 64), "thumbnails stand in");
await using var agent = new SyncAgent(f.Sync, f.Remote, () => new SyncPolicy(KeepProxiesOffline: true), engine, EventsOnly);
agent.Start();
await WaitAsync(() => agent.Snapshot is not null, "first comparison");
await agent.RefreshAsync(f.Ct);
Assert.Count(1, await DownloadsAsync(f));
// Another PC sends the proxies of two frames; the server's proxy pass then records the sequence's state.
foreach (var frame in remote.Frames.Take(2)) f.Remote.SentProxies[frame.Id] = frame.Proxy;
remote.UpdatedAt = DateTimeOffset.UtcNow.AddSeconds(1);
await agent.RefreshAsync(f.Ct);
var refresh = Assert.Contains(await DownloadsAsync(f), j => j.Id != first.Id);
await f.Archive.WaitForAsync(refresh.Id, JobState.Done);
var opened = Assert.NotNull(f.Sync.OpenRemote(f.Server, remote.Id));
Assert.SequenceEqual([remote.Frames[0].Proxy.Length, remote.Frames[1].Proxy.Length, 64], opened.Files.Select(file => (int)new FileInfo(file!).Length));
// The frame still waiting keeps its thumbnail; nothing is queued again until the server's sequence changes.
await agent.RefreshAsync(f.Ct);
Assert.Count(2, await DownloadsAsync(f));
}
[Test]
public async Task FramesTheServerHadNotDrawnAreFetchedAgainOnceItDid()
{
await using var f = await SyncFixture.CreateAsync(context);
var remote = f.Remote.Add("Construction cam", f.NewPhotos(2));
var engine = await f.StartEngineAsync();
await f.RefreshAsync();
var first = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Construction cam", SyncDownloadMode.Proxies, null);
await f.Archive.WaitForAsync(first.Id, JobState.Done);
await using var agent = new SyncAgent(f.Sync, f.Remote, () => new SyncPolicy(KeepProxiesOffline: true), engine, EventsOnly);
agent.Start();
await WaitAsync(() => agent.Snapshot is not null, "first comparison");
// A photo reaches the server, whose proxy flag stays set until its next proxy pass draws the photo: the refresh
// that follows the upload caches nothing for it.
var added = remote.AddFrame(f.NewPhotos(1)[0]);
f.Remote.Undrawn.UnionWith([(added.Id, "proxy"), (added.Id, "thumb")]);
await agent.RefreshAsync(f.Ct);
var refresh = Assert.Contains(await DownloadsAsync(f), j => j.Id != first.Id);
await f.Archive.WaitForAsync(refresh.Id, JobState.Done);
Assert.Null(Assert.NotNull(f.Sync.OpenRemote(f.Server, remote.Id)).Files[2]);
Assert.True((await f.EntryAsync("Construction cam")).Link!.ProxiesStale);
// Nothing is fetched again while the server's sequence stands still.
await agent.RefreshAsync(f.Ct);
Assert.Count(2, await DownloadsAsync(f));
// The pass draws the photo and records the sequence's state.
f.Remote.Undrawn.Clear();
remote.UpdatedAt = DateTimeOffset.UtcNow.AddSeconds(1);
await agent.RefreshAsync(f.Ct);
var drawn = Assert.Contains(await DownloadsAsync(f), j => j.Id != first.Id && j.Id != refresh.Id);
await f.Archive.WaitForAsync(drawn.Id, JobState.Done);
var opened = Assert.NotNull(f.Sync.OpenRemote(f.Server, remote.Id));
Assert.SequenceEqual(remote.Frames.Select(r => (long)r.Proxy.Length), opened.Files.Select(file => new FileInfo(file!).Length));
Assert.False((await f.EntryAsync("Construction cam")).Link!.ProxiesStale);
await agent.RefreshAsync(f.Ct);
Assert.Count(3, await DownloadsAsync(f));
}
[Test]
public async Task AStandInDownloadThatFailedIsQueuedAgainAfterItsBackoff()
{
await using var f = await SyncFixture.CreateAsync(context);
var remote = f.Remote.Add("Fog", f.NewPhotos(3), status: SequenceStatus.ThumbsBuilt);
remote.Undecodable = true;
var engine = await f.StartEngineAsync();
await f.RefreshAsync();
var first = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Fog", SyncDownloadMode.Proxies, null);
await f.Archive.WaitForAsync(first.Id, JobState.Done);
await using var agent = new SyncAgent(f.Sync, f.Remote, () => new SyncPolicy(KeepProxiesOffline: true), engine, EventsOnly);
agent.Start();
await WaitAsync(() => agent.Snapshot is not null, "first comparison");
// Two frames' proxies reach the server, but their download fails (the server restarts meanwhile).
foreach (var frame in remote.Frames.Take(2)) f.Remote.SentProxies[frame.Id] = frame.Proxy;
remote.UpdatedAt = DateTimeOffset.UtcNow.AddSeconds(1);
f.Remote.FailAssets = true;
await agent.RefreshAsync(f.Ct);
var failed = Assert.Contains(await DownloadsAsync(f), j => j.Id != first.Id);
await f.Archive.WaitForAsync(failed.Id, JobState.Failed);
// The server's sequence does not change again: once the backoff has passed, the download is queued anyway.
f.Remote.FailAssets = false;
await WaitAsync(async () =>
{
await agent.RefreshAsync(f.Ct);
return (await DownloadsAsync(f)).Count == 3;
}, "the download queued again");
var retry = Assert.Contains(await DownloadsAsync(f), j => j.Id != first.Id && j.Id != failed.Id);
await f.Archive.WaitForAsync(retry.Id, JobState.Done);
var opened = Assert.NotNull(f.Sync.OpenRemote(f.Server, remote.Id));
Assert.SequenceEqual([remote.Frames[0].Proxy.Length, remote.Frames[1].Proxy.Length, 64], opened.Files.Select(file => (int)new FileInfo(file!).Length));
}
private static async Task<IReadOnlyList<Job>> DownloadsAsync(SyncFixture f) =>
(await f.Db.Jobs.ListAsync(null, JobKind.Download, 100, null, f.Ct)).Items;
/// <summary>
/// Runs <paramref name="cause"/> and returns once the comparison it starts has finished. The engine raises
/// <see cref="SyncService.Changed"/> after a comparison stored every link and state, the moment the Server screen
/// reloads; a poll could instead see the local copy updated before the link that goes with it is stored. No other
/// comparison may be running.
/// </summary>
private async Task ComparedAfterAsync(SyncFixture f, Action cause, string what)
{
// Continuations run on the pool, not inside the agent loop that raises Changed and that the test later stops.
var compared = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
Action<string> onChanged = _ => compared.TrySetResult();
f.Sync.Changed += onChanged;
try
{
cause();
await SignalAsync(compared.Task, what);
}
finally
{
f.Sync.Changed -= onChanged;
}
}
private async Task SignalAsync(Task signal, string what)
{
try
{
await signal.WaitAsync(Deadline, context.Cancellation);
}
catch (TimeoutException)
{
Assert.Fail("Timed out waiting for " + what);
}
}
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 + Deadline;
while (!await condition())
{
if (DateTime.UtcNow > until) Assert.Fail("Timed out waiting for " + what);
await Task.Delay(20, context.Cancellation);
}
}
}
@@ -0,0 +1,120 @@
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Data.Sync;
using Chronos.Data.Tests.Archiving;
using Chronos.Testing;
namespace Chronos.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 ChronosDatabase 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>Files one more original into a local sequence through the archive ingest (an earlier photo lands before the others).</summary>
public async Task AddLocalAsync(Guid sequenceId, byte[] original)
{
var staging = Path.Combine(Archive.Paths.StagingDirectory, "test");
Directory.CreateDirectory(staging);
var path = Path.Combine(staging, $"{Guid.NewGuid():N}.part");
await File.WriteAllBytesAsync(path, original, Ct);
var sha = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(original));
await Archive.Service.Ingest.CommitAsync(new IngestRequest(Archive.Archive.Id, sequenceId, null, null, path, $"IMG_{sha[..8]}.JPG", original.Length, sha,
null, null), Ct);
}
/// <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 Chronos.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,196 @@
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Sync;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.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 FramesEitherSideHasNotHashedAreMatchedBySizeAndCaptureTime()
{
var time = new DateTime(2026, 9, 28, 18, 0, 0);
FramePhoto Photo(string? sha, long size, int second) => new(sha, size, time.AddSeconds(second));
// A folder the server adopted and never verified: each of its frames counts on its own, matched by size and time.
Assert.Equal((0, 0), SyncRules.CompareOriginals([Photo("aa", 100, 0), Photo("bb", 200, 10)], [Photo("", 100, 0), Photo("", 200, 10)]));
Assert.Equal((1, 2), SyncRules.CompareOriginals([Photo("aa", 100, 0), Photo("bb", 200, 10)], [Photo("", 100, 0), Photo("", 300, 20), Photo("", 400, 30)]));
Assert.Equal((0, 3), SyncRules.CompareOriginals(Array.Empty<string?>(), ["", "", ""]));
// Hashed on both sides, the hash decides even when size and time agree.
Assert.Equal((1, 1), SyncRules.CompareOriginals([Photo("aa", 100, 0)], [Photo("cc", 100, 0)]));
// A photo the adopted folder holds twice ('IMG_0001.JPG' and 'IMG_0001 (1).JPG') is here in this PC's one copy,
// as the download finds it: nothing is left to fetch.
Assert.Equal((0, 0), SyncRules.CompareOriginals([Photo("aa", 100, 0)], [Photo("", 100, 0), Photo("", 100, 0)]));
Assert.Equal((0, 0), SyncRules.CompareOriginals([Photo(null, 100, 0)], [Photo("", 100, 0), Photo("", 100, 0)]));
Assert.Equal((0, 1), SyncRules.CompareOriginals([Photo("aa", 100, 0)], [Photo("", 100, 0), Photo("", 100, 0), Photo("", 100, 10)]));
}
[Test]
public void ProxiesOfFramesTheServerHasNotHashedAreCountedByCaptureTime()
{
var heif = new ImageDecoder([new NativeHeif()]);
var time = new DateTime(2026, 9, 28, 18, 0, 0);
List<Frame> local =
[
Original("aa", 100, ImageFileFormat.Heif) with { CapturedAt = time },
Original("bb", 200, ImageFileFormat.Heif) with { CapturedAt = time.AddSeconds(10) },
];
var first = Wanted(string.Empty, 100, "IMG_0001.HEIC");
var second = Wanted(string.Empty, 200, "IMG_0002.HEIC");
var manifest = new SequenceManifest(Guid.CreateVersion7(), 1, 1, null, [], [first, second], [], new ProxySpec(1920, 90));
var captured = new Dictionary<Guid, DateTime?> { [first.Id] = time, [second.Id] = time.AddSeconds(11) };
Assert.Equal(1, SyncRules.ProxiesToSend(manifest, local, heif, captured));
Assert.Equal(0, SyncRules.ProxiesToSend(manifest, local, heif));
Assert.Same(local[0], SyncRules.ProxyOriginal(first, time, local, SyncRules.Photos(local)));
Assert.Null(SyncRules.ProxyOriginal(second, time.AddSeconds(11), local, SyncRules.Photos(local)));
}
[Test]
public void ProxiesTheServerAsksForAreCountedForOriginalsThisPcReads()
{
var heif = new ImageDecoder([new NativeHeif()]);
List<Frame> local =
[
Original("aa", 100, ImageFileFormat.Heif),
Original(null, 200, ImageFileFormat.Heif),
Original(null, 300, ImageFileFormat.Heif),
Original("dd", 400, ImageFileFormat.Avif),
];
var manifest = new SequenceManifest(Guid.CreateVersion7(), 1, 1, null, [],
[
Wanted("AA", 100, "2026-10-01_0001.heic"),
// Not hashed here: matched by size, whatever name the server gave its copy.
Wanted("bb", 200, "2026-10-01_0002.heic"),
Wanted("cc", 999, "IMG_0003.HEIC"),
// The server has no hash of it yet: nothing tells which original it is.
Wanted(string.Empty, 300, "IMG_0004.HEIC"),
// This PC cannot decode AVIF.
Wanted("dd", 400, "IMG_0005.AVIF"),
Wanted("ee", 200, "IMG_0006.HEIC") with { WantsProxy = false },
], [], new ProxySpec(1920, 90));
Assert.Equal(2, SyncRules.ProxiesToSend(manifest, local, heif));
Assert.Equal(0, SyncRules.ProxiesToSend(manifest, local, DecoderFactory.CreateServer()));
Assert.True(SyncRules.MakesProxiesFor(local, heif), "HEIF the server cannot decode and this PC can");
Assert.False(SyncRules.MakesProxiesFor(local, DecoderFactory.CreateServer()), "a PC that reads no more than the server");
Assert.False(SyncRules.MakesProxiesFor([Original("aa", 100, ImageFileFormat.Jpeg)], heif), "the server decodes JPEG itself");
}
[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"] }));
}
private static Frame Original(string? sha, long size, ImageFileFormat format) => new()
{
Id = Guid.CreateVersion7(),
SequenceId = Local.Id,
Index = (int)(size / 100),
RelativePath = $"2026/a/{size}",
FileName = $"{size}",
Size = size,
Sha256 = sha,
Format = format,
};
private static ManifestFrame Wanted(string sha, long size, string name) =>
new(Guid.CreateVersion7(), (int)(size / 100), name, size, sha, HasProxy: false, HasThumb: true, WantsProxy: true);
/// <summary>A provider that decodes HEIF natively (WIC with the HEIF extension on a desktop).</summary>
private sealed class NativeHeif : IImageDecoderProvider
{
public string Name => "native-heif";
public DecodeTier? TierFor(ImageFileFormat format) => format == ImageFileFormat.Heif ? DecodeTier.Native : null;
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default) => null;
}
}
@@ -0,0 +1,669 @@
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Archiving;
using Chronos.Data.Sync;
using Chronos.Data.Tests.Archiving;
using Chronos.Protocol;
using Chronos.Protocol.Client;
using Chronos.Testing;
namespace Chronos.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 PositionsSentToTheServerNameItsFramesAndWaitForPhotosItLacks()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(5);
var local = await f.LocalAsync("Harbour", photos);
// The server lacks the earliest photo (not uploaded yet).
var remote = f.Remote.Add("Harbour", photos[1..]);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
await f.EditLocalSettingsAsync(local.Id, new ProjectSettings { ExcludedFrames = [0, 2], HeroFrame = 4 }.ToJson());
await f.RefreshAsync();
var sent = ProjectSettings.FromJson(remote.SettingsJson!);
Assert.SequenceEqual([Sha(photos[2])], sent.ExcludedFrames.Select(i => remote.Frames[i].Sha256));
Assert.Equal(Sha(photos[4]), remote.Frames[sent.HeroFrame!.Value].Sha256);
Assert.Count(1, sent.PendingFrames!);
var waiting = sent.PendingFrames![0];
Assert.True(waiting.Excluded && waiting.Sha256 == Sha(photos[0]), "the exclusion of the photo the server lacks waits for it");
Assert.Equal(remote.FramesVersion, f.Remote.Updates[^1].ExpectedFramesVersion);
// This PC's project keeps its own positions.
Assert.SequenceEqual([0, 2], ProjectSettings.FromJson((await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson!).ExcludedFrames);
Assert.Equal(SyncStatus.LocalAhead, (await f.EntryAsync("Harbour")).Status);
Assert.Equal(1, (await f.EntryAsync("Harbour")).Link!.MissingRemote);
}
[Test]
public async Task SettingsSentWhileTheServersFramesChangeAreTranslatedAgain()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(4);
var local = await f.LocalAsync("Harbour", photos[1..]);
var remote = f.Remote.Add("Harbour", photos[1..]);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
await f.EditLocalSettingsAsync(local.Id, new ProjectSettings { ExcludedFrames = [1] }.ToJson());
// An earlier photo is filed on the server after the manifest was read, before the settings arrive.
var racing = new RacingRemote(f.Remote, () => remote.InsertFrame(0, photos[0]), beforeUpdate: true);
await f.Sync.RefreshAsync(racing, new SyncPolicy(), f.Ct);
Assert.Empty(f.Remote.Updates);
Assert.Equal(SyncStatus.LocalAhead, (await f.EntryAsync("Harbour")).Status);
await f.RefreshAsync();
Assert.SequenceEqual([Sha(photos[2])], ProjectSettings.FromJson(remote.SettingsJson!).ExcludedFrames.Select(i => remote.Frames[i].Sha256));
Assert.Equal((SyncStatus.ServerAhead, 1), ((await f.EntryAsync("Harbour")).Status, (await f.EntryAsync("Harbour")).Link!.MissingLocal));
}
[Test]
public async Task SettingsSentWhileAnImportHereMovesTheirPositionsStayOnTheirPhotos()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(4);
var local = await f.LocalAsync("Harbour", photos[1..]);
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, new ProjectSettings { ExcludedFrames = [1], HeroFrame = 2 }.ToJson());
// The earliest photo is imported here after the comparison read this copy, before its settings are translated.
var racing = new RacingRemote(f.Remote, () => f.AddLocalAsync(local.Id, photos[0]).GetAwaiter().GetResult(), beforeManifest: true);
await f.Sync.RefreshAsync(racing, new SyncPolicy(), f.Ct);
var mine = ProjectSettings.FromJson((await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson!);
Assert.SequenceEqual([2], mine.ExcludedFrames);
Assert.Equal(3, mine.HeroFrame);
var sent = ProjectSettings.FromJson(remote.SettingsJson!);
Assert.SequenceEqual([Sha(photos[2])], sent.ExcludedFrames.Select(i => remote.Frames[i].Sha256));
Assert.Equal(Sha(photos[3]), remote.Frames[sent.HeroFrame!.Value].Sha256);
Assert.Null(sent.PendingFrames);
}
[Test]
public async Task SettingsComparedWhileAnImportHereMovesTheirPositionsAreAgreed()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(4);
var local = await f.LocalAsync("Harbour", photos[1..]);
var remote = f.Remote.Add("Harbour", photos);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
// Both sides exclude the same photo, each by its own frames.
await f.EditLocalSettingsAsync(local.Id, new ProjectSettings { ExcludedFrames = [1] }.ToJson());
f.Remote.EditSettings(remote.Id, new ProjectSettings { ExcludedFrames = [2] }.ToJson());
var racing = new RacingRemote(f.Remote, () => f.AddLocalAsync(local.Id, photos[0]).GetAwaiter().GetResult(), beforeManifest: true);
await f.Sync.RefreshAsync(racing, new SyncPolicy(), f.Ct);
var entry = await f.EntryAsync("Harbour");
Assert.Null(entry.Link!.ConflictRemote);
Assert.Equal(entry.Local!.SettingsVersion, entry.Link.BaseLocalSettings);
Assert.Equal(remote.SettingsVersion, entry.Link.BaseRemoteSettings);
Assert.SequenceEqual([2], ProjectSettings.FromJson(entry.Local.SettingsJson!).ExcludedFrames);
}
[Test]
public async Task TheSameSettingsFromTheServerAreAgreedWhileTheArchiveIsOffline()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Harbour", photos, SyncFixture.Window41);
var remote = f.Remote.Add("Harbour", photos, SyncFixture.Window41);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status);
// The server's version moves with the same content (another PC sent the same values); the archive's drive is unplugged.
f.Remote.EditSettings(remote.Id, SyncFixture.Window41);
var aside = f.Archive.Paths.ManifestPath + ".unplugged";
File.Move(f.Archive.Paths.ManifestPath, aside);
try
{
await f.RefreshAsync();
}
finally
{
File.Move(aside, f.Archive.Paths.ManifestPath);
}
var entry = await f.EntryAsync("Harbour");
Assert.Null(entry.Link!.Error);
Assert.Equal(SyncStatus.InSync, entry.Status);
Assert.Equal(local.SettingsVersion, entry.Local!.SettingsVersion);
}
[Test]
public async Task AnEditSavedHereDuringTheComparisonIsNotReplacedByTheServers()
{
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's copy changes; the editor saves this PC's edit after the comparison read the local copy, before it
// takes the server's version.
f.Remote.EditSettings(remote.Id, SyncFixture.Window33);
var racing = new RacingRemote(f.Remote, () => f.EditLocalSettingsAsync(local.Id, SyncFixture.Window41).GetAwaiter().GetResult(),
beforeManifest: true);
await f.Sync.RefreshAsync(racing, new SyncPolicy(), f.Ct);
var entry = await f.EntryAsync("Harbour");
Assert.Equal(SyncStatus.Conflict, entry.Status);
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, entry.Local!.SettingsJson), "this PC's edit is kept");
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, await File.ReadAllTextAsync(f.Archive.Paths.Sequence(entry.Local.Folder).ProjectPath, f.Ct)));
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, entry.Link!.ConflictRemote!.SettingsJson), "the user picks");
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, remote.SettingsJson));
}
[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 InfoTakenFromTheServerLeavesPhotosAnotherWriterAddedHereToTheNextScan()
{
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 desktop sharing this PC's archive imports a photo into the sequence: its own index follows the sidecar, this one not yet.
var (desktop, archive) = await f.Archive.OtherWriterAsync();
var staged = f.Archive.Stage(ArchiveFixture.Start.AddMinutes(10), seed: 90);
await desktop.Ingest.CommitAsync(new IngestRequest(archive.Id, local.Id, null, null, staged.Path, "IMG_0009.JPG", staged.Size, staged.Sha256, null, null),
f.Ct);
// The server's new title reaches this PC meanwhile, in its index and the sidecar.
await f.Remote.UpdateSequenceAsync(remote.Id, new UpdateSequenceRequest("Harbour at dusk", null, null, null, null, null), f.Ct);
await f.RefreshAsync();
var taken = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
Assert.Equal(("Harbour at dusk", 2), (taken.Title, taken.FrameCount));
// The next scan still finds the folder changed, and indexes the photo.
Assert.Contains(local.Id, (await f.Archive.ScanAsync()).Sequences);
var row = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
Assert.Equal(("Harbour at dusk", 3), (row.Title, row.FrameCount));
}
[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 Chronos.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);
}
private static string Sha(byte[] bytes) => Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(bytes));
/// <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 edits right after the first read of a sequence, right before the first edit, or right
/// before the first manifest is read.
/// </summary>
private sealed class RacingRemote(FakeSyncRemote inner, Action race, bool beforeUpdate = false, bool beforeManifest = 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 && !beforeManifest) 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)
{
if (beforeManifest) Interlocked.Exchange(ref _race, null)?.Invoke();
return 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,610 @@
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Data.Sync;
using Chronos.Testing;
namespace Chronos.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 AnUploadSendsTheProxiesTheServerCannotMakeItself()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Holy grail", photos);
// The server has the originals already (the Uploader sent them) but cannot decode them (HEIF, BRIEF §2.3).
var remote = f.Remote.Add("Holy grail", photos);
remote.Undecodable = true;
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
var ahead = await f.EntryAsync("Holy grail");
Assert.Equal((SyncStatus.LocalAhead, 3), (ahead.Status, ahead.Link!.MissingRemote));
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
var done = await f.Archive.WaitForAsync(job.Id, JobState.Done);
Assert.True(f.Remote.SentProxies.Keys.ToHashSet().SetEquals(remote.Frames.Select(r => r.Id)), "a proxy of every frame");
foreach (var proxy in f.Remote.SentProxies.Values)
{
var info = JpegDecoder.ReadInfo(proxy);
Assert.True(info.Width <= 1280 && info.Height <= 1280, "made as the server's policy says");
}
Assert.Contains(Loc.L("Archive.Log.ProxiesSent", 3, 0), done.LogTail);
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Holy grail")).Status);
}
[Test]
public async Task AnUploadOfAnUnverifiedCopySendsTheProxiesTheServerAsksFor()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(3);
// An adopted folder (never verified, so its frames have no hash here) whose originals the server already holds
// under the names it gave them, and cannot decode (HEIF, BRIEF §2.3).
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, $"DSC_{i + 1:0000}.JPG"), photos[i], f.Ct);
await f.Archive.ScanAsync();
var local = Assert.Contains((await f.Db.Sequences.ListAsync(new Chronos.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);
remote.Undecodable = true;
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
var ahead = await f.EntryAsync(local.DisplayTitle);
Assert.Equal((SyncStatus.LocalAhead, 3), (ahead.Status, ahead.Link!.MissingRemote));
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
var done = await f.Archive.WaitForAsync(job.Id, JobState.Done);
Assert.True(f.Remote.SentProxies.Keys.ToHashSet().SetEquals(remote.Frames.Select(r => r.Id)), "a proxy of every frame");
Assert.Contains(Loc.L("Archive.Log.ProxiesSent", 3, 0), done.LogTail);
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync(local.DisplayTitle)).Status);
}
[Test]
public async Task ProxiesSentFromElsewhereAreNoLongerCountedHere()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Holy grail", photos);
var remote = f.Remote.Add("Holy grail", photos);
remote.Undecodable = true;
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
Assert.Equal(2, (await f.EntryAsync("Holy grail")).Link!.MissingRemote);
var calls = f.Remote.ManifestCalls;
await f.RefreshAsync();
Assert.Equal(calls, f.Remote.ManifestCalls);
// A render node sends them after a job: the server's frame counters stand still, its sequence changes.
foreach (var frame in remote.Frames) f.Remote.SentProxies[frame.Id] = frame.Proxy;
remote.UpdatedAt = remote.UpdatedAt.AddSeconds(1);
await f.RefreshAsync();
var entry = await f.EntryAsync("Holy grail");
Assert.Equal((SyncStatus.InSync, 0), (entry.Status, entry.Link!.MissingRemote));
}
[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 Chronos.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 OriginalsTheServerHasNotHashedAreDownloadedAndHashedHere()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(3);
// A folder the server adopted and never verified: its manifest lists no SHA-256.
var remote = f.Remote.Add("Adopted on the server", photos);
remote.Unhashed = true;
await f.RefreshAsync();
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Adopted on the server", SyncDownloadMode.Originals, f.Archive.Archive.Id);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
var entry = await f.EntryAsync("Adopted on the server");
var frames = await f.Db.Frames.ListBySequenceAsync(entry.Local!.Id, cancellationToken: f.Ct);
Assert.True(frames.Select(r => r.Sha256).ToHashSet().SetEquals(photos.Select(Sha)), "every original arrived, hashed here");
// Matched by size and capture time, the copies are the server's originals.
Assert.Equal((SyncStatus.InSync, 0, 0), (entry.Status, entry.Link!.MissingRemote, entry.Link.MissingLocal));
// One more photo adopted there: only that one travels.
remote.AddFrame(f.NewPhotos(1)[0]);
await f.RefreshAsync();
Assert.Equal(1, (await f.EntryAsync("Adopted on the server")).Link!.MissingLocal);
job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Adopted on the server", SyncDownloadMode.Originals, null);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
Assert.Equal(4, (await f.Db.Frames.ListBySequenceAsync(entry.Local.Id, cancellationToken: f.Ct)).Count);
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Adopted on the server")).Status);
}
[Test]
public async Task AnUploadDoesNotSendAgainWhatTheServerHoldsWithoutAHash()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(4);
var local = await f.LocalAsync("Harbour", photos);
// The server adopted the first three photos and never verified them: it cannot recognise them by content.
var remote = f.Remote.Add("Harbour", photos[..3]);
remote.Unhashed = true;
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
var ahead = (await f.EntryAsync("Harbour")).Link!;
Assert.Equal((1, 0), (ahead.MissingRemote, ahead.MissingLocal));
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
var done = await f.Archive.WaitForAsync(job.Id, JobState.Done);
Assert.Equal((4L, 4L), (done.ProgressDone, done.ProgressTotal));
Assert.SequenceEqual(photos.Select(Sha), remote.Frames.Select(r => r.Sha256));
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status);
}
[Test]
public async Task ProxiesOfFramesTheServerHasNotHashedAreSentToo()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Holy grail", photos);
// The server adopted the same originals, cannot decode them and has not hashed them.
var remote = f.Remote.Add("Holy grail", photos);
remote.Undecodable = true;
remote.Unhashed = true;
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
Assert.Equal(3, (await f.EntryAsync("Holy grail")).Link!.MissingRemote);
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
Assert.True(f.Remote.SentProxies.Keys.ToHashSet().SetEquals(remote.Frames.Select(r => r.Id)), "a proxy of every frame");
Assert.Equal((SyncStatus.InSync, 0), ((await f.EntryAsync("Holy grail")).Status, (await f.EntryAsync("Holy grail")).Link!.MissingRemote));
}
[Test]
public async Task PositionsTakenFromTheServerStayOnTheirPhotosWhenTheOriginalsArrive()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(6);
var local = await f.LocalAsync("Harbour", photos[1..5]);
var remote = f.Remote.Add("Harbour", photos[1..5]);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
// Another PC sends the server an earlier and a later photo; then an editor there excludes two photos, picks the
// hero and keys the camera, by the server's frames.
remote.InsertFrame(0, photos[0]);
remote.AddFrame(photos[5]);
f.Remote.EditSettings(remote.Id, new ProjectSettings
{
ExcludedFrames = [0, 3],
HeroFrame = 5,
Camera = new CameraSettings { Keyframes = [new CameraKey(2, 0.4, 0.5, 1.5, 0)] },
}.ToJson());
await f.RefreshAsync();
var taken = await NamedAsync(f, local.Id);
Assert.SequenceEqual([Sha(photos[3])], taken.Excluded);
Assert.Null(taken.Hero);
Assert.SequenceEqual([Sha(photos[2])], taken.Keyframes);
Assert.True(taken.Pending.ToHashSet().SetEquals([Sha(photos[0]), Sha(photos[5])]), "the photos this copy lacks wait for them");
// Each waits with its capture time too, whichever side hashed what: the same project reads the same either way.
var waiting = ProjectSettings.FromJson((await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson!).PendingFrames!;
Assert.True(waiting.All(p => p.CapturedAt is not null), "a photo waits with its capture time");
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);
// The same photos as on the server, and nothing waits any more.
var arrived = await NamedAsync(f, local.Id);
Assert.SequenceEqual([Sha(photos[0]), Sha(photos[3])], arrived.Excluded);
Assert.Equal(Sha(photos[5]), arrived.Hero);
Assert.SequenceEqual([Sha(photos[2])], arrived.Keyframes);
Assert.Empty(arrived.Pending);
var row = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
var frames = await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct);
Assert.Equal(Sha(photos[5]), frames.Single(fr => fr.Id == row.HeroFrameId).Sha256);
Assert.True(SyncRules.SameSettings(row.SettingsJson, await File.ReadAllTextAsync(f.Archive.Paths.Sequence(row.Folder).ProjectPath, f.Ct)),
"project.json mirrors the index");
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status);
// An edit here later sends the server the same photos, by its frames.
var edited = ProjectSettings.FromJson(row.SettingsJson!) with { Exposure = new ExposureSettings { DeflickerWindow = new Auto<int>().WithManual(41) } };
await f.EditLocalSettingsAsync(local.Id, edited.ToJson());
await f.RefreshAsync();
var server = ProjectSettings.FromJson(remote.SettingsJson!);
Assert.Equal(41, server.Exposure.DeflickerWindow.Manual);
Assert.SequenceEqual([Sha(photos[0]), Sha(photos[3])], server.ExcludedFrames.Select(i => remote.Frames[i].Sha256));
Assert.Equal(Sha(photos[5]), remote.Frames[server.HeroFrame!.Value].Sha256);
Assert.SequenceEqual([Sha(photos[2])], server.Camera.Keyframes.Select(k => remote.Frames[k.Frame].Sha256));
}
[Test]
public async Task ACachedThumbnailIsReplacedOnceTheServerHasTheProxy()
{
await using var f = await SyncFixture.CreateAsync(context);
var remote = f.Remote.Add("Fog", f.NewPhotos(2), status: SequenceStatus.ThumbsBuilt);
await f.RefreshAsync();
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);
Assert.True(Assert.NotNull(f.Sync.OpenRemote(f.Server, remote.Id)).Files.All(file => new FileInfo(file!).Length == 64), "thumbnails stand in");
Assert.True((await f.EntryAsync("Fog")).Link!.ProxiesStale, "the cache is filled again once the server has proxies");
// Proxies arrive on the server (a client or render node sent them); the frames did not change.
remote.Status |= SequenceStatus.ProxiesBuilt;
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.SequenceEqual(remote.Frames.Select(r => (long)r.Proxy.Length), opened.Files.Select(file => new FileInfo(file!).Length));
Assert.False((await f.EntryAsync("Fog")).Link!.ProxiesStale);
}
[Test]
public async Task ACacheMadeBeforeTheServerDrewItsNewFramesStaysStaleUntilItHasTheirProxies()
{
await using var f = await SyncFixture.CreateAsync(context);
var remote = f.Remote.Add("Harbour", f.NewPhotos(2));
await f.RefreshAsync();
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Harbour", SyncDownloadMode.Proxies, null);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
Assert.False((await f.EntryAsync("Harbour")).Link!.ProxiesStale);
// Two photos reach the server. Its proxy flag stays set until its next proxy pass, which has not drawn them yet:
// the first has its thumbnail only, the second nothing at all.
var added = f.NewPhotos(2).Select(photo => remote.AddFrame(photo)).ToList();
f.Remote.Undrawn.UnionWith([(added[0].Id, "proxy"), (added[1].Id, "proxy"), (added[1].Id, "thumb")]);
await f.RefreshAsync();
job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Harbour", SyncDownloadMode.Proxies, null);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
var opened = Assert.NotNull(f.Sync.OpenRemote(f.Server, remote.Id));
Assert.SequenceEqual([remote.Frames[0].Proxy.Length, remote.Frames[1].Proxy.Length, 64], opened.Files.Take(3).Select(file => (int)new FileInfo(file!).Length));
Assert.Null(opened.Files[3]);
Assert.True((await f.EntryAsync("Harbour")).Link!.ProxiesStale, "a thumbnail or a missing file stands in for a proxy the server offers");
// The pass draws them: the frames stay as they were, the server's sequence records the pass.
f.Remote.Undrawn.Clear();
remote.UpdatedAt = DateTimeOffset.UtcNow.AddSeconds(1);
await f.RefreshAsync();
Assert.True((await f.EntryAsync("Harbour")).Link!.ProxiesStale);
job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Harbour", SyncDownloadMode.Proxies, null);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
opened = Assert.NotNull(f.Sync.OpenRemote(f.Server, remote.Id));
Assert.SequenceEqual(remote.Frames.Select(r => (long)r.Proxy.Length), opened.Files.Select(file => new FileInfo(file!).Length));
Assert.False((await f.EntryAsync("Harbour")).Link!.ProxiesStale);
}
[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(Chronos.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));
/// <summary>The photos (SHA-256) the local copy's project excludes, shows as hero, keys the camera on, and waits for.</summary>
private static async Task<(string[] Excluded, string? Hero, string[] Keyframes, string[] Pending)> NamedAsync(SyncFixture f, Guid localId)
{
var project = ProjectSettings.FromJson((await f.Db.Sequences.GetAsync(localId, f.Ct))!.SettingsJson!);
var frames = await f.Db.Frames.ListBySequenceAsync(localId, cancellationToken: f.Ct);
return ([.. project.ExcludedFrames.Select(i => frames[i].Sha256!)], project.HeroFrame is { } hero ? frames[hero].Sha256 : null,
[.. project.Camera.Keyframes.Select(k => frames[k.Frame].Sha256!)], [.. (project.PendingFrames ?? []).Select(p => p.Sha256!)]);
}
}