fix(sync): resolve conflicts against the versions shown, isolate failures, renders on request

- Conflicts are settled against the versions the user was shown; a later change on
  either side refuses the choice and compares again. Title, tags, rating and notes
  changed differently on both sides are a conflict too (no silent tag union).
- Links are written under the engine's gate and forgotten only after a 404; linked
  local copies are read by id; unlinked copies with the same originals are linked
  by content.
- A failure on one sequence is recorded on its link; the others are still compared.
- Downloads hash unverified local copies first and restore originals missing here.
- Background proxy downloads give way to the user's requests; "Keep proxies offline"
  refreshes the caches of sequences opened with proxies, checks free space and backs
  off after a failure.
- Renders travel on request: Send exports (chunked, hash-verified upload keeping the
  render id; new POST /sequences/{id}/renders endpoints) and Get exports.
- Server screen: stable row buttons, mockup column grid, Tab through rows, conflict
  rows first on the card colour, localised conflict detail, Save both confirmation,
  Pause metered uploads, culture switch, Library one-word sync glyphs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-03 10:26:56 +00:00
1 parent 3601e0a47f
commit 2d40a613b9
48 files changed
+2498 -465

No files matched your search

+366 -113
View File
@@ -1,3 +1,4 @@
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Globalization;
using System.Net;
@@ -5,6 +6,7 @@ using System.Text.Json;
using Titano.Core.Archiving;
using Titano.Core.Diagnostics;
using Titano.Core.IO;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data.Archiving;
using Titano.Data.Jobs;
@@ -35,24 +37,33 @@ public sealed record SyncOptions
/// <summary>
/// Client side of sync (BRIEF §4.4, §14.5). Compares every server sequence with its local copy from the server listing
/// and, when frame counters moved, the manifest: originals are matched by SHA-256 and never conflict; settings, title,
/// tags, rating and notes travel together under the settings version, so a change on one side is sent or taken
/// (automatically or on request) and a change on both sides with different settings is a conflict the user settles
/// with <see cref="ResolveAsync"/>. Uploads and downloads run as jobs (<see cref="CreateJobHandlers"/>): uploads use the
/// chunked, hash-verified, resumable protocol; downloaded originals are verified and committed through the archive
/// ingest, so sidecars stay right; proxies go to a cache and open as a <see cref="RemoteSequence"/>. Proxies and
/// thumbnails never travel upward. The state of each local sequence is written to its <c>sync_state</c> for the Library.
/// and, when frame counters or render counts moved, the manifest: originals are matched by SHA-256 and never conflict;
/// renders by id. Settings, title, tags, rating and notes travel together under the settings version, so a change on
/// one side is sent or taken (automatically or on request) and a change on both sides with different content is a
/// conflict the user settles with <see cref="ResolveAsync"/>, against the versions the user was shown. Uploads and
/// downloads run as jobs (<see cref="CreateJobHandlers"/>): uploads use the chunked, hash-verified, resumable protocol;
/// downloaded originals are verified and committed through the archive ingest, so sidecars stay right; proxies go to a
/// cache and open as a <see cref="RemoteSequence"/>; renders travel on request. Proxies and thumbnails never travel
/// upward. A local copy and a server sequence holding the same originals are linked by content when no link joins
/// them. The state of each local sequence is written to its <c>sync_state</c> for the Library. A failure while
/// comparing one sequence is recorded on its link and does not stop the others.
/// </summary>
public sealed class SyncService
{
private const string LogCategory = "sync";
private const string SessionKeyPrefix = "titano-sync:";
/// <summary>Recomputes states without sending or taking settings on the user's behalf.</summary>
internal static readonly SyncPolicy CompareOnly = new(AutoSyncSettings: false);
private readonly TitanoDatabase _db;
private readonly SyncLinkStore _links;
private readonly ProjectStore _projects;
private readonly SemaphoreSlim _gate = new(1, 1);
/// <summary>Unlinked pairs whose manifests were compared at these frame versions without a match (not fetched again).</summary>
private readonly ConcurrentDictionary<string, byte> _unmatched = new(StringComparer.Ordinal);
public SyncService(TitanoDatabase db, ArchiveService archives, SyncOptions options)
{
_db = db;
@@ -79,6 +90,9 @@ public sealed class SyncService
/// <summary>"https://nas.local:8443": the key links are stored under (scheme, lower-case host, port, path).</summary>
public static string ServerKey(Uri address) => address.GetLeftPart(UriPartial.Path).TrimEnd('/').ToLowerInvariant();
/// <summary>What an upload or download job moves; null for any other job.</summary>
public static SyncTransferKind? TransferKind(Job job) => SyncJobParameters.Read(job)?.Kind(job.Kind);
/// <summary>Session key the local archive groups the downloaded originals of one server sequence by.</summary>
internal static string SessionKey(Guid remoteId) => SessionKeyPrefix + remoteId.ToString("N");
@@ -86,30 +100,34 @@ public sealed class SyncService
/// <summary>
/// Lists the server, compares every sequence with its local copy, sends or takes settings changed on one side when
/// <see cref="SyncPolicy.AutoSyncSettings"/> is on, forgets sequences deleted on the server, and stores the states.
/// <see cref="SyncPolicy.AutoSyncSettings"/> is on, forgets sequences the server confirms deleted, links unlinked
/// copies holding the same originals, and stores the states.
/// </summary>
public async Task<SyncSnapshot> RefreshAsync(ISyncRemote remote, SyncPolicy policy, CancellationToken cancellationToken)
{
var clock = Stopwatch.StartNew();
var listing = await remote.ListSequencesAsync(cancellationToken).ConfigureAwait(false);
Dictionary<Guid, Sequence> locals;
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
var links = (await _links.ListAsync(remote.Server, cancellationToken).ConfigureAwait(false)).ToDictionary(l => l.RemoteId);
var locals = await LocalSequencesAsync(cancellationToken).ConfigureAwait(false);
locals = await LocalSequencesAsync(cancellationToken).ConfigureAwait(false);
foreach (var dto in listing)
{
links.Remove(dto.Id, out var link);
var local = link?.LocalId is { } id ? locals.GetValueOrDefault(id) : null;
await ReconcileSafelyAsync(remote, Observe(link, remote.Server, dto), dto, local, policy, cancellationToken).ConfigureAwait(false);
var local = await LocalOfAsync(link, locals, cancellationToken).ConfigureAwait(false);
await ReconcileSafelyAsync(remote, Observe(link, remote.Server, dto), dto, local, locals, policy, cancellationToken).ConfigureAwait(false);
}
foreach (var gone in links.Values) await ForgetAsync(gone, cancellationToken).ConfigureAwait(false);
// Not in the listing: deleted on the server, or created or moved while its pages were read. Only a 404 forgets a link.
foreach (var link in links.Values) await CompareOneAsync(remote, link.RemoteId, link, locals, policy, cancellationToken).ConfigureAwait(false);
await MatchByContentAsync(remote, listing, locals, policy, cancellationToken).ConfigureAwait(false);
}
finally
{
_gate.Release();
}
var entries = await StoreStatesAsync(remote.Server, cancellationToken).ConfigureAwait(false);
var entries = await StoreStatesAsync(remote.Server, locals, cancellationToken).ConfigureAwait(false);
Changed?.Invoke(remote.Server);
return new SyncSnapshot(remote.Server, entries, DateTimeOffset.UtcNow, clock.Elapsed);
}
@@ -123,49 +141,22 @@ public sealed class SyncService
foreach (var id in remoteIds)
{
var link = await _links.GetAsync(remote.Server, id, cancellationToken).ConfigureAwait(false);
SequenceDto dto;
try
{
dto = await remote.GetSequenceAsync(id, cancellationToken).ConfigureAwait(false);
}
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound)
{
if (link is not null) await ForgetAsync(link, cancellationToken).ConfigureAwait(false);
continue;
}
var local = link?.LocalId is { } localId ? await _db.Sequences.GetAsync(localId, cancellationToken).ConfigureAwait(false) : null;
await ReconcileSafelyAsync(remote, Observe(link, remote.Server, dto), dto, local, policy, cancellationToken).ConfigureAwait(false);
await CompareOneAsync(remote, id, link, null, policy, cancellationToken).ConfigureAwait(false);
}
}
finally
{
_gate.Release();
}
await StoreStatesAsync(remote.Server, cancellationToken).ConfigureAwait(false);
await StoreStatesAsync(remote.Server, null, cancellationToken).ConfigureAwait(false);
Changed?.Invoke(remote.Server);
}
/// <summary>The sync table of <paramref name="server"/> as last compared: every server sequence and every local one, with active transfers.</summary>
public async Task<IReadOnlyList<SyncEntry>> ListAsync(string server, CancellationToken cancellationToken)
{
var links = await _links.ListAsync(server, cancellationToken).ConfigureAwait(false);
var locals = await LocalSequencesAsync(cancellationToken).ConfigureAwait(false);
var transfers = await _links.ActiveTransfersAsync(cancellationToken).ConfigureAwait(false);
var entries = new List<SyncEntry>(links.Count + locals.Count);
foreach (var link in links)
{
var local = link.LocalId is { } id && locals.Remove(id, out var found) ? found : null;
var transfer = (local is null ? null : transfers.GetValueOrDefault(local.Id)) ?? transfers.GetValueOrDefault(link.RemoteId);
entries.Add(new SyncEntry(local, link, transfer is null ? SyncRules.Status(local, link) : SyncStatus.Transferring, transfer));
}
foreach (var local in locals.Values)
{
var transfer = transfers.GetValueOrDefault(local.Id);
entries.Add(new SyncEntry(local, null, transfer is null ? SyncStatus.LocalOnly : SyncStatus.Transferring, transfer));
}
entries.Sort((a, b) => string.Compare(a.Title, b.Title, StringComparison.CurrentCultureIgnoreCase));
return entries;
}
/// <summary>
/// The sync table of <paramref name="server"/> as last compared: every server sequence and every local one, with
/// active transfers; conflicts first, then transfers, then by title.
/// </summary>
public Task<IReadOnlyList<SyncEntry>> ListAsync(string server, CancellationToken cancellationToken) => EntriesAsync(server, null, cancellationToken);
/// <summary>
/// Links a local sequence to a server sequence holding the same originals. Nothing was agreed yet, so the next
@@ -180,41 +171,73 @@ public sealed class SyncService
// ---------------- Settings ----------------
/// <summary>Settles a settings conflict as the user chose (BRIEF §12.7); a 409 means the server changed again meanwhile.</summary>
public async Task ResolveAsync(ISyncRemote remote, Guid remoteId, SyncResolution resolution, CancellationToken cancellationToken)
/// <summary>
/// Settles a conflict as the user chose (BRIEF §12.7), against the versions the user was shown: when either side
/// changed again since, nothing is written, the sequence is compared again and <see cref="SyncConflictChangedException"/>
/// is thrown. Returns the file this PC's settings were saved to for <see cref="SyncResolution.SaveBoth"/>, else null.
/// </summary>
public async Task<string?> ResolveAsync(ISyncRemote remote, Guid remoteId, SyncResolution resolution, CancellationToken cancellationToken)
{
string? saved = null;
var changed = false;
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
var (link, local) = await LinkedAsync(remote.Server, remoteId, cancellationToken).ConfigureAwait(false);
var dto = await remote.GetSequenceAsync(remoteId, cancellationToken).ConfigureAwait(false);
link = Observe(link, remote.Server, dto);
if (resolution == SyncResolution.KeepMine)
if (link is not { ConflictRemote: { } theirs, ConflictLocalSettings: { } seenLocal, ConflictRemoteSettings: { } seenRemote }
|| local.SettingsVersion != seenLocal)
{
var updated = await remote.UpdateSequenceAsync(remoteId, SyncPayload.Of(local).ToRequest(dto.SettingsVersion), cancellationToken).ConfigureAwait(false);
link = Agreed(Observe(link, remote.Server, updated), local.SettingsVersion, updated.SettingsVersion);
changed = true;
}
else if (resolution == SyncResolution.KeepMine)
{
try
{
var updated = await remote.UpdateSequenceAsync(remoteId, SyncPayload.Of(local).ToRequest(seenRemote), cancellationToken).ConfigureAwait(false);
link = Agreed(Observe(link, remote.Server, updated), local.SettingsVersion, updated.SettingsVersion);
}
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.Conflict)
{
changed = true;
}
}
else
{
if (resolution == SyncResolution.SaveBoth) await SaveCopyAsync(local, cancellationToken).ConfigureAwait(false);
var manifest = await remote.GetManifestAsync(remoteId, cancellationToken).ConfigureAwait(false);
var applied = await ApplyLocallyAsync(local, SyncPayload.Of(dto, manifest.SettingsJson), cancellationToken).ConfigureAwait(false);
link = Agreed(link, applied.SettingsVersion, manifest.SettingsVersion);
var dto = await remote.GetSequenceAsync(remoteId, cancellationToken).ConfigureAwait(false);
if (dto.SettingsVersion != seenRemote)
{
changed = true;
}
else
{
if (resolution == SyncResolution.SaveBoth) saved = await SaveCopyAsync(local, cancellationToken).ConfigureAwait(false);
var applied = await ApplyLocallyAsync(local, theirs, cancellationToken).ConfigureAwait(false);
link = Agreed(Observe(link, remote.Server, dto), applied.SettingsVersion, seenRemote);
}
}
if (!changed)
{
await _links.UpsertAsync(link with { SyncedAt = DateTimeOffset.UtcNow }, cancellationToken).ConfigureAwait(false);
Log.Info(LogCategory, $"Conflict on {local.DisplayTitle} settled: {resolution}");
}
await _links.UpsertAsync(link with { SyncedAt = DateTimeOffset.UtcNow }, cancellationToken).ConfigureAwait(false);
Log.Info(LogCategory, $"Conflict on {local.DisplayTitle} settled: {resolution}");
}
finally
{
_gate.Release();
}
await StoreStatesAsync(remote.Server, cancellationToken).ConfigureAwait(false);
if (changed)
{
await RefreshSequencesAsync(remote, [remoteId], CompareOnly, cancellationToken).ConfigureAwait(false);
throw new SyncConflictChangedException(Loc.L("Errors.Sync.ChangedAgain"));
}
await StoreStatesAsync(remote.Server, null, cancellationToken).ConfigureAwait(false);
Changed?.Invoke(remote.Server);
return saved;
}
/// <summary>Sends or takes settings changed on one side only (the row action while automatic sync is off).</summary>
public Task SyncSettingsAsync(ISyncRemote remote, Guid remoteId, CancellationToken cancellationToken) =>
RefreshSequencesAsync(remote, [remoteId], new SyncPolicy(AutoSyncSettings: true), cancellationToken);
public Task SyncSettingsAsync(ISyncRemote remote, Guid remoteId, SyncPolicy policy, CancellationToken cancellationToken) =>
RefreshSequencesAsync(remote, [remoteId], policy with { AutoSyncSettings = true }, cancellationToken);
// ---------------- Transfers ----------------
@@ -222,9 +245,16 @@ public sealed class SyncService
public Task<Job> EnqueueUploadAsync(JobEngine engine, string server, Sequence local, CancellationToken cancellationToken = default) =>
EnqueueAsync(engine, JobKind.UploadCommit, local.Id, local.DisplayTitle, new SyncJobParameters(server), JobPriority.User, cancellationToken);
/// <summary>Queues sending the renders of a local copy the server lacks (BRIEF §14.5), unless that is already waiting or running.</summary>
public Task<Job> EnqueueSendExportsAsync(JobEngine engine, string server, Sequence local, CancellationToken cancellationToken = default) =>
EnqueueAsync(engine, JobKind.UploadCommit, local.Id, local.DisplayTitle, new SyncJobParameters(server, Upload: SyncUploadMode.Exports), JobPriority.User,
cancellationToken);
/// <summary>
/// Queues a download of a server sequence, unless one is already waiting or running: originals into
/// <paramref name="archiveId"/> (ignored when the sequence already has a local copy), or proxies into the cache.
/// Queues a download of a server sequence, unless the same one is already waiting or running: originals into
/// <paramref name="archiveId"/> (ignored when the sequence already has a local copy), proxies into the cache, or the
/// server's renders into the local copy. A background proxy download gives way to the user's request for the same
/// proxies (queued again at the user's priority) or for the originals.
/// </summary>
public Task<Job> EnqueueDownloadAsync(JobEngine engine, string server, Guid remoteId, string title, SyncDownloadMode mode, Guid? archiveId,
JobPriority priority = JobPriority.User, CancellationToken cancellationToken = default) =>
@@ -253,11 +283,34 @@ public sealed class SyncService
/// <summary>Creates or updates the link of a local sequence to a server sequence (an upload or download made it).</summary>
internal async Task<SyncLink> LinkAsync(string server, Guid remoteId, Sequence local, CancellationToken cancellationToken)
{
var link = await _links.GetAsync(server, remoteId, cancellationToken).ConfigureAwait(false)
?? new SyncLink { Server = server, RemoteId = remoteId, Title = local.DisplayTitle, RemoteUpdatedAt = DateTimeOffset.UtcNow };
link = link with { LocalId = local.Id };
await _links.UpsertAsync(link, cancellationToken).ConfigureAwait(false);
return link;
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
var link = await _links.GetAsync(server, remoteId, cancellationToken).ConfigureAwait(false)
?? new SyncLink { Server = server, RemoteId = remoteId, Title = local.DisplayTitle, RemoteUpdatedAt = DateTimeOffset.UtcNow };
if (link.LocalId != local.Id) link = Unlinked(link) with { LocalId = local.Id };
await _links.UpsertAsync(link, cancellationToken).ConfigureAwait(false);
return link;
}
finally
{
_gate.Release();
}
}
/// <summary>Forgets a link whose server sequence an upload found deleted (its originals go into a new one).</summary>
internal async Task ForgetGoneAsync(string server, Guid remoteId, CancellationToken cancellationToken)
{
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
if (await _links.GetAsync(server, remoteId, cancellationToken).ConfigureAwait(false) is { } link)
await ForgetAsync(link, cancellationToken).ConfigureAwait(false);
}
finally
{
_gate.Release();
}
}
/// <summary>
@@ -312,6 +365,25 @@ public sealed class SyncService
}
}
/// <summary>
/// Compares a sequence again after a transfer, originals and renders included even when no counter moved (a
/// restored original or a hash given by verify changes no frame version), without sending or taking settings.
/// </summary>
internal async Task RecompareAsync(ISyncRemote remote, Guid remoteId, CancellationToken cancellationToken)
{
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
if (await _links.GetAsync(remote.Server, remoteId, cancellationToken).ConfigureAwait(false) is { } link)
await _links.UpsertAsync(link with { DiffLocalFrames = null, DiffLocalRenders = null }, cancellationToken).ConfigureAwait(false);
}
finally
{
_gate.Release();
}
await RefreshSequencesAsync(remote, [remoteId], CompareOnly, cancellationToken).ConfigureAwait(false);
}
/// <summary>Records what the proxy cache holds for a server sequence.</summary>
internal async Task SetProxiesAsync(string server, SequenceDto dto, int cached, int framesVersion, CancellationToken cancellationToken)
{
@@ -328,87 +400,151 @@ public sealed class SyncService
Changed?.Invoke(server);
}
private async Task ReconcileSafelyAsync(ISyncRemote remote, SyncLink link, SequenceDto dto, Sequence? local, SyncPolicy policy, CancellationToken cancellationToken)
/// <summary>The file of a local render: archive-relative for outputs inside the archive, absolute otherwise.</summary>
internal static string RenderFile(Archive archive, Render render) =>
Path.IsPathRooted(render.OutputPath) ? render.OutputPath : new ArchivePaths(archive.RootPath).FromRelative(render.OutputPath);
/// <summary>
/// Compares one server sequence (under the gate): fetches it, forgets its link on a 404, records a failure on its
/// link. <paramref name="locals"/> (when given) receives the local copy as it stands after the comparison.
/// </summary>
private async Task CompareOneAsync(ISyncRemote remote, Guid remoteId, SyncLink? link, Dictionary<Guid, Sequence>? locals, SyncPolicy policy,
CancellationToken cancellationToken)
{
SequenceDto dto;
try
{
link = await ReconcileAsync(remote, link, dto, local, policy, cancellationToken).ConfigureAwait(false);
dto = await remote.GetSequenceAsync(remoteId, cancellationToken).ConfigureAwait(false);
}
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound)
{
// Deleted between the listing and the manifest: the next refresh forgets it.
if (link is not null) await ForgetAsync(link, cancellationToken).ConfigureAwait(false);
return;
}
catch (Exception ex) when (IsIsolated(ex, cancellationToken))
{
Log.Warning(LogCategory, $"Sequence {remoteId} could not be compared", ex);
if (link is not null) await _links.UpsertAsync(link with { Error = ex.Message }, cancellationToken).ConfigureAwait(false);
return;
}
var local = await LocalOfAsync(link, locals, cancellationToken).ConfigureAwait(false);
await ReconcileSafelyAsync(remote, Observe(link, remote.Server, dto), dto, local, locals, policy, cancellationToken).ConfigureAwait(false);
}
private async Task ReconcileSafelyAsync(ISyncRemote remote, SyncLink link, SequenceDto dto, Sequence? local, Dictionary<Guid, Sequence>? locals,
SyncPolicy policy, CancellationToken cancellationToken)
{
try
{
(link, local) = await ReconcileAsync(remote, link, dto, local, policy, cancellationToken).ConfigureAwait(false);
link = link with { Error = null };
if (local is not null && locals is not null) locals[local.Id] = local;
}
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound)
{
// Deleted between the listing and the manifest: the next comparison forgets it.
Log.Info(LogCategory, $"{dto.DisplayTitle} vanished from the server during the comparison");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or LeaseUnavailableException)
catch (Exception ex) when (IsIsolated(ex, cancellationToken))
{
// The local archive is offline or busy: compare again next time; the other sequences go on.
// The archive is offline or busy, the server refused this sequence, or its project is unreadable: it is
// compared again next time and the other sequences go on.
Log.Warning(LogCategory, $"{dto.DisplayTitle} could not be synced", ex);
link = link with { Error = ex.Message };
}
await _links.UpsertAsync(link, cancellationToken).ConfigureAwait(false);
}
/// <summary>Compares originals when frame counters moved, then settles the settings; returns the updated link.</summary>
private async Task<SyncLink> ReconcileAsync(ISyncRemote remote, SyncLink link, SequenceDto dto, Sequence? local, SyncPolicy policy,
/// <summary>A failure that concerns one sequence; a lost session (401) or the caller's cancellation stops the whole comparison.</summary>
private static bool IsIsolated(Exception ex, CancellationToken cancellationToken) => ex switch
{
TitanoApiException api => api.Status != HttpStatusCode.Unauthorized,
OperationCanceledException => !cancellationToken.IsCancellationRequested,
_ => ex is HttpRequestException or JsonException or IOException or UnauthorizedAccessException or InvalidDataException or LeaseUnavailableException,
};
/// <summary>Compares originals and renders when either side's moved, then settles the settings; returns the updated link and local copy.</summary>
private async Task<(SyncLink Link, Sequence? Local)> ReconcileAsync(ISyncRemote remote, SyncLink link, SequenceDto dto, Sequence? local, SyncPolicy policy,
CancellationToken cancellationToken)
{
if (local is null)
{
// A cleared cache leaves nothing to open; a deleted local copy makes the sequence remote again.
if (link.ProxiesCached > 0 && !Proxies.Exists(link.Server, link.RemoteId)) link = link with { ProxiesCached = 0, ProxiesFramesVersion = null };
return link.LocalId is null ? link : Unlinked(link);
return (link.LocalId is null ? link : Unlinked(link), null);
}
SequenceManifest? manifest = null;
if (link.DiffLocalFrames != local.FramesVersion || link.DiffRemoteFrames != link.RemoteFramesVersion)
if (link.DiffLocalFrames != local.FramesVersion || link.DiffRemoteFrames != link.RemoteFramesVersion
|| link.DiffLocalRenders != local.RenderedCount || link.DiffRemoteRenders != link.RenderCount)
{
manifest = await remote.GetManifestAsync(link.RemoteId, cancellationToken).ConfigureAwait(false);
var frames = await SequenceFrames.ListAsync(_db, local.Id, cancellationToken).ConfigureAwait(false);
// A frame flagged missing here counts as absent: downloading the originals restores it from the server.
var (missingRemote, missingLocal) = SyncRules.CompareOriginals(
[.. frames.Where(f => (f.Flags & FrameFlags.Missing) == 0).Select(f => f.Sha256)], [.. manifest.Frames.Select(f => f.Sha256)]);
link = link with
link = await CompareExportsAsync(link, local, manifest.Renders, cancellationToken).ConfigureAwait(false) with
{
DiffLocalFrames = local.FramesVersion,
DiffRemoteFrames = manifest.FramesVersion,
RemoteFramesVersion = manifest.FramesVersion,
DiffLocalRenders = local.RenderedCount,
DiffRemoteRenders = manifest.Renders.Count,
MissingRemote = missingRemote,
MissingLocal = missingLocal,
};
}
link = await SettleSettingsAsync(remote, link, dto, local, manifest, policy, cancellationToken).ConfigureAwait(false);
return link with { SyncedAt = DateTimeOffset.UtcNow };
(link, local) = await SettleSettingsAsync(remote, link, dto, local, manifest, policy, cancellationToken).ConfigureAwait(false);
return (link with { SyncedAt = DateTimeOffset.UtcNow }, local);
}
private async Task<SyncLink> SettleSettingsAsync(ISyncRemote remote, SyncLink link, SequenceDto dto, Sequence local, SequenceManifest? manifest,
SyncPolicy policy, CancellationToken cancellationToken)
/// <summary>Renders each side lacks, by id (a render keeps its id on both sides); local renders whose file is gone cannot be sent.</summary>
private async Task<SyncLink> CompareExportsAsync(SyncLink link, Sequence local, IReadOnlyList<RenderDto> remoteRenders, CancellationToken cancellationToken)
{
var renders = await _db.Renders.ListBySequenceAsync(local.Id, cancellationToken).ConfigureAwait(false);
var archive = await _db.Archives.GetAsync(local.ArchiveId, cancellationToken).ConfigureAwait(false);
var here = renders.Select(r => r.Id).ToHashSet();
var there = remoteRenders.Select(r => r.Id).ToHashSet();
var toGet = remoteRenders.Where(r => !here.Contains(r.Id)).ToList();
var toSend = archive is null ? [] : renders.Where(r => !there.Contains(r.Id) && File.Exists(RenderFile(archive, r))).ToList();
return link with
{
ExportsToGet = toGet.Count,
ExportsToGetBytes = toGet.Sum(r => r.Bytes),
ExportsToSend = toSend.Count,
ExportsToSendBytes = toSend.Sum(r => r.Bytes),
};
}
private async Task<(SyncLink Link, Sequence Local)> SettleSettingsAsync(ISyncRemote remote, SyncLink link, SequenceDto dto, Sequence local,
SequenceManifest? manifest, SyncPolicy policy, CancellationToken cancellationToken)
{
var localChanged = link.BaseLocalSettings != local.SettingsVersion;
var remoteChanged = link.BaseRemoteSettings != link.RemoteSettingsVersion;
if (!localChanged && !remoteChanged) return link;
if (!localChanged && !remoteChanged) return (link, local);
if (localChanged && remoteChanged)
{
if (link.ConflictLocalSettings == local.SettingsVersion && link.ConflictRemoteSettings == link.RemoteSettingsVersion) return link;
if (link.ConflictLocalSettings == local.SettingsVersion && link.ConflictRemoteSettings == link.RemoteSettingsVersion) return (link, local);
manifest ??= await remote.GetManifestAsync(link.RemoteId, cancellationToken).ConfigureAwait(false);
// The listing and the manifest disagree: the server changed during the comparison; settle it next time.
if (manifest.SettingsVersion != dto.SettingsVersion) return (link, local);
var mine = SyncPayload.Of(local);
var theirs = SyncPayload.Of(dto, manifest.SettingsJson);
if (mine.SameAs(theirs)) return Agreed(link, local.SettingsVersion, manifest.SettingsVersion);
if (!SyncRules.SameSettings(mine.SettingsJson, theirs.SettingsJson))
if (mine.SameAs(theirs)) return (Agreed(link, local.SettingsVersion, manifest.SettingsVersion), local);
// Last writer wins only when one side changed; both changed differently is the user's choice (BRIEF §14.5).
return (link with
{
return link with
{
ConflictLocalSettings = local.SettingsVersion,
ConflictRemoteSettings = link.RemoteSettingsVersion,
ConflictSettingsJson = SyncRules.NormalizeSettings(theirs.SettingsJson),
};
}
// Only title, tags, rating or notes differ: merge them and give both sides the result.
var merged = SyncRules.Merge(mine, theirs, local.UpdatedAt >= dto.UpdatedAt);
var applied = merged.SameMetadata(mine) ? local : await ApplyLocallyAsync(local, merged, cancellationToken).ConfigureAwait(false);
return await PushAsync(remote, link, applied, manifest.SettingsVersion, cancellationToken).ConfigureAwait(false);
ConflictLocalSettings = local.SettingsVersion,
ConflictRemoteSettings = manifest.SettingsVersion,
ConflictRemote = theirs with { SettingsJson = SyncRules.NormalizeSettings(theirs.SettingsJson) },
}, local);
}
if (!policy.AutoSyncSettings) return link;
if (localChanged) return await PushAsync(remote, link, local, link.BaseRemoteSettings, cancellationToken).ConfigureAwait(false);
if (!policy.AutoSyncSettings) return (link, local);
if (localChanged)
return (policy.CanEdit ? await PushAsync(remote, link, local, link.BaseRemoteSettings, cancellationToken).ConfigureAwait(false) : link, local);
manifest ??= await remote.GetManifestAsync(link.RemoteId, cancellationToken).ConfigureAwait(false);
if (manifest.SettingsVersion != dto.SettingsVersion) return (link, local);
var pulled = await ApplyLocallyAsync(local, SyncPayload.Of(dto, manifest.SettingsJson), cancellationToken).ConfigureAwait(false);
return Agreed(link, pulled.SettingsVersion, manifest.SettingsVersion);
return (Agreed(link, pulled.SettingsVersion, manifest.SettingsVersion), pulled);
}
/// <summary>Sends this PC's payload unless the server moved past <paramref name="expected"/>, which shows up as a conflict next.</summary>
@@ -425,6 +561,62 @@ public sealed class SyncService
}
}
/// <summary>
/// Links local copies and server sequences that hold the same originals but no link joins (an Uploader upload of
/// the same card, a link lost with an old index): candidates start at the same second with the same camera, and
/// at least half of the smaller side's originals must match by SHA-256. A pair that does not match is not fetched
/// again until either side's frames change.
/// </summary>
private async Task MatchByContentAsync(ISyncRemote remote, IReadOnlyList<SequenceDto> listing, Dictionary<Guid, Sequence> locals, SyncPolicy policy,
CancellationToken cancellationToken)
{
var links = await _links.ListAsync(remote.Server, cancellationToken).ConfigureAwait(false);
var linkedLocals = links.Where(l => l.LocalId is not null).Select(l => l.LocalId!.Value).ToHashSet();
var linkedRemotes = links.Where(l => l.LocalId is not null).Select(l => l.RemoteId).ToHashSet();
var candidates = listing.Where(d => !linkedRemotes.Contains(d.Id) && d.FrameCount > 0 && d.FirstCapture is not null)
.ToLookup(d => Second(d.FirstCapture!.Value));
foreach (var local in locals.Values.Where(l => !linkedLocals.Contains(l.Id) && l.FrameCount > 0 && l.FirstCapture is not null).ToList())
{
foreach (var dto in candidates[Second(local.FirstCapture!.Value)])
{
if (linkedRemotes.Contains(dto.Id) || !string.Equals(dto.CameraModel, local.CameraModel, StringComparison.OrdinalIgnoreCase)) continue;
var key = string.Create(CultureInfo.InvariantCulture, $"{local.Id:N}:{local.FramesVersion}:{dto.Id:N}:{dto.FramesVersion}");
if (_unmatched.ContainsKey(key)) continue;
try
{
if (!await SameOriginalsAsync(remote, local, dto, cancellationToken).ConfigureAwait(false))
{
_unmatched[key] = 0;
continue;
}
}
catch (Exception ex) when (IsIsolated(ex, cancellationToken))
{
Log.Warning(LogCategory, $"{local.DisplayTitle} could not be matched with {dto.DisplayTitle}", ex);
continue;
}
Log.Info(LogCategory, $"{local.DisplayTitle} holds the originals of {dto.DisplayTitle} on {remote.Server}: linked");
var link = links.FirstOrDefault(l => l.RemoteId == dto.Id);
var linked = Unlinked(Observe(link, remote.Server, dto)) with { LocalId = local.Id };
await ReconcileSafelyAsync(remote, linked, dto, local, locals, policy, cancellationToken).ConfigureAwait(false);
linkedRemotes.Add(dto.Id);
break;
}
}
}
private async Task<bool> SameOriginalsAsync(ISyncRemote remote, Sequence local, SequenceDto dto, CancellationToken cancellationToken)
{
var hashes = (await SequenceFrames.ListAsync(_db, local.Id, cancellationToken).ConfigureAwait(false))
.Select(f => f.Sha256?.ToLowerInvariant()).OfType<string>().ToHashSet(StringComparer.Ordinal);
if (hashes.Count == 0) return false;
var manifest = await remote.GetManifestAsync(dto.Id, cancellationToken).ConfigureAwait(false);
var shared = manifest.Frames.Select(f => f.Sha256.ToLowerInvariant()).Distinct(StringComparer.Ordinal).Count(hashes.Contains);
return shared > 0 && shared * 2 >= Math.Min(hashes.Count, manifest.Frames.Count);
}
private static DateTime Second(DateTime time) => new(time.Ticks - time.Ticks % TimeSpan.TicksPerSecond, DateTimeKind.Unspecified);
/// <summary>Writes a payload into the local sidecar, project and index (each write bumps the local settings version).</summary>
private async Task<Sequence> ApplyLocallyAsync(Sequence local, SyncPayload payload, CancellationToken cancellationToken)
{
@@ -441,18 +633,21 @@ public sealed class SyncService
return await _db.Sequences.GetAsync(local.Id, cancellationToken).ConfigureAwait(false) ?? current;
}
/// <summary>"Save both": this PC's project is kept as <c>.titano/project.local-&lt;UTC time&gt;.json</c> before the server's replaces it.</summary>
private async Task SaveCopyAsync(Sequence local, CancellationToken cancellationToken)
/// <summary>"Save both": this PC's project is kept next to <c>project.json</c> as <c>project.this-pc-&lt;local time&gt;.json</c> before the server's replaces it.</summary>
private async Task<string> SaveCopyAsync(Sequence local, CancellationToken cancellationToken)
{
var archive = await _db.Archives.GetAsync(local.ArchiveId, cancellationToken).ConfigureAwait(false)
?? throw new InvalidDataException($"Archive {local.ArchiveId} is not indexed.");
var folder = new ArchivePaths(archive.RootPath).Sequence(local.Folder);
Directory.CreateDirectory(folder.MetaDirectory);
var name = string.Create(CultureInfo.InvariantCulture, $"project.local-{DateTime.UtcNow:yyyyMMdd-HHmmss}.json");
AtomicFile.WriteAllText(Path.Combine(folder.MetaDirectory, name), SyncRules.NormalizeSettings(local.SettingsJson));
Log.Info(LogCategory, $"Settings of {local.DisplayTitle} kept as {name}");
var path = Path.Combine(folder.MetaDirectory, SavedCopyName(DateTime.Now));
AtomicFile.WriteAllText(path, SyncRules.NormalizeSettings(local.SettingsJson));
Log.Info(LogCategory, $"Settings of {local.DisplayTitle} kept as {path}");
return path;
}
internal static string SavedCopyName(DateTime localTime) => string.Create(CultureInfo.InvariantCulture, $"project.this-pc-{localTime:yyyyMMdd-HHmmss}.json");
private async Task ForgetAsync(SyncLink link, CancellationToken cancellationToken)
{
await _links.DeleteAsync(link.Server, link.RemoteId, cancellationToken).ConfigureAwait(false);
@@ -461,9 +656,9 @@ public sealed class SyncService
}
/// <summary>Writes each local sequence's state for the Library and returns the table.</summary>
private async Task<IReadOnlyList<SyncEntry>> StoreStatesAsync(string server, CancellationToken cancellationToken)
private async Task<IReadOnlyList<SyncEntry>> StoreStatesAsync(string server, Dictionary<Guid, Sequence>? locals, CancellationToken cancellationToken)
{
var entries = await ListAsync(server, cancellationToken).ConfigureAwait(false);
var entries = await EntriesAsync(server, locals, cancellationToken).ConfigureAwait(false);
foreach (var entry in entries)
{
if (entry.Local is { } local && SyncRules.ToSequenceState(entry.Status) is { } state && state != local.SyncState)
@@ -472,6 +667,50 @@ public sealed class SyncService
return entries;
}
/// <summary>The table from the stored links and <paramref name="known"/> local sequences (read from the index when null).</summary>
private async Task<IReadOnlyList<SyncEntry>> EntriesAsync(string server, Dictionary<Guid, Sequence>? known, CancellationToken cancellationToken)
{
var links = await _links.ListAsync(server, cancellationToken).ConfigureAwait(false);
var locals = known is null ? await LocalSequencesAsync(cancellationToken).ConfigureAwait(false) : new Dictionary<Guid, Sequence>(known);
var transfers = await _links.ActiveTransfersAsync(cancellationToken).ConfigureAwait(false);
var entries = new List<SyncEntry>(links.Count + locals.Count);
foreach (var link in links)
{
var local = await LocalOfAsync(link, locals, cancellationToken).ConfigureAwait(false);
if (local is not null) locals.Remove(local.Id);
var transfer = Pick(local is null ? null : transfers.GetValueOrDefault(local.Id), transfers.GetValueOrDefault(link.RemoteId));
entries.Add(new SyncEntry(local, link, transfer is null ? SyncRules.Status(local, link) : SyncStatus.Transferring, transfer));
}
foreach (var local in locals.Values)
{
var transfer = Pick(transfers.GetValueOrDefault(local.Id), null);
entries.Add(new SyncEntry(local, null, transfer is null ? SyncStatus.LocalOnly : SyncStatus.Transferring, transfer));
}
return [.. entries.OrderBy(e => e.Status switch { SyncStatus.Conflict => 0, SyncStatus.Transferring => 1, _ => 2 })
.ThenBy(e => e.Title, StringComparer.CurrentCultureIgnoreCase)];
}
/// <summary>The transfer a row shows: the user's before background ones, originals before renders before proxies, running before waiting.</summary>
private static Job? Pick(IReadOnlyList<Job>? local, IReadOnlyList<Job>? remote) =>
(local ?? []).Concat(remote ?? [])
.OrderByDescending(j => j.Priority)
.ThenBy(j => TransferKind(j) switch
{
SyncTransferKind.DownloadProxies => 2,
SyncTransferKind.SendExports or SyncTransferKind.GetExports => 1,
_ => 0,
})
.ThenBy(j => j.State == JobState.Running ? 0 : 1)
.FirstOrDefault();
/// <summary>The local copy of a link: from <paramref name="locals"/>, or the index when the paged listing missed it.</summary>
private async Task<Sequence?> LocalOfAsync(SyncLink? link, Dictionary<Guid, Sequence>? locals, CancellationToken cancellationToken)
{
if (link?.LocalId is not { } id) return null;
if (locals is not null && locals.TryGetValue(id, out var known)) return known;
return await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false);
}
private async Task<(SyncLink Link, Sequence Local)> LinkedAsync(string server, Guid remoteId, CancellationToken cancellationToken)
{
var link = await _links.GetAsync(server, remoteId, cancellationToken).ConfigureAwait(false);
@@ -498,8 +737,16 @@ public sealed class SyncService
private async Task<Job> EnqueueAsync(JobEngine engine, JobKind kind, Guid target, string label, SyncJobParameters parameters, JobPriority priority,
CancellationToken cancellationToken)
{
var active = await _links.ActiveTransfersAsync(cancellationToken).ConfigureAwait(false);
if (active.TryGetValue(target, out var running) && running.Kind == kind) return running;
var wanted = parameters.Kind(kind);
var active = (await _links.ActiveTransfersAsync(cancellationToken).ConfigureAwait(false)).GetValueOrDefault(target) ?? [];
foreach (var job in active)
{
var running = TransferKind(job);
var outranked = running == SyncTransferKind.DownloadProxies && job.Priority < priority;
if (running == wanted && !outranked) return job;
if (outranked && wanted is SyncTransferKind.DownloadProxies or SyncTransferKind.DownloadOriginals)
await engine.CancelAsync(job.Id, cancellationToken).ConfigureAwait(false);
}
return await engine.EnqueueAsync(kind, [target], label, JsonSerializer.Serialize(parameters, SyncJobJson.Default.SyncJobParameters), priority,
cancellationToken: cancellationToken).ConfigureAwait(false);
}
@@ -525,7 +772,7 @@ public sealed class SyncService
RemoteSettingsVersion = remoteVersion,
ConflictLocalSettings = null,
ConflictRemoteSettings = null,
ConflictSettingsJson = null,
ConflictRemote = null,
};
private static SyncLink Unlinked(SyncLink link) => link with
@@ -535,10 +782,16 @@ public sealed class SyncService
BaseRemoteSettings = null,
DiffLocalFrames = null,
DiffRemoteFrames = null,
DiffLocalRenders = null,
DiffRemoteRenders = null,
MissingRemote = 0,
MissingLocal = 0,
ExportsToGet = 0,
ExportsToGetBytes = 0,
ExportsToSend = 0,
ExportsToSendBytes = 0,
ConflictLocalSettings = null,
ConflictRemoteSettings = null,
ConflictSettingsJson = null,
ConflictRemote = null,
};
}