From b79e4ed6d9e8991e61cd5c022c90328c5a494ba2 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 22:23:23 +0000 Subject: [PATCH 1/8] 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 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Model/Enums.cs | 3 + .../Migrations/postgres/0004_sync.sql | 30 + .../Migrations/sqlite/0004_sync.sql | 30 + .../Processing/RenderNodeClient.cs | 4 +- src/Titano.Data/Sync/ProxyCache.cs | 157 ++++++ src/Titano.Data/Sync/SyncAgent.cs | 245 ++++++++ src/Titano.Data/Sync/SyncJobHandler.cs | 46 ++ src/Titano.Data/Sync/SyncLinkStore.cs | 100 ++++ src/Titano.Data/Sync/SyncModel.cs | 132 +++++ src/Titano.Data/Sync/SyncRemote.cs | 109 ++++ src/Titano.Data/Sync/SyncRules.cs | 145 +++++ src/Titano.Data/Sync/SyncService.cs | 529 ++++++++++++++++++ src/Titano.Data/Sync/SyncTransfers.cs | 330 +++++++++++ 13 files changed, 1858 insertions(+), 2 deletions(-) create mode 100644 src/Titano.Data/Migrations/postgres/0004_sync.sql create mode 100644 src/Titano.Data/Migrations/sqlite/0004_sync.sql create mode 100644 src/Titano.Data/Sync/ProxyCache.cs create mode 100644 src/Titano.Data/Sync/SyncAgent.cs create mode 100644 src/Titano.Data/Sync/SyncJobHandler.cs create mode 100644 src/Titano.Data/Sync/SyncLinkStore.cs create mode 100644 src/Titano.Data/Sync/SyncModel.cs create mode 100644 src/Titano.Data/Sync/SyncRemote.cs create mode 100644 src/Titano.Data/Sync/SyncRules.cs create mode 100644 src/Titano.Data/Sync/SyncService.cs create mode 100644 src/Titano.Data/Sync/SyncTransfers.cs diff --git a/src/Titano.Core/Model/Enums.cs b/src/Titano.Core/Model/Enums.cs index 09627a48..2bb39f50 100644 --- a/src/Titano.Core/Model/Enums.cs +++ b/src/Titano.Core/Model/Enums.cs @@ -72,6 +72,9 @@ public enum JobKind Orphans, Adopt, Move, + + /// Client: originals or proxies of a server sequence fetched into this PC (BRIEF §14.5). + Download, } public enum JobState diff --git a/src/Titano.Data/Migrations/postgres/0004_sync.sql b/src/Titano.Data/Migrations/postgres/0004_sync.sql new file mode 100644 index 00000000..2acff6e6 --- /dev/null +++ b/src/Titano.Data/Migrations/postgres/0004_sync.sql @@ -0,0 +1,30 @@ +-- Client sync state (BRIEF §4.4, §14.5): one row per sequence of a server this client has listed, linked to the local +-- copy when there is one. Versions are the counters both sides agreed on at the last sync. Mirrors sqlite/0004_sync.sql. + +CREATE TABLE sync_links ( + server text COLLATE "C" NOT NULL, + remote_id uuid NOT NULL, + local_id uuid REFERENCES sequences (id) ON DELETE SET NULL, + title text NOT NULL, + frame_count integer NOT NULL DEFAULT 0, + total_bytes bigint NOT NULL DEFAULT 0, + render_count integer NOT NULL DEFAULT 0, + remote_status integer NOT NULL DEFAULT 0, + remote_settings_version integer NOT NULL DEFAULT 0, + remote_frames_version integer NOT NULL DEFAULT 0, + remote_updated_at timestamptz NOT NULL, + base_local_settings integer, + base_remote_settings integer, + diff_local_frames integer, + diff_remote_frames integer, + missing_remote integer NOT NULL DEFAULT 0, + missing_local integer NOT NULL DEFAULT 0, + conflict_local_settings integer, + conflict_remote_settings integer, + conflict_settings text, + proxies_cached integer NOT NULL DEFAULT 0, + proxies_frames_version integer, + synced_at timestamptz, + PRIMARY KEY (server, remote_id) +); +CREATE UNIQUE INDEX ix_sync_links_local ON sync_links (server, local_id); diff --git a/src/Titano.Data/Migrations/sqlite/0004_sync.sql b/src/Titano.Data/Migrations/sqlite/0004_sync.sql new file mode 100644 index 00000000..9e846d0d --- /dev/null +++ b/src/Titano.Data/Migrations/sqlite/0004_sync.sql @@ -0,0 +1,30 @@ +-- Client sync state (BRIEF §4.4, §14.5): one row per sequence of a server this client has listed, linked to the local +-- copy when there is one. Versions are the counters both sides agreed on at the last sync. Mirrors postgres/0004_sync.sql. + +CREATE TABLE sync_links ( + server TEXT NOT NULL, + remote_id TEXT NOT NULL, + local_id TEXT REFERENCES sequences (id) ON DELETE SET NULL, + title TEXT NOT NULL, + frame_count INTEGER NOT NULL DEFAULT 0, + total_bytes INTEGER NOT NULL DEFAULT 0, + render_count INTEGER NOT NULL DEFAULT 0, + remote_status INTEGER NOT NULL DEFAULT 0, + remote_settings_version INTEGER NOT NULL DEFAULT 0, + remote_frames_version INTEGER NOT NULL DEFAULT 0, + remote_updated_at TEXT NOT NULL, + base_local_settings INTEGER, + base_remote_settings INTEGER, + diff_local_frames INTEGER, + diff_remote_frames INTEGER, + missing_remote INTEGER NOT NULL DEFAULT 0, + missing_local INTEGER NOT NULL DEFAULT 0, + conflict_local_settings INTEGER, + conflict_remote_settings INTEGER, + conflict_settings TEXT, + proxies_cached INTEGER NOT NULL DEFAULT 0, + proxies_frames_version INTEGER, + synced_at TEXT, + PRIMARY KEY (server, remote_id) +); +CREATE UNIQUE INDEX ix_sync_links_local ON sync_links (server, local_id); diff --git a/src/Titano.Data/Processing/RenderNodeClient.cs b/src/Titano.Data/Processing/RenderNodeClient.cs index 8361caab..127ff847 100644 --- a/src/Titano.Data/Processing/RenderNodeClient.cs +++ b/src/Titano.Data/Processing/RenderNodeClient.cs @@ -368,7 +368,7 @@ public sealed class RenderNodeClient : IAsyncDisposable } } - private static Sequence ToSequence(SequenceDto s) => new() + internal static Sequence ToSequence(SequenceDto s) => new() { Id = s.Id, ArchiveId = Guid.Empty, @@ -382,7 +382,7 @@ public sealed class RenderNodeClient : IAsyncDisposable FrameCount = s.FrameCount, }; - private static Frame ToFrame(FrameDto f) => new() + internal static Frame ToFrame(FrameDto f) => new() { Id = f.Id, SequenceId = f.SequenceId, diff --git a/src/Titano.Data/Sync/ProxyCache.cs b/src/Titano.Data/Sync/ProxyCache.cs new file mode 100644 index 00000000..09c3de2d --- /dev/null +++ b/src/Titano.Data/Sync/ProxyCache.cs @@ -0,0 +1,157 @@ +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; +using Titano.Core.Diagnostics; +using Titano.Core.Imaging; +using Titano.Core.IO; +using Titano.Core.Model; +using Titano.Core.Render; +using Titano.Data.Processing; +using Titano.Protocol; + +namespace Titano.Data.Sync; + +/// +/// A server sequence opened with proxies (BRIEF §14.5 "edit with proxies, render where the originals are"): the +/// sequence and frame rows as the server lists them, and for each frame its cached proxy (a thumbnail when the server +/// had no proxy). Frames without a cached file are flagged , so analysis and renders +/// skip them. Not part of the local index. +/// +public sealed class RemoteSequence +{ + internal RemoteSequence(string server, Sequence sequence, IReadOnlyList frames, IReadOnlyList files) + { + Server = server; + Sequence = sequence; + Frames = frames; + Files = files; + } + + /// The server it belongs to (). + public string Server { get; } + + /// The server's sequence: its id, , its settings JSON and versions; no archive. + public Sequence Sequence { get; } + + public IReadOnlyList Frames { get; } + + /// Absolute path of each frame's cached proxy, in frame order; null when it is not cached. + public IReadOnlyList Files { get; } + + public int CachedCount => Files.Count(f => f is not null); + + /// + /// The editor's frame source over the cached proxies, decoded by through the same + /// read-ahead window as archive renders. The result also implements + /// and ; dispose it when done. Frames are proxy-sized while the source reports the + /// originals' size, which allows. + /// + public IRenderFrameSource OpenFrames(ImageDecoder decoder, FrameWindowOptions? window = null) + { + var frames = new SequenceFrames(Sequence, Frames, Files); + return new SequenceFrameSource(frames, frames.LightFrames(), decoder, window); + } +} + +/// What the proxy cache keeps next to the files of one server sequence. +internal sealed record ProxyCacheIndex(SequenceDto Sequence, string? SettingsJson, int FramesVersion, IReadOnlyList Frames, IReadOnlyList Files); + +[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)] +[JsonSerializable(typeof(ProxyCacheIndex))] +internal sealed partial class ProxyCacheJson : JsonSerializerContext; + +/// +/// Proxies of server sequences on this PC: <root>/<server hash>/<sequence id>/ with one JPEG per +/// frame (named by frame id, so renumbering never mixes them up) and remote.json. Everything here can be +/// downloaded again, so the folder lives in the client's cache. +/// +internal sealed class ProxyCache(string root) +{ + private const string IndexFile = "remote.json"; + + public string Folder(string server, Guid remoteId) => + Path.Combine(root, Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(server)))[..16], remoteId.ToString("N")); + + public static string FileName(Guid frameId) => frameId.ToString("N") + ".jpg"; + + public bool Exists(string server, Guid remoteId) => File.Exists(Path.Combine(Folder(server, remoteId), IndexFile)); + + public void Save(string server, Guid remoteId, ProxyCacheIndex index) => + AtomicFile.WriteAllText(Path.Combine(Folder(server, remoteId), IndexFile), JsonSerializer.Serialize(index, ProxyCacheJson.Default.ProxyCacheIndex)); + + /// The cached sequence, or null when it was never cached or the cache was cleared. + public RemoteSequence? Load(string server, Guid remoteId) + { + var folder = Folder(server, remoteId); + var path = Path.Combine(folder, IndexFile); + if (!File.Exists(path)) return null; + ProxyCacheIndex? index; + try + { + index = JsonSerializer.Deserialize(File.ReadAllText(path), ProxyCacheJson.Default.ProxyCacheIndex); + } + catch (Exception ex) when (ex is JsonException or IOException) + { + Log.Warning("sync", $"Proxy cache of {remoteId} is unreadable", ex); + return null; + } + if (index is null || index.Files.Count != index.Frames.Count) return null; + var dto = index.Sequence; + var sequence = RenderNodeClient.ToSequence(dto) with + { + Tags = dto.Tags, + Rating = dto.Rating, + Notes = dto.Notes, + MedianInterval = dto.MedianInterval, + TotalBytes = dto.TotalBytes, + Status = (SequenceStatus)dto.Status, + HeroFrameId = dto.HeroFrameId, + SettingsJson = index.SettingsJson, + SettingsVersion = dto.SettingsVersion, + FramesVersion = index.FramesVersion, + Origin = SequenceOrigin.Server, + SyncState = SyncState.RemoteOnly, + OwnerUserId = dto.OwnerUserId, + UpdatedAt = dto.UpdatedAt, + }; + var files = index.Files.Select(f => f is not null && File.Exists(Path.Combine(folder, f)) ? Path.Combine(folder, f) : null).ToList(); + var frames = index.Frames.Select((f, i) => + { + var frame = RenderNodeClient.ToFrame(f); + return files[i] is null ? frame with { Flags = frame.Flags | FrameFlags.Missing } : frame; + }).ToList(); + return new RemoteSequence(server, sequence, frames, files); + } + + /// Removes the files of a sequence the server no longer has. + public void Delete(string server, Guid remoteId) + { + var folder = Folder(server, remoteId); + try + { + if (Directory.Exists(folder)) Directory.Delete(folder, recursive: true); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Warning("sync", $"Proxy cache {folder} could not be removed", ex); + } + } + + /// Deletes proxies of frames does not name (frames removed on the server). + public static void Prune(string folder, IReadOnlySet keep) + { + foreach (var file in Directory.EnumerateFiles(folder, "*.jpg")) + { + if (keep.Contains(Path.GetFileName(file))) continue; + try + { + File.Delete(file); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Warning("sync", $"Stale proxy {file} could not be removed", ex); + } + } + } +} diff --git a/src/Titano.Data/Sync/SyncAgent.cs b/src/Titano.Data/Sync/SyncAgent.cs new file mode 100644 index 00000000..1bb57426 --- /dev/null +++ b/src/Titano.Data/Sync/SyncAgent.cs @@ -0,0 +1,245 @@ +using System.Collections.Concurrent; +using System.Threading.Channels; +using Titano.Core.Diagnostics; +using Titano.Core.Model; +using Titano.Data.Jobs; +using Titano.Protocol; + +namespace Titano.Data.Sync; + +/// Timing of a . +public sealed record SyncAgentOptions +{ + /// Full comparison while nothing asks for one sooner (catches edits on this PC and missed events). + public TimeSpan RefreshInterval { get; init; } = TimeSpan.FromMinutes(2); + + /// Server events are collected this long, then their sequences are compared in one pass. + public TimeSpan EventDelay { get; init; } = TimeSpan.FromSeconds(1); + + /// First wait after a failed refresh or a lost event socket; doubles up to . + public TimeSpan MinBackoff { get; init; } = TimeSpan.FromSeconds(5); + + public TimeSpan MaxBackoff { get; init; } = TimeSpan.FromMinutes(5); +} + +/// +/// Keeps the sync table of one signed-in server current in the background: a full comparison at start, on request +/// and every ; the sequences named by the server's sequenceChanged +/// 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 +/// , proxy downloads queued for every server sequence without local +/// originals whose cache is stale. Dispose to stop. +/// +public sealed class SyncAgent : IAsyncDisposable +{ + private const string LogCategory = "sync"; + + private readonly SyncService _sync; + private readonly ISyncRemote _remote; + private readonly Func _policy; + private readonly JobEngine? _engine; + private readonly SyncAgentOptions _options; + private readonly CancellationTokenSource _stopping = new(); + private readonly Channel _refreshWake = Channel.CreateBounded(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite }); + private readonly Channel _eventWake = Channel.CreateBounded(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite }); + private readonly ConcurrentDictionary _changed = new(); + private readonly SemaphoreSlim _refreshing = new(1, 1); + private Task _running = Task.CompletedTask; + private SyncSnapshot? _snapshot; + private Exception? _lastError; + + /// Read before every comparison, so option changes apply at once. + /// Queue for proxy downloads; null keeps no proxies offline. + public SyncAgent(SyncService sync, ISyncRemote remote, Func policy, JobEngine? engine, SyncAgentOptions? options = null) + { + _sync = sync; + _remote = remote; + _policy = policy; + _engine = engine; + _options = options ?? new SyncAgentOptions(); + } + + public string Server => _remote.Server; + + /// The last full comparison; null until the first one finished. + public SyncSnapshot? Snapshot => Volatile.Read(ref _snapshot); + + /// Why the last full comparison failed; null after a successful one. + public Exception? LastError => Volatile.Read(ref _lastError); + + /// or changed (any thread). + public event Action? Changed; + + /// Starts the comparison and event loops. + public void Start() + { + var token = _stopping.Token; + _running = Task.WhenAll( + Task.Run(() => RefreshLoopAsync(token), CancellationToken.None), + Task.Run(() => EventLoopAsync(token), CancellationToken.None), + Task.Run(() => ChangedLoopAsync(token), CancellationToken.None)); + } + + /// Asks for a full comparison soon (after an edit on this PC, an option change, a reconnect). + public void RequestRefresh() => _refreshWake.Writer.TryWrite(true); + + /// Compares everything now; concurrent calls run one after the other. + public async Task RefreshAsync(CancellationToken cancellationToken = default) + { + using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _stopping.Token); + await _refreshing.WaitAsync(linked.Token).ConfigureAwait(false); + try + { + var policy = _policy(); + var snapshot = await _sync.RefreshAsync(_remote, policy, linked.Token).ConfigureAwait(false); + Volatile.Write(ref _snapshot, snapshot); + Volatile.Write(ref _lastError, null); + if (policy.KeepProxiesOffline && _engine is not null) await QueueProxiesAsync(snapshot, linked.Token).ConfigureAwait(false); + Changed?.Invoke(); + return snapshot; + } + finally + { + _refreshing.Release(); + } + } + + public async ValueTask DisposeAsync() + { + await _stopping.CancelAsync().ConfigureAwait(false); + try + { + await _running.ConfigureAwait(false); + } + catch (OperationCanceledException) + { + } + _stopping.Dispose(); + } + + private TimeSpan Backoff(int failures) => + TimeSpan.FromTicks(Math.Min(_options.MaxBackoff.Ticks, _options.MinBackoff.Ticks << Math.Min(failures, 20))); + + private async Task RefreshLoopAsync(CancellationToken cancellationToken) + { + var failures = 0; + while (!cancellationToken.IsCancellationRequested) + { + TimeSpan wait; + try + { + await RefreshAsync(cancellationToken).ConfigureAwait(false); + failures = 0; + wait = _options.RefreshInterval; + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + return; + } + catch (Exception ex) + { + Log.Warning(LogCategory, $"Comparing with {Server} failed", ex); + Volatile.Write(ref _lastError, ex); + Changed?.Invoke(); + wait = Backoff(failures++); + } + if (!await WaitAsync(_refreshWake.Reader, wait, cancellationToken).ConfigureAwait(false)) return; + } + } + + /// Listens to the server's events; a lost socket reconnects with backoff and asks for a full comparison (events were missed). + private async Task EventLoopAsync(CancellationToken cancellationToken) + { + var failures = 0; + while (!cancellationToken.IsCancellationRequested) + { + try + { + await foreach (var e in _remote.EventsAsync(cancellationToken).ConfigureAwait(false)) + { + failures = 0; + if (e is not SequenceChangedEvent changed) continue; + _changed[changed.SequenceId] = 0; + _eventWake.Writer.TryWrite(true); + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + return; + } + catch (Exception ex) + { + Log.Info(LogCategory, $"Event stream of {Server} lost: {ex.Message}"); + } + try + { + await Task.Delay(Backoff(failures++), cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + return; + } + RequestRefresh(); + } + } + + /// Compares the sequences named by events, a short while after the first one arrived. + private async Task ChangedLoopAsync(CancellationToken cancellationToken) + { + try + { + while (await _eventWake.Reader.WaitToReadAsync(cancellationToken).ConfigureAwait(false)) + { + _eventWake.Reader.TryRead(out _); + await Task.Delay(_options.EventDelay, cancellationToken).ConfigureAwait(false); + var ids = _changed.Keys.ToList(); + foreach (var id in ids) _changed.TryRemove(id, out _); + try + { + var busy = await _sync.TransferringAsync(Server, cancellationToken).ConfigureAwait(false); + var due = ids.Where(id => !busy.Contains(id)).ToList(); + if (due.Count > 0) await _sync.RefreshSequencesAsync(_remote, due, _policy(), cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + Log.Warning(LogCategory, $"Comparing changed sequences of {Server} failed", ex); + RequestRefresh(); + } + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + } + } + + /// Queues (background priority) the proxies of server sequences without local originals whose cache is stale. + private async Task QueueProxiesAsync(SyncSnapshot snapshot, CancellationToken cancellationToken) + { + foreach (var entry in snapshot.Entries) + { + if (entry is not { Local: null, Transfer: null, Link: { ServerHasProxies: true, ProxiesStale: true } link }) continue; + await _sync.EnqueueDownloadAsync(_engine!, Server, link.RemoteId, link.Title, SyncDownloadMode.Proxies, null, JobPriority.Background, cancellationToken) + .ConfigureAwait(false); + } + } + + /// Waits for a wake-up or the delay; false when stopping. + private static async Task WaitAsync(ChannelReader wake, TimeSpan delay, CancellationToken cancellationToken) + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(delay); + try + { + await wake.ReadAsync(timeout.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + // The delay elapsed. + } + catch (OperationCanceledException) + { + return false; + } + return true; + } +} diff --git a/src/Titano.Data/Sync/SyncJobHandler.cs b/src/Titano.Data/Sync/SyncJobHandler.cs new file mode 100644 index 00000000..ab826246 --- /dev/null +++ b/src/Titano.Data/Sync/SyncJobHandler.cs @@ -0,0 +1,46 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using Titano.Core.Localization; +using Titano.Core.Model; +using Titano.Data.Jobs; + +namespace Titano.Data.Sync; + +/// +/// Parameters of upload and download jobs. The job's target is the local sequence for an upload and the server +/// sequence for a download. +/// +/// Archive that receives downloaded originals when the sequence has no local copy yet. +internal sealed record SyncJobParameters(string Server, SyncDownloadMode? Mode = null, Guid? ArchiveId = null); + +[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, UseStringEnumConverter = true, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)] +[JsonSerializable(typeof(SyncJobParameters))] +internal sealed partial class SyncJobJson : JsonSerializerContext; + +/// Runs upload and download jobs with a connection to their server; the job fails with a reason when this PC is not connected to it. +internal sealed class SyncJobHandler(JobKind kind, SyncTransfers transfers, ISyncConnector connector) : IJobHandler +{ + public JobKind Kind => kind; + + public async Task RunAsync(JobContext context) + { + var parameters = (context.Job.ParametersJson is { } json ? JsonSerializer.Deserialize(json, SyncJobJson.Default.SyncJobParameters) : null) + ?? throw new InvalidDataException("The job has no sync parameters."); + if (context.Job.TargetIds is not [var target, ..]) throw new InvalidDataException("The job has no target sequence."); + using var remote = await connector.ConnectAsync(parameters.Server, context.Cancellation).ConfigureAwait(false) + ?? throw new InvalidOperationException(Loc.L("Errors.Sync.NotConnected")); + switch (kind, parameters.Mode) + { + case (JobKind.UploadCommit, _): + await transfers.UploadAsync(context, remote, target).ConfigureAwait(false); + break; + case (JobKind.Download, SyncDownloadMode.Proxies): + await transfers.DownloadProxiesAsync(context, remote, target).ConfigureAwait(false); + break; + default: + await transfers.DownloadOriginalsAsync(context, remote, target, parameters.ArchiveId).ConfigureAwait(false); + break; + } + } +} diff --git a/src/Titano.Data/Sync/SyncLinkStore.cs b/src/Titano.Data/Sync/SyncLinkStore.cs new file mode 100644 index 00000000..33f1496e --- /dev/null +++ b/src/Titano.Data/Sync/SyncLinkStore.cs @@ -0,0 +1,100 @@ +using Titano.Core.Model; +using Titano.Data.Repositories; + +namespace Titano.Data.Sync; + +/// The sync_links table and the sync columns of local sequences (origin, sync state). +internal sealed class SyncLinkStore(TitanoDatabase db) +{ + private const string Columns = + "server, remote_id, local_id, title, frame_count, total_bytes, render_count, remote_status, remote_settings_version, " + + "remote_frames_version, remote_updated_at, base_local_settings, base_remote_settings, diff_local_frames, diff_remote_frames, " + + "missing_remote, missing_local, conflict_local_settings, conflict_remote_settings, conflict_settings, proxies_cached, " + + "proxies_frames_version, synced_at"; + + private static readonly string UpsertSql = SqlDialect.Upsert("sync_links", Columns.Split(", "), 2); + + private static readonly JobState[] Active = [JobState.Queued, JobState.Running, JobState.Paused]; + + private readonly DbAccess _db = new(db.Database); + + public Task> ListAsync(string server, CancellationToken cancellationToken) => + _db.ListAsync($"SELECT {Columns} FROM sync_links WHERE server = $1 ORDER BY remote_id", [server], Map, cancellationToken); + + public Task GetAsync(string server, Guid remoteId, CancellationToken cancellationToken) => + _db.SingleAsync($"SELECT {Columns} FROM sync_links WHERE server = $1 AND remote_id = $2", [server, remoteId], Map, cancellationToken); + + public Task FindByLocalAsync(string server, Guid localId, CancellationToken cancellationToken) => + _db.SingleAsync($"SELECT {Columns} FROM sync_links WHERE server = $1 AND local_id = $2", [server, localId], Map, cancellationToken); + + public Task UpsertAsync(SyncLink l, CancellationToken cancellationToken) => + _db.ExecuteAsync(UpsertSql, + [ + l.Server, l.RemoteId, l.LocalId, l.Title, l.FrameCount, l.TotalBytes, l.RenderCount, (int)l.RemoteStatus, l.RemoteSettingsVersion, + l.RemoteFramesVersion, l.RemoteUpdatedAt, l.BaseLocalSettings, l.BaseRemoteSettings, l.DiffLocalFrames, l.DiffRemoteFrames, + l.MissingRemote, l.MissingLocal, l.ConflictLocalSettings, l.ConflictRemoteSettings, l.ConflictSettingsJson, l.ProxiesCached, + l.ProxiesFramesVersion, l.SyncedAt, + ], cancellationToken); + + public Task DeleteAsync(string server, Guid remoteId, CancellationToken cancellationToken) => + _db.ExecuteAsync("DELETE FROM sync_links WHERE server = $1 AND remote_id = $2", [server, remoteId], cancellationToken); + + /// Records where a local sequence stands for the Library; touches neither its versions nor its update time. + public Task SetLocalStateAsync(Guid localId, SyncState state, CancellationToken cancellationToken) => + _db.ExecuteAsync("UPDATE sequences SET sync_state = $2 WHERE id = $1 AND sync_state <> $2", [localId, (int)state], cancellationToken); + + /// Marks a local sequence as downloaded from the server. + public Task SetOriginAsync(Guid localId, SequenceOrigin origin, CancellationToken cancellationToken) => + _db.ExecuteAsync("UPDATE sequences SET origin = $2 WHERE id = $1", [localId, (int)origin], cancellationToken); + + /// Upload and download jobs that are waiting, running or paused, by target id (local id for uploads, server id for downloads). + public async Task> ActiveTransfersAsync(CancellationToken cancellationToken) + { + var transfers = new Dictionary(); + foreach (var kind in new[] { JobKind.UploadCommit, JobKind.Download }) + { + foreach (var state in Active) + { + string? cursor = null; + do + { + var page = await db.Jobs.ListAsync(state, kind, 500, cursor, cancellationToken).ConfigureAwait(false); + foreach (var job in page.Items) + { + if (job.TargetIds.Count > 0) transfers.TryAdd(job.TargetIds[0], job); + } + cursor = page.NextCursor; + } + while (cursor is not null); + } + } + return transfers; + } + + private static SyncLink Map(DbRow r) => new() + { + Server = r.GetString(0), + RemoteId = r.GetGuid(1), + LocalId = r.GetGuidOrNull(2), + Title = r.GetString(3), + FrameCount = r.GetInt32(4), + TotalBytes = r.GetInt64(5), + RenderCount = r.GetInt32(6), + RemoteStatus = (SequenceStatus)r.GetInt32(7), + RemoteSettingsVersion = r.GetInt32(8), + RemoteFramesVersion = r.GetInt32(9), + RemoteUpdatedAt = r.GetDateTimeOffset(10), + BaseLocalSettings = r.GetInt32OrNull(11), + BaseRemoteSettings = r.GetInt32OrNull(12), + DiffLocalFrames = r.GetInt32OrNull(13), + DiffRemoteFrames = r.GetInt32OrNull(14), + MissingRemote = r.GetInt32(15), + MissingLocal = r.GetInt32(16), + ConflictLocalSettings = r.GetInt32OrNull(17), + ConflictRemoteSettings = r.GetInt32OrNull(18), + ConflictSettingsJson = r.GetStringOrNull(19), + ProxiesCached = r.GetInt32(20), + ProxiesFramesVersion = r.GetInt32OrNull(21), + SyncedAt = r.GetDateTimeOffsetOrNull(22), + }; +} diff --git a/src/Titano.Data/Sync/SyncModel.cs b/src/Titano.Data/Sync/SyncModel.cs new file mode 100644 index 00000000..db73243b --- /dev/null +++ b/src/Titano.Data/Sync/SyncModel.cs @@ -0,0 +1,132 @@ +using Titano.Core.Model; + +namespace Titano.Data.Sync; + +/// Where a sequence stands between this PC and the server (BRIEF §12.7, §14.5). +public enum SyncStatus +{ + /// Same originals and settings on both sides. + InSync, + + LocalOnly, + RemoteOnly, + + /// Only on the server; this PC keeps its proxies for editing. + ProxiesOnly, + + /// This PC holds originals or settings the server lacks. + LocalAhead, + + /// The server holds originals or settings this PC lacks. + ServerAhead, + + /// Both sides changed the settings since they last agreed: the user picks. + Conflict, + + /// An upload or download job is queued, running or paused. + Transferring, +} + +/// How the user settles a settings conflict (BRIEF §12.7). +public enum SyncResolution +{ + KeepMine, + TakeServer, + + /// The server's settings win; this PC's are kept next to the project as a dated copy. + SaveBoth, +} + +/// What a download job fetches. +public enum SyncDownloadMode +{ + /// Originals, hash-verified, into the local archive. + Originals, + + /// Proxies (thumbnails where the server has none) into the proxy cache. + Proxies, +} + +/// +/// One server sequence as this client last saw it, linked to its local copy when there is one. The base versions are +/// the settings counters both sides had when they last agreed; the diff versions are the frame counters the missing +/// counts were computed at, so originals are compared again only when either side's frames change. +/// +public sealed record SyncLink +{ + /// Normalised server address (). + public required string Server { get; init; } + + public required Guid RemoteId { get; init; } + public Guid? LocalId { get; init; } + + // ---- The server's side, from its sequence listing ---- + public required string Title { get; init; } + public int FrameCount { get; init; } + public long TotalBytes { get; init; } + public int RenderCount { get; init; } + public SequenceStatus RemoteStatus { get; init; } + public int RemoteSettingsVersion { get; init; } + public int RemoteFramesVersion { get; init; } + public DateTimeOffset RemoteUpdatedAt { get; init; } + + // ---- Agreement and comparison state ---- + public int? BaseLocalSettings { get; init; } + public int? BaseRemoteSettings { get; init; } + public int? DiffLocalFrames { get; init; } + public int? DiffRemoteFrames { get; init; } + + /// Local originals the server does not have. + public int MissingRemote { get; init; } + + /// Server originals this PC does not have. + public int MissingLocal { get; init; } + + /// Settings versions at which the content was found to conflict; null when it does not. + public int? ConflictLocalSettings { get; init; } + + public int? ConflictRemoteSettings { get; init; } + + /// The server's settings when the conflict was found, so it can be shown without asking the server again. + public string? ConflictSettingsJson { get; init; } + + /// Frames whose proxy (or thumbnail) is in this PC's proxy cache. + public int ProxiesCached { get; init; } + + /// Server frames version the proxy cache was filled at. + public int? ProxiesFramesVersion { get; init; } + + public DateTimeOffset? SyncedAt { get; init; } + + public bool ServerHasProxies => (RemoteStatus & SequenceStatus.ProxiesBuilt) != 0; + + /// The proxy cache misses frames the server has, or predates its last frame change. + public bool ProxiesStale => ProxiesCached < FrameCount || ProxiesFramesVersion != RemoteFramesVersion; +} + +/// One row of the sync table: the local sequence, the server sequence, or both, and where they stand. +/// The upload or download job working on it, if any. +public sealed record SyncEntry(Sequence? Local, SyncLink? Link, SyncStatus Status, Job? Transfer = null) +{ + public string Title => Local?.DisplayTitle ?? Link?.Title ?? string.Empty; + + /// The server's id, or the local one for a sequence the server does not have. + public Guid Id => Link?.RemoteId ?? Local!.Id; + + /// This PC holds originals of the sequence. + public bool HasLocalOriginals => Local is { FrameCount: > 0 }; +} + +/// The sync table after a refresh. +/// Time the refresh took (listing, manifest diffs, settings exchange). +public sealed record SyncSnapshot(string Server, IReadOnlyList Entries, DateTimeOffset RefreshedAt, TimeSpan Duration) +{ + public long ServerBytes => Entries.Sum(e => e.Link?.TotalBytes ?? 0); + + public int ServerSequences => Entries.Count(e => e.Link is not null); +} + +/// Options a refresh applies. +/// Send and take settings changed on one side only (Server.html "Sync projects automatically"). +/// Keep the proxies of every server sequence without local originals in the cache. +public sealed record SyncPolicy(bool AutoSyncSettings = true, bool KeepProxiesOffline = false); diff --git a/src/Titano.Data/Sync/SyncRemote.cs b/src/Titano.Data/Sync/SyncRemote.cs new file mode 100644 index 00000000..a4b8a8fc --- /dev/null +++ b/src/Titano.Data/Sync/SyncRemote.cs @@ -0,0 +1,109 @@ +using Titano.Protocol; +using Titano.Protocol.Client; + +namespace Titano.Data.Sync; + +/// +/// The server calls the sync engine makes (BRIEF §14.3). sends them with +/// ; screenshots and tests substitute fakes. Failures are s +/// (404 gone, 409 settings conflict) or network exceptions. Dispose a remote handed out by an . +/// +public interface ISyncRemote : IDisposable +{ + /// Normalised server address the links are stored under (). + string Server { get; } + + /// Every sequence on the server. + Task> ListSequencesAsync(CancellationToken cancellationToken); + + Task GetSequenceAsync(Guid id, CancellationToken cancellationToken); + + Task GetManifestAsync(Guid id, CancellationToken cancellationToken); + + /// Every frame row of a sequence, in index order. + Task> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken); + + Task CreateSequenceAsync(CreateSequenceRequest request, CancellationToken cancellationToken); + + /// A 409 means the settings version moved on the server. + Task UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken); + + /// + /// Chunked, resumable upload of one original that the server verifies against before + /// committing it (BRIEF §14.4); see . + /// + Task UploadFileAsync(string path, Guid sequenceId, string sha256, DateTime? capturedAt, CancellationToken cancellationToken); + + /// Streams a frame's original, proxy or thumb, resuming with Range from the destination's length. + Task DownloadFrameAsync(Guid frameId, string kind, Stream destination, CancellationToken cancellationToken); + + /// Server events until cancelled or the socket closes. + IAsyncEnumerable EventsAsync(CancellationToken cancellationToken); +} + +/// Where sync jobs find their server connection. +public interface ISyncConnector +{ + /// A signed-in remote of owned by the caller; null when this PC is not connected to that server. + ValueTask ConnectAsync(string server, CancellationToken cancellationToken); +} + +/// over a signed-in , which it disposes when it owns it. +public sealed class TitanoSyncRemote(TitanoClient client, bool ownsClient) : ISyncRemote +{ + private const int SequencePage = 500; + private const int FramePage = 1000; + + public string Server { get; } = SyncService.ServerKey(client.BaseAddress); + + public async Task> ListSequencesAsync(CancellationToken cancellationToken) + { + var all = new List(); + string? cursor = null; + do + { + var page = await client.ListSequencesAsync(null, cursor, SequencePage, cancellationToken).ConfigureAwait(false); + all.AddRange(page.Items); + cursor = page.NextCursor; + } + while (cursor is not null); + return all; + } + + public Task GetSequenceAsync(Guid id, CancellationToken cancellationToken) => client.GetSequenceAsync(id, cancellationToken); + + public Task GetManifestAsync(Guid id, CancellationToken cancellationToken) => client.GetManifestAsync(id, cancellationToken); + + public async Task> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken) + { + var all = new List(); + string? cursor = null; + do + { + var page = await client.ListFramesAsync(sequenceId, cursor, FramePage, cancellationToken).ConfigureAwait(false); + all.AddRange(page.Items); + cursor = page.NextCursor; + } + while (cursor is not null); + return all; + } + + public Task CreateSequenceAsync(CreateSequenceRequest request, CancellationToken cancellationToken) => + client.CreateSequenceAsync(request, cancellationToken); + + public Task UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken) => + client.UpdateSequenceAsync(id, request, cancellationToken); + + public Task UploadFileAsync(string path, Guid sequenceId, string sha256, DateTime? capturedAt, CancellationToken cancellationToken) => + client.UploadFileAsync(path, sequenceId, capturedAt, null, sha256, null, cancellationToken); + + public Task DownloadFrameAsync(Guid frameId, string kind, Stream destination, CancellationToken cancellationToken) => + client.DownloadFrameAsync(frameId, kind, destination, null, cancellationToken); + + public IAsyncEnumerable EventsAsync(CancellationToken cancellationToken) => client.EventsAsync(cancellationToken); + + public void Dispose() + { + if (ownsClient) client.Dispose(); + } +} diff --git a/src/Titano.Data/Sync/SyncRules.cs b/src/Titano.Data/Sync/SyncRules.cs new file mode 100644 index 00000000..c9fe5ebe --- /dev/null +++ b/src/Titano.Data/Sync/SyncRules.cs @@ -0,0 +1,145 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using Titano.Core.Model; +using Titano.Core.Project; +using Titano.Protocol; + +namespace Titano.Data.Sync; + +/// The fields both sides version together (BRIEF §14.5: settings and tags carry version counters). +public sealed record SyncPayload(string? Title, IReadOnlyList Tags, int Rating, string? Notes, string? SettingsJson) +{ + public static SyncPayload Of(Sequence s) => new(s.Title, s.Tags, s.Rating, s.Notes, s.SettingsJson); + + public static SyncPayload Of(SequenceDto s, string? settingsJson) => new(s.Title, s.Tags, s.Rating, s.Notes, settingsJson); + + /// Title, tags, rating and notes match (blank equals absent, tags ignore case and order). + public bool SameMetadata(SyncPayload other) => + Blank(Title) == Blank(other.Title) + && Blank(Notes) == Blank(other.Notes) + && Rating == other.Rating + && Tags.ToHashSet(StringComparer.OrdinalIgnoreCase).SetEquals(other.Tags); + + public bool SameAs(SyncPayload other) => SameMetadata(other) && SyncRules.SameSettings(SettingsJson, other.SettingsJson); + + /// The PATCH that makes the server's copy equal to this one; settings are sent in their normalised form. + public UpdateSequenceRequest ToRequest(int? expectedSettingsVersion) => + new(Title ?? string.Empty, Tags, Rating, Notes ?? string.Empty, SyncRules.NormalizeSettings(SettingsJson), expectedSettingsVersion); + + private static string Blank(string? text) => text?.Trim() ?? string.Empty; +} + +/// One setting that differs: its dotted path ("exposure.deflicker.window") and the JSON value on each side (null when absent). +public sealed record SettingsDifference(string Path, string? Mine, string? Theirs); + +/// Decisions of the sync engine that need no I/O: the status of a row, settings equality and differences, merges. +public static class SyncRules +{ + /// + /// Where a linked pair stands. Settings changed on both sides since they last agreed are a conflict (the engine + /// settles equal content and metadata-only differences before a row is shown); missing originals count before + /// settings changed on one side only. + /// + public static SyncStatus Status(Sequence? local, SyncLink? link) + { + if (link is null) return SyncStatus.LocalOnly; + if (local is null) return link.ProxiesCached > 0 ? SyncStatus.ProxiesOnly : SyncStatus.RemoteOnly; + var localChanged = link.BaseLocalSettings != local.SettingsVersion; + var remoteChanged = link.BaseRemoteSettings != link.RemoteSettingsVersion; + if (localChanged && remoteChanged) return SyncStatus.Conflict; + if (link.MissingRemote > 0 || localChanged) return SyncStatus.LocalAhead; + if (link.MissingLocal > 0 || remoteChanged) return SyncStatus.ServerAhead; + return SyncStatus.InSync; + } + + /// The state stored on the local sequence for the Library; null for rows without a local copy or in transfer. + public static SyncState? ToSequenceState(SyncStatus status) => status switch + { + SyncStatus.InSync => SyncState.InSync, + SyncStatus.LocalOnly => SyncState.LocalOnly, + SyncStatus.LocalAhead => SyncState.LocalAhead, + SyncStatus.ServerAhead => SyncState.ServerAhead, + SyncStatus.Conflict => SyncState.Conflict, + _ => null, + }; + + /// + /// Settings JSON in the form both sides store: a project read and written again (missing members take their + /// defaults, so "no settings" equals the default project). Text that is not a project of this build is kept as is. + /// + public static string NormalizeSettings(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return new ProjectSettings().ToJson(); + try + { + return ProjectSettings.FromJson(json).ToJson(); + } + catch (Exception ex) when (ex is JsonException or InvalidDataException) + { + return json.Trim(); + } + } + + public static bool SameSettings(string? a, string? b) => Differences(a, b, 1).Count == 0; + + /// Up to settings that differ, in document order. + public static IReadOnlyList Differences(string? mine, string? theirs, int max = 3) + { + var differences = new List(); + Collect(Parse(NormalizeSettings(mine)), Parse(NormalizeSettings(theirs)), string.Empty, differences, max); + return differences; + } + + /// + /// Metadata-only divergence (settings equal): tags are united, title, rating and notes come from the side edited last. + /// + public static SyncPayload Merge(SyncPayload local, SyncPayload remote, bool localIsNewer) + { + var newer = localIsNewer ? local : remote; + var tags = local.Tags.Concat(remote.Tags).Distinct(StringComparer.OrdinalIgnoreCase).ToList(); + return newer with { Tags = tags, SettingsJson = local.SettingsJson }; + } + + /// + /// Originals missing on each side by content (BRIEF §14.5: originals never conflict). Local frames not hashed yet + /// (adopted, not verified) are assumed to match server frames that no hash matched. + /// + public static (int MissingRemote, int MissingLocal) CompareOriginals(IReadOnlyCollection localHashes, IReadOnlyCollection remoteHashes) + { + var remote = remoteHashes.Select(h => h.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal); + var hashed = localHashes.Where(h => !string.IsNullOrEmpty(h)).Select(h => h!.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal); + var unhashed = localHashes.Count(string.IsNullOrEmpty); + var matched = hashed.Count(remote.Contains); + var unmatchedRemote = remote.Count - matched; + return (hashed.Count - matched + Math.Max(0, unhashed - unmatchedRemote), Math.Max(0, unmatchedRemote - unhashed)); + } + + private static JsonNode? Parse(string json) + { + try + { + return JsonNode.Parse(json); + } + catch (JsonException) + { + return JsonValue.Create(json); + } + } + + private static void Collect(JsonNode? a, JsonNode? b, string path, List differences, int max) + { + if (differences.Count >= max) return; + if (a is JsonObject left && b is JsonObject right) + { + foreach (var name in left.Select(p => p.Key).Concat(right.Select(p => p.Key)).Distinct(StringComparer.Ordinal)) + { + left.TryGetPropertyValue(name, out var x); + right.TryGetPropertyValue(name, out var y); + Collect(x, y, path.Length == 0 ? name : path + "." + name, differences, max); + if (differences.Count >= max) return; + } + return; + } + if (!JsonNode.DeepEquals(a, b)) differences.Add(new SettingsDifference(path.Length == 0 ? "settings" : path, a?.ToJsonString(), b?.ToJsonString())); + } +} diff --git a/src/Titano.Data/Sync/SyncService.cs b/src/Titano.Data/Sync/SyncService.cs new file mode 100644 index 00000000..72121690 --- /dev/null +++ b/src/Titano.Data/Sync/SyncService.cs @@ -0,0 +1,529 @@ +using System.Diagnostics; +using System.Globalization; +using System.Net; +using System.Text.Json; +using Titano.Core.Archiving; +using Titano.Core.Diagnostics; +using Titano.Core.IO; +using Titano.Core.Model; +using Titano.Data.Archiving; +using Titano.Data.Jobs; +using Titano.Data.Processing; +using Titano.Data.Repositories; +using Titano.Protocol; +using Titano.Protocol.Client; +using SequenceFrames = Titano.Data.Processing.SequenceFrames; +using SequenceManifest = Titano.Protocol.SequenceManifest; + +namespace Titano.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 (inside the client's cache). + public required string ProxyCacheDirectory { 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 moved, the manifest: originals are matched by SHA-256 and never conflict; 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 settings is a conflict the user settles +/// with . 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 . Proxies and +/// thumbnails never travel upward. The state of each local sequence is written to its sync_state for the Library. +/// +public sealed class SyncService +{ + private const string LogCategory = "sync"; + private const string SessionKeyPrefix = "titano-sync:"; + + private readonly TitanoDatabase _db; + private readonly SyncLinkStore _links; + private readonly ProjectStore _projects; + private readonly SemaphoreSlim _gate = new(1, 1); + + public SyncService(TitanoDatabase db, ArchiveService archives, SyncOptions options) + { + _db = db; + Archives = archives; + Options = options; + _links = new SyncLinkStore(db); + _projects = new ProjectStore(db, new SequenceWriter(options.Archive)); + Proxies = new ProxyCache(options.ProxyCacheDirectory); + } + + public SyncOptions Options { get; } + + /// The links or local states of a server (the argument) changed: refresh, resolution, transfer; raised on any thread. + public event Action? Changed; + + internal ProxyCache Proxies { get; } + + internal SyncLinkStore Links => _links; + + internal TitanoDatabase Database => _db; + + internal ArchiveService Archives { get; } + + /// "https://nas.local:8443": the key links are stored under (scheme, lower-case host, port, path). + public static string ServerKey(Uri address) => address.GetLeftPart(UriPartial.Path).TrimEnd('/').ToLowerInvariant(); + + /// 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 deleted on the server, and stores the states. + /// + public async Task RefreshAsync(ISyncRemote remote, SyncPolicy policy, CancellationToken cancellationToken) + { + var clock = Stopwatch.StartNew(); + var listing = await remote.ListSequencesAsync(cancellationToken).ConfigureAwait(false); + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + var links = (await _links.ListAsync(remote.Server, cancellationToken).ConfigureAwait(false)).ToDictionary(l => l.RemoteId); + var locals = await LocalSequencesAsync(cancellationToken).ConfigureAwait(false); + foreach (var dto in listing) + { + links.Remove(dto.Id, out var link); + var local = link?.LocalId is { } id ? locals.GetValueOrDefault(id) : null; + await ReconcileSafelyAsync(remote, Observe(link, remote.Server, dto), dto, local, policy, cancellationToken).ConfigureAwait(false); + } + foreach (var gone in links.Values) await ForgetAsync(gone, cancellationToken).ConfigureAwait(false); + } + finally + { + _gate.Release(); + } + var entries = await StoreStatesAsync(remote.Server, cancellationToken).ConfigureAwait(false); + Changed?.Invoke(remote.Server); + 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) + { + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + foreach (var id in remoteIds) + { + var link = await _links.GetAsync(remote.Server, id, cancellationToken).ConfigureAwait(false); + SequenceDto dto; + try + { + dto = await remote.GetSequenceAsync(id, cancellationToken).ConfigureAwait(false); + } + catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound) + { + if (link is not null) await ForgetAsync(link, cancellationToken).ConfigureAwait(false); + continue; + } + var local = link?.LocalId is { } localId ? await _db.Sequences.GetAsync(localId, cancellationToken).ConfigureAwait(false) : null; + await ReconcileSafelyAsync(remote, Observe(link, remote.Server, dto), dto, local, policy, cancellationToken).ConfigureAwait(false); + } + } + finally + { + _gate.Release(); + } + await StoreStatesAsync(remote.Server, cancellationToken).ConfigureAwait(false); + Changed?.Invoke(remote.Server); + } + + /// The sync table of as last compared: every server sequence and every local one, with active transfers. + public async Task> ListAsync(string server, CancellationToken cancellationToken) + { + var links = await _links.ListAsync(server, cancellationToken).ConfigureAwait(false); + var locals = await LocalSequencesAsync(cancellationToken).ConfigureAwait(false); + var transfers = await _links.ActiveTransfersAsync(cancellationToken).ConfigureAwait(false); + var entries = new List(links.Count + locals.Count); + foreach (var link in links) + { + var local = link.LocalId is { } id && locals.Remove(id, out var found) ? found : null; + var transfer = (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 = transfers.GetValueOrDefault(local.Id); + entries.Add(new SyncEntry(local, null, transfer is null ? SyncStatus.LocalOnly : SyncStatus.Transferring, transfer)); + } + entries.Sort((a, b) => string.Compare(a.Title, b.Title, StringComparison.CurrentCultureIgnoreCase)); + return entries; + } + + /// + /// 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); + } + + // ---------------- Settings ---------------- + + /// Settles a settings conflict as the user chose (BRIEF §12.7); a 409 means the server changed again meanwhile. + public async Task ResolveAsync(ISyncRemote remote, Guid remoteId, SyncResolution resolution, 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); + link = Observe(link, remote.Server, dto); + if (resolution == SyncResolution.KeepMine) + { + var updated = await remote.UpdateSequenceAsync(remoteId, SyncPayload.Of(local).ToRequest(dto.SettingsVersion), cancellationToken).ConfigureAwait(false); + link = Agreed(Observe(link, remote.Server, updated), local.SettingsVersion, updated.SettingsVersion); + } + else + { + if (resolution == SyncResolution.SaveBoth) await SaveCopyAsync(local, cancellationToken).ConfigureAwait(false); + var manifest = await remote.GetManifestAsync(remoteId, cancellationToken).ConfigureAwait(false); + var applied = await ApplyLocallyAsync(local, SyncPayload.Of(dto, manifest.SettingsJson), cancellationToken).ConfigureAwait(false); + link = Agreed(link, applied.SettingsVersion, manifest.SettingsVersion); + } + await _links.UpsertAsync(link with { SyncedAt = DateTimeOffset.UtcNow }, cancellationToken).ConfigureAwait(false); + Log.Info(LogCategory, $"Conflict on {local.DisplayTitle} settled: {resolution}"); + } + finally + { + _gate.Release(); + } + await StoreStatesAsync(remote.Server, cancellationToken).ConfigureAwait(false); + Changed?.Invoke(remote.Server); + } + + /// Sends or takes settings changed on one side only (the row action while automatic sync is off). + public Task SyncSettingsAsync(ISyncRemote remote, Guid remoteId, CancellationToken cancellationToken) => + RefreshSequencesAsync(remote, [remoteId], new SyncPolicy(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) => + EnqueueAsync(engine, JobKind.UploadCommit, local.Id, local.DisplayTitle, new SyncJobParameters(server), JobPriority.User, cancellationToken); + + /// + /// Queues a download of a server sequence, unless one is already waiting or running: originals into + /// (ignored when the sequence already has a local copy), or proxies into the cache. + /// + 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); + + // ---------------- 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) + { + var link = await _links.GetAsync(server, remoteId, cancellationToken).ConfigureAwait(false) + ?? new SyncLink { Server = server, RemoteId = remoteId, Title = local.DisplayTitle, RemoteUpdatedAt = DateTimeOffset.UtcNow }; + link = link with { LocalId = local.Id }; + await _links.UpsertAsync(link, cancellationToken).ConfigureAwait(false); + return link; + } + + /// Makes the server's copy equal to this PC's (an upload sends the settings with the originals). + 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); + var dto = await remote.GetSequenceAsync(remoteId, cancellationToken).ConfigureAwait(false); + var updated = await remote.UpdateSequenceAsync(remoteId, SyncPayload.Of(local).ToRequest(dto.SettingsVersion), cancellationToken).ConfigureAwait(false); + await _links.UpsertAsync(Agreed(Observe(link, remote.Server, updated), local.SettingsVersion, updated.SettingsVersion), cancellationToken) + .ConfigureAwait(false); + } + 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); + var applied = await ApplyLocallyAsync(local, SyncPayload.Of(dto, manifest.SettingsJson), cancellationToken).ConfigureAwait(false); + await _links.UpsertAsync(Agreed(Observe(link, remote.Server, dto), applied.SettingsVersion, manifest.SettingsVersion), cancellationToken) + .ConfigureAwait(false); + } + finally + { + _gate.Release(); + } + } + + /// Records what the proxy cache holds for a server sequence. + internal async Task SetProxiesAsync(string server, SequenceDto dto, int cached, 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); + await _links.UpsertAsync(link with { ProxiesCached = cached, ProxiesFramesVersion = framesVersion }, cancellationToken).ConfigureAwait(false); + } + finally + { + _gate.Release(); + } + Changed?.Invoke(server); + } + + private async Task ReconcileSafelyAsync(ISyncRemote remote, SyncLink link, SequenceDto dto, Sequence? local, SyncPolicy policy, CancellationToken cancellationToken) + { + try + { + link = await ReconcileAsync(remote, link, dto, local, policy, cancellationToken).ConfigureAwait(false); + } + catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound) + { + // Deleted between the listing and the manifest: the next refresh forgets it. + Log.Info(LogCategory, $"{dto.DisplayTitle} vanished from the server during the comparison"); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or LeaseUnavailableException) + { + // The local archive is offline or busy: compare again next time; the other sequences go on. + Log.Warning(LogCategory, $"{dto.DisplayTitle} could not be synced", ex); + } + await _links.UpsertAsync(link, cancellationToken).ConfigureAwait(false); + } + + /// Compares originals when frame counters moved, then settles the settings; returns the updated link. + private async Task 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); + } + SequenceManifest? manifest = null; + if (link.DiffLocalFrames != local.FramesVersion || link.DiffRemoteFrames != link.RemoteFramesVersion) + { + manifest = await remote.GetManifestAsync(link.RemoteId, cancellationToken).ConfigureAwait(false); + var frames = await SequenceFrames.ListAsync(_db, local.Id, cancellationToken).ConfigureAwait(false); + var (missingRemote, missingLocal) = SyncRules.CompareOriginals( + [.. frames.Where(f => (f.Flags & FrameFlags.Missing) == 0).Select(f => f.Sha256)], [.. manifest.Frames.Select(f => f.Sha256)]); + link = link with + { + DiffLocalFrames = local.FramesVersion, + DiffRemoteFrames = manifest.FramesVersion, + RemoteFramesVersion = manifest.FramesVersion, + MissingRemote = missingRemote, + MissingLocal = missingLocal, + }; + } + link = await SettleSettingsAsync(remote, link, dto, local, manifest, policy, cancellationToken).ConfigureAwait(false); + return link with { SyncedAt = DateTimeOffset.UtcNow }; + } + + private async Task 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; + if (localChanged && remoteChanged) + { + if (link.ConflictLocalSettings == local.SettingsVersion && link.ConflictRemoteSettings == link.RemoteSettingsVersion) return link; + manifest ??= await remote.GetManifestAsync(link.RemoteId, cancellationToken).ConfigureAwait(false); + var mine = SyncPayload.Of(local); + var theirs = SyncPayload.Of(dto, manifest.SettingsJson); + if (mine.SameAs(theirs)) return Agreed(link, local.SettingsVersion, manifest.SettingsVersion); + if (!SyncRules.SameSettings(mine.SettingsJson, theirs.SettingsJson)) + { + return link with + { + ConflictLocalSettings = local.SettingsVersion, + ConflictRemoteSettings = link.RemoteSettingsVersion, + ConflictSettingsJson = SyncRules.NormalizeSettings(theirs.SettingsJson), + }; + } + // Only title, tags, rating or notes differ: merge them and give both sides the result. + var merged = SyncRules.Merge(mine, theirs, local.UpdatedAt >= dto.UpdatedAt); + var applied = merged.SameMetadata(mine) ? local : await ApplyLocallyAsync(local, merged, cancellationToken).ConfigureAwait(false); + return await PushAsync(remote, link, applied, manifest.SettingsVersion, cancellationToken).ConfigureAwait(false); + } + if (!policy.AutoSyncSettings) return link; + if (localChanged) return await PushAsync(remote, link, local, link.BaseRemoteSettings, cancellationToken).ConfigureAwait(false); + manifest ??= await remote.GetManifestAsync(link.RemoteId, cancellationToken).ConfigureAwait(false); + var pulled = await ApplyLocallyAsync(local, SyncPayload.Of(dto, manifest.SettingsJson), cancellationToken).ConfigureAwait(false); + return Agreed(link, pulled.SettingsVersion, manifest.SettingsVersion); + } + + /// Sends this PC's payload unless the server moved past , which shows up as a conflict next. + private static async Task PushAsync(ISyncRemote remote, SyncLink link, Sequence local, int? expected, CancellationToken cancellationToken) + { + try + { + var updated = await remote.UpdateSequenceAsync(link.RemoteId, SyncPayload.Of(local).ToRequest(expected), cancellationToken).ConfigureAwait(false); + return Agreed(Observe(link, link.Server, updated), local.SettingsVersion, updated.SettingsVersion); + } + catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.Conflict) + { + return Observe(link, link.Server, await remote.GetSequenceAsync(link.RemoteId, cancellationToken).ConfigureAwait(false)); + } + } + + /// Writes a payload into the local sidecar, project and index (each write bumps the local settings version). + private async Task ApplyLocallyAsync(Sequence local, SyncPayload payload, CancellationToken cancellationToken) + { + var current = local; + if (!payload.SameMetadata(SyncPayload.Of(local))) + current = await Archives.SetSequenceInfoAsync(local.Id, payload.Title, payload.Tags, payload.Rating, payload.Notes, cancellationToken).ConfigureAwait(false); + if (!SyncRules.SameSettings(payload.SettingsJson, current.SettingsJson)) + { + var archive = await _db.Archives.GetAsync(current.ArchiveId, cancellationToken).ConfigureAwait(false) + ?? throw new InvalidDataException($"Archive {current.ArchiveId} is not indexed."); + var project = ProjectStore.Parse(SyncRules.NormalizeSettings(payload.SettingsJson)); + await _projects.UpdateAsync(new ArchivePaths(archive.RootPath), current, _ => project, cancellationToken).ConfigureAwait(false); + } + return await _db.Sequences.GetAsync(local.Id, cancellationToken).ConfigureAwait(false) ?? current; + } + + /// "Save both": this PC's project is kept as .titano/project.local-<UTC time>.json before the server's replaces it. + 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 folder = new ArchivePaths(archive.RootPath).Sequence(local.Folder); + Directory.CreateDirectory(folder.MetaDirectory); + var name = string.Create(CultureInfo.InvariantCulture, $"project.local-{DateTime.UtcNow:yyyyMMdd-HHmmss}.json"); + AtomicFile.WriteAllText(Path.Combine(folder.MetaDirectory, name), SyncRules.NormalizeSettings(local.SettingsJson)); + Log.Info(LogCategory, $"Settings of {local.DisplayTitle} kept as {name}"); + } + + private async Task ForgetAsync(SyncLink link, CancellationToken cancellationToken) + { + 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, CancellationToken cancellationToken) + { + var entries = await ListAsync(server, 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; + } + + 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 active = await _links.ActiveTransfersAsync(cancellationToken).ConfigureAwait(false); + if (active.TryGetValue(target, out var running) && running.Kind == kind) return running; + 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, + ConflictSettingsJson = null, + }; + + private static SyncLink Unlinked(SyncLink link) => link with + { + LocalId = null, + BaseLocalSettings = null, + BaseRemoteSettings = null, + DiffLocalFrames = null, + DiffRemoteFrames = null, + MissingRemote = 0, + MissingLocal = 0, + ConflictLocalSettings = null, + ConflictRemoteSettings = null, + ConflictSettingsJson = null, + }; +} diff --git a/src/Titano.Data/Sync/SyncTransfers.cs b/src/Titano.Data/Sync/SyncTransfers.cs new file mode 100644 index 00000000..4747f117 --- /dev/null +++ b/src/Titano.Data/Sync/SyncTransfers.cs @@ -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; + +/// +/// 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. +/// +internal sealed class SyncTransfers(SyncService sync) +{ + private const long SpaceReserve = 512L << 20; + + /// Recomputes a sequence's state after a transfer without sending or taking settings on the user's behalf. + 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 have = local is null + ? new HashSet() + : (await SequenceFrames.ListAsync(db, local.Id, ct).ConfigureAwait(false)).Select(f => f.Sha256).OfType().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 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"); + } + + /// The server sequence an upload fills and whether this job created it: the linked one, one an interrupted attempt created, or a new one. + 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 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; + } + } + + /// Hashes the original again and sends it; false (logged) when it is gone or no longer the archived file. + private static async Task 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; + } + + /// Downloads one original into staging and commits it into the local sequence (created from the server id when null). + private async Task CommitAsync(ISyncRemote remote, Guid remoteId, Guid archiveId, Guid? sequenceId, ManifestFrame frame, string staging, + IReadOnlyDictionary 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; + } + + /// A verified copy in staging: resumed from a partial download, accepted only with the manifest's SHA-256 (two attempts). + private static async Task 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)); + } + } + + /// The cached proxy's file name, downloading the first asset kind the server has; null when it has none. + private static async Task FetchProxyAsync(ISyncRemote remote, Guid frameId, IReadOnlyList 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"], + _ => [], + }; + + /// Puts a follow-up job in the queue; the engine claims it on its next poll. + 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 }; + + /// Files done out of the total, reported in order from parallel workers. + 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); + } +} From 7f542646b4fe7d53c3551fea8d2a158b9859173e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 22:29:49 +0000 Subject: [PATCH 2/8] test(sync): state, settings conflicts, transfers and agent against an in-memory server Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- i18n/en/Errors.resx | 7 + i18n/en/Jobs.resx | 1 + i18n/it/Errors.it.resx | 7 + i18n/it/Jobs.it.resx | 1 + .../Titano.Data.Tests/Sync/FakeSyncRemote.cs | 205 +++++++++++++ .../Titano.Data.Tests/Sync/SyncAgentTests.cs | 99 ++++++ tests/Titano.Data.Tests/Sync/SyncFixture.cs | 108 +++++++ .../Titano.Data.Tests/Sync/SyncRulesTests.cs | 97 ++++++ .../Sync/SyncServiceTests.cs | 285 ++++++++++++++++++ .../Sync/SyncTransferTests.cs | 196 ++++++++++++ 10 files changed, 1006 insertions(+) create mode 100644 tests/Titano.Data.Tests/Sync/FakeSyncRemote.cs create mode 100644 tests/Titano.Data.Tests/Sync/SyncAgentTests.cs create mode 100644 tests/Titano.Data.Tests/Sync/SyncFixture.cs create mode 100644 tests/Titano.Data.Tests/Sync/SyncRulesTests.cs create mode 100644 tests/Titano.Data.Tests/Sync/SyncServiceTests.cs create mode 100644 tests/Titano.Data.Tests/Sync/SyncTransferTests.cs diff --git a/i18n/en/Errors.resx b/i18n/en/Errors.resx index 22ce17de..6018a270 100644 --- a/i18n/en/Errors.resx +++ b/i18n/en/Errors.resx @@ -18,6 +18,13 @@ The sequence to render is no longer in the archive. Enter a server address such as nas.local:8443 or https://titano.example.com. This file does not contain Titano settings. + The archive disk needs {0} GB more for these originals.{0} gigabytes missing + {0} did not arrive intact; download it again.{0} file name + The sequence is no longer in this PC's archive index. + Open or create an archive on this PC to receive the originals. + Not connected to this server; connect and retry the job. + {0} original is missing or changed since it was archived; verify the archive.{0} count + {0} originals are missing or changed since they were archived; verify the archive.{0} count The template is empty. Empty token at position {1}: write a name between the braces. File names cannot contain a slash; put folders in the folder template. diff --git a/i18n/en/Jobs.resx b/i18n/en/Jobs.resx index a165f36d..723aaee7 100644 --- a/i18n/en/Jobs.resx +++ b/i18n/en/Jobs.resx @@ -33,6 +33,7 @@ History keeps {0} days Adopt folder Deep analysis + Download Duplicates Import Light analysis diff --git a/i18n/it/Errors.it.resx b/i18n/it/Errors.it.resx index 31b8b300..aee44508 100644 --- a/i18n/it/Errors.it.resx +++ b/i18n/it/Errors.it.resx @@ -18,6 +18,13 @@ La sequenza da renderizzare non è più nell'archivio. Inserisci l'indirizzo di un server, ad esempio nas.local:8443 o https://titano.example.com. Questo file non contiene impostazioni di Titano. + Al disco dell'archivio servono altri {0} GB per questi originali. + {0} non è arrivato integro; scaricalo di nuovo. + La sequenza non è più nell'indice dell'archivio di questo PC. + Apri o crea un archivio su questo PC per ricevere gli originali. + Non connesso a questo server; collegati e riprova l'attività. + {0} originale manca o è cambiato dopo l'archiviazione; verifica l'archivio. + {0} originali mancano o sono cambiati dopo l'archiviazione; verifica l'archivio. Il modello è vuoto. Segnaposto vuoto alla posizione {1}: scrivi un nome tra le parentesi graffe. I nomi dei file non possono contenere la barra; metti le cartelle nel modello delle cartelle. diff --git a/i18n/it/Jobs.it.resx b/i18n/it/Jobs.it.resx index 29507c5b..58ed4e7c 100644 --- a/i18n/it/Jobs.it.resx +++ b/i18n/it/Jobs.it.resx @@ -33,6 +33,7 @@ Cronologia di {0} giorni Adozione cartella Analisi approfondita + Scaricamento Duplicati Importazione Analisi rapida diff --git a/tests/Titano.Data.Tests/Sync/FakeSyncRemote.cs b/tests/Titano.Data.Tests/Sync/FakeSyncRemote.cs new file mode 100644 index 00000000..14d7ee67 --- /dev/null +++ b/tests/Titano.Data.Tests/Sync/FakeSyncRemote.cs @@ -0,0 +1,205 @@ +using System.Net; +using System.Runtime.CompilerServices; +using System.Security.Cryptography; +using System.Threading.Channels; +using Titano.Core.Model; +using Titano.Data.Sync; +using Titano.Protocol; +using Titano.Protocol.Client; + +namespace Titano.Data.Tests.Sync; + +/// An in-memory Titano Server for the sync engine: sequences with versions, originals, proxies, thumbnails and events. +internal sealed class FakeSyncRemote : ISyncRemote +{ + private readonly Lock _gate = new(); + private readonly Channel _events = Channel.CreateUnbounded(); + + public string Server => "https://nas.test:8443"; + + public Dictionary Sequences { get; } = []; + + /// Manifest requests so far (comparisons skip them while frame counters stand still). + public int ManifestCalls { get; private set; } + + /// Listings still to fail with a network error. + public int FailingListings { get; set; } + + /// The next original download of this frame returns damaged bytes. + public Guid? CorruptOnce { get; set; } + + public FakeSequence Add(string? title, IEnumerable originals, string? settingsJson = null, + SequenceStatus status = SequenceStatus.ProxiesBuilt | SequenceStatus.ThumbsBuilt) + { + var sequence = new FakeSequence { Id = Guid.CreateVersion7(), Title = title, SettingsJson = settingsJson, Status = status }; + foreach (var bytes in originals) sequence.AddFrame(bytes); + lock (_gate) Sequences[sequence.Id] = sequence; + return sequence; + } + + /// Someone else edits the settings on the server. + public void EditSettings(Guid id, string settingsJson) + { + lock (_gate) + { + var s = Sequences[id]; + s.SettingsJson = settingsJson; + s.SettingsVersion++; + s.UpdatedAt = DateTimeOffset.UtcNow; + } + } + + public void Publish(ServerEvent e) => _events.Writer.TryWrite(e); + + public Task> ListSequencesAsync(CancellationToken cancellationToken) + { + lock (_gate) + { + if (FailingListings > 0) + { + FailingListings--; + throw new HttpRequestException("connection refused"); + } + return Task.FromResult>([.. Sequences.Values.Select(s => s.Dto())]); + } + } + + public Task GetSequenceAsync(Guid id, CancellationToken cancellationToken) + { + lock (_gate) return Task.FromResult(Find(id).Dto()); + } + + public Task GetManifestAsync(Guid id, CancellationToken cancellationToken) + { + lock (_gate) + { + ManifestCalls++; + return Task.FromResult(Find(id).Manifest()); + } + } + + public Task> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken) + { + lock (_gate) return Task.FromResult>([.. Find(sequenceId).Frames.Select((f, i) => f.Dto(sequenceId, i))]); + } + + public Task CreateSequenceAsync(CreateSequenceRequest request, CancellationToken cancellationToken) + { + var sequence = Add(request.Title, []); + return Task.FromResult(sequence.Dto()); + } + + public Task UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken) + { + lock (_gate) + { + var s = Find(id); + if (request.ExpectedSettingsVersion is { } expected && expected != s.SettingsVersion) + throw new TitanoApiException(HttpStatusCode.Conflict, new ApiError("settings_conflict", "changed")); + if (request.Title is not null) s.Title = request.Title.Length == 0 ? null : request.Title; + if (request.Tags is not null) s.Tags = [.. request.Tags]; + if (request.Rating is { } rating) s.Rating = rating; + if (request.Notes is not null) s.Notes = request.Notes.Length == 0 ? null : request.Notes; + if (request.SettingsJson is not null) s.SettingsJson = request.SettingsJson; + s.SettingsVersion++; + s.UpdatedAt = DateTimeOffset.UtcNow; + return Task.FromResult(s.Dto()); + } + } + + public async Task UploadFileAsync(string path, Guid sequenceId, string sha256, DateTime? capturedAt, CancellationToken cancellationToken) + { + var bytes = await File.ReadAllBytesAsync(path, cancellationToken); + if (Convert.ToHexStringLower(SHA256.HashData(bytes)) != sha256) + throw new TitanoApiException(HttpStatusCode.BadRequest, new ApiError("hash_mismatch", "hash")); + lock (_gate) + { + var s = Find(sequenceId); + var existing = s.Frames.FindIndex(f => f.Sha256 == sha256); + if (existing >= 0) return new CompleteUploadResponse(s.Frames[existing].Id, sequenceId, existing); + var frame = s.AddFrame(bytes, Path.GetFileName(path), capturedAt); + return new CompleteUploadResponse(frame.Id, sequenceId, s.Frames.Count - 1); + } + } + + public async Task DownloadFrameAsync(Guid frameId, string kind, Stream destination, CancellationToken cancellationToken) + { + byte[] bytes; + lock (_gate) + { + var (sequence, frame) = Sequences.Values.SelectMany(s => s.Frames.Select(f => (s, f))).FirstOrDefault(p => p.f.Id == frameId); + if (frame is null) throw NotFound(); + bytes = kind switch + { + "original" when CorruptOnce == frameId => [.. frame.Bytes.Select(b => (byte)~b)], + "original" => frame.Bytes, + "proxy" when (sequence.Status & SequenceStatus.ProxiesBuilt) != 0 => frame.Proxy, + "thumb" when (sequence.Status & SequenceStatus.ThumbsBuilt) != 0 => frame.Proxy[..Math.Min(frame.Proxy.Length, 64)], + _ => throw NotFound(), + }; + if (kind == "original" && CorruptOnce == frameId) CorruptOnce = null; + } + // Range: continue after what the destination already holds, like the real endpoint. + var offset = destination.CanSeek ? (int)Math.Min(destination.Length, bytes.Length) : 0; + if (destination.CanSeek) destination.Seek(0, SeekOrigin.End); + await destination.WriteAsync(bytes.AsMemory(offset), cancellationToken); + } + + public async IAsyncEnumerable EventsAsync([EnumeratorCancellation] CancellationToken cancellationToken) + { + while (await _events.Reader.WaitToReadAsync(cancellationToken)) + { + while (_events.Reader.TryRead(out var e)) yield return e; + } + } + + public void Dispose() + { + } + + private FakeSequence Find(Guid id) => Sequences.TryGetValue(id, out var s) ? s : throw NotFound(); + + private static TitanoApiException NotFound() => new(HttpStatusCode.NotFound, new ApiError("not_found", "sequence")); +} + +internal sealed class FakeSequence +{ + public required Guid Id { get; init; } + public string? Title { get; set; } + public List Tags { get; set; } = []; + public int Rating { get; set; } + public string? Notes { get; set; } + public string? SettingsJson { get; set; } + public int SettingsVersion { get; set; } = 1; + public int FramesVersion { get; set; } + public SequenceStatus Status { get; set; } + public DateTimeOffset UpdatedAt { get; set; } = DateTimeOffset.UtcNow; + public List Frames { get; } = []; + + public FakeFrame AddFrame(byte[] bytes, string? name = null, DateTime? capturedAt = null) + { + var frame = new FakeFrame(Guid.CreateVersion7(), name ?? $"IMG_{Frames.Count + 1:0000}.JPG", bytes, capturedAt); + Frames.Add(frame); + FramesVersion++; + UpdatedAt = DateTimeOffset.UtcNow; + return frame; + } + + public SequenceDto Dto() => new(Id, Title, Title ?? "Untitled", "2026/" + Id.ToString("N"), "Canon", "Canon EOS R5", null, null, null, Frames.Count, 10, + Frames.Sum(f => (long)f.Bytes.Length), (long)Status, 0, null, Tags, Rating, Notes, SettingsVersion, FramesVersion, 0, null, UpdatedAt); + + public SequenceManifest Manifest() => new(Id, FramesVersion, SettingsVersion, SettingsJson, Tags, + [.. Frames.Select((f, i) => new ManifestFrame(f.Id, i, f.FileName, f.Bytes.Length, f.Sha256, (Status & SequenceStatus.ProxiesBuilt) != 0, + (Status & SequenceStatus.ThumbsBuilt) != 0))], []); +} + +internal sealed record FakeFrame(Guid Id, string FileName, byte[] Bytes, DateTime? CapturedAt) +{ + public string Sha256 { get; } = Convert.ToHexStringLower(SHA256.HashData(Bytes)); + + /// The original stands in for its proxy: a real JPEG the decoders read. + public byte[] Proxy => Bytes; + + public FrameDto Dto(Guid sequenceId, int index) => + new(Id, sequenceId, index, FileName, Bytes.Length, Sha256, CapturedAt, null, 1.0 / 250, 8, 100, 24, 1, 48, 32, "jpeg", 0); +} diff --git a/tests/Titano.Data.Tests/Sync/SyncAgentTests.cs b/tests/Titano.Data.Tests/Sync/SyncAgentTests.cs new file mode 100644 index 00000000..d442bcbd --- /dev/null +++ b/tests/Titano.Data.Tests/Sync/SyncAgentTests.cs @@ -0,0 +1,99 @@ +using Titano.Core.Model; +using Titano.Data.Sync; +using Titano.Protocol; +using Titano.Testing; + +namespace Titano.Data.Tests.Sync; + +/// The background agent: event-driven comparisons, retries with backoff, proxies kept offline. +[Category("sync")] +public sealed class SyncAgentTests(TestContext context) +{ + /// Full comparisons only at start, so anything later comes from events or explicit requests. + private static readonly SyncAgentOptions EventsOnly = new() + { + RefreshInterval = TimeSpan.FromHours(1), + EventDelay = TimeSpan.FromMilliseconds(20), + MinBackoff = TimeSpan.FromMilliseconds(20), + MaxBackoff = TimeSpan.FromMilliseconds(200), + }; + + [Test] + public async Task ServerEventsBringChangesWithoutAFullComparison() + { + await using var f = await SyncFixture.CreateAsync(context); + var photos = f.NewPhotos(2); + var local = await f.LocalAsync("Harbour", photos); + var remote = f.Remote.Add("Harbour", photos); + await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct); + await using var agent = new SyncAgent(f.Sync, f.Remote, () => new SyncPolicy(), null, EventsOnly); + agent.Start(); + await WaitAsync(() => agent.Snapshot is not null, "first comparison"); + var first = agent.Snapshot!; + + f.Remote.EditSettings(remote.Id, SyncFixture.Window33); + f.Remote.Publish(new SequenceChangedEvent(remote.Id, "settings", remote.FramesVersion, remote.SettingsVersion)); + await WaitAsync(async () => SyncRules.SameSettings(SyncFixture.Window33, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson), + "the server's edit reached this PC"); + + var created = f.Remote.Add("New on the server", f.NewPhotos(1)); + f.Remote.Publish(new SequenceChangedEvent(created.Id, "created", 1, 1)); + await WaitAsync(async () => (await f.Sync.ListAsync(f.Server, f.Ct)).Any(e => e.Title == "New on the server"), "a sequence created on the server"); + Assert.Same(first, agent.Snapshot); + } + + [Test] + public async Task FailedComparisonsAreRetriedWithBackoff() + { + await using var f = await SyncFixture.CreateAsync(context); + f.Remote.Add("Harbour", f.NewPhotos(1)); + f.Remote.FailingListings = 3; + var changes = 0; + await using var agent = new SyncAgent(f.Sync, f.Remote, () => new SyncPolicy(), null, EventsOnly); + agent.Changed += () => Interlocked.Increment(ref changes); + agent.Start(); + + await WaitAsync(() => agent.Snapshot is not null, "a comparison after the failures"); + Assert.Null(agent.LastError); + Assert.Equal(0, f.Remote.FailingListings); + Assert.GreaterOrEqual(changes, 4); + Assert.Equal(1, agent.Snapshot!.ServerSequences); + } + + [Test] + public async Task KeepingProxiesOfflineQueuesThemForRemoteSequences() + { + await using var f = await SyncFixture.CreateAsync(context); + var photos = f.NewPhotos(2); + var local = await f.LocalAsync("Harbour", photos); + await f.Sync.LinkAsync(f.Server, f.Remote.Add("Harbour", photos).Id, local.Id, f.Ct); + var remote = f.Remote.Add("Construction cam", f.NewPhotos(2)); + f.Remote.Add("No proxies yet", f.NewPhotos(1), status: SequenceStatus.ThumbsBuilt); + var engine = await f.StartEngineAsync(); + var keep = false; + await using var agent = new SyncAgent(f.Sync, f.Remote, () => new SyncPolicy(KeepProxiesOffline: keep), engine, EventsOnly); + agent.Start(); + await WaitAsync(() => agent.Snapshot is not null, "first comparison"); + Assert.Null(f.Sync.OpenRemote(f.Server, remote.Id)); + + keep = true; + await agent.RefreshAsync(f.Ct); + await WaitAsync(() => f.Sync.OpenRemote(f.Server, remote.Id) is { CachedCount: 2 }, "proxies of the remote sequence"); + var entries = await f.Sync.ListAsync(f.Server, f.Ct); + Assert.Equal(SyncStatus.ProxiesOnly, entries.Single(e => e.Title == "Construction cam").Status); + Assert.Equal(SyncStatus.RemoteOnly, entries.Single(e => e.Title == "No proxies yet").Status); + Assert.Equal(SyncStatus.InSync, entries.Single(e => e.Title == "Harbour").Status); + } + + private async Task WaitAsync(Func condition, string what) => await WaitAsync(() => Task.FromResult(condition()), what); + + private async Task WaitAsync(Func> condition, string what) + { + var until = DateTime.UtcNow.AddSeconds(30); + while (!await condition()) + { + if (DateTime.UtcNow > until) Assert.Fail("Timed out waiting for " + what); + await Task.Delay(20, context.Cancellation); + } + } +} diff --git a/tests/Titano.Data.Tests/Sync/SyncFixture.cs b/tests/Titano.Data.Tests/Sync/SyncFixture.cs new file mode 100644 index 00000000..0e10ea5a --- /dev/null +++ b/tests/Titano.Data.Tests/Sync/SyncFixture.cs @@ -0,0 +1,108 @@ +using Titano.Core.Model; +using Titano.Data.Archiving; +using Titano.Data.Jobs; +using Titano.Data.Sync; +using Titano.Data.Tests.Archiving; +using Titano.Testing; + +namespace Titano.Data.Tests.Sync; + +/// A local archive and index, the sync engine over them and an in-memory server. +internal sealed class SyncFixture : IAsyncDisposable +{ + public const string Window41 = """{"exposure":{"deflickerWindow":{"isAuto":false,"manual":41}}}"""; + public const string Window33 = """{"exposure":{"deflickerWindow":{"isAuto":false,"manual":33}}}"""; + + private readonly List _owned = []; + private int _seed; + + private SyncFixture(ArchiveFixture archive, SyncService sync) + { + Archive = archive; + Sync = sync; + _owned.Add(archive); + } + + public ArchiveFixture Archive { get; } + public SyncService Sync { get; } + public FakeSyncRemote Remote { get; } = new(); + public TitanoDatabase Db => Archive.Db; + public string Server => Remote.Server; + public CancellationToken Ct => Archive.Ct; + + public static async Task CreateAsync(TestContext context) + { + var archive = await ArchiveFixture.CreateAsync(context); + var sync = new SyncService(archive.Db, archive.Service, new SyncOptions + { + Archive = new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) }, + ProxyCacheDirectory = context.CreateTempDirectory("proxies"), + }); + return new SyncFixture(archive, sync); + } + + public Task RefreshAsync(SyncPolicy? policy = null) => Sync.RefreshAsync(Remote, policy ?? new SyncPolicy(), Ct); + + public async Task EntryAsync(string title) => + (await Sync.ListAsync(Server, Ct)).Single(e => e.Title == title); + + /// Distinct photos (the same bytes on both sides make the same original). + public List NewPhotos(int count) + { + var photos = new List(count); + for (var i = 0; i < count; i++, _seed++) photos.Add(Photos.Jpeg(ArchiveFixture.Start.AddSeconds(10 * _seed), 1000 + _seed)); + return photos; + } + + /// A local sequence made through the archive ingest (hashed frames, a real sidecar). + public async Task LocalAsync(string title, IReadOnlyList originals, string? settingsJson = null) + { + Guid? id = null; + var staging = Path.Combine(Archive.Paths.StagingDirectory, "test"); + Directory.CreateDirectory(staging); + for (var i = 0; i < originals.Count; i++) + { + var path = Path.Combine(staging, $"{Guid.NewGuid():N}.part"); + await File.WriteAllBytesAsync(path, originals[i], Ct); + var sha = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(originals[i])); + var result = await Archive.Service.Ingest.CommitAsync(new IngestRequest(Archive.Archive.Id, id, id is null ? title : null, null, path, + $"IMG_{i + 1:0000}.JPG", originals[i].Length, sha, ArchiveFixture.Start.AddSeconds(10 * i), null), Ct); + id = result.SequenceId; + } + var sequence = (await Db.Sequences.GetAsync(id!.Value, Ct))!; + if (settingsJson is not null) sequence = await EditLocalSettingsAsync(sequence.Id, settingsJson); + return sequence; + } + + /// An edit on this PC, as the editor makes it (project file and index, settings version + 1). + public async Task EditLocalSettingsAsync(Guid id, string settingsJson) + { + var sequence = (await Db.Sequences.GetAsync(id, Ct))!; + var folder = Archive.Paths.Sequence(sequence.Folder); + await File.WriteAllTextAsync(folder.ProjectPath, settingsJson, Ct); + var result = await Db.Sequences.EditAsync(id, new Titano.Data.Repositories.SequenceEdit { SettingsJson = settingsJson }, sequence.SettingsVersion, Ct); + return result.Sequence!; + } + + /// A started engine with the archive and sync handlers; jobs reach the server through (the fake by default). + public async Task StartEngineAsync(ISyncConnector? connector = null) + { + var engine = new JobEngine(Db, [.. Archive.Service.CreateJobHandlers(), .. Sync.CreateJobHandlers(connector ?? new Connector(Remote))], + new JobEngineOptions { Workers = 2, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) }); + _owned.Insert(0, engine); + await engine.StartAsync(Ct); + return engine; + } + + public async ValueTask DisposeAsync() + { + foreach (var owned in _owned) await owned.DisposeAsync(); + } + + /// Hands out for its own server; null for any other, or always when is null. + public sealed class Connector(ISyncRemote? remote) : ISyncConnector + { + public ValueTask ConnectAsync(string server, CancellationToken cancellationToken) => + ValueTask.FromResult(remote is not null && remote.Server == server ? remote : null); + } +} diff --git a/tests/Titano.Data.Tests/Sync/SyncRulesTests.cs b/tests/Titano.Data.Tests/Sync/SyncRulesTests.cs new file mode 100644 index 00000000..961d44a4 --- /dev/null +++ b/tests/Titano.Data.Tests/Sync/SyncRulesTests.cs @@ -0,0 +1,97 @@ +using Titano.Core.Model; +using Titano.Data.Sync; +using Titano.Testing; + +namespace Titano.Data.Tests.Sync; + +public sealed class SyncRulesTests +{ + private static readonly Sequence Local = new() { Id = Guid.CreateVersion7(), ArchiveId = Guid.CreateVersion7(), Folder = "2026/a", SettingsVersion = 4 }; + + private static readonly SyncLink Agreed = new() + { + Server = "https://nas", + RemoteId = Guid.CreateVersion7(), + Title = "Harbour", + RemoteSettingsVersion = 7, + BaseLocalSettings = 4, + BaseRemoteSettings = 7, + }; + + [Test] + public void StateFollowsLinksOriginalsAndSettingsVersions() + { + Assert.Equal(SyncStatus.LocalOnly, SyncRules.Status(Local, null)); + Assert.Equal(SyncStatus.RemoteOnly, SyncRules.Status(null, Agreed)); + Assert.Equal(SyncStatus.ProxiesOnly, SyncRules.Status(null, Agreed with { ProxiesCached = 3 })); + Assert.Equal(SyncStatus.InSync, SyncRules.Status(Local, Agreed)); + + Assert.Equal(SyncStatus.LocalAhead, SyncRules.Status(Local, Agreed with { MissingRemote = 2 })); + Assert.Equal(SyncStatus.LocalAhead, SyncRules.Status(Local with { SettingsVersion = 5 }, Agreed)); + Assert.Equal(SyncStatus.ServerAhead, SyncRules.Status(Local, Agreed with { MissingLocal = 1 })); + Assert.Equal(SyncStatus.ServerAhead, SyncRules.Status(Local, Agreed with { RemoteSettingsVersion = 8 })); + // Originals never conflict: what this PC lacks is downloaded after what the server lacks is uploaded. + Assert.Equal(SyncStatus.LocalAhead, SyncRules.Status(Local, Agreed with { MissingRemote = 1, MissingLocal = 1 })); + + Assert.Equal(SyncStatus.Conflict, SyncRules.Status(Local with { SettingsVersion = 5 }, Agreed with { RemoteSettingsVersion = 8 })); + // A link nothing was agreed on yet: both sides count as changed until the content is compared. + Assert.Equal(SyncStatus.Conflict, SyncRules.Status(Local, Agreed with { BaseLocalSettings = null, BaseRemoteSettings = null })); + } + + [Test] + public void TheLibraryStoresOnlyStatesOfLocalCopies() + { + Assert.Equal(SyncState.InSync, SyncRules.ToSequenceState(SyncStatus.InSync)); + Assert.Equal(SyncState.Conflict, SyncRules.ToSequenceState(SyncStatus.Conflict)); + Assert.Equal(SyncState.LocalAhead, SyncRules.ToSequenceState(SyncStatus.LocalAhead)); + Assert.Equal(SyncState.ServerAhead, SyncRules.ToSequenceState(SyncStatus.ServerAhead)); + Assert.Equal(SyncState.LocalOnly, SyncRules.ToSequenceState(SyncStatus.LocalOnly)); + Assert.Null(SyncRules.ToSequenceState(SyncStatus.Transferring)); + Assert.Null(SyncRules.ToSequenceState(SyncStatus.RemoteOnly)); + } + + [Test] + public void OriginalsAreComparedByContent() + { + Assert.Equal((0, 0), SyncRules.CompareOriginals(["AA", "bb"], ["aa", "BB"])); + Assert.Equal((1, 0), SyncRules.CompareOriginals(["aa", "bb", "cc"], ["aa", "bb"])); + Assert.Equal((0, 2), SyncRules.CompareOriginals(["aa"], ["aa", "bb", "cc"])); + Assert.Equal((1, 1), SyncRules.CompareOriginals(["aa", "dd"], ["aa", "ee"])); + // Frames not hashed yet (adopted, not verified) stand for server frames no hash matched. + Assert.Equal((0, 0), SyncRules.CompareOriginals(["aa", null, null], ["aa", "bb", "cc"])); + Assert.Equal((0, 1), SyncRules.CompareOriginals([null], ["bb", "cc"])); + Assert.Equal((1, 0), SyncRules.CompareOriginals([null, null], ["bb"])); + } + + [Test] + public void SettingsAreComparedAsProjectsNotAsText() + { + Assert.True(SyncRules.SameSettings(null, "{}"), "no settings is the default project"); + Assert.True(SyncRules.SameSettings(SyncFixture.Window41, "{ \"exposure\": { \"deflickerWindow\": { \"manual\": 41, \"isAuto\": false } } }")); + Assert.False(SyncRules.SameSettings(SyncFixture.Window41, SyncFixture.Window33)); + + var difference = Assert.Contains(SyncRules.Differences(SyncFixture.Window41, SyncFixture.Window33), d => d.Path.StartsWith("exposure.deflickerWindow", StringComparison.Ordinal)); + Assert.Equal("exposure.deflickerWindow.manual", difference.Path); + Assert.Equal("41", difference.Mine); + Assert.Equal("33", difference.Theirs); + Assert.Count(1, SyncRules.Differences("""{"exposure":{"exposureOffsetEv":1},"stack":{"length":3}}""", "{}", max: 1)); + Assert.Empty(SyncRules.Differences(SyncFixture.Window33, SyncFixture.Window33)); + } + + [Test] + public void MetadataMergeUnitesTagsAndTakesTheRestFromTheNewerSide() + { + var mine = new SyncPayload("Harbour", ["sunset", "Harbour"], 3, "mine", SyncFixture.Window41); + var theirs = new SyncPayload("Harbour at dusk", ["harbour", "boats"], 5, null, SyncFixture.Window41); + + var newerHere = SyncRules.Merge(mine, theirs, localIsNewer: true); + Assert.Equal("Harbour", newerHere.Title); + Assert.Equal(3, newerHere.Rating); + Assert.SequenceEqual(["sunset", "Harbour", "boats"], newerHere.Tags); + + var newerThere = SyncRules.Merge(mine, theirs, localIsNewer: false); + Assert.Equal("Harbour at dusk", newerThere.Title); + Assert.Null(newerThere.Notes); + Assert.True(newerThere.SameMetadata(newerThere with { Tags = ["BOATS", "harbour", "SUNSET"] }), "tags ignore case and order"); + } +} diff --git a/tests/Titano.Data.Tests/Sync/SyncServiceTests.cs b/tests/Titano.Data.Tests/Sync/SyncServiceTests.cs new file mode 100644 index 00000000..f82f3ee3 --- /dev/null +++ b/tests/Titano.Data.Tests/Sync/SyncServiceTests.cs @@ -0,0 +1,285 @@ +using Titano.Core.Model; +using Titano.Data.Sync; +using Titano.Protocol; +using Titano.Protocol.Client; +using Titano.Testing; + +namespace Titano.Data.Tests.Sync; + +/// Comparison, settings exchange and conflict resolution against an in-memory server. +[Category("sync")] +public sealed class SyncServiceTests(TestContext context) +{ + [Test] + public async Task TheTableListsLocalAndServerSequences() + { + await using var f = await SyncFixture.CreateAsync(context); + await f.LocalAsync("Comet", f.NewPhotos(2)); + f.Remote.Add("Construction cam", f.NewPhotos(3)); + + var snapshot = await f.RefreshAsync(); + + Assert.Equal(2, snapshot.Entries.Count); + Assert.Equal(1, snapshot.ServerSequences); + Assert.Equal(SyncStatus.LocalOnly, (await f.EntryAsync("Comet")).Status); + var remote = await f.EntryAsync("Construction cam"); + Assert.Equal(SyncStatus.RemoteOnly, remote.Status); + Assert.Null(remote.Local); + Assert.Equal(3, remote.Link!.FrameCount); + } + + [Test] + public async Task LinkedCopiesWithTheSameOriginalsAreInSyncAndTheLibraryKnows() + { + await using var f = await SyncFixture.CreateAsync(context); + var photos = f.NewPhotos(3); + var local = await f.LocalAsync("Harbour", photos); + var remote = f.Remote.Add("Harbour", photos); + await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct); + + await f.RefreshAsync(); + Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status); + Assert.Equal(SyncState.InSync, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SyncState); + + // Nothing moved: the manifest is not fetched again. + var manifests = f.Remote.ManifestCalls; + await f.RefreshAsync(); + Assert.Equal(manifests, f.Remote.ManifestCalls); + } + + [Test] + public async Task OriginalsMissingOnEitherSideAreCountedFromTheManifest() + { + await using var f = await SyncFixture.CreateAsync(context); + var photos = f.NewPhotos(4); + var local = await f.LocalAsync("Harbour", photos[..3]); + var remote = f.Remote.Add("Harbour", photos[..2]); + await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct); + + await f.RefreshAsync(); + var ahead = await f.EntryAsync("Harbour"); + Assert.Equal(SyncStatus.LocalAhead, ahead.Status); + Assert.Equal(1, ahead.Link!.MissingRemote); + Assert.Equal(SyncState.LocalAhead, ahead.Local!.SyncState); + + remote.AddFrame(photos[2]); + remote.AddFrame(photos[3]); + await f.RefreshAsync(); + var behind = await f.EntryAsync("Harbour"); + Assert.Equal(SyncStatus.ServerAhead, behind.Status); + Assert.Equal((0, 1), (behind.Link!.MissingRemote, behind.Link.MissingLocal)); + } + + [Test] + public async Task SettingsChangedOnOneSideAreSentOrTaken() + { + await using var f = await SyncFixture.CreateAsync(context); + var photos = f.NewPhotos(2); + var local = await f.LocalAsync("Harbour", photos); + var remote = f.Remote.Add("Harbour", photos); + await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct); + await f.RefreshAsync(); + + await f.EditLocalSettingsAsync(local.Id, SyncFixture.Window41); + await f.RefreshAsync(); + Assert.True(SyncRules.SameSettings(SyncFixture.Window41, remote.SettingsJson), "this PC's edit reached the server"); + Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status); + + f.Remote.EditSettings(remote.Id, SyncFixture.Window33); + await f.RefreshAsync(); + var taken = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!; + Assert.True(SyncRules.SameSettings(SyncFixture.Window33, taken.SettingsJson), "the server's edit reached this PC"); + var project = await File.ReadAllTextAsync(f.Archive.Paths.Sequence(taken.Folder).ProjectPath, f.Ct); + Assert.True(SyncRules.SameSettings(SyncFixture.Window33, project), "project.json follows the index"); + Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status); + } + + [Test] + public async Task WithoutAutomaticSyncAnEditWaitsForTheUser() + { + await using var f = await SyncFixture.CreateAsync(context); + var photos = f.NewPhotos(1); + var local = await f.LocalAsync("Harbour", photos); + var remote = f.Remote.Add("Harbour", photos); + await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct); + await f.RefreshAsync(); + + await f.EditLocalSettingsAsync(local.Id, SyncFixture.Window41); + await f.RefreshAsync(new SyncPolicy(AutoSyncSettings: false)); + Assert.Equal(SyncStatus.LocalAhead, (await f.EntryAsync("Harbour")).Status); + Assert.Null(remote.SettingsJson); + + await f.Sync.SyncSettingsAsync(f.Remote, remote.Id, f.Ct); + Assert.True(SyncRules.SameSettings(SyncFixture.Window41, remote.SettingsJson)); + Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status); + } + + [Test] + public async Task OnlyMetadataChangedOnBothSidesIsMergedWithoutAConflict() + { + await using var f = await SyncFixture.CreateAsync(context); + var photos = f.NewPhotos(1); + var local = await f.LocalAsync("Harbour", photos); + var remote = f.Remote.Add("Harbour", photos); + await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct); + await f.RefreshAsync(); + + // The server is edited first, so this PC's later title and rating win; tags are united. + await f.Remote.UpdateSequenceAsync(remote.Id, new UpdateSequenceRequest(null, ["boats"], 2, null, null, null), f.Ct); + await Task.Delay(20, f.Ct); + await f.Archive.Service.SetSequenceInfoAsync(local.Id, "Harbour", ["sunset"], 4, null, f.Ct); + await f.RefreshAsync(); + + Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status); + var merged = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!; + Assert.True(merged.Tags.ToHashSet().SetEquals(["sunset", "boats"]), string.Join(",", merged.Tags)); + Assert.True(remote.Tags.ToHashSet().SetEquals(["sunset", "boats"]), string.Join(",", remote.Tags)); + Assert.Equal(4, remote.Rating); + } + + [Test] + public async Task SettingsChangedOnBothSidesAreAConflictUntilTheUserPicks() + { + await using var f = await SyncFixture.CreateAsync(context); + var (local, remote) = await ConflictAsync(f); + + var entry = await f.EntryAsync("Holy grail"); + Assert.Equal(SyncStatus.Conflict, entry.Status); + Assert.Equal(SyncState.Conflict, entry.Local!.SyncState); + Assert.True(SyncRules.SameSettings(SyncFixture.Window33, entry.Link!.ConflictSettingsJson), "the server's side is kept for display"); + Assert.Equal("exposure.deflickerWindow.manual", SyncRules.Differences(entry.Local.SettingsJson, entry.Link.ConflictSettingsJson)[0].Path); + + // Neither side is overwritten while the conflict stands, and the comparison does not fetch it again. + var manifests = f.Remote.ManifestCalls; + await f.RefreshAsync(); + Assert.True(SyncRules.SameSettings(SyncFixture.Window33, remote.SettingsJson)); + Assert.True(SyncRules.SameSettings(SyncFixture.Window41, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson)); + Assert.Equal(manifests, f.Remote.ManifestCalls); + } + + [Test] + public async Task KeepMineSendsThisPcsSettings() + { + await using var f = await SyncFixture.CreateAsync(context); + var (local, remote) = await ConflictAsync(f); + + await f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.KeepMine, f.Ct); + + Assert.True(SyncRules.SameSettings(SyncFixture.Window41, remote.SettingsJson)); + Assert.True(SyncRules.SameSettings(SyncFixture.Window41, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson)); + Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Holy grail")).Status); + await f.RefreshAsync(); + Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Holy grail")).Status); + } + + [Test] + public async Task TakeServerReplacesThisPcsSettings() + { + await using var f = await SyncFixture.CreateAsync(context); + var (local, remote) = await ConflictAsync(f); + + await f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.TakeServer, f.Ct); + + var taken = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!; + Assert.True(SyncRules.SameSettings(SyncFixture.Window33, taken.SettingsJson)); + Assert.True(SyncRules.SameSettings(SyncFixture.Window33, await File.ReadAllTextAsync(f.Archive.Paths.Sequence(taken.Folder).ProjectPath, f.Ct))); + Assert.True(SyncRules.SameSettings(SyncFixture.Window33, remote.SettingsJson)); + Assert.Empty(Directory.GetFiles(f.Archive.Paths.Sequence(taken.Folder).MetaDirectory, "project.local-*.json")); + Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Holy grail")).Status); + } + + [Test] + public async Task SaveBothKeepsThisPcsSettingsNextToTheServers() + { + await using var f = await SyncFixture.CreateAsync(context); + var (local, remote) = await ConflictAsync(f); + + await f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.SaveBoth, f.Ct); + + var taken = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!; + Assert.True(SyncRules.SameSettings(SyncFixture.Window33, taken.SettingsJson)); + var copy = Assert.Contains(Directory.GetFiles(f.Archive.Paths.Sequence(taken.Folder).MetaDirectory, "project.local-*.json"), _ => true); + Assert.True(SyncRules.SameSettings(SyncFixture.Window41, await File.ReadAllTextAsync(copy, f.Ct)), "this PC's version is kept"); + Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Holy grail")).Status); + } + + [Test] + public async Task KeepMineRefusesWhenTheServerChangedAgainMeanwhile() + { + await using var f = await SyncFixture.CreateAsync(context); + var (_, remote) = await ConflictAsync(f); + var racing = new RacingRemote(f.Remote, () => f.Remote.EditSettings(remote.Id, SyncFixture.Window33.Replace("33", "35", StringComparison.Ordinal))); + + var error = await Assert.ThrowsAsync(() => f.Sync.ResolveAsync(racing, remote.Id, SyncResolution.KeepMine, f.Ct)); + Assert.Equal(System.Net.HttpStatusCode.Conflict, error.Status); + Assert.True(SyncRules.SameSettings(SyncFixture.Window33.Replace("33", "35", StringComparison.Ordinal), remote.SettingsJson), "nothing overwritten"); + } + + [Test] + public async Task SequencesDeletedOnTheServerAreForgotten() + { + await using var f = await SyncFixture.CreateAsync(context); + var photos = f.NewPhotos(1); + var local = await f.LocalAsync("Harbour", photos); + var remote = f.Remote.Add("Harbour", photos); + f.Remote.Add("Gone", f.NewPhotos(1)); + await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct); + await f.RefreshAsync(); + + f.Remote.Sequences.Clear(); + var snapshot = await f.RefreshAsync(); + + Assert.Equal(0, snapshot.ServerSequences); + Assert.Equal(SyncStatus.LocalOnly, (await f.EntryAsync("Harbour")).Status); + Assert.Equal(SyncState.LocalOnly, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SyncState); + } + + /// A linked sequence whose settings changed differently on both sides since they last agreed (41 here, 33 on the server). + private static async Task<(Sequence Local, FakeSequence Remote)> ConflictAsync(SyncFixture f) + { + var photos = f.NewPhotos(2); + var local = await f.LocalAsync("Holy grail", photos); + var remote = f.Remote.Add("Holy grail", photos); + await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct); + await f.RefreshAsync(); + Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Holy grail")).Status); + + local = await f.EditLocalSettingsAsync(local.Id, SyncFixture.Window41); + f.Remote.EditSettings(remote.Id, SyncFixture.Window33); + await f.RefreshAsync(); + return (local, remote); + } + + /// A remote where someone else edits the settings right after the first read of a sequence. + private sealed class RacingRemote(FakeSyncRemote inner, Action race) : ISyncRemote + { + private Action? _race = race; + + public string Server => inner.Server; + + public async Task GetSequenceAsync(Guid id, CancellationToken cancellationToken) + { + var dto = await inner.GetSequenceAsync(id, cancellationToken); + Interlocked.Exchange(ref _race, null)?.Invoke(); + return dto; + } + + public Task> ListSequencesAsync(CancellationToken cancellationToken) => inner.ListSequencesAsync(cancellationToken); + public Task GetManifestAsync(Guid id, CancellationToken cancellationToken) => inner.GetManifestAsync(id, cancellationToken); + public Task> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken) => inner.ListFramesAsync(sequenceId, cancellationToken); + public Task CreateSequenceAsync(CreateSequenceRequest request, CancellationToken cancellationToken) => inner.CreateSequenceAsync(request, cancellationToken); + public Task UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken) => inner.UpdateSequenceAsync(id, request, cancellationToken); + + public Task UploadFileAsync(string path, Guid sequenceId, string sha256, DateTime? capturedAt, CancellationToken cancellationToken) => + inner.UploadFileAsync(path, sequenceId, sha256, capturedAt, cancellationToken); + + public Task DownloadFrameAsync(Guid frameId, string kind, Stream destination, CancellationToken cancellationToken) => + inner.DownloadFrameAsync(frameId, kind, destination, cancellationToken); + + public IAsyncEnumerable EventsAsync(CancellationToken cancellationToken) => inner.EventsAsync(cancellationToken); + + public void Dispose() + { + } + } +} diff --git a/tests/Titano.Data.Tests/Sync/SyncTransferTests.cs b/tests/Titano.Data.Tests/Sync/SyncTransferTests.cs new file mode 100644 index 00000000..e348082e --- /dev/null +++ b/tests/Titano.Data.Tests/Sync/SyncTransferTests.cs @@ -0,0 +1,196 @@ +using Titano.Core.Imaging; +using Titano.Core.Imaging.Decoders; +using Titano.Core.Model; +using Titano.Core.Render; +using Titano.Data.Sync; +using Titano.Testing; + +namespace Titano.Data.Tests.Sync; + +/// Upload, download and proxy jobs on the job engine against an in-memory server. +[Category("sync")] +public sealed class SyncTransferTests(TestContext context) +{ + [Test] + public async Task UploadSendsTheOriginalsAndSettingsOfALocalSequence() + { + await using var f = await SyncFixture.CreateAsync(context); + var photos = f.NewPhotos(3); + var local = await f.LocalAsync("Comet", photos, SyncFixture.Window41); + var engine = await f.StartEngineAsync(); + + var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local); + Assert.Equal(job.Id, (await f.Sync.EnqueueUploadAsync(engine, f.Server, local)).Id); + var done = await f.Archive.WaitForAsync(job.Id, JobState.Done); + + Assert.Equal((3L, 3L), (done.ProgressDone, done.ProgressTotal)); + var remote = Assert.Contains(f.Remote.Sequences.Values, s => s.Title == "Comet"); + Assert.True(remote.Frames.Select(r => r.Sha256).ToHashSet().SetEquals(photos.Select(Sha)), "every original arrived"); + Assert.True(SyncRules.SameSettings(SyncFixture.Window41, remote.SettingsJson), "the settings travel with the originals"); + var entry = await f.EntryAsync("Comet"); + Assert.Equal(SyncStatus.InSync, entry.Status); + Assert.Equal(remote.Id, entry.Link!.RemoteId); + } + + [Test] + public async Task AResumedUploadSendsOnlyWhatTheServerLacks() + { + await using var f = await SyncFixture.CreateAsync(context); + var photos = f.NewPhotos(4); + var local = await f.LocalAsync("Comet", photos); + // A crashed attempt had created the server sequence and sent two originals. + var remote = f.Remote.Add("Comet", photos[..2]); + var engine = await f.StartEngineAsync(); + var job = await f.Archive.EnqueueWithCheckpointAsync(engine, + new(JobKind.UploadCommit, [local.Id], "Comet", """{"server":"https://nas.test:8443"}""", JobPriority.User), remote.Id.ToString()); + + await f.Archive.WaitForAsync(job.Id, JobState.Done); + + Assert.Count(1, f.Remote.Sequences.Values); + Assert.Equal(4, remote.Frames.Count); + Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Comet")).Status); + } + + [Test] + public async Task OriginalsChangedSinceTheyWereArchivedAreNeverUploaded() + { + await using var f = await SyncFixture.CreateAsync(context); + var local = await f.LocalAsync("Comet", f.NewPhotos(3)); + var damaged = (await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct))[1]; + var path = f.Archive.Paths.FromRelative(damaged.RelativePath); + var bytes = await File.ReadAllBytesAsync(path, f.Ct); + bytes[^3] ^= 0xFF; + await File.WriteAllBytesAsync(path, bytes, f.Ct); + var engine = await f.StartEngineAsync(); + + var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local); + var failed = await f.Archive.WaitForAsync(job.Id, JobState.Failed); + + Assert.Contains("1", failed.Error); + var remote = Assert.Contains(f.Remote.Sequences.Values, s => s.Title == "Comet"); + Assert.Equal(2, remote.Frames.Count); + Assert.DoesNotContain(damaged.Sha256!, remote.Frames.Select(r => r.Sha256)); + Assert.Equal(SyncStatus.LocalAhead, (await f.EntryAsync("Comet")).Status); + } + + [Test] + public async Task DownloadedOriginalsAreVerifiedAndCommittedThroughTheArchive() + { + await using var f = await SyncFixture.CreateAsync(context); + var photos = f.NewPhotos(3); + var remote = f.Remote.Add("Construction cam", photos, SyncFixture.Window33); + remote.Tags = ["site"]; + f.Remote.CorruptOnce = remote.Frames[1].Id; + await f.RefreshAsync(); + var engine = await f.StartEngineAsync(); + + var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Construction cam", SyncDownloadMode.Originals, f.Archive.Archive.Id); + await f.Archive.WaitForAsync(job.Id, JobState.Done); + + var entry = await f.EntryAsync("Construction cam"); + Assert.Equal(SyncStatus.InSync, entry.Status); + var local = Assert.NotNull(entry.Local); + Assert.Equal(SequenceOrigin.Server, local.Origin); + Assert.True(SyncRules.SameSettings(SyncFixture.Window33, local.SettingsJson), "the server's settings came along"); + Assert.SequenceEqual(["site"], local.Tags); + var frames = await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct); + Assert.Equal(3, frames.Count); + foreach (var frame in frames) + { + var bytes = await File.ReadAllBytesAsync(f.Archive.Paths.FromRelative(frame.RelativePath), f.Ct); + Assert.Equal(frame.Sha256, Sha(bytes)); + } + Assert.True(frames.Select(r => r.Sha256).ToHashSet().SetEquals(photos.Select(Sha)), "the damaged transfer was fetched again"); + Assert.FileExists(f.Archive.Paths.Sequence(local.Folder).ManifestPath); + Assert.False(Directory.Exists(Path.Combine(f.Archive.Paths.StagingDirectory, "sync-" + remote.Id.ToString("N"))), "staging cleaned up"); + } + + [Test] + public async Task DownloadFillsInWhatALocalCopyLacks() + { + await using var f = await SyncFixture.CreateAsync(context); + var photos = f.NewPhotos(3); + var local = await f.LocalAsync("Harbour", photos[..1], SyncFixture.Window41); + var remote = f.Remote.Add("Harbour", photos); + await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct); + await f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.KeepMine, f.Ct); + var engine = await f.StartEngineAsync(); + + var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Harbour", SyncDownloadMode.Originals, null); + await f.Archive.WaitForAsync(job.Id, JobState.Done); + + Assert.Equal(3, (await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct)).Count); + var entry = await f.EntryAsync("Harbour"); + Assert.Equal(SyncStatus.InSync, entry.Status); + Assert.Equal(SequenceOrigin.Local, entry.Local!.Origin); + Assert.True(SyncRules.SameSettings(SyncFixture.Window41, entry.Local.SettingsJson), "an existing copy keeps its settings"); + } + + [Test] + public async Task ProxiesOpenARemoteSequenceForTheEditor() + { + await using var f = await SyncFixture.CreateAsync(context); + var remote = f.Remote.Add("Milan skyline", f.NewPhotos(3), SyncFixture.Window33); + await f.RefreshAsync(); + Assert.Null(f.Sync.OpenRemote(f.Server, remote.Id)); + var engine = await f.StartEngineAsync(); + + var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Milan skyline", SyncDownloadMode.Proxies, null); + await f.Archive.WaitForAsync(job.Id, JobState.Done); + + var entry = await f.EntryAsync("Milan skyline"); + Assert.Equal(SyncStatus.ProxiesOnly, entry.Status); + Assert.Equal(3, entry.Link!.ProxiesCached); + Assert.False(entry.Link.ProxiesStale); + var opened = Assert.NotNull(f.Sync.OpenRemote(f.Server, remote.Id)); + Assert.Equal(remote.Id, opened.Sequence.Id); + Assert.Equal(SequenceOrigin.Server, opened.Sequence.Origin); + Assert.True(SyncRules.SameSettings(SyncFixture.Window33, opened.Sequence.SettingsJson)); + Assert.Equal(3, opened.CachedCount); + + var source = opened.OpenFrames(DecoderFactory.CreateServer()); + await using (source as IAsyncDisposable) + { + Assert.Equal(3, source.FrameCount); + using var frame = await source.GetFrameAsync(2, 0, DecodePurpose.Render, f.Ct); + Assert.Equal((48, 32), (frame.Width, frame.Height)); + } + + // Nothing local was created, and a frame added on the server makes the cache stale. + Assert.Null(entry.Local); + remote.AddFrame(f.NewPhotos(1)[0]); + await f.RefreshAsync(); + Assert.True((await f.EntryAsync("Milan skyline")).Link!.ProxiesStale); + } + + [Test] + public async Task ThumbnailsStandInWhenTheServerHasNoProxies() + { + await using var f = await SyncFixture.CreateAsync(context); + var remote = f.Remote.Add("Fog", f.NewPhotos(2), status: SequenceStatus.ThumbsBuilt); + var engine = await f.StartEngineAsync(); + + var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Fog", SyncDownloadMode.Proxies, null); + await f.Archive.WaitForAsync(job.Id, JobState.Done); + + var opened = Assert.NotNull(f.Sync.OpenRemote(f.Server, remote.Id)); + Assert.Equal(2, opened.CachedCount); + Assert.True(opened.Files.All(file => new FileInfo(file!).Length == 64), "thumbnails"); + } + + [Test] + public async Task TransfersFailWithAReasonWhenThisPcIsNotConnected() + { + await using var f = await SyncFixture.CreateAsync(context); + var local = await f.LocalAsync("Comet", f.NewPhotos(1)); + var engine = await f.StartEngineAsync(new SyncFixture.Connector(null)); + + var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local); + var failed = await f.Archive.WaitForAsync(job.Id, JobState.Failed); + + Assert.Equal(Titano.Core.Localization.Loc.L("Errors.Sync.NotConnected"), failed.Error); + Assert.Empty(f.Remote.Sequences); + } + + private static string Sha(byte[] bytes) => Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(bytes)); +} From c02d1867d0c802ee580580fe29bcc3b13606d164 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 22:44:20 +0000 Subject: [PATCH 3/8] test(sync): upload, download, resume, proxies and live events against the real server The first original of an upload now creates the server sequence through its session key (the archive ingest files API-created empty sequences nowhere), and settings sent after an upload are retried when the server's own analysis edits the new sequence meanwhile. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- i18n/en/Errors.resx | 1 + i18n/it/Errors.it.resx | 1 + src/Titano.Data/Sync/SyncRemote.cs | 19 +- src/Titano.Data/Sync/SyncService.cs | 25 ++- src/Titano.Data/Sync/SyncTransfers.cs | 63 ++++-- .../Titano.Data.Tests/Sync/FakeSyncRemote.cs | 28 ++- .../Sync/SyncServiceTests.cs | 6 +- tests/Titano.Server.Tests/Sync/SyncClient.cs | 120 ++++++++++ .../Sync/SyncServerTests.cs | 206 ++++++++++++++++++ 9 files changed, 420 insertions(+), 49 deletions(-) create mode 100644 tests/Titano.Server.Tests/Sync/SyncClient.cs create mode 100644 tests/Titano.Server.Tests/Sync/SyncServerTests.cs diff --git a/i18n/en/Errors.resx b/i18n/en/Errors.resx index 6018a270..7391b68d 100644 --- a/i18n/en/Errors.resx +++ b/i18n/en/Errors.resx @@ -23,6 +23,7 @@ The sequence is no longer in this PC's archive index. Open or create an archive on this PC to receive the originals. Not connected to this server; connect and retry the job. + No original reached the server: they are missing here or already in another server sequence. {0} original is missing or changed since it was archived; verify the archive.{0} count {0} originals are missing or changed since they were archived; verify the archive.{0} count The template is empty. diff --git a/i18n/it/Errors.it.resx b/i18n/it/Errors.it.resx index aee44508..7bc74c12 100644 --- a/i18n/it/Errors.it.resx +++ b/i18n/it/Errors.it.resx @@ -23,6 +23,7 @@ La sequenza non è più nell'indice dell'archivio di questo PC. Apri o crea un archivio su questo PC per ricevere gli originali. Non connesso a questo server; collegati e riprova l'attività. + Nessun originale è arrivato al server: mancano qui o sono già in un'altra sequenza del server. {0} originale manca o è cambiato dopo l'archiviazione; verifica l'archivio. {0} originali mancano o sono cambiati dopo l'archiviazione; verifica l'archivio. Il modello è vuoto. diff --git a/src/Titano.Data/Sync/SyncRemote.cs b/src/Titano.Data/Sync/SyncRemote.cs index a4b8a8fc..70194202 100644 --- a/src/Titano.Data/Sync/SyncRemote.cs +++ b/src/Titano.Data/Sync/SyncRemote.cs @@ -23,16 +23,17 @@ public interface ISyncRemote : IDisposable /// Every frame row of a sequence, in index order. Task> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken); - Task CreateSequenceAsync(CreateSequenceRequest request, CancellationToken cancellationToken); - /// A 409 means the settings version moved on the server. Task UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken); /// - /// Chunked, resumable upload of one original that the server verifies against before - /// committing it (BRIEF §14.4); see . + /// Chunked, resumable upload of one original into , or into the sequence the server + /// files under (created by the first one); the server verifies + /// before committing it (BRIEF §14.4). An original the server already holds is not sent again: the response then + /// names ( without one). See . /// - Task UploadFileAsync(string path, Guid sequenceId, string sha256, DateTime? capturedAt, CancellationToken cancellationToken); + Task UploadFileAsync(string path, Guid? sequenceId, string? sessionKey, string sha256, DateTime? capturedAt, + CancellationToken cancellationToken); /// Streams a frame's original, proxy or thumb, resuming with Range from the destination's length. Task DownloadFrameAsync(Guid frameId, string kind, Stream destination, CancellationToken cancellationToken); @@ -88,14 +89,12 @@ public sealed class TitanoSyncRemote(TitanoClient client, bool ownsClient) : ISy return all; } - public Task CreateSequenceAsync(CreateSequenceRequest request, CancellationToken cancellationToken) => - client.CreateSequenceAsync(request, cancellationToken); - public Task UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken) => client.UpdateSequenceAsync(id, request, cancellationToken); - public Task UploadFileAsync(string path, Guid sequenceId, string sha256, DateTime? capturedAt, CancellationToken cancellationToken) => - client.UploadFileAsync(path, sequenceId, capturedAt, null, sha256, null, cancellationToken); + public Task UploadFileAsync(string path, Guid? sequenceId, string? sessionKey, string sha256, DateTime? capturedAt, + CancellationToken cancellationToken) => + client.UploadFileAsync(path, sequenceId, capturedAt, sessionKey, sha256, null, cancellationToken); public Task DownloadFrameAsync(Guid frameId, string kind, Stream destination, CancellationToken cancellationToken) => client.DownloadFrameAsync(frameId, kind, destination, null, cancellationToken); diff --git a/src/Titano.Data/Sync/SyncService.cs b/src/Titano.Data/Sync/SyncService.cs index 72121690..dce35e76 100644 --- a/src/Titano.Data/Sync/SyncService.cs +++ b/src/Titano.Data/Sync/SyncService.cs @@ -260,17 +260,32 @@ public sealed class SyncService return link; } - /// Makes the server's copy equal to this PC's (an upload sends the settings with the originals). + /// + /// 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); - var dto = await remote.GetSequenceAsync(remoteId, cancellationToken).ConfigureAwait(false); - var updated = await remote.UpdateSequenceAsync(remoteId, SyncPayload.Of(local).ToRequest(dto.SettingsVersion), cancellationToken).ConfigureAwait(false); - await _links.UpsertAsync(Agreed(Observe(link, remote.Server, updated), local.SettingsVersion, updated.SettingsVersion), cancellationToken) - .ConfigureAwait(false); + for (var attempt = 1; ; attempt++) + { + var dto = await remote.GetSequenceAsync(remoteId, cancellationToken).ConfigureAwait(false); + try + { + var updated = await remote.UpdateSequenceAsync(remoteId, SyncPayload.Of(local).ToRequest(dto.SettingsVersion), cancellationToken) + .ConfigureAwait(false); + await _links.UpsertAsync(Agreed(Observe(link, remote.Server, updated), local.SettingsVersion, updated.SettingsVersion), cancellationToken) + .ConfigureAwait(false); + return; + } + catch (TitanoApiException 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 { diff --git a/src/Titano.Data/Sync/SyncTransfers.cs b/src/Titano.Data/Sync/SyncTransfers.cs index 4747f117..9f993d92 100644 --- a/src/Titano.Data/Sync/SyncTransfers.cs +++ b/src/Titano.Data/Sync/SyncTransfers.cs @@ -38,22 +38,41 @@ internal sealed class SyncTransfers(SyncService sync) 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 present = remoteId is { } known + ? (await remote.GetManifestAsync(known, ct).ConfigureAwait(false)).Frames.Select(f => f.Sha256.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal) + : []; + var pending = new Queue(frames.Where(f => f.Sha256 is null || !present.Contains(f.Sha256.ToLowerInvariant()))); var progress = new TransferProgress(context, frames.Count, frames.Count - pending.Count); await progress.ReportAsync().ConfigureAwait(false); var skipped = 0; + + // Without a server sequence the originals go out one by one under this sequence's session key until the + // server has filed one, which creates the sequence (an original it already holds elsewhere creates nothing). + while (remoteId is null && pending.TryDequeue(out var first)) + { + var sent = await UploadFrameAsync(context, remote, null, SyncService.SessionKey(local.Id), paths.FromRelative(first.RelativePath), first, ct) + .ConfigureAwait(false); + if (sent is null) skipped++; + else if (sent.SequenceId != Guid.Empty) + { + remoteId = sent.SequenceId; + await context.CheckpointAsync(sent.SequenceId.ToString(), progress.Done + 1, frames.Count).ConfigureAwait(false); + await sync.LinkAsync(remote.Server, sent.SequenceId, local, ct).ConfigureAwait(false); + } + await progress.StepAsync().ConfigureAwait(false); + } + if (remoteId is not { } target) throw new InvalidOperationException(Loc.L("Errors.Sync.NothingSent")); + 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)) + if (await UploadFrameAsync(context, remote, target, null, paths.FromRelative(frame.RelativePath), frame, token).ConfigureAwait(false) is null) 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 (created) await sync.PushAllAsync(remote, target, ct).ConfigureAwait(false); + await sync.RefreshSequencesAsync(remote, [target], CompareOnly, ct).ConfigureAwait(false); if (skipped > 0) throw new InvalidDataException(Loc.Plural("Errors.Sync.Unreadable", skipped)); } @@ -139,8 +158,11 @@ internal sealed class SyncTransfers(SyncService sync) if (cached < frames.Count) context.Log($"{frames.Count - cached} frame(s) have neither proxy nor thumbnail on the server"); } - /// The server sequence an upload fills and whether this job created it: the linked one, one an interrupted attempt created, or a new one. - private async Task<(Guid RemoteId, bool Created)> TargetAsync(JobContext context, ISyncRemote remote, Sequence local) + /// + /// The server sequence an upload fills and whether this job creates it: the linked one, the one an interrupted + /// attempt created, or none yet (the first original creates it). + /// + 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; @@ -153,13 +175,10 @@ internal sealed class SyncTransfers(SyncService sync) 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. + // Deleted on the server meanwhile: the originals go 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); + return (null, true); } private static async Task ExistsAsync(ISyncRemote remote, Guid id, CancellationToken cancellationToken) @@ -175,22 +194,26 @@ internal sealed class SyncTransfers(SyncService sync) } } - /// Hashes the original again and sends it; false (logged) when it is gone or no longer the archived file. - private static async Task UploadFrameAsync(JobContext context, ISyncRemote remote, Guid remoteId, string path, Frame frame, CancellationToken cancellationToken) + /// + /// Hashes the original again and sends it into (or the sequence of + /// ); null (logged) when it is gone or no longer the archived file. + /// + private static async Task UploadFrameAsync(JobContext context, ISyncRemote remote, Guid? sequenceId, string? sessionKey, string path, + Frame frame, CancellationToken cancellationToken) { if (!File.Exists(path)) { context.Log($"{frame.FileName}: missing, not uploaded"); - return false; + return null; } 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; + return null; } - await remote.UploadFileAsync(path, remoteId, sha, frame.CapturedAt, cancellationToken).ConfigureAwait(false); - return true; + return await remote.UploadFileAsync(path, sequenceId, sessionKey, sha, frame.CapturedAt, cancellationToken).ConfigureAwait(false) + ?? new CompleteUploadResponse(Guid.Empty, sequenceId ?? Guid.Empty, -1); } /// Downloads one original into staging and commits it into the local sequence (created from the server id when null). @@ -325,6 +348,8 @@ internal sealed class SyncTransfers(SyncService sync) } } + public long Done => done; + public ValueTask ReportAsync() => context.ReportAsync(done, total); } } diff --git a/tests/Titano.Data.Tests/Sync/FakeSyncRemote.cs b/tests/Titano.Data.Tests/Sync/FakeSyncRemote.cs index 14d7ee67..50d497cc 100644 --- a/tests/Titano.Data.Tests/Sync/FakeSyncRemote.cs +++ b/tests/Titano.Data.Tests/Sync/FakeSyncRemote.cs @@ -14,6 +14,7 @@ internal sealed class FakeSyncRemote : ISyncRemote { private readonly Lock _gate = new(); private readonly Channel _events = Channel.CreateUnbounded(); + private readonly Dictionary _sessions = []; public string Server => "https://nas.test:8443"; @@ -83,12 +84,6 @@ internal sealed class FakeSyncRemote : ISyncRemote lock (_gate) return Task.FromResult>([.. Find(sequenceId).Frames.Select((f, i) => f.Dto(sequenceId, i))]); } - public Task CreateSequenceAsync(CreateSequenceRequest request, CancellationToken cancellationToken) - { - var sequence = Add(request.Title, []); - return Task.FromResult(sequence.Dto()); - } - public Task UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken) { lock (_gate) @@ -107,18 +102,27 @@ internal sealed class FakeSyncRemote : ISyncRemote } } - public async Task UploadFileAsync(string path, Guid sequenceId, string sha256, DateTime? capturedAt, CancellationToken cancellationToken) + /// Like the server: content it already holds anywhere is not stored again; a session key files the first original into a new sequence. + public async Task UploadFileAsync(string path, Guid? sequenceId, string? sessionKey, string sha256, DateTime? capturedAt, + CancellationToken cancellationToken) { var bytes = await File.ReadAllBytesAsync(path, cancellationToken); if (Convert.ToHexStringLower(SHA256.HashData(bytes)) != sha256) throw new TitanoApiException(HttpStatusCode.BadRequest, new ApiError("hash_mismatch", "hash")); lock (_gate) { - var s = Find(sequenceId); - var existing = s.Frames.FindIndex(f => f.Sha256 == sha256); - if (existing >= 0) return new CompleteUploadResponse(s.Frames[existing].Id, sequenceId, existing); - var frame = s.AddFrame(bytes, Path.GetFileName(path), capturedAt); - return new CompleteUploadResponse(frame.Id, sequenceId, s.Frames.Count - 1); + if (Sequences.Values.SelectMany(s => s.Frames).FirstOrDefault(f => f.Sha256 == sha256) is { } existing) + return new CompleteUploadResponse(existing.Id, sequenceId ?? Guid.Empty, -1); + FakeSequence target; + if (sequenceId is { } id) target = Find(id); + else if (!_sessions.TryGetValue(sessionKey!, out target!)) + { + target = new FakeSequence { Id = Guid.CreateVersion7() }; + Sequences[target.Id] = target; + _sessions[sessionKey!] = target; + } + var frame = target.AddFrame(bytes, Path.GetFileName(path), capturedAt); + return new CompleteUploadResponse(frame.Id, target.Id, target.Frames.Count - 1); } } diff --git a/tests/Titano.Data.Tests/Sync/SyncServiceTests.cs b/tests/Titano.Data.Tests/Sync/SyncServiceTests.cs index f82f3ee3..7e5a71fc 100644 --- a/tests/Titano.Data.Tests/Sync/SyncServiceTests.cs +++ b/tests/Titano.Data.Tests/Sync/SyncServiceTests.cs @@ -267,11 +267,11 @@ public sealed class SyncServiceTests(TestContext context) public Task> ListSequencesAsync(CancellationToken cancellationToken) => inner.ListSequencesAsync(cancellationToken); public Task GetManifestAsync(Guid id, CancellationToken cancellationToken) => inner.GetManifestAsync(id, cancellationToken); public Task> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken) => inner.ListFramesAsync(sequenceId, cancellationToken); - public Task CreateSequenceAsync(CreateSequenceRequest request, CancellationToken cancellationToken) => inner.CreateSequenceAsync(request, cancellationToken); public Task UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken) => inner.UpdateSequenceAsync(id, request, cancellationToken); - public Task UploadFileAsync(string path, Guid sequenceId, string sha256, DateTime? capturedAt, CancellationToken cancellationToken) => - inner.UploadFileAsync(path, sequenceId, sha256, capturedAt, cancellationToken); + public Task UploadFileAsync(string path, Guid? sequenceId, string? sessionKey, string sha256, DateTime? capturedAt, + CancellationToken cancellationToken) => + inner.UploadFileAsync(path, sequenceId, sessionKey, sha256, capturedAt, cancellationToken); public Task DownloadFrameAsync(Guid frameId, string kind, Stream destination, CancellationToken cancellationToken) => inner.DownloadFrameAsync(frameId, kind, destination, cancellationToken); diff --git a/tests/Titano.Server.Tests/Sync/SyncClient.cs b/tests/Titano.Server.Tests/Sync/SyncClient.cs new file mode 100644 index 00000000..9b642c99 --- /dev/null +++ b/tests/Titano.Server.Tests/Sync/SyncClient.cs @@ -0,0 +1,120 @@ +using System.Security.Cryptography; +using Titano.Core.Codecs.Jpeg; +using Titano.Core.Model; +using Titano.Data; +using Titano.Data.Archiving; +using Titano.Data.Jobs; +using Titano.Data.Sync; +using Titano.Protocol.Client; +using Titano.Testing; + +namespace Titano.Server.Tests.Sync; + +/// A desktop client's sync side: its own index and archive, the sync engine and a job engine, signed in to a test server. +internal sealed class SyncClient : IAsyncDisposable +{ + private readonly TestContext _context; + private readonly TitanoClient _client; + + private SyncClient(TestContext context, TitanoDatabase db, ArchiveService archives, Archive archive, SyncService sync, TitanoClient client, JobEngine engine) + { + _context = context; + Db = db; + Archives = archives; + Archive = archive; + Sync = sync; + _client = client; + Engine = engine; + Remote = new TitanoSyncRemote(client, ownsClient: false); + } + + public TitanoDatabase Db { get; } + public ArchiveService Archives { get; } + public Archive Archive { get; } + public SyncService Sync { get; } + public JobEngine Engine { get; } + + /// The connection the table and the agent use (jobs get their own from the connector). + public TitanoSyncRemote Remote { get; } + + public string Server => Remote.Server; + private CancellationToken Ct => _context.Cancellation; + + public static async Task StartAsync(TestContext context, TestServer server, string token, string name) + { + var db = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory(name + "-db"), "titano.db")), context.Cancellation); + var options = new ArchiveServiceOptions { Owner = name, LeaseWait = TimeSpan.FromSeconds(20) }; + var archives = new ArchiveService(db, options); + var archive = await archives.CreateAsync(context.CreateTempDirectory(name + "-archive"), "Main", cancellationToken: context.Cancellation); + var sync = new SyncService(db, archives, new SyncOptions { Archive = options, ProxyCacheDirectory = context.CreateTempDirectory(name + "-proxies") }); + var client = new TitanoClient(server.HttpBase, new CertificatePinning([]), name) { Token = token }; + var engine = new JobEngine(db, [.. archives.CreateJobHandlers(), .. sync.CreateJobHandlers(new Connector(client))], + new JobEngineOptions { Workers = 2, WorkerId = name, PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) }); + await engine.StartAsync(context.Cancellation); + return new SyncClient(context, db, archives, archive, sync, client, engine); + } + + /// Distinct JPEGs larger than one 64 KiB chunk. + public static byte[] Photo(int seed) + { + const int width = 512, height = 384; + var pixels = new byte[width * height * 3]; + new Random(seed).NextBytes(pixels); + return JpegEncoder.Encode(pixels, width, height, 3, new JpegEncodeOptions { Quality = 95 }); + } + + public static string Sha(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes)); + + /// A local sequence committed through the archive ingest, optionally with project settings edited on this PC. + public async Task LocalAsync(string title, IReadOnlyList photos, string? settingsJson = null) + { + var staging = Path.Combine(Archive.RootPath, ".titano", "staging", "test"); + Directory.CreateDirectory(staging); + Guid? id = null; + for (var i = 0; i < photos.Count; i++) + { + var path = Path.Combine(staging, $"{Guid.NewGuid():N}.part"); + await File.WriteAllBytesAsync(path, photos[i], Ct); + var result = await Archives.Ingest.CommitAsync(new IngestRequest(Archive.Id, id, id is null ? title : null, null, path, $"IMG_{i + 1:0000}.JPG", + photos[i].Length, Sha(photos[i]), new DateTime(2026, 9, 28, 18, 0, 0).AddSeconds(10 * i), null), Ct); + id = result.SequenceId; + } + var sequence = (await Db.Sequences.GetAsync(id!.Value, Ct))!; + if (settingsJson is null) return sequence; + var edited = await Db.Sequences.EditAsync(sequence.Id, new Titano.Data.Repositories.SequenceEdit { SettingsJson = settingsJson }, null, Ct); + return edited.Sequence!; + } + + public async Task WaitAsync(Guid jobId, JobState state = JobState.Done) + { + var until = DateTime.UtcNow.AddSeconds(60); + while (true) + { + var job = await Db.Jobs.GetAsync(jobId, Ct); + if (job?.State == state) return job; + if (job?.State is JobState.Failed && state != JobState.Failed) Assert.Fail($"Job failed: {job.Error}\n{job.LogTail}"); + if (DateTime.UtcNow > until) Assert.Fail($"Job {jobId} did not reach {state} (now {job?.State})"); + await Task.Delay(25, Ct); + } + } + + public async Task EntryAsync(string title) => (await Sync.ListAsync(Server, Ct)).Single(e => e.Title == title); + + public async ValueTask DisposeAsync() + { + await Engine.DisposeAsync(); + Remote.Dispose(); + _client.Dispose(); + await Db.DisposeAsync(); + } + + /// Every job gets its own remote over the shared signed-in client. + private sealed class Connector(TitanoClient client) : ISyncConnector + { + public ValueTask ConnectAsync(string server, CancellationToken cancellationToken) + { + ISyncRemote remote = new TitanoSyncRemote(client, ownsClient: false); + return ValueTask.FromResult(remote.Server == server ? remote : null); + } + } +} diff --git a/tests/Titano.Server.Tests/Sync/SyncServerTests.cs b/tests/Titano.Server.Tests/Sync/SyncServerTests.cs new file mode 100644 index 00000000..e5ce7857 --- /dev/null +++ b/tests/Titano.Server.Tests/Sync/SyncServerTests.cs @@ -0,0 +1,206 @@ +using System.Net; +using System.Net.Http.Json; +using Microsoft.Extensions.DependencyInjection; +using Titano.Core.Imaging; +using Titano.Core.Imaging.Decoders; +using Titano.Core.Model; +using Titano.Core.Project; +using Titano.Data.Repositories; +using Titano.Data.Sync; +using Titano.Protocol; +using Titano.Server.Events; +using Titano.Server.Storage; +using Titano.Testing; + +namespace Titano.Server.Tests.Sync; + +/// The client's sync engine against the real server: uploads, downloads, proxies and live events through the API. +[Category("server")] +[Timeout(180_000)] +public sealed class SyncServerTests(TestContext context) +{ + private const string Window41 = """{"exposure":{"deflickerWindow":{"isAuto":false,"manual":41}}}"""; + private const string Window33 = """{"exposure":{"deflickerWindow":{"isAuto":false,"manual":33}}}"""; + + [Test] + public async Task ASequenceUploadedFromOnePcDownloadsIdenticallyOnAnother() + { + await using var server = await StartServerAsync(); + var (_, _, token) = await server.UserAsync("alberto", "editor"); + await using var studio = await SyncClient.StartAsync(context, server, token, "studio"); + await using var laptop = await SyncClient.StartAsync(context, server, token, "laptop"); + var photos = Enumerable.Range(1, 3).Select(SyncClient.Photo).ToList(); + var local = await studio.LocalAsync("Comet over the ridge", photos, Window41); + + var upload = await studio.Sync.EnqueueUploadAsync(studio.Engine, studio.Server, local); + await studio.WaitAsync(upload.Id); + + var uploaded = await studio.EntryAsync("Comet over the ridge"); + Assert.Equal((0, 0), (uploaded.Link!.MissingRemote, uploaded.Link.MissingLocal)); + var remoteId = uploaded.Link!.RemoteId; + var onServer = Assert.NotNull(await server.Database.Sequences.GetAsync(remoteId)); + Assert.Equal(41, ProjectSettings.FromJson(onServer.SettingsJson!).Exposure.DeflickerWindow.Manual, "settings travel with the originals"); + var serverFrames = await server.Database.Frames.ListBySequenceAsync(remoteId); + Assert.True(serverFrames.Select(f => f.Sha256).ToHashSet().SetEquals(photos.Select(SyncClient.Sha)), "every original was committed"); + + await ServerIdleAsync(server); + await laptop.Sync.RefreshAsync(laptop.Remote, new SyncPolicy(), context.Cancellation); + Assert.Equal(SyncStatus.RemoteOnly, (await laptop.EntryAsync("Comet over the ridge")).Status); + var download = await laptop.Sync.EnqueueDownloadAsync(laptop.Engine, laptop.Server, remoteId, "Comet over the ridge", SyncDownloadMode.Originals, + laptop.Archive.Id); + await laptop.WaitAsync(download.Id); + + var copy = await laptop.EntryAsync("Comet over the ridge"); + Assert.Equal(SyncStatus.InSync, copy.Status); + Assert.Equal(SequenceOrigin.Server, copy.Local!.Origin); + // The server's analysis may have added its advice meanwhile; the copy has what the server has, the user's edit included. + Assert.True(SyncRules.SameSettings((await server.Database.Sequences.GetAsync(remoteId))!.SettingsJson, copy.Local.SettingsJson)); + Assert.Equal(41, ProjectSettings.FromJson(copy.Local.SettingsJson!).Exposure.DeflickerWindow.Manual); + var files = (await laptop.Db.Frames.ListBySequenceAsync(copy.Local.Id)) + .Select(f => File.ReadAllBytes(Path.Combine(laptop.Archive.RootPath, f.RelativePath))).ToList(); + Assert.True(files.Select(SyncClient.Sha).ToHashSet().SetEquals(photos.Select(SyncClient.Sha)), "byte-identical originals"); + + await studio.Sync.RefreshAsync(studio.Remote, new SyncPolicy(), context.Cancellation); + Assert.Equal(SyncStatus.InSync, (await studio.EntryAsync("Comet over the ridge")).Status); + } + + [Test] + public async Task AnUploadInterruptedMidFileResumesTheServersPartialUpload() + { + await using var server = await StartServerAsync(); + var (http, _, token) = await server.UserAsync("alberto", "editor"); + await using var studio = await SyncClient.StartAsync(context, server, token, "studio"); + var photos = Enumerable.Range(10, 2).Select(SyncClient.Photo).ToList(); + var local = await studio.LocalAsync("Clouds", photos); + // The crashed attempt had sent the first original (which created the server sequence) and one chunk of the second. + var first = await Uploads.UploadAsync(http, photos[0], "IMG_0001.JPG", sessionKey: "crashed-attempt"); + var partial = await Uploads.StartAsync(http, photos[1], "IMG_0002.JPG", first.SequenceId); + Assert.True(photos[1].Length > partial.ChunkSize, "the photo spans several chunks"); + using (var chunk = await Uploads.PutChunkAsync(http, partial.UploadId!.Value, 0, Uploads.Chunk(photos[1], partial.ChunkSize, 0))) + await chunk.ExpectAsync(HttpStatusCode.OK); + + var job = new Job + { + Id = Guid.CreateVersion7(), + Kind = JobKind.UploadCommit, + TargetIds = [local.Id], + TargetLabel = "Clouds", + ParametersJson = $$"""{"server":"{{studio.Server}}"}""", + Checkpoint = first.SequenceId.ToString(), + State = JobState.Queued, + Created = DateTimeOffset.UtcNow, + }; + await studio.Db.Jobs.EnqueueAsync(job, context.Cancellation); + studio.Engine.Wake(); + await studio.WaitAsync(job.Id); + + var resumed = Assert.NotNull(await server.Database.Uploads.GetAsync(partial.UploadId!.Value)); + Assert.Equal(Titano.Data.Repositories.UploadState.Committed, resumed.State); + Assert.Equal(2, (await server.Database.Frames.ListBySequenceAsync(first.SequenceId)).Count); + // Every original is on both sides (the server's analysis may still be editing the settings). + var link = (await studio.EntryAsync("Clouds")).Link!; + Assert.Equal((first.SequenceId, 0, 0), (link.RemoteId, link.MissingRemote, link.MissingLocal)); + } + + [Test] + public async Task ADownloadResumesPartialFilesAndRefusesDamagedOnes() + { + await using var server = await StartServerAsync(); + var (_, _, token) = await server.UserAsync("alberto", "editor"); + await using var studio = await SyncClient.StartAsync(context, server, token, "studio"); + await using var laptop = await SyncClient.StartAsync(context, server, token, "laptop"); + var photos = Enumerable.Range(20, 3).Select(SyncClient.Photo).ToList(); + var local = await studio.LocalAsync("Aurora", photos); + await studio.WaitAsync((await studio.Sync.EnqueueUploadAsync(studio.Engine, studio.Server, local)).Id); + var remoteId = (await studio.EntryAsync("Aurora")).Link!.RemoteId; + + // An earlier attempt left half of one original, and a damaged half of another. + var staging = Path.Combine(laptop.Archive.RootPath, ".titano", "staging", "sync-" + remoteId.ToString("N")); + Directory.CreateDirectory(staging); + await File.WriteAllBytesAsync(Path.Combine(staging, SyncClient.Sha(photos[0]) + ".jpg.part"), photos[0][..(photos[0].Length / 2)]); + await File.WriteAllBytesAsync(Path.Combine(staging, SyncClient.Sha(photos[1]) + ".jpg.part"), new byte[photos[1].Length / 2]); + + await laptop.Sync.RefreshAsync(laptop.Remote, new SyncPolicy(), context.Cancellation); + var download = await laptop.Sync.EnqueueDownloadAsync(laptop.Engine, laptop.Server, remoteId, "Aurora", SyncDownloadMode.Originals, laptop.Archive.Id); + await laptop.WaitAsync(download.Id); + + var copy = Assert.NotNull((await laptop.EntryAsync("Aurora")).Local); + var hashes = (await laptop.Db.Frames.ListBySequenceAsync(copy.Id)) + .Select(f => SyncClient.Sha(File.ReadAllBytes(Path.Combine(laptop.Archive.RootPath, f.RelativePath)))).ToHashSet(); + Assert.True(hashes.SetEquals(photos.Select(SyncClient.Sha)), "every original arrived intact"); + Assert.False(Directory.Exists(staging), "staging cleaned up"); + } + + [Test] + public async Task ServerEventsUpdateThisPcWithoutWaitingForTheNextComparison() + { + await using var server = await StartServerAsync(); + var (http, _, token) = await server.UserAsync("alberto", "editor"); + await using var studio = await SyncClient.StartAsync(context, server, token, "studio"); + var local = await studio.LocalAsync("Harbour sunset", [SyncClient.Photo(30)]); + await studio.WaitAsync((await studio.Sync.EnqueueUploadAsync(studio.Engine, studio.Server, local)).Id); + var remoteId = (await studio.EntryAsync("Harbour sunset")).Link!.RemoteId; + await ServerIdleAsync(server); + await using var agent = new SyncAgent(studio.Sync, studio.Remote, () => new SyncPolicy(), studio.Engine, + new SyncAgentOptions { RefreshInterval = TimeSpan.FromHours(1), EventDelay = TimeSpan.FromMilliseconds(50) }); + agent.Start(); + var hub = server.Services.GetRequiredService(); + await UntilAsync(() => Task.FromResult(agent.Snapshot is not null && hub.SubscriberCount > 0), "the agent's first comparison and event socket"); + + // Someone edits the project on the server (web or another PC). + using (var patch = await http.PatchAsJsonAsync($"/api/v1/sequences/{remoteId}", + new UpdateSequenceRequest(null, null, null, null, Window33, null), ProtocolJson.Default.UpdateSequenceRequest)) + await patch.ExpectAsync(HttpStatusCode.OK); + + await UntilAsync(async () => ProjectSettings.FromJson((await studio.Db.Sequences.GetAsync(local.Id))!.SettingsJson ?? "{}").Exposure.DeflickerWindow.Manual == 33, + "the edit reached this PC"); + Assert.Equal(SyncStatus.InSync, (await studio.EntryAsync("Harbour sunset")).Status); + } + + [Test] + public async Task ARemoteSequenceOpensWithProxiesOnly() + { + await using var server = await StartServerAsync(); + var (_, _, token) = await server.UserAsync("alberto", "editor"); + await using var studio = await SyncClient.StartAsync(context, server, token, "studio"); + await using var laptop = await SyncClient.StartAsync(context, server, token, "laptop"); + var photos = Enumerable.Range(40, 2).Select(SyncClient.Photo).ToList(); + var local = await studio.LocalAsync("Milan skyline dusk", photos, Window41); + await studio.WaitAsync((await studio.Sync.EnqueueUploadAsync(studio.Engine, studio.Server, local)).Id); + var remoteId = (await studio.EntryAsync("Milan skyline dusk")).Link!.RemoteId; + await ServerIdleAsync(server); + Assert.True(((await server.Database.Sequences.GetAsync(remoteId))!.Status & SequenceStatus.ThumbsBuilt) != 0, "thumbnails on the server"); + + await laptop.Sync.RefreshAsync(laptop.Remote, new SyncPolicy(), context.Cancellation); + var job = await laptop.Sync.EnqueueDownloadAsync(laptop.Engine, laptop.Server, remoteId, "Milan skyline dusk", SyncDownloadMode.Proxies, null); + await laptop.WaitAsync(job.Id); + + Assert.Equal(SyncStatus.ProxiesOnly, (await laptop.EntryAsync("Milan skyline dusk")).Status); + Assert.Empty((await laptop.Db.Sequences.ListAsync(new SequenceQuery())).Items); + var opened = Assert.NotNull(laptop.Sync.OpenRemote(laptop.Server, remoteId)); + Assert.Equal(2, opened.CachedCount); + Assert.Equal(41, ProjectSettings.FromJson(opened.Sequence.SettingsJson!).Exposure.DeflickerWindow.Manual); + var source = opened.OpenFrames(DecoderFactory.CreateServer()); + await using (source as IAsyncDisposable) + { + using var frame = await source.GetFrameAsync(0, 0, DecodePurpose.Render, context.Cancellation); + Assert.True(frame.Width > 0 && frame.Height > 0, "a proxy decodes"); + } + } + + private Task StartServerAsync() => TestServer.StartAsync(context, o => o.ChunkSizeBytes = 64 * 1024, ArchiveModule.Register); + + /// Waits until the server's engines finished what the commits queued (thumbnails, proxies, analysis, which may edit settings). + private Task ServerIdleAsync(TestServer server) => + UntilAsync(async () => await server.Database.Jobs.CountAsync(DateTimeOffset.UtcNow) is { Queued: 0, Running: 0 }, "the server's jobs"); + + private async Task UntilAsync(Func> condition, string what) + { + var until = DateTime.UtcNow.AddSeconds(60); + while (!await condition()) + { + if (DateTime.UtcNow > until) Assert.Fail("Timed out waiting for " + what); + await Task.Delay(50, context.Cancellation); + } + } +} From 25653c052ba85b1f91c96e338ad7cfe831368208 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 22:53:24 +0000 Subject: [PATCH 4/8] feat(app): server sync table, conflict resolution, sync options and Library sync glyphs SyncHost runs the sync agent of the signed-in session and gives transfer jobs their connection; the Server screen lists every sequence of this PC and of the server with its state and actions (upload, download originals, open with proxies, keep mine / take server / save both, pause, resume), filter chips, search, Upload all local and the comparison footer. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- i18n/en/Library.resx | 3 + i18n/en/Server.resx | 55 +++ i18n/en/Tooltips.resx | 37 ++ i18n/it/Library.it.resx | 3 + i18n/it/Server.it.resx | 54 +++ i18n/it/Tooltips.it.resx | 37 ++ src/Titano.App/Infrastructure/AppServices.cs | 21 +- src/Titano.App/Infrastructure/AppSettings.cs | 6 + src/Titano.App/Library/SequenceItem.cs | 13 +- src/Titano.App/Sections/LibraryViewModel.cs | 2 +- src/Titano.App/Sections/ServerView.xaml | 108 +++++- src/Titano.App/Sections/ServerViewModel.cs | 35 +- src/Titano.App/Server/SyncHost.cs | 137 +++++++ src/Titano.App/Server/SyncRow.cs | 58 +++ src/Titano.App/Server/SyncTableViewModel.cs | 366 +++++++++++++++++++ src/Titano.App/Server/SyncText.cs | 147 ++++++++ 16 files changed, 1072 insertions(+), 10 deletions(-) create mode 100644 src/Titano.App/Server/SyncHost.cs create mode 100644 src/Titano.App/Server/SyncRow.cs create mode 100644 src/Titano.App/Server/SyncTableViewModel.cs create mode 100644 src/Titano.App/Server/SyncText.cs diff --git a/i18n/en/Library.resx b/i18n/en/Library.resx index 8d365087..b4bac4f4 100644 --- a/i18n/en/Library.resx +++ b/i18n/en/Library.resx @@ -61,8 +61,11 @@ Title Analysed Analysing + Conflict + Newer here Proxies Remote + Newer on server Synced View Grid diff --git a/i18n/en/Server.resx b/i18n/en/Server.resx index 512ef763..9e2ada8b 100644 --- a/i18n/en/Server.resx +++ b/i18n/en/Server.resx @@ -5,12 +5,19 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 nas.local:8443invariant + Sync projects automatically Certificate Forget Keep Titano trusts this certificate for this server. Forgetting it disconnects, and the next connection asks again.long Server certificate TLS {0} trusted {1} + Cancel + {0}: {1} here, {2} on the serverlong; {0} setting path, {1} value on this PC, {2} value on the server + The server copy of {0} will be replaced by this PC's settings.long; {0} sequence title + Keep this PC's settings? + This PC's settings of {0} will be replaced by the server copy.long; {0} sequence title + Take the server's settings? Connect Disconnect Not connected to a server @@ -71,6 +78,7 @@ The current password is wrong.long This upload belongs to a render job.long Servers found + Keep proxies offline Account Server Status @@ -93,6 +101,53 @@ Connecting… Disconnected Not connected + Download originals + Keep mine + Open with proxies + Pause + Resume + Save both + Sync settings + Take server + Upload + Server archive {1} · {0} sequencelong; {0} sequence count, {1} archive size + Server archive {1} · {0} sequenceslong; {0} sequence count, {1} archive size + The server copy changed again; compare and choose again.long + This PC + Sequence + Server + State + Nothing to compare yet + {0} export{0} count + {0} exports{0} count + All · {0}{0} count + Conflicts · {0}{0} count + Local only · {0}{0} count + Remote · {0}{0} count + Last sync {0} · manifest diff {1} slong; {0} time of day, {1} seconds + No sequence matches + —invariant + Open admin panel + originals + proxies + {0} upload queued{0} count + {0} uploads queued{0} count + {0} received{0} percent + Not compared · retrying + Search + settings differ + downloading + in sync + newer here + local only + paused + proxies only + remote + newer on server + uploading + waiting + Sequences + Upload all local Trust Cancel {0} uses a certificate Titano does not know yet. Compare the fingerprint with the one in the server's admin panel before you trust it.long diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx index 7ca6cbe4..8995adcf 100644 --- a/i18n/en/Tooltips.resx +++ b/i18n/en/Tooltips.resx @@ -74,13 +74,16 @@ Filter by analysis, proxies, verification or warnings Analysed: exposure, flicker and motion are measured An analysis job is running on this sequence + Settings changed here and on the server; choose on the Server screen Some frames are missing or unreadable; open the sequence for details + This PC has originals or settings the server does not have yet No proxies yet; editing reads the originals Not analysed yet JPEG proxies built for fast editing Lives on the server; this PC has proxies at most Rendered once Rendered {0:N0} times + The server has originals or settings this PC does not have yet The same on this PC and on the server {0:N0} warning; open the sequence for details {0:N0} warnings; open the sequence for details @@ -97,14 +100,18 @@ Connection, sync and render node · Ctrl+6 Preferences of this PC · Ctrl+, Address of the Titano Server; https is assumed · Enter connects + Send and take project settings as they change; settings changed on both sides wait for your choice in the table below Show the full fingerprint, or forget the trust Fingerprint trusted on first use; a change blocks the connection and asks you again + Close without changing either copy + The settings that differ: this PC's value, then the server's Identify the server, confirm a new certificate, then sign in · Enter Close the session and work with the local archive only; you stay signed in Do not connect; nothing is sent to this server SHA-256 fingerprint of the server certificate Forget this certificate; the next connection asks again Servers found on this network and used before + Keep JPEG proxies of every server sequence on this PC to edit without the originals; uses space in the cache folder Keep trusting this certificate Close without signing in · Esc Sent only to this server; Titano keeps a session token, never the password @@ -118,6 +125,36 @@ Sign in; the token is stored encrypted for this Windows user · Enter Sign out; the token is removed from this PC Connection to the server + Size and sequences of the server archive + Fetch the originals to this PC, verified by hash ({0}){0} size + All sequences on this PC and on the server + Settings differ between this PC and the server + Only on this PC + Only on the server + Overwrite the server copy with this PC's settings + When this PC last compared every sequence with the server, and how long it took + Open the web admin in your browser (admins only) + Open the editor on the proxies; the render runs on the server + Pause this transfer; it resumes where it stopped + Resume this transfer where it stopped + The last comparison failed: {0}. It is retried automatically.{0} reason + Take the server copy and keep this PC's settings as a dated copy of the project + Filter the table by sequence title + Settings changed both here and on the server; choose which to keep + Originals or proxies are arriving from the server + Same originals and settings on this PC and on the server + This PC has originals or settings the server does not have yet + Only on this PC; upload it to keep it on the server too + The transfer is paused; resume it to continue + On the server; this PC keeps its proxies for editing + Only on the server + The server has originals or settings this PC does not have yet + Originals are being sent to the server + The transfer waits for its turn in the job queue + Send or take the settings changed on one side + Replace this PC's settings with the server copy + Copy originals and settings to the server ({0}){0} size + Send every local-only sequence to the server ({0} sequences, {1}){0} count, {1} size Trust this certificate for this server and continue to sign in Use this address Graphics adapter and Media Foundation encoders found diff --git a/i18n/it/Library.it.resx b/i18n/it/Library.it.resx index cbf7ca1a..29240386 100644 --- a/i18n/it/Library.it.resx +++ b/i18n/it/Library.it.resx @@ -61,8 +61,11 @@ Titolo Analizzata In analisi + Conflitto + Più recente qui Proxy Remota + Più recente sul server Sincronizzata Vista Griglia diff --git a/i18n/it/Server.it.resx b/i18n/it/Server.it.resx index fb5bdb68..b5bd92ab 100644 --- a/i18n/it/Server.it.resx +++ b/i18n/it/Server.it.resx @@ -4,12 +4,19 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Sincronia automatica progetti Certificato Dimentica Mantieni Titano considera attendibile questo certificato per questo server. Se lo dimentichi la connessione si chiude e la prossima volta te lo chiederà di nuovo. Certificato del server TLS {0} attendibile dal {1} + Annulla + {0}: {1} qui, {2} sul server + La copia sul server di {0} sarà sostituita dalle impostazioni di questo PC. + Tenere le impostazioni di questo PC? + Le impostazioni di {0} su questo PC saranno sostituite dalla copia del server. + Usare le impostazioni del server? Connetti Disconnetti Non connesso a un server @@ -70,6 +77,7 @@ La password attuale è errata. Questo caricamento appartiene a un job di rendering. Server trovati + Proxy disponibili offline Account Server Stato @@ -92,6 +100,52 @@ Connessione… Disconnesso Non connesso + Scarica originali + Tieni le mie + Apri con i proxy + Pausa + Riprendi + Salva entrambe + Sincronizza + Usa il server + Carica + Archivio del server {1} · {0} sequenza + Archivio del server {1} · {0} sequenze + La copia sul server è cambiata di nuovo; confronta e scegli di nuovo. + Questo PC + Sequenza + Server + Stato + Ancora nulla da confrontare + {0} esportazione + {0} esportazioni + Tutte · {0} + Conflitti · {0} + Solo locali · {0} + Sul server · {0} + Ultima sincronia {0} · confronto {1} s + Nessuna sequenza corrisponde + Apri pannello admin + originali + proxy + {0} caricamento in coda + {0} caricamenti in coda + {0} ricevuto + Confronto non riuscito · riprovo + Cerca + impostazioni diverse + in scaricamento + sincronizzata + più recente qui + solo locale + in pausa + solo proxy + sul server + più recente sul server + in caricamento + in attesa + Sequenze + Carica tutte le locali Considera attendibile Annulla {0} usa un certificato che Titano non conosce ancora. Confronta l'impronta con quella del pannello di amministrazione del server prima di considerarlo attendibile. diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx index c81ad08f..cd171b20 100644 --- a/i18n/it/Tooltips.it.resx +++ b/i18n/it/Tooltips.it.resx @@ -74,13 +74,16 @@ Filtra per analisi, proxy, verifica o avvisi Analizzata: esposizione, flicker e movimento sono misurati Un'attività di analisi è in corso su questa sequenza + Impostazioni cambiate qui e sul server; scegli nella schermata Server Alcuni fotogrammi mancano o sono illeggibili; apri la sequenza per i dettagli + Questo PC ha originali o impostazioni che il server non ha ancora Ancora nessun proxy; la modifica legge gli originali Non ancora analizzata Proxy JPEG pronti per una modifica veloce Si trova sul server; questo PC ne ha al massimo i proxy Esportata una volta Esportata {0:N0} volte + Il server ha originali o impostazioni che questo PC non ha ancora Uguale su questo PC e sul server {0:N0} avviso; apri la sequenza per i dettagli {0:N0} avvisi; apri la sequenza per i dettagli @@ -97,14 +100,18 @@ Connessione, sincronizzazione e nodo di rendering · Ctrl+6 Preferenze di questo PC · Ctrl+, Indirizzo del Titano Server; si presume https · Invio per connettersi + Invia e ricevi le impostazioni dei progetti quando cambiano; quelle cambiate da entrambe le parti attendono la tua scelta nella tabella sotto Mostra l'impronta completa o revoca la fiducia Impronta accettata al primo utilizzo; se cambia, la connessione si blocca e te lo chiede di nuovo + Chiudi senza modificare nessuna delle due copie + Le impostazioni diverse: il valore di questo PC, poi quello del server Identifica il server, conferma un certificato nuovo e poi accedi · Invio Chiude la sessione e lavora solo con l'archivio locale; l'accesso resta salvato Non connetterti; a questo server non viene inviato nulla Impronta SHA-256 del certificato del server Dimentica questo certificato; alla prossima connessione verrà chiesto di nuovo Server trovati in questa rete e usati in precedenza + Tieni su questo PC i proxy JPEG di ogni sequenza del server per lavorare senza gli originali; usa spazio nella cartella cache Continua a considerare attendibile questo certificato Chiude senza accedere · Esc Inviata solo a questo server; Titano conserva un token di sessione, mai la password @@ -118,6 +125,36 @@ Accedi; il token viene salvato cifrato per questo utente di Windows · Invio Esci; il token viene rimosso da questo PC Connessione al server + Dimensione e sequenze dell'archivio del server + Scarica gli originali su questo PC, verificati con l'hash ({0}) + Tutte le sequenze di questo PC e del server + Le impostazioni differiscono tra questo PC e il server + Solo su questo PC + Solo sul server + Sovrascrivi la copia del server con le impostazioni di questo PC + Quando questo PC ha confrontato per l'ultima volta tutte le sequenze con il server, e quanto ha impiegato + Apri l'amministrazione web nel browser (solo amministratori) + Apri l'editor sui proxy; il rendering avviene sul server + Metti in pausa questo trasferimento; riprende da dove si è fermato + Riprendi questo trasferimento da dove si è fermato + L'ultimo confronto non è riuscito: {0}. Viene ripetuto automaticamente. + Usa la copia del server e conserva le impostazioni di questo PC come copia datata del progetto + Filtra la tabella per titolo della sequenza + Le impostazioni sono cambiate sia qui sia sul server; scegli quali tenere + Originali o proxy in arrivo dal server + Stessi originali e impostazioni su questo PC e sul server + Questo PC ha originali o impostazioni che il server non ha ancora + Solo su questo PC; caricala per averla anche sul server + Il trasferimento è in pausa; riprendilo per continuare + Sul server; questo PC ne conserva i proxy per modificarla + Solo sul server + Il server ha originali o impostazioni che questo PC non ha ancora + Originali in invio al server + Il trasferimento attende il suo turno nella coda delle attività + Invia o ricevi le impostazioni cambiate da una sola parte + Sostituisci le impostazioni di questo PC con la copia del server + Copia originali e impostazioni sul server ({0}) + Invia al server ogni sequenza solo locale ({0} sequenze, {1}) Considera attendibile questo certificato per questo server e prosegui con l'accesso Usa questo indirizzo Scheda grafica ed encoder Media Foundation trovati diff --git a/src/Titano.App/Infrastructure/AppServices.cs b/src/Titano.App/Infrastructure/AppServices.cs index 5ed5098f..9184d2b4 100644 --- a/src/Titano.App/Infrastructure/AppServices.cs +++ b/src/Titano.App/Infrastructure/AppServices.cs @@ -29,7 +29,7 @@ namespace Titano.App.Infrastructure; /// archive engine (WIC first, then managed decoders), the analysis and render engine (the same decoders; Media /// Foundation, then managed encoders), the one of this PC with the handlers of /// , thumbnails, the server session, the render node, the encoder inventory and the -/// update check. Started after the window shows, stopped when the app exits. The last archive is reopened at start and +/// update check, and the sync with the signed-in server (). Started after the window shows, stopped when the app exits. The last archive is reopened at start and /// rescanned every (BRIEF §7: polling, no file-system watchers). The render node runs while /// the user offers this PC () and a server session is open. /// @@ -52,6 +52,7 @@ public sealed class AppServices : IAsyncDisposable SaveSettingsAction = saveSettings; Dialogs = dialogs; ArchiveSetup = new EngineArchiveSetup(this); + Sync = new SyncHost(this); Server = new ServerSession(settings, saveSettings, new TitanoServerApiFactory(), new DpapiTokenProtector()); Encoders = new MediaFoundationInventory(); CheckForUpdateAsync = ct => UpdateCheck.FetchAsync(Http.Value, ProductLinks.LatestReleaseApi, VersionText, ct); @@ -81,9 +82,13 @@ public sealed class AppServices : IAsyncDisposable _server = value; _server.PropertyChanged += OnServerChanged; UpdateRenderNode(); + Sync.Update(); } } + /// Sync with the signed-in server: engine, job connection, background comparison. + public SyncHost Sync { get; } + public IEncoderInventory Encoders { get; set; } /// Latest public release (GitHub Releases API of the releases repository, BRIEF §18). @@ -111,7 +116,10 @@ public sealed class AppServices : IAsyncDisposable /// The job handlers of this PC's engine — the single registration list; a kind without a handler stays /// queued (it is never claimed here). public static IReadOnlyList CreateJobHandlers(AppServices services) => - [.. services.Archives?.CreateJobHandlers() ?? [], .. services.Processing?.CreateJobHandlers() ?? []]; + [ + .. services.Archives?.CreateJobHandlers() ?? [], .. services.Processing?.CreateJobHandlers() ?? [], + .. services.Sync.Service?.CreateJobHandlers(services.Sync) ?? [], + ]; /// Queues a scan of unless one is already waiting or running. public async Task QueueScanAsync(Archive archive, bool full, CancellationToken ct = default) @@ -174,6 +182,7 @@ public sealed class AppServices : IAsyncDisposable _server.PropertyChanged -= OnServerChanged; await _nodeSwitch; await StopRenderNodeAsync(); + await Sync.DisposeAsync(); (Jobs as IDisposable)?.Dispose(); if (Engine is not null) await Engine.DisposeAsync(); Thumbnails?.Dispose(); @@ -209,6 +218,7 @@ public sealed class AppServices : IAsyncDisposable var archive = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateClient(new WicDecoderProvider()) }; Archives = new ArchiveService(database, archive); Processing = new ProcessingService(database, ProcessingOptions(archive)); + Sync.Open(database, Archives, archive); var handlers = CreateJobHandlers(this); var kinds = handlers.Select(h => h.Kind).Distinct().ToArray(); Engine = new JobEngine(database, handlers, new JobEngineOptions { WorkerId = WorkerId, Kinds = kinds }); @@ -218,6 +228,7 @@ public sealed class AppServices : IAsyncDisposable Jobs = new EngineJobQueue(database, Engine, started); Log.Info("jobs", started ? $"Job engine started with {Engine.Options.Workers} worker(s) for {string.Join(", ", kinds)}" : "No job handlers registered; jobs stay queued"); UpdateRenderNode(); + Sync.Update(); } /// Media Foundation (hardware first, software H.264) then managed encoders; frames spill into the cache folder @@ -235,7 +246,11 @@ public sealed class AppServices : IAsyncDisposable }, }; - private void OnServerChanged(object? sender, PropertyChangedEventArgs e) => UpdateRenderNode(); + private void OnServerChanged(object? sender, PropertyChangedEventArgs e) + { + UpdateRenderNode(); + Sync.Update(); + } /// Waits for the previous switch, then runs the node for the current session, or stops it. private async Task SwitchRenderNodeAsync(Task previous) diff --git a/src/Titano.App/Infrastructure/AppSettings.cs b/src/Titano.App/Infrastructure/AppSettings.cs index 59385ce1..dcf5bb47 100644 --- a/src/Titano.App/Infrastructure/AppSettings.cs +++ b/src/Titano.App/Infrastructure/AppSettings.cs @@ -111,6 +111,12 @@ public sealed class AppSettings /// Let the server send render jobs to this PC (BRIEF §14.7). public bool RenderNodeOptIn { get; set; } + /// Keep the proxies of every server sequence without local originals in the cache (BRIEF §12.7). + public bool KeepProxiesOffline { get; set; } + + /// Send and take project settings changed on one side without asking (Server.html). + public bool SyncSettingsAutomatically { get; set; } = true; + // ---- Jobs ---- /// "Clear done": finished jobs older than this are hidden from the Jobs list (they stay in the history). public DateTimeOffset? JobsClearedAt { get; set; } diff --git a/src/Titano.App/Library/SequenceItem.cs b/src/Titano.App/Library/SequenceItem.cs index f1ed8d64..ef467181 100644 --- a/src/Titano.App/Library/SequenceItem.cs +++ b/src/Titano.App/Library/SequenceItem.cs @@ -147,6 +147,16 @@ public sealed class SequenceItem : ObservableObject OnPropertyChanged(nameof(PrimaryStatus)); } + /// Where a local copy stands against the server (the sync engine writes the state); null while it is only here. + public static CardStatus? SyncStatus(SyncState state) => state switch + { + SyncState.InSync => new CardStatus(StatusKind.Synced, Loc.L("Library.Status.Synced"), Loc.L("Tooltips.Library.Status.Synced")), + SyncState.LocalAhead => new CardStatus(StatusKind.Synced, Loc.L("Library.Status.LocalAhead"), Loc.L("Tooltips.Library.Status.LocalAhead")), + SyncState.ServerAhead => new CardStatus(StatusKind.Remote, Loc.L("Library.Status.ServerAhead"), Loc.L("Tooltips.Library.Status.ServerAhead")), + SyncState.Conflict => new CardStatus(StatusKind.Warning, Loc.L("Library.Status.Conflict"), Loc.L("Tooltips.Library.Status.Conflict")), + _ => null, + }; + /// Card status row: analysed, proxies, renders, sync, warnings (Main.html). public static IReadOnlyList BuildStatuses(Sequence s, bool analysing) { @@ -168,8 +178,7 @@ public sealed class SequenceItem : ObservableObject if (s.RenderedCount > 0) list.Add(new CardStatus(StatusKind.Rendered, Formatting.Count(s.RenderedCount), Loc.Plural("Tooltips.Library.Status.Rendered", s.RenderedCount))); - if (s.SyncState == SyncState.InSync) - list.Add(new CardStatus(StatusKind.Synced, Loc.L("Library.Status.Synced"), Loc.L("Tooltips.Library.Status.Synced"))); + if (SyncStatus(s.SyncState) is { } sync) list.Add(sync); if ((s.Status & SequenceStatus.HasErrors) != 0) list.Add(new CardStatus(StatusKind.Error, Formatting.Count(Math.Max(1, s.WarningCount)), Loc.L("Tooltips.Library.Status.Errors"))); else if (s.WarningCount > 0 || (s.Status & SequenceStatus.HasWarnings) != 0) diff --git a/src/Titano.App/Sections/LibraryViewModel.cs b/src/Titano.App/Sections/LibraryViewModel.cs index f1072311..a70ed8d7 100644 --- a/src/Titano.App/Sections/LibraryViewModel.cs +++ b/src/Titano.App/Sections/LibraryViewModel.cs @@ -497,7 +497,7 @@ public sealed class LibraryViewModel : SectionViewModel { if (await _db.Sequences.GetAsync(item.Id) is { } fresh) item.Update(fresh); } - if (job.Kind is JobKind.Scan or JobKind.Rebuild or JobKind.Import or JobKind.Adopt or JobKind.Move or JobKind.UploadCommit) await RefreshAsync(); + if (job.Kind is JobKind.Scan or JobKind.Rebuild or JobKind.Import or JobKind.Adopt or JobKind.Move or JobKind.UploadCommit or JobKind.Download) await RefreshAsync(); } catch (DatabaseException ex) { diff --git a/src/Titano.App/Sections/ServerView.xaml b/src/Titano.App/Sections/ServerView.xaml index 4ad2e471..c4d1d067 100644 --- a/src/Titano.App/Sections/ServerView.xaml +++ b/src/Titano.App/Sections/ServerView.xaml @@ -15,9 +15,12 @@ + + + - + @@ -112,9 +115,112 @@ + + + + + + + + + + + + + + + + public sealed class SyncAgent : IAsyncDisposable { @@ -43,6 +43,11 @@ public sealed class SyncAgent : IAsyncDisposable private readonly Channel _refreshWake = Channel.CreateBounded(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite }); private readonly Channel _eventWake = Channel.CreateBounded(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite }); private readonly ConcurrentDictionary _changed = new(); + + /// Proxy downloads this agent queued, by server id, and the failures of each sequence's last ones. + private readonly Dictionary _proxyJobs = []; + + private readonly Dictionary _proxyFailures = []; private readonly SemaphoreSlim _refreshing = new(1, 1); private Task _running = Task.CompletedTask; private SyncSnapshot? _snapshot; @@ -200,8 +205,9 @@ public sealed class SyncAgent : IAsyncDisposable var due = ids.Where(id => !busy.Contains(id)).ToList(); if (due.Count > 0) await _sync.RefreshSequencesAsync(_remote, due, _policy(), cancellationToken).ConfigureAwait(false); } - catch (Exception ex) when (ex is not OperationCanceledException) + catch (Exception ex) when (!cancellationToken.IsCancellationRequested) { + // Includes timeouts reported as cancellation: the loop goes on and a full comparison catches up. Log.Warning(LogCategory, $"Comparing changed sequences of {Server} failed", ex); RequestRefresh(); } @@ -212,14 +218,34 @@ public sealed class SyncAgent : IAsyncDisposable } } - /// Queues (background priority) the proxies of server sequences without local originals whose cache is stale. + /// + /// Queues (background priority) the proxies of server sequences this PC keeps proxies of, without local originals, + /// whose cache is stale; a sequence whose last download failed waits for its backoff. + /// private async Task QueueProxiesAsync(SyncSnapshot snapshot, CancellationToken cancellationToken) { + foreach (var (remoteId, jobId) in _proxyJobs.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; + _proxyJobs.Remove(remoteId); + if (job?.State == JobState.Failed) + { + var failures = _proxyFailures.GetValueOrDefault(remoteId).Failures + 1; + _proxyFailures[remoteId] = (failures, DateTime.UtcNow + Backoff(failures)); + } + else + { + _proxyFailures.Remove(remoteId); + } + } foreach (var entry in snapshot.Entries) { - if (entry is not { Local: null, Transfer: null, Link: { ServerHasProxies: true, ProxiesStale: true } link }) continue; - await _sync.EnqueueDownloadAsync(_engine!, Server, link.RemoteId, link.Title, SyncDownloadMode.Proxies, null, JobPriority.Background, cancellationToken) - .ConfigureAwait(false); + if (entry is not { Local: null, Transfer: null, Link: { ProxiesCached: > 0, ServerHasProxies: true, ProxiesStale: true } link }) continue; + if (_proxyFailures.TryGetValue(link.RemoteId, out var failed) && DateTime.UtcNow < failed.NotBefore) continue; + var job = await _sync.EnqueueDownloadAsync(_engine!, Server, link.RemoteId, link.Title, SyncDownloadMode.Proxies, null, JobPriority.Background, + cancellationToken).ConfigureAwait(false); + _proxyJobs[link.RemoteId] = job.Id; } } diff --git a/src/Titano.Data/Sync/SyncJobHandler.cs b/src/Titano.Data/Sync/SyncJobHandler.cs index ab826246..be602d4b 100644 --- a/src/Titano.Data/Sync/SyncJobHandler.cs +++ b/src/Titano.Data/Sync/SyncJobHandler.cs @@ -6,12 +6,54 @@ using Titano.Data.Jobs; namespace Titano.Data.Sync; +/// What an upload or download job moves. +public enum SyncTransferKind +{ + /// Originals and settings of a local sequence to the server. + Upload, + + /// Renders of a local copy to the server. + SendExports, + + /// Originals of a server sequence into the local archive. + DownloadOriginals, + + /// Proxies of a server sequence into the proxy cache. + DownloadProxies, + + /// Renders of a server sequence into the local copy's exports. + GetExports, +} + /// /// Parameters of upload and download jobs. The job's target is the local sequence for an upload and the server /// sequence for a download. /// /// Archive that receives downloaded originals when the sequence has no local copy yet. -internal sealed record SyncJobParameters(string Server, SyncDownloadMode? Mode = null, Guid? ArchiveId = null); +internal sealed record SyncJobParameters(string Server, SyncDownloadMode? Mode = null, Guid? ArchiveId = null, SyncUploadMode? Upload = null) +{ + public static SyncJobParameters? Read(Job job) + { + if (job.Kind is not (JobKind.UploadCommit or JobKind.Download) || job.ParametersJson is not { } json) return null; + try + { + return JsonSerializer.Deserialize(json, SyncJobJson.Default.SyncJobParameters); + } + catch (JsonException) + { + return null; + } + } + + public SyncTransferKind Kind(JobKind kind) => (kind, Mode, Upload) switch + { + (JobKind.UploadCommit, _, SyncUploadMode.Exports) => SyncTransferKind.SendExports, + (JobKind.UploadCommit, _, _) => SyncTransferKind.Upload, + (_, SyncDownloadMode.Proxies, _) => SyncTransferKind.DownloadProxies, + (_, SyncDownloadMode.Exports, _) => SyncTransferKind.GetExports, + _ => SyncTransferKind.DownloadOriginals, + }; +} [JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, UseStringEnumConverter = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)] @@ -25,19 +67,24 @@ internal sealed class SyncJobHandler(JobKind kind, SyncTransfers transfers, ISyn public async Task RunAsync(JobContext context) { - var parameters = (context.Job.ParametersJson is { } json ? JsonSerializer.Deserialize(json, SyncJobJson.Default.SyncJobParameters) : null) - ?? throw new InvalidDataException("The job has no sync parameters."); + var parameters = SyncJobParameters.Read(context.Job) ?? throw new InvalidDataException("The job has no sync parameters."); if (context.Job.TargetIds is not [var target, ..]) throw new InvalidDataException("The job has no target sequence."); using var remote = await connector.ConnectAsync(parameters.Server, context.Cancellation).ConfigureAwait(false) ?? throw new InvalidOperationException(Loc.L("Errors.Sync.NotConnected")); - switch (kind, parameters.Mode) + switch (parameters.Kind(kind)) { - case (JobKind.UploadCommit, _): + case SyncTransferKind.Upload: await transfers.UploadAsync(context, remote, target).ConfigureAwait(false); break; - case (JobKind.Download, SyncDownloadMode.Proxies): + case SyncTransferKind.SendExports: + await transfers.SendExportsAsync(context, remote, target).ConfigureAwait(false); + break; + case SyncTransferKind.DownloadProxies: await transfers.DownloadProxiesAsync(context, remote, target).ConfigureAwait(false); break; + case SyncTransferKind.GetExports: + await transfers.GetExportsAsync(context, remote, target).ConfigureAwait(false); + break; default: await transfers.DownloadOriginalsAsync(context, remote, target, parameters.ArchiveId).ConfigureAwait(false); break; diff --git a/src/Titano.Data/Sync/SyncLinkStore.cs b/src/Titano.Data/Sync/SyncLinkStore.cs index 33f1496e..1d28e3f4 100644 --- a/src/Titano.Data/Sync/SyncLinkStore.cs +++ b/src/Titano.Data/Sync/SyncLinkStore.cs @@ -1,3 +1,4 @@ +using System.Text.Json; using Titano.Core.Model; using Titano.Data.Repositories; @@ -9,8 +10,8 @@ internal sealed class SyncLinkStore(TitanoDatabase db) private const string Columns = "server, remote_id, local_id, title, frame_count, total_bytes, render_count, remote_status, remote_settings_version, " + "remote_frames_version, remote_updated_at, base_local_settings, base_remote_settings, diff_local_frames, diff_remote_frames, " + - "missing_remote, missing_local, conflict_local_settings, conflict_remote_settings, conflict_settings, proxies_cached, " + - "proxies_frames_version, synced_at"; + "diff_local_renders, diff_remote_renders, missing_remote, missing_local, exports_to_get, exports_to_get_bytes, exports_to_send, " + + "exports_to_send_bytes, conflict_local_settings, conflict_remote_settings, conflict_remote, proxies_cached, proxies_frames_version, error, synced_at"; private static readonly string UpsertSql = SqlDialect.Upsert("sync_links", Columns.Split(", "), 2); @@ -32,8 +33,10 @@ internal sealed class SyncLinkStore(TitanoDatabase db) [ l.Server, l.RemoteId, l.LocalId, l.Title, l.FrameCount, l.TotalBytes, l.RenderCount, (int)l.RemoteStatus, l.RemoteSettingsVersion, l.RemoteFramesVersion, l.RemoteUpdatedAt, l.BaseLocalSettings, l.BaseRemoteSettings, l.DiffLocalFrames, l.DiffRemoteFrames, - l.MissingRemote, l.MissingLocal, l.ConflictLocalSettings, l.ConflictRemoteSettings, l.ConflictSettingsJson, l.ProxiesCached, - l.ProxiesFramesVersion, l.SyncedAt, + l.DiffLocalRenders, l.DiffRemoteRenders, l.MissingRemote, l.MissingLocal, l.ExportsToGet, l.ExportsToGetBytes, l.ExportsToSend, + l.ExportsToSendBytes, l.ConflictLocalSettings, l.ConflictRemoteSettings, + l.ConflictRemote is { } remote ? JsonSerializer.Serialize(remote, SyncPayloadJson.Default.SyncPayload) : null, + l.ProxiesCached, l.ProxiesFramesVersion, l.Error, l.SyncedAt, ], cancellationToken); public Task DeleteAsync(string server, Guid remoteId, CancellationToken cancellationToken) => @@ -48,9 +51,9 @@ internal sealed class SyncLinkStore(TitanoDatabase db) _db.ExecuteAsync("UPDATE sequences SET origin = $2 WHERE id = $1", [localId, (int)origin], cancellationToken); /// Upload and download jobs that are waiting, running or paused, by target id (local id for uploads, server id for downloads). - public async Task> ActiveTransfersAsync(CancellationToken cancellationToken) + public async Task>> ActiveTransfersAsync(CancellationToken cancellationToken) { - var transfers = new Dictionary(); + var jobs = new List(); foreach (var kind in new[] { JobKind.UploadCommit, JobKind.Download }) { foreach (var state in Active) @@ -59,16 +62,13 @@ internal sealed class SyncLinkStore(TitanoDatabase db) do { var page = await db.Jobs.ListAsync(state, kind, 500, cursor, cancellationToken).ConfigureAwait(false); - foreach (var job in page.Items) - { - if (job.TargetIds.Count > 0) transfers.TryAdd(job.TargetIds[0], job); - } + jobs.AddRange(page.Items.Where(j => j.TargetIds.Count > 0)); cursor = page.NextCursor; } while (cursor is not null); } } - return transfers; + return jobs.GroupBy(j => j.TargetIds[0]).ToDictionary(g => g.Key, g => (IReadOnlyList)[.. g]); } private static SyncLink Map(DbRow r) => new() @@ -88,13 +88,20 @@ internal sealed class SyncLinkStore(TitanoDatabase db) BaseRemoteSettings = r.GetInt32OrNull(12), DiffLocalFrames = r.GetInt32OrNull(13), DiffRemoteFrames = r.GetInt32OrNull(14), - MissingRemote = r.GetInt32(15), - MissingLocal = r.GetInt32(16), - ConflictLocalSettings = r.GetInt32OrNull(17), - ConflictRemoteSettings = r.GetInt32OrNull(18), - ConflictSettingsJson = r.GetStringOrNull(19), - ProxiesCached = r.GetInt32(20), - ProxiesFramesVersion = r.GetInt32OrNull(21), - SyncedAt = r.GetDateTimeOffsetOrNull(22), + DiffLocalRenders = r.GetInt32OrNull(15), + DiffRemoteRenders = r.GetInt32OrNull(16), + MissingRemote = r.GetInt32(17), + MissingLocal = r.GetInt32(18), + ExportsToGet = r.GetInt32(19), + ExportsToGetBytes = r.GetInt64(20), + ExportsToSend = r.GetInt32(21), + ExportsToSendBytes = r.GetInt64(22), + ConflictLocalSettings = r.GetInt32OrNull(23), + ConflictRemoteSettings = r.GetInt32OrNull(24), + ConflictRemote = r.GetStringOrNull(25) is { } json ? JsonSerializer.Deserialize(json, SyncPayloadJson.Default.SyncPayload) : null, + ProxiesCached = r.GetInt32(26), + ProxiesFramesVersion = r.GetInt32OrNull(27), + Error = r.GetStringOrNull(28), + SyncedAt = r.GetDateTimeOffsetOrNull(29), }; } diff --git a/src/Titano.Data/Sync/SyncModel.cs b/src/Titano.Data/Sync/SyncModel.cs index 7d2e730f..ca465d6c 100644 --- a/src/Titano.Data/Sync/SyncModel.cs +++ b/src/Titano.Data/Sync/SyncModel.cs @@ -20,20 +20,20 @@ public enum SyncStatus /// The server holds originals or settings this PC lacks. ServerAhead, - /// Both sides changed the settings since they last agreed: the user picks. + /// Both sides changed the settings, title, tags, rating or notes since they last agreed: the user picks. Conflict, /// An upload or download job is queued, running or paused. Transferring, } -/// How the user settles a settings conflict (BRIEF §12.7). +/// How the user settles a conflict (BRIEF §12.7). public enum SyncResolution { KeepMine, TakeServer, - /// The server's settings win; this PC's are kept next to the project as a dated copy. + /// The server's version wins; this PC's settings are kept next to the project as a dated copy. SaveBoth, } @@ -45,12 +45,25 @@ public enum SyncDownloadMode /// Proxies (thumbnails where the server has none) into the proxy cache. Proxies, + + /// The server's renders the local copy lacks, into its exports folder. + Exports, +} + +/// What an upload job sends. +public enum SyncUploadMode +{ + /// Originals and settings (creating the server sequence when needed). + Originals, + + /// This PC's renders the server lacks (BRIEF §14.5: renders are uploaded on request). + Exports, } /// /// One server sequence as this client last saw it, linked to its local copy when there is one. The base versions are -/// the settings counters both sides had when they last agreed; the diff versions are the frame counters the missing -/// counts were computed at, so originals are compared again only when either side's frames change. +/// the settings counters both sides had when they last agreed; the diff versions are the frame counters and render +/// counts the missing counts were computed at, so originals and renders are compared again only when either side's change. /// public sealed record SyncLink { @@ -75,6 +88,8 @@ public sealed record SyncLink public int? BaseRemoteSettings { get; init; } public int? DiffLocalFrames { get; init; } public int? DiffRemoteFrames { get; init; } + public int? DiffLocalRenders { get; init; } + public int? DiffRemoteRenders { get; init; } /// Local originals the server does not have. public int MissingRemote { get; init; } @@ -82,13 +97,23 @@ public sealed record SyncLink /// Server originals this PC does not have. public int MissingLocal { get; init; } + /// Server renders the local copy does not have, and their size. + public int ExportsToGet { get; init; } + + public long ExportsToGetBytes { get; init; } + + /// Renders of the local copy the server does not have (whose file is still on this PC), and their size. + public int ExportsToSend { get; init; } + + public long ExportsToSendBytes { get; init; } + /// Settings versions at which the content was found to conflict; null when it does not. public int? ConflictLocalSettings { get; init; } public int? ConflictRemoteSettings { get; init; } - /// The server's settings when the conflict was found, so it can be shown without asking the server again. - public string? ConflictSettingsJson { get; init; } + /// The server's side when the conflict was found: what the user is shown and what "Take server" applies. + public SyncPayload? ConflictRemote { get; init; } /// Frames whose proxy (or thumbnail) is in this PC's proxy cache. public int ProxiesCached { get; init; } @@ -96,6 +121,9 @@ public sealed record SyncLink /// Server frames version the proxy cache was filled at. public int? ProxiesFramesVersion { get; init; } + /// Why the last comparison of this sequence failed (it is compared again next time); null when it worked. + public string? Error { get; init; } + public DateTimeOffset? SyncedAt { get; init; } public bool ServerHasProxies => (RemoteStatus & SequenceStatus.ProxiesBuilt) != 0; @@ -108,7 +136,7 @@ public sealed record SyncLink } /// One row of the sync table: the local sequence, the server sequence, or both, and where they stand. -/// The upload or download job working on it, if any. +/// The upload or download job working on it, if any (the user's before background ones). public sealed record SyncEntry(Sequence? Local, SyncLink? Link, SyncStatus Status, Job? Transfer = null) { public string Title => Local?.DisplayTitle ?? Link?.Title ?? string.Empty; @@ -131,5 +159,12 @@ public sealed record SyncSnapshot(string Server, IReadOnlyList Entrie /// Options a refresh applies. /// Send and take settings changed on one side only (Server.html "Sync projects automatically"). -/// Keep the proxies of every server sequence without local originals in the cache. -public sealed record SyncPolicy(bool AutoSyncSettings = true, bool KeepProxiesOffline = false); +/// Keep the proxy caches of server sequences this PC opened with proxies up to date. +/// The account may change server sequences; without it this PC's edits are never sent. +public sealed record SyncPolicy(bool AutoSyncSettings = true, bool KeepProxiesOffline = false, bool CanEdit = true); + +/// +/// A conflict could not be settled as the user chose because one side changed again after it was shown; the +/// sequence was compared again, so the user can choose on the fresh content. +/// +public sealed class SyncConflictChangedException(string message) : InvalidOperationException(message); diff --git a/src/Titano.Data/Sync/SyncRemote.cs b/src/Titano.Data/Sync/SyncRemote.cs index 70194202..3cf2dc88 100644 --- a/src/Titano.Data/Sync/SyncRemote.cs +++ b/src/Titano.Data/Sync/SyncRemote.cs @@ -38,6 +38,15 @@ public interface ISyncRemote : IDisposable /// Streams a frame's original, proxy or thumb, resuming with Range from the destination's length. Task DownloadFrameAsync(Guid frameId, string kind, Stream destination, CancellationToken cancellationToken); + /// Streams a render's file, resuming with Range from the destination's length; returns the file name the server gives it. + Task DownloadRenderAsync(Guid renderId, Stream destination, CancellationToken cancellationToken); + + /// + /// Chunked, resumable upload of a render of made on this PC; the server verifies the + /// SHA-256 and keeps the render's id. Null when the server already has it. See . + /// + Task UploadRenderAsync(Guid sequenceId, string path, RenderUploadRequest request, CancellationToken cancellationToken); + /// Server events until cancelled or the socket closes. IAsyncEnumerable EventsAsync(CancellationToken cancellationToken); } @@ -99,6 +108,12 @@ public sealed class TitanoSyncRemote(TitanoClient client, bool ownsClient) : ISy public Task DownloadFrameAsync(Guid frameId, string kind, Stream destination, CancellationToken cancellationToken) => client.DownloadFrameAsync(frameId, kind, destination, null, cancellationToken); + public Task DownloadRenderAsync(Guid renderId, Stream destination, CancellationToken cancellationToken) => + client.DownloadRenderAsync(renderId, destination, cancellationToken); + + public Task UploadRenderAsync(Guid sequenceId, string path, RenderUploadRequest request, CancellationToken cancellationToken) => + client.UploadRenderAsync(sequenceId, path, request, null, cancellationToken); + public IAsyncEnumerable EventsAsync(CancellationToken cancellationToken) => client.EventsAsync(cancellationToken); public void Dispose() diff --git a/src/Titano.Data/Sync/SyncRules.cs b/src/Titano.Data/Sync/SyncRules.cs index c9fe5ebe..a8aa0e12 100644 --- a/src/Titano.Data/Sync/SyncRules.cs +++ b/src/Titano.Data/Sync/SyncRules.cs @@ -1,5 +1,7 @@ +using System.Globalization; using System.Text.Json; using System.Text.Json.Nodes; +using System.Text.Json.Serialization; using Titano.Core.Model; using Titano.Core.Project; using Titano.Protocol; @@ -15,8 +17,8 @@ public sealed record SyncPayload(string? Title, IReadOnlyList Tags, int /// Title, tags, rating and notes match (blank equals absent, tags ignore case and order). public bool SameMetadata(SyncPayload other) => - Blank(Title) == Blank(other.Title) - && Blank(Notes) == Blank(other.Notes) + SyncRules.Blank(Title) == SyncRules.Blank(other.Title) + && SyncRules.Blank(Notes) == SyncRules.Blank(other.Notes) && Rating == other.Rating && Tags.ToHashSet(StringComparer.OrdinalIgnoreCase).SetEquals(other.Tags); @@ -25,20 +27,27 @@ public sealed record SyncPayload(string? Title, IReadOnlyList Tags, int /// The PATCH that makes the server's copy equal to this one; settings are sent in their normalised form. public UpdateSequenceRequest ToRequest(int? expectedSettingsVersion) => new(Title ?? string.Empty, Tags, Rating, Notes ?? string.Empty, SyncRules.NormalizeSettings(SettingsJson), expectedSettingsVersion); - - private static string Blank(string? text) => text?.Trim() ?? string.Empty; } -/// One setting that differs: its dotted path ("exposure.deflicker.window") and the JSON value on each side (null when absent). +[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)] +[JsonSerializable(typeof(SyncPayload))] +internal sealed partial class SyncPayloadJson : JsonSerializerContext; + +/// +/// One field that differs: its dotted path ("exposure.deflickerWindow.manual", or "sequence.tags" for the metadata) +/// and the value on each side (JSON for settings, plain text for metadata; null when absent). +/// public sealed record SettingsDifference(string Path, string? Mine, string? Theirs); /// Decisions of the sync engine that need no I/O: the status of a row, settings equality and differences, merges. public static class SyncRules { + /// Path prefix of the title, tags, rating and notes in . + public const string MetadataPath = "sequence."; + /// /// Where a linked pair stands. Settings changed on both sides since they last agreed are a conflict (the engine - /// settles equal content and metadata-only differences before a row is shown); missing originals count before - /// settings changed on one side only. + /// settles equal content before a row is shown); missing originals count before settings changed on one side only. /// public static SyncStatus Status(Sequence? local, SyncLink? link) { @@ -91,13 +100,20 @@ public static class SyncRules } /// - /// Metadata-only divergence (settings equal): tags are united, title, rating and notes come from the side edited last. + /// Up to differences between two payloads: title, tags, rating and notes first (paths + /// sequence.title, sequence.tags, …, tags as one comma-separated value), then the settings. /// - public static SyncPayload Merge(SyncPayload local, SyncPayload remote, bool localIsNewer) + public static IReadOnlyList Differences(SyncPayload mine, SyncPayload theirs, int max = 3) { - var newer = localIsNewer ? local : remote; - var tags = local.Tags.Concat(remote.Tags).Distinct(StringComparer.OrdinalIgnoreCase).ToList(); - return newer with { Tags = tags, SettingsJson = local.SettingsJson }; + var differences = new List(); + if (Blank(mine.Title) != Blank(theirs.Title)) differences.Add(new(MetadataPath + "title", Blank(mine.Title), Blank(theirs.Title))); + if (!mine.Tags.ToHashSet(StringComparer.OrdinalIgnoreCase).SetEquals(theirs.Tags)) + differences.Add(new(MetadataPath + "tags", string.Join(", ", mine.Tags), string.Join(", ", theirs.Tags))); + if (mine.Rating != theirs.Rating) + differences.Add(new(MetadataPath + "rating", mine.Rating.ToString(CultureInfo.InvariantCulture), theirs.Rating.ToString(CultureInfo.InvariantCulture))); + if (Blank(mine.Notes) != Blank(theirs.Notes)) differences.Add(new(MetadataPath + "notes", Blank(mine.Notes), Blank(theirs.Notes))); + if (differences.Count < max) differences.AddRange(Differences(mine.SettingsJson, theirs.SettingsJson, max - differences.Count)); + return differences.Count > max ? differences.GetRange(0, max) : differences; } /// @@ -114,6 +130,8 @@ public static class SyncRules return (hashed.Count - matched + Math.Max(0, unhashed - unmatchedRemote), Math.Max(0, unmatchedRemote - unhashed)); } + internal static string Blank(string? text) => text?.Trim() ?? string.Empty; + private static JsonNode? Parse(string json) { try diff --git a/src/Titano.Data/Sync/SyncService.cs b/src/Titano.Data/Sync/SyncService.cs index dce35e76..4b46f848 100644 --- a/src/Titano.Data/Sync/SyncService.cs +++ b/src/Titano.Data/Sync/SyncService.cs @@ -1,3 +1,4 @@ +using System.Collections.Concurrent; using System.Diagnostics; using System.Globalization; using System.Net; @@ -5,6 +6,7 @@ using System.Text.Json; using Titano.Core.Archiving; using Titano.Core.Diagnostics; using Titano.Core.IO; +using Titano.Core.Localization; using Titano.Core.Model; using Titano.Data.Archiving; using Titano.Data.Jobs; @@ -35,24 +37,33 @@ public sealed record SyncOptions /// /// 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 moved, the manifest: originals are matched by SHA-256 and never conflict; 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 settings is a conflict the user settles -/// with . 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 . Proxies and -/// thumbnails never travel upward. The state of each local sequence is written to its sync_state for the Library. +/// 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. 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. Proxies and thumbnails never travel +/// upward. 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 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 = "titano-sync:"; + /// Recomputes states without sending or taking settings on the user's behalf. + internal static readonly SyncPolicy CompareOnly = new(AutoSyncSettings: false); + private readonly TitanoDatabase _db; private readonly SyncLinkStore _links; private readonly ProjectStore _projects; private readonly SemaphoreSlim _gate = new(1, 1); + /// Unlinked pairs whose manifests were compared at these frame versions without a match (not fetched again). + private readonly ConcurrentDictionary _unmatched = new(StringComparer.Ordinal); + public SyncService(TitanoDatabase db, ArchiveService archives, SyncOptions options) { _db = db; @@ -79,6 +90,9 @@ public sealed class SyncService /// "https://nas.local:8443": the key links are stored under (scheme, lower-case host, port, path). public static string ServerKey(Uri address) => address.GetLeftPart(UriPartial.Path).TrimEnd('/').ToLowerInvariant(); + /// 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"); @@ -86,30 +100,34 @@ public sealed class SyncService /// /// Lists the server, compares every sequence with its local copy, sends or takes settings changed on one side when - /// is on, forgets sequences deleted on the server, and stores the states. + /// is on, forgets sequences the server confirms deleted, links unlinked + /// copies holding the same originals, and stores the states. /// public async Task RefreshAsync(ISyncRemote remote, SyncPolicy policy, CancellationToken cancellationToken) { var clock = Stopwatch.StartNew(); var listing = await remote.ListSequencesAsync(cancellationToken).ConfigureAwait(false); + Dictionary locals; await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); try { var links = (await _links.ListAsync(remote.Server, cancellationToken).ConfigureAwait(false)).ToDictionary(l => l.RemoteId); - var locals = await LocalSequencesAsync(cancellationToken).ConfigureAwait(false); + locals = await LocalSequencesAsync(cancellationToken).ConfigureAwait(false); foreach (var dto in listing) { links.Remove(dto.Id, out var link); - var local = link?.LocalId is { } id ? locals.GetValueOrDefault(id) : null; - await ReconcileSafelyAsync(remote, Observe(link, remote.Server, dto), dto, local, policy, cancellationToken).ConfigureAwait(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); } - foreach (var gone in links.Values) await ForgetAsync(gone, 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); } finally { _gate.Release(); } - var entries = await StoreStatesAsync(remote.Server, cancellationToken).ConfigureAwait(false); + var entries = await StoreStatesAsync(remote.Server, locals, cancellationToken).ConfigureAwait(false); Changed?.Invoke(remote.Server); return new SyncSnapshot(remote.Server, entries, DateTimeOffset.UtcNow, clock.Elapsed); } @@ -123,49 +141,22 @@ public sealed class SyncService foreach (var id in remoteIds) { var link = await _links.GetAsync(remote.Server, id, cancellationToken).ConfigureAwait(false); - SequenceDto dto; - try - { - dto = await remote.GetSequenceAsync(id, cancellationToken).ConfigureAwait(false); - } - catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound) - { - if (link is not null) await ForgetAsync(link, cancellationToken).ConfigureAwait(false); - continue; - } - var local = link?.LocalId is { } localId ? await _db.Sequences.GetAsync(localId, cancellationToken).ConfigureAwait(false) : null; - await ReconcileSafelyAsync(remote, Observe(link, remote.Server, dto), dto, local, policy, cancellationToken).ConfigureAwait(false); + await CompareOneAsync(remote, id, link, null, policy, cancellationToken).ConfigureAwait(false); } } finally { _gate.Release(); } - await StoreStatesAsync(remote.Server, cancellationToken).ConfigureAwait(false); + 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. - public async Task> ListAsync(string server, CancellationToken cancellationToken) - { - var links = await _links.ListAsync(server, cancellationToken).ConfigureAwait(false); - var locals = await LocalSequencesAsync(cancellationToken).ConfigureAwait(false); - var transfers = await _links.ActiveTransfersAsync(cancellationToken).ConfigureAwait(false); - var entries = new List(links.Count + locals.Count); - foreach (var link in links) - { - var local = link.LocalId is { } id && locals.Remove(id, out var found) ? found : null; - var transfer = (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 = transfers.GetValueOrDefault(local.Id); - entries.Add(new SyncEntry(local, null, transfer is null ? SyncStatus.LocalOnly : SyncStatus.Transferring, transfer)); - } - entries.Sort((a, b) => string.Compare(a.Title, b.Title, StringComparison.CurrentCultureIgnoreCase)); - return entries; - } + /// + /// 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 @@ -180,41 +171,73 @@ public sealed class SyncService // ---------------- Settings ---------------- - /// Settles a settings conflict as the user chose (BRIEF §12.7); a 409 means the server changed again meanwhile. - public async Task ResolveAsync(ISyncRemote remote, Guid remoteId, SyncResolution resolution, CancellationToken cancellationToken) + /// + /// 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. 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; 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); - link = Observe(link, remote.Server, dto); - if (resolution == SyncResolution.KeepMine) + if (link is not { ConflictRemote: { } theirs, ConflictLocalSettings: { } seenLocal, ConflictRemoteSettings: { } seenRemote } + || local.SettingsVersion != seenLocal) { - var updated = await remote.UpdateSequenceAsync(remoteId, SyncPayload.Of(local).ToRequest(dto.SettingsVersion), cancellationToken).ConfigureAwait(false); - link = Agreed(Observe(link, remote.Server, updated), local.SettingsVersion, updated.SettingsVersion); + changed = true; + } + else if (resolution == SyncResolution.KeepMine) + { + try + { + var updated = await remote.UpdateSequenceAsync(remoteId, SyncPayload.Of(local).ToRequest(seenRemote), cancellationToken).ConfigureAwait(false); + link = Agreed(Observe(link, remote.Server, updated), local.SettingsVersion, updated.SettingsVersion); + } + catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.Conflict) + { + changed = true; + } } else { - if (resolution == SyncResolution.SaveBoth) await SaveCopyAsync(local, cancellationToken).ConfigureAwait(false); - var manifest = await remote.GetManifestAsync(remoteId, cancellationToken).ConfigureAwait(false); - var applied = await ApplyLocallyAsync(local, SyncPayload.Of(dto, manifest.SettingsJson), cancellationToken).ConfigureAwait(false); - link = Agreed(link, applied.SettingsVersion, manifest.SettingsVersion); + var dto = await remote.GetSequenceAsync(remoteId, cancellationToken).ConfigureAwait(false); + if (dto.SettingsVersion != seenRemote) + { + changed = true; + } + else + { + if (resolution == SyncResolution.SaveBoth) saved = await SaveCopyAsync(local, cancellationToken).ConfigureAwait(false); + var applied = await ApplyLocallyAsync(local, theirs, cancellationToken).ConfigureAwait(false); + link = Agreed(Observe(link, remote.Server, dto), applied.SettingsVersion, seenRemote); + } + } + if (!changed) + { + await _links.UpsertAsync(link with { SyncedAt = DateTimeOffset.UtcNow }, cancellationToken).ConfigureAwait(false); + Log.Info(LogCategory, $"Conflict on {local.DisplayTitle} settled: {resolution}"); } - await _links.UpsertAsync(link with { SyncedAt = DateTimeOffset.UtcNow }, cancellationToken).ConfigureAwait(false); - Log.Info(LogCategory, $"Conflict on {local.DisplayTitle} settled: {resolution}"); } finally { _gate.Release(); } - await StoreStatesAsync(remote.Server, cancellationToken).ConfigureAwait(false); + if (changed) + { + await RefreshSequencesAsync(remote, [remoteId], CompareOnly, cancellationToken).ConfigureAwait(false); + throw new SyncConflictChangedException(Loc.L("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, CancellationToken cancellationToken) => - RefreshSequencesAsync(remote, [remoteId], new SyncPolicy(AutoSyncSettings: true), cancellationToken); + public Task SyncSettingsAsync(ISyncRemote remote, Guid remoteId, SyncPolicy policy, CancellationToken cancellationToken) => + RefreshSequencesAsync(remote, [remoteId], policy with { AutoSyncSettings = true }, cancellationToken); // ---------------- Transfers ---------------- @@ -222,9 +245,16 @@ public sealed class SyncService public Task EnqueueUploadAsync(JobEngine engine, string server, Sequence local, CancellationToken cancellationToken = default) => EnqueueAsync(engine, JobKind.UploadCommit, local.Id, local.DisplayTitle, new SyncJobParameters(server), JobPriority.User, cancellationToken); + /// 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 one is already waiting or running: originals into - /// (ignored when the sequence already has a local copy), or proxies into the cache. + /// 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) => @@ -253,11 +283,34 @@ public sealed class SyncService /// 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) { - var link = await _links.GetAsync(server, remoteId, cancellationToken).ConfigureAwait(false) - ?? new SyncLink { Server = server, RemoteId = remoteId, Title = local.DisplayTitle, RemoteUpdatedAt = DateTimeOffset.UtcNow }; - link = link with { LocalId = local.Id }; - await _links.UpsertAsync(link, cancellationToken).ConfigureAwait(false); - return link; + 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); + return link; + } + 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, cancellationToken).ConfigureAwait(false); + } + finally + { + _gate.Release(); + } } /// @@ -312,6 +365,25 @@ public sealed class SyncService } } + /// + /// 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. internal async Task SetProxiesAsync(string server, SequenceDto dto, int cached, int framesVersion, CancellationToken cancellationToken) { @@ -328,87 +400,151 @@ public sealed class SyncService Changed?.Invoke(server); } - private async Task ReconcileSafelyAsync(ISyncRemote remote, SyncLink link, SequenceDto dto, Sequence? local, SyncPolicy policy, CancellationToken cancellationToken) + /// 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, records a failure on its + /// link. (when given) receives the local copy as it stands after the comparison. + /// + private async Task CompareOneAsync(ISyncRemote remote, Guid remoteId, SyncLink? link, Dictionary? locals, SyncPolicy policy, + CancellationToken cancellationToken) { + SequenceDto dto; try { - link = await ReconcileAsync(remote, link, dto, local, policy, cancellationToken).ConfigureAwait(false); + dto = await remote.GetSequenceAsync(remoteId, cancellationToken).ConfigureAwait(false); } catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound) { - // Deleted between the listing and the manifest: the next refresh forgets it. + if (link is not null) await ForgetAsync(link, cancellationToken).ConfigureAwait(false); + return; + } + 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; + } + var local = await LocalOfAsync(link, locals, cancellationToken).ConfigureAwait(false); + await ReconcileSafelyAsync(remote, Observe(link, remote.Server, dto), dto, local, locals, policy, 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 (TitanoApiException 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 (ex is IOException or UnauthorizedAccessException or InvalidDataException or LeaseUnavailableException) + catch (Exception ex) when (IsIsolated(ex, cancellationToken)) { - // The local archive is offline or busy: compare again next time; the other sequences go on. + // 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); } - /// Compares originals when frame counters moved, then settles the settings; returns the updated link. - private async Task ReconcileAsync(ISyncRemote remote, SyncLink link, SequenceDto dto, Sequence? local, SyncPolicy policy, + /// 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 + { + TitanoApiException 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); + return (link.LocalId is null ? link : Unlinked(link), null); } SequenceManifest? manifest = null; - if (link.DiffLocalFrames != local.FramesVersion || link.DiffRemoteFrames != link.RemoteFramesVersion) + if (link.DiffLocalFrames != local.FramesVersion || link.DiffRemoteFrames != link.RemoteFramesVersion + || link.DiffLocalRenders != local.RenderedCount || link.DiffRemoteRenders != link.RenderCount) { 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 (missingRemote, missingLocal) = SyncRules.CompareOriginals( [.. frames.Where(f => (f.Flags & FrameFlags.Missing) == 0).Select(f => f.Sha256)], [.. manifest.Frames.Select(f => f.Sha256)]); - link = link with + 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, MissingRemote = missingRemote, MissingLocal = missingLocal, }; } - link = await SettleSettingsAsync(remote, link, dto, local, manifest, policy, cancellationToken).ConfigureAwait(false); - return link with { SyncedAt = DateTimeOffset.UtcNow }; + (link, local) = await SettleSettingsAsync(remote, link, dto, local, manifest, policy, cancellationToken).ConfigureAwait(false); + return (link with { SyncedAt = DateTimeOffset.UtcNow }, local); } - private async Task SettleSettingsAsync(ISyncRemote remote, SyncLink link, SequenceDto dto, Sequence local, SequenceManifest? manifest, - SyncPolicy policy, CancellationToken cancellationToken) + /// 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; + if (!localChanged && !remoteChanged) return (link, local); if (localChanged && remoteChanged) { - if (link.ConflictLocalSettings == local.SettingsVersion && link.ConflictRemoteSettings == link.RemoteSettingsVersion) return link; + 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); var mine = SyncPayload.Of(local); var theirs = SyncPayload.Of(dto, manifest.SettingsJson); - if (mine.SameAs(theirs)) return Agreed(link, local.SettingsVersion, manifest.SettingsVersion); - if (!SyncRules.SameSettings(mine.SettingsJson, theirs.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 { - return link with - { - ConflictLocalSettings = local.SettingsVersion, - ConflictRemoteSettings = link.RemoteSettingsVersion, - ConflictSettingsJson = SyncRules.NormalizeSettings(theirs.SettingsJson), - }; - } - // Only title, tags, rating or notes differ: merge them and give both sides the result. - var merged = SyncRules.Merge(mine, theirs, local.UpdatedAt >= dto.UpdatedAt); - var applied = merged.SameMetadata(mine) ? local : await ApplyLocallyAsync(local, merged, cancellationToken).ConfigureAwait(false); - return await PushAsync(remote, link, applied, manifest.SettingsVersion, cancellationToken).ConfigureAwait(false); + ConflictLocalSettings = local.SettingsVersion, + ConflictRemoteSettings = manifest.SettingsVersion, + ConflictRemote = theirs with { SettingsJson = SyncRules.NormalizeSettings(theirs.SettingsJson) }, + }, local); } - if (!policy.AutoSyncSettings) return link; - if (localChanged) return await PushAsync(remote, link, local, link.BaseRemoteSettings, cancellationToken).ConfigureAwait(false); + if (!policy.AutoSyncSettings) return (link, local); + if (localChanged) + return (policy.CanEdit ? await PushAsync(remote, link, local, link.BaseRemoteSettings, cancellationToken).ConfigureAwait(false) : link, local); manifest ??= await remote.GetManifestAsync(link.RemoteId, cancellationToken).ConfigureAwait(false); + if (manifest.SettingsVersion != dto.SettingsVersion) return (link, local); var pulled = await ApplyLocallyAsync(local, SyncPayload.Of(dto, manifest.SettingsJson), cancellationToken).ConfigureAwait(false); - return Agreed(link, pulled.SettingsVersion, manifest.SettingsVersion); + return (Agreed(link, pulled.SettingsVersion, manifest.SettingsVersion), pulled); } /// Sends this PC's payload unless the server moved past , which shows up as a conflict next. @@ -425,6 +561,62 @@ public sealed class SyncService } } + /// + /// 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. + /// + private async Task MatchByContentAsync(ISyncRemote remote, IReadOnlyList listing, Dictionary 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; + } + } + } + + private async Task SameOriginalsAsync(ISyncRemote remote, Sequence local, SequenceDto dto, CancellationToken cancellationToken) + { + var hashes = (await SequenceFrames.ListAsync(_db, local.Id, cancellationToken).ConfigureAwait(false)) + .Select(f => f.Sha256?.ToLowerInvariant()).OfType().ToHashSet(StringComparer.Ordinal); + if (hashes.Count == 0) return false; + var manifest = await remote.GetManifestAsync(dto.Id, cancellationToken).ConfigureAwait(false); + var shared = manifest.Frames.Select(f => f.Sha256.ToLowerInvariant()).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); + /// Writes a payload into the local sidecar, project and index (each write bumps the local settings version). private async Task ApplyLocallyAsync(Sequence local, SyncPayload payload, CancellationToken cancellationToken) { @@ -441,18 +633,21 @@ public sealed class SyncService return await _db.Sequences.GetAsync(local.Id, cancellationToken).ConfigureAwait(false) ?? current; } - /// "Save both": this PC's project is kept as .titano/project.local-<UTC time>.json before the server's replaces it. - private async Task SaveCopyAsync(Sequence local, CancellationToken cancellationToken) + /// "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. + 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 folder = new ArchivePaths(archive.RootPath).Sequence(local.Folder); Directory.CreateDirectory(folder.MetaDirectory); - var name = string.Create(CultureInfo.InvariantCulture, $"project.local-{DateTime.UtcNow:yyyyMMdd-HHmmss}.json"); - AtomicFile.WriteAllText(Path.Combine(folder.MetaDirectory, name), SyncRules.NormalizeSettings(local.SettingsJson)); - Log.Info(LogCategory, $"Settings of {local.DisplayTitle} kept as {name}"); + var 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; } + internal static string SavedCopyName(DateTime localTime) => string.Create(CultureInfo.InvariantCulture, $"project.this-pc-{localTime:yyyyMMdd-HHmmss}.json"); + private async Task ForgetAsync(SyncLink link, CancellationToken cancellationToken) { await _links.DeleteAsync(link.Server, link.RemoteId, cancellationToken).ConfigureAwait(false); @@ -461,9 +656,9 @@ public sealed class SyncService } /// Writes each local sequence's state for the Library and returns the table. - private async Task> StoreStatesAsync(string server, CancellationToken cancellationToken) + private async Task> StoreStatesAsync(string server, Dictionary? locals, CancellationToken cancellationToken) { - var entries = await ListAsync(server, cancellationToken).ConfigureAwait(false); + 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) @@ -472,6 +667,50 @@ public sealed class SyncService 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); @@ -498,8 +737,16 @@ public sealed class SyncService private async Task EnqueueAsync(JobEngine engine, JobKind kind, Guid target, string label, SyncJobParameters parameters, JobPriority priority, CancellationToken cancellationToken) { - var active = await _links.ActiveTransfersAsync(cancellationToken).ConfigureAwait(false); - if (active.TryGetValue(target, out var running) && running.Kind == kind) return running; + 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; + if (running == wanted && !outranked) 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); } @@ -525,7 +772,7 @@ public sealed class SyncService RemoteSettingsVersion = remoteVersion, ConflictLocalSettings = null, ConflictRemoteSettings = null, - ConflictSettingsJson = null, + ConflictRemote = null, }; private static SyncLink Unlinked(SyncLink link) => link with @@ -535,10 +782,16 @@ public sealed class SyncService BaseRemoteSettings = null, DiffLocalFrames = null, DiffRemoteFrames = null, + DiffLocalRenders = null, + DiffRemoteRenders = null, MissingRemote = 0, MissingLocal = 0, + ExportsToGet = 0, + ExportsToGetBytes = 0, + ExportsToSend = 0, + ExportsToSendBytes = 0, ConflictLocalSettings = null, ConflictRemoteSettings = null, - ConflictSettingsJson = null, + ConflictRemote = null, }; } diff --git a/src/Titano.Data/Sync/SyncTransfers.cs b/src/Titano.Data/Sync/SyncTransfers.cs index 9f993d92..3fb1fa6b 100644 --- a/src/Titano.Data/Sync/SyncTransfers.cs +++ b/src/Titano.Data/Sync/SyncTransfers.cs @@ -19,15 +19,18 @@ namespace Titano.Data.Sync; /// 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. +/// sequence, which then takes the server's settings. Frames of the local copy not hashed yet are hashed first (so the +/// server's copies of them are recognised), and originals flagged missing here are restored to their recorded place. +/// Proxy downloads fill the proxy cache. Renders travel on request: this PC's to the server (hash-verified chunked +/// upload) and the server's into the local copy's exports. A resumed job skips what is already on the other side, so +/// pausing or a crash loses at most the files in flight. /// internal sealed class SyncTransfers(SyncService sync) { private const long SpaceReserve = 512L << 20; - /// Recomputes a sequence's state after a transfer without sending or taking settings on the user's behalf. - private static readonly SyncPolicy CompareOnly = new(AutoSyncSettings: false); + /// Space a cached proxy is assumed to take before it is downloaded (1920 px JPEG, BRIEF §8.5). + private const long ProxyEstimate = 3L << 19; public async Task UploadAsync(JobContext context, ISyncRemote remote, Guid localId) { @@ -72,7 +75,7 @@ internal sealed class SyncTransfers(SyncService sync) }).ConfigureAwait(false); if (created) await sync.PushAllAsync(remote, target, ct).ConfigureAwait(false); - await sync.RefreshSequencesAsync(remote, [target], CompareOnly, ct).ConfigureAwait(false); + await sync.RecompareAsync(remote, target, ct).ConfigureAwait(false); if (skipped > 0) throw new InvalidDataException(Loc.Plural("Errors.Sync.Unreadable", skipped)); } @@ -89,10 +92,8 @@ internal sealed class SyncTransfers(SyncService sync) 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 have = local is null - ? new HashSet() - : (await SequenceFrames.ListAsync(db, local.Id, ct).ConfigureAwait(false)).Select(f => f.Sha256).OfType().ToHashSet(StringComparer.OrdinalIgnoreCase); - var wanted = manifest.Frames.Where(f => !have.Contains(f.Sha256)).DistinctBy(f => f.Sha256.ToLowerInvariant()).ToList(); + var (have, restore) = local is null ? ([], []) : await LocalContentAsync(archive, local, ct).ConfigureAwait(false); + var wanted = manifest.Frames.Where(f => !have.Contains(f.Sha256.ToLowerInvariant())).DistinctBy(f => f.Sha256.ToLowerInvariant()).ToList(); EnsureSpace(paths.Root, wanted.Sum(f => f.Size)); var staging = Path.Combine(paths.StagingDirectory, "sync-" + remoteId.ToString("N")); @@ -114,16 +115,27 @@ internal sealed class SyncTransfers(SyncService sync) await progress.StepAsync().ConfigureAwait(false); } var sequenceId = local?.Id; + var restored = 0; 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); + if (restore.TryGetValue(frame.Sha256.ToLowerInvariant(), out var place)) + { + await RestoreAsync(remote, frame, staging, place, token).ConfigureAwait(false); + Interlocked.Increment(ref restored); + } + else + { + await CommitAsync(remote, remoteId, archive.Id, sequenceId, frame, staging, captured, token).ConfigureAwait(false); + } await progress.StepAsync().ConfigureAwait(false); }).ConfigureAwait(false); TryDeleteDirectory(staging); + // Restored originals are checked against their records, which clears their missing flag. + if (restored > 0) await VerifyAsync(archive, local!.Id, ct).ConfigureAwait(false); 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) + await sync.RecompareAsync(remote, remoteId, ct).ConfigureAwait(false); + if (sequenceId is { } downloaded && wanted.Count > restored) { var label = local!.DisplayTitle; await EnqueueFollowUpAsync(ArchiveJobs.Thumbnails([downloaded], label), ct).ConfigureAwait(false); @@ -131,6 +143,161 @@ internal sealed class SyncTransfers(SyncService sync) } } + /// + /// The originals a local copy holds (lower-case SHA-256) and where each original flagged missing belongs. Frames + /// not hashed yet (an adopted folder never verified) are hashed first through the archive's verify, so the + /// server's copies of them are recognised instead of committed again as duplicates. + /// + private async Task<(HashSet Have, Dictionary Restore)> LocalContentAsync(Archive archive, Sequence local, CancellationToken ct) + { + var frames = await SequenceFrames.ListAsync(sync.Database, local.Id, ct).ConfigureAwait(false); + if (frames.Any(f => f.Sha256 is null && (f.Flags & FrameFlags.Missing) == 0)) + { + await VerifyAsync(archive, local.Id, ct).ConfigureAwait(false); + frames = await SequenceFrames.ListAsync(sync.Database, local.Id, ct).ConfigureAwait(false); + } + var have = frames.Where(f => (f.Flags & FrameFlags.Missing) == 0 && f.Sha256 is not null).Select(f => f.Sha256!.ToLowerInvariant()) + .ToHashSet(StringComparer.Ordinal); + var paths = new ArchivePaths(archive.RootPath); + var restore = new Dictionary(StringComparer.Ordinal); + foreach (var frame in frames.Where(f => (f.Flags & FrameFlags.Missing) != 0 && f.Sha256 is not null)) + { + var sha = frame.Sha256!.ToLowerInvariant(); + if (!have.Contains(sha)) restore.TryAdd(sha, paths.FromRelative(frame.RelativePath)); + } + return (have, restore); + } + + private Task VerifyAsync(Archive archive, Guid sequenceId, CancellationToken ct) => + sync.Archives.Verifier.VerifyAsync(archive, [sequenceId], default, (_, _, _) => ValueTask.CompletedTask, cancellationToken: ct); + + /// Puts a verified copy of an original flagged missing back where its record says; a file that reappeared meanwhile is kept. + private static async Task RestoreAsync(ISyncRemote remote, ManifestFrame frame, string staging, string place, CancellationToken cancellationToken) + { + var staged = await FetchOriginalAsync(remote, frame, staging, cancellationToken).ConfigureAwait(false); + if (File.Exists(place)) + { + File.Delete(staged); + return; + } + Directory.CreateDirectory(Path.GetDirectoryName(place)!); + File.Move(staged, place, overwrite: false); + } + + public async Task SendExportsAsync(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 link = await sync.Links.FindByLocalAsync(remote.Server, local.Id, ct).ConfigureAwait(false) + ?? throw new InvalidOperationException(Loc.L("Errors.Sync.NotLinked")); + var there = (await remote.GetManifestAsync(link.RemoteId, ct).ConfigureAwait(false)).Renders.Select(r => r.Id).ToHashSet(); + var renders = (await db.Renders.ListBySequenceAsync(local.Id, ct).ConfigureAwait(false)).Where(r => !there.Contains(r.Id)).ToList(); + var progress = new TransferProgress(context, renders.Count, 0); + await progress.ReportAsync().ConfigureAwait(false); + var gone = 0; + foreach (var render in renders) + { + var file = SyncService.RenderFile(archive, render); + if (File.Exists(file)) + { + var sha = await TitanoClient.HashFileAsync(file, ct).ConfigureAwait(false); + await remote.UploadRenderAsync(link.RemoteId, file, new RenderUploadRequest(render.Id, Path.GetFileName(file), new FileInfo(file).Length, sha, + render.PresetName, render.Codec, render.Width, render.Height, render.Fps, render.DurationSeconds, render.ProducedBy), ct).ConfigureAwait(false); + } + else + { + gone++; + } + await progress.StepAsync().ConfigureAwait(false); + } + await sync.RecompareAsync(remote, link.RemoteId, ct).ConfigureAwait(false); + if (gone > 0) throw new FileNotFoundException(Loc.Plural("Errors.Sync.ExportsGone", gone)); + } + + public async Task GetExportsAsync(JobContext context, ISyncRemote remote, Guid remoteId) + { + 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) + ?? 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); + ArchiveVolume.EnsureWritable(paths); + var here = (await db.Renders.ListBySequenceAsync(local.Id, ct).ConfigureAwait(false)).Select(r => r.Id).ToHashSet(); + var wanted = (await remote.GetManifestAsync(remoteId, ct).ConfigureAwait(false)).Renders.Where(r => !here.Contains(r.Id)).ToList(); + EnsureSpace(paths.Root, wanted.Sum(r => r.Bytes)); + + var staging = Path.Combine(paths.StagingDirectory, "exports-" + remoteId.ToString("N")); + var exports = paths.Sequence(local.Folder).Exports; + Directory.CreateDirectory(staging); + Directory.CreateDirectory(exports); + var progress = new TransferProgress(context, wanted.Count, 0); + await progress.ReportAsync().ConfigureAwait(false); + foreach (var render in wanted) + { + var (part, name) = await FetchRenderAsync(remote, render, staging, ct).ConfigureAwait(false); + var target = Unique(exports, name); + File.Move(part, target); + await db.Renders.InsertAsync(new Render + { + Id = render.Id, + SequenceId = local.Id, + PresetName = render.PresetName, + OutputPath = paths.ToRelative(target), + Codec = render.Codec, + Width = render.Width, + Height = render.Height, + Fps = render.Fps, + DurationSeconds = render.DurationSeconds, + Bytes = new FileInfo(target).Length, + Created = render.Created, + ProducedBy = render.ProducedBy, + }, ct).ConfigureAwait(false); + await progress.StepAsync().ConfigureAwait(false); + } + TryDeleteDirectory(staging); + await sync.RecompareAsync(remote, remoteId, ct).ConfigureAwait(false); + } + + /// A render's file in staging (resumed with Range; started over once if the partial copy no longer fits) and the name the server gives it. + private static async Task<(string Part, string Name)> FetchRenderAsync(ISyncRemote remote, RenderDto render, string staging, CancellationToken cancellationToken) + { + var part = Path.Combine(staging, render.Id.ToString("N") + ".part"); + for (var attempt = 1; ; attempt++) + { + try + { + string? name; + await using (var file = new FileStream(part, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)) + name = await remote.DownloadRenderAsync(render.Id, file, cancellationToken).ConfigureAwait(false); + return (part, SafeFileName(name) ?? render.Id.ToString("N")); + } + catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.RequestedRangeNotSatisfiable && attempt == 1) + { + File.Delete(part); + } + } + } + + private static string? SafeFileName(string? name) + { + var file = Path.GetFileName(name?.Trim()); + return string.IsNullOrEmpty(file) || file.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || file is "." or ".." ? null : file; + } + + /// "name.mp4", else "name (2).mp4", … — an existing export is never replaced. + private static string Unique(string folder, string fileName) + { + var candidate = Path.Combine(folder, fileName); + var stem = Path.GetFileNameWithoutExtension(fileName); + var extension = Path.GetExtension(fileName); + for (var n = 2; File.Exists(candidate); n++) candidate = Path.Combine(folder, string.Create(CultureInfo.InvariantCulture, $"{stem} ({n}){extension}")); + return candidate; + } + public async Task DownloadProxiesAsync(JobContext context, ISyncRemote remote, Guid remoteId) { var ct = context.Cancellation; @@ -141,6 +308,7 @@ internal sealed class SyncTransfers(SyncService sync) var folder = sync.Proxies.Folder(remote.Server, remoteId); Directory.CreateDirectory(folder); ProxyCache.Prune(folder, frames.Select(f => ProxyCache.FileName(f.Id)).ToHashSet(StringComparer.Ordinal)); + EnsureSpace(folder, frames.Count(f => !File.Exists(Path.Combine(folder, ProxyCache.FileName(f.Id)))) * ProxyEstimate); var files = new string?[frames.Count]; var progress = new TransferProgress(context, frames.Count, 0); @@ -176,7 +344,7 @@ internal sealed class SyncTransfers(SyncService sync) return (id, id == started); } // Deleted on the server meanwhile: the originals go into a new sequence. - if (id == link?.RemoteId) await sync.Links.DeleteAsync(remote.Server, id, ct).ConfigureAwait(false); + if (id == link?.RemoteId) await sync.ForgetGoneAsync(remote.Server, id, ct).ConfigureAwait(false); } return (null, true); } diff --git a/src/Titano.Protocol/Client/TitanoClient.cs b/src/Titano.Protocol/Client/TitanoClient.cs index d843ca82..96fe88a8 100644 --- a/src/Titano.Protocol/Client/TitanoClient.cs +++ b/src/Titano.Protocol/Client/TitanoClient.cs @@ -175,6 +175,46 @@ public sealed class TitanoClient : IDisposable .ConfigureAwait(false); } + /// + /// Sends a render of made on this PC in resumable chunks; the server verifies the + /// SHA-256 in and files it under the sequence's exports with the same id. Null when the + /// server already has that render. + /// + public async Task UploadRenderAsync(Guid sequenceId, string path, RenderUploadRequest request, IProgress? progress = null, + CancellationToken ct = default) + { + var length = new FileInfo(path).Length; + if (length != request.Size) throw new ArgumentException("The render size does not match the file.", nameof(request)); + var start = await RetryAsync(() => SendAsync(HttpMethod.Post, $"api/v1/sequences/{sequenceId}/renders", request, + ProtocolJson.Default.RenderUploadRequest, ProtocolJson.Default.StartUploadResponse, ct), ct).ConfigureAwait(false); + if (start.AlreadyExists) return null; + var uploadId = start.UploadId ?? throw new InvalidOperationException("Server returned no upload id."); + await SendChunksAsync(path, length, uploadId, start.ChunkSize, start.Received, progress, ct).ConfigureAwait(false); + return await RetryAsync(() => SendAsync(HttpMethod.Post, $"api/v1/sequences/{sequenceId}/renders/{uploadId}/complete", + ProtocolJson.Default.RenderDto, ct), ct).ConfigureAwait(false); + } + + /// + /// Streams a render's file to , resuming with Range from its current length; returns + /// the file name the server gives it. + /// + public async Task DownloadRenderAsync(Guid renderId, Stream destination, CancellationToken ct = default) + { + using var request = new HttpRequestMessage(HttpMethod.Get, $"api/v1/renders/{renderId}/file"); + if (destination.CanSeek && destination.Length > 0) + { + destination.Seek(0, SeekOrigin.End); + request.Headers.Range = new RangeHeaderValue(destination.Length, null); + } + using var response = await _http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false); + await EnsureSuccessAsync(response, ct).ConfigureAwait(false); + if (response.StatusCode == HttpStatusCode.OK && destination.CanSeek) destination.SetLength(0); + await using var body = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false); + await body.CopyToAsync(destination, ct).ConfigureAwait(false); + var disposition = response.Content.Headers.ContentDisposition; + return (disposition?.FileNameStar ?? disposition?.FileName)?.Trim('"'); + } + /// Sends every chunk the server does not have yet; each PUT is idempotent and retried on transient errors. private async Task SendChunksAsync(string path, long length, Guid uploadId, int chunkSize, IReadOnlyList alreadyReceived, IProgress? progress, CancellationToken ct) diff --git a/src/Titano.Protocol/ProtocolJson.cs b/src/Titano.Protocol/ProtocolJson.cs index 2db29cac..7af9a1b2 100644 --- a/src/Titano.Protocol/ProtocolJson.cs +++ b/src/Titano.Protocol/ProtocolJson.cs @@ -56,6 +56,7 @@ namespace Titano.Protocol; [JsonSerializable(typeof(JobPriorityRequest))] [JsonSerializable(typeof(RenderJobParameters))] [JsonSerializable(typeof(RenderResultRequest))] +[JsonSerializable(typeof(RenderUploadRequest))] [JsonSerializable(typeof(NodeJobFailure))] [JsonSerializable(typeof(ServerSettingsDto))] [JsonSerializable(typeof(LogFileDto))] diff --git a/src/Titano.Protocol/Uploads.cs b/src/Titano.Protocol/Uploads.cs index b2ff863c..3be2f2e7 100644 --- a/src/Titano.Protocol/Uploads.cs +++ b/src/Titano.Protocol/Uploads.cs @@ -16,3 +16,23 @@ public sealed record CompleteUploadResponse(Guid FrameId, Guid SequenceId, int I /// GET /api/v1/uploads/{id}: resume state. public sealed record UploadState(Guid UploadId, string FileName, long Size, string Sha256, int ChunkSize, IReadOnlyList Received, string State); + +/// +/// POST /api/v1/sequences/{id}/renders: a client offers one of its renders of the sequence (BRIEF §14.5, +/// renders are uploaded on request). The render keeps its id on the server, so both sides recognise it; when the +/// server already has that id it answers 200 with . Chunks go to +/// /uploads/{uploadId}/chunks/{n}; POST /sequences/{id}/renders/{uploadId}/complete verifies the SHA-256 +/// and files the render under the sequence's exports. +/// +public sealed record RenderUploadRequest( + Guid RenderId, + string FileName, + long Size, + string Sha256, + string PresetName, + string? Codec, + int Width, + int Height, + double Fps, + double DurationSeconds, + string? ProducedBy); diff --git a/src/Titano.Server/Api/SequenceEndpoints.cs b/src/Titano.Server/Api/SequenceEndpoints.cs index dae6adf2..af64e3cc 100644 --- a/src/Titano.Server/Api/SequenceEndpoints.cs +++ b/src/Titano.Server/Api/SequenceEndpoints.cs @@ -37,6 +37,15 @@ public static class SequenceEndpoints sequences.MapGet("/{id:guid}/analysis", AnalysisAsync).Requires(Permissions.Read); sequences.MapGet("/{id:guid}/stats", StatsAsync).Requires(Permissions.Read); sequences.MapGet("/{id:guid}/renders", RendersAsync).Requires(Permissions.Read); + // Renders made on a client, sent on request (BRIEF §14.5); chunks go through /uploads. + sequences.MapPost("/{id:guid}/renders", async (HttpContext c, Caller caller, Guid id, RenderUploadRequest request, RenderUploads uploads) => + (await uploads.StartAsync(caller, id, request, c.RequestAborted)).ToResult(c, r => Results.Json(r, ProtocolJson.Default.StartUploadResponse, + statusCode: r.AlreadyExists ? StatusCodes.Status200OK : StatusCodes.Status201Created))).Requires(Permissions.Upload | Permissions.Edit); + sequences.MapPost("/{id:guid}/renders/{uploadId:guid}/complete", async (HttpContext c, Caller caller, Guid id, Guid uploadId, RenderUploads uploads, + IHostApplicationLifetime lifetime) => + // The commit runs to the end even if the client disconnects meanwhile. + (await uploads.CompleteAsync(caller, id, uploadId, lifetime.ApplicationStopping)).ToResult(c, r => Results.Json(r, ProtocolJson.Default.RenderDto))) + .Requires(Permissions.Upload | Permissions.Edit); } private static async Task ListAsync(HttpContext context, TitanoDatabase db, ServerArchive archive, int? year, string? camera, string? status, diff --git a/src/Titano.Server/Hosting/ServerHost.cs b/src/Titano.Server/Hosting/ServerHost.cs index a06cf32f..7ae2b5b8 100644 --- a/src/Titano.Server/Hosting/ServerHost.cs +++ b/src/Titano.Server/Hosting/ServerHost.cs @@ -121,6 +121,7 @@ public static class ServerHost services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/Titano.Server/Storage/RenderStore.cs b/src/Titano.Server/Storage/RenderStore.cs index 841e3f95..c23784d8 100644 --- a/src/Titano.Server/Storage/RenderStore.cs +++ b/src/Titano.Server/Storage/RenderStore.cs @@ -12,7 +12,12 @@ public sealed class RenderStore(TitanoDatabase db, ServerArchive archive, TimePr /// Moves (on the archive volume) to <sequence folder>/exports/, never /// replacing an existing export, and inserts the render row. Null when the sequence has no folder in the archive yet. /// - public async Task CommitAsync(Sequence sequence, string stagedFile, RenderResultRequest output, string producedBy, CancellationToken cancellationToken) + public Task CommitAsync(Sequence sequence, string stagedFile, RenderResultRequest output, string producedBy, CancellationToken cancellationToken) => + CommitAsync(sequence, stagedFile, output, producedBy, Guid.CreateVersion7(), cancellationToken); + + /// As above, keeping : a render a client sends keeps the id it has on that client. + public async Task CommitAsync(Sequence sequence, string stagedFile, RenderResultRequest output, string producedBy, Guid id, + CancellationToken cancellationToken) { if (string.IsNullOrEmpty(sequence.Folder) || ArchivePathGuard.Resolve(archive.Root, sequence.Folder.TrimEnd('/') + "/exports") is not { } exports) return null; @@ -21,7 +26,7 @@ public sealed class RenderStore(TitanoDatabase db, ServerArchive archive, TimePr File.Move(stagedFile, target); var render = new Render { - Id = Guid.CreateVersion7(), + Id = id, SequenceId = sequence.Id, PresetName = output.PresetName, OutputPath = LongPath.ToPortableRelative(archive.Root, target), diff --git a/src/Titano.Server/Storage/RenderUploads.cs b/src/Titano.Server/Storage/RenderUploads.cs new file mode 100644 index 00000000..f0345a41 --- /dev/null +++ b/src/Titano.Server/Storage/RenderUploads.cs @@ -0,0 +1,118 @@ +using System.Globalization; +using System.Text.Json; +using Titano.Data; +using Titano.Data.Repositories; +using Titano.Protocol; +using Titano.Server.Api; +using Titano.Server.Configuration; +using Titano.Server.Events; +using Titano.Server.Security; +using UploadState = Titano.Data.Repositories.UploadState; + +namespace Titano.Server.Storage; + +/// +/// Renders a client sends on request (BRIEF §14.5): chunked like frame uploads (same store, chunk endpoint and +/// retention), verified against their SHA-256 at completion and filed by under the +/// sequence's exports with the client's render id, so both sides recognise the same render. +/// +public sealed class RenderUploads( + TitanoDatabase db, + ServerOptions options, + UploadService uploads, + UploadStore store, + RenderStore renders, + EventHub events, + TimeProvider time) +{ + public async Task> StartAsync(Caller caller, Guid sequenceId, RenderUploadRequest request, CancellationToken cancellationToken) + { + if (await db.Sequences.GetAsync(sequenceId, cancellationToken) is null) return Outcome.Fail(404, "not_found", "sequence"); + if (UploadRules.SafeFileName(request.FileName) is not { } fileName) return Outcome.Fail(400, "invalid_file_name"); + if (!UploadRules.IsSha256(request.Sha256)) return Outcome.Fail(400, "invalid_hash"); + if (request.Size <= 0) return Outcome.Fail(400, "bad_request", "size"); + if (request.Size > options.MaxUploadBytes) + return Outcome.Fail(413, "too_large", options.MaxUploadBytes.ToString(CultureInfo.InvariantCulture)); + if (string.IsNullOrWhiteSpace(request.PresetName) || request.PresetName.Length > 200) return Outcome.Fail(400, "bad_request", "presetName"); + if (request.RenderId == Guid.Empty) return Outcome.Fail(400, "bad_request", "renderId"); + + if (await db.Renders.GetAsync(request.RenderId, cancellationToken) is { } known) + { + return known.SequenceId == sequenceId + ? new StartUploadResponse(null, options.ChunkSizeBytes, [], AlreadyExists: true, null) + : Outcome.Fail(409, "render_exists"); + } + var sha = request.Sha256.ToLowerInvariant(); + if (await db.Uploads.FindReceivingAsync(caller.Id, sha, cancellationToken) is { } open && open.SequenceId == sequenceId && open.Size == request.Size + && Read(open)?.RenderId == request.RenderId && store.Exists(open.Id)) + return Started(open); + if (UploadRules.FreeBytes(options.UploadsPath) is { } free && free < request.Size) return Outcome.Fail(507, "insufficient_storage"); + + var now = time.GetUtcNow(); + var upload = await db.Uploads.CreateAsync(new Upload + { + Id = Guid.CreateVersion7(), + UserId = caller.Id, + SequenceId = sequenceId, + FileName = fileName, + Size = request.Size, + Sha256 = sha, + ChunkSize = options.ChunkSizeBytes, + State = UploadState.Receiving, + Created = now, + UpdatedAt = now, + RenderJson = JsonSerializer.Serialize(request with { FileName = fileName, Sha256 = sha }, ProtocolJson.Default.RenderUploadRequest), + }, cancellationToken); + store.Create(upload.Id, upload.Size); + return Started(upload); + } + + /// Verifies a fully received render and files it; completing a committed one answers it again (a lost response). + public async Task> CompleteAsync(Caller caller, Guid sequenceId, Guid uploadId, CancellationToken cancellationToken) + { + var upload = await db.Uploads.GetAsync(uploadId, cancellationToken); + if (upload is null || upload.UserId != caller.Id || upload.SequenceId != sequenceId || upload.JobId is not null || Read(upload) is not { } output) + return Outcome.Fail(404, "not_found", "upload"); + if (upload.State == UploadState.Committed && await db.Renders.GetAsync(output.RenderId, cancellationToken) is { } done) return Dto.Render(done); + if (upload.State != UploadState.Receiving) return Outcome.Fail(409, "upload_state"); + if (!upload.IsComplete) + return Outcome.Fail(409, "incomplete", (upload.ChunkCount - upload.ReceivedCount).ToString(CultureInfo.InvariantCulture)); + if (!await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Receiving, UploadState.Committing, cancellationToken: cancellationToken)) + return Outcome.Fail(409, "upload_state"); + + if (await uploads.StageVerifiedAsync(upload, cancellationToken) is not { } staged) return Outcome.Fail(422, "hash_mismatch"); + var sequence = await db.Sequences.GetAsync(sequenceId, cancellationToken); + var result = new RenderResultRequest(output.FileName, output.Size, output.Sha256, output.PresetName, output.Codec, output.Width, output.Height, output.Fps, + output.DurationSeconds); + var render = sequence is null ? null : await renders.CommitAsync(sequence, staged, result, output.ProducedBy ?? caller.ClientName ?? caller.User.Username, + output.RenderId, cancellationToken); + if (render is null) + { + UploadStore.TryDelete(staged); + await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Committing, UploadState.Failed, cancellationToken: CancellationToken.None); + store.Delete(upload.Id); + return Outcome.Fail(409, "upload_state", "sequence"); + } + await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Committing, UploadState.Committed, cancellationToken: CancellationToken.None); + store.Delete(upload.Id); + if (await db.Sequences.GetAsync(sequenceId, CancellationToken.None) is { } updated) + events.Publish(new SequenceChangedEvent(updated.Id, "renders", updated.FramesVersion, updated.SettingsVersion)); + return Dto.Render(render); + } + + private static RenderUploadRequest? Read(Upload upload) + { + if (upload.RenderJson is not { } json) return null; + try + { + return JsonSerializer.Deserialize(json, ProtocolJson.Default.RenderUploadRequest) is { RenderId: var id } request && id != Guid.Empty ? request : null; + } + catch (JsonException) + { + return null; + } + } + + private static StartUploadResponse Started(Upload upload) => + new(upload.Id, upload.ChunkSize, UploadRules.ReceivedChunks(upload), AlreadyExists: false, FrameId: null); +} diff --git a/src/Titano.Server/Storage/UploadService.cs b/src/Titano.Server/Storage/UploadService.cs index cef9f2ff..327bd02d 100644 --- a/src/Titano.Server/Storage/UploadService.cs +++ b/src/Titano.Server/Storage/UploadService.cs @@ -144,7 +144,7 @@ public sealed class UploadService( var stopping = lifetime.ApplicationStopping; var upload = await db.Uploads.GetAsync(id, stopping); if (upload is null || upload.UserId != caller.Id) return Fail(404, "not_found", "upload"); - if (upload.JobId is not null) return Fail(409, "wrong_upload_kind"); + if (upload.JobId is not null || upload.RenderJson is not null) return Fail(409, "wrong_upload_kind"); if (upload is { State: UploadState.Committed, FrameId: { } committed } && await db.Frames.GetAsync(committed, stopping) is { } done) return new CompleteUploadResponse(done.Id, done.SequenceId, done.Index); if (upload.State != UploadState.Receiving) return Fail(409, "upload_state"); diff --git a/src/Titano.Ui/Themes/Controls.xaml b/src/Titano.Ui/Themes/Controls.xaml index 2a689464..a22debfb 100644 --- a/src/Titano.Ui/Themes/Controls.xaml +++ b/src/Titano.Ui/Themes/Controls.xaml @@ -1248,10 +1248,11 @@ - + + - - + + diff --git a/tests/Titano.App.Tests/Server/ServerScreenSmokeTests.cs b/tests/Titano.App.Tests/Server/ServerScreenSmokeTests.cs index 5b8b3f97..8c1ee512 100644 --- a/tests/Titano.App.Tests/Server/ServerScreenSmokeTests.cs +++ b/tests/Titano.App.Tests/Server/ServerScreenSmokeTests.cs @@ -1,7 +1,11 @@ +using System.Windows.Controls; +using System.Windows.Input; +using Titano.App.Infrastructure; using Titano.App.Sections; using Titano.App.Server; using Titano.App.Shell; using Titano.App.Tests.Windows; +using Titano.Core.Localization; using Titano.Core.Model; using Titano.Data.Sync; using Titano.Testing; @@ -9,7 +13,7 @@ using Titano.Ui.Controls; namespace Titano.App.Tests.Server; -/// The Server screen's sync table on the capture sample data: comparison, transfer, conflict and the Library's glyphs. +/// The Server screen's sync table on the capture sample data: comparison, transfers, conflict and the Library's glyphs. [WindowsOnly] [Serial] [Timeout(300_000)] @@ -24,45 +28,77 @@ public sealed class ServerScreenSmokeTests await shell.Library.RefreshAsync(); await shell.Services.Server.RestoreAsync(); Assert.NotNull(await shell.Services.Sync.RefreshAsync()); + await app.Sample.CacheProxiesAsync(); var table = shell.Server.Sync; await table.ReloadAsync(); - // 36 sequences here (4 also on the server) and 2 only on the server. + // 36 sequences here (6 also on the server) and 2 only on the server; the conflict is listed first. Assert.True(table.IsActive); Assert.Equal(38, table.Rows.Count); + Assert.Equal("Holy grail · Monviso", table.Rows[0].Title); + Assert.True(table.Rows[0].IsConflict); Assert.Equal(1, Chip(table, SyncFilter.Conflicts).Count); Assert.Equal(2, Chip(table, SyncFilter.Remote).Count); - Assert.Equal(32, Chip(table, SyncFilter.LocalOnly).Count); + Assert.Equal(30, Chip(table, SyncFilter.LocalOnly).Count); Assert.Equal(SyncStatus.InSync, Row(table, "Harbour sunset").Entry.Status); Assert.Equal(SyncStatus.ServerAhead, Row(table, "Construction cam · week 38").Entry.Status); - Assert.SequenceEqual([SyncAction.DownloadOriginals], Row(table, "Construction cam · week 38").Actions.Select(a => a.Action)); - Assert.SequenceEqual([SyncAction.OpenWithProxies, SyncAction.DownloadOriginals], Row(table, "Sunrise over Superga").Actions.Select(a => a.Action)); - Assert.SequenceEqual([SyncAction.Upload], Row(table, "Clouds over the Langhe").Actions.Select(a => a.Action)); + Assert.SequenceEqual([SyncAction.DownloadOriginals], Actions(Row(table, "Construction cam · week 38"))); + Assert.SequenceEqual([SyncAction.Upload], Actions(Row(table, "Milan skyline dusk"))); + Assert.SequenceEqual([SyncAction.GetExports], Actions(Row(table, "Star trails, Colle del Nivolet"))); + var sunrise = Row(table, "Sunrise over Superga"); + Assert.Equal(SyncStatus.ProxiesOnly, sunrise.Entry.Status); + Assert.Equal(Loc.L("Server.Sync.Proxies"), sunrise.LocalText); + Assert.SequenceEqual([SyncAction.OpenWithProxies, SyncAction.DownloadOriginals], Actions(sunrise)); + Assert.SequenceEqual([SyncAction.Upload], Actions(Row(table, "Clouds over the Langhe"))); var conflict = Row(table, "Holy grail · Monviso"); Assert.Equal(StatusKind.Warning, conflict.StateKind); - Assert.SequenceEqual([SyncAction.KeepMine, SyncAction.TakeServer, SyncAction.SaveBoth], conflict.Actions.Select(a => a.Action)); - Assert.Contains("41", conflict.StateToolTip); + Assert.SequenceEqual([SyncAction.KeepMine, SyncAction.TakeServer, SyncAction.SaveBoth], Actions(conflict)); + Assert.Equal(Loc.L("Server.Conflict.Difference", Loc.L("Server.Setting.DeflickerWindow"), "41", "33"), conflict.StateToolTip); Assert.NotNull(table.LastSyncText); Assert.NotNull(table.ArchiveText); + Assert.True(table.UploadAllCommand.CanExecute(null), "the table filled after the view bound"); - // The Library shows the real sync state of each local copy. + // Resolving shows the plan first: what differs and which side is overwritten. + var keepMine = SyncTableViewModel.ConflictRequest(conflict.Entry, SyncAction.KeepMine); + Assert.True(keepMine.IsDestructive); + Assert.Contains(Loc.L("Server.Setting.DeflickerWindow"), keepMine.Detail); + Assert.False(SyncTableViewModel.ConflictRequest(conflict.Entry, SyncAction.SaveBoth).IsDestructive); + + // The Library shows the real sync state of each local copy, in one word. var holyGrail = shell.Library.Items.Single(i => i.Title == "Holy grail · Monviso"); Assert.Equal(SyncState.Conflict, holyGrail.Sequence.SyncState); - Assert.Contains(holyGrail.Statuses, s => s.Kind == StatusKind.Warning); + Assert.Equal(StatusKind.Warning, holyGrail.Statuses[^1].Kind); Assert.Contains(shell.Library.Items.Single(i => i.Title == "Harbour sunset").Statuses, s => s.Kind == StatusKind.Synced); + var milan = shell.Library.Items.Single(i => i.Title == "Milan skyline dusk").Statuses[^1]; + Assert.Equal((StatusKind.Synced, Loc.L("Library.Status.Synced")), (milan.Kind, milan.Text)); shell.Navigate(SectionKey.Server); await app.ExpectAsync("server"); - // An upload in progress: the row shows what the server received and offers Pause. + // Tab walks the row buttons of every row: the rows take no focus, the list passes Tab on to their content. + var list = app.FindAll().Single(l => l.Name == "SyncList"); + Assert.Equal(KeyboardNavigationMode.Continue, KeyboardNavigation.GetTabNavigation(list)); + var rowButtons = app.FindAll diff --git a/src/Titano.App/Server/SyncText.cs b/src/Titano.App/Server/SyncText.cs index c3d66d66..f55ab693 100644 --- a/src/Titano.App/Server/SyncText.cs +++ b/src/Titano.App/Server/SyncText.cs @@ -94,7 +94,11 @@ public static class SyncText public static string Local(SyncEntry entry) { if (entry.HasLocalOriginals) - return (entry.Local!.Status & SequenceStatus.ProxiesBuilt) != 0 ? Join(Loc.L("Server.Sync.Originals"), Loc.L("Server.Sync.Proxies")) : Loc.L("Server.Sync.Originals"); + { + return (entry.Local!.Status & SequenceStatus.ProxiesBuilt) != 0 + ? Join(Loc.L("Server.Sync.Originals"), Loc.L("Server.Sync.Proxies")) + : Loc.L("Server.Sync.Originals"); + } return entry.Link is { ProxiesCached: > 0 } ? Loc.L("Server.Sync.Proxies") : Loc.L("Server.Sync.None"); } @@ -202,7 +206,8 @@ public static class SyncText actions.AddRange([SyncAction.TakeServer, SyncAction.SaveBoth]); return actions; } - if (entry is { Local: not null, Link: { } link }) + // Renders travel on request once no original is waiting to go either way. + if (entry is { Local: not null, Link: { MissingRemote: 0, MissingLocal: 0 } link }) { if (link.ExportsToGet > 0) actions.Add(SyncAction.GetExports); if (link.ExportsToSend > 0 && rights.CanUpload) actions.Add(SyncAction.SendExports); diff --git a/src/Titano.App/Shell/ScreenCapture.cs b/src/Titano.App/Shell/ScreenCapture.cs index af7efa5e..c4fa8290 100644 --- a/src/Titano.App/Shell/ScreenCapture.cs +++ b/src/Titano.App/Shell/ScreenCapture.cs @@ -57,7 +57,6 @@ public static class ScreenCapture await shell.Jobs.ReloadAsync(); await shell.Services.Server.RestoreAsync(); await shell.Services.Sync.RefreshAsync(); - await sample.CacheProxiesAsync(); await shell.Server.Sync.ReloadAsync(); shell.About.SetResult(null); await shell.Settings.DetectEncodersAsync(); @@ -101,7 +100,9 @@ public static class ScreenCapture written += await SaveAsync(window, directory, key.ToString().ToLowerInvariant(), theme); } } - // The sync table with transfers in every state, then filtered to the conflict, then the conflict's confirmation. + // The sync table with proxies kept here and transfers in every state, then filtered to the conflict, then the + // conflict's confirmation (after the other screens, so the Jobs capture keeps its own sample). + await sample.CacheProxiesAsync(); await sample.FillSyncAsync(); await shell.Server.Sync.ReloadAsync(); foreach (var theme in Themes) diff --git a/src/Titano.Data/Sync/SyncService.cs b/src/Titano.Data/Sync/SyncService.cs index 4b46f848..a1a3232d 100644 --- a/src/Titano.Data/Sync/SyncService.cs +++ b/src/Titano.Data/Sync/SyncService.cs @@ -633,7 +633,10 @@ public sealed class SyncService return await _db.Sequences.GetAsync(local.Id, cancellationToken).ConfigureAwait(false) ?? current; } - /// "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. + /// + /// "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. + /// private async Task SaveCopyAsync(Sequence local, CancellationToken cancellationToken) { var archive = await _db.Archives.GetAsync(local.ArchiveId, cancellationToken).ConfigureAwait(false)