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
@@ -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