merge: client server mode (sync engine, Server screen sync table and conflicts, Library sync glyphs, render transfers)
Keeps the render node host from the processing branch and disposes the sync host after it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
56 files changed
+6777
-25
No files matched your search
@@ -0,0 +1,38 @@
|
||||
-- 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; conflict_remote is the
|
||||
-- server's side (title, tags, rating, notes, settings) of an unresolved conflict as JSON. 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,
|
||||
diff_local_renders integer,
|
||||
diff_remote_renders integer,
|
||||
missing_remote integer NOT NULL DEFAULT 0,
|
||||
missing_local integer NOT NULL DEFAULT 0,
|
||||
exports_to_get integer NOT NULL DEFAULT 0,
|
||||
exports_to_get_bytes bigint NOT NULL DEFAULT 0,
|
||||
exports_to_send integer NOT NULL DEFAULT 0,
|
||||
exports_to_send_bytes bigint NOT NULL DEFAULT 0,
|
||||
conflict_local_settings integer,
|
||||
conflict_remote_settings integer,
|
||||
conflict_remote text,
|
||||
proxies_cached integer NOT NULL DEFAULT 0,
|
||||
proxies_frames_version integer,
|
||||
error text,
|
||||
synced_at timestamptz,
|
||||
PRIMARY KEY (server, remote_id)
|
||||
);
|
||||
CREATE UNIQUE INDEX ix_sync_links_local ON sync_links (server, local_id);
|
||||
@@ -0,0 +1,38 @@
|
||||
-- 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; conflict_remote is the
|
||||
-- server's side (title, tags, rating, notes, settings) of an unresolved conflict as JSON. 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,
|
||||
diff_local_renders INTEGER,
|
||||
diff_remote_renders INTEGER,
|
||||
missing_remote INTEGER NOT NULL DEFAULT 0,
|
||||
missing_local INTEGER NOT NULL DEFAULT 0,
|
||||
exports_to_get INTEGER NOT NULL DEFAULT 0,
|
||||
exports_to_get_bytes INTEGER NOT NULL DEFAULT 0,
|
||||
exports_to_send INTEGER NOT NULL DEFAULT 0,
|
||||
exports_to_send_bytes INTEGER NOT NULL DEFAULT 0,
|
||||
conflict_local_settings INTEGER,
|
||||
conflict_remote_settings INTEGER,
|
||||
conflict_remote TEXT,
|
||||
proxies_cached INTEGER NOT NULL DEFAULT 0,
|
||||
proxies_frames_version INTEGER,
|
||||
error TEXT,
|
||||
synced_at TEXT,
|
||||
PRIMARY KEY (server, remote_id)
|
||||
);
|
||||
CREATE UNIQUE INDEX ix_sync_links_local ON sync_links (server, local_id);
|
||||
@@ -430,7 +430,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,
|
||||
@@ -444,7 +444,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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="FrameFlags.Missing"/>, so analysis and renders
|
||||
/// skip them. Not part of the local index.
|
||||
/// </summary>
|
||||
public sealed class RemoteSequence
|
||||
{
|
||||
internal RemoteSequence(string server, Sequence sequence, IReadOnlyList<Frame> frames, IReadOnlyList<string?> files)
|
||||
{
|
||||
Server = server;
|
||||
Sequence = sequence;
|
||||
Frames = frames;
|
||||
Files = files;
|
||||
}
|
||||
|
||||
/// <summary>The server it belongs to (<see cref="SyncService.ServerKey"/>).</summary>
|
||||
public string Server { get; }
|
||||
|
||||
/// <summary>The server's sequence: its id, <see cref="SequenceOrigin.Server"/>, its settings JSON and versions; no archive.</summary>
|
||||
public Sequence Sequence { get; }
|
||||
|
||||
public IReadOnlyList<Frame> Frames { get; }
|
||||
|
||||
/// <summary>Absolute path of each frame's cached proxy, in frame order; null when it is not cached.</summary>
|
||||
public IReadOnlyList<string?> Files { get; }
|
||||
|
||||
public int CachedCount => Files.Count(f => f is not null);
|
||||
|
||||
/// <summary>
|
||||
/// The editor's frame source over the cached proxies, decoded by <paramref name="decoder"/> through the same
|
||||
/// read-ahead window as archive renders. The result also implements <see cref="Core.Analysis.Deep.IFrameSource"/>
|
||||
/// and <see cref="IAsyncDisposable"/>; dispose it when done. Frames are proxy-sized while the source reports the
|
||||
/// originals' size, which <see cref="IRenderFrameSource"/> allows.
|
||||
/// </summary>
|
||||
public IRenderFrameSource OpenFrames(ImageDecoder decoder, FrameWindowOptions? window = null)
|
||||
{
|
||||
var frames = new SequenceFrames(Sequence, Frames, Files);
|
||||
return new SequenceFrameSource(frames, frames.LightFrames(), decoder, window);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What the proxy cache keeps next to the files of one server sequence.</summary>
|
||||
internal sealed record ProxyCacheIndex(SequenceDto Sequence, string? SettingsJson, int FramesVersion, IReadOnlyList<FrameDto> Frames, IReadOnlyList<string?> Files);
|
||||
|
||||
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
[JsonSerializable(typeof(ProxyCacheIndex))]
|
||||
internal sealed partial class ProxyCacheJson : JsonSerializerContext;
|
||||
|
||||
/// <summary>
|
||||
/// Proxies of server sequences on this PC: <c><root>/<server hash>/<sequence id>/</c> with one JPEG per
|
||||
/// frame (named by frame id, so renumbering never mixes them up) and <c>remote.json</c>. Everything here can be
|
||||
/// downloaded again, so the folder lives in the client's cache.
|
||||
/// </summary>
|
||||
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));
|
||||
|
||||
/// <summary>The cached sequence, or null when it was never cached or the cache was cleared.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Removes the files of a sequence the server no longer has.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Deletes proxies of frames <paramref name="keep"/> does not name (frames removed on the server).</summary>
|
||||
public static void Prune(string folder, IReadOnlySet<string> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
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;
|
||||
|
||||
/// <summary>Timing of a <see cref="SyncAgent"/>.</summary>
|
||||
public sealed record SyncAgentOptions
|
||||
{
|
||||
/// <summary>Full comparison while nothing asks for one sooner (catches edits on this PC and missed events).</summary>
|
||||
public TimeSpan RefreshInterval { get; init; } = TimeSpan.FromMinutes(2);
|
||||
|
||||
/// <summary>Server events are collected this long, then their sequences are compared in one pass.</summary>
|
||||
public TimeSpan EventDelay { get; init; } = TimeSpan.FromSeconds(1);
|
||||
|
||||
/// <summary>First wait after a failed refresh or a lost event socket; doubles up to <see cref="MaxBackoff"/>.</summary>
|
||||
public TimeSpan MinBackoff { get; init; } = TimeSpan.FromSeconds(5);
|
||||
|
||||
public TimeSpan MaxBackoff { get; init; } = TimeSpan.FromMinutes(5);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Keeps the sync table of one signed-in server current in the background: a full comparison at start, on request
|
||||
/// and every <see cref="SyncAgentOptions.RefreshInterval"/>; the sequences named by the server's <c>sequenceChanged</c>
|
||||
/// events (WebSocket) compared again within a second, except those an upload or download is working on (it compares
|
||||
/// them when it ends); failures retried with exponential backoff; and, with
|
||||
/// <see cref="SyncPolicy.KeepProxiesOffline"/>, background downloads that bring stale proxy caches of the sequences
|
||||
/// this PC opened with proxies up to date (a failed one waits with the same backoff). Dispose to stop.
|
||||
/// </summary>
|
||||
public sealed class SyncAgent : IAsyncDisposable
|
||||
{
|
||||
private const string LogCategory = "sync";
|
||||
|
||||
private readonly SyncService _sync;
|
||||
private readonly ISyncRemote _remote;
|
||||
private readonly Func<SyncPolicy> _policy;
|
||||
private readonly JobEngine? _engine;
|
||||
private readonly SyncAgentOptions _options;
|
||||
private readonly CancellationTokenSource _stopping = new();
|
||||
private readonly Channel<bool> _refreshWake = Channel.CreateBounded<bool>(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite });
|
||||
private readonly Channel<bool> _eventWake = Channel.CreateBounded<bool>(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite });
|
||||
private readonly ConcurrentDictionary<Guid, byte> _changed = new();
|
||||
|
||||
/// <summary>Proxy downloads this agent queued, by server id, and the failures of each sequence's last ones.</summary>
|
||||
private readonly Dictionary<Guid, Guid> _proxyJobs = [];
|
||||
|
||||
private readonly Dictionary<Guid, (int Failures, DateTime NotBefore)> _proxyFailures = [];
|
||||
private readonly SemaphoreSlim _refreshing = new(1, 1);
|
||||
private Task _running = Task.CompletedTask;
|
||||
private SyncSnapshot? _snapshot;
|
||||
private Exception? _lastError;
|
||||
|
||||
/// <param name="policy">Read before every comparison, so option changes apply at once.</param>
|
||||
/// <param name="engine">Queue for proxy downloads; null keeps no proxies offline.</param>
|
||||
public SyncAgent(SyncService sync, ISyncRemote remote, Func<SyncPolicy> policy, JobEngine? engine, SyncAgentOptions? options = null)
|
||||
{
|
||||
_sync = sync;
|
||||
_remote = remote;
|
||||
_policy = policy;
|
||||
_engine = engine;
|
||||
_options = options ?? new SyncAgentOptions();
|
||||
}
|
||||
|
||||
public string Server => _remote.Server;
|
||||
|
||||
/// <summary>The last full comparison; null until the first one finished.</summary>
|
||||
public SyncSnapshot? Snapshot => Volatile.Read(ref _snapshot);
|
||||
|
||||
/// <summary>Why the last full comparison failed; null after a successful one.</summary>
|
||||
public Exception? LastError => Volatile.Read(ref _lastError);
|
||||
|
||||
/// <summary><see cref="Snapshot"/> or <see cref="LastError"/> changed (any thread).</summary>
|
||||
public event Action? Changed;
|
||||
|
||||
/// <summary>Starts the comparison and event loops.</summary>
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>Asks for a full comparison soon (after an edit on this PC, an option change, a reconnect).</summary>
|
||||
public void RequestRefresh() => _refreshWake.Writer.TryWrite(true);
|
||||
|
||||
/// <summary>Compares everything now; concurrent calls run one after the other.</summary>
|
||||
public async Task<SyncSnapshot> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Listens to the server's events; a lost socket reconnects with backoff and asks for a full comparison (events were missed).</summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Compares the sequences named by events, a short while after the first one arrived.</summary>
|
||||
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 (!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();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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: { 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Waits for a wake-up or the delay; false when stopping.</summary>
|
||||
private static async Task<bool> WaitAsync(ChannelReader<bool> 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
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;
|
||||
|
||||
/// <summary>What an upload or download job moves.</summary>
|
||||
public enum SyncTransferKind
|
||||
{
|
||||
/// <summary>Originals and settings of a local sequence to the server.</summary>
|
||||
Upload,
|
||||
|
||||
/// <summary>Renders of a local copy to the server.</summary>
|
||||
SendExports,
|
||||
|
||||
/// <summary>Originals of a server sequence into the local archive.</summary>
|
||||
DownloadOriginals,
|
||||
|
||||
/// <summary>Proxies of a server sequence into the proxy cache.</summary>
|
||||
DownloadProxies,
|
||||
|
||||
/// <summary>Renders of a server sequence into the local copy's exports.</summary>
|
||||
GetExports,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parameters of upload and download jobs. The job's target is the local sequence for an upload and the server
|
||||
/// sequence for a download.
|
||||
/// </summary>
|
||||
/// <param name="ArchiveId">Archive that receives downloaded originals when the sequence has no local copy yet.</param>
|
||||
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)]
|
||||
[JsonSerializable(typeof(SyncJobParameters))]
|
||||
internal sealed partial class SyncJobJson : JsonSerializerContext;
|
||||
|
||||
/// <summary>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.</summary>
|
||||
internal sealed class SyncJobHandler(JobKind kind, SyncTransfers transfers, ISyncConnector connector) : IJobHandler
|
||||
{
|
||||
public JobKind Kind => kind;
|
||||
|
||||
public async Task RunAsync(JobContext context)
|
||||
{
|
||||
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 (parameters.Kind(kind))
|
||||
{
|
||||
case SyncTransferKind.Upload:
|
||||
await transfers.UploadAsync(context, remote, target).ConfigureAwait(false);
|
||||
break;
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
using System.Text.Json;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Repositories;
|
||||
|
||||
namespace Titano.Data.Sync;
|
||||
|
||||
/// <summary>The <c>sync_links</c> table and the sync columns of local sequences (origin, sync state).</summary>
|
||||
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, " +
|
||||
"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);
|
||||
|
||||
private static readonly JobState[] Active = [JobState.Queued, JobState.Running, JobState.Paused];
|
||||
|
||||
private readonly DbAccess _db = new(db.Database);
|
||||
|
||||
public Task<IReadOnlyList<SyncLink>> ListAsync(string server, CancellationToken cancellationToken) =>
|
||||
_db.ListAsync($"SELECT {Columns} FROM sync_links WHERE server = $1 ORDER BY remote_id", [server], Map, cancellationToken);
|
||||
|
||||
public Task<SyncLink?> 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<SyncLink?> 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.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) =>
|
||||
_db.ExecuteAsync("DELETE FROM sync_links WHERE server = $1 AND remote_id = $2", [server, remoteId], cancellationToken);
|
||||
|
||||
/// <summary>Records where a local sequence stands for the Library; touches neither its versions nor its update time.</summary>
|
||||
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);
|
||||
|
||||
/// <summary>Marks a local sequence as downloaded from the server.</summary>
|
||||
public Task SetOriginAsync(Guid localId, SequenceOrigin origin, CancellationToken cancellationToken) =>
|
||||
_db.ExecuteAsync("UPDATE sequences SET origin = $2 WHERE id = $1", [localId, (int)origin], cancellationToken);
|
||||
|
||||
/// <summary>Upload and download jobs that are waiting, running or paused, by target id (local id for uploads, server id for downloads).</summary>
|
||||
public async Task<IReadOnlyDictionary<Guid, IReadOnlyList<Job>>> ActiveTransfersAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var jobs = new List<Job>();
|
||||
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);
|
||||
jobs.AddRange(page.Items.Where(j => j.TargetIds.Count > 0));
|
||||
cursor = page.NextCursor;
|
||||
}
|
||||
while (cursor is not null);
|
||||
}
|
||||
}
|
||||
return jobs.GroupBy(j => j.TargetIds[0]).ToDictionary(g => g.Key, g => (IReadOnlyList<Job>)[.. g]);
|
||||
}
|
||||
|
||||
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),
|
||||
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),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
using Titano.Core.Model;
|
||||
|
||||
namespace Titano.Data.Sync;
|
||||
|
||||
/// <summary>Where a sequence stands between this PC and the server (BRIEF §12.7, §14.5).</summary>
|
||||
public enum SyncStatus
|
||||
{
|
||||
/// <summary>Same originals and settings on both sides.</summary>
|
||||
InSync,
|
||||
|
||||
LocalOnly,
|
||||
RemoteOnly,
|
||||
|
||||
/// <summary>Only on the server; this PC keeps its proxies for editing.</summary>
|
||||
ProxiesOnly,
|
||||
|
||||
/// <summary>This PC holds originals or settings the server lacks.</summary>
|
||||
LocalAhead,
|
||||
|
||||
/// <summary>The server holds originals or settings this PC lacks.</summary>
|
||||
ServerAhead,
|
||||
|
||||
/// <summary>Both sides changed the settings, title, tags, rating or notes since they last agreed: the user picks.</summary>
|
||||
Conflict,
|
||||
|
||||
/// <summary>An upload or download job is queued, running or paused.</summary>
|
||||
Transferring,
|
||||
}
|
||||
|
||||
/// <summary>How the user settles a conflict (BRIEF §12.7).</summary>
|
||||
public enum SyncResolution
|
||||
{
|
||||
KeepMine,
|
||||
TakeServer,
|
||||
|
||||
/// <summary>The server's version wins; this PC's settings are kept next to the project as a dated copy.</summary>
|
||||
SaveBoth,
|
||||
}
|
||||
|
||||
/// <summary>What a download job fetches.</summary>
|
||||
public enum SyncDownloadMode
|
||||
{
|
||||
/// <summary>Originals, hash-verified, into the local archive.</summary>
|
||||
Originals,
|
||||
|
||||
/// <summary>Proxies (thumbnails where the server has none) into the proxy cache.</summary>
|
||||
Proxies,
|
||||
|
||||
/// <summary>The server's renders the local copy lacks, into its exports folder.</summary>
|
||||
Exports,
|
||||
}
|
||||
|
||||
/// <summary>What an upload job sends.</summary>
|
||||
public enum SyncUploadMode
|
||||
{
|
||||
/// <summary>Originals and settings (creating the server sequence when needed).</summary>
|
||||
Originals,
|
||||
|
||||
/// <summary>This PC's renders the server lacks (BRIEF §14.5: renders are uploaded on request).</summary>
|
||||
Exports,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 and render
|
||||
/// counts the missing counts were computed at, so originals and renders are compared again only when either side's change.
|
||||
/// </summary>
|
||||
public sealed record SyncLink
|
||||
{
|
||||
/// <summary>Normalised server address (<see cref="SyncService.ServerKey"/>).</summary>
|
||||
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; }
|
||||
public int? DiffLocalRenders { get; init; }
|
||||
public int? DiffRemoteRenders { get; init; }
|
||||
|
||||
/// <summary>Local originals the server does not have.</summary>
|
||||
public int MissingRemote { get; init; }
|
||||
|
||||
/// <summary>Server originals this PC does not have.</summary>
|
||||
public int MissingLocal { get; init; }
|
||||
|
||||
/// <summary>Server renders the local copy does not have, and their size.</summary>
|
||||
public int ExportsToGet { get; init; }
|
||||
|
||||
public long ExportsToGetBytes { get; init; }
|
||||
|
||||
/// <summary>Renders of the local copy the server does not have (whose file is still on this PC), and their size.</summary>
|
||||
public int ExportsToSend { get; init; }
|
||||
|
||||
public long ExportsToSendBytes { get; init; }
|
||||
|
||||
/// <summary>Settings versions at which the content was found to conflict; null when it does not.</summary>
|
||||
public int? ConflictLocalSettings { get; init; }
|
||||
|
||||
public int? ConflictRemoteSettings { get; init; }
|
||||
|
||||
/// <summary>The server's side when the conflict was found: what the user is shown and what "Take server" applies.</summary>
|
||||
public SyncPayload? ConflictRemote { get; init; }
|
||||
|
||||
/// <summary>Frames whose proxy (or thumbnail) is in this PC's proxy cache.</summary>
|
||||
public int ProxiesCached { get; init; }
|
||||
|
||||
/// <summary>Server frames version the proxy cache was filled at.</summary>
|
||||
public int? ProxiesFramesVersion { get; init; }
|
||||
|
||||
/// <summary>Why the last comparison of this sequence failed (it is compared again next time); null when it worked.</summary>
|
||||
public string? Error { get; init; }
|
||||
|
||||
public DateTimeOffset? SyncedAt { get; init; }
|
||||
|
||||
public bool ServerHasProxies => (RemoteStatus & SequenceStatus.ProxiesBuilt) != 0;
|
||||
|
||||
/// <summary>
|
||||
/// The proxy cache was never completed or predates the server's last frame change (frames the server has no
|
||||
/// proxy or thumbnail for stay missing until their frames change, so they are not fetched again and again).
|
||||
/// </summary>
|
||||
public bool ProxiesStale => ProxiesFramesVersion != RemoteFramesVersion;
|
||||
}
|
||||
|
||||
/// <summary>One row of the sync table: the local sequence, the server sequence, or both, and where they stand.</summary>
|
||||
/// <param name="Transfer">The upload or download job working on it, if any (the user's before background ones).</param>
|
||||
public sealed record SyncEntry(Sequence? Local, SyncLink? Link, SyncStatus Status, Job? Transfer = null)
|
||||
{
|
||||
public string Title => Local?.DisplayTitle ?? Link?.Title ?? string.Empty;
|
||||
|
||||
/// <summary>The server's id, or the local one for a sequence the server does not have.</summary>
|
||||
public Guid Id => Link?.RemoteId ?? Local!.Id;
|
||||
|
||||
/// <summary>This PC holds originals of the sequence.</summary>
|
||||
public bool HasLocalOriginals => Local is { FrameCount: > 0 };
|
||||
}
|
||||
|
||||
/// <summary>The sync table after a refresh.</summary>
|
||||
/// <param name="Duration">Time the refresh took (listing, manifest diffs, settings exchange).</param>
|
||||
public sealed record SyncSnapshot(string Server, IReadOnlyList<SyncEntry> 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);
|
||||
}
|
||||
|
||||
/// <summary>Options a refresh applies.</summary>
|
||||
/// <param name="AutoSyncSettings">Send and take settings changed on one side only (Server.html "Sync projects automatically").</param>
|
||||
/// <param name="KeepProxiesOffline">Keep the proxy caches of server sequences this PC opened with proxies up to date.</param>
|
||||
/// <param name="CanEdit">The account may change server sequences; without it this PC's edits are never sent.</param>
|
||||
public sealed record SyncPolicy(bool AutoSyncSettings = true, bool KeepProxiesOffline = false, bool CanEdit = true);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class SyncConflictChangedException(string message) : InvalidOperationException(message);
|
||||
@@ -0,0 +1,123 @@
|
||||
using Titano.Protocol;
|
||||
using Titano.Protocol.Client;
|
||||
|
||||
namespace Titano.Data.Sync;
|
||||
|
||||
/// <summary>
|
||||
/// The server calls the sync engine makes (BRIEF §14.3). <see cref="TitanoSyncRemote"/> sends them with
|
||||
/// <see cref="TitanoClient"/>; screenshots and tests substitute fakes. Failures are <see cref="TitanoApiException"/>s
|
||||
/// (404 gone, 409 settings conflict) or network exceptions. Dispose a remote handed out by an <see cref="ISyncConnector"/>.
|
||||
/// </summary>
|
||||
public interface ISyncRemote : IDisposable
|
||||
{
|
||||
/// <summary>Normalised server address the links are stored under (<see cref="SyncService.ServerKey"/>).</summary>
|
||||
string Server { get; }
|
||||
|
||||
/// <summary>Every sequence on the server.</summary>
|
||||
Task<IReadOnlyList<SequenceDto>> ListSequencesAsync(CancellationToken cancellationToken);
|
||||
|
||||
Task<SequenceDto> GetSequenceAsync(Guid id, CancellationToken cancellationToken);
|
||||
|
||||
Task<SequenceManifest> GetManifestAsync(Guid id, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Every frame row of a sequence, in index order.</summary>
|
||||
Task<IReadOnlyList<FrameDto>> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>A 409 <see cref="TitanoApiException"/> means the settings version moved on the server.</summary>
|
||||
Task<SequenceDto> UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Chunked, resumable upload of one original into <paramref name="sequenceId"/>, or into the sequence the server
|
||||
/// files <paramref name="sessionKey"/> under (created by the first one); the server verifies <paramref name="sha256"/>
|
||||
/// before committing it (BRIEF §14.4). An original the server already holds is not sent again: the response then
|
||||
/// names <paramref name="sequenceId"/> (<see cref="Guid.Empty"/> without one). See <see cref="TitanoClient.UploadFileAsync"/>.
|
||||
/// </summary>
|
||||
Task<CompleteUploadResponse?> UploadFileAsync(string path, Guid? sequenceId, string? sessionKey, string sha256, DateTime? capturedAt,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Streams a frame's original, proxy or thumb, resuming with Range from the destination's length.</summary>
|
||||
Task DownloadFrameAsync(Guid frameId, string kind, Stream destination, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Streams a render's file, resuming with Range from the destination's length; returns the file name the server gives it.</summary>
|
||||
Task<string?> DownloadRenderAsync(Guid renderId, Stream destination, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Chunked, resumable upload of a render of <paramref name="sequenceId"/> made on this PC; the server verifies the
|
||||
/// SHA-256 and keeps the render's id. Null when the server already has it. See <see cref="TitanoClient.UploadRenderAsync"/>.
|
||||
/// </summary>
|
||||
Task<RenderDto?> UploadRenderAsync(Guid sequenceId, string path, RenderUploadRequest request, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Server events until cancelled or the socket closes.</summary>
|
||||
IAsyncEnumerable<ServerEvent> EventsAsync(CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Where sync jobs find their server connection.</summary>
|
||||
public interface ISyncConnector
|
||||
{
|
||||
/// <summary>A signed-in remote of <paramref name="server"/> owned by the caller; null when this PC is not connected to that server.</summary>
|
||||
ValueTask<ISyncRemote?> ConnectAsync(string server, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary><see cref="ISyncRemote"/> over a signed-in <see cref="TitanoClient"/>, which it disposes when it owns it.</summary>
|
||||
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<IReadOnlyList<SequenceDto>> ListSequencesAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var all = new List<SequenceDto>();
|
||||
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<SequenceDto> GetSequenceAsync(Guid id, CancellationToken cancellationToken) => client.GetSequenceAsync(id, cancellationToken);
|
||||
|
||||
public Task<SequenceManifest> GetManifestAsync(Guid id, CancellationToken cancellationToken) => client.GetManifestAsync(id, cancellationToken);
|
||||
|
||||
public async Task<IReadOnlyList<FrameDto>> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken)
|
||||
{
|
||||
var all = new List<FrameDto>();
|
||||
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<SequenceDto> UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken) =>
|
||||
client.UpdateSequenceAsync(id, request, cancellationToken);
|
||||
|
||||
public Task<CompleteUploadResponse?> 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);
|
||||
|
||||
public Task<string?> DownloadRenderAsync(Guid renderId, Stream destination, CancellationToken cancellationToken) =>
|
||||
client.DownloadRenderAsync(renderId, destination, cancellationToken);
|
||||
|
||||
public Task<RenderDto?> UploadRenderAsync(Guid sequenceId, string path, RenderUploadRequest request, CancellationToken cancellationToken) =>
|
||||
client.UploadRenderAsync(sequenceId, path, request, null, cancellationToken);
|
||||
|
||||
public IAsyncEnumerable<ServerEvent> EventsAsync(CancellationToken cancellationToken) => client.EventsAsync(cancellationToken);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (ownsClient) client.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
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;
|
||||
|
||||
namespace Titano.Data.Sync;
|
||||
|
||||
/// <summary>The fields both sides version together (BRIEF §14.5: settings and tags carry version counters).</summary>
|
||||
public sealed record SyncPayload(string? Title, IReadOnlyList<string> 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);
|
||||
|
||||
/// <summary>Title, tags, rating and notes match (blank equals absent, tags ignore case and order).</summary>
|
||||
public bool SameMetadata(SyncPayload other) =>
|
||||
SyncRules.Blank(Title) == SyncRules.Blank(other.Title)
|
||||
&& SyncRules.Blank(Notes) == SyncRules.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);
|
||||
|
||||
/// <summary>The PATCH that makes the server's copy equal to this one; settings are sent in their normalised form.</summary>
|
||||
public UpdateSequenceRequest ToRequest(int? expectedSettingsVersion) =>
|
||||
new(Title ?? string.Empty, Tags, Rating, Notes ?? string.Empty, SyncRules.NormalizeSettings(SettingsJson), expectedSettingsVersion);
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
[JsonSerializable(typeof(SyncPayload))]
|
||||
internal sealed partial class SyncPayloadJson : JsonSerializerContext;
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public sealed record SettingsDifference(string Path, string? Mine, string? Theirs);
|
||||
|
||||
/// <summary>Decisions of the sync engine that need no I/O: the status of a row, settings equality and differences, merges.</summary>
|
||||
public static class SyncRules
|
||||
{
|
||||
/// <summary>Path prefix of the title, tags, rating and notes in <see cref="Differences(SyncPayload, SyncPayload, int)"/>.</summary>
|
||||
public const string MetadataPath = "sequence.";
|
||||
|
||||
/// <summary>
|
||||
/// Where a linked pair stands. Settings changed on both sides since they last agreed are a conflict (the engine
|
||||
/// settles equal content before a row is shown); missing originals count before settings changed on one side only.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The state stored on the local sequence for the Library; null for rows without a local copy or in transfer.</summary>
|
||||
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,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>Up to <paramref name="max"/> settings that differ, in document order.</summary>
|
||||
public static IReadOnlyList<SettingsDifference> Differences(string? mine, string? theirs, int max = 3)
|
||||
{
|
||||
var differences = new List<SettingsDifference>();
|
||||
Collect(Parse(NormalizeSettings(mine)), Parse(NormalizeSettings(theirs)), string.Empty, differences, max);
|
||||
return differences;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Up to <paramref name="max"/> differences between two payloads: title, tags, rating and notes first (paths
|
||||
/// <c>sequence.title</c>, <c>sequence.tags</c>, …, tags as one comma-separated value), then the settings.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<SettingsDifference> Differences(SyncPayload mine, SyncPayload theirs, int max = 3)
|
||||
{
|
||||
var differences = new List<SettingsDifference>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static (int MissingRemote, int MissingLocal) CompareOriginals(IReadOnlyCollection<string?> localHashes, IReadOnlyCollection<string> 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));
|
||||
}
|
||||
|
||||
internal static string Blank(string? text) => text?.Trim() ?? string.Empty;
|
||||
|
||||
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<SettingsDifference> 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()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,800 @@
|
||||
using System.Collections.Concurrent;
|
||||
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.Localization;
|
||||
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;
|
||||
|
||||
/// <summary>Settings of a <see cref="SyncService"/>.</summary>
|
||||
public sealed record SyncOptions
|
||||
{
|
||||
/// <summary>Decoders, lease owner and lease timing for sidecar and project writes (shared with the archive engine).</summary>
|
||||
public ArchiveServiceOptions Archive { get; init; } = new();
|
||||
|
||||
/// <summary>Folder of the proxy cache of server sequences (inside the client's cache).</summary>
|
||||
public required string ProxyCacheDirectory { get; init; }
|
||||
|
||||
/// <summary>Concurrent frame downloads of one job.</summary>
|
||||
public int Downloads { get; init; } = 4;
|
||||
|
||||
/// <summary>Concurrent file uploads of one job (the server accepts 8 chunks in flight per user).</summary>
|
||||
public int Uploads { get; init; } = 2;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 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 <see cref="ResolveAsync"/>, against the versions the user was shown. Uploads and
|
||||
/// downloads run as jobs (<see cref="CreateJobHandlers"/>): 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 <see cref="RemoteSequence"/>; 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 <c>sync_state</c> for the Library. A failure while
|
||||
/// comparing one sequence is recorded on its link and does not stop the others.
|
||||
/// </summary>
|
||||
public sealed class SyncService
|
||||
{
|
||||
private const string LogCategory = "sync";
|
||||
private const string SessionKeyPrefix = "titano-sync:";
|
||||
|
||||
/// <summary>Recomputes states without sending or taking settings on the user's behalf.</summary>
|
||||
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);
|
||||
|
||||
/// <summary>Unlinked pairs whose manifests were compared at these frame versions without a match (not fetched again).</summary>
|
||||
private readonly ConcurrentDictionary<string, byte> _unmatched = new(StringComparer.Ordinal);
|
||||
|
||||
public SyncService(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; }
|
||||
|
||||
/// <summary>The links or local states of a server (the argument) changed: refresh, resolution, transfer; raised on any thread.</summary>
|
||||
public event Action<string>? Changed;
|
||||
|
||||
internal ProxyCache Proxies { get; }
|
||||
|
||||
internal SyncLinkStore Links => _links;
|
||||
|
||||
internal TitanoDatabase Database => _db;
|
||||
|
||||
internal ArchiveService Archives { get; }
|
||||
|
||||
/// <summary>"https://nas.local:8443": the key links are stored under (scheme, lower-case host, port, path).</summary>
|
||||
public static string ServerKey(Uri address) => address.GetLeftPart(UriPartial.Path).TrimEnd('/').ToLowerInvariant();
|
||||
|
||||
/// <summary>What an upload or download job moves; null for any other job.</summary>
|
||||
public static SyncTransferKind? TransferKind(Job job) => SyncJobParameters.Read(job)?.Kind(job.Kind);
|
||||
|
||||
/// <summary>Session key the local archive groups the downloaded originals of one server sequence by.</summary>
|
||||
internal static string SessionKey(Guid remoteId) => SessionKeyPrefix + remoteId.ToString("N");
|
||||
|
||||
// ---------------- Table ----------------
|
||||
|
||||
/// <summary>
|
||||
/// Lists the server, compares every sequence with its local copy, sends or takes settings changed on one side when
|
||||
/// <see cref="SyncPolicy.AutoSyncSettings"/> is on, forgets sequences the server confirms deleted, links unlinked
|
||||
/// copies holding the same originals, and stores the states.
|
||||
/// </summary>
|
||||
public async Task<SyncSnapshot> RefreshAsync(ISyncRemote remote, SyncPolicy policy, CancellationToken cancellationToken)
|
||||
{
|
||||
var clock = Stopwatch.StartNew();
|
||||
var listing = await remote.ListSequencesAsync(cancellationToken).ConfigureAwait(false);
|
||||
Dictionary<Guid, Sequence> locals;
|
||||
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
var links = (await _links.ListAsync(remote.Server, cancellationToken).ConfigureAwait(false)).ToDictionary(l => l.RemoteId);
|
||||
locals = await LocalSequencesAsync(cancellationToken).ConfigureAwait(false);
|
||||
foreach (var dto in listing)
|
||||
{
|
||||
links.Remove(dto.Id, out var link);
|
||||
var local = await LocalOfAsync(link, locals, cancellationToken).ConfigureAwait(false);
|
||||
await ReconcileSafelyAsync(remote, Observe(link, remote.Server, dto), dto, local, locals, policy, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
// Not in the listing: deleted on the server, or created or moved while its pages were read. Only a 404 forgets a link.
|
||||
foreach (var link in links.Values) await CompareOneAsync(remote, link.RemoteId, link, locals, policy, cancellationToken).ConfigureAwait(false);
|
||||
await MatchByContentAsync(remote, listing, locals, policy, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
var entries = await StoreStatesAsync(remote.Server, locals, cancellationToken).ConfigureAwait(false);
|
||||
Changed?.Invoke(remote.Server);
|
||||
return new SyncSnapshot(remote.Server, entries, DateTimeOffset.UtcNow, clock.Elapsed);
|
||||
}
|
||||
|
||||
/// <summary>Compares the given server sequences again (live events, finished transfers); a sequence gone from the server is forgotten.</summary>
|
||||
public async Task RefreshSequencesAsync(ISyncRemote remote, IReadOnlyCollection<Guid> remoteIds, SyncPolicy policy, CancellationToken cancellationToken)
|
||||
{
|
||||
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
foreach (var id in remoteIds)
|
||||
{
|
||||
var link = await _links.GetAsync(remote.Server, id, cancellationToken).ConfigureAwait(false);
|
||||
await CompareOneAsync(remote, id, link, null, policy, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
await StoreStatesAsync(remote.Server, null, cancellationToken).ConfigureAwait(false);
|
||||
Changed?.Invoke(remote.Server);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sync table of <paramref name="server"/> as last compared: every server sequence and every local one, with
|
||||
/// active transfers; conflicts first, then transfers, then by title.
|
||||
/// </summary>
|
||||
public Task<IReadOnlyList<SyncEntry>> ListAsync(string server, CancellationToken cancellationToken) => EntriesAsync(server, null, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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 ----------------
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="SyncConflictChangedException"/>
|
||||
/// is thrown. Returns the file this PC's settings were saved to for <see cref="SyncResolution.SaveBoth"/>, else null.
|
||||
/// </summary>
|
||||
public async Task<string?> 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);
|
||||
if (link is not { ConflictRemote: { } theirs, ConflictLocalSettings: { } seenLocal, ConflictRemoteSettings: { } seenRemote }
|
||||
|| local.SettingsVersion != seenLocal)
|
||||
{
|
||||
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
|
||||
{
|
||||
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}");
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Sends or takes settings changed on one side only (the row action while automatic sync is off).</summary>
|
||||
public Task SyncSettingsAsync(ISyncRemote remote, Guid remoteId, SyncPolicy policy, CancellationToken cancellationToken) =>
|
||||
RefreshSequencesAsync(remote, [remoteId], policy with { AutoSyncSettings = true }, cancellationToken);
|
||||
|
||||
// ---------------- Transfers ----------------
|
||||
|
||||
/// <summary>Queues the upload of a local sequence's originals and settings, unless one is already waiting or running.</summary>
|
||||
public Task<Job> EnqueueUploadAsync(JobEngine engine, string server, Sequence local, CancellationToken cancellationToken = default) =>
|
||||
EnqueueAsync(engine, JobKind.UploadCommit, local.Id, local.DisplayTitle, new SyncJobParameters(server), JobPriority.User, cancellationToken);
|
||||
|
||||
/// <summary>Queues sending the renders of a local copy the server lacks (BRIEF §14.5), unless that is already waiting or running.</summary>
|
||||
public Task<Job> EnqueueSendExportsAsync(JobEngine engine, string server, Sequence local, CancellationToken cancellationToken = default) =>
|
||||
EnqueueAsync(engine, JobKind.UploadCommit, local.Id, local.DisplayTitle, new SyncJobParameters(server, Upload: SyncUploadMode.Exports), JobPriority.User,
|
||||
cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Queues a download of a server sequence, unless the same one is already waiting or running: originals into
|
||||
/// <paramref name="archiveId"/> (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.
|
||||
/// </summary>
|
||||
public Task<Job> 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);
|
||||
|
||||
/// <summary>Handlers for <see cref="JobKind.UploadCommit"/> and <see cref="JobKind.Download"/>; register them on the client's engine.</summary>
|
||||
public IReadOnlyList<IJobHandler> CreateJobHandlers(ISyncConnector connector)
|
||||
{
|
||||
var transfers = new SyncTransfers(this);
|
||||
return [new SyncJobHandler(JobKind.UploadCommit, transfers, connector), new SyncJobHandler(JobKind.Download, transfers, connector)];
|
||||
}
|
||||
|
||||
/// <summary>A server sequence from the proxy cache, for the editor; null when its proxies were never fetched or were cleared.</summary>
|
||||
public RemoteSequence? OpenRemote(string server, Guid remoteId) => Proxies.Load(server, remoteId);
|
||||
|
||||
// ---------------- Engine ----------------
|
||||
|
||||
/// <summary>Server ids of the sequences an upload or download job is working on.</summary>
|
||||
internal async Task<IReadOnlySet<Guid>> 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();
|
||||
}
|
||||
|
||||
/// <summary>Creates or updates the link of a local sequence to a server sequence (an upload or download made it).</summary>
|
||||
internal async Task<SyncLink> LinkAsync(string server, Guid remoteId, Sequence local, CancellationToken cancellationToken)
|
||||
{
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Forgets a link whose server sequence an upload found deleted (its originals go into a new one).</summary>
|
||||
internal async Task ForgetGoneAsync(string server, Guid remoteId, CancellationToken cancellationToken)
|
||||
{
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
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
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Makes this PC's copy equal to the server's (a sequence a download just created takes the server's settings).</summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Compares a sequence again after a transfer, originals and renders included even when no counter moved (a
|
||||
/// restored original or a hash given by verify changes no frame version), without sending or taking settings.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Records what the proxy cache holds for a server sequence.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>The file of a local render: archive-relative for outputs inside the archive, absolute otherwise.</summary>
|
||||
internal static string RenderFile(Archive archive, Render render) =>
|
||||
Path.IsPathRooted(render.OutputPath) ? render.OutputPath : new ArchivePaths(archive.RootPath).FromRelative(render.OutputPath);
|
||||
|
||||
/// <summary>
|
||||
/// Compares one server sequence (under the gate): fetches it, forgets its link on a 404, records a failure on its
|
||||
/// link. <paramref name="locals"/> (when given) receives the local copy as it stands after the comparison.
|
||||
/// </summary>
|
||||
private async Task CompareOneAsync(ISyncRemote remote, Guid remoteId, SyncLink? link, Dictionary<Guid, Sequence>? locals, SyncPolicy policy,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
SequenceDto dto;
|
||||
try
|
||||
{
|
||||
dto = await remote.GetSequenceAsync(remoteId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound)
|
||||
{
|
||||
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<Guid, Sequence>? 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 (IsIsolated(ex, cancellationToken))
|
||||
{
|
||||
// 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);
|
||||
}
|
||||
|
||||
/// <summary>A failure that concerns one sequence; a lost session (401) or the caller's cancellation stops the whole comparison.</summary>
|
||||
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,
|
||||
};
|
||||
|
||||
/// <summary>Compares originals and renders when either side's moved, then settles the settings; returns the updated link and local copy.</summary>
|
||||
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), null);
|
||||
}
|
||||
SequenceManifest? manifest = null;
|
||||
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 = 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, local) = await SettleSettingsAsync(remote, link, dto, local, manifest, policy, cancellationToken).ConfigureAwait(false);
|
||||
return (link with { SyncedAt = DateTimeOffset.UtcNow }, local);
|
||||
}
|
||||
|
||||
/// <summary>Renders each side lacks, by id (a render keeps its id on both sides); local renders whose file is gone cannot be sent.</summary>
|
||||
private async Task<SyncLink> CompareExportsAsync(SyncLink link, Sequence local, IReadOnlyList<RenderDto> remoteRenders, CancellationToken cancellationToken)
|
||||
{
|
||||
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, local);
|
||||
if (localChanged && remoteChanged)
|
||||
{
|
||||
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), local);
|
||||
// Last writer wins only when one side changed; both changed differently is the user's choice (BRIEF §14.5).
|
||||
return (link with
|
||||
{
|
||||
ConflictLocalSettings = local.SettingsVersion,
|
||||
ConflictRemoteSettings = manifest.SettingsVersion,
|
||||
ConflictRemote = theirs with { SettingsJson = SyncRules.NormalizeSettings(theirs.SettingsJson) },
|
||||
}, local);
|
||||
}
|
||||
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), pulled);
|
||||
}
|
||||
|
||||
/// <summary>Sends this PC's payload unless the server moved past <paramref name="expected"/>, which shows up as a conflict next.</summary>
|
||||
private static async Task<SyncLink> 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));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Links local copies and server sequences that hold the same originals but no link joins (an Uploader upload of
|
||||
/// the same card, a link lost with an old index): candidates start at the same second with the same camera, and
|
||||
/// at least half of the smaller side's originals must match by SHA-256. A pair that does not match is not fetched
|
||||
/// again until either side's frames change.
|
||||
/// </summary>
|
||||
private async Task MatchByContentAsync(ISyncRemote remote, IReadOnlyList<SequenceDto> listing, Dictionary<Guid, Sequence> locals, SyncPolicy policy,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var links = await _links.ListAsync(remote.Server, cancellationToken).ConfigureAwait(false);
|
||||
var linkedLocals = links.Where(l => l.LocalId is not null).Select(l => l.LocalId!.Value).ToHashSet();
|
||||
var linkedRemotes = links.Where(l => l.LocalId is not null).Select(l => l.RemoteId).ToHashSet();
|
||||
var candidates = listing.Where(d => !linkedRemotes.Contains(d.Id) && d.FrameCount > 0 && d.FirstCapture is not null)
|
||||
.ToLookup(d => Second(d.FirstCapture!.Value));
|
||||
foreach (var local in locals.Values.Where(l => !linkedLocals.Contains(l.Id) && l.FrameCount > 0 && l.FirstCapture is not null).ToList())
|
||||
{
|
||||
foreach (var dto in candidates[Second(local.FirstCapture!.Value)])
|
||||
{
|
||||
if (linkedRemotes.Contains(dto.Id) || !string.Equals(dto.CameraModel, local.CameraModel, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
var key = string.Create(CultureInfo.InvariantCulture, $"{local.Id:N}:{local.FramesVersion}:{dto.Id:N}:{dto.FramesVersion}");
|
||||
if (_unmatched.ContainsKey(key)) continue;
|
||||
try
|
||||
{
|
||||
if (!await SameOriginalsAsync(remote, local, dto, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
_unmatched[key] = 0;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (IsIsolated(ex, cancellationToken))
|
||||
{
|
||||
Log.Warning(LogCategory, $"{local.DisplayTitle} could not be matched with {dto.DisplayTitle}", ex);
|
||||
continue;
|
||||
}
|
||||
Log.Info(LogCategory, $"{local.DisplayTitle} holds the originals of {dto.DisplayTitle} on {remote.Server}: linked");
|
||||
var link = links.FirstOrDefault(l => l.RemoteId == dto.Id);
|
||||
var linked = Unlinked(Observe(link, remote.Server, dto)) with { LocalId = local.Id };
|
||||
await ReconcileSafelyAsync(remote, linked, dto, local, locals, policy, cancellationToken).ConfigureAwait(false);
|
||||
linkedRemotes.Add(dto.Id);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<bool> 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<string>().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);
|
||||
|
||||
/// <summary>Writes a payload into the local sidecar, project and index (each write bumps the local settings version).</summary>
|
||||
private async Task<Sequence> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "Save both": this PC's project is kept next to <c>project.json</c> as <c>project.this-pc-<local time>.json</c>
|
||||
/// before the server's replaces it; returns that file.
|
||||
/// </summary>
|
||||
private async Task<string> 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 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);
|
||||
Proxies.Delete(link.Server, link.RemoteId);
|
||||
Log.Info(LogCategory, $"{link.Title} is no longer on {link.Server}");
|
||||
}
|
||||
|
||||
/// <summary>Writes each local sequence's state for the Library and returns the table.</summary>
|
||||
private async Task<IReadOnlyList<SyncEntry>> StoreStatesAsync(string server, Dictionary<Guid, Sequence>? locals, CancellationToken cancellationToken)
|
||||
{
|
||||
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)
|
||||
await _links.SetLocalStateAsync(local.Id, state, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
/// <summary>The table from the stored links and <paramref name="known"/> local sequences (read from the index when null).</summary>
|
||||
private async Task<IReadOnlyList<SyncEntry>> EntriesAsync(string server, Dictionary<Guid, Sequence>? known, CancellationToken cancellationToken)
|
||||
{
|
||||
var links = await _links.ListAsync(server, cancellationToken).ConfigureAwait(false);
|
||||
var locals = known is null ? await LocalSequencesAsync(cancellationToken).ConfigureAwait(false) : new Dictionary<Guid, Sequence>(known);
|
||||
var transfers = await _links.ActiveTransfersAsync(cancellationToken).ConfigureAwait(false);
|
||||
var entries = new List<SyncEntry>(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)];
|
||||
}
|
||||
|
||||
/// <summary>The transfer a row shows: the user's before background ones, originals before renders before proxies, running before waiting.</summary>
|
||||
private static Job? Pick(IReadOnlyList<Job>? local, IReadOnlyList<Job>? 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();
|
||||
|
||||
/// <summary>The local copy of a link: from <paramref name="locals"/>, or the index when the paged listing missed it.</summary>
|
||||
private async Task<Sequence?> LocalOfAsync(SyncLink? link, Dictionary<Guid, Sequence>? 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);
|
||||
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<Dictionary<Guid, Sequence>> LocalSequencesAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var all = new Dictionary<Guid, Sequence>();
|
||||
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<Job> EnqueueAsync(JobEngine engine, JobKind kind, Guid target, string label, SyncJobParameters parameters, JobPriority priority,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>The link with the server's side as <paramref name="dto"/> lists it (a new link when there was none).</summary>
|
||||
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,
|
||||
ConflictRemote = null,
|
||||
};
|
||||
|
||||
private static SyncLink Unlinked(SyncLink link) => link with
|
||||
{
|
||||
LocalId = null,
|
||||
BaseLocalSettings = null,
|
||||
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,
|
||||
ConflictRemote = null,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,523 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using Titano.Core.Archiving;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Archiving;
|
||||
using Titano.Data.Archiving.Jobs;
|
||||
using Titano.Data.Jobs;
|
||||
using Titano.Data.Processing;
|
||||
using Titano.Protocol;
|
||||
using Titano.Protocol.Client;
|
||||
using SequenceFrames = Titano.Data.Processing.SequenceFrames;
|
||||
|
||||
namespace Titano.Data.Sync;
|
||||
|
||||
/// <summary>
|
||||
/// The work of upload and download jobs. Uploads send every local original the server lacks through the chunked,
|
||||
/// resumable protocol after hashing it again (an original that no longer matches its archived hash is never sent),
|
||||
/// creating the server sequence first and sending its settings when the upload made it. Downloads fetch originals the
|
||||
/// local copy lacks into the archive's staging folder (resuming with Range), require the manifest's SHA-256 and commit
|
||||
/// them through the archive ingest, which names them and writes the sidecar; the first original creates the local
|
||||
/// sequence, which then takes the server's settings. 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.
|
||||
/// </summary>
|
||||
internal sealed class SyncTransfers(SyncService sync)
|
||||
{
|
||||
private const long SpaceReserve = 512L << 20;
|
||||
|
||||
/// <summary>Space a cached proxy is assumed to take before it is downloaded (1920 px JPEG, BRIEF §8.5).</summary>
|
||||
private const long ProxyEstimate = 3L << 19;
|
||||
|
||||
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 frames = (await SequenceFrames.ListAsync(db, local.Id, ct).ConfigureAwait(false)).Where(f => (f.Flags & FrameFlags.Missing) == 0).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<Frame>(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, 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, target, ct).ConfigureAwait(false);
|
||||
await sync.RecompareAsync(remote, target, 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);
|
||||
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"));
|
||||
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;
|
||||
var restored = 0;
|
||||
await Parallel.ForEachAsync(rest, Workers(sync.Options.Downloads, ct), async (frame, token) =>
|
||||
{
|
||||
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.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);
|
||||
await EnqueueFollowUpAsync(ProcessingJobs.LightAnalysis([downloaded], label), ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private async Task<(HashSet<string> Have, Dictionary<string, string> 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<string, string>(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);
|
||||
|
||||
/// <summary>Puts a verified copy of an original flagged missing back where its record says; a file that reappeared meanwhile is kept.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>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.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>"name.mp4", else "name (2).mp4", … — an existing export is never replaced.</summary>
|
||||
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;
|
||||
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));
|
||||
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);
|
||||
await progress.ReportAsync().ConfigureAwait(false);
|
||||
await Parallel.ForEachAsync(Enumerable.Range(0, frames.Count), Workers(sync.Options.Downloads, ct), async (i, token) =>
|
||||
{
|
||||
IReadOnlyList<string> kinds = assets.TryGetValue(frames[i].Id, out var asset) ? Kinds(asset) : [];
|
||||
files[i] = await FetchProxyAsync(remote, frames[i].Id, kinds, folder, token).ConfigureAwait(false);
|
||||
await progress.StepAsync().ConfigureAwait(false);
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
sync.Proxies.Save(remote.Server, remoteId, new ProxyCacheIndex(dto, manifest.SettingsJson, manifest.FramesVersion, frames, files));
|
||||
var cached = files.Count(f => f is not null);
|
||||
await sync.SetProxiesAsync(remote.Server, dto, cached, manifest.FramesVersion, ct).ConfigureAwait(false);
|
||||
if (cached < frames.Count) context.Log($"{frames.Count - cached} frame(s) have neither proxy nor thumbnail on the server");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The server sequence an upload fills and whether this job creates it: the linked one, the one an interrupted
|
||||
/// attempt created, or none yet (the first original creates it).
|
||||
/// </summary>
|
||||
private async Task<(Guid? RemoteId, bool Created)> TargetAsync(JobContext context, ISyncRemote remote, Sequence local)
|
||||
{
|
||||
var ct = context.Cancellation;
|
||||
Guid? started = Guid.TryParse(context.Checkpoint, out var saved) ? saved : null;
|
||||
var link = await sync.Links.FindByLocalAsync(remote.Server, local.Id, ct).ConfigureAwait(false);
|
||||
foreach (var candidate in new[] { link?.RemoteId, started })
|
||||
{
|
||||
if (candidate is not { } id) continue;
|
||||
if (await ExistsAsync(remote, id, ct).ConfigureAwait(false))
|
||||
{
|
||||
if (link?.RemoteId != id) await sync.LinkAsync(remote.Server, id, local, ct).ConfigureAwait(false);
|
||||
return (id, id == started);
|
||||
}
|
||||
// Deleted on the server meanwhile: the originals go into a new sequence.
|
||||
if (id == link?.RemoteId) await sync.ForgetGoneAsync(remote.Server, id, ct).ConfigureAwait(false);
|
||||
}
|
||||
return (null, true);
|
||||
}
|
||||
|
||||
private static async Task<bool> ExistsAsync(ISyncRemote remote, Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await remote.GetSequenceAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Hashes the original again and sends it into <paramref name="sequenceId"/> (or the sequence of
|
||||
/// <paramref name="sessionKey"/>); null (logged) when it is gone or no longer the archived file.
|
||||
/// </summary>
|
||||
private static async Task<CompleteUploadResponse?> 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 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 null;
|
||||
}
|
||||
return await remote.UploadFileAsync(path, sequenceId, sessionKey, sha, frame.CapturedAt, cancellationToken).ConfigureAwait(false)
|
||||
?? new CompleteUploadResponse(Guid.Empty, sequenceId ?? Guid.Empty, -1);
|
||||
}
|
||||
|
||||
/// <summary>Downloads one original into staging and commits it into the local sequence (created from the server id when null).</summary>
|
||||
private async Task<IngestResult> CommitAsync(ISyncRemote remote, Guid remoteId, Guid archiveId, Guid? sequenceId, ManifestFrame frame, string staging,
|
||||
IReadOnlyDictionary<Guid, DateTime?> captured, CancellationToken cancellationToken)
|
||||
{
|
||||
var staged = await FetchOriginalAsync(remote, frame, staging, cancellationToken).ConfigureAwait(false);
|
||||
var request = new IngestRequest(archiveId, sequenceId, null, sequenceId is null ? SyncService.SessionKey(remoteId) : null, staged, frame.FileName,
|
||||
frame.Size, frame.Sha256.ToLowerInvariant(), captured.GetValueOrDefault(frame.Id), null);
|
||||
var result = await sync.Archives.Ingest.CommitAsync(request, cancellationToken).ConfigureAwait(false);
|
||||
// A duplicate stays in staging (the sequence already holds that content).
|
||||
if (result.Duplicate) File.Delete(staged);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>A verified copy in staging: resumed from a partial download, accepted only with the manifest's SHA-256 (two attempts).</summary>
|
||||
private static async Task<string> FetchOriginalAsync(ISyncRemote remote, ManifestFrame frame, string staging, CancellationToken cancellationToken)
|
||||
{
|
||||
var sha = frame.Sha256.ToLowerInvariant();
|
||||
if (sha.Length != 64 || !sha.All(char.IsAsciiHexDigitLower)) throw new InvalidDataException(Loc.L("Errors.Sync.Hash", frame.FileName));
|
||||
var target = Path.Combine(staging, sha + Path.GetExtension(frame.FileName).ToLowerInvariant());
|
||||
if (File.Exists(target)) return target;
|
||||
var part = target + ".part";
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
await using (var file = new FileStream(part, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
|
||||
await remote.DownloadFrameAsync(frame.Id, "original", file, cancellationToken).ConfigureAwait(false);
|
||||
if (await TitanoClient.HashFileAsync(part, cancellationToken).ConfigureAwait(false) == sha)
|
||||
{
|
||||
File.Move(part, target, overwrite: true);
|
||||
return target;
|
||||
}
|
||||
File.Delete(part);
|
||||
if (attempt == 2) throw new InvalidDataException(Loc.L("Errors.Sync.Hash", frame.FileName));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The cached proxy's file name, downloading the first asset kind the server has; null when it has none.</summary>
|
||||
private static async Task<string?> FetchProxyAsync(ISyncRemote remote, Guid frameId, IReadOnlyList<string> kinds, string folder, CancellationToken cancellationToken)
|
||||
{
|
||||
var name = ProxyCache.FileName(frameId);
|
||||
var path = Path.Combine(folder, name);
|
||||
if (new FileInfo(path) is { Exists: true, Length: > 0 }) return name;
|
||||
var part = path + ".part";
|
||||
foreach (var kind in kinds)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using (var file = new FileStream(part, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
|
||||
await remote.DownloadFrameAsync(frameId, kind, file, cancellationToken).ConfigureAwait(false);
|
||||
File.Move(part, path, overwrite: true);
|
||||
return name;
|
||||
}
|
||||
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound)
|
||||
{
|
||||
File.Delete(part);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string[] Kinds(ManifestFrame frame) => (frame.HasProxy, frame.HasThumb) switch
|
||||
{
|
||||
(true, true) => ["proxy", "thumb"],
|
||||
(true, false) => ["proxy"],
|
||||
(false, true) => ["thumb"],
|
||||
_ => [],
|
||||
};
|
||||
|
||||
/// <summary>Puts a follow-up job in the queue; the engine claims it on its next poll.</summary>
|
||||
private Task EnqueueFollowUpAsync(ArchiveJobRequest request, CancellationToken cancellationToken) =>
|
||||
sync.Database.Jobs.EnqueueAsync(new Job
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Kind = request.Kind,
|
||||
TargetIds = request.Targets,
|
||||
TargetLabel = request.Label,
|
||||
ParametersJson = request.ParametersJson,
|
||||
Priority = request.Priority,
|
||||
State = JobState.Queued,
|
||||
Created = DateTimeOffset.UtcNow,
|
||||
}, cancellationToken);
|
||||
|
||||
private static void EnsureSpace(string root, long bytes)
|
||||
{
|
||||
long? free;
|
||||
try
|
||||
{
|
||||
var full = Path.GetFullPath(root);
|
||||
// Windows wants a drive root; Unix accepts any directory and reports the volume it is mounted on.
|
||||
free = new DriveInfo(OperatingSystem.IsWindows() ? Path.GetPathRoot(full)! : full).AvailableFreeSpace;
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or IOException or UnauthorizedAccessException)
|
||||
{
|
||||
free = null; // network shares: the copy itself reports a full disk
|
||||
}
|
||||
if (free is { } available && available < bytes + SpaceReserve)
|
||||
throw new IOException(Loc.L("Errors.Sync.DiskFull", ((bytes + SpaceReserve - available) / 1e9).ToString("0.0", CultureInfo.CurrentCulture)));
|
||||
}
|
||||
|
||||
private static void TryDeleteDirectory(string folder)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.Delete(folder, recursive: true);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Core.Diagnostics.Log.Warning("sync", $"Staging folder {folder} could not be removed", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static ParallelOptions Workers(int degree, CancellationToken cancellationToken) =>
|
||||
new() { MaxDegreeOfParallelism = Math.Max(1, degree), CancellationToken = cancellationToken };
|
||||
|
||||
/// <summary>Files done out of the total, reported in order from parallel workers.</summary>
|
||||
private sealed class TransferProgress(JobContext context, long total, long done)
|
||||
{
|
||||
private readonly SemaphoreSlim _gate = new(1, 1);
|
||||
|
||||
public async Task StepAsync()
|
||||
{
|
||||
await _gate.WaitAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
done++;
|
||||
await context.ReportAsync(done, total).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public long Done => done;
|
||||
|
||||
public ValueTask ReportAsync() => context.ReportAsync(done, total);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user