fix(sync): resolve conflicts against the versions shown, isolate failures, renders on request
- Conflicts are settled against the versions the user was shown; a later change on
either side refuses the choice and compares again. Title, tags, rating and notes
changed differently on both sides are a conflict too (no silent tag union).
- Links are written under the engine's gate and forgotten only after a 404; linked
local copies are read by id; unlinked copies with the same originals are linked
by content.
- A failure on one sequence is recorded on its link; the others are still compared.
- Downloads hash unverified local copies first and restore originals missing here.
- Background proxy downloads give way to the user's requests; "Keep proxies offline"
refreshes the caches of sequences opened with proxies, checks free space and backs
off after a failure.
- Renders travel on request: Send exports (chunked, hash-verified upload keeping the
render id; new POST /sequences/{id}/renders endpoints) and Get exports.
- Server screen: stable row buttons, mockup column grid, Tab through rows, conflict
rows first on the card colour, localised conflict detail, Save both confirmation,
Pause metered uploads, culture switch, Library one-word sync glyphs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
48 files changed
+2498
-465
No files matched your search
@@ -1,5 +1,6 @@
|
||||
-- Client sync state (BRIEF §4.4, §14.5): one row per sequence of a server this client has listed, linked to the local
|
||||
-- copy when there is one. Versions are the counters both sides agreed on at the last sync. Mirrors sqlite/0004_sync.sql.
|
||||
-- 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,
|
||||
@@ -17,13 +18,20 @@ CREATE TABLE sync_links (
|
||||
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_settings text,
|
||||
conflict_remote text,
|
||||
proxies_cached integer NOT NULL DEFAULT 0,
|
||||
proxies_frames_version integer,
|
||||
error text,
|
||||
synced_at timestamptz,
|
||||
PRIMARY KEY (server, remote_id)
|
||||
);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
-- Client sync state (BRIEF §4.4, §14.5): one row per sequence of a server this client has listed, linked to the local
|
||||
-- copy when there is one. Versions are the counters both sides agreed on at the last sync. Mirrors postgres/0004_sync.sql.
|
||||
-- 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,
|
||||
@@ -17,13 +18,20 @@ CREATE TABLE sync_links (
|
||||
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_settings TEXT,
|
||||
conflict_remote TEXT,
|
||||
proxies_cached INTEGER NOT NULL DEFAULT 0,
|
||||
proxies_frames_version INTEGER,
|
||||
error TEXT,
|
||||
synced_at TEXT,
|
||||
PRIMARY KEY (server, remote_id)
|
||||
);
|
||||
|
||||
@@ -27,8 +27,8 @@ public sealed record SyncAgentOptions
|
||||
/// 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"/>, proxy downloads queued for every server sequence without local
|
||||
/// originals whose cache is stale. Dispose to stop.
|
||||
/// <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
|
||||
{
|
||||
@@ -43,6 +43,11 @@ public sealed class SyncAgent : IAsyncDisposable
|
||||
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;
|
||||
@@ -200,8 +205,9 @@ public sealed class SyncAgent : IAsyncDisposable
|
||||
var due = ids.Where(id => !busy.Contains(id)).ToList();
|
||||
if (due.Count > 0) await _sync.RefreshSequencesAsync(_remote, due, _policy(), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
catch (Exception ex) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
// Includes timeouts reported as cancellation: the loop goes on and a full comparison catches up.
|
||||
Log.Warning(LogCategory, $"Comparing changed sequences of {Server} failed", ex);
|
||||
RequestRefresh();
|
||||
}
|
||||
@@ -212,14 +218,34 @@ public sealed class SyncAgent : IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Queues (background priority) the proxies of server sequences without local originals whose cache is stale.</summary>
|
||||
/// <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: { ServerHasProxies: true, ProxiesStale: true } link }) continue;
|
||||
await _sync.EnqueueDownloadAsync(_engine!, Server, link.RemoteId, link.Title, SyncDownloadMode.Proxies, null, JobPriority.Background, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (entry is not { Local: null, Transfer: null, Link: { ProxiesCached: > 0, ServerHasProxies: true, ProxiesStale: true } link }) continue;
|
||||
if (_proxyFailures.TryGetValue(link.RemoteId, out var failed) && DateTime.UtcNow < failed.NotBefore) continue;
|
||||
var job = await _sync.EnqueueDownloadAsync(_engine!, Server, link.RemoteId, link.Title, SyncDownloadMode.Proxies, null, JobPriority.Background,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
_proxyJobs[link.RemoteId] = job.Id;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,12 +6,54 @@ 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);
|
||||
internal sealed record SyncJobParameters(string Server, SyncDownloadMode? Mode = null, Guid? ArchiveId = null, SyncUploadMode? Upload = null)
|
||||
{
|
||||
public static SyncJobParameters? Read(Job job)
|
||||
{
|
||||
if (job.Kind is not (JobKind.UploadCommit or JobKind.Download) || job.ParametersJson is not { } json) return null;
|
||||
try
|
||||
{
|
||||
return JsonSerializer.Deserialize(json, SyncJobJson.Default.SyncJobParameters);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public SyncTransferKind Kind(JobKind kind) => (kind, Mode, Upload) switch
|
||||
{
|
||||
(JobKind.UploadCommit, _, SyncUploadMode.Exports) => SyncTransferKind.SendExports,
|
||||
(JobKind.UploadCommit, _, _) => SyncTransferKind.Upload,
|
||||
(_, SyncDownloadMode.Proxies, _) => SyncTransferKind.DownloadProxies,
|
||||
(_, SyncDownloadMode.Exports, _) => SyncTransferKind.GetExports,
|
||||
_ => SyncTransferKind.DownloadOriginals,
|
||||
};
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, UseStringEnumConverter = true,
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
@@ -25,19 +67,24 @@ internal sealed class SyncJobHandler(JobKind kind, SyncTransfers transfers, ISyn
|
||||
|
||||
public async Task RunAsync(JobContext context)
|
||||
{
|
||||
var parameters = (context.Job.ParametersJson is { } json ? JsonSerializer.Deserialize(json, SyncJobJson.Default.SyncJobParameters) : null)
|
||||
?? throw new InvalidDataException("The job has no sync parameters.");
|
||||
var parameters = SyncJobParameters.Read(context.Job) ?? throw new InvalidDataException("The job has no sync parameters.");
|
||||
if (context.Job.TargetIds is not [var target, ..]) throw new InvalidDataException("The job has no target sequence.");
|
||||
using var remote = await connector.ConnectAsync(parameters.Server, context.Cancellation).ConfigureAwait(false)
|
||||
?? throw new InvalidOperationException(Loc.L("Errors.Sync.NotConnected"));
|
||||
switch (kind, parameters.Mode)
|
||||
switch (parameters.Kind(kind))
|
||||
{
|
||||
case (JobKind.UploadCommit, _):
|
||||
case SyncTransferKind.Upload:
|
||||
await transfers.UploadAsync(context, remote, target).ConfigureAwait(false);
|
||||
break;
|
||||
case (JobKind.Download, SyncDownloadMode.Proxies):
|
||||
case SyncTransferKind.SendExports:
|
||||
await transfers.SendExportsAsync(context, remote, target).ConfigureAwait(false);
|
||||
break;
|
||||
case SyncTransferKind.DownloadProxies:
|
||||
await transfers.DownloadProxiesAsync(context, remote, target).ConfigureAwait(false);
|
||||
break;
|
||||
case SyncTransferKind.GetExports:
|
||||
await transfers.GetExportsAsync(context, remote, target).ConfigureAwait(false);
|
||||
break;
|
||||
default:
|
||||
await transfers.DownloadOriginalsAsync(context, remote, target, parameters.ArchiveId).ConfigureAwait(false);
|
||||
break;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Text.Json;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Repositories;
|
||||
|
||||
@@ -9,8 +10,8 @@ internal sealed class SyncLinkStore(TitanoDatabase db)
|
||||
private const string Columns =
|
||||
"server, remote_id, local_id, title, frame_count, total_bytes, render_count, remote_status, remote_settings_version, " +
|
||||
"remote_frames_version, remote_updated_at, base_local_settings, base_remote_settings, diff_local_frames, diff_remote_frames, " +
|
||||
"missing_remote, missing_local, conflict_local_settings, conflict_remote_settings, conflict_settings, proxies_cached, " +
|
||||
"proxies_frames_version, synced_at";
|
||||
"diff_local_renders, diff_remote_renders, missing_remote, missing_local, exports_to_get, exports_to_get_bytes, exports_to_send, " +
|
||||
"exports_to_send_bytes, conflict_local_settings, conflict_remote_settings, conflict_remote, proxies_cached, proxies_frames_version, error, synced_at";
|
||||
|
||||
private static readonly string UpsertSql = SqlDialect.Upsert("sync_links", Columns.Split(", "), 2);
|
||||
|
||||
@@ -32,8 +33,10 @@ internal sealed class SyncLinkStore(TitanoDatabase db)
|
||||
[
|
||||
l.Server, l.RemoteId, l.LocalId, l.Title, l.FrameCount, l.TotalBytes, l.RenderCount, (int)l.RemoteStatus, l.RemoteSettingsVersion,
|
||||
l.RemoteFramesVersion, l.RemoteUpdatedAt, l.BaseLocalSettings, l.BaseRemoteSettings, l.DiffLocalFrames, l.DiffRemoteFrames,
|
||||
l.MissingRemote, l.MissingLocal, l.ConflictLocalSettings, l.ConflictRemoteSettings, l.ConflictSettingsJson, l.ProxiesCached,
|
||||
l.ProxiesFramesVersion, l.SyncedAt,
|
||||
l.DiffLocalRenders, l.DiffRemoteRenders, l.MissingRemote, l.MissingLocal, l.ExportsToGet, l.ExportsToGetBytes, l.ExportsToSend,
|
||||
l.ExportsToSendBytes, l.ConflictLocalSettings, l.ConflictRemoteSettings,
|
||||
l.ConflictRemote is { } remote ? JsonSerializer.Serialize(remote, SyncPayloadJson.Default.SyncPayload) : null,
|
||||
l.ProxiesCached, l.ProxiesFramesVersion, l.Error, l.SyncedAt,
|
||||
], cancellationToken);
|
||||
|
||||
public Task DeleteAsync(string server, Guid remoteId, CancellationToken cancellationToken) =>
|
||||
@@ -48,9 +51,9 @@ internal sealed class SyncLinkStore(TitanoDatabase db)
|
||||
_db.ExecuteAsync("UPDATE sequences SET origin = $2 WHERE id = $1", [localId, (int)origin], cancellationToken);
|
||||
|
||||
/// <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, Job>> ActiveTransfersAsync(CancellationToken cancellationToken)
|
||||
public async Task<IReadOnlyDictionary<Guid, IReadOnlyList<Job>>> ActiveTransfersAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var transfers = new Dictionary<Guid, Job>();
|
||||
var jobs = new List<Job>();
|
||||
foreach (var kind in new[] { JobKind.UploadCommit, JobKind.Download })
|
||||
{
|
||||
foreach (var state in Active)
|
||||
@@ -59,16 +62,13 @@ internal sealed class SyncLinkStore(TitanoDatabase db)
|
||||
do
|
||||
{
|
||||
var page = await db.Jobs.ListAsync(state, kind, 500, cursor, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var job in page.Items)
|
||||
{
|
||||
if (job.TargetIds.Count > 0) transfers.TryAdd(job.TargetIds[0], job);
|
||||
}
|
||||
jobs.AddRange(page.Items.Where(j => j.TargetIds.Count > 0));
|
||||
cursor = page.NextCursor;
|
||||
}
|
||||
while (cursor is not null);
|
||||
}
|
||||
}
|
||||
return transfers;
|
||||
return jobs.GroupBy(j => j.TargetIds[0]).ToDictionary(g => g.Key, g => (IReadOnlyList<Job>)[.. g]);
|
||||
}
|
||||
|
||||
private static SyncLink Map(DbRow r) => new()
|
||||
@@ -88,13 +88,20 @@ internal sealed class SyncLinkStore(TitanoDatabase db)
|
||||
BaseRemoteSettings = r.GetInt32OrNull(12),
|
||||
DiffLocalFrames = r.GetInt32OrNull(13),
|
||||
DiffRemoteFrames = r.GetInt32OrNull(14),
|
||||
MissingRemote = r.GetInt32(15),
|
||||
MissingLocal = r.GetInt32(16),
|
||||
ConflictLocalSettings = r.GetInt32OrNull(17),
|
||||
ConflictRemoteSettings = r.GetInt32OrNull(18),
|
||||
ConflictSettingsJson = r.GetStringOrNull(19),
|
||||
ProxiesCached = r.GetInt32(20),
|
||||
ProxiesFramesVersion = r.GetInt32OrNull(21),
|
||||
SyncedAt = r.GetDateTimeOffsetOrNull(22),
|
||||
DiffLocalRenders = r.GetInt32OrNull(15),
|
||||
DiffRemoteRenders = r.GetInt32OrNull(16),
|
||||
MissingRemote = r.GetInt32(17),
|
||||
MissingLocal = r.GetInt32(18),
|
||||
ExportsToGet = r.GetInt32(19),
|
||||
ExportsToGetBytes = r.GetInt64(20),
|
||||
ExportsToSend = r.GetInt32(21),
|
||||
ExportsToSendBytes = r.GetInt64(22),
|
||||
ConflictLocalSettings = r.GetInt32OrNull(23),
|
||||
ConflictRemoteSettings = r.GetInt32OrNull(24),
|
||||
ConflictRemote = r.GetStringOrNull(25) is { } json ? JsonSerializer.Deserialize(json, SyncPayloadJson.Default.SyncPayload) : null,
|
||||
ProxiesCached = r.GetInt32(26),
|
||||
ProxiesFramesVersion = r.GetInt32OrNull(27),
|
||||
Error = r.GetStringOrNull(28),
|
||||
SyncedAt = r.GetDateTimeOffsetOrNull(29),
|
||||
};
|
||||
}
|
||||
@@ -20,20 +20,20 @@ public enum SyncStatus
|
||||
/// <summary>The server holds originals or settings this PC lacks.</summary>
|
||||
ServerAhead,
|
||||
|
||||
/// <summary>Both sides changed the settings since they last agreed: the user picks.</summary>
|
||||
/// <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 settings conflict (BRIEF §12.7).</summary>
|
||||
/// <summary>How the user settles a conflict (BRIEF §12.7).</summary>
|
||||
public enum SyncResolution
|
||||
{
|
||||
KeepMine,
|
||||
TakeServer,
|
||||
|
||||
/// <summary>The server's settings win; this PC's are kept next to the project as a dated copy.</summary>
|
||||
/// <summary>The server's version wins; this PC's settings are kept next to the project as a dated copy.</summary>
|
||||
SaveBoth,
|
||||
}
|
||||
|
||||
@@ -45,12 +45,25 @@ public enum SyncDownloadMode
|
||||
|
||||
/// <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 the missing
|
||||
/// counts were computed at, so originals are compared again only when either side's frames change.
|
||||
/// the settings counters both sides had when they last agreed; the diff versions are the frame counters and render
|
||||
/// counts the missing counts were computed at, so originals and renders are compared again only when either side's change.
|
||||
/// </summary>
|
||||
public sealed record SyncLink
|
||||
{
|
||||
@@ -75,6 +88,8 @@ public sealed record SyncLink
|
||||
public int? BaseRemoteSettings { get; init; }
|
||||
public int? DiffLocalFrames { get; init; }
|
||||
public int? DiffRemoteFrames { get; init; }
|
||||
public int? DiffLocalRenders { get; init; }
|
||||
public int? DiffRemoteRenders { get; init; }
|
||||
|
||||
/// <summary>Local originals the server does not have.</summary>
|
||||
public int MissingRemote { get; init; }
|
||||
@@ -82,13 +97,23 @@ public sealed record SyncLink
|
||||
/// <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 settings when the conflict was found, so it can be shown without asking the server again.</summary>
|
||||
public string? ConflictSettingsJson { 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; }
|
||||
@@ -96,6 +121,9 @@ public sealed record SyncLink
|
||||
/// <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;
|
||||
@@ -108,7 +136,7 @@ public sealed record SyncLink
|
||||
}
|
||||
|
||||
/// <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.</param>
|
||||
/// <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;
|
||||
@@ -131,5 +159,12 @@ public sealed record SyncSnapshot(string Server, IReadOnlyList<SyncEntry> Entrie
|
||||
|
||||
/// <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 proxies of every server sequence without local originals in the cache.</param>
|
||||
public sealed record SyncPolicy(bool AutoSyncSettings = true, bool KeepProxiesOffline = false);
|
||||
/// <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);
|
||||
@@ -38,6 +38,15 @@ public interface ISyncRemote : IDisposable
|
||||
/// <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);
|
||||
}
|
||||
@@ -99,6 +108,12 @@ public sealed class TitanoSyncRemote(TitanoClient client, bool ownsClient) : ISy
|
||||
public Task DownloadFrameAsync(Guid frameId, string kind, Stream destination, CancellationToken cancellationToken) =>
|
||||
client.DownloadFrameAsync(frameId, kind, destination, null, cancellationToken);
|
||||
|
||||
public Task<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()
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Text.Json.Serialization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Protocol;
|
||||
@@ -15,8 +17,8 @@ public sealed record SyncPayload(string? Title, IReadOnlyList<string> Tags, int
|
||||
|
||||
/// <summary>Title, tags, rating and notes match (blank equals absent, tags ignore case and order).</summary>
|
||||
public bool SameMetadata(SyncPayload other) =>
|
||||
Blank(Title) == Blank(other.Title)
|
||||
&& Blank(Notes) == Blank(other.Notes)
|
||||
SyncRules.Blank(Title) == SyncRules.Blank(other.Title)
|
||||
&& SyncRules.Blank(Notes) == SyncRules.Blank(other.Notes)
|
||||
&& Rating == other.Rating
|
||||
&& Tags.ToHashSet(StringComparer.OrdinalIgnoreCase).SetEquals(other.Tags);
|
||||
|
||||
@@ -25,20 +27,27 @@ public sealed record SyncPayload(string? Title, IReadOnlyList<string> Tags, int
|
||||
/// <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);
|
||||
|
||||
private static string Blank(string? text) => text?.Trim() ?? string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>One setting that differs: its dotted path ("exposure.deflicker.window") and the JSON value on each side (null when absent).</summary>
|
||||
[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 and metadata-only differences before a row is shown); missing originals count before
|
||||
/// settings changed on one side only.
|
||||
/// settles equal content before a row is shown); missing originals count before settings changed on one side only.
|
||||
/// </summary>
|
||||
public static SyncStatus Status(Sequence? local, SyncLink? link)
|
||||
{
|
||||
@@ -91,13 +100,20 @@ public static class SyncRules
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Metadata-only divergence (settings equal): tags are united, title, rating and notes come from the side edited last.
|
||||
/// 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 SyncPayload Merge(SyncPayload local, SyncPayload remote, bool localIsNewer)
|
||||
public static IReadOnlyList<SettingsDifference> Differences(SyncPayload mine, SyncPayload theirs, int max = 3)
|
||||
{
|
||||
var newer = localIsNewer ? local : remote;
|
||||
var tags = local.Tags.Concat(remote.Tags).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
|
||||
return newer with { Tags = tags, SettingsJson = local.SettingsJson };
|
||||
var differences = new List<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>
|
||||
@@ -114,6 +130,8 @@ public static class SyncRules
|
||||
return (hashed.Count - matched + Math.Max(0, unhashed - unmatchedRemote), Math.Max(0, unmatchedRemote - unhashed));
|
||||
}
|
||||
|
||||
internal static string Blank(string? text) => text?.Trim() ?? string.Empty;
|
||||
|
||||
private static JsonNode? Parse(string json)
|
||||
{
|
||||
try
|
||||
|
||||
+366
-113
@@ -1,3 +1,4 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
@@ -5,6 +6,7 @@ using System.Text.Json;
|
||||
using Titano.Core.Archiving;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.IO;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Archiving;
|
||||
using Titano.Data.Jobs;
|
||||
@@ -35,24 +37,33 @@ public sealed record SyncOptions
|
||||
|
||||
/// <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 moved, the manifest: originals are matched by SHA-256 and never conflict; settings, title,
|
||||
/// tags, rating and notes travel together under the settings version, so a change on one side is sent or taken
|
||||
/// (automatically or on request) and a change on both sides with different settings is a conflict the user settles
|
||||
/// with <see cref="ResolveAsync"/>. 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"/>. Proxies and
|
||||
/// thumbnails never travel upward. The state of each local sequence is written to its <c>sync_state</c> for the Library.
|
||||
/// and, when frame counters or render counts moved, the manifest: originals are matched by SHA-256 and never conflict;
|
||||
/// renders by id. Settings, title, tags, rating and notes travel together under the settings version, so a change on
|
||||
/// one side is sent or taken (automatically or on request) and a change on both sides with different content is a
|
||||
/// conflict the user settles with <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;
|
||||
@@ -79,6 +90,9 @@ public sealed class SyncService
|
||||
/// <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");
|
||||
|
||||
@@ -86,30 +100,34 @@ public sealed class SyncService
|
||||
|
||||
/// <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 deleted on the server, and stores the states.
|
||||
/// <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);
|
||||
var locals = await LocalSequencesAsync(cancellationToken).ConfigureAwait(false);
|
||||
locals = await LocalSequencesAsync(cancellationToken).ConfigureAwait(false);
|
||||
foreach (var dto in listing)
|
||||
{
|
||||
links.Remove(dto.Id, out var link);
|
||||
var local = link?.LocalId is { } id ? locals.GetValueOrDefault(id) : null;
|
||||
await ReconcileSafelyAsync(remote, Observe(link, remote.Server, dto), dto, local, policy, cancellationToken).ConfigureAwait(false);
|
||||
var local = await LocalOfAsync(link, locals, cancellationToken).ConfigureAwait(false);
|
||||
await ReconcileSafelyAsync(remote, Observe(link, remote.Server, dto), dto, local, locals, policy, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
foreach (var gone in links.Values) await ForgetAsync(gone, cancellationToken).ConfigureAwait(false);
|
||||
// Not in the listing: deleted on the server, or created or moved while its pages were read. Only a 404 forgets a link.
|
||||
foreach (var link in links.Values) await CompareOneAsync(remote, link.RemoteId, link, locals, policy, cancellationToken).ConfigureAwait(false);
|
||||
await MatchByContentAsync(remote, listing, locals, policy, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
var entries = await StoreStatesAsync(remote.Server, cancellationToken).ConfigureAwait(false);
|
||||
var entries = await StoreStatesAsync(remote.Server, locals, cancellationToken).ConfigureAwait(false);
|
||||
Changed?.Invoke(remote.Server);
|
||||
return new SyncSnapshot(remote.Server, entries, DateTimeOffset.UtcNow, clock.Elapsed);
|
||||
}
|
||||
@@ -123,49 +141,22 @@ public sealed class SyncService
|
||||
foreach (var id in remoteIds)
|
||||
{
|
||||
var link = await _links.GetAsync(remote.Server, id, cancellationToken).ConfigureAwait(false);
|
||||
SequenceDto dto;
|
||||
try
|
||||
{
|
||||
dto = await remote.GetSequenceAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound)
|
||||
{
|
||||
if (link is not null) await ForgetAsync(link, cancellationToken).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
var local = link?.LocalId is { } localId ? await _db.Sequences.GetAsync(localId, cancellationToken).ConfigureAwait(false) : null;
|
||||
await ReconcileSafelyAsync(remote, Observe(link, remote.Server, dto), dto, local, policy, cancellationToken).ConfigureAwait(false);
|
||||
await CompareOneAsync(remote, id, link, null, policy, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
await StoreStatesAsync(remote.Server, cancellationToken).ConfigureAwait(false);
|
||||
await StoreStatesAsync(remote.Server, null, cancellationToken).ConfigureAwait(false);
|
||||
Changed?.Invoke(remote.Server);
|
||||
}
|
||||
|
||||
/// <summary>The sync table of <paramref name="server"/> as last compared: every server sequence and every local one, with active transfers.</summary>
|
||||
public async Task<IReadOnlyList<SyncEntry>> ListAsync(string server, CancellationToken cancellationToken)
|
||||
{
|
||||
var links = await _links.ListAsync(server, cancellationToken).ConfigureAwait(false);
|
||||
var locals = await LocalSequencesAsync(cancellationToken).ConfigureAwait(false);
|
||||
var transfers = await _links.ActiveTransfersAsync(cancellationToken).ConfigureAwait(false);
|
||||
var entries = new List<SyncEntry>(links.Count + locals.Count);
|
||||
foreach (var link in links)
|
||||
{
|
||||
var local = link.LocalId is { } id && locals.Remove(id, out var found) ? found : null;
|
||||
var transfer = (local is null ? null : transfers.GetValueOrDefault(local.Id)) ?? transfers.GetValueOrDefault(link.RemoteId);
|
||||
entries.Add(new SyncEntry(local, link, transfer is null ? SyncRules.Status(local, link) : SyncStatus.Transferring, transfer));
|
||||
}
|
||||
foreach (var local in locals.Values)
|
||||
{
|
||||
var transfer = transfers.GetValueOrDefault(local.Id);
|
||||
entries.Add(new SyncEntry(local, null, transfer is null ? SyncStatus.LocalOnly : SyncStatus.Transferring, transfer));
|
||||
}
|
||||
entries.Sort((a, b) => string.Compare(a.Title, b.Title, StringComparison.CurrentCultureIgnoreCase));
|
||||
return entries;
|
||||
}
|
||||
/// <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
|
||||
@@ -180,41 +171,73 @@ public sealed class SyncService
|
||||
|
||||
// ---------------- Settings ----------------
|
||||
|
||||
/// <summary>Settles a settings conflict as the user chose (BRIEF §12.7); a 409 means the server changed again meanwhile.</summary>
|
||||
public async Task ResolveAsync(ISyncRemote remote, Guid remoteId, SyncResolution resolution, CancellationToken cancellationToken)
|
||||
/// <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);
|
||||
var dto = await remote.GetSequenceAsync(remoteId, cancellationToken).ConfigureAwait(false);
|
||||
link = Observe(link, remote.Server, dto);
|
||||
if (resolution == SyncResolution.KeepMine)
|
||||
if (link is not { ConflictRemote: { } theirs, ConflictLocalSettings: { } seenLocal, ConflictRemoteSettings: { } seenRemote }
|
||||
|| local.SettingsVersion != seenLocal)
|
||||
{
|
||||
var updated = await remote.UpdateSequenceAsync(remoteId, SyncPayload.Of(local).ToRequest(dto.SettingsVersion), cancellationToken).ConfigureAwait(false);
|
||||
link = Agreed(Observe(link, remote.Server, updated), local.SettingsVersion, updated.SettingsVersion);
|
||||
changed = true;
|
||||
}
|
||||
else if (resolution == SyncResolution.KeepMine)
|
||||
{
|
||||
try
|
||||
{
|
||||
var updated = await remote.UpdateSequenceAsync(remoteId, SyncPayload.Of(local).ToRequest(seenRemote), cancellationToken).ConfigureAwait(false);
|
||||
link = Agreed(Observe(link, remote.Server, updated), local.SettingsVersion, updated.SettingsVersion);
|
||||
}
|
||||
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.Conflict)
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (resolution == SyncResolution.SaveBoth) await SaveCopyAsync(local, cancellationToken).ConfigureAwait(false);
|
||||
var manifest = await remote.GetManifestAsync(remoteId, cancellationToken).ConfigureAwait(false);
|
||||
var applied = await ApplyLocallyAsync(local, SyncPayload.Of(dto, manifest.SettingsJson), cancellationToken).ConfigureAwait(false);
|
||||
link = Agreed(link, applied.SettingsVersion, manifest.SettingsVersion);
|
||||
var dto = await remote.GetSequenceAsync(remoteId, cancellationToken).ConfigureAwait(false);
|
||||
if (dto.SettingsVersion != seenRemote)
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (resolution == SyncResolution.SaveBoth) saved = await SaveCopyAsync(local, cancellationToken).ConfigureAwait(false);
|
||||
var applied = await ApplyLocallyAsync(local, theirs, cancellationToken).ConfigureAwait(false);
|
||||
link = Agreed(Observe(link, remote.Server, dto), applied.SettingsVersion, seenRemote);
|
||||
}
|
||||
}
|
||||
if (!changed)
|
||||
{
|
||||
await _links.UpsertAsync(link with { SyncedAt = DateTimeOffset.UtcNow }, cancellationToken).ConfigureAwait(false);
|
||||
Log.Info(LogCategory, $"Conflict on {local.DisplayTitle} settled: {resolution}");
|
||||
}
|
||||
await _links.UpsertAsync(link with { SyncedAt = DateTimeOffset.UtcNow }, cancellationToken).ConfigureAwait(false);
|
||||
Log.Info(LogCategory, $"Conflict on {local.DisplayTitle} settled: {resolution}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
await StoreStatesAsync(remote.Server, cancellationToken).ConfigureAwait(false);
|
||||
if (changed)
|
||||
{
|
||||
await RefreshSequencesAsync(remote, [remoteId], CompareOnly, cancellationToken).ConfigureAwait(false);
|
||||
throw new SyncConflictChangedException(Loc.L("Errors.Sync.ChangedAgain"));
|
||||
}
|
||||
await StoreStatesAsync(remote.Server, null, cancellationToken).ConfigureAwait(false);
|
||||
Changed?.Invoke(remote.Server);
|
||||
return saved;
|
||||
}
|
||||
|
||||
/// <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, CancellationToken cancellationToken) =>
|
||||
RefreshSequencesAsync(remote, [remoteId], new SyncPolicy(AutoSyncSettings: true), cancellationToken);
|
||||
public Task SyncSettingsAsync(ISyncRemote remote, Guid remoteId, SyncPolicy policy, CancellationToken cancellationToken) =>
|
||||
RefreshSequencesAsync(remote, [remoteId], policy with { AutoSyncSettings = true }, cancellationToken);
|
||||
|
||||
// ---------------- Transfers ----------------
|
||||
|
||||
@@ -222,9 +245,16 @@ public sealed class SyncService
|
||||
public Task<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 one is already waiting or running: originals into
|
||||
/// <paramref name="archiveId"/> (ignored when the sequence already has a local copy), or proxies into the cache.
|
||||
/// Queues a download of a server sequence, unless the same one is already waiting or running: originals into
|
||||
/// <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) =>
|
||||
@@ -253,11 +283,34 @@ public sealed class SyncService
|
||||
/// <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)
|
||||
{
|
||||
var link = await _links.GetAsync(server, remoteId, cancellationToken).ConfigureAwait(false)
|
||||
?? new SyncLink { Server = server, RemoteId = remoteId, Title = local.DisplayTitle, RemoteUpdatedAt = DateTimeOffset.UtcNow };
|
||||
link = link with { LocalId = local.Id };
|
||||
await _links.UpsertAsync(link, cancellationToken).ConfigureAwait(false);
|
||||
return link;
|
||||
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
var link = await _links.GetAsync(server, remoteId, cancellationToken).ConfigureAwait(false)
|
||||
?? new SyncLink { Server = server, RemoteId = remoteId, Title = local.DisplayTitle, RemoteUpdatedAt = DateTimeOffset.UtcNow };
|
||||
if (link.LocalId != local.Id) link = Unlinked(link) with { LocalId = local.Id };
|
||||
await _links.UpsertAsync(link, cancellationToken).ConfigureAwait(false);
|
||||
return link;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <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>
|
||||
@@ -312,6 +365,25 @@ public sealed class SyncService
|
||||
}
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
@@ -328,87 +400,151 @@ public sealed class SyncService
|
||||
Changed?.Invoke(server);
|
||||
}
|
||||
|
||||
private async Task ReconcileSafelyAsync(ISyncRemote remote, SyncLink link, SequenceDto dto, Sequence? local, SyncPolicy policy, CancellationToken cancellationToken)
|
||||
/// <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
|
||||
{
|
||||
link = await ReconcileAsync(remote, link, dto, local, policy, cancellationToken).ConfigureAwait(false);
|
||||
dto = await remote.GetSequenceAsync(remoteId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound)
|
||||
{
|
||||
// Deleted between the listing and the manifest: the next refresh forgets it.
|
||||
if (link is not null) await ForgetAsync(link, cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
catch (Exception ex) when (IsIsolated(ex, cancellationToken))
|
||||
{
|
||||
Log.Warning(LogCategory, $"Sequence {remoteId} could not be compared", ex);
|
||||
if (link is not null) await _links.UpsertAsync(link with { Error = ex.Message }, cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
var local = await LocalOfAsync(link, locals, cancellationToken).ConfigureAwait(false);
|
||||
await ReconcileSafelyAsync(remote, Observe(link, remote.Server, dto), dto, local, locals, policy, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task ReconcileSafelyAsync(ISyncRemote remote, SyncLink link, SequenceDto dto, Sequence? local, Dictionary<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 (ex is IOException or UnauthorizedAccessException or InvalidDataException or LeaseUnavailableException)
|
||||
catch (Exception ex) when (IsIsolated(ex, cancellationToken))
|
||||
{
|
||||
// The local archive is offline or busy: compare again next time; the other sequences go on.
|
||||
// The archive is offline or busy, the server refused this sequence, or its project is unreadable: it is
|
||||
// compared again next time and the other sequences go on.
|
||||
Log.Warning(LogCategory, $"{dto.DisplayTitle} could not be synced", ex);
|
||||
link = link with { Error = ex.Message };
|
||||
}
|
||||
await _links.UpsertAsync(link, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Compares originals when frame counters moved, then settles the settings; returns the updated link.</summary>
|
||||
private async Task<SyncLink> ReconcileAsync(ISyncRemote remote, SyncLink link, SequenceDto dto, Sequence? local, SyncPolicy policy,
|
||||
/// <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);
|
||||
return (link.LocalId is null ? link : Unlinked(link), null);
|
||||
}
|
||||
SequenceManifest? manifest = null;
|
||||
if (link.DiffLocalFrames != local.FramesVersion || link.DiffRemoteFrames != link.RemoteFramesVersion)
|
||||
if (link.DiffLocalFrames != local.FramesVersion || link.DiffRemoteFrames != link.RemoteFramesVersion
|
||||
|| link.DiffLocalRenders != local.RenderedCount || link.DiffRemoteRenders != link.RenderCount)
|
||||
{
|
||||
manifest = await remote.GetManifestAsync(link.RemoteId, cancellationToken).ConfigureAwait(false);
|
||||
var frames = await SequenceFrames.ListAsync(_db, local.Id, cancellationToken).ConfigureAwait(false);
|
||||
// A frame flagged missing here counts as absent: downloading the originals restores it from the server.
|
||||
var (missingRemote, missingLocal) = SyncRules.CompareOriginals(
|
||||
[.. frames.Where(f => (f.Flags & FrameFlags.Missing) == 0).Select(f => f.Sha256)], [.. manifest.Frames.Select(f => f.Sha256)]);
|
||||
link = link with
|
||||
link = await CompareExportsAsync(link, local, manifest.Renders, cancellationToken).ConfigureAwait(false) with
|
||||
{
|
||||
DiffLocalFrames = local.FramesVersion,
|
||||
DiffRemoteFrames = manifest.FramesVersion,
|
||||
RemoteFramesVersion = manifest.FramesVersion,
|
||||
DiffLocalRenders = local.RenderedCount,
|
||||
DiffRemoteRenders = manifest.Renders.Count,
|
||||
MissingRemote = missingRemote,
|
||||
MissingLocal = missingLocal,
|
||||
};
|
||||
}
|
||||
link = await SettleSettingsAsync(remote, link, dto, local, manifest, policy, cancellationToken).ConfigureAwait(false);
|
||||
return link with { SyncedAt = DateTimeOffset.UtcNow };
|
||||
(link, local) = await SettleSettingsAsync(remote, link, dto, local, manifest, policy, cancellationToken).ConfigureAwait(false);
|
||||
return (link with { SyncedAt = DateTimeOffset.UtcNow }, local);
|
||||
}
|
||||
|
||||
private async Task<SyncLink> SettleSettingsAsync(ISyncRemote remote, SyncLink link, SequenceDto dto, Sequence local, SequenceManifest? manifest,
|
||||
SyncPolicy policy, CancellationToken cancellationToken)
|
||||
/// <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;
|
||||
if (!localChanged && !remoteChanged) return (link, local);
|
||||
if (localChanged && remoteChanged)
|
||||
{
|
||||
if (link.ConflictLocalSettings == local.SettingsVersion && link.ConflictRemoteSettings == link.RemoteSettingsVersion) return link;
|
||||
if (link.ConflictLocalSettings == local.SettingsVersion && link.ConflictRemoteSettings == link.RemoteSettingsVersion) return (link, local);
|
||||
manifest ??= await remote.GetManifestAsync(link.RemoteId, cancellationToken).ConfigureAwait(false);
|
||||
// The listing and the manifest disagree: the server changed during the comparison; settle it next time.
|
||||
if (manifest.SettingsVersion != dto.SettingsVersion) return (link, local);
|
||||
var mine = SyncPayload.Of(local);
|
||||
var theirs = SyncPayload.Of(dto, manifest.SettingsJson);
|
||||
if (mine.SameAs(theirs)) return Agreed(link, local.SettingsVersion, manifest.SettingsVersion);
|
||||
if (!SyncRules.SameSettings(mine.SettingsJson, theirs.SettingsJson))
|
||||
if (mine.SameAs(theirs)) return (Agreed(link, local.SettingsVersion, manifest.SettingsVersion), local);
|
||||
// Last writer wins only when one side changed; both changed differently is the user's choice (BRIEF §14.5).
|
||||
return (link with
|
||||
{
|
||||
return link with
|
||||
{
|
||||
ConflictLocalSettings = local.SettingsVersion,
|
||||
ConflictRemoteSettings = link.RemoteSettingsVersion,
|
||||
ConflictSettingsJson = SyncRules.NormalizeSettings(theirs.SettingsJson),
|
||||
};
|
||||
}
|
||||
// Only title, tags, rating or notes differ: merge them and give both sides the result.
|
||||
var merged = SyncRules.Merge(mine, theirs, local.UpdatedAt >= dto.UpdatedAt);
|
||||
var applied = merged.SameMetadata(mine) ? local : await ApplyLocallyAsync(local, merged, cancellationToken).ConfigureAwait(false);
|
||||
return await PushAsync(remote, link, applied, manifest.SettingsVersion, cancellationToken).ConfigureAwait(false);
|
||||
ConflictLocalSettings = local.SettingsVersion,
|
||||
ConflictRemoteSettings = manifest.SettingsVersion,
|
||||
ConflictRemote = theirs with { SettingsJson = SyncRules.NormalizeSettings(theirs.SettingsJson) },
|
||||
}, local);
|
||||
}
|
||||
if (!policy.AutoSyncSettings) return link;
|
||||
if (localChanged) return await PushAsync(remote, link, local, link.BaseRemoteSettings, cancellationToken).ConfigureAwait(false);
|
||||
if (!policy.AutoSyncSettings) return (link, local);
|
||||
if (localChanged)
|
||||
return (policy.CanEdit ? await PushAsync(remote, link, local, link.BaseRemoteSettings, cancellationToken).ConfigureAwait(false) : link, local);
|
||||
manifest ??= await remote.GetManifestAsync(link.RemoteId, cancellationToken).ConfigureAwait(false);
|
||||
if (manifest.SettingsVersion != dto.SettingsVersion) return (link, local);
|
||||
var pulled = await ApplyLocallyAsync(local, SyncPayload.Of(dto, manifest.SettingsJson), cancellationToken).ConfigureAwait(false);
|
||||
return Agreed(link, pulled.SettingsVersion, manifest.SettingsVersion);
|
||||
return (Agreed(link, pulled.SettingsVersion, manifest.SettingsVersion), pulled);
|
||||
}
|
||||
|
||||
/// <summary>Sends this PC's payload unless the server moved past <paramref name="expected"/>, which shows up as a conflict next.</summary>
|
||||
@@ -425,6 +561,62 @@ public sealed class SyncService
|
||||
}
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
@@ -441,18 +633,21 @@ public sealed class SyncService
|
||||
return await _db.Sequences.GetAsync(local.Id, cancellationToken).ConfigureAwait(false) ?? current;
|
||||
}
|
||||
|
||||
/// <summary>"Save both": this PC's project is kept as <c>.titano/project.local-<UTC time>.json</c> before the server's replaces it.</summary>
|
||||
private async Task SaveCopyAsync(Sequence local, CancellationToken cancellationToken)
|
||||
/// <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.</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 name = string.Create(CultureInfo.InvariantCulture, $"project.local-{DateTime.UtcNow:yyyyMMdd-HHmmss}.json");
|
||||
AtomicFile.WriteAllText(Path.Combine(folder.MetaDirectory, name), SyncRules.NormalizeSettings(local.SettingsJson));
|
||||
Log.Info(LogCategory, $"Settings of {local.DisplayTitle} kept as {name}");
|
||||
var path = Path.Combine(folder.MetaDirectory, SavedCopyName(DateTime.Now));
|
||||
AtomicFile.WriteAllText(path, SyncRules.NormalizeSettings(local.SettingsJson));
|
||||
Log.Info(LogCategory, $"Settings of {local.DisplayTitle} kept as {path}");
|
||||
return path;
|
||||
}
|
||||
|
||||
internal static string SavedCopyName(DateTime localTime) => string.Create(CultureInfo.InvariantCulture, $"project.this-pc-{localTime:yyyyMMdd-HHmmss}.json");
|
||||
|
||||
private async Task ForgetAsync(SyncLink link, CancellationToken cancellationToken)
|
||||
{
|
||||
await _links.DeleteAsync(link.Server, link.RemoteId, cancellationToken).ConfigureAwait(false);
|
||||
@@ -461,9 +656,9 @@ public sealed class SyncService
|
||||
}
|
||||
|
||||
/// <summary>Writes each local sequence's state for the Library and returns the table.</summary>
|
||||
private async Task<IReadOnlyList<SyncEntry>> StoreStatesAsync(string server, CancellationToken cancellationToken)
|
||||
private async Task<IReadOnlyList<SyncEntry>> StoreStatesAsync(string server, Dictionary<Guid, Sequence>? locals, CancellationToken cancellationToken)
|
||||
{
|
||||
var entries = await ListAsync(server, cancellationToken).ConfigureAwait(false);
|
||||
var entries = await EntriesAsync(server, locals, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var entry in entries)
|
||||
{
|
||||
if (entry.Local is { } local && SyncRules.ToSequenceState(entry.Status) is { } state && state != local.SyncState)
|
||||
@@ -472,6 +667,50 @@ public sealed class SyncService
|
||||
return entries;
|
||||
}
|
||||
|
||||
/// <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);
|
||||
@@ -498,8 +737,16 @@ public sealed class SyncService
|
||||
private async Task<Job> EnqueueAsync(JobEngine engine, JobKind kind, Guid target, string label, SyncJobParameters parameters, JobPriority priority,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var active = await _links.ActiveTransfersAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (active.TryGetValue(target, out var running) && running.Kind == kind) return running;
|
||||
var wanted = parameters.Kind(kind);
|
||||
var active = (await _links.ActiveTransfersAsync(cancellationToken).ConfigureAwait(false)).GetValueOrDefault(target) ?? [];
|
||||
foreach (var job in active)
|
||||
{
|
||||
var running = TransferKind(job);
|
||||
var outranked = running == SyncTransferKind.DownloadProxies && job.Priority < priority;
|
||||
if (running == wanted && !outranked) return job;
|
||||
if (outranked && wanted is SyncTransferKind.DownloadProxies or SyncTransferKind.DownloadOriginals)
|
||||
await engine.CancelAsync(job.Id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
return await engine.EnqueueAsync(kind, [target], label, JsonSerializer.Serialize(parameters, SyncJobJson.Default.SyncJobParameters), priority,
|
||||
cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
@@ -525,7 +772,7 @@ public sealed class SyncService
|
||||
RemoteSettingsVersion = remoteVersion,
|
||||
ConflictLocalSettings = null,
|
||||
ConflictRemoteSettings = null,
|
||||
ConflictSettingsJson = null,
|
||||
ConflictRemote = null,
|
||||
};
|
||||
|
||||
private static SyncLink Unlinked(SyncLink link) => link with
|
||||
@@ -535,10 +782,16 @@ public sealed class SyncService
|
||||
BaseRemoteSettings = null,
|
||||
DiffLocalFrames = null,
|
||||
DiffRemoteFrames = null,
|
||||
DiffLocalRenders = null,
|
||||
DiffRemoteRenders = null,
|
||||
MissingRemote = 0,
|
||||
MissingLocal = 0,
|
||||
ExportsToGet = 0,
|
||||
ExportsToGetBytes = 0,
|
||||
ExportsToSend = 0,
|
||||
ExportsToSendBytes = 0,
|
||||
ConflictLocalSettings = null,
|
||||
ConflictRemoteSettings = null,
|
||||
ConflictSettingsJson = null,
|
||||
ConflictRemote = null,
|
||||
};
|
||||
}
|
||||
@@ -19,15 +19,18 @@ namespace Titano.Data.Sync;
|
||||
/// creating the server sequence first and sending its settings when the upload made it. Downloads fetch originals the
|
||||
/// local copy lacks into the archive's staging folder (resuming with Range), require the manifest's SHA-256 and commit
|
||||
/// them through the archive ingest, which names them and writes the sidecar; the first original creates the local
|
||||
/// sequence, which then takes the server's settings. Proxy downloads fill the proxy cache. A resumed job skips what
|
||||
/// is already on the other side, so pausing or a crash loses at most the files in flight.
|
||||
/// sequence, which then takes the server's settings. Frames of the local copy not hashed yet are hashed first (so the
|
||||
/// server's copies of them are recognised), and originals flagged missing here are restored to their recorded place.
|
||||
/// Proxy downloads fill the proxy cache. Renders travel on request: this PC's to the server (hash-verified chunked
|
||||
/// upload) and the server's into the local copy's exports. A resumed job skips what is already on the other side, so
|
||||
/// pausing or a crash loses at most the files in flight.
|
||||
/// </summary>
|
||||
internal sealed class SyncTransfers(SyncService sync)
|
||||
{
|
||||
private const long SpaceReserve = 512L << 20;
|
||||
|
||||
/// <summary>Recomputes a sequence's state after a transfer without sending or taking settings on the user's behalf.</summary>
|
||||
private static readonly SyncPolicy CompareOnly = new(AutoSyncSettings: false);
|
||||
/// <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)
|
||||
{
|
||||
@@ -72,7 +75,7 @@ internal sealed class SyncTransfers(SyncService sync)
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
if (created) await sync.PushAllAsync(remote, target, ct).ConfigureAwait(false);
|
||||
await sync.RefreshSequencesAsync(remote, [target], CompareOnly, ct).ConfigureAwait(false);
|
||||
await sync.RecompareAsync(remote, target, ct).ConfigureAwait(false);
|
||||
if (skipped > 0) throw new InvalidDataException(Loc.Plural("Errors.Sync.Unreadable", skipped));
|
||||
}
|
||||
|
||||
@@ -89,10 +92,8 @@ internal sealed class SyncTransfers(SyncService sync)
|
||||
|
||||
var manifest = await remote.GetManifestAsync(remoteId, ct).ConfigureAwait(false);
|
||||
var captured = (await remote.ListFramesAsync(remoteId, ct).ConfigureAwait(false)).ToDictionary(f => f.Id, f => f.CapturedAt);
|
||||
IReadOnlySet<string> have = local is null
|
||||
? new HashSet<string>()
|
||||
: (await SequenceFrames.ListAsync(db, local.Id, ct).ConfigureAwait(false)).Select(f => f.Sha256).OfType<string>().ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var wanted = manifest.Frames.Where(f => !have.Contains(f.Sha256)).DistinctBy(f => f.Sha256.ToLowerInvariant()).ToList();
|
||||
var (have, restore) = local is null ? ([], []) : await LocalContentAsync(archive, local, ct).ConfigureAwait(false);
|
||||
var wanted = manifest.Frames.Where(f => !have.Contains(f.Sha256.ToLowerInvariant())).DistinctBy(f => f.Sha256.ToLowerInvariant()).ToList();
|
||||
EnsureSpace(paths.Root, wanted.Sum(f => f.Size));
|
||||
|
||||
var staging = Path.Combine(paths.StagingDirectory, "sync-" + remoteId.ToString("N"));
|
||||
@@ -114,16 +115,27 @@ internal sealed class SyncTransfers(SyncService sync)
|
||||
await progress.StepAsync().ConfigureAwait(false);
|
||||
}
|
||||
var sequenceId = local?.Id;
|
||||
var restored = 0;
|
||||
await Parallel.ForEachAsync(rest, Workers(sync.Options.Downloads, ct), async (frame, token) =>
|
||||
{
|
||||
await CommitAsync(remote, remoteId, archive.Id, sequenceId, frame, staging, captured, token).ConfigureAwait(false);
|
||||
if (restore.TryGetValue(frame.Sha256.ToLowerInvariant(), out var place))
|
||||
{
|
||||
await RestoreAsync(remote, frame, staging, place, token).ConfigureAwait(false);
|
||||
Interlocked.Increment(ref restored);
|
||||
}
|
||||
else
|
||||
{
|
||||
await CommitAsync(remote, remoteId, archive.Id, sequenceId, frame, staging, captured, token).ConfigureAwait(false);
|
||||
}
|
||||
await progress.StepAsync().ConfigureAwait(false);
|
||||
}).ConfigureAwait(false);
|
||||
TryDeleteDirectory(staging);
|
||||
// Restored originals are checked against their records, which clears their missing flag.
|
||||
if (restored > 0) await VerifyAsync(archive, local!.Id, ct).ConfigureAwait(false);
|
||||
|
||||
if (created) await sync.TakeAllAsync(remote, remoteId, ct).ConfigureAwait(false);
|
||||
await sync.RefreshSequencesAsync(remote, [remoteId], CompareOnly, ct).ConfigureAwait(false);
|
||||
if (sequenceId is { } downloaded && wanted.Count > 0)
|
||||
await sync.RecompareAsync(remote, remoteId, ct).ConfigureAwait(false);
|
||||
if (sequenceId is { } downloaded && wanted.Count > restored)
|
||||
{
|
||||
var label = local!.DisplayTitle;
|
||||
await EnqueueFollowUpAsync(ArchiveJobs.Thumbnails([downloaded], label), ct).ConfigureAwait(false);
|
||||
@@ -131,6 +143,161 @@ internal sealed class SyncTransfers(SyncService sync)
|
||||
}
|
||||
}
|
||||
|
||||
/// <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;
|
||||
@@ -141,6 +308,7 @@ internal sealed class SyncTransfers(SyncService sync)
|
||||
var folder = sync.Proxies.Folder(remote.Server, remoteId);
|
||||
Directory.CreateDirectory(folder);
|
||||
ProxyCache.Prune(folder, frames.Select(f => ProxyCache.FileName(f.Id)).ToHashSet(StringComparer.Ordinal));
|
||||
EnsureSpace(folder, frames.Count(f => !File.Exists(Path.Combine(folder, ProxyCache.FileName(f.Id)))) * ProxyEstimate);
|
||||
|
||||
var files = new string?[frames.Count];
|
||||
var progress = new TransferProgress(context, frames.Count, 0);
|
||||
@@ -176,7 +344,7 @@ internal sealed class SyncTransfers(SyncService sync)
|
||||
return (id, id == started);
|
||||
}
|
||||
// Deleted on the server meanwhile: the originals go into a new sequence.
|
||||
if (id == link?.RemoteId) await sync.Links.DeleteAsync(remote.Server, id, ct).ConfigureAwait(false);
|
||||
if (id == link?.RemoteId) await sync.ForgetGoneAsync(remote.Server, id, ct).ConfigureAwait(false);
|
||||
}
|
||||
return (null, true);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user