feat(copies): detection and sync integration (owner review 6, P1b)
A refresh no longer links copies by content behind the user's back. After the gate is released, CopyFinder looks for copies whose ids differ: the server's photo lookup (or 1.1's gate and the hints on an older server), session keys, and an exact comparison by manifest, bounded per refresh and remembered in copy_probes so nothing is compared twice while neither side moves. What a pair becomes is the Link matches setting's call: asked by default, linked by itself only as the setting allows, through a compare-and-set that a Keep apart wins. Local detection finds copies inside this PC's archives and never links them. SyncService gives every link its pair, adds Unlink (kept apart, observation kept), marks pairs whose server sequence answers 404 (once per refresh, twice reads deleted, never on an address key or in a 404 sweep), keeps deletion counts current at each comparison, writes an Integrate's agreed details to both sides by content (ApplyAgreedAsync) and queues uploads at a given priority. CopyReviewBuilder assembles what the Compare dialog shows. Refs #73 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9912baf78a
commit
ade908cb6d
11 files changed
+2035
-89
No files matched your search
@@ -1,4 +1,3 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
@@ -10,6 +9,7 @@ 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;
|
||||
@@ -61,8 +61,9 @@ public sealed record SyncOptions
|
||||
/// downloaded originals are verified and committed through the archive ingest, so sidecars stay right; proxies go to a
|
||||
/// cache and open as a <see cref="RemoteSequence"/>; renders travel on request. 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. A local copy and a server sequence holding the same originals are linked by content when no link joins
|
||||
/// them. The state of each local sequence is written to its <c>sync_state</c> for the Library. A failure while
|
||||
/// server lacks. Copies whose ids differ are found after each full refresh (<see cref="Finder"/>) and linked by themselves
|
||||
/// only as <see cref="SyncPolicy.Linking"/> allows; every link has a pair in <see cref="Copies"/> (owner review 6, #73).
|
||||
/// The state of each local sequence is written to its <c>sync_state</c> for the Library. A failure while
|
||||
/// comparing one sequence is recorded on its link and does not stop the others.
|
||||
/// </summary>
|
||||
public sealed class SyncService
|
||||
@@ -70,6 +71,12 @@ public sealed class SyncService
|
||||
private const string LogCategory = "sync";
|
||||
private const string SessionKeyPrefix = "chronos-sync:";
|
||||
|
||||
/// <summary>Linked sequences answering 404 in one refresh, none answering, that read as a server serving something else (design §6.3).</summary>
|
||||
private const int SweepLinks = 5;
|
||||
|
||||
/// <summary>How long a pair marked gone once waits before its remote is asked for again (design §6.3).</summary>
|
||||
private static readonly TimeSpan GoneRecheck = TimeSpan.FromMinutes(10);
|
||||
|
||||
/// <summary>Recomputes states without sending or taking settings on the user's behalf.</summary>
|
||||
internal static readonly SyncPolicy CompareOnly = new(AutoSyncSettings: false);
|
||||
|
||||
@@ -78,9 +85,6 @@ public sealed class SyncService
|
||||
private readonly SequenceWriter _writer;
|
||||
private readonly SemaphoreSlim _gate = new(1, 1);
|
||||
|
||||
/// <summary>Unlinked pairs whose manifests were compared at these frame versions without a match (not fetched again).</summary>
|
||||
private readonly ConcurrentDictionary<string, byte> _unmatched = new(StringComparer.Ordinal);
|
||||
|
||||
public SyncService(ChronosDatabase db, ArchiveService archives, SyncOptions options)
|
||||
{
|
||||
_db = db;
|
||||
@@ -89,13 +93,24 @@ public sealed class SyncService
|
||||
_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; }
|
||||
|
||||
/// <summary>The pairs of copies of one time-lapse (owner review 6, #73): every link has one, and detection adds the others.</summary>
|
||||
public FoundCopyStore Copies { get; }
|
||||
|
||||
/// <summary>Detection of the copies whose ids differ (owner review 6, #73), run at the end of every full refresh.</summary>
|
||||
public CopyFinder Finder { 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;
|
||||
|
||||
/// <summary>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.</summary>
|
||||
public event Action<string, CopyFindResult>? CopiesFound;
|
||||
|
||||
internal ProxyCache Proxies { get; }
|
||||
|
||||
internal SyncLinkStore Links => _links;
|
||||
@@ -135,48 +150,76 @@ public sealed class SyncService
|
||||
|
||||
/// <summary>
|
||||
/// Lists the server, compares every sequence with its local copy, sends or takes settings changed on one side when
|
||||
/// <see cref="SyncPolicy.AutoSyncSettings"/> is on, forgets sequences the server confirms deleted, links unlinked
|
||||
/// copies holding the same originals, and stores the states.
|
||||
/// <see cref="SyncPolicy.AutoSyncSettings"/> 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
|
||||
/// (<see cref="CopyFinder.FindServerAsync"/>): linked by themselves only as <see cref="SyncPolicy.Linking"/> allows,
|
||||
/// asked otherwise (<see cref="CopiesFound"/>).
|
||||
/// </summary>
|
||||
public async Task<SyncSnapshot> RefreshAsync(ISyncRemote remote, SyncPolicy policy, CancellationToken cancellationToken)
|
||||
{
|
||||
var clock = Stopwatch.StartNew();
|
||||
var listing = await remote.ListSequencesAsync(cancellationToken).ConfigureAwait(false);
|
||||
var refreshId = Guid.NewGuid();
|
||||
Dictionary<Guid, Sequence> locals;
|
||||
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
var links = (await _links.ListAsync(remote.Server, cancellationToken).ConfigureAwait(false)).ToDictionary(l => l.RemoteId);
|
||||
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.
|
||||
foreach (var link in links.Values) await CompareOneAsync(remote, link.RemoteId, link, locals, policy, cancellationToken).ConfigureAwait(false);
|
||||
await MatchByContentAsync(remote, listing, locals, policy, cancellationToken).ConfigureAwait(false);
|
||||
var gone = new List<SyncLink>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
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, cancellationToken).ConfigureAwait(false);
|
||||
await CompareOneAsync(remote, id, link, null, policy, refreshId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
finally
|
||||
@@ -204,6 +247,32 @@ public sealed class SyncService
|
||||
await LinkAsync(server, remoteId, local, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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 ----------------
|
||||
|
||||
/// <summary>
|
||||
@@ -312,7 +381,14 @@ public sealed class SyncService
|
||||
|
||||
/// <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);
|
||||
EnqueueUploadAsync(engine, server, local, JobPriority.User, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Queues the upload of a local sequence at <paramref name="priority"/> (an integrated pair's new photos go in the
|
||||
/// background, owner review 6, #73), unless one is already waiting or running.
|
||||
/// </summary>
|
||||
public Task<Job> 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);
|
||||
|
||||
/// <summary>Queues sending the renders of a local copy the server lacks (BRIEF §14.5), unless that is already waiting or running.</summary>
|
||||
public Task<Job> EnqueueSendExportsAsync(JobEngine engine, string server, Sequence local, CancellationToken cancellationToken = default) =>
|
||||
@@ -363,6 +439,7 @@ public sealed class SyncService
|
||||
?? 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
|
||||
@@ -371,6 +448,41 @@ public sealed class SyncService
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Links a pair detection found (<see cref="CopyRules.Decide"/> 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.
|
||||
/// </summary>
|
||||
internal async Task<bool> AutoLinkAsync(ISyncRemote remote, SyncPolicy policy, FoundCopy copy, SequenceDto dto, Sequence local,
|
||||
Dictionary<Guid, Sequence>? 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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Forgets a link whose server sequence an upload found deleted (its originals go into a new one).</summary>
|
||||
internal async Task ForgetGoneAsync(string server, Guid remoteId, CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -378,7 +490,7 @@ public sealed class SyncService
|
||||
try
|
||||
{
|
||||
if (await _links.GetAsync(server, remoteId, cancellationToken).ConfigureAwait(false) is { } link)
|
||||
await ForgetAsync(link, cancellationToken).ConfigureAwait(false);
|
||||
await ForgetAsync(link, null, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -446,6 +558,123 @@ public sealed class SyncService
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the details an Integrate agreed (design §5c step 5) to both copies of a linked pair, the server first, by
|
||||
/// content: <paramref name="finalPortable"/> is the one payload in portable form, <paramref name="plannedLocal"/> and
|
||||
/// <paramref name="plannedRemote"/> 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 <see cref="SyncConflictChangedException"/> (<c>Errors.Copies.DetailsChanged</c>).
|
||||
/// A side already holding the final payload is not written again (a resumed job).
|
||||
/// </summary>
|
||||
/// <returns>Both copies as they are once agreed.</returns>
|
||||
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;
|
||||
|
||||
/// <summary>A side's photos by frame index as the settings name them, the encodings both sides' conversions link read as one.</summary>
|
||||
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)))));
|
||||
|
||||
/// <summary>
|
||||
/// Compares a sequence again after a transfer, originals and renders included even when no counter moved (a
|
||||
/// restored original or a hash given by verify changes no frame version), without sending or taking settings.
|
||||
@@ -492,11 +721,13 @@ public sealed class SyncService
|
||||
Path.IsPathRooted(render.OutputPath) ? render.OutputPath : new ArchivePaths(archive.RootPath).FromRelative(render.OutputPath);
|
||||
|
||||
/// <summary>
|
||||
/// Compares one server sequence (under the gate): fetches it, forgets its link on a 404, records a failure on its
|
||||
/// link. <paramref name="locals"/> (when given) receives the local copy as it stands after the comparison.
|
||||
/// Compares one server sequence (under the gate): fetches it, forgets its link on a 404 (or adds it to
|
||||
/// <paramref name="gone"/>, when given, for the caller to forget), records a failure on its link.
|
||||
/// <paramref name="locals"/> (when given) receives the local copy as it stands after the comparison. True when the server
|
||||
/// answered with the sequence.
|
||||
/// </summary>
|
||||
private async Task CompareOneAsync(ISyncRemote remote, Guid remoteId, SyncLink? link, Dictionary<Guid, Sequence>? locals, SyncPolicy policy,
|
||||
CancellationToken cancellationToken)
|
||||
private async Task<bool> CompareOneAsync(ISyncRemote remote, Guid remoteId, SyncLink? link, Dictionary<Guid, Sequence>? locals, SyncPolicy policy,
|
||||
Guid? refreshId, CancellationToken cancellationToken, List<SyncLink>? gone = null)
|
||||
{
|
||||
SequenceDto dto;
|
||||
try
|
||||
@@ -505,17 +736,63 @@ public sealed class SyncService
|
||||
}
|
||||
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.NotFound)
|
||||
{
|
||||
if (link is not null) await ForgetAsync(link, cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
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;
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="GoneRecheck"/> after it was marked, and a second 404 there makes the
|
||||
/// pair read "deleted on server". The links of those pairs are gone already (the first 404 forgot them).
|
||||
/// </summary>
|
||||
private async Task AskGoneAgainAsync(ISyncRemote remote, IReadOnlyList<SequenceDto> 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);
|
||||
// No link joins the two any more: the user is asked again.
|
||||
if (pair.State is CopyState.Linked or CopyState.Integrated)
|
||||
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<Guid, Sequence>? locals,
|
||||
@@ -575,8 +852,10 @@ public sealed class SyncService
|
||||
: 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);
|
||||
var (missingRemote, missingLocal) = SyncRules.CompareOriginals([.. present.Select(f => new FramePhoto(f.Sha256, f.Size, f.CapturedAt))],
|
||||
[.. manifest.Frames.Select(f => new FramePhoto(f.Sha256, f.Size, captured?.GetValueOrDefault(f.Id)))], tombstones);
|
||||
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
|
||||
@@ -598,6 +877,32 @@ public sealed class SyncService
|
||||
return (link with { SyncedAt = DateTimeOffset.UtcNow }, local);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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) gets the
|
||||
/// whole detection score once, so a Keep apart after an Unlink is measured against what the two held when it was answered.
|
||||
/// </summary>
|
||||
private async Task ScoreLinkedAsync(SyncLink link, Sequence local, SequenceManifest manifest, IReadOnlyDictionary<Guid, DateTime?>? captured,
|
||||
IReadOnlyCollection<FramePhoto> here, IReadOnlyCollection<FramePhoto> 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)
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Renders each side lacks, by id (a render keeps its id on both sides); local renders whose file is gone cannot be sent.</summary>
|
||||
private async Task<SyncLink> CompareExportsAsync(SyncLink link, Sequence local, IReadOnlyList<RenderDto> remoteRenders, CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -706,68 +1011,6 @@ public sealed class SyncService
|
||||
|
||||
private SyncPositions Positions(ISyncRemote remote, Sequence local, SequenceManifest manifest) => new(_db, remote, local.Id, manifest);
|
||||
|
||||
/// <summary>
|
||||
/// Links local copies and server sequences that hold the same originals but no link joins (an Uploader upload of
|
||||
/// the same card, a link lost with an old index): candidates start at the same second with the same camera, and
|
||||
/// at least half of the smaller side's originals must match by SHA-256. A pair that does not match is not fetched
|
||||
/// again until either side's frames change.
|
||||
/// </summary>
|
||||
private async Task MatchByContentAsync(ISyncRemote remote, IReadOnlyList<SequenceDto> listing, Dictionary<Guid, Sequence> locals, SyncPolicy policy,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var links = await _links.ListAsync(remote.Server, cancellationToken).ConfigureAwait(false);
|
||||
var linkedLocals = links.Where(l => l.LocalId is not null).Select(l => l.LocalId!.Value).ToHashSet();
|
||||
var linkedRemotes = links.Where(l => l.LocalId is not null).Select(l => l.RemoteId).ToHashSet();
|
||||
var candidates = listing.Where(d => !linkedRemotes.Contains(d.Id) && d.FrameCount > 0 && d.FirstCapture is not null)
|
||||
.ToLookup(d => Second(d.FirstCapture!.Value));
|
||||
foreach (var local in locals.Values.Where(l => !linkedLocals.Contains(l.Id) && l.FrameCount > 0 && l.FirstCapture is not null).ToList())
|
||||
{
|
||||
foreach (var dto in candidates[Second(local.FirstCapture!.Value)])
|
||||
{
|
||||
if (linkedRemotes.Contains(dto.Id) || !string.Equals(dto.CameraModel, local.CameraModel, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
var key = string.Create(CultureInfo.InvariantCulture, $"{local.Id:N}:{local.FramesVersion}:{dto.Id:N}:{dto.FramesVersion}");
|
||||
if (_unmatched.ContainsKey(key)) continue;
|
||||
try
|
||||
{
|
||||
if (!await SameOriginalsAsync(remote, local, dto, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
_unmatched[key] = 0;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (IsIsolated(ex, cancellationToken))
|
||||
{
|
||||
Log.Warning(LogCategory, $"{local.DisplayTitle} could not be matched with {dto.DisplayTitle}", ex);
|
||||
continue;
|
||||
}
|
||||
Log.Info(LogCategory, $"{local.DisplayTitle} holds the originals of {dto.DisplayTitle} on {remote.Server}: linked");
|
||||
var link = links.FirstOrDefault(l => l.RemoteId == dto.Id);
|
||||
var linked = Unlinked(Observe(link, remote.Server, dto)) with { LocalId = local.Id };
|
||||
await ReconcileSafelyAsync(remote, linked, dto, local, locals, policy, cancellationToken).ConfigureAwait(false);
|
||||
linkedRemotes.Add(dto.Id);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether at least half of the smaller side's originals are the other side's by content: a photo either side replaced by
|
||||
/// a converted file counts as its replacement (owner review 2, R7), as the comparison of linked pairs counts it, so a copy
|
||||
/// converted on one side before the two were linked is still found.
|
||||
/// </summary>
|
||||
private async Task<bool> SameOriginalsAsync(ISyncRemote remote, Sequence local, SequenceDto dto, CancellationToken cancellationToken)
|
||||
{
|
||||
var frames = await SequenceFrames.ListAsync(_db, local.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (!frames.Any(f => !string.IsNullOrEmpty(f.Sha256))) return false;
|
||||
var manifest = await remote.GetManifestAsync(dto.Id, cancellationToken).ConfigureAwait(false);
|
||||
var tombstones = new SyncTombstones(await _db.FrameRemovals.ListBySequenceAsync(local.Id, cancellationToken).ConfigureAwait(false), manifest.Removed);
|
||||
var hashes = frames.Where(f => !string.IsNullOrEmpty(f.Sha256)).Select(f => tombstones.Canonical(f.Sha256)!).ToHashSet(StringComparer.Ordinal);
|
||||
var shared = manifest.Frames.Where(f => f.Sha256.Length > 0).Select(f => tombstones.Canonical(f.Sha256)!).Distinct(StringComparer.Ordinal).Count(hashes.Contains);
|
||||
return shared > 0 && shared * 2 >= Math.Min(hashes.Count, manifest.Frames.Count);
|
||||
}
|
||||
|
||||
private static DateTime Second(DateTime time) => new(time.Ticks - time.Ticks % TimeSpan.TicksPerSecond, DateTimeKind.Unspecified);
|
||||
|
||||
/// <summary>The same instant as databases keep it (to the microsecond).</summary>
|
||||
internal static bool SameMoment(DateTimeOffset a, DateTimeOffset b) => a.UtcTicks / 10 == b.UtcTicks / 10;
|
||||
|
||||
@@ -933,8 +1176,14 @@ public sealed class SyncService
|
||||
: null;
|
||||
}
|
||||
|
||||
private async Task ForgetAsync(SyncLink link, CancellationToken cancellationToken)
|
||||
/// <summary>
|
||||
/// Forgets a link the server answered 404 for. With <paramref name="refreshId"/>, on a server keyed by its id (an address
|
||||
/// key may name another server tomorrow), the pair counts the 404 first (<see cref="FoundCopyStore.MarkRemoteGoneAsync"/>).
|
||||
/// </summary>
|
||||
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);
|
||||
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}");
|
||||
|
||||
Reference in new issue
Block a user