feat(sync): client sync engine with links, settings conflicts, transfers and background agent

Per-sequence state between the local index and a server from listings and
manifest diffs; version-counter settings sync with explicit conflicts; upload,
original and proxy download jobs; WebSocket-driven background agent.

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

No files matched your search

+529
View File
@@ -0,0 +1,529 @@
using System.Diagnostics;
using System.Globalization;
using System.Net;
using System.Text.Json;
using Titano.Core.Archiving;
using Titano.Core.Diagnostics;
using Titano.Core.IO;
using Titano.Core.Model;
using Titano.Data.Archiving;
using Titano.Data.Jobs;
using Titano.Data.Processing;
using Titano.Data.Repositories;
using Titano.Protocol;
using Titano.Protocol.Client;
using SequenceFrames = Titano.Data.Processing.SequenceFrames;
using SequenceManifest = Titano.Protocol.SequenceManifest;
namespace Titano.Data.Sync;
/// <summary>Settings of a <see cref="SyncService"/>.</summary>
public sealed record SyncOptions
{
/// <summary>Decoders, lease owner and lease timing for sidecar and project writes (shared with the archive engine).</summary>
public ArchiveServiceOptions Archive { get; init; } = new();
/// <summary>Folder of the proxy cache of server sequences (inside the client's cache).</summary>
public required string ProxyCacheDirectory { get; init; }
/// <summary>Concurrent frame downloads of one job.</summary>
public int Downloads { get; init; } = 4;
/// <summary>Concurrent file uploads of one job (the server accepts 8 chunks in flight per user).</summary>
public int Uploads { get; init; } = 2;
}
/// <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.
/// </summary>
public sealed class SyncService
{
private const string LogCategory = "sync";
private const string SessionKeyPrefix = "titano-sync:";
private readonly TitanoDatabase _db;
private readonly SyncLinkStore _links;
private readonly ProjectStore _projects;
private readonly SemaphoreSlim _gate = new(1, 1);
public SyncService(TitanoDatabase db, ArchiveService archives, SyncOptions options)
{
_db = db;
Archives = archives;
Options = options;
_links = new SyncLinkStore(db);
_projects = new ProjectStore(db, new SequenceWriter(options.Archive));
Proxies = new ProxyCache(options.ProxyCacheDirectory);
}
public SyncOptions Options { get; }
/// <summary>The links or local states of a server (the argument) changed: refresh, resolution, transfer; raised on any thread.</summary>
public event Action<string>? Changed;
internal ProxyCache Proxies { get; }
internal SyncLinkStore Links => _links;
internal TitanoDatabase Database => _db;
internal ArchiveService Archives { get; }
/// <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>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");
// ---------------- Table ----------------
/// <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.
/// </summary>
public async Task<SyncSnapshot> RefreshAsync(ISyncRemote remote, SyncPolicy policy, CancellationToken cancellationToken)
{
var clock = Stopwatch.StartNew();
var listing = await remote.ListSequencesAsync(cancellationToken).ConfigureAwait(false);
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);
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);
}
foreach (var gone in links.Values) await ForgetAsync(gone, cancellationToken).ConfigureAwait(false);
}
finally
{
_gate.Release();
}
var entries = await StoreStatesAsync(remote.Server, cancellationToken).ConfigureAwait(false);
Changed?.Invoke(remote.Server);
return new SyncSnapshot(remote.Server, entries, DateTimeOffset.UtcNow, clock.Elapsed);
}
/// <summary>Compares the given server sequences again (live events, finished transfers); a sequence gone from the server is forgotten.</summary>
public async Task RefreshSequencesAsync(ISyncRemote remote, IReadOnlyCollection<Guid> remoteIds, SyncPolicy policy, CancellationToken cancellationToken)
{
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
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);
}
}
finally
{
_gate.Release();
}
await StoreStatesAsync(remote.Server, 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>
/// Links a local sequence to a server sequence holding the same originals. Nothing was agreed yet, so the next
/// comparison settles equal settings and reports different ones as a conflict.
/// </summary>
public async Task LinkAsync(string server, Guid remoteId, Guid localId, CancellationToken cancellationToken = default)
{
var local = await _db.Sequences.GetAsync(localId, cancellationToken).ConfigureAwait(false)
?? throw new ArgumentException($"Unknown sequence {localId}.", nameof(localId));
await LinkAsync(server, remoteId, local, cancellationToken).ConfigureAwait(false);
}
// ---------------- 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)
{
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)
{
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);
}
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);
}
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);
Changed?.Invoke(remote.Server);
}
/// <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);
// ---------------- Transfers ----------------
/// <summary>Queues the upload of a local sequence's originals and settings, unless one is already waiting or running.</summary>
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 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.
/// </summary>
public Task<Job> EnqueueDownloadAsync(JobEngine engine, string server, Guid remoteId, string title, SyncDownloadMode mode, Guid? archiveId,
JobPriority priority = JobPriority.User, CancellationToken cancellationToken = default) =>
EnqueueAsync(engine, JobKind.Download, remoteId, title, new SyncJobParameters(server, mode, archiveId), priority, cancellationToken);
/// <summary>Handlers for <see cref="JobKind.UploadCommit"/> and <see cref="JobKind.Download"/>; register them on the client's engine.</summary>
public IReadOnlyList<IJobHandler> CreateJobHandlers(ISyncConnector connector)
{
var transfers = new SyncTransfers(this);
return [new SyncJobHandler(JobKind.UploadCommit, transfers, connector), new SyncJobHandler(JobKind.Download, transfers, connector)];
}
/// <summary>A server sequence from the proxy cache, for the editor; null when its proxies were never fetched or were cleared.</summary>
public RemoteSequence? OpenRemote(string server, Guid remoteId) => Proxies.Load(server, remoteId);
// ---------------- Engine ----------------
/// <summary>Server ids of the sequences an upload or download job is working on.</summary>
internal async Task<IReadOnlySet<Guid>> TransferringAsync(string server, CancellationToken cancellationToken)
{
var transfers = await _links.ActiveTransfersAsync(cancellationToken).ConfigureAwait(false);
var links = await _links.ListAsync(server, cancellationToken).ConfigureAwait(false);
return links.Where(l => transfers.ContainsKey(l.RemoteId) || (l.LocalId is { } id && transfers.ContainsKey(id))).Select(l => l.RemoteId).ToHashSet();
}
/// <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;
}
/// <summary>Makes the server's copy equal to this PC's (an upload sends the settings with the originals).</summary>
internal async Task PushAllAsync(ISyncRemote remote, Guid remoteId, CancellationToken cancellationToken)
{
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);
var updated = await remote.UpdateSequenceAsync(remoteId, SyncPayload.Of(local).ToRequest(dto.SettingsVersion), cancellationToken).ConfigureAwait(false);
await _links.UpsertAsync(Agreed(Observe(link, remote.Server, updated), local.SettingsVersion, updated.SettingsVersion), cancellationToken)
.ConfigureAwait(false);
}
finally
{
_gate.Release();
}
}
/// <summary>Makes this PC's copy equal to the server's (a sequence a download just created takes the server's settings).</summary>
internal async Task TakeAllAsync(ISyncRemote remote, Guid remoteId, CancellationToken cancellationToken)
{
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);
var manifest = await remote.GetManifestAsync(remoteId, cancellationToken).ConfigureAwait(false);
var applied = await ApplyLocallyAsync(local, SyncPayload.Of(dto, manifest.SettingsJson), cancellationToken).ConfigureAwait(false);
await _links.UpsertAsync(Agreed(Observe(link, remote.Server, dto), applied.SettingsVersion, manifest.SettingsVersion), cancellationToken)
.ConfigureAwait(false);
}
finally
{
_gate.Release();
}
}
/// <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)
{
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
var link = Observe(await _links.GetAsync(server, dto.Id, cancellationToken).ConfigureAwait(false), server, dto);
await _links.UpsertAsync(link with { ProxiesCached = cached, ProxiesFramesVersion = framesVersion }, cancellationToken).ConfigureAwait(false);
}
finally
{
_gate.Release();
}
Changed?.Invoke(server);
}
private async Task ReconcileSafelyAsync(ISyncRemote remote, SyncLink link, SequenceDto dto, Sequence? local, SyncPolicy policy, CancellationToken cancellationToken)
{
try
{
link = await ReconcileAsync(remote, link, dto, local, policy, cancellationToken).ConfigureAwait(false);
}
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound)
{
// Deleted between the listing and the manifest: the next refresh 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)
{
// The local archive is offline or busy: compare again next time; the other sequences go on.
Log.Warning(LogCategory, $"{dto.DisplayTitle} could not be synced", ex);
}
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,
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);
}
SequenceManifest? manifest = null;
if (link.DiffLocalFrames != local.FramesVersion || link.DiffRemoteFrames != link.RemoteFramesVersion)
{
manifest = await remote.GetManifestAsync(link.RemoteId, cancellationToken).ConfigureAwait(false);
var frames = await SequenceFrames.ListAsync(_db, local.Id, cancellationToken).ConfigureAwait(false);
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
{
DiffLocalFrames = local.FramesVersion,
DiffRemoteFrames = manifest.FramesVersion,
RemoteFramesVersion = manifest.FramesVersion,
MissingRemote = missingRemote,
MissingLocal = missingLocal,
};
}
link = await SettleSettingsAsync(remote, link, dto, local, manifest, policy, cancellationToken).ConfigureAwait(false);
return link with { SyncedAt = DateTimeOffset.UtcNow };
}
private async Task<SyncLink> 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)
{
if (link.ConflictLocalSettings == local.SettingsVersion && link.ConflictRemoteSettings == link.RemoteSettingsVersion) return link;
manifest ??= await remote.GetManifestAsync(link.RemoteId, cancellationToken).ConfigureAwait(false);
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))
{
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);
}
if (!policy.AutoSyncSettings) return link;
if (localChanged) return await PushAsync(remote, link, local, link.BaseRemoteSettings, cancellationToken).ConfigureAwait(false);
manifest ??= await remote.GetManifestAsync(link.RemoteId, cancellationToken).ConfigureAwait(false);
var pulled = await ApplyLocallyAsync(local, SyncPayload.Of(dto, manifest.SettingsJson), cancellationToken).ConfigureAwait(false);
return Agreed(link, pulled.SettingsVersion, manifest.SettingsVersion);
}
/// <summary>Sends this PC's payload unless the server moved past <paramref name="expected"/>, which shows up as a conflict next.</summary>
private static async Task<SyncLink> PushAsync(ISyncRemote remote, SyncLink link, Sequence local, int? expected, CancellationToken cancellationToken)
{
try
{
var updated = await remote.UpdateSequenceAsync(link.RemoteId, SyncPayload.Of(local).ToRequest(expected), cancellationToken).ConfigureAwait(false);
return Agreed(Observe(link, link.Server, updated), local.SettingsVersion, updated.SettingsVersion);
}
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.Conflict)
{
return Observe(link, link.Server, await remote.GetSequenceAsync(link.RemoteId, cancellationToken).ConfigureAwait(false));
}
}
/// <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)
{
var current = local;
if (!payload.SameMetadata(SyncPayload.Of(local)))
current = await Archives.SetSequenceInfoAsync(local.Id, payload.Title, payload.Tags, payload.Rating, payload.Notes, cancellationToken).ConfigureAwait(false);
if (!SyncRules.SameSettings(payload.SettingsJson, current.SettingsJson))
{
var archive = await _db.Archives.GetAsync(current.ArchiveId, cancellationToken).ConfigureAwait(false)
?? throw new InvalidDataException($"Archive {current.ArchiveId} is not indexed.");
var project = ProjectStore.Parse(SyncRules.NormalizeSettings(payload.SettingsJson));
await _projects.UpdateAsync(new ArchivePaths(archive.RootPath), current, _ => project, cancellationToken).ConfigureAwait(false);
}
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)
{
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}");
}
private async Task ForgetAsync(SyncLink link, CancellationToken cancellationToken)
{
await _links.DeleteAsync(link.Server, link.RemoteId, cancellationToken).ConfigureAwait(false);
Proxies.Delete(link.Server, link.RemoteId);
Log.Info(LogCategory, $"{link.Title} is no longer on {link.Server}");
}
/// <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)
{
var entries = await ListAsync(server, cancellationToken).ConfigureAwait(false);
foreach (var entry in entries)
{
if (entry.Local is { } local && SyncRules.ToSequenceState(entry.Status) is { } state && state != local.SyncState)
await _links.SetLocalStateAsync(local.Id, state, cancellationToken).ConfigureAwait(false);
}
return entries;
}
private async Task<(SyncLink Link, Sequence Local)> LinkedAsync(string server, Guid remoteId, CancellationToken cancellationToken)
{
var link = await _links.GetAsync(server, remoteId, cancellationToken).ConfigureAwait(false);
var local = link?.LocalId is { } id ? await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false) : null;
if (link is null || local is null) throw new InvalidOperationException($"Sequence {remoteId} has no local copy.");
return (link, local);
}
private async Task<Dictionary<Guid, Sequence>> LocalSequencesAsync(CancellationToken cancellationToken)
{
var all = new Dictionary<Guid, Sequence>();
string? cursor = null;
do
{
var page = await _db.Sequences.ListAsync(new SequenceQuery { Limit = 1000, Cursor = cursor, Sort = SequenceSort.Oldest }, cancellationToken)
.ConfigureAwait(false);
foreach (var s in page.Items) all[s.Id] = s;
cursor = page.NextCursor;
}
while (cursor is not null);
return all;
}
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;
return await engine.EnqueueAsync(kind, [target], label, JsonSerializer.Serialize(parameters, SyncJobJson.Default.SyncJobParameters), priority,
cancellationToken: cancellationToken).ConfigureAwait(false);
}
/// <summary>The link with the server's side as <paramref name="dto"/> lists it (a new link when there was none).</summary>
internal static SyncLink Observe(SyncLink? link, string server, SequenceDto dto) =>
(link ?? new SyncLink { Server = server, RemoteId = dto.Id, Title = dto.DisplayTitle }) with
{
Title = dto.DisplayTitle,
FrameCount = dto.FrameCount,
TotalBytes = dto.TotalBytes,
RenderCount = dto.RenderedCount,
RemoteStatus = (SequenceStatus)dto.Status,
RemoteSettingsVersion = dto.SettingsVersion,
RemoteFramesVersion = dto.FramesVersion,
RemoteUpdatedAt = dto.UpdatedAt,
};
private static SyncLink Agreed(SyncLink link, int localVersion, int remoteVersion) => link with
{
BaseLocalSettings = localVersion,
BaseRemoteSettings = remoteVersion,
RemoteSettingsVersion = remoteVersion,
ConflictLocalSettings = null,
ConflictRemoteSettings = null,
ConflictSettingsJson = null,
};
private static SyncLink Unlinked(SyncLink link) => link with
{
LocalId = null,
BaseLocalSettings = null,
BaseRemoteSettings = null,
DiffLocalFrames = null,
DiffRemoteFrames = null,
MissingRemote = 0,
MissingLocal = 0,
ConflictLocalSettings = null,
ConflictRemoteSettings = null,
ConflictSettingsJson = null,
};
}