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

+78 -1
View File
@@ -22,10 +22,13 @@ using Chronos.Core.Windows.MediaFoundation;
using Chronos.Core.Windows.Wic;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Copies;
using Chronos.Data.Homes;
using Chronos.Data.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Projects;
using Chronos.Data.Scheduling;
using Chronos.Data.Sync;
using Chronos.Data.Workspaces;
using Chronos.Protocol.Client;
@@ -64,6 +67,8 @@ public sealed class AppServices : IAsyncDisposable
private WicDecoderProvider? _wic;
private readonly RenderNodeHost _renderNode;
private ServerSession _server = null!;
private CopyEngine? _copies;
private CopyWatch? _copyWatch;
public AppServices(AppEnvironment environment, AppSettings settings, Action saveSettings, IAppDialogs dialogs)
{
@@ -205,8 +210,68 @@ public sealed class AppServices : IAsyncDisposable
.. services.Database is { } db && services.Archives is { } archives
? WorkspaceJobs.CreateHandlers(db, archives, services.Sync, WorkspaceOptions(services, archives))
: [],
.. CopyHandlers(services),
];
/// <summary>
/// The matches' jobs (owner review 6, #73): the integration of a pair with a server sequence, over the signed-in session,
/// and the merge of two local sequences, which waits for workspace work not sent home.
/// </summary>
private static IReadOnlyList<IJobHandler> CopyHandlers(AppServices services)
{
if (services.Database is not { } db || services.Archives is not { } archives || services.Sync.Service is not { } sync) return [];
return
[
CopyJobs.CreateIntegrateHandler(sync, archives, services.Sync, sync.Copies),
SequenceMerger.CreateHandler(db, new SequenceMerger(db, archives, new CopySides(db)), archives, new ProjectTransplant(),
new WorkspaceCopyGuard(services.Workspace)),
];
}
/// <summary>
/// The matches engine over the open index (owner review 6, #73): the planners, the workspace guard of merges, the
/// signed-in server's comparisons through its agent, and the names the servers are known by here.
/// </summary>
private CopyEngine CreateCopyEngine(ChronosDatabase database, ArchiveService archives, SyncService sync)
{
var sides = new CopySides(database);
var homes = CopyJobs.ServerHomes(Sync);
return new CopyEngine(sync, archives, new IntegratePlanner(sync, sides, archives.Projects, homes), new SequenceMerger(database, archives, sides),
new CopyReviewBuilder(database, archives.Projects, sides, homes), CopyContext, new WorkspaceCopyGuard(Workspace),
refresh: async (remote, ct) =>
{
// The signed-in server compares through its agent, one comparison at a time; another (a job's session) directly.
if (Sync.Agent is { } agent && string.Equals(agent.Server, remote.Server, StringComparison.Ordinal)) await agent.RefreshAsync(ct).ConfigureAwait(false);
else await sync.RefreshAsync(remote, Sync.Policy, ct).ConfigureAwait(false);
},
serverNames: ServerNameOf,
followUps: () => Engine,
workspaceProjects: async ct => Workspace.IsAvailable
? [.. (await Workspace.ListAsync(ct).ConfigureAwait(false)).Where(e => e.IsReadable).Select(e => (e.Home, e.Name))]
: []);
}
/// <summary>
/// What the planners know of this PC and the signed-in account. The account's rights stand for its rights over the
/// server's sequence: the server enforces ownership itself, so OwnsOrAdmin reads Delete or an admin right.
/// </summary>
private CopyPlanContext CopyContext(ISyncRemote? remote)
{
var user = remote is not null ? Server.User : null;
var permissions = user?.Permissions ?? 0;
var rights = SyncRights.Of(permissions);
bool Has(Permissions p) => (permissions & (long)p) != 0;
var originals = Settings.KnownServers.Select(k => k.OriginalsArchiveId).OfType<Guid>().ToHashSet();
return new CopyPlanContext(System.Environment.MachineName, remote is null ? null : Server.ServerName, rights.CanUpload, rights.CanFetchOriginals,
rights.CanEdit, Has(Permissions.Delete), Has(Permissions.Delete) || Has(Permissions.ManageArchive) || Has(Permissions.ManageUsers),
remote is not null && Sync.HasProjects, user is { QuotaBytes: > 0 } ? Math.Max(0, user.QuotaBytes - user.UsedBytes) : null, new HashSet<Guid>(),
originals);
}
/// <summary>The name a server key is shown by: the known server's name (by its id), else none (the key is shown).</summary>
private string? ServerNameOf(string key) =>
ServerIdentity.IdOf(Sync.Identity.Canonical(key)) is { } id && Settings.FindKnownServer(id) is { Name: { Length: > 0 } name } ? name : null;
/// <summary>
/// The workspace jobs' share of the desktop (phase 5c): its processing options for local renders, the metered hold of
/// Settings › Server over transfers with a server, the workspace that follows a moved folder, and the folder in use
@@ -342,7 +407,9 @@ public sealed class AppServices : IAsyncDisposable
_stopping.Dispose();
_server.PropertyChanged -= OnServerChanged;
await _renderNode.DisposeAsync().ConfigureAwait(false);
if (_copyWatch is not null) await _copyWatch.DisposeAsync().ConfigureAwait(false);
await Sync.DisposeAsync().ConfigureAwait(false);
_copies?.Dispose();
(Jobs as IDisposable)?.Dispose();
if (Engine is not null) await Engine.DisposeAsync().ConfigureAwait(false);
Thumbnails?.Dispose();
@@ -589,7 +656,10 @@ public sealed class AppServices : IAsyncDisposable
Archives.Videos.ProtectedFolders = () => [Workspace.Root, Share.Folder];
Archives.Videos.Servers = Sync;
Processing = new ProcessingService(database, ProcessingOptions(archive));
Sync.Open(database, Archives, archive);
var sync = Sync.Open(database, Archives, archive);
_copies = CreateCopyEngine(database, Archives, sync);
// Sample data puts its own engine in place in capture.
Sync.Copies = _copies;
var handlers = CreateJobHandlers(this);
var kinds = handlers.Select(h => h.Kind).Distinct().ToArray();
// One job at a time (owner review 1): the parallelism works inside it, the priority queue decides which runs.
@@ -603,6 +673,13 @@ public sealed class AppServices : IAsyncDisposable
var started = startEngine && handlers.Count > 0;
if (started) await Engine.StartAsync(ct);
Jobs = new EngineJobQueue(database, Engine, started);
// Two copies of a sequence among this PC's archives are looked for by themselves (owner review 6, #73).
if (!Environment.IsCapture)
{
var copies = _copies;
_copyWatch = new CopyWatch(ct => copies.FindLocalAsync(ct));
_copyWatch.Start(Engine);
}
Log.Info("jobs", started ? $"Job engine started for {string.Join(", ", kinds)}" : "No job handlers registered; jobs stay queued");
UpdateRenderNode();
}
+158
View File
@@ -0,0 +1,158 @@
using Chronos.Core.Diagnostics;
using Chronos.Core.Model;
using Chronos.Data.Jobs;
namespace Chronos.App.Server;
/// <summary>Timing of a <see cref="CopyWatch"/>.</summary>
public sealed record CopyWatchOptions
{
/// <summary>The first local detection runs this long after the index opened.</summary>
public TimeSpan StartDelay { get; init; } = TimeSpan.FromSeconds(30);
/// <summary>A detection runs this long after a job that changes the index's photos ended; more such jobs meanwhile wait for the same one.</summary>
public TimeSpan AfterJobDelay { get; init; } = TimeSpan.FromSeconds(10);
}
/// <summary>
/// Looks for two copies of a sequence among this index's archives by itself (owner review 6, #73; design §3.4): once a
/// while after the index opened, and a while after a job that changes photos (a scan, rebuild, verify, import, download,
/// conversion, merge, integration, or an emptied trash) ended, done, failed or cancelled. One detection at a time; the
/// requests that arrive while one runs give one more after it. What a detection finds is told by the matches engine.
/// </summary>
public sealed class CopyWatch : IAsyncDisposable
{
private readonly Func<CancellationToken, Task> _find;
private readonly CopyWatchOptions _options;
private readonly CancellationTokenSource _stopping = new();
private readonly Lock _lock = new();
private DateTimeOffset? _due;
private TaskCompletionSource _wake = NewWake();
private JobEngine? _engine;
private Task _running = Task.CompletedTask;
private int _runs;
/// <param name="find">One local detection (<see cref="Data.Copies.CopyEngine.FindLocalAsync"/>).</param>
public CopyWatch(Func<CancellationToken, Task> find, CopyWatchOptions? options = null)
{
_find = find ?? throw new ArgumentNullException(nameof(find));
_options = options ?? new CopyWatchOptions();
}
/// <summary>The kinds of job whose end asks for a detection.</summary>
internal static IReadOnlySet<JobKind> Triggers { get; } = new HashSet<JobKind>
{
JobKind.Scan, JobKind.Rebuild, JobKind.Verify, JobKind.Import, JobKind.Download, JobKind.Convert, JobKind.MergeSequences, JobKind.Integrate,
JobKind.EmptyTrash,
};
/// <summary>Detections that ended (for tests).</summary>
internal int Runs => Volatile.Read(ref _runs);
/// <summary>A detection ended, found something or not, or failed (any thread).</summary>
internal event Action? Ran;
/// <summary>Follows the jobs of <paramref name="engine"/> and runs the first detection after <see cref="CopyWatchOptions.StartDelay"/>.</summary>
public void Start(JobEngine? engine)
{
if (engine is not null)
{
_engine = engine;
engine.JobChanged += OnJobChanged;
}
_running = Task.Run(() => LoopAsync(_stopping.Token), CancellationToken.None);
Request(_options.StartDelay);
}
public async ValueTask DisposeAsync()
{
if (_engine is not null) _engine.JobChanged -= OnJobChanged;
await _stopping.CancelAsync().ConfigureAwait(false);
try
{
await _running.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
_stopping.Dispose();
}
/// <summary>A job that changes the index's photos ended: a detection follows after <see cref="CopyWatchOptions.AfterJobDelay"/>.</summary>
internal void OnJobChanged(Job job)
{
if (job is { State: JobState.Done or JobState.Failed or JobState.Cancelled } && Triggers.Contains(job.Kind)) Request(_options.AfterJobDelay);
}
/// <summary>A detection within <paramref name="delay"/>; one already due sooner stands.</summary>
internal void Request(TimeSpan delay)
{
lock (_lock)
{
var at = DateTimeOffset.UtcNow + delay;
if (_due is not { } due || at < due) _due = at;
_wake.TrySetResult();
}
}
private static TaskCompletionSource NewWake() => new(TaskCreationOptions.RunContinuationsAsynchronously);
private async Task LoopAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
Task wake;
TimeSpan? wait;
lock (_lock)
{
if (_wake.Task.IsCompleted) _wake = NewWake();
wake = _wake.Task;
wait = _due is { } due ? due - DateTimeOffset.UtcNow : null;
if (wait <= TimeSpan.Zero)
{
_due = null;
wait = TimeSpan.Zero;
}
}
if (wait is null)
{
await wake.WaitAsync(cancellationToken).ConfigureAwait(false);
continue;
}
if (wait > TimeSpan.Zero)
{
using var delay = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
await Task.WhenAny(wake, Task.Delay(wait.Value, delay.Token)).ConfigureAwait(false);
await delay.CancelAsync().ConfigureAwait(false);
continue;
}
await RunAsync(cancellationToken).ConfigureAwait(false);
}
}
private async Task RunAsync(CancellationToken cancellationToken)
{
try
{
await _find(cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
return;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// The next job that changes photos, or the next start, looks again.
Log.Warning("copies", "Looking for copies among the archives failed", ex);
}
Interlocked.Increment(ref _runs);
try
{
Ran?.Invoke();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("copies", "The end of a detection was not told", ex);
}
}
}
+6 -4
View File
@@ -12,7 +12,7 @@ namespace Chronos.App.Server;
/// "Pause metered transfers" (Server.html): while <see cref="AppSettings.PauseUploadsOnMetered"/> is on and Windows reports
/// the connection as metered, the transfers with a server are paused (a running one stops after its current chunk or file
/// and keeps its checkpoint): upload jobs, the sync's downloads, and since phase 5c the workspace's copies from a server and
/// its renders sent to one (<see cref="Holds"/>); a copy from or a send to this PC's archive is never held. They are resumed when the connection
/// its renders sent to one, and since owner review 6 the integration of a pair with a server sequence (<see cref="Holds"/>); a copy from or a send to this PC's archive is never held. They are resumed when the connection
/// is no longer metered or the option goes off. Only the jobs it paused are resumed. Checked when the network or one of
/// those jobs changes, and every minute.
/// </summary>
@@ -65,10 +65,12 @@ public sealed class UploadHold : IDisposable
}
/// <summary>The kinds of job a metered connection may hold (<see cref="Holds"/> says which of them).</summary>
internal static IReadOnlyList<JobKind> Kinds { get; } = [JobKind.UploadCommit, JobKind.Download, JobKind.WorkspaceCopy, JobKind.WorkspaceSend];
internal static IReadOnlyList<JobKind> Kinds { get; } = [JobKind.UploadCommit, JobKind.Download, JobKind.WorkspaceCopy, JobKind.WorkspaceSend,
JobKind.Integrate];
/// <summary>
/// Whether a metered connection holds <paramref name="job"/>: an upload, a sync download (every one is from a server), or a
/// Whether a metered connection holds <paramref name="job"/>: an upload, a sync download (every one is from a server), an
/// integration (it always moves photos with a server), or a
/// workspace copy or send whose home is a server (its parameters name one). One whose parameters cannot be read is not
/// held: it fails with its reason.
/// </summary>
@@ -77,7 +79,7 @@ public sealed class UploadHold : IDisposable
ArgumentNullException.ThrowIfNull(job);
return job.Kind switch
{
JobKind.UploadCommit or JobKind.Download => true,
JobKind.UploadCommit or JobKind.Download or JobKind.Integrate => true,
JobKind.WorkspaceCopy => WorkspaceJobs.CopyParameters(job)?.Server is { Length: > 0 },
JobKind.WorkspaceSend => WorkspaceJobs.SendParameters(job)?.Server is { Length: > 0 },
_ => false,
@@ -0,0 +1,15 @@
using Chronos.App.Workspace;
using Chronos.Data.Copies;
namespace Chronos.App.Server;
/// <summary>
/// What a merge of two local sequences asks the workspace (owner review 6, #73; design §6): whether a project of a sequence
/// holds work not sent home, which the sequence that goes would leave without a home. A merge waits for it.
/// </summary>
public sealed class WorkspaceCopyGuard(WorkspaceHost workspace) : IWorkspaceGuard
{
private readonly WorkspaceHost _workspace = workspace ?? throw new ArgumentNullException(nameof(workspace));
public Task<bool> HasUnsentAsync(Guid sequenceId, CancellationToken cancellationToken) => _workspace.HasUnsentWorkAsync(sequenceId, cancellationToken);
}
@@ -430,6 +430,34 @@ public sealed partial class WorkspaceHost
return [.. (await ListAsync(cancellationToken).ConfigureAwait(false)).Where(e => e.SequenceId == sequenceId)];
}
/// <summary>
/// Whether a workspace project whose home is <paramref name="sequenceId"/> in this PC's archive holds work not sent home
/// (owner review 6, #73: a merge that removes the sequence waits for it): versions not pushed, or changes not saved as a
/// version. While the workspace folder moves, or when a project's state cannot be read, the answer is yes (the safe
/// side); a workspace that is off holds none.
/// </summary>
public async Task<bool> HasUnsentWorkAsync(Guid sequenceId, CancellationToken cancellationToken = default)
{
if (!IsEnabled) return false;
try
{
EnsureNotMoving();
foreach (var entry in await ListAsync(cancellationToken).ConfigureAwait(false))
{
if (entry.SequenceId != sequenceId || !entry.Home.IsArchive) continue;
if (!entry.IsReadable) return true;
var status = await StatusAsync(entry.ProjectId, askHome: false, cancellationToken).ConfigureAwait(false);
if (status.Ahead > 0 || (status.Modified && !status.ReadOnly)) return true;
}
return false;
}
catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException)
{
Log.Info("workspace", $"Whether sequence {sequenceId} has workspace work not sent could not be read: {ex.Message}");
return true;
}
}
/// <summary>A workspace project by id (damaged or newer when this Chronos cannot read its working state); null when the workspace has none.</summary>
/// <exception cref="WorkspaceException">The workspace folder is being moved (<c>Errors.Workspace.Moving</c>).</exception>
public Task<WorkspaceEntry?> FindAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>