using System.Diagnostics;
using System.Globalization;
using System.Net;
using System.Text.Json;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.IO;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Archiving;
using Chronos.Data.Copies;
using Chronos.Data.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Repositories;
using Chronos.Protocol;
using Chronos.Protocol.Client;
using SequenceFrames = Chronos.Data.Processing.SequenceFrames;
using SequenceManifest = Chronos.Protocol.SequenceManifest;
namespace Chronos.Data.Sync;
/// Settings of a .
public sealed record SyncOptions
{
/// Decoders, lease owner and lease timing for sidecar and project writes (shared with the archive engine).
public ArchiveServiceOptions Archive { get; init; } = new();
///
/// Folder of the proxy cache of server sequences as 1.0 laid it out (<cache>\proxies\<address hash>):
/// where proxies go without , and where a sequence's proxies are still read from, with it,
/// until they are moved into their server's home.
///
public required string ProxyCacheDirectory { get; init; }
///
/// The servers' homes in the client's cache (<cache>\servers, owner review 5, #66): with it, a server's
/// proxies go to <servers>\<home folder>\proxies\<sequence id>
/// (). Null keeps the 1.0 layout under .
///
public string? ServersDirectory { get; init; }
/// The alias table the cache finds a server's home by (); null: every key is its own.
public Func? Identity { get; init; }
/// Concurrent frame downloads of one job.
public int Downloads { get; init; } = 4;
/// Concurrent file uploads of one job (the server accepts 8 chunks in flight per user).
public int Uploads { get; init; } = 2;
}
///
/// 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 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 , against the versions the user was shown. The settings'
/// frame positions are translated by photo to the frames of the copy they go to (). Uploads and
/// downloads run as jobs (): 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 ; renders travel on request. Thumbnails never travel upward, and
/// proxies only for originals the server cannot decode (BRIEF §2.3: HEIF), made here and counted with the originals the
/// server lacks. Copies whose ids differ are found after each full refresh () and linked by themselves
/// only as allows; every link has a pair in (owner review 6, #73).
/// The state of each local sequence is written to its sync_state for the Library. A failure while
/// comparing one sequence is recorded on its link and does not stop the others.
///
public sealed class SyncService
{
private const string LogCategory = "sync";
private const string SessionKeyPrefix = "chronos-sync:";
/// Linked sequences answering 404 in one refresh, none answering, that read as a server serving something else (design §6.3).
private const int SweepLinks = 5;
/// How long a pair marked gone once waits before its remote is asked for again (design §6.3).
private static readonly TimeSpan GoneRecheck = FoundCopyStore.GoneRecheck;
/// Recomputes states without sending or taking settings on the user's behalf.
internal static readonly SyncPolicy CompareOnly = new(AutoSyncSettings: false);
private readonly ChronosDatabase _db;
private readonly SyncLinkStore _links;
private readonly SequenceWriter _writer;
private readonly SemaphoreSlim _gate = new(1, 1);
public SyncService(ChronosDatabase db, ArchiveService archives, SyncOptions options)
{
_db = db;
Archives = archives;
Options = options;
_links = new SyncLinkStore(db);
_writer = new SequenceWriter(options.Archive);
Proxies = new ProxyCache(options.ProxyCacheDirectory, options.ServersDirectory, options.Identity);
Copies = new FoundCopyStore(db);
Finder = new CopyFinder(db, Copies, new CopySides(db));
}
public SyncOptions Options { get; }
/// The pairs of copies of one time-lapse (owner review 6, #73): every link has one, and detection adds the others.
public FoundCopyStore Copies { get; }
/// Detection of the copies whose ids differ (owner review 6, #73), run at the end of every full refresh.
public CopyFinder Finder { get; }
/// The links or local states of a server (the argument) changed: refresh, resolution, transfer; raised on any thread.
public event Action? Changed;
/// A refresh of a server (the argument) found new pairs, linked some by itself or asked again about kept-apart ones; raised on any thread.
public event Action? CopiesFound;
internal ProxyCache Proxies { get; }
internal SyncLinkStore Links => _links;
internal ChronosDatabase Database => _db;
internal ArchiveService Archives { get; }
///
/// "https://nas.local:8443": the address key (scheme, lower-case host, port, path), the key every server had in 1.0 and an
/// older server, which announces no id, still has. A server that announces one is keyed by it
/// (), its address keys kept as aliases.
///
public static string ServerKey(Uri address) => address.GetLeftPart(UriPartial.Path).TrimEnd('/').ToLowerInvariant();
///
/// Moves the links of (an address key the server was reached under) to (its
/// id key, owner review 5, #66) in one transaction. A link both keys hold for one server sequence, or for one local copy,
/// keeps the row compared last (); the other row goes, which loses nothing: the next
/// comparison makes links again. Nothing happens when the keys are the same.
///
/// The links moved, and those dropped for a newer one.
public async Task<(int Moved, int Dropped)> RekeyAsync(string from, string to, CancellationToken cancellationToken)
{
var result = await _links.RekeyAsync(from, to, cancellationToken).ConfigureAwait(false);
if (result.Moved + result.Dropped > 0) Changed?.Invoke(to);
return result;
}
/// What an upload or download job moves; null for any other job.
public static SyncTransferKind? TransferKind(Job job) => SyncJobParameters.Read(job)?.Kind(job.Kind);
/// Session key the local archive groups the downloaded originals of one server sequence by.
internal static string SessionKey(Guid remoteId) => SessionKeyPrefix + remoteId.ToString("N");
// ---------------- Table ----------------
///
/// Lists the server, compares every sequence with its local copy, sends or takes settings changed on one side when
/// is on, forgets sequences the server confirms deleted (marking their pairs,
/// design §6.3), stores the states, and then, outside the gate, looks for copies whose ids differ
/// (): linked by themselves only as allows,
/// asked otherwise ().
///
public async Task RefreshAsync(ISyncRemote remote, SyncPolicy policy, CancellationToken cancellationToken)
{
var clock = Stopwatch.StartNew();
var listing = await remote.ListSequencesAsync(cancellationToken).ConfigureAwait(false);
var refreshId = Guid.NewGuid();
Dictionary locals;
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
var links = (await _links.ListAsync(remote.Server, cancellationToken).ConfigureAwait(false)).ToDictionary(l => l.RemoteId);
locals = await LocalSequencesAsync(cancellationToken).ConfigureAwait(false);
var found = 0;
foreach (var dto in listing)
{
links.Remove(dto.Id, out var link);
if (link?.LocalId is not null) found++;
var local = await LocalOfAsync(link, locals, cancellationToken).ConfigureAwait(false);
await ReconcileSafelyAsync(remote, Observe(link, remote.Server, dto), dto, local, locals, policy, 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.
var gone = new List();
foreach (var link in links.Values)
{
if (await CompareOneAsync(remote, link.RemoteId, link, locals, policy, null, cancellationToken, gone).ConfigureAwait(false) && link.LocalId is not null)
found++;
}
// Every linked sequence answering 404 at once is a server that now serves something else (another archive, a new
// identity), not five deletions: the links go as before, and no pair reads "deleted on server".
var sweep = gone.Count(l => l.LocalId is not null) >= SweepLinks && found == 0;
if (sweep) Log.Warning(LogCategory, $"Every linked sequence of {remote.Server} answered 404 at once ({gone.Count}): none is marked deleted on the server");
foreach (var link in gone) await ForgetAsync(link, sweep ? null : refreshId, cancellationToken).ConfigureAwait(false);
await AskGoneAgainAsync(remote, listing, refreshId, cancellationToken).ConfigureAwait(false);
}
finally
{
_gate.Release();
}
var result = CopyFindResult.Empty;
try
{
// Outside the gate: the lookup and up to 50 comparisons must not hold uploads and resolutions up; a link takes the gate itself.
result = await Finder.FindServerAsync(remote, listing, locals, policy.Linking,
(copy, dto, local) => AutoLinkAsync(remote, policy, copy, dto, local, locals, cancellationToken), cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (IsIsolated(ex, cancellationToken))
{
Log.Warning(LogCategory, $"Matches on {remote.Server} could not be looked for", ex);
}
var entries = await StoreStatesAsync(remote.Server, locals, cancellationToken).ConfigureAwait(false);
Changed?.Invoke(remote.Server);
if (!result.IsEmpty) CopiesFound?.Invoke(remote.Server, result);
return new SyncSnapshot(remote.Server, entries, DateTimeOffset.UtcNow, clock.Elapsed);
}
/// Compares the given server sequences again (live events, finished transfers); a sequence gone from the server is forgotten.
public async Task RefreshSequencesAsync(ISyncRemote remote, IReadOnlyCollection remoteIds, SyncPolicy policy, CancellationToken cancellationToken)
{
var refreshId = Guid.NewGuid();
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
foreach (var id in remoteIds)
{
var link = await _links.GetAsync(remote.Server, id, cancellationToken).ConfigureAwait(false);
await CompareOneAsync(remote, id, link, null, policy, refreshId, cancellationToken).ConfigureAwait(false);
}
}
finally
{
_gate.Release();
}
await StoreStatesAsync(remote.Server, null, cancellationToken).ConfigureAwait(false);
Changed?.Invoke(remote.Server);
}
///
/// The sync table of as last compared: every server sequence and every local one, with
/// active transfers; conflicts first, then transfers, then by title.
///
public Task> ListAsync(string server, CancellationToken cancellationToken) => EntriesAsync(server, null, cancellationToken);
///
/// 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.
///
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);
}
///
/// Unlinks a server sequence from its local copy (owner review 6, #73): the link stays as an observation of the server's
/// sequence, the local copy reads as this PC's only, and the pair is kept apart (asked again only by a large later change).
/// Nothing happens when the server sequence has no local copy.
///
public async Task UnlinkAsync(string server, Guid remoteId, CancellationToken cancellationToken = default)
{
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
if (await _links.GetAsync(server, remoteId, cancellationToken).ConfigureAwait(false) is not { LocalId: { } localId } link) return;
await _links.UpsertAsync(Unlinked(link), cancellationToken).ConfigureAwait(false);
await _links.SetLocalStateAsync(localId, SyncState.LocalOnly, cancellationToken).ConfigureAwait(false);
var row = await Copies.FindRemoteAsync(localId, server, remoteId, cancellationToken).ConfigureAwait(false)
?? await Copies.EnsureLinkedAsync(server, remoteId, localId, cancellationToken).ConfigureAwait(false);
await Copies.SetStateAsync(row.Id, null, CopyState.KeptApart, new CopyAnswer(row.Fingerprint, row.Score.Shared, null, false, DateTimeOffset.UtcNow),
cancellationToken).ConfigureAwait(false);
Log.Info(LogCategory, $"{link.Title} unlinked from its copy on this PC");
}
finally
{
_gate.Release();
}
Changed?.Invoke(server);
}
// ---------------- Settings ----------------
///
/// 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
/// is thrown, as it is when cannot keep this PC's version first or the server's
/// version cannot be written because the folder is not where the index has it (another index moved it; its message then
/// says to try again after the next scan). Returns the file this PC's settings were saved to for
/// , else null.
///
public async Task ResolveAsync(ISyncRemote remote, Guid remoteId, SyncResolution resolution, CancellationToken cancellationToken)
{
string? saved = null;
var changed = false;
var moved = false;
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
var (link, local) = await LinkedAsync(remote.Server, remoteId, cancellationToken).ConfigureAwait(false);
if (link is not { ConflictRemote: not null, ConflictLocalSettings: { } seenLocal, ConflictRemoteSettings: { } seenRemote }
|| local.SettingsVersion != seenLocal)
{
changed = true;
}
else if (resolution == SyncResolution.KeepMine)
{
try
{
var manifest = await remote.GetManifestAsync(remoteId, cancellationToken).ConfigureAwait(false);
// Edited here since it was shown, or frames that kept changing while they were read: compared again.
if (await RequestAsync(remote, local, manifest, seenRemote, cancellationToken).ConfigureAwait(false) is not { } request)
{
changed = true;
}
else
{
var updated = await remote.UpdateSequenceAsync(remoteId, request, cancellationToken).ConfigureAwait(false);
link = Agreed(Observe(link, remote.Server, updated), local.SettingsVersion, updated.SettingsVersion);
}
}
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.Conflict)
{
changed = true;
}
}
else
{
// The server's version as it is now: the one shown, with its positions on the server's current frames.
var dto = await remote.GetSequenceAsync(remoteId, cancellationToken).ConfigureAwait(false);
var manifest = dto.SettingsVersion == seenRemote ? await remote.GetManifestAsync(remoteId, cancellationToken).ConfigureAwait(false) : null;
if (manifest?.SettingsVersion != seenRemote)
{
changed = true;
}
else if (resolution == SyncResolution.SaveBoth && (saved = await SaveCopyAsync(local, cancellationToken).ConfigureAwait(false)) is null)
{
// This PC's version could not be kept (another index moved the folder): the server's does not replace it,
// even where this index's scan finds the folder before the server's version would be written.
changed = true;
moved = true;
}
else
{
var theirs = SyncPayload.Of(dto, manifest!.SettingsJson);
if (await ApplyLocallyAsync(local, theirs, Positions(remote, local, manifest), cancellationToken).ConfigureAwait(false) is { } applied)
{
link = Agreed(Observe(link, remote.Server, dto), applied.SettingsVersion, seenRemote);
}
else
{
// Edited on this PC since it was read, or the folder moved by another index: the copy of a version the
// user did not choose to keep goes.
changed = true;
moved = await FolderMovedAsync(local, cancellationToken).ConfigureAwait(false);
if (saved is not null) await DeleteCopyAsync(local, saved, cancellationToken).ConfigureAwait(false);
saved = null;
}
}
}
if (!changed)
{
await _links.UpsertAsync(link with { SyncedAt = DateTimeOffset.UtcNow }, cancellationToken).ConfigureAwait(false);
Log.Info(LogCategory, $"Conflict on {local.DisplayTitle} settled: {resolution}");
}
}
finally
{
_gate.Release();
}
if (changed)
{
await RefreshSequencesAsync(remote, [remoteId], CompareOnly, cancellationToken).ConfigureAwait(false);
// Choosing again changes nothing while the folder is not where the index has it: the next scan finds it.
throw new SyncConflictChangedException(Loc.L(moved ? "Errors.Archive.FolderMoved" : "Errors.Sync.ChangedAgain"));
}
await StoreStatesAsync(remote.Server, null, cancellationToken).ConfigureAwait(false);
Changed?.Invoke(remote.Server);
return saved;
}
/// Sends or takes settings changed on one side only (the row action while automatic sync is off).
public Task SyncSettingsAsync(ISyncRemote remote, Guid remoteId, SyncPolicy policy, CancellationToken cancellationToken) =>
RefreshSequencesAsync(remote, [remoteId], policy with { AutoSyncSettings = true }, cancellationToken);
// ---------------- Transfers ----------------
/// Queues the upload of a local sequence's originals and settings, unless one is already waiting or running.
public Task EnqueueUploadAsync(JobEngine engine, string server, Sequence local, CancellationToken cancellationToken = default) =>
EnqueueUploadAsync(engine, server, local, JobPriority.User, cancellationToken);
///
/// Queues the upload of a local sequence at (an integrated pair's new photos go in the
/// background, owner review 6, #73), unless one is already waiting or running.
///
public Task EnqueueUploadAsync(JobEngine engine, string server, Sequence local, JobPriority priority, CancellationToken cancellationToken = default) =>
EnqueueAsync(engine, JobKind.UploadCommit, local.Id, local.DisplayTitle, new SyncJobParameters(server), priority, cancellationToken);
///
/// Queues, in the background, the new photos of a pair integrated with automatic photos to its server sequence (owner
/// review 6, design §7.3): the job sends only into the sequence the pair names, and fails rather than create another
/// when that one is gone or the pair changed.
///
internal Task EnqueueAutomaticUploadAsync(JobEngine engine, string server, Sequence local, CancellationToken cancellationToken = default) =>
EnqueueAsync(engine, JobKind.UploadCommit, local.Id, local.DisplayTitle, new SyncJobParameters(server, Automatic: true), JobPriority.Background,
cancellationToken);
/// The other way of : the server's new photos into the pair's local sequence only.
internal Task EnqueueAutomaticDownloadAsync(JobEngine engine, string server, Guid remoteId, string title, Guid archiveId,
CancellationToken cancellationToken = default) =>
EnqueueAsync(engine, JobKind.Download, remoteId, title, new SyncJobParameters(server, SyncDownloadMode.Originals, archiveId, Automatic: true),
JobPriority.Background, cancellationToken);
///
/// Whether is an automatic transfer of an integrated pair's new photos
/// (, ): a metered connection pauses
/// those whatever the option says (owner review 6, Q6).
///
public static bool IsAutomaticTransfer(Job job)
{
ArgumentNullException.ThrowIfNull(job);
return SyncJobParameters.Read(job)?.IsAutomatic == true;
}
/// Queues sending the renders of a local copy the server lacks (BRIEF §14.5), unless that is already waiting or running.
public Task 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);
///
/// Queues a download of a server sequence, unless the same one is already waiting or running: originals into
/// (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.
///
public Task 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);
/// Handlers for and ; register them on the client's engine.
public IReadOnlyList CreateJobHandlers(ISyncConnector connector)
{
var transfers = new SyncTransfers(this);
return [new SyncJobHandler(JobKind.UploadCommit, transfers, connector), new SyncJobHandler(JobKind.Download, transfers, connector)];
}
/// A server sequence from the proxy cache, for the editor; null when its proxies were never fetched or were cleared.
public RemoteSequence? OpenRemote(string server, Guid remoteId) => Proxies.Load(server, remoteId);
/// The link of a local sequence to a sequence of ; null when the server does not have it.
public Task LinkOfAsync(string server, Guid localId, CancellationToken cancellationToken = default) =>
_links.FindByLocalAsync(server, localId, cancellationToken);
// ---------------- Engine ----------------
/// Server ids of the sequences an upload or download job is working on.
internal async Task> 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();
}
/// Creates or updates the link of a local sequence to a server sequence (an upload or download made it).
internal async Task LinkAsync(string server, Guid remoteId, Sequence local, CancellationToken cancellationToken)
{
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);
await Copies.EnsureLinkedAsync(server, remoteId, local.Id, cancellationToken).ConfigureAwait(false);
return link;
}
finally
{
_gate.Release();
}
}
///
/// Links a pair detection found ( said Link), under the gate: only while the pair is still a
/// Candidate (a Keep apart answered meanwhile wins) and neither side got a link to this server since. The pair is moved to
/// Linked first (compare-and-set), then the link is made and compared as a new one; a failure moves the pair back.
///
internal async Task AutoLinkAsync(ISyncRemote remote, SyncPolicy policy, FoundCopy copy, SequenceDto dto, Sequence local,
Dictionary? locals, CancellationToken cancellationToken)
{
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
if (await Copies.GetAsync(copy.Id, cancellationToken).ConfigureAwait(false) is not { State: CopyState.Candidate }) return false;
var link = await _links.GetAsync(remote.Server, dto.Id, cancellationToken).ConfigureAwait(false);
if (link?.LocalId is not null || await _links.FindByLocalAsync(remote.Server, local.Id, cancellationToken).ConfigureAwait(false) is not null)
return false;
if (!await Copies.SetStateAsync(copy.Id, CopyState.Candidate, CopyState.Linked, null, cancellationToken).ConfigureAwait(false)) return false;
try
{
var linked = Unlinked(Observe(link, remote.Server, dto)) with { LocalId = local.Id };
await ReconcileSafelyAsync(remote, linked, dto, local, locals, policy, cancellationToken).ConfigureAwait(false);
await Copies.EnsureLinkedAsync(remote.Server, dto.Id, local.Id, cancellationToken).ConfigureAwait(false);
}
catch
{
await Copies.SetStateAsync(copy.Id, CopyState.Linked, CopyState.Candidate, null, CancellationToken.None).ConfigureAwait(false);
throw;
}
return true;
}
finally
{
_gate.Release();
}
}
/// Forgets a link whose server sequence an upload found deleted (its originals go into a new one).
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, null, cancellationToken).ConfigureAwait(false);
}
finally
{
_gate.Release();
}
}
///
/// Makes the server's copy equal to this PC's (an upload sends the settings with the originals of the sequence it
/// created); the server's own processing may edit the new sequence meanwhile, so a refused edit is sent again.
///
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);
for (var attempt = 1; ; attempt++)
{
var manifest = await remote.GetManifestAsync(remoteId, cancellationToken).ConfigureAwait(false);
try
{
if (await RequestAsync(remote, local, manifest, manifest.SettingsVersion, cancellationToken).ConfigureAwait(false) is not { } request)
{
// An edit saved here meanwhile goes instead; frames that keep changing here leave it to the next comparison.
if (attempt >= 3 || await _db.Sequences.GetAsync(local.Id, cancellationToken).ConfigureAwait(false) is not { } fresh) return;
local = fresh;
continue;
}
var updated = await remote.UpdateSequenceAsync(remoteId, request, cancellationToken).ConfigureAwait(false);
await _links.UpsertAsync(Agreed(Observe(link, remote.Server, updated), local.SettingsVersion, updated.SettingsVersion), cancellationToken)
.ConfigureAwait(false);
return;
}
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.Conflict && attempt < 3)
{
Log.Info(LogCategory, $"{local.DisplayTitle} changed on the server while its settings were sent; sending again");
}
}
}
finally
{
_gate.Release();
}
}
/// Makes this PC's copy equal to the server's (a sequence a download just created takes the server's settings).
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);
// Edited on this PC meanwhile: nothing is agreed yet, so the next comparison settles both sides' content.
if (await ApplyLocallyAsync(local, SyncPayload.Of(dto, manifest.SettingsJson), Positions(remote, local, manifest), cancellationToken)
.ConfigureAwait(false) is not { } applied) return;
await _links.UpsertAsync(Agreed(Observe(link, remote.Server, dto), applied.SettingsVersion, manifest.SettingsVersion), cancellationToken)
.ConfigureAwait(false);
}
finally
{
_gate.Release();
}
}
///
/// Writes the details an Integrate agreed (design §5c step 5) to both copies of a linked pair, the server first, by
/// content: is the one payload in portable form, and
/// each side's portable payload when the plan was made. A one-sided server change since
/// the plan (its own analysis of photos just filed) is absorbed: the final payload takes the server's fresh value at those
/// paths, on both sides. Any local change since the plan, a server that keeps changing (three refused edits) or a local
/// write refused under the lease throws (Errors.Copies.DetailsChanged).
/// A side already holding the final payload is not written again (a resumed job).
///
/// Both copies as they are once agreed.
internal async Task<(Sequence Local, SequenceDto Remote)> ApplyAgreedAsync(ISyncRemote remote, Guid remoteId, SyncPayload finalPortable,
SyncPayload plannedLocal, SyncPayload plannedRemote, int expectedLocalSettings, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(finalPortable);
ArgumentNullException.ThrowIfNull(plannedLocal);
ArgumentNullException.ThrowIfNull(plannedRemote);
(Sequence, SequenceDto) result;
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
var (link, local) = await LinkedAsync(remote.Server, remoteId, cancellationToken).ConfigureAwait(false);
if (local.SettingsVersion != expectedLocalSettings) throw DetailsChanged();
var sides = new CopySides(_db);
for (var attempt = 1; ; attempt++)
{
var dto = await remote.GetSequenceAsync(remoteId, cancellationToken).ConfigureAwait(false);
var manifest = await remote.GetManifestAsync(remoteId, cancellationToken).ConfigureAwait(false);
if (manifest.SettingsVersion != dto.SettingsVersion)
{
// Changed between the two reads: read again.
if (attempt >= AgreeAttempts) throw DetailsChanged();
continue;
}
var here = await sides.LocalAsync(local.Id, cancellationToken).ConfigureAwait(false);
var captured = manifest.Frames.Any(f => f.Sha256.Length == 0) || here.Photos.Any(p => string.IsNullOrEmpty(p.Sha256))
? (await remote.ListFramesAsync(remoteId, cancellationToken).ConfigureAwait(false)).ToDictionary(f => f.Id, f => f.CapturedAt)
: null;
var there = CopyFinder.ServerSide(manifest, captured);
var tombstones = SyncTombstones.FromDtos(here.Removed, there.Removed);
var localPhotos = PhotosOf(here, tombstones);
var remotePhotos = PhotosOf(there, tombstones);
var freshLocal = CopyPayload.Portable(SyncPayload.Of(local), localPhotos);
if (!freshLocal.SameAs(finalPortable) && CopyPayload.Moved(plannedLocal, freshLocal).Count > 0) throw DetailsChanged();
var freshRemote = CopyPayload.Portable(SyncPayload.Of(dto, manifest.SettingsJson), remotePhotos);
var final = finalPortable;
var absorbed = CopyPayload.Moved(plannedRemote, freshRemote);
if (absorbed.Count > 0 && !freshRemote.SameAs(final))
{
final = CopyPayload.Merge(final, freshRemote, absorbed.ToDictionary(p => p, _ => CopySide.Other, StringComparer.Ordinal),
[.. absorbed.Select(p => new DetailLine(p, null, null))]);
}
// Placed on the server's frames as the manifest lists them; this copy's are placed from those under its lease.
var placed = final;
try
{
if (!string.IsNullOrWhiteSpace(final.SettingsJson))
placed = final with { SettingsJson = ProjectContent.Place(final.SettingsJson, remotePhotos) };
}
catch (JsonException)
{
// Settings that are not a project have no positions to place.
}
var updated = dto;
if (!freshRemote.SameAs(final))
{
if (ProjectContent.FormatOf(placed.SettingsJson) > await remote.SettingsFormatAsync(cancellationToken).ConfigureAwait(false))
throw new ServerFormatException(Loc.L("Tooltips.Server.NeedsNewerServer"));
var frames = ProjectSettings.NamesFrames(placed.SettingsJson) ? manifest.FramesVersion : (int?)null;
try
{
updated = await remote.UpdateSequenceAsync(remoteId, placed.ToRequest(dto.SettingsVersion, frames), cancellationToken).ConfigureAwait(false);
}
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.Conflict)
{
if (attempt >= AgreeAttempts) throw DetailsChanged();
Log.Info(LogCategory, $"{local.DisplayTitle} changed on the server while its agreed details were sent; checking again");
continue;
}
}
var applied = local;
if (!freshLocal.SameAs(final))
{
if (await ApplyLocallyAsync(local, placed, Positions(remote, local, manifest), cancellationToken).ConfigureAwait(false) is not { } written)
{
await _links.UpsertAsync(Observe(link, remote.Server, updated), cancellationToken).ConfigureAwait(false);
throw DetailsChanged();
}
applied = written;
}
await _links.UpsertAsync(Agreed(Observe(link, remote.Server, updated), applied.SettingsVersion, updated.SettingsVersion) with
{
SyncedAt = DateTimeOffset.UtcNow,
}, cancellationToken).ConfigureAwait(false);
Log.Info(LogCategory, $"Details of {local.DisplayTitle} agreed with {remote.Server}");
result = (applied, updated);
break;
}
}
finally
{
_gate.Release();
}
Changed?.Invoke(remote.Server);
return result;
static SyncConflictChangedException DetailsChanged() => new(Loc.L("Errors.Copies.DetailsChanged"));
}
private const int AgreeAttempts = 3;
/// A side's photos by frame index as the settings name them, the encodings both sides' conversions link read as one.
private static FramePhotos PhotosOf(CopySideInput side, SyncTombstones tombstones) =>
new(side.Photos.Select(p => (p.Index, tombstones.Canonical(new FramePhoto(p.Sha256, p.Size, p.CapturedAt)))));
///
/// 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.
///
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);
}
///
/// Records what the proxy cache holds for a server sequence. Stand-ins (: thumbnails, or
/// no file, in place of proxies a frame may still get) leave the cache stale, whether the server has the sequence's
/// proxies or not: its flag also offers the proxies of frames added since its last proxy pass, which it cannot serve
/// until that pass draws them. The cache is filled again once the server has those proxies.
///
internal async Task SetProxiesAsync(string server, SequenceDto dto, int cached, int standIns, 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);
int? filledAt = standIns > 0 ? null : framesVersion;
await _links.UpsertAsync(link with { ProxiesCached = cached, ProxiesFramesVersion = filledAt }, cancellationToken).ConfigureAwait(false);
}
finally
{
_gate.Release();
}
Changed?.Invoke(server);
}
/// The file of a local render: archive-relative for outputs inside the archive, absolute otherwise.
internal static string RenderFile(Archive archive, Render render) =>
Path.IsPathRooted(render.OutputPath) ? render.OutputPath : new ArchivePaths(archive.RootPath).FromRelative(render.OutputPath);
///
/// Compares one server sequence (under the gate): fetches it, forgets its link on a 404 (or adds it to
/// , when given, for the caller to forget), records a failure on its link.
/// (when given) receives the local copy as it stands after the comparison. True when the server
/// answered with the sequence.
///
private async Task CompareOneAsync(ISyncRemote remote, Guid remoteId, SyncLink? link, Dictionary? locals, SyncPolicy policy,
Guid? refreshId, CancellationToken cancellationToken, List? gone = null)
{
SequenceDto dto;
try
{
dto = await remote.GetSequenceAsync(remoteId, cancellationToken).ConfigureAwait(false);
}
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.NotFound)
{
if (link is null) return false;
if (gone is not null) gone.Add(link);
else await ForgetAsync(link, refreshId, cancellationToken).ConfigureAwait(false);
return false;
}
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 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);
return true;
}
///
/// Pairs one 404 marked (design §6.3): a remote listed again is cleared at once and asked about again; one still unlisted
/// is asked for once more, no sooner than after it was marked, and a second 404 there makes the
/// pair read "deleted on server". A refresh's first 404 forgot the link (the pair is asked about again); a job's 404
/// kept it (the pair stays Linked or Integrated).
///
private async Task AskGoneAgainAsync(ISyncRemote remote, IReadOnlyList listing, Guid refreshId, CancellationToken cancellationToken)
{
var listed = listing.Select(d => d.Id).ToHashSet();
var now = DateTimeOffset.UtcNow;
foreach (var pair in await Copies.ListByServerAsync(remote.Server, cancellationToken).ConfigureAwait(false))
{
if (pair is not { RemoteGoneHits: 1, RemoteId: { } remoteId }) continue;
if (listed.Contains(remoteId))
{
await BackAsync(pair, remoteId).ConfigureAwait(false);
continue;
}
if (pair.RemoteGoneAt is { } at && now - at < GoneRecheck) continue;
try
{
await remote.GetSequenceAsync(remoteId, cancellationToken).ConfigureAwait(false);
await BackAsync(pair, remoteId).ConfigureAwait(false);
}
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.NotFound)
{
if (ServerIdentity.IsIdKey(remote.Server))
await Copies.MarkRemoteGoneAsync(remote.Server, remoteId, pair.LocalId, refreshId, now, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (IsIsolated(ex, cancellationToken))
{
Log.Warning(LogCategory, $"Sequence {remoteId} could not be asked for again", ex);
}
}
async Task BackAsync(FoundCopy pair, Guid remoteId)
{
await Copies.ClearRemoteGoneAsync(remote.Server, remoteId, cancellationToken).ConfigureAwait(false);
if (pair.State is not (CopyState.Linked or CopyState.Integrated)) return;
// A 404 a job saw (a transfer, an Integrate) keeps the link: the pair stays as it was. A link the refresh's 404
// forgot joins nothing any more: the user is asked again.
var link = await _links.GetAsync(remote.Server, remoteId, cancellationToken).ConfigureAwait(false);
if (link?.LocalId == pair.LocalId) return;
await Copies.SetStateAsync(pair.Id, pair.State, CopyState.Candidate, null, cancellationToken).ConfigureAwait(false);
}
}
private async Task ReconcileSafelyAsync(ISyncRemote remote, SyncLink link, SequenceDto dto, Sequence? local, Dictionary? 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 (ChronosApiException 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 (IsIsolated(ex, cancellationToken))
{
// 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);
}
/// A failure that concerns one sequence; a lost session (401) or the caller's cancellation stops the whole comparison.
private static bool IsIsolated(Exception ex, CancellationToken cancellationToken) => ex switch
{
ChronosApiException api => api.Status != HttpStatusCode.Unauthorized,
OperationCanceledException => !cancellationToken.IsCancellationRequested,
_ => ex is HttpRequestException or JsonException or IOException or UnauthorizedAccessException or InvalidDataException or LeaseUnavailableException,
};
/// Compares originals and renders when either side's moved, then settles the settings; returns the updated link and local copy.
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), null);
}
SequenceManifest? manifest = null;
if (link.DiffLocalFrames != local.FramesVersion || link.DiffRemoteFrames != link.RemoteFramesVersion
|| link.DiffLocalRenders != local.RenderedCount || link.DiffRemoteRenders != link.RenderCount
|| (link.DiffRemoteUpdatedAt is { } compared && !SameMoment(compared, link.RemoteUpdatedAt)))
{
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 present = frames.Where(f => (f.Flags & FrameFlags.Missing) == 0).ToList();
// A frame either side has not hashed yet (a folder adopted, not verified) is told apart by size and capture time.
var captured = manifest.Frames.Any(f => f.Sha256.Length == 0) || present.Any(f => f.Sha256 is null)
? (await remote.ListFramesAsync(link.RemoteId, cancellationToken).ConfigureAwait(false)).ToDictionary(f => f.Id, f => f.CapturedAt)
: null;
// Photos either side removed are not offered back; one replaced by a converted file counts as its replacement (owner review 2, R6).
var tombstones = new SyncTombstones(await _db.FrameRemovals.ListBySequenceAsync(local.Id, cancellationToken).ConfigureAwait(false), manifest.Removed);
FramePhoto[] herePhotos = [.. present.Select(f => new FramePhoto(f.Sha256, f.Size, f.CapturedAt))];
FramePhoto[] therePhotos = [.. manifest.Frames.Select(f => new FramePhoto(f.Sha256, f.Size, captured?.GetValueOrDefault(f.Id)))];
var (missingRemote, missingLocal) = SyncRules.CompareOriginals(herePhotos, therePhotos, tombstones);
await ScoreLinkedAsync(link, local, manifest, captured, herePhotos, therePhotos, tombstones, cancellationToken).ConfigureAwait(false);
// Proxies the server asks for that this PC can make from its originals travel with an upload too (BRIEF §2.3).
var proxies = policy.CanEdit && manifest.Proxies is not null ? SyncRules.ProxiesToSend(manifest, present, Options.Archive.Decoder, captured, tombstones) : 0;
// Those change without the server's frame counters moving: while some may be made here, the server's next
// change of the sequence brings a new comparison.
var watch = policy.CanEdit && (proxies > 0 || SyncRules.MakesProxiesFor(present, Options.Archive.Decoder));
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,
DiffRemoteUpdatedAt = watch ? link.RemoteUpdatedAt : null,
MissingRemote = missingRemote + proxies,
MissingLocal = missingLocal,
};
}
(link, local) = await SettleSettingsAsync(remote, link, dto, local, manifest, policy, cancellationToken).ConfigureAwait(false);
return (link with { SyncedAt = DateTimeOffset.UtcNow }, local);
}
///
/// Keeps the deletion counts of a linked pair current at each comparison of its originals (design §6.2): photos one side
/// deleted that the other still holds. A pair scored never before (a plain link an upload or download made), or whose
/// photos moved on either side since its score, gets the whole detection score again, so a Keep apart after an Unlink is
/// measured against what the two hold when it is answered.
///
private async Task ScoreLinkedAsync(SyncLink link, Sequence local, SequenceManifest manifest, IReadOnlyDictionary? captured,
IReadOnlyCollection here, IReadOnlyCollection there, SyncTombstones tombstones, CancellationToken cancellationToken)
{
if (await Copies.FindRemoteAsync(local.Id, link.Server, link.RemoteId, cancellationToken).ConfigureAwait(false)
is not { State: CopyState.Linked or CopyState.Integrated } row) return;
CopyScore score;
if ((row.Score.LocalPhotos == 0 && row.Score.OtherPhotos == 0)
|| row.LocalFramesVersion != local.FramesVersion || row.OtherFramesVersion != manifest.FramesVersion)
{
var side = await new CopySides(_db).LocalAsync(local.Id, cancellationToken).ConfigureAwait(false);
score = CopyFinder.Detection(CopyComparer.Compare(side, CopyFinder.ServerSide(manifest, captured)).Score) with { Hints = row.Score.Hints };
}
else
{
var (deletedHere, deletedThere) = CopyComparer.Deletions(here, there, tombstones);
if (deletedHere == row.Score.DeletedHere && deletedThere == row.Score.DeletedThere) return;
score = row.Score with { DeletedHere = deletedHere, DeletedThere = deletedThere };
}
await Copies.UpdateScoreAsync(row.Id, score, local.FramesVersion, manifest.FramesVersion,
CopyRules.Fingerprint(score, local.FramesVersion, manifest.FramesVersion), cancellationToken).ConfigureAwait(false);
}
/// Renders each side lacks, by id (a render keeps its id on both sides); local renders whose file is gone cannot be sent.
private async Task CompareExportsAsync(SyncLink link, Sequence local, IReadOnlyList 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, local);
// Frames inserted here since the copy was listed moved its positions without a new settings version.
if (await _db.Sequences.GetAsync(local.Id, cancellationToken).ConfigureAwait(false) is { } current && current.SettingsVersion == local.SettingsVersion)
local = current;
if (localChanged && remoteChanged)
{
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);
// Compared (and shown) with its positions on this copy's frames, against this copy as it is at those frames: the
// same photos are the same settings. Edited here meanwhile, or frames that kept changing: compared next time.
if (await Positions(remote, local, manifest).ToLocalAsync(manifest.SettingsJson, local.SettingsVersion, cancellationToken).ConfigureAwait(false)
is not { } translated) return (link, local);
local = translated.Local;
var mine = SyncPayload.Of(local);
var theirs = SyncPayload.Of(dto, translated.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
{
ConflictLocalSettings = local.SettingsVersion,
ConflictRemoteSettings = manifest.SettingsVersion,
ConflictRemote = theirs with { SettingsJson = SyncRules.NormalizeSettings(theirs.SettingsJson) },
}, local);
}
if (!policy.AutoSyncSettings) return (link, local);
if (localChanged)
{
if (!policy.CanEdit) return (link, local);
manifest ??= await remote.GetManifestAsync(link.RemoteId, cancellationToken).ConfigureAwait(false);
return (await PushAsync(remote, link, local, manifest, link.BaseRemoteSettings, cancellationToken).ConfigureAwait(false), local);
}
manifest ??= await remote.GetManifestAsync(link.RemoteId, cancellationToken).ConfigureAwait(false);
if (manifest.SettingsVersion != dto.SettingsVersion) return (link, local);
if (await ApplyLocallyAsync(local, SyncPayload.Of(dto, manifest.SettingsJson), Positions(remote, local, manifest), cancellationToken)
.ConfigureAwait(false) is { } pulled)
return (Agreed(link, pulled.SettingsVersion, manifest.SettingsVersion), pulled);
// The local copy was read when the comparison began and an edit was saved on this PC since: both sides changed,
// so the server's version must not replace it unseen (BRIEF §14.5).
var fresh = await _db.Sequences.GetAsync(local.Id, cancellationToken).ConfigureAwait(false);
if (fresh is null || fresh.SettingsVersion == local.SettingsVersion) return (link, local);
return await SettleSettingsAsync(remote, link, dto, fresh, manifest, policy, cancellationToken).ConfigureAwait(false);
}
///
/// Sends this PC's payload unless the server moved past , which shows up as a conflict next,
/// or either copy's frames changed since they were read (the positions are translated again next time).
///
private async Task PushAsync(ISyncRemote remote, SyncLink link, Sequence local, SequenceManifest manifest, int? expected,
CancellationToken cancellationToken)
{
try
{
if (await RequestAsync(remote, local, manifest, expected, cancellationToken).ConfigureAwait(false) is not { } request) return link;
var updated = await remote.UpdateSequenceAsync(link.RemoteId, request, cancellationToken).ConfigureAwait(false);
return Agreed(Observe(link, link.Server, updated), local.SettingsVersion, updated.SettingsVersion);
}
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.Conflict)
{
return Observe(link, link.Server, await remote.GetSequenceAsync(link.RemoteId, cancellationToken).ConfigureAwait(false));
}
}
///
/// The PATCH that makes the server's copy equal to this copy at 's settings version (read again
/// with its frames, which may have moved its positions since), its frame positions moved to the server's frames as
/// lists them; the server refuses it when its frames changed since. Null when this copy
/// was edited since was read, or either copy's frames cannot be read as one state now.
///
private async Task RequestAsync(ISyncRemote remote, Sequence local, SequenceManifest manifest, int? expected,
CancellationToken cancellationToken)
{
var positions = Positions(remote, local, manifest);
if (await positions.ToServerAsync(local.SettingsVersion, cancellationToken).ConfigureAwait(false) is not { } translated) return null;
// Settings an older server cannot read (owner review 1, phase 4: a turn, a mirror, a look) stay here, the sync row
// saying why: the server would store them and then fail every render of them.
if (ProjectContent.FormatOf(translated.SettingsJson) > await remote.SettingsFormatAsync(cancellationToken).ConfigureAwait(false))
throw new ServerFormatException(Loc.L("Tooltips.Server.NeedsNewerServer"));
var frames = ProjectSettings.NamesFrames(translated.Local.SettingsJson) ? positions.ServerFrames : (int?)null;
return (SyncPayload.Of(translated.Local) with { SettingsJson = translated.SettingsJson }).ToRequest(expected, frames);
}
private SyncPositions Positions(ISyncRemote remote, Sequence local, SequenceManifest manifest) => new(_db, remote, local.Id, manifest);
/// The same instant as databases keep it (to the microsecond).
internal static bool SameMoment(DateTimeOffset a, DateTimeOffset b) => a.UtcTicks / 10 == b.UtcTicks / 10;
///
/// Writes the server's payload into the local index, project and sidecar in one step (settings version + 1) under the
/// sequence's lease, which the editor's saves and the archive's frame commits take too, and only while the local copy
/// is still at the settings version was read at. The settings' frame positions are moved to
/// this copy's frames as they are under the lease (). Null when an edit was saved on this
/// PC since, the frames of either copy could not be read as one state, or the copy is not in the folder this index has
/// (another index moved it): nothing is written then. A payload the local copy already holds writes nothing, so it
/// needs neither a writable archive nor the lease.
///
private async Task ApplyLocallyAsync(Sequence local, SyncPayload payload, SyncPositions positions, CancellationToken cancellationToken)
{
if (await positions.ToLocalAsync(payload.SettingsJson, local.SettingsVersion, cancellationToken).ConfigureAwait(false) is not { } stored) return null;
// Settled as it is: an archive that is offline or read-only does not keep the link from being agreed.
if ((payload with { SettingsJson = stored.SettingsJson }).SameAs(SyncPayload.Of(stored.Local))) return stored.Local;
var archive = await _db.Archives.GetAsync(local.ArchiveId, cancellationToken).ConfigureAwait(false)
?? throw new InvalidDataException($"Archive {local.ArchiveId} is not indexed.");
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
await using (await _writer.LockAsync(paths, local.Id, cancellationToken).ConfigureAwait(false))
{
// The frames cannot change under the lease: the positions are moved to them as they are now.
if (await positions.ToLocalAsync(payload.SettingsJson, local.SettingsVersion, cancellationToken).ConfigureAwait(false) is not { } current) return null;
var row = current.Local;
// The folder too: a Reorganize moves it and its row under this lease. One another index moved is found by the next
// scan; nothing is written until then, so the folder it left is not created again, nor written in when it holds
// another sequence now.
var folder = paths.Sequence(row.Folder);
if (!SequenceFolders.Holds(folder, row.Id)) return null;
payload = payload with { SettingsJson = current.SettingsJson };
var metadata = !payload.SameMetadata(SyncPayload.Of(row));
var settings = !SyncRules.SameSettings(payload.SettingsJson, row.SettingsJson);
if (!metadata && !settings) return row;
string? project = null;
Guid? hero = null;
if (settings)
{
var edited = ProjectStore.Parse(SyncRules.NormalizeSettings(payload.SettingsJson));
project = edited.ToJson();
hero = await HeroFrame.EditAsync(_db, row.Id, ProjectStore.Read(row, folder).HeroFrame, edited.HeroFrame, cancellationToken).ConfigureAwait(false);
}
var edit = new SequenceEdit
{
Title = metadata ? payload.Title?.Trim() ?? string.Empty : null,
Tags = metadata ? payload.Tags : null,
Rating = metadata ? payload.Rating : null,
Notes = metadata ? payload.Notes ?? string.Empty : null,
SettingsJson = project,
HeroFrameId = hero,
};
// The index first, at the version read under the lease: a writer that skips the lease still cannot be overwritten.
var result = await _db.Sequences.EditAsync(row.Id, edit, row.SettingsVersion, cancellationToken).ConfigureAwait(false);
if (result is not { Outcome: SequenceEditOutcome.Updated, Sequence: { } updated }) return null;
if (project is not null) AtomicFile.WriteAllText(folder.ProjectPath, project);
if (metadata)
{
var manifest = SequenceWriter.ReadLocked(folder, row.Id);
// Asked before the sidecar is written: frames or flags another process wrote there since this index last
// synced the folder keep it changed for the next scan (ArchiveIndexer.InStepAsync).
var inStep = await Archives.Indexer.InStepAsync(archive, folder, manifest, cancellationToken).ConfigureAwait(false);
ManifestStore.WriteSequence(folder.ManifestPath, manifest with
{
Title = updated.Title,
Tags = updated.Tags,
Rating = updated.Rating,
Notes = updated.Notes,
Versions = manifest.Versions with { Settings = Math.Max(manifest.Versions.Settings, updated.SettingsVersion) },
UpdatedAt = DateTimeOffset.UtcNow,
});
if (inStep) await Archives.Indexer.RecordStampsAsync(archive, folder, row.Id, cancellationToken).ConfigureAwait(false);
}
return updated;
}
}
///
/// "Save both": this PC's project is kept next to project.json as project.this-pc-<local time>.json
/// before the server's replaces it; returns that file. Written under the sequence's lease into its folder as the index
/// has it then: a Reorganize may have moved it while the server was asked, and the folder it left is never created again.
/// Null, with nothing written, when the sequence is not in that folder (another index moved it, and maybe another
/// sequence into it; the next scan finds them, ).
///
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 paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
string path;
await using (await _writer.LockAsync(paths, local.Id, cancellationToken).ConfigureAwait(false))
{
var folder = await SequenceWriter.FolderAsync(_db, paths, local, cancellationToken).ConfigureAwait(false);
if (!SequenceFolders.Holds(folder, local.Id)) return null;
Directory.CreateDirectory(folder.MetaDirectory);
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;
}
///
/// Whether the sequence is not in the folder the index has for it now, on an archive that is there: another index moved
/// it (and maybe another sequence into that folder), and this index's next scan finds it. Read without the lease, to
/// tell why a resolution wrote nothing.
///
private async Task FolderMovedAsync(Sequence local, CancellationToken cancellationToken)
{
if (await _db.Sequences.GetAsync(local.Id, cancellationToken).ConfigureAwait(false) is not { } row
|| await _db.Archives.GetAsync(row.ArchiveId, cancellationToken).ConfigureAwait(false) is not { } archive)
return false;
var paths = new ArchivePaths(archive.RootPath);
return Directory.Exists(paths.Root) && !SequenceFolders.Holds(paths.Sequence(row.Folder), row.Id);
}
///
/// Deletes a "Save both" copy of a version the user did not keep from the sequence's folder as the index has it now: a
/// Reorganize may have moved the folder, the copy with it, since the copy was written. Best effort: a copy that cannot
/// be reached (the folder gone or another sequence's now, the sequence busy, the archive offline) stays, as one more
/// copy of this PC's version.
///
private async Task DeleteCopyAsync(Sequence local, string saved, CancellationToken cancellationToken)
{
try
{
var archive = await _db.Archives.GetAsync(local.ArchiveId, cancellationToken).ConfigureAwait(false)
?? throw new InvalidDataException($"Archive {local.ArchiveId} is not indexed.");
var paths = new ArchivePaths(archive.RootPath);
await using (await _writer.LockAsync(paths, local.Id, cancellationToken).ConfigureAwait(false))
{
var folder = await SequenceWriter.FolderAsync(_db, paths, local, cancellationToken).ConfigureAwait(false);
if (SequenceFolders.Holds(folder, local.Id) && Directory.Exists(folder.MetaDirectory))
File.Delete(Path.Combine(folder.MetaDirectory, Path.GetFileName(saved)));
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
{
Log.Warning(LogCategory, $"The copy {saved} of {local.DisplayTitle}'s settings could not be deleted", ex);
}
}
/// The file name of a "Save both" copy kept at .
public static string SavedCopyName(DateTime localTime) =>
string.Create(CultureInfo.InvariantCulture, $"{SavedCopyPrefix}{localTime.ToString(SavedCopyTimeFormat, CultureInfo.InvariantCulture)}.json");
/// File name pattern of "Save both" copies in a sequence's .chronos folder.
public const string SavedCopyPattern = SavedCopyPrefix + "*.json";
private const string SavedCopyPrefix = "project.this-pc-";
private const string SavedCopyTimeFormat = "yyyyMMdd-HHmmss";
/// When a "Save both" copy was kept (local time, from its name); null for a name of another shape.
public static DateTime? SavedCopyTime(string fileName)
{
var name = Path.GetFileNameWithoutExtension(fileName);
return name.StartsWith(SavedCopyPrefix, StringComparison.Ordinal)
&& DateTime.TryParseExact(name[SavedCopyPrefix.Length..], SavedCopyTimeFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out var time)
? time
: null;
}
///
/// Forgets a link the server answered 404 for. With , on a server keyed by its id (an address
/// key may name another server tomorrow), the pair counts the 404 first ();
/// otherwise the pairs the link joined are settled (), never left Linked
/// with no link behind them.
///
private async Task ForgetAsync(SyncLink link, Guid? refreshId, CancellationToken cancellationToken)
{
if (refreshId is { } id && ServerIdentity.IsIdKey(link.Server))
await Copies.MarkRemoteGoneAsync(link.Server, link.RemoteId, link.LocalId, id, DateTimeOffset.UtcNow, cancellationToken).ConfigureAwait(false);
else if (link.LocalId is { } localId)
await Copies.SettleForgottenAsync(link.Server, link.RemoteId, localId, cancellationToken).ConfigureAwait(false);
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}");
}
/// Writes each local sequence's state for the Library and returns the table.
private async Task> StoreStatesAsync(string server, Dictionary? locals, CancellationToken cancellationToken)
{
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)
await _links.SetLocalStateAsync(local.Id, state, cancellationToken).ConfigureAwait(false);
}
return entries;
}
/// The table from the stored links and local sequences (read from the index when null).
private async Task> EntriesAsync(string server, Dictionary? known, CancellationToken cancellationToken)
{
var links = await _links.ListAsync(server, cancellationToken).ConfigureAwait(false);
var locals = known is null ? await LocalSequencesAsync(cancellationToken).ConfigureAwait(false) : new Dictionary(known);
var transfers = await _links.ActiveTransfersAsync(cancellationToken).ConfigureAwait(false);
var entries = new List(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)];
}
/// The transfer a row shows: the user's before background ones, originals before renders before proxies, running before waiting.
private static Job? Pick(IReadOnlyList? local, IReadOnlyList? 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();
/// The local copy of a link: from , or the index when the paged listing missed it.
private async Task LocalOfAsync(SyncLink? link, Dictionary? 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);
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> LocalSequencesAsync(CancellationToken cancellationToken)
{
var all = new Dictionary();
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 EnqueueAsync(JobEngine engine, JobKind kind, Guid target, string label, SyncJobParameters parameters, JobPriority priority,
CancellationToken cancellationToken)
{
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;
// An automatic transfer never creates a sequence: it does not stand for the user's own.
var narrower = SyncJobParameters.Read(job)?.IsAutomatic == true && !parameters.IsAutomatic;
if (running == wanted && !outranked && !narrower) 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);
}
/// The link with the server's side as lists it (a new link when there was none).
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,
ConflictRemote = null,
};
private static SyncLink Unlinked(SyncLink link) => link with
{
LocalId = null,
BaseLocalSettings = null,
BaseRemoteSettings = null,
DiffLocalFrames = null,
DiffRemoteFrames = null,
DiffLocalRenders = null,
DiffRemoteRenders = null,
DiffRemoteUpdatedAt = null,
MissingRemote = 0,
MissingLocal = 0,
ExportsToGet = 0,
ExportsToGetBytes = 0,
ExportsToSend = 0,
ExportsToSendBytes = 0,
ConflictLocalSettings = null,
ConflictRemoteSettings = null,
ConflictRemote = null,
};
}