feat(sync): client sync engine with links, settings conflicts, transfers and background agent
Per-sequence state between the local index and a server from listings and manifest diffs; version-counter settings sync with explicit conflicts; upload, original and proxy download jobs; WebSocket-driven background agent. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
13 files changed
+1858
-2
No files matched your search
@@ -0,0 +1,330 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using Titano.Core.Archiving;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Archiving;
|
||||
using Titano.Data.Archiving.Jobs;
|
||||
using Titano.Data.Jobs;
|
||||
using Titano.Data.Processing;
|
||||
using Titano.Protocol;
|
||||
using Titano.Protocol.Client;
|
||||
using SequenceFrames = Titano.Data.Processing.SequenceFrames;
|
||||
|
||||
namespace Titano.Data.Sync;
|
||||
|
||||
/// <summary>
|
||||
/// The work of upload and download jobs. Uploads send every local original the server lacks through the chunked,
|
||||
/// resumable protocol after hashing it again (an original that no longer matches its archived hash is never sent),
|
||||
/// creating the server sequence first and sending its settings when the upload made it. Downloads fetch originals the
|
||||
/// local copy lacks into the archive's staging folder (resuming with Range), require the manifest's SHA-256 and commit
|
||||
/// them through the archive ingest, which names them and writes the sidecar; the first original creates the local
|
||||
/// sequence, which then takes the server's settings. Proxy downloads fill the proxy cache. A resumed job skips what
|
||||
/// is already on the other side, so pausing or a crash loses at most the files in flight.
|
||||
/// </summary>
|
||||
internal sealed class SyncTransfers(SyncService sync)
|
||||
{
|
||||
private const long SpaceReserve = 512L << 20;
|
||||
|
||||
/// <summary>Recomputes a sequence's state after a transfer without sending or taking settings on the user's behalf.</summary>
|
||||
private static readonly SyncPolicy CompareOnly = new(AutoSyncSettings: false);
|
||||
|
||||
public async Task UploadAsync(JobContext context, ISyncRemote remote, Guid localId)
|
||||
{
|
||||
var ct = context.Cancellation;
|
||||
var db = sync.Database;
|
||||
var local = await db.Sequences.GetAsync(localId, ct).ConfigureAwait(false) ?? throw new InvalidOperationException(Loc.L("Errors.Sync.LocalMissing"));
|
||||
var archive = await db.Archives.GetAsync(local.ArchiveId, ct).ConfigureAwait(false) ?? throw new InvalidOperationException(Loc.L("Errors.Sync.NoArchive"));
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
var (remoteId, created) = await TargetAsync(context, remote, local).ConfigureAwait(false);
|
||||
|
||||
var manifest = await remote.GetManifestAsync(remoteId, ct).ConfigureAwait(false);
|
||||
var present = manifest.Frames.Select(f => f.Sha256.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
|
||||
var frames = (await SequenceFrames.ListAsync(db, local.Id, ct).ConfigureAwait(false)).Where(f => (f.Flags & FrameFlags.Missing) == 0).ToList();
|
||||
var pending = frames.Where(f => f.Sha256 is null || !present.Contains(f.Sha256.ToLowerInvariant())).ToList();
|
||||
var progress = new TransferProgress(context, frames.Count, frames.Count - pending.Count);
|
||||
await progress.ReportAsync().ConfigureAwait(false);
|
||||
var skipped = 0;
|
||||
await Parallel.ForEachAsync(pending, Workers(sync.Options.Uploads, ct), async (frame, token) =>
|
||||
{
|
||||
if (!await UploadFrameAsync(context, remote, remoteId, paths.FromRelative(frame.RelativePath), frame, token).ConfigureAwait(false))
|
||||
Interlocked.Increment(ref skipped);
|
||||
await progress.StepAsync().ConfigureAwait(false);
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
if (created) await sync.PushAllAsync(remote, remoteId, ct).ConfigureAwait(false);
|
||||
await sync.RefreshSequencesAsync(remote, [remoteId], CompareOnly, ct).ConfigureAwait(false);
|
||||
if (skipped > 0) throw new InvalidDataException(Loc.Plural("Errors.Sync.Unreadable", skipped));
|
||||
}
|
||||
|
||||
public async Task DownloadOriginalsAsync(JobContext context, ISyncRemote remote, Guid remoteId, Guid? targetArchive)
|
||||
{
|
||||
var ct = context.Cancellation;
|
||||
var db = sync.Database;
|
||||
var link = await sync.Links.GetAsync(remote.Server, remoteId, ct).ConfigureAwait(false);
|
||||
var local = link?.LocalId is { } id ? await db.Sequences.GetAsync(id, ct).ConfigureAwait(false) : null;
|
||||
var archive = (local?.ArchiveId ?? targetArchive) is { } archiveId ? await db.Archives.GetAsync(archiveId, ct).ConfigureAwait(false) : null;
|
||||
if (archive is null) throw new InvalidOperationException(Loc.L("Errors.Sync.NoArchive"));
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
|
||||
var manifest = await remote.GetManifestAsync(remoteId, ct).ConfigureAwait(false);
|
||||
var captured = (await remote.ListFramesAsync(remoteId, ct).ConfigureAwait(false)).ToDictionary(f => f.Id, f => f.CapturedAt);
|
||||
IReadOnlySet<string> have = local is null
|
||||
? new HashSet<string>()
|
||||
: (await SequenceFrames.ListAsync(db, local.Id, ct).ConfigureAwait(false)).Select(f => f.Sha256).OfType<string>().ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var wanted = manifest.Frames.Where(f => !have.Contains(f.Sha256)).DistinctBy(f => f.Sha256.ToLowerInvariant()).ToList();
|
||||
EnsureSpace(paths.Root, wanted.Sum(f => f.Size));
|
||||
|
||||
var staging = Path.Combine(paths.StagingDirectory, "sync-" + remoteId.ToString("N"));
|
||||
Directory.CreateDirectory(staging);
|
||||
var progress = new TransferProgress(context, manifest.Frames.Count, manifest.Frames.Count - wanted.Count);
|
||||
await progress.ReportAsync().ConfigureAwait(false);
|
||||
var created = false;
|
||||
var rest = wanted;
|
||||
if (local is null && wanted.Count > 0)
|
||||
{
|
||||
// The first original creates the local sequence (grouped by the server id); the others join it.
|
||||
var first = await CommitAsync(remote, remoteId, archive.Id, null, wanted[0], staging, captured, ct).ConfigureAwait(false);
|
||||
local = await db.Sequences.GetAsync(first.SequenceId, ct).ConfigureAwait(false)
|
||||
?? throw new InvalidOperationException(Loc.L("Errors.Sync.LocalMissing"));
|
||||
await sync.LinkAsync(remote.Server, remoteId, local, ct).ConfigureAwait(false);
|
||||
await sync.Links.SetOriginAsync(local.Id, SequenceOrigin.Server, ct).ConfigureAwait(false);
|
||||
created = true;
|
||||
rest = wanted.GetRange(1, wanted.Count - 1);
|
||||
await progress.StepAsync().ConfigureAwait(false);
|
||||
}
|
||||
var sequenceId = local?.Id;
|
||||
await Parallel.ForEachAsync(rest, Workers(sync.Options.Downloads, ct), async (frame, token) =>
|
||||
{
|
||||
await CommitAsync(remote, remoteId, archive.Id, sequenceId, frame, staging, captured, token).ConfigureAwait(false);
|
||||
await progress.StepAsync().ConfigureAwait(false);
|
||||
}).ConfigureAwait(false);
|
||||
TryDeleteDirectory(staging);
|
||||
|
||||
if (created) await sync.TakeAllAsync(remote, remoteId, ct).ConfigureAwait(false);
|
||||
await sync.RefreshSequencesAsync(remote, [remoteId], CompareOnly, ct).ConfigureAwait(false);
|
||||
if (sequenceId is { } downloaded && wanted.Count > 0)
|
||||
{
|
||||
var label = local!.DisplayTitle;
|
||||
await EnqueueFollowUpAsync(ArchiveJobs.Thumbnails([downloaded], label), ct).ConfigureAwait(false);
|
||||
await EnqueueFollowUpAsync(ProcessingJobs.LightAnalysis([downloaded], label), ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task DownloadProxiesAsync(JobContext context, ISyncRemote remote, Guid remoteId)
|
||||
{
|
||||
var ct = context.Cancellation;
|
||||
var dto = await remote.GetSequenceAsync(remoteId, ct).ConfigureAwait(false);
|
||||
var manifest = await remote.GetManifestAsync(remoteId, ct).ConfigureAwait(false);
|
||||
var frames = await remote.ListFramesAsync(remoteId, ct).ConfigureAwait(false);
|
||||
var assets = manifest.Frames.ToDictionary(f => f.Id);
|
||||
var folder = sync.Proxies.Folder(remote.Server, remoteId);
|
||||
Directory.CreateDirectory(folder);
|
||||
ProxyCache.Prune(folder, frames.Select(f => ProxyCache.FileName(f.Id)).ToHashSet(StringComparer.Ordinal));
|
||||
|
||||
var files = new string?[frames.Count];
|
||||
var progress = new TransferProgress(context, frames.Count, 0);
|
||||
await progress.ReportAsync().ConfigureAwait(false);
|
||||
await Parallel.ForEachAsync(Enumerable.Range(0, frames.Count), Workers(sync.Options.Downloads, ct), async (i, token) =>
|
||||
{
|
||||
IReadOnlyList<string> kinds = assets.TryGetValue(frames[i].Id, out var asset) ? Kinds(asset) : [];
|
||||
files[i] = await FetchProxyAsync(remote, frames[i].Id, kinds, folder, token).ConfigureAwait(false);
|
||||
await progress.StepAsync().ConfigureAwait(false);
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
sync.Proxies.Save(remote.Server, remoteId, new ProxyCacheIndex(dto, manifest.SettingsJson, manifest.FramesVersion, frames, files));
|
||||
var cached = files.Count(f => f is not null);
|
||||
await sync.SetProxiesAsync(remote.Server, dto, cached, manifest.FramesVersion, ct).ConfigureAwait(false);
|
||||
if (cached < frames.Count) context.Log($"{frames.Count - cached} frame(s) have neither proxy nor thumbnail on the server");
|
||||
}
|
||||
|
||||
/// <summary>The server sequence an upload fills and whether this job created it: the linked one, one an interrupted attempt created, or a new one.</summary>
|
||||
private async Task<(Guid RemoteId, bool Created)> TargetAsync(JobContext context, ISyncRemote remote, Sequence local)
|
||||
{
|
||||
var ct = context.Cancellation;
|
||||
Guid? started = Guid.TryParse(context.Checkpoint, out var saved) ? saved : null;
|
||||
var link = await sync.Links.FindByLocalAsync(remote.Server, local.Id, ct).ConfigureAwait(false);
|
||||
foreach (var candidate in new[] { link?.RemoteId, started })
|
||||
{
|
||||
if (candidate is not { } id) continue;
|
||||
if (await ExistsAsync(remote, id, ct).ConfigureAwait(false))
|
||||
{
|
||||
if (link?.RemoteId != id) await sync.LinkAsync(remote.Server, id, local, ct).ConfigureAwait(false);
|
||||
return (id, id == started);
|
||||
}
|
||||
// Deleted on the server meanwhile: upload into a new sequence.
|
||||
if (id == link?.RemoteId) await sync.Links.DeleteAsync(remote.Server, id, ct).ConfigureAwait(false);
|
||||
}
|
||||
var dto = await remote.CreateSequenceAsync(new CreateSequenceRequest(local.Title, local.CameraModel), ct).ConfigureAwait(false);
|
||||
await context.CheckpointAsync(dto.Id.ToString(), 0, local.FrameCount).ConfigureAwait(false);
|
||||
await sync.LinkAsync(remote.Server, dto.Id, local, ct).ConfigureAwait(false);
|
||||
return (dto.Id, true);
|
||||
}
|
||||
|
||||
private static async Task<bool> ExistsAsync(ISyncRemote remote, Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await remote.GetSequenceAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Hashes the original again and sends it; false (logged) when it is gone or no longer the archived file.</summary>
|
||||
private static async Task<bool> UploadFrameAsync(JobContext context, ISyncRemote remote, Guid remoteId, string path, Frame frame, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
context.Log($"{frame.FileName}: missing, not uploaded");
|
||||
return false;
|
||||
}
|
||||
var sha = await TitanoClient.HashFileAsync(path, cancellationToken).ConfigureAwait(false);
|
||||
if (frame.Sha256 is { } archived && !archived.Equals(sha, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
context.Log($"{frame.FileName}: changed since it was archived, not uploaded");
|
||||
return false;
|
||||
}
|
||||
await remote.UploadFileAsync(path, remoteId, sha, frame.CapturedAt, cancellationToken).ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Downloads one original into staging and commits it into the local sequence (created from the server id when null).</summary>
|
||||
private async Task<IngestResult> CommitAsync(ISyncRemote remote, Guid remoteId, Guid archiveId, Guid? sequenceId, ManifestFrame frame, string staging,
|
||||
IReadOnlyDictionary<Guid, DateTime?> captured, CancellationToken cancellationToken)
|
||||
{
|
||||
var staged = await FetchOriginalAsync(remote, frame, staging, cancellationToken).ConfigureAwait(false);
|
||||
var request = new IngestRequest(archiveId, sequenceId, null, sequenceId is null ? SyncService.SessionKey(remoteId) : null, staged, frame.FileName,
|
||||
frame.Size, frame.Sha256.ToLowerInvariant(), captured.GetValueOrDefault(frame.Id), null);
|
||||
var result = await sync.Archives.Ingest.CommitAsync(request, cancellationToken).ConfigureAwait(false);
|
||||
// A duplicate stays in staging (the sequence already holds that content).
|
||||
if (result.Duplicate) File.Delete(staged);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>A verified copy in staging: resumed from a partial download, accepted only with the manifest's SHA-256 (two attempts).</summary>
|
||||
private static async Task<string> FetchOriginalAsync(ISyncRemote remote, ManifestFrame frame, string staging, CancellationToken cancellationToken)
|
||||
{
|
||||
var sha = frame.Sha256.ToLowerInvariant();
|
||||
if (sha.Length != 64 || !sha.All(char.IsAsciiHexDigitLower)) throw new InvalidDataException(Loc.L("Errors.Sync.Hash", frame.FileName));
|
||||
var target = Path.Combine(staging, sha + Path.GetExtension(frame.FileName).ToLowerInvariant());
|
||||
if (File.Exists(target)) return target;
|
||||
var part = target + ".part";
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
await using (var file = new FileStream(part, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
|
||||
await remote.DownloadFrameAsync(frame.Id, "original", file, cancellationToken).ConfigureAwait(false);
|
||||
if (await TitanoClient.HashFileAsync(part, cancellationToken).ConfigureAwait(false) == sha)
|
||||
{
|
||||
File.Move(part, target, overwrite: true);
|
||||
return target;
|
||||
}
|
||||
File.Delete(part);
|
||||
if (attempt == 2) throw new InvalidDataException(Loc.L("Errors.Sync.Hash", frame.FileName));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The cached proxy's file name, downloading the first asset kind the server has; null when it has none.</summary>
|
||||
private static async Task<string?> FetchProxyAsync(ISyncRemote remote, Guid frameId, IReadOnlyList<string> kinds, string folder, CancellationToken cancellationToken)
|
||||
{
|
||||
var name = ProxyCache.FileName(frameId);
|
||||
var path = Path.Combine(folder, name);
|
||||
if (new FileInfo(path) is { Exists: true, Length: > 0 }) return name;
|
||||
var part = path + ".part";
|
||||
foreach (var kind in kinds)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using (var file = new FileStream(part, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
|
||||
await remote.DownloadFrameAsync(frameId, kind, file, cancellationToken).ConfigureAwait(false);
|
||||
File.Move(part, path, overwrite: true);
|
||||
return name;
|
||||
}
|
||||
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound)
|
||||
{
|
||||
File.Delete(part);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string[] Kinds(ManifestFrame frame) => (frame.HasProxy, frame.HasThumb) switch
|
||||
{
|
||||
(true, true) => ["proxy", "thumb"],
|
||||
(true, false) => ["proxy"],
|
||||
(false, true) => ["thumb"],
|
||||
_ => [],
|
||||
};
|
||||
|
||||
/// <summary>Puts a follow-up job in the queue; the engine claims it on its next poll.</summary>
|
||||
private Task EnqueueFollowUpAsync(ArchiveJobRequest request, CancellationToken cancellationToken) =>
|
||||
sync.Database.Jobs.EnqueueAsync(new Job
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Kind = request.Kind,
|
||||
TargetIds = request.Targets,
|
||||
TargetLabel = request.Label,
|
||||
ParametersJson = request.ParametersJson,
|
||||
Priority = request.Priority,
|
||||
State = JobState.Queued,
|
||||
Created = DateTimeOffset.UtcNow,
|
||||
}, cancellationToken);
|
||||
|
||||
private static void EnsureSpace(string root, long bytes)
|
||||
{
|
||||
long? free;
|
||||
try
|
||||
{
|
||||
var full = Path.GetFullPath(root);
|
||||
// Windows wants a drive root; Unix accepts any directory and reports the volume it is mounted on.
|
||||
free = new DriveInfo(OperatingSystem.IsWindows() ? Path.GetPathRoot(full)! : full).AvailableFreeSpace;
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or IOException or UnauthorizedAccessException)
|
||||
{
|
||||
free = null; // network shares: the copy itself reports a full disk
|
||||
}
|
||||
if (free is { } available && available < bytes + SpaceReserve)
|
||||
throw new IOException(Loc.L("Errors.Sync.DiskFull", ((bytes + SpaceReserve - available) / 1e9).ToString("0.0", CultureInfo.CurrentCulture)));
|
||||
}
|
||||
|
||||
private static void TryDeleteDirectory(string folder)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.Delete(folder, recursive: true);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Core.Diagnostics.Log.Warning("sync", $"Staging folder {folder} could not be removed", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static ParallelOptions Workers(int degree, CancellationToken cancellationToken) =>
|
||||
new() { MaxDegreeOfParallelism = Math.Max(1, degree), CancellationToken = cancellationToken };
|
||||
|
||||
/// <summary>Files done out of the total, reported in order from parallel workers.</summary>
|
||||
private sealed class TransferProgress(JobContext context, long total, long done)
|
||||
{
|
||||
private readonly SemaphoreSlim _gate = new(1, 1);
|
||||
|
||||
public async Task StepAsync()
|
||||
{
|
||||
await _gate.WaitAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
done++;
|
||||
await context.ReportAsync(done, total).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public ValueTask ReportAsync() => context.ReportAsync(done, total);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user