fix(copies): close the eighth verification round of owner review 6

- A merge's Renders stage never deletes what sits at a journaled render
  target: a file or folder it did not copy there (a render of the kept
  sequence made after a failed run), or a path another render of the kept
  sequence names, makes the copy take a new free name instead.
- A merge's Verify stage records the hash it read for each kept frame the
  index had none for, the Details stage leaves the versions the verify filed
  out of Main, and Two versions also lists a whole-second instant holding two
  frames of one size and other content (owner Q3).
- The Integrate journal keeps the losers the plan listed as last copies; a
  loser that became the only copy while the job ran is never trashed: the
  journal goes and the job fails as a stale plan.
- Download originals of a server sequence whose earlier download was
  unlinked or kept apart makes a new local sequence under a key of the job,
  instead of filling the old one, re-linking it and overwriting its details.
- An upload never links again from its checkpoint a server sequence the user
  kept apart since the attempt that made it.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 11:38:18 +01:00
1 parent 123ceba845
commit aad8ae46dd
11 files changed
+536 -36

No files matched your search

@@ -18,6 +18,9 @@ public readonly record struct VerifyPosition(int Sequence, int Frame);
/// </summary>
public readonly record struct VerifyProgress(long BytesDone, long BytesTotal, int Sequence, int Sequences, string Title, int Frame, int Frames);
/// <summary>A frame's file hashed by another job: its SHA-256 and the stamp the file had before it was read.</summary>
internal readonly record struct HashedFile(Guid FrameId, string Sha256, FileStamp Stamp);
/// <summary>Outcome of one verify run (frames before a resume point are counted by the run that checked them).</summary>
public sealed record VerifyReport(int Sequences, long Checked, long Ok, long Hashed, IReadOnlyList<VerifyProblem> Problems);
@@ -195,6 +198,43 @@ public sealed class ArchiveVerifier
}
}
/// <summary>
/// Records first hashes another job read (a merge's verify stage, owner review 6): each frame of <paramref name="target"/>
/// the index has no hash for, whose sidecar has none (or this one) and whose file still has the stamp it was hashed at,
/// gets that hash in the sidecar and the index, under one lease, as a verify gives an adopted frame its first hash; flags
/// stay as they are. Returns how many.
/// </summary>
internal async Task<int> RecordHashesAsync(Archive archive, ArchivePaths paths, Sequence target, IReadOnlyList<HashedFile> hashes,
CancellationToken cancellationToken)
{
if (hashes.Count == 0) return 0;
await using (await _writer.LockAsync(paths, target.Id, cancellationToken).ConfigureAwait(false))
{
var sequence = await SequenceWriter.FolderAsync(_db, paths, target, cancellationToken).ConfigureAwait(false);
var manifest = SequenceWriter.ReadLocked(sequence, target.Id);
var current = manifest.Frames.ToDictionary(f => f.Id);
// The sidecar may hold the hash already (another index wrote it): only that one is recorded, never another.
var found = hashes.Where(h => current.TryGetValue(h.FrameId, out var now)
&& (string.IsNullOrEmpty(now.Sha256) || string.Equals(now.Sha256, h.Sha256, StringComparison.OrdinalIgnoreCase))
&& FileStamp.Of(sequence.File(now.File)) == h.Stamp).DistinctBy(h => h.FrameId).ToList();
if (found.Count == 0) return 0;
var inStep = await _indexer.InStepAsync(archive, sequence, manifest, cancellationToken).ConfigureAwait(false);
var changes = found.ToDictionary(h => h.FrameId, h => (Func<SidecarFrame, SidecarFrame>)(f => f with { Sha256 = h.Sha256.ToLowerInvariant() }));
ManifestStore.WriteSequence(sequence.ManifestPath, SequenceFrames.Update(manifest, changes));
await using (var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false))
{
if (await tx.Sequences.GetForUpdateAsync(target.Id, cancellationToken).ConfigureAwait(false) is not null)
{
await tx.Frames.UpdateIntegrityAsync(found.ConvertAll(h => new FrameIntegrity(h.FrameId, current[h.FrameId].Flags, h.Sha256)), cancellationToken)
.ConfigureAwait(false);
}
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
}
if (inStep) await _indexer.RecordStampsAsync(archive, sequence, target.Id, cancellationToken).ConfigureAwait(false);
return found.Count;
}
}
/// <summary>A frame's check with the stamp its file had before it was read (null: no file).</summary>
private readonly record struct PendingCheck(FrameCheck Check, FileStamp? File);
}
@@ -450,16 +450,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
if (inside && (File.Exists(source) || Directory.Exists(source)))
{
// Inside the folder that goes to the trash: copied (verified) into the kept sequence's exports first.
if (!journal.RenderTargets.TryGetValue(step.RenderId, out var target))
{
target = keepPaths.ToRelative(Free(keepPaths.Sequence(keep.Folder).Exports, Path.GetFileName(source)));
journal.RenderTargets[step.RenderId] = target;
Save();
}
var destination = keepPaths.FromRelative(target);
if (Directory.Exists(source)) await CopyFolderAsync(source, destination).ConfigureAwait(false);
else await CopyRenderAsync(source, destination, render.Sha256, step.FileName).ConfigureAwait(false);
output = target;
output = await CopyInAsync(step, render, source, keep).ConfigureAwait(false);
}
else
{
@@ -482,43 +473,94 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
}
}
/// <summary>
/// Copies the render <paramref name="source"/> (a file or an image-sequence folder) into the kept sequence's exports
/// under the name journaled for it, and returns that archive-relative path. Nothing this job did not copy is ever
/// overwritten or deleted: when the journaled name holds something else by now (a render of the kept sequence made
/// after a failed run freed the name) or another render of the kept sequence names it, the copy takes a new free name,
/// journaled before it is made.
/// </summary>
private async Task<string> CopyInAsync(RenderStep step, Render render, string source, Sequence keep)
{
var exports = keepPaths.Sequence(keep.Folder).Exports;
var taken = (await _db.Renders.ListBySequenceAsync(journal.KeepId, _ct).ConfigureAwait(false))
.Where(r => r.Id != step.RenderId).Select(r => Path.GetFullPath(SyncService.RenderFile(keepArchive, r)))
.ToHashSet(StringComparer.OrdinalIgnoreCase);
var folder = Directory.Exists(source);
if (!journal.RenderTargets.TryGetValue(step.RenderId, out var target)
|| taken.Contains(Path.GetFullPath(keepPaths.FromRelative(target)))
|| !await OursAsync(source, keepPaths.FromRelative(target), render.Sha256, folder).ConfigureAwait(false))
{
target = keepPaths.ToRelative(Free(exports, Path.GetFileName(source), taken));
journal.RenderTargets[step.RenderId] = target;
Save();
}
var destination = keepPaths.FromRelative(target);
if (folder) await CopyFolderAsync(source, destination).ConfigureAwait(false);
else await CopyRenderAsync(source, destination, render.Sha256, step.FileName).ConfigureAwait(false);
return target;
}
/// <summary>
/// Whether <paramref name="destination"/> holds nothing, or only what this job copies there: the render itself (by its
/// recorded SHA-256, else by the source's content) or, for a folder, files that each are the source's file of that name.
/// VerifiedCopy never leaves a partial file, so a run that stopped midway left whole files or none.
/// </summary>
private async Task<bool> OursAsync(string source, string destination, string? sha, bool folder)
{
if (!File.Exists(destination) && !Directory.Exists(destination)) return true;
if (!folder)
{
if (!File.Exists(destination)) return false;
var held = await ContentHash.Sha256Async(destination, null, _ct).ConfigureAwait(false);
var expected = sha is { Length: > 0 } ? sha : await ContentHash.Sha256Async(source, null, _ct).ConfigureAwait(false);
return string.Equals(held, expected, StringComparison.OrdinalIgnoreCase);
}
if (!Directory.Exists(destination)) return false;
foreach (var file in Directory.EnumerateFiles(destination, "*", SearchOption.AllDirectories))
{
var original = Path.Combine(source, Path.GetRelativePath(destination, file));
if (!File.Exists(original) || new FileInfo(original).Length != new FileInfo(file).Length
|| !string.Equals(await ContentHash.Sha256Async(file, null, _ct).ConfigureAwait(false),
await ContentHash.Sha256Async(original, null, _ct).ConfigureAwait(false), StringComparison.Ordinal))
return false;
}
return true;
}
/// <summary>Copies a render file to <paramref name="destination"/> (<see cref="OursAsync"/> said what is there is this copy).</summary>
private async Task CopyRenderAsync(string source, string destination, string? sha, string name)
{
if (File.Exists(destination))
{
// A run that copied it before its row moved: kept when it is the same file.
if (sha is { Length: > 0 } && string.Equals(await ContentHash.Sha256Async(destination, null, _ct).ConfigureAwait(false), sha, StringComparison.OrdinalIgnoreCase))
return;
File.Delete(destination);
}
// A run that copied it before its row moved: the same file, kept.
if (File.Exists(destination)) return;
var copied = await VerifiedCopy.CopyAsync(source, destination, verify: true, null, _ct).ConfigureAwait(false);
if (sha is { Length: > 0 } && !string.Equals(copied, sha, StringComparison.OrdinalIgnoreCase))
{
// This job's own copy, of a render that changed since it was recorded.
File.Delete(destination);
throw new InvalidOperationException(Loc.L("Errors.Copies.ChangedFile", name));
}
}
/// <summary>Copies the files of a render folder that <paramref name="destination"/> lacks (<see cref="OursAsync"/> checked the others).</summary>
private async Task CopyFolderAsync(string source, string destination)
{
foreach (var file in Directory.EnumerateFiles(source, "*", SearchOption.AllDirectories))
{
var target = Path.Combine(destination, Path.GetRelativePath(source, file));
if (File.Exists(target) && new FileInfo(target).Length == new FileInfo(file).Length
&& string.Equals(await ContentHash.Sha256Async(target, null, _ct).ConfigureAwait(false),
await ContentHash.Sha256Async(file, null, _ct).ConfigureAwait(false), StringComparison.Ordinal))
continue;
if (File.Exists(target)) File.Delete(target);
if (File.Exists(target)) continue;
await VerifiedCopy.CopyAsync(file, target, verify: true, null, _ct).ConfigureAwait(false);
}
}
private static string Free(string folder, string name)
/// <summary>A name in <paramref name="folder"/> that nothing on disk and no render of <paramref name="taken"/> uses.</summary>
private static string Free(string folder, string name, IReadOnlySet<string> taken)
{
var stem = Path.GetFileNameWithoutExtension(name);
var extension = Path.GetExtension(name);
var candidate = Path.Combine(folder, name);
for (var n = 2; File.Exists(candidate) || Directory.Exists(candidate); n++) candidate = Path.Combine(folder, $"{stem} ({n}){extension}");
for (var n = 2; File.Exists(candidate) || Directory.Exists(candidate) || taken.Contains(Path.GetFullPath(candidate)); n++)
candidate = Path.Combine(folder, $"{stem} ({n}){extension}");
return candidate;
}
@@ -537,14 +579,22 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
var total = keepFrames.Count + dropFrames.Count + flagged.Count;
var done = 0;
// What the kept sequence holds now, hashed again.
// What the kept sequence holds now, hashed again. A frame the index had no hash for gets this one (owner Q3): a
// photo the merge keeps in two versions is listed under Two versions only once both are hashed.
var held = new Dictionary<string, Guid>(StringComparer.Ordinal);
var first = new List<HashedFile>();
foreach (var frame in keepFrames.Where(f => (f.Flags & CopySides.UnusableFlags) == 0))
{
_ct.ThrowIfCancellationRequested();
await context.ReportAsync(Done(), Total, new JobDetail(JobStep.Verify, frame.FileName, ++done, total)).ConfigureAwait(false);
if (await HashAsync(keepPaths.FromRelative(frame.RelativePath)).ConfigureAwait(false) is { } sha) held.TryAdd(sha, frame.Id);
var path = keepPaths.FromRelative(frame.RelativePath);
var stamp = frame.Sha256 is { Length: > 0 } ? null : FileStamp.Of(path);
if (await HashAsync(path).ConfigureAwait(false) is not { } sha) continue;
held.TryAdd(sha, frame.Id);
if (stamp is { } read) first.Add(new HashedFile(frame.Id, sha, read));
}
if (first.Count > 0 && await _db.Sequences.GetAsync(journal.KeepId, _ct).ConfigureAwait(false) is { } keepRow)
await owner.Archives.Verifier.RecordHashesAsync(keepArchive, keepPaths, keepRow, first, _ct).ConfigureAwait(false);
var keepRemoved = (await _db.FrameRemovals.ListBySequenceAsync(journal.KeepId, _ct).ConfigureAwait(false))
.Select(r => r.Sha256.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
@@ -786,11 +836,13 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
private async Task DetailsAsync()
{
if (journal.Payload is null || journal.DetailsDone) return;
if (journal.DetailsDone) return;
var payload = await PayloadAsync().ConfigureAwait(false);
if (payload is not { } write) return;
await context.ReportAsync(Done(), Total, new JobDetail(JobStep.Details)).ConfigureAwait(false);
try
{
await new SequencePayloadWriter(_db, owner.Archives).ApplyAsync(journal.KeepId, journal.Payload, journal.KeepSettingsVersion, _ct).ConfigureAwait(false);
await new SequencePayloadWriter(_db, owner.Archives).ApplyAsync(journal.KeepId, write.Payload, write.SettingsVersion, _ct).ConfigureAwait(false);
}
catch (SyncConflictChangedException)
{
@@ -803,6 +855,43 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
Save();
}
/// <summary>
/// What the Details stage writes, and at which settings version of the kept sequence: the plan's payload (at the
/// version the plan read), with the second versions the verify filed (photos the plan compared by size and time only,
/// another photo after all) left out of Main as the plan leaves its own out (owner Q3). Without a planned payload,
/// the kept sequence's settings as they are now with those versions left out, at the version read with them. Null
/// when nothing is written.
/// </summary>
private async Task<(SyncPayload Payload, int SettingsVersion)?> PayloadAsync()
{
var versions = journal.SecondVersions.Select(id => journal.Verified.GetValueOrDefault(id)?.Sha256).OfType<string>()
.Select(s => s.ToLowerInvariant()).Distinct(StringComparer.Ordinal).ToList();
var planned = journal.Payload is { } p ? (p, journal.KeepSettingsVersion) : ((SyncPayload, int)?)null;
if (versions.Count == 0) return planned;
SyncPayload basis;
int version;
if (planned is { } known)
{
(basis, version) = known;
}
else
{
var keep = await _db.Sequences.GetAsync(journal.KeepId, _ct).ConfigureAwait(false) ?? throw new StaleCopyPlanException();
basis = CopyPayload.Portable(SyncPayload.Of(keep), await SequencePayloadWriter.PhotosAsync(_db, journal.KeepId, null, _ct).ConfigureAwait(false));
version = keep.SettingsVersion;
}
try
{
var excluded = CopyPayload.ExcludeVersions(basis, versions);
return planned is null && excluded.SameAs(basis) ? null : (excluded, version);
}
catch (Exception ex) when (ex is System.Text.Json.JsonException or InvalidDataException)
{
// Settings that are not a project of this Chronos: the versions stay included, as the plan leaves its own.
return planned;
}
}
// ---- projects ----
private async Task ProjectsAsync()
+5 -2
View File
@@ -67,7 +67,8 @@ public sealed class CopySides(ChronosDatabase db)
/// <summary>
/// The photos one sequence keeps in two versions (owner Q3, design §4.1 Versions): a sub-second capture instant holding
/// exactly two usable, hashed frames of different content, as a Union merge or Integrate leaves them. Read from the
/// exactly two usable, hashed frames of different content, as a Union merge or Integrate leaves them, or a whole second
/// holding two such frames of the same size (matched by size and time, another photo after all). Read from the
/// frames themselves, so they stay listed after the pair that made them is gone; each pair once, in index order.
/// </summary>
public async Task<IReadOnlyList<PhotoVersions>> VersionsAsync(Guid sequenceId, CancellationToken ct)
@@ -78,9 +79,11 @@ public sealed class CopySides(ChronosDatabase db)
foreach (var group in frames.Where(f => (f.Flags & UnusableFlags) == 0 && f.Sha256 is { Length: > 0 } && f.CapturedAt is not null)
.GroupBy(f => CopyComparer.Millisecond(f.CapturedAt!.Value)))
{
if (group.Key % 1000 == 0) continue;
var versions = group.DistinctBy(f => f.Sha256!.ToLowerInvariant(), StringComparer.Ordinal).OrderBy(f => f.Index).ToList();
if (versions.Count != 2 || group.Count() != 2) continue;
// A camera that records whole seconds takes several photos in one: two at a whole second are two versions only
// when they also share the size, as the comparison matched them (an uncompressed RAW series, say).
if (group.Key % 1000 == 0 && versions[0].Size != versions[1].Size) continue;
result.Add(new PhotoVersions(versions[0].Id, versions[0].FileName, versions[0].Sha256!.ToLowerInvariant(),
versions[1].Id, versions[1].FileName, versions[1].Sha256!.ToLowerInvariant())
{
@@ -192,6 +192,8 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
: p.Action == PhotoAction.TrashThere && sent.GetValueOrDefault(p.Key) is { Length: > 0 }))
.Select(p => new IntegrateTrash(p.Key, p.Action == PhotoAction.TrashHere ? CopySide.ThisPc : CopySide.Other, p.FrameId!.Value, p.FileName,
(p.Action == PhotoAction.TrashHere ? fetched[p.Key] : sent[p.Key])!))],
LastHere = [.. plan.LastCopies.Where(l => l.Side == CopySide.ThisPc).Select(l => l.Key.ToLowerInvariant())],
LastThere = [.. plan.LastCopies.Where(l => l.Side == CopySide.Other).Select(l => l.Key.ToLowerInvariant())],
Payload = plan.Payload,
LocalPayload = plan.LocalPayload,
RemotePayload = plan.RemotePayload,
@@ -347,6 +349,9 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
Keep(step, Loc.L("Archive.Log.KeptReason.NotInPlace"));
return;
}
// Held by another copy when planned, by nothing now (that sequence deleted or flagged while the photos moved): a
// last copy the plan did not list. It stays; the journal goes and a retry plans again against both sides as they are.
if (!await LoserHeldHereAsync(loser).ConfigureAwait(false)) Stale();
try
{
var local = await _db.Sequences.GetAsync(journal.LocalId, _ct).ConfigureAwait(false) ?? throw new StaleCopyPlanException();
@@ -391,6 +396,8 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
Keep(step, Loc.L("Archive.Log.KeptReason.NotInPlaceServer"));
return;
}
// As on this PC: a loser the plan counted as held elsewhere that nothing holds now is never trashed unlisted.
if (!await LoserHeldThereAsync(manifest, step.FrameId).ConfigureAwait(false)) Stale();
try
{
// At the frames version of the manifest that showed the winner in place: a server sequence changed since (the
@@ -419,6 +426,47 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
context.Log(Loc.L("Archive.Log.CopyKept", step.FileName, why));
}
/// <summary>
/// Whether this PC's losing version <paramref name="loser"/> may go to the trash, asked as the plan asked it but now: a
/// last copy the plan listed, or held by another usable frame of the local copy, by another sequence of this index, or
/// by the server sequence (a fresh manifest). An unhashed loser was never compared by content and is not asked.
/// </summary>
private async Task<bool> LoserHeldHereAsync(Frame loser)
{
if (loser.Sha256 is not { Length: > 0 } recorded) return true;
var sha = recorded.ToLowerInvariant();
if (journal.LastHere.Contains(sha)) return true;
foreach (var frame in await _db.Frames.FindBySha256Async(sha, _ct).ConfigureAwait(false))
if (frame.SequenceId == journal.LocalId && frame.Id != loser.Id && (frame.Flags & CopySides.UnusableFlags) == 0) return true;
if ((await new CopySides(_db).HeldElsewhereAsync([sha], [journal.LocalId], _ct).ConfigureAwait(false)).Contains(sha)) return true;
SequenceManifest manifest;
try
{
manifest = await remote.GetManifestAsync(journal.RemoteId, _ct).ConfigureAwait(false);
}
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.NotFound)
{
throw await GoneAsync(ex).ConfigureAwait(false);
}
return manifest.Frames.Any(f => (f.Flags & (long)CopySides.UnusableFlags) == 0 && string.Equals(f.Sha256, sha, StringComparison.OrdinalIgnoreCase));
}
/// <summary>
/// Whether the server's losing version (frame <paramref name="loserId"/> of <paramref name="manifest"/>) may go to its
/// trash: a last copy the plan listed, or held by another usable frame of the server sequence or by a sequence of this
/// index now. An unhashed loser is not asked.
/// </summary>
private async Task<bool> LoserHeldThereAsync(SequenceManifest manifest, Guid loserId)
{
if (manifest.Frames.FirstOrDefault(f => f.Id == loserId) is not { Sha256.Length: > 0 } loser) return true;
var sha = loser.Sha256.ToLowerInvariant();
if (journal.LastThere.Contains(sha)) return true;
if (manifest.Frames.Any(f => f.Id != loserId && (f.Flags & (long)CopySides.UnusableFlags) == 0
&& string.Equals(f.Sha256, sha, StringComparison.OrdinalIgnoreCase)))
return true;
return (await new CopySides(_db).HeldElsewhereAsync([sha], [], _ct).ConfigureAwait(false)).Contains(sha);
}
/// <summary>Whether a usable frame of the local copy holds <paramref name="sha"/>, its file hashed again now.</summary>
private async Task<bool> WinnerHereAsync(string sha)
{
@@ -61,6 +61,15 @@ internal sealed class IntegrateJournal
public List<IntegrateTrash> Trash { get; set; } = [];
/// <summary>
/// Raw SHA-256 of this PC's losing versions the plan listed as last copies (the user confirmed them): any other goes to
/// the trash only while another copy still holds it (asked again at the trash, which the plan may not wait for).
/// </summary>
public List<string> LastHere { get; set; } = [];
/// <summary>Raw SHA-256 of the server's losing versions the plan listed as last copies; as <see cref="LastHere"/>.</summary>
public List<string> LastThere { get; set; } = [];
/// <summary>The one portable payload both sides get; null when the details stay as they are.</summary>
public SyncPayload? Payload { get; set; }
+32 -6
View File
@@ -538,8 +538,9 @@ internal sealed class SyncTransfers(SyncService sync)
if (local is null && wanted.Count > 0)
{
// The first original creates the local sequence (grouped by the server id); the others join it.
var key = await DownloadKeyAsync(context, remote, remoteId, archive.Id).ConfigureAwait(false);
var (staged, sha) = await FetchOriginalAsync(remote, wanted[0], staging, ct).ConfigureAwait(false);
var first = await CommitAsync(remoteId, archive.Id, null, wanted[0], staged, sha, captured, ct).ConfigureAwait(false);
var first = await CommitAsync(key, archive.Id, null, wanted[0], staged, sha, captured, ct).ConfigureAwait(false);
local = await db.Sequences.GetAsync(first.SequenceId, ct).ConfigureAwait(false)
?? throw new InvalidOperationException(Loc.L("Errors.Sync.LocalMissing"));
await sync.LinkAsync(remote.Server, remoteId, local, ct).ConfigureAwait(false);
@@ -574,7 +575,7 @@ internal sealed class SyncTransfers(SyncService sync)
}
else
{
await CommitAsync(remoteId, archive.Id, sequenceId, frame, staged, sha, captured, token).ConfigureAwait(false);
await CommitAsync(null, archive.Id, sequenceId, frame, staged, sha, captured, token).ConfigureAwait(false);
}
await progress.StepAsync().ConfigureAwait(false);
}).ConfigureAwait(false);
@@ -942,7 +943,7 @@ internal sealed class SyncTransfers(SyncService sync)
/// <summary>
/// The server sequence an upload fills and whether this job creates it: the linked one, the one an interrupted
/// attempt created, or none yet (the first original creates it).
/// attempt created (unless the user kept it apart or unlinked it since), or none yet (the first original creates it).
/// </summary>
private async Task<(Guid? RemoteId, bool Created)> TargetAsync(JobContext context, ISyncRemote remote, Sequence local)
{
@@ -952,6 +953,10 @@ internal sealed class SyncTransfers(SyncService sync)
foreach (var candidate in new[] { link?.RemoteId, started })
{
if (candidate is not { } id) continue;
// The sequence an interrupted attempt created, unlinked or kept apart by the user since: never linked again from
// the checkpoint. The upload makes a new sequence (SessionKeyAsync), as one of a kept-apart sequence does.
if (id != link?.RemoteId && await sync.Copies.FindRemoteAsync(local.Id, remote.Server, id, ct).ConfigureAwait(false) is { State: CopyState.KeptApart })
continue;
if (await ExistsAsync(remote, id, ct).ConfigureAwait(false))
{
if (link?.RemoteId != id) await sync.LinkAsync(remote.Server, id, local, ct).ConfigureAwait(false);
@@ -978,6 +983,24 @@ internal sealed class SyncTransfers(SyncService sync)
return apart ? string.Create(CultureInfo.InvariantCulture, $"{own}:{context.Job.Id:N}") : own;
}
/// <summary>
/// The session key the first original of a download without a local copy goes under: the server sequence's own
/// (<see cref="SyncService.SessionKey"/>), which groups the download in the local sequence an earlier download of it made,
/// unless that sequence has been unlinked or kept apart from it, or linked to another sequence of this server since (it
/// has a pair or a link for this server). The user chose to keep such a sequence separate: the download makes a new
/// local sequence instead, under a key of this job (the same on a retry), and never fills or overwrites the other.
/// </summary>
private async Task<string> DownloadKeyAsync(JobContext context, ISyncRemote remote, Guid remoteId, Guid archiveId)
{
var ct = context.Cancellation;
var own = SyncService.SessionKey(remoteId);
if (await sync.Database.Sequences.FindBySessionKeyAsync(archiveId, own, ct).ConfigureAwait(false) is not { } holder) return own;
var apart = (await sync.Copies.ListByLocalAsync(holder, ct).ConfigureAwait(false))
.Any(c => c.Kind == CopyKind.LocalServer && string.Equals(c.Server, remote.Server, StringComparison.Ordinal) && c.LocalId == holder)
|| await sync.Links.FindByLocalAsync(remote.Server, holder, ct).ConfigureAwait(false) is not null;
return apart ? string.Create(CultureInfo.InvariantCulture, $"{own}:{context.Job.Id:N}") : own;
}
private static async Task<bool> ExistsAsync(ISyncRemote remote, Guid id, CancellationToken cancellationToken)
{
try
@@ -1060,11 +1083,14 @@ internal sealed class SyncTransfers(SyncService sync)
public bool Refuse() => Interlocked.Exchange(ref _refused, 1) == 0;
}
/// <summary>Commits one original from staging into the local sequence (created from the server id when null).</summary>
private async Task<IngestResult> CommitAsync(Guid remoteId, Guid archiveId, Guid? sequenceId, ManifestFrame frame, string staged, string sha,
/// <summary>
/// Commits one original from staging into the local sequence <paramref name="sequenceId"/>, or (when null) the one of
/// <paramref name="sessionKey"/>, created by the first original (<see cref="DownloadKeyAsync"/>).
/// </summary>
private async Task<IngestResult> CommitAsync(string? sessionKey, Guid archiveId, Guid? sequenceId, ManifestFrame frame, string staged, string sha,
IReadOnlyDictionary<Guid, DateTime?> captured, CancellationToken cancellationToken)
{
var request = new IngestRequest(archiveId, sequenceId, null, sequenceId is null ? SyncService.SessionKey(remoteId) : null, staged, frame.FileName,
var request = new IngestRequest(archiveId, sequenceId, null, sequenceId is null ? sessionKey : null, staged, frame.FileName,
frame.Size, sha, captured.GetValueOrDefault(frame.Id), null);
var result = await sync.Archives.Ingest.CommitAsync(request, cancellationToken).ConfigureAwait(false);
// A duplicate stays in staging (the sequence already holds that content).