feat(copies): engine composition, automatic photos, metered hold and App wiring (owner review 6, P5)

CopyEngine puts the planners together behind ICopyEngine so the App can find,
compare, integrate, merge, link, unlink and keep pairs apart. It also moves
photos that one side deleted to the other side's trash. Each trash step
re-reads both sides when applied, and nothing moves if any photo was restored
since the dry run. The sync agent now queues the new photos of pairs that were
integrated with automatic photos, both ways, at background priority. Failures
back off, and three in a row are reported so the pair can show "not sent". On
a metered connection, integrations are held like other server transfers.
AppServices builds the engine and registers the Integrate and Merge handlers.
A CopyWatch looks for local copies after start and after jobs that change
photos. Merges wait for workspace work that has not been sent home.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-17 12:03:56 +01:00
1 parent 461dfcf4a3
commit 96b5b4078b
11 files changed
+1377 -8

No files matched your search

+104 -1
View File
@@ -3,6 +3,7 @@ using System.Text.Json;
using System.Threading.Channels;
using Chronos.Core.Diagnostics;
using Chronos.Core.Model;
using Chronos.Data.Copies;
using Chronos.Data.Jobs;
using Chronos.Protocol;
using Chronos.Protocol.Client;
@@ -24,13 +25,21 @@ public sealed record SyncAgentOptions
public TimeSpan MaxBackoff { get; init; } = TimeSpan.FromMinutes(5);
}
/// <summary>
/// The automatic photo transfers of an integrated pair that failed in a row (owner review 6, #73; design §7.3): how many,
/// and why the last one did.
/// </summary>
public sealed record AutoPhotoFailure(int Count, string Reason);
/// <summary>
/// Keeps the sync table of one signed-in server current in the background: a full comparison at start, on request
/// and every <see cref="SyncAgentOptions.RefreshInterval"/>; the sequences named by the server's <c>sequenceChanged</c>
/// events (WebSocket) compared again within a second, except those an upload or download is working on (it compares
/// them when it ends); failures retried with exponential backoff; and, with
/// <see cref="SyncPolicy.KeepProxiesOffline"/>, background downloads that bring stale proxy caches of the sequences
/// this PC opened with proxies up to date (a failed one waits with the same backoff). Dispose to stop.
/// this PC opened with proxies up to date (a failed one waits with the same backoff); and, for the pairs integrated with
/// automatic photos (owner review 6, #73), background transfers of the photos one side added since (a failed one waits
/// with the same backoff, and three in a row are told through <see cref="PhotosNotSent"/>). Dispose to stop.
/// </summary>
public sealed class SyncAgent : IAsyncDisposable
{
@@ -57,6 +66,14 @@ public sealed class SyncAgent : IAsyncDisposable
/// </summary>
private readonly Dictionary<Guid, DateTimeOffset> _standInsCompared = [];
/// <summary>Automatic photo transfers this agent queued, by local sequence and direction (true: upload).</summary>
private readonly Dictionary<(Guid Local, bool Upload), Guid> _photoJobs = [];
/// <summary>When the next automatic transfer of a local sequence whose last one failed may be queued.</summary>
private readonly Dictionary<Guid, DateTime> _photoNotBefore = [];
private readonly ConcurrentDictionary<Guid, AutoPhotoFailure> _photoFailures = new();
private readonly SemaphoreSlim _refreshing = new(1, 1);
private Task _running = Task.CompletedTask;
@@ -102,6 +119,15 @@ public sealed class SyncAgent : IAsyncDisposable
/// </summary>
public event Action<ProjectChangedEvent?>? ProjectChanged;
/// <summary>Failed automatic photo transfers in a row, by local sequence of an integrated pair; a finished one clears its entry.</summary>
public IReadOnlyDictionary<Guid, AutoPhotoFailure> PhotoFailures => _photoFailures;
/// <summary>The automatic photo transfers of a local sequence failed <see cref="NotSentAfter"/> times in a row (any thread).</summary>
public event Action<Guid, AutoPhotoFailure>? PhotosNotSent;
/// <summary>Failed automatic transfers in a row after which a pair reads "not sent".</summary>
public const int NotSentAfter = 3;
/// <summary>Starts the comparison and event loops.</summary>
public void Start()
{
@@ -130,6 +156,7 @@ public sealed class SyncAgent : IAsyncDisposable
Volatile.Write(ref _snapshot, snapshot);
Volatile.Write(ref _lastError, null);
if (policy.KeepProxiesOffline && _engine is not null) await QueueProxiesAsync(snapshot, linked.Token).ConfigureAwait(false);
if (_engine is not null) await QueuePhotosAsync(snapshot, linked.Token).ConfigureAwait(false);
Changed?.Invoke();
if (reopened && Interlocked.CompareExchange(ref _projectsMissed, InStep, Reopened) == Reopened) TellProjects(null);
return snapshot;
@@ -324,6 +351,82 @@ public sealed class SyncAgent : IAsyncDisposable
}
}
/// <summary>
/// Queues (background priority) the photos one side of a pair integrated with automatic photos added since: an upload
/// when the server lacks originals of the local copy, a download into the local copy's archive when this PC lacks the
/// server's. Never for a pair only linked, one integrated without automatic photos, or one whose server copy looks
/// deleted. A local sequence whose last automatic transfer failed waits for its backoff. What fails here is logged: the
/// comparison it follows stands.
/// </summary>
private async Task QueuePhotosAsync(SyncSnapshot snapshot, CancellationToken cancellationToken)
{
try
{
await CheckPhotoJobsAsync(cancellationToken).ConfigureAwait(false);
var pairs = (await _sync.Copies.ListByServerAsync(Server, cancellationToken).ConfigureAwait(false))
.Where(c => c is { Kind: CopyKind.LocalServer, State: CopyState.Integrated, AutoPhotos: true, RemoteGoneHits: 0, RemoteId: not null })
.ToDictionary(c => c.LocalId, c => c.RemoteId!.Value);
if (pairs.Count == 0) return;
foreach (var entry in snapshot.Entries)
{
if (entry is not { Local: { } local, Link: { } link, Transfer: null }) continue;
if (!pairs.TryGetValue(local.Id, out var remoteId) || remoteId != link.RemoteId) continue;
if (_photoNotBefore.TryGetValue(local.Id, out var notBefore) && DateTime.UtcNow < notBefore) continue;
if (link.MissingRemote > 0 && !_photoJobs.ContainsKey((local.Id, true)))
{
var job = await _sync.EnqueueUploadAsync(_engine!, Server, local, JobPriority.Background, cancellationToken).ConfigureAwait(false);
_photoJobs[(local.Id, true)] = job.Id;
}
if (link.MissingLocal > 0 && !_photoJobs.ContainsKey((local.Id, false)))
{
var job = await _sync.EnqueueDownloadAsync(_engine!, Server, link.RemoteId, link.Title, SyncDownloadMode.Originals, local.ArchiveId,
JobPriority.Background, cancellationToken).ConfigureAwait(false);
_photoJobs[(local.Id, false)] = job.Id;
}
}
}
catch (Exception ex) when (!cancellationToken.IsCancellationRequested && ex is not OutOfMemoryException)
{
Log.Warning(LogCategory, $"New photos of integrated pairs on {Server} were not queued", ex);
}
}
/// <summary>Settles the automatic transfers that ended: a failed one counts and backs off, a finished one clears the count.</summary>
private async Task CheckPhotoJobsAsync(CancellationToken cancellationToken)
{
foreach (var (key, jobId) in _photoJobs.ToList())
{
var job = await _sync.Database.Jobs.GetAsync(jobId, cancellationToken).ConfigureAwait(false);
if (job?.State is JobState.Queued or JobState.Running or JobState.Paused) continue;
_photoJobs.Remove(key);
if (job?.State == JobState.Failed)
{
var failure = _photoFailures.AddOrUpdate(key.Local, _ => new AutoPhotoFailure(1, job.Error ?? string.Empty),
(_, last) => new AutoPhotoFailure(last.Count + 1, job.Error ?? last.Reason));
_photoNotBefore[key.Local] = DateTime.UtcNow + Backoff(failure.Count);
Log.Info(LogCategory, $"Automatic photo transfer of sequence {key.Local} with {Server} failed ({failure.Count} in a row): {failure.Reason}");
if (failure.Count == NotSentAfter) TellNotSent(key.Local, failure);
}
else if (job?.State == JobState.Done)
{
_photoFailures.TryRemove(key.Local, out _);
_photoNotBefore.Remove(key.Local);
}
}
}
private void TellNotSent(Guid localId, AutoPhotoFailure failure)
{
try
{
PhotosNotSent?.Invoke(localId, failure);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning(LogCategory, $"Photos not sent to {Server} were not told", ex);
}
}
/// <summary>Whether the cache was compared with the server's sequence, or its download queued, at the sequence's current update time.</summary>
private bool ComparedNow(SyncLink link) =>
_standInsCompared.TryGetValue(link.RemoteId, out var compared) && SyncService.SameMoment(compared, link.RemoteUpdatedAt);