fix(copies): close the owner review 6 verification findings
A merge could still trash photos it never verified, resume against a pair the user had answered meanwhile, and take different unhashed photos for copies; the dialog and the lists worded several facts wrongly or lost them on refresh. - Merge: a retry resumes only while the pair is still the job's; Verify requires the other archive online and its folder in place, stops on an unreadable photo, files a differing unhashed photo as a second version and must cover every frame before Trash; the plan hashes unmatched unhashed photos first, lists "Deleted in the other" and names the relinked servers; second versions stay discoverable (CopySides.VersionsAsync). - Integrate: a retry after a failure before the journal runs again. - Sync: a sequence back after a 404 stays Linked while its link holds; a local cull no longer asks for attention. - Block lines of both planners name the right sequence, archive, server and space through one formatter. - Compare dialog: one Details row per setting with worded values, Projects headings, Choose focuses the kept-sequence radios, the photo selection reaches rows outside the viewport, the Replace confirmation lists the losers per side, plan lines read as queued. - Matches and Library: counts first and grouped, integrating shown as a share, local matches name the other archive, the Library keeps its match and "deleted on server" statuses across a refresh. Refs #73 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d10577b175
commit
b34b6b6fe0
41 files changed
+1046
-193
No files matched your search
@@ -45,6 +45,8 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
|
||||
private IWorkspaceGuard Workspace => workspace;
|
||||
|
||||
private SequenceMerger Merger => merger;
|
||||
|
||||
/// <summary>Called before each stage runs (tests: a crash, a change made between stages).</summary>
|
||||
internal Func<MergeStage, Task>? BeforeStage { get; set; }
|
||||
|
||||
@@ -58,7 +60,9 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
var keepPaths = new ArchivePaths(keepArchive.RootPath);
|
||||
try
|
||||
{
|
||||
var journal = MergeJournal.Read(keepPaths, job.Id) ?? await StartAsync(context, parameters, keepRow, keepPaths).ConfigureAwait(false);
|
||||
var journal = MergeJournal.Read(keepPaths, job.Id);
|
||||
if (journal is null) journal = await StartAsync(context, parameters, keepRow, keepPaths).ConfigureAwait(false);
|
||||
else await ResumeAsync(job, parameters, keepPaths, ct).ConfigureAwait(false);
|
||||
var staging = MergeJournal.StagingFor(keepPaths, job.Id);
|
||||
if (Directory.Exists(staging)) Directory.Delete(staging, recursive: true);
|
||||
await new Run(this, context, journal, keepArchive, keepPaths).RunAsync().ConfigureAwait(false);
|
||||
@@ -101,6 +105,28 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
await new FoundCopyStore(db).ReleaseAsync(parameters.CopyId, job.Id, null, keepJob: false, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A resumed run (a pause, a crash, or a retry after a failure) goes on only while the pair is still this job's: it reads
|
||||
/// Integrating with this job (a failure keeps both; a Keep apart, an Ask again or another merge since clears them), or
|
||||
/// it is gone with the other sequence (the trash stage ran before the journal said so). Otherwise the journal is stale:
|
||||
/// it and its staging go and nothing more is applied; the pair, no longer this job's, is left as it is.
|
||||
/// </summary>
|
||||
private async Task ResumeAsync(Job job, MergeJobParameters parameters, ArchivePaths keepPaths, CancellationToken ct)
|
||||
{
|
||||
var copy = await new FoundCopyStore(db).GetAsync(parameters.CopyId, ct).ConfigureAwait(false);
|
||||
if (copy is { State: CopyState.Integrating } && copy.JobId == job.Id) return;
|
||||
if (copy is null && await db.Sequences.GetAsync(parameters.DropId, ct).ConfigureAwait(false) is null) return;
|
||||
try
|
||||
{
|
||||
MergeJournal.Delete(keepPaths, job.Id);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("archive", $"The stale journal of merge {job.Id} was not removed", ex);
|
||||
}
|
||||
throw new StaleCopyPlanException();
|
||||
}
|
||||
|
||||
/// <summary>The first run: plans again, refuses a plan that moved or is blocked, and journals it.</summary>
|
||||
private async Task<MergeJournal> StartAsync(JobContext context, MergeJobParameters parameters, Sequence keepRow, ArchivePaths keepPaths)
|
||||
{
|
||||
@@ -196,6 +222,31 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
|
||||
private InvalidOperationException Changed(string title) => new(Loc.L("Errors.Copies.Changed", title));
|
||||
|
||||
/// <summary>Drops this run's journal and staging: what it planned no longer holds.</summary>
|
||||
private void ForgetJournal()
|
||||
{
|
||||
try
|
||||
{
|
||||
MergeJournal.Delete(keepPaths, journal.JobId);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("archive", $"The stale journal of merge {journal.JobId} was not removed", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The other sequence's files are where the index says, on a volume that answers: a verify or a trash never reads an
|
||||
/// absent drive or a moved folder as "nothing there to lose".
|
||||
/// </summary>
|
||||
private void EnsureDropReadable(Sequence drop)
|
||||
{
|
||||
if (ArchiveVolume.Probe(_dropPaths) != ArchiveAvailability.Online)
|
||||
throw new InvalidOperationException(Loc.L("Errors.Copies.ArchiveOffline", _dropTitle));
|
||||
if (drop.Folder.Length > 0 && !SequenceFolders.Holds(_dropPaths.Sequence(drop.Folder), drop.Id))
|
||||
throw new InvalidOperationException(Loc.L("Errors.Copies.FolderMoved", _dropTitle));
|
||||
}
|
||||
|
||||
private async Task EnsureDropUnchangedAsync(int expected)
|
||||
{
|
||||
var drop = await _db.Sequences.GetAsync(journal.DropId, _ct).ConfigureAwait(false);
|
||||
@@ -215,15 +266,19 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
await EnsureDropUnchangedAsync(journal.DropFramesVersion).ConfigureAwait(false);
|
||||
var frame = await _db.Frames.GetAsync(copy.DropFrameId, _ct).ConfigureAwait(false) ?? throw Changed(_dropTitle);
|
||||
await context.ReportAsync(Done(), Total, new JobDetail(JobStep.CopyPhoto, copy.FileName, n, journal.Copies.Count)).ConfigureAwait(false);
|
||||
var result = await FileAsync(frame, copy.Sha256).ConfigureAwait(false);
|
||||
var result = await FileAsync(frame, copy.Sha256, planned: copy.Sha256 is { Length: > 0 }).ConfigureAwait(false);
|
||||
journal.Committed[copy.DropFrameId] = result.FrameId;
|
||||
Save();
|
||||
context.Log(Loc.L("Archive.Log.MergeCopied", copy.FileName));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Copies a frame of the other into staging (hash-checked against <paramref name="expected"/>) and files it in the kept sequence.</summary>
|
||||
private async Task<IngestResult> FileAsync(Frame frame, string? expected)
|
||||
/// <summary>
|
||||
/// Copies a frame of the other into staging (hash-checked against <paramref name="expected"/>) and files it in the
|
||||
/// kept sequence. <paramref name="planned"/>: the plan knew the photo's content (else a tombstone of the kept sequence
|
||||
/// may refuse it although the plan listed no last copy: the plan is stale, never this job's to retry).
|
||||
/// </summary>
|
||||
private async Task<IngestResult> FileAsync(Frame frame, string? expected, bool planned)
|
||||
{
|
||||
Directory.CreateDirectory(_staging);
|
||||
var staged = Path.Combine(_staging, frame.Id.ToString("N") + Path.GetExtension(frame.FileName));
|
||||
@@ -251,9 +306,12 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
}
|
||||
catch (PhotoRemovedException)
|
||||
{
|
||||
// Deleted from the kept sequence since the plan: it would be a last copy the plan did not list.
|
||||
File.Delete(staged);
|
||||
throw Changed(_keepTitle);
|
||||
if (planned) throw Changed(_keepTitle); // deleted from the kept sequence since the plan: a last copy the plan did not list
|
||||
// A photo the plan could not compare by content (unhashed) that the kept sequence deleted: a last copy the
|
||||
// plan did not list. Retrying this journal would fail the same way: it goes, and the user plans again.
|
||||
ForgetJournal();
|
||||
throw new StaleCopyPlanException();
|
||||
}
|
||||
if (File.Exists(staged)) File.Delete(staged);
|
||||
return result;
|
||||
@@ -365,6 +423,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
{
|
||||
var drop = await _db.Sequences.GetAsync(journal.DropId, _ct).ConfigureAwait(false) ?? throw Changed(_dropTitle);
|
||||
if (drop.FramesVersion != journal.DropFramesVersion) throw Changed(_dropTitle);
|
||||
EnsureDropReadable(drop);
|
||||
var keepFrames = await ProcessingFrames.ListAsync(_db, journal.KeepId, _ct).ConfigureAwait(false);
|
||||
var dropFrames = (await ProcessingFrames.ListAsync(_db, journal.DropId, _ct).ConfigureAwait(false))
|
||||
.Where(f => (f.Flags & CopySides.UnusableFlags) == 0).ToList();
|
||||
@@ -380,18 +439,18 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
if (await HashAsync(keepPaths.FromRelative(frame.RelativePath)).ConfigureAwait(false) is { } sha) held.TryAdd(sha, frame.Id);
|
||||
}
|
||||
|
||||
var failed = new List<string>();
|
||||
var keepRemoved = (await _db.FrameRemovals.ListBySequenceAsync(journal.KeepId, _ct).ConfigureAwait(false))
|
||||
.Select(r => r.Sha256.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
|
||||
var failed = new List<(Guid FrameId, string Sha256)>();
|
||||
foreach (var frame in dropFrames)
|
||||
{
|
||||
_ct.ThrowIfCancellationRequested();
|
||||
await context.ReportAsync(Done(), Total, new JobDetail(JobStep.Verify, frame.FileName, ++done, total)).ConfigureAwait(false);
|
||||
if (journal.Verified.ContainsKey(frame.Id)) continue;
|
||||
var sha = await HashAsync(_dropPaths.FromRelative(frame.RelativePath)).ConfigureAwait(false);
|
||||
if (sha is null)
|
||||
{
|
||||
// Nothing on disk: nothing of it can be lost.
|
||||
continue;
|
||||
}
|
||||
if (journal.Verified.ContainsKey(frame.Id) || journal.Settled.Contains(frame.Id)) continue;
|
||||
// A usable frame (not flagged Missing) whose file is absent stops the merge (design §5d step 4): it is not
|
||||
// "nothing to lose" until a verify says so.
|
||||
var sha = await HashAsync(_dropPaths.FromRelative(frame.RelativePath)).ConfigureAwait(false)
|
||||
?? throw new InvalidOperationException(Loc.L("Errors.Copies.ChangedFile", frame.FileName));
|
||||
if (frame.Sha256 is { Length: > 0 } recorded && !string.Equals(recorded, sha, StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException(Loc.L("Errors.Copies.ChangedFile", frame.FileName));
|
||||
if (held.TryGetValue(sha, out var keepFrame))
|
||||
@@ -399,26 +458,33 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
journal.Verified[frame.Id] = new MergeVerified(sha, keepFrame);
|
||||
continue;
|
||||
}
|
||||
if (frame.Sha256 is not { Length: > 0 })
|
||||
if (journal.Absent.Contains(sha))
|
||||
{
|
||||
// A last copy the plan listed (or left out by the user's choice).
|
||||
journal.Settled.Add(frame.Id);
|
||||
continue;
|
||||
}
|
||||
if (frame.Sha256 is not { Length: > 0 } && !keepRemoved.Contains(sha))
|
||||
{
|
||||
// Compared by size and time only, and another photo after all: filed in the kept sequence as a second version.
|
||||
var filed = await FileAsync(frame, sha).ConfigureAwait(false);
|
||||
var filed = await FileAsync(frame, sha, planned: false).ConfigureAwait(false);
|
||||
journal.SecondVersions.Add(frame.Id);
|
||||
journal.Verified[frame.Id] = new MergeVerified(sha, filed.FrameId);
|
||||
held.TryAdd(sha, filed.FrameId);
|
||||
Save();
|
||||
continue;
|
||||
}
|
||||
if (journal.Absent.Contains(sha)) continue;
|
||||
failed.Add(sha);
|
||||
failed.Add((frame.Id, sha));
|
||||
}
|
||||
if (failed.Count > 0)
|
||||
{
|
||||
// A photo held by another sequence of the index is not lost with the other; any other is. The kept
|
||||
// sequence's index rows prove nothing: its files were hashed again above and did not hold it.
|
||||
var others = await new CopySides(_db).HeldElsewhereAsync(failed, [journal.DropId, journal.KeepId], _ct).ConfigureAwait(false);
|
||||
var lost = failed.Count(s => !others.Contains(s));
|
||||
var others = await new CopySides(_db).HeldElsewhereAsync([.. failed.Select(f => f.Sha256)], [journal.DropId, journal.KeepId], _ct)
|
||||
.ConfigureAwait(false);
|
||||
var lost = failed.Where(f => !others.Contains(f.Sha256)).Select(f => f.Sha256).Distinct(StringComparer.Ordinal).Count();
|
||||
if (lost > 0) throw new InvalidOperationException(Loc.Plural("Errors.Copies.VerifyFailed", lost));
|
||||
journal.Settled.AddRange(failed.Select(f => f.FrameId));
|
||||
}
|
||||
journal.VerifiedDropFramesVersion = drop.FramesVersion;
|
||||
Save();
|
||||
@@ -598,8 +664,16 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
}
|
||||
if (!journal.LinksMoved)
|
||||
{
|
||||
var moved = await new FoundCopyStore(_db).MoveToKeptAsync(journal.DropId, journal.KeepId, keepArchive.Id, journal.SessionKeys, journal.CopyId, _ct)
|
||||
.ConfigureAwait(false);
|
||||
MoveResult moved;
|
||||
try
|
||||
{
|
||||
moved = await new FoundCopyStore(_db).MoveToKeptAsync(journal.DropId, journal.KeepId, keepArchive.Id, journal.SessionKeys, journal.CopyId, _ct)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
catch (CopyLinkTakenException ex) when (ex.Server is { } key)
|
||||
{
|
||||
throw CopyLinkTakenException.BothLinked(key, owner.Merger.ServerName(key));
|
||||
}
|
||||
foreach (var key in moved.SkippedKeys) context.Log(key);
|
||||
journal.LinksMoved = true;
|
||||
Save();
|
||||
@@ -617,6 +691,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
throw new InvalidOperationException(Loc.L("Errors.Copies.Unsent", _dropTitle));
|
||||
var expected = journal.VerifiedDropFramesVersion ?? throw Changed(_dropTitle);
|
||||
if (drop.FramesVersion != expected) throw Changed(_dropTitle);
|
||||
EnsureDropReadable(drop);
|
||||
await using (await owner.Archives.Writer.LockAsync(keepPaths, journal.KeepId, _ct).ConfigureAwait(false))
|
||||
{
|
||||
await EnsureVerifiedHeldAsync().ConfigureAwait(false);
|
||||
@@ -636,9 +711,18 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
context.Log(Loc.L("Archive.Log.MergeTrashed", _dropTitle));
|
||||
}
|
||||
|
||||
/// <summary>Every photo the verify found in the kept sequence is still there and usable (read under its lease).</summary>
|
||||
/// <summary>
|
||||
/// Every usable photo of the other was verified (held by the kept sequence, or a last copy the plan listed, or held by
|
||||
/// a third sequence), and every photo the verify found in the kept sequence is still there and usable (read under its lease).
|
||||
/// </summary>
|
||||
private async Task EnsureVerifiedHeldAsync()
|
||||
{
|
||||
// Every usable photo of the other was verified in this journal: a verify cut short (an absent drive, a moved
|
||||
// folder) never lets the rest through unread.
|
||||
var dropFrames = await ProcessingFrames.ListAsync(_db, journal.DropId, _ct).ConfigureAwait(false);
|
||||
if (dropFrames.Any(f => (f.Flags & CopySides.UnusableFlags) == 0 && !journal.Verified.ContainsKey(f.Id) && !journal.Settled.Contains(f.Id)))
|
||||
throw Changed(_dropTitle);
|
||||
|
||||
var frames = await ProcessingFrames.ListAsync(_db, journal.KeepId, _ct).ConfigureAwait(false);
|
||||
var byId = frames.Where(f => (f.Flags & CopySides.UnusableFlags) == 0).ToDictionary(f => f.Id);
|
||||
var hashes = byId.Values.Select(f => f.Sha256).OfType<string>().Select(s => s.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
|
||||
|
||||
@@ -87,6 +87,9 @@ internal sealed class MergeJournal
|
||||
/// <summary>Drop frames the verify found to be another photo than keep's (unhashed, same size and time) and filed as a second version.</summary>
|
||||
public List<Guid> SecondVersions { get; set; } = [];
|
||||
|
||||
/// <summary>Drop frames the verify found nothing of to lose: last copies the plan listed, or photos a third sequence holds.</summary>
|
||||
public List<Guid> Settled { get; set; } = [];
|
||||
|
||||
/// <summary>The dropped sequence's frames version the verify read: the trash refuses another.</summary>
|
||||
public int? VerifiedDropFramesVersion { get; set; }
|
||||
|
||||
|
||||
@@ -32,8 +32,14 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
||||
private readonly CopySides _sides = sides ?? throw new ArgumentNullException(nameof(sides));
|
||||
private readonly DbAccess _access = new(db.Database);
|
||||
|
||||
/// <summary>The name a server key is shown by (default: the key): the links a merge moves and the server both are linked to.</summary>
|
||||
public Func<string, string?>? ServerNames { get; init; }
|
||||
|
||||
internal ChronosDatabase Db => _db;
|
||||
|
||||
/// <summary>The name <paramref name="key"/> is shown by.</summary>
|
||||
internal string ServerName(string key) => ServerNames?.Invoke(key) is { Length: > 0 } name ? name : key;
|
||||
|
||||
internal ArchiveService Archives => _archives;
|
||||
|
||||
/// <summary>The handler of <see cref="JobKind.MergeSequences"/> jobs; register it on the <see cref="JobEngine"/>.</summary>
|
||||
@@ -99,6 +105,13 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
||||
var here = await _sides.LocalAsync(keep, ct).ConfigureAwait(false);
|
||||
var there = await _sides.LocalAsync(drop, ct).ConfigureAwait(false);
|
||||
var comparison = CopyComparer.Compare(here, there);
|
||||
if (online && await HashOnlyThereAsync(comparison, there, dropPaths, ct).ConfigureAwait(false) is { } hashed)
|
||||
{
|
||||
// Compared by content now: a photo the kept sequence deleted reads Deleted here (a last copy when nothing else
|
||||
// holds it), never a copy the kept sequence's tombstone refuses.
|
||||
there = hashed;
|
||||
comparison = CopyComparer.Compare(here, there);
|
||||
}
|
||||
var steps = new List<PhotoStep>();
|
||||
var excluded = new List<string>();
|
||||
foreach (var photo in comparison.Photos)
|
||||
@@ -201,7 +214,8 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
||||
var links = await _access.ListAsync("SELECT server, local_id FROM sync_links WHERE local_id = $1 OR local_id = $2", [keep, drop],
|
||||
r => (Server: r.GetString(0), Local: r.GetGuid(1)), ct).ConfigureAwait(false);
|
||||
var moved = links.Where(l => l.Local == drop).Select(l => l.Server).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToList();
|
||||
if (links.GroupBy(l => l.Server, StringComparer.Ordinal).Any(g => g.Select(l => l.Local).Distinct().Count() > 1)) blocks.Add(CopyBlock.BothLinked);
|
||||
var bothLinked = links.GroupBy(l => l.Server, StringComparer.Ordinal).FirstOrDefault(g => g.Select(l => l.Local).Distinct().Count() > 1)?.Key;
|
||||
if (bothLinked is not null) blocks.Add(CopyBlock.BothLinked);
|
||||
|
||||
// The other goes to the trash.
|
||||
var trash = await _archives.Trash.PlanAsync([drop], null, ct, exceptJob).ConfigureAwait(false);
|
||||
@@ -220,7 +234,46 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
||||
projects, sessionKeys, skippedKeys));
|
||||
return new MergePlan(copyId, keep, drop, choices, steps, lastCopies, renders, payload, changes, projects, sessionKeys, skippedKeys, moved, trash,
|
||||
copyBytes, free ?? -1, [.. blocks.Distinct()], keepRow.FramesVersion, keepRow.SettingsVersion, dropRow.FramesVersion, dropRow.SettingsVersion,
|
||||
fingerprint);
|
||||
fingerprint)
|
||||
{
|
||||
LinkNames = [.. moved.Select(ServerName)],
|
||||
BothLinkedServer = bothLinked is null ? null : ServerName(bothLinked),
|
||||
DeletedInOther = comparison.Photos.Count(p => p.Class == PhotoClass.DeletedThere),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The other's unhashed photos only it holds, hashed now (in memory: a dry run writes nothing); null when there are none.
|
||||
/// Matched by size and time only they would be copied blindly, even a photo whose content the kept sequence deleted.
|
||||
/// </summary>
|
||||
private async Task<CopySideInput?> HashOnlyThereAsync(CopyComparisonResult comparison, CopySideInput there, ArchivePaths dropPaths, CancellationToken ct)
|
||||
{
|
||||
var keys = comparison.Photos.Where(p => p.Class == PhotoClass.OnlyThere && p.Key.StartsWith(CopyComparer.UnhashedPrefix, StringComparison.Ordinal))
|
||||
.Select(p => p.Key).ToHashSet(StringComparer.Ordinal);
|
||||
if (keys.Count == 0) return null;
|
||||
var photos = new List<CopyPhotoInput>(there.Photos.Count);
|
||||
var changed = false;
|
||||
foreach (var photo in there.Photos)
|
||||
{
|
||||
if (photo.Unusable || photo.Sha256 is { Length: > 0 } || !keys.Contains(CopyComparer.UnhashedKey(photo.Size, photo.CapturedAt, photo.FrameId))
|
||||
|| await _db.Frames.GetAsync(photo.FrameId, ct).ConfigureAwait(false) is not { } frame)
|
||||
{
|
||||
photos.Add(photo);
|
||||
continue;
|
||||
}
|
||||
try
|
||||
{
|
||||
var sha = await ContentHash.Sha256Async(dropPaths.FromRelative(frame.RelativePath), null, ct).ConfigureAwait(false);
|
||||
photos.Add(photo with { Sha256 = sha.ToLowerInvariant() });
|
||||
changed = true;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// Unreadable now: left as it is (the job's copy fails on it and says which file).
|
||||
photos.Add(photo);
|
||||
}
|
||||
}
|
||||
return changed ? there with { Photos = photos } : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -260,18 +313,26 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
||||
{
|
||||
var keep = await _db.Sequences.GetAsync(plan.KeepId, ct).ConfigureAwait(false);
|
||||
var drop = await _db.Sequences.GetAsync(plan.DropId, ct).ConfigureAwait(false);
|
||||
var (keepTitle, dropTitle) = (keep?.DisplayTitle ?? string.Empty, drop?.DisplayTitle ?? string.Empty);
|
||||
return plan.Blocks[0] switch
|
||||
return BlockText(plan, plan.Blocks[0], keep?.DisplayTitle ?? string.Empty, drop?.DisplayTitle ?? string.Empty);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sentence of <paramref name="block"/> of a merge plan, the one the dialog shows and the job fails with: the kept
|
||||
/// sequence for space, the other for where it lies and its trash, the server both are linked to by its name.
|
||||
/// </summary>
|
||||
public static string BlockText(MergePlan plan, CopyBlock block, string keepTitle, string dropTitle, int unchosen = 1)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
return block switch
|
||||
{
|
||||
CopyBlock.Busy => Loc.L("Errors.Copies.Busy"),
|
||||
CopyBlock.ArchiveOffline => Loc.L("Errors.Copies.ArchiveOffline", dropTitle),
|
||||
CopyBlock.FolderMoved => Loc.L("Errors.Copies.FolderMoved", dropTitle),
|
||||
CopyBlock.ArchiveOffline or CopyBlock.FolderMoved or CopyBlock.ChangedFile => Loc.L("Errors.Copies." + block, dropTitle),
|
||||
CopyBlock.NoSpace => Loc.L("Errors.Copies.NoSpace", keepTitle, Size(plan.CopyBytes + SpaceReserve)),
|
||||
CopyBlock.BothLinked => Loc.L("Errors.Copies.BothLinked", string.Empty),
|
||||
CopyBlock.BothLinked => Loc.L("Errors.Copies.BothLinked", plan.BothLinkedServer ?? string.Empty),
|
||||
CopyBlock.UnsentWorkspace => Loc.L("Errors.Copies.Unsent", dropTitle),
|
||||
CopyBlock.TrashBlocked => Loc.L("Errors.Copies.TrashBlocked", dropTitle,
|
||||
plan.Trash.Blocked.Select(b => Loc.L("Archive.Delete.Reason." + b.Reason)).FirstOrDefault() ?? string.Empty),
|
||||
CopyBlock.DetailsUnchosen => Loc.Plural("Errors.Copies.DetailsUnchosen", 1),
|
||||
CopyBlock.DetailsUnchosen => Loc.Plural("Errors.Copies.DetailsUnchosen", Math.Max(1, unchosen)),
|
||||
CopyBlock.KeptUnchosen => Loc.L("Errors.Copies.KeptUnchosen"),
|
||||
_ => Loc.L("Errors.Copies.StalePlan"),
|
||||
};
|
||||
|
||||
@@ -167,9 +167,13 @@ public sealed record FoundCopy
|
||||
/// <summary>Shown in Server › Matches: everything but the plain links every upload or download makes.</summary>
|
||||
public bool IsListed => Evidence != CopyEvidence.Link || State is not CopyState.Linked || RemoteGone || Score.DeletedThere > 0;
|
||||
|
||||
/// <summary>Draws the chip in warning colours, counts in the Server rail badge and gives the Library card its status.</summary>
|
||||
/// <summary>
|
||||
/// Draws the chip in warning colours, counts in the Server rail badge and gives the Library card its status. Photos
|
||||
/// deleted here do not: a local cull is the user's own act, and Compare › Photos › Deleted here offers the server's
|
||||
/// side of it.
|
||||
/// </summary>
|
||||
public bool NeedsAttention => State == CopyState.Candidate || (RemoteGone && State != CopyState.KeptApart)
|
||||
|| (State is CopyState.Integrated or CopyState.Linked && (Score.DeletedThere > 0 || Score.DeletedHere > 0));
|
||||
|| (State is CopyState.Integrated or CopyState.Linked && Score.DeletedThere > 0);
|
||||
|
||||
/// <summary>Whether <paramref name="sequenceId"/> is one of the pair's local sequences.</summary>
|
||||
public bool Names(Guid sequenceId) => LocalId == sequenceId || OtherId == sequenceId;
|
||||
|
||||
@@ -97,6 +97,15 @@ public sealed record MergePlan(Guid CopyId, Guid KeepId, Guid DropId, MergeChoic
|
||||
int KeepFramesVersion, int KeepSettingsVersion, int DropFramesVersion, int DropSettingsVersion, string Fingerprint)
|
||||
{
|
||||
public bool CanApply => Blocks.Count == 0;
|
||||
|
||||
/// <summary><see cref="Links"/> by the names their servers are shown by.</summary>
|
||||
public IReadOnlyList<string> LinkNames { get; init; } = [];
|
||||
|
||||
/// <summary>The name of the server both sequences are linked to (<see cref="CopyBlock.BothLinked"/>); null otherwise.</summary>
|
||||
public string? BothLinkedServer { get; init; }
|
||||
|
||||
/// <summary>Photos the kept sequence holds that the other deleted: they stay in the kept one ("Deleted in the other").</summary>
|
||||
public int DeletedInOther { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -189,6 +198,16 @@ public sealed class CopyLinkTakenException : InvalidOperationException
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>The server key both sequences of a merge are linked to (<see cref="BothLinked"/>); null otherwise.</summary>
|
||||
public string? Server { get; private init; }
|
||||
|
||||
/// <summary>The refusal for <paramref name="title"/> already linked to another sequence of <paramref name="server"/>.</summary>
|
||||
public static CopyLinkTakenException For(string title, string server) => new(Loc.L("Errors.Copies.LinkTaken", title, server));
|
||||
|
||||
/// <summary>
|
||||
/// The refusal of a merge whose two sequences are both linked to sequences of the server <paramref name="key"/>, worded
|
||||
/// with <paramref name="name"/> (the caller resolves the key to the name the server is shown by; the key by default).
|
||||
/// </summary>
|
||||
public static CopyLinkTakenException BothLinked(string key, string? name = null) =>
|
||||
new(Loc.L("Errors.Copies.BothLinked", name ?? key)) { Server = key };
|
||||
}
|
||||
@@ -5,6 +5,9 @@ using Chronos.Protocol;
|
||||
|
||||
namespace Chronos.Data.Copies;
|
||||
|
||||
/// <summary>One photo a sequence keeps in two versions: each version's frame, file name and SHA-256.</summary>
|
||||
public sealed record PhotoVersions(Guid FirstFrameId, string FirstFileName, string FirstSha256, Guid SecondFrameId, string SecondFileName, string SecondSha256);
|
||||
|
||||
/// <summary>
|
||||
/// The two sides of a comparison as <see cref="CopyComparer"/> reads them (owner review 6, #73; design §4.2): a local
|
||||
/// sequence's frames and tombstones, a server sequence's manifest with its frames' capture times, and the last-copy check
|
||||
@@ -48,6 +51,27 @@ public sealed class CopySides(ChronosDatabase db)
|
||||
manifest.Removed ?? []);
|
||||
}
|
||||
|
||||
/// <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
|
||||
/// 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)
|
||||
{
|
||||
var frames = await Processing.SequenceFrames.ListAsync(_db, sequenceId, ct).ConfigureAwait(false);
|
||||
var result = new List<PhotoVersions>();
|
||||
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;
|
||||
result.Add(new PhotoVersions(versions[0].Id, versions[0].FileName, versions[0].Sha256!.ToLowerInvariant(),
|
||||
versions[1].Id, versions[1].FileName, versions[1].Sha256!.ToLowerInvariant()));
|
||||
}
|
||||
return [.. result.OrderBy(v => frames.First(f => f.Id == v.FirstFrameId).Index)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The raw SHA-256 (lower-case) of <paramref name="sha256"/> that a usable frame (not Missing or Corrupt) of any sequence
|
||||
/// of this index other than <paramref name="except"/> holds: what is not the last copy of its photo. Batched.
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Runtime.CompilerServices;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Repositories;
|
||||
using Chronos.Data.Sync;
|
||||
@@ -349,7 +348,7 @@ public sealed class FoundCopyStore(ChronosDatabase db, TimeProvider? time = null
|
||||
var linked = await inner.ListAsync("SELECT server, local_id FROM sync_links WHERE local_id = $1 OR local_id = $2", [drop, keep],
|
||||
r => (Server: r.GetString(0), Local: r.GetGuid(1)), ct).ConfigureAwait(false);
|
||||
var both = linked.GroupBy(l => l.Server, StringComparer.Ordinal).FirstOrDefault(g => g.Select(l => l.Local).Distinct().Count() > 1);
|
||||
if (both is not null) throw new CopyLinkTakenException(Loc.L("Errors.Copies.BothLinked", both.Key));
|
||||
if (both is not null) throw CopyLinkTakenException.BothLinked(both.Key);
|
||||
|
||||
// (1) Session keys.
|
||||
var (keys, skipped) = (0, new List<string>());
|
||||
|
||||
@@ -158,7 +158,15 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
|
||||
{
|
||||
var ct = context.Cancellation;
|
||||
var copy = await copies.GetAsync(parameters.CopyId, ct).ConfigureAwait(false);
|
||||
if (copy is not { State: CopyState.Integrating } || copy.JobId != context.Job.Id) throw new StaleCopyPlanException();
|
||||
if (copy is null || copy.JobId != context.Job.Id) throw new StaleCopyPlanException();
|
||||
if (copy.State != CopyState.Integrating)
|
||||
{
|
||||
// A retry after a failure before the journal was written: the pair kept this job's id, nothing else touched it.
|
||||
if (!await copies.SetStateAsync(copy.Id, copy.State, CopyState.Integrating, new CopyAnswer(null, null, context.Job.Id, null, DateTimeOffset.UtcNow), ct)
|
||||
.ConfigureAwait(false))
|
||||
throw new StaleCopyPlanException();
|
||||
copy = await copies.GetAsync(parameters.CopyId, ct).ConfigureAwait(false) ?? throw new StaleCopyPlanException();
|
||||
}
|
||||
var planContext = (parameters.Context ?? IntegrateJobContext.Permissive).ToPlanContext();
|
||||
var plan = await planner.PlanAsync(remote, copy, parameters.Choices, planContext, context.Job.Id, ct).ConfigureAwait(false);
|
||||
if (!plan.CanApply) throw new InvalidOperationException(await planner.BlockMessageAsync(plan, remote, ct).ConfigureAwait(false));
|
||||
|
||||
@@ -219,9 +219,14 @@ public sealed class IntegratePlanner(SyncService sync, CopySides sides, ProjectS
|
||||
internal async Task<string> BlockMessageAsync(IntegratePlan plan, ISyncRemote remote, CancellationToken ct)
|
||||
{
|
||||
var local = await Db.Sequences.GetAsync(plan.LocalId, ct).ConfigureAwait(false);
|
||||
var title = local?.DisplayTitle ?? string.Empty;
|
||||
var server = plan.Context?.ServerName ?? remote.Server;
|
||||
return plan.Blocks[0] switch
|
||||
return BlockText(plan, plan.Blocks[0], local?.DisplayTitle ?? string.Empty, plan.Context?.ServerName ?? remote.Server);
|
||||
}
|
||||
|
||||
/// <summary>The sentence of <paramref name="block"/> of an Integrate plan, the one the dialog shows and the job fails with.</summary>
|
||||
public static string BlockText(IntegratePlan plan, CopyBlock block, string title, string server, int unchosen = 1)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
return block switch
|
||||
{
|
||||
CopyBlock.NeedsNewerServer => Loc.L("Errors.Copies.NeedsNewerServer", server),
|
||||
CopyBlock.NoUploadRight => Loc.L("Errors.Copies.NoUploadRight"),
|
||||
@@ -231,9 +236,9 @@ public sealed class IntegratePlanner(SyncService sync, CopySides sides, ProjectS
|
||||
CopyBlock.LinkTaken => Loc.L("Errors.Copies.LinkTaken", title, server),
|
||||
CopyBlock.NoSpace => Loc.L("Errors.Copies.NoSpace", title, Size(plan.FetchBytes + SpaceReserve)),
|
||||
CopyBlock.Busy => Loc.L("Errors.Copies.Busy"),
|
||||
CopyBlock.ArchiveOffline => Loc.L("Errors.Copies.ArchiveOffline", title),
|
||||
CopyBlock.FolderMoved => Loc.L("Errors.Copies.FolderMoved", title),
|
||||
CopyBlock.DetailsUnchosen => Loc.Plural("Errors.Copies.DetailsUnchosen", 1),
|
||||
CopyBlock.ArchiveOffline or CopyBlock.FolderMoved or CopyBlock.ChangedFile => Loc.L("Errors.Copies." + block, title),
|
||||
CopyBlock.UnsentWorkspace => Loc.L("Errors.Copies.Unsent", title),
|
||||
CopyBlock.DetailsUnchosen => Loc.Plural("Errors.Copies.DetailsUnchosen", Math.Max(1, unchosen)),
|
||||
_ => Loc.L("Errors.Copies.StalePlan"),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -770,7 +770,8 @@ public sealed class SyncService
|
||||
/// <summary>
|
||||
/// Pairs one 404 marked (design §6.3): a remote listed again is cleared at once and asked about again; one still unlisted
|
||||
/// is asked for once more, no sooner than <see cref="GoneRecheck"/> after it was marked, and a second 404 there makes the
|
||||
/// pair read "deleted on server". The links of those pairs are gone already (the first 404 forgot them).
|
||||
/// pair read "deleted on server". A refresh's first 404 forgot the link (the pair is asked about again); a job's 404
|
||||
/// kept it (the pair stays Linked or Integrated).
|
||||
/// </summary>
|
||||
private async Task AskGoneAgainAsync(ISyncRemote remote, IReadOnlyList<SequenceDto> listing, Guid refreshId, CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -804,9 +805,12 @@ public sealed class SyncService
|
||||
async Task BackAsync(FoundCopy pair, Guid remoteId)
|
||||
{
|
||||
await Copies.ClearRemoteGoneAsync(remote.Server, remoteId, cancellationToken).ConfigureAwait(false);
|
||||
// No link joins the two any more: the user is asked again.
|
||||
if (pair.State is CopyState.Linked or CopyState.Integrated)
|
||||
await Copies.SetStateAsync(pair.Id, pair.State, CopyState.Candidate, null, cancellationToken).ConfigureAwait(false);
|
||||
if (pair.State is not (CopyState.Linked or CopyState.Integrated)) return;
|
||||
// A 404 a job saw (a transfer, an Integrate) keeps the link: the pair stays as it was. A link the refresh's 404
|
||||
// forgot joins nothing any more: the user is asked again.
|
||||
var link = await _links.GetAsync(remote.Server, remoteId, cancellationToken).ConfigureAwait(false);
|
||||
if (link?.LocalId == pair.LocalId) return;
|
||||
await Copies.SetStateAsync(pair.Id, pair.State, CopyState.Candidate, null, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user