fix(copies): close the third verification round and add the match baselines
Integrate trashes a server photo only for the sequence's owner or an admin, a Details stage stops instead of overwriting a server change the user had kept this PC's value against, a merge retried after a stop plans again when work reached the other sequence, detection keeps pairs answered while it ran, and a sync row whose match the server deleted offers Keep here, Upload again and To trash. The Integrate and merge logs say in the UI language why a version was kept. The edit-picker-twins capture scene showed no Twin chip, since a capture has no workspace: it now lists sample workspace projects of the sample matches. The screenshot baselines gain the 38 Matches screens and take the Matches chip, the three Settings > Server rows, the longer priority list and 1.2.0. Refs #73 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3e6110d329
commit
3c99badcfe
96 files changed
+910
-147
No files matched your search
@@ -152,6 +152,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
Stage = MergeStage.Copy,
|
||||
KeepSettingsVersion = plan.KeepSettingsVersion,
|
||||
DropFramesVersion = plan.DropFramesVersion,
|
||||
DropSettingsVersion = plan.DropSettingsVersion,
|
||||
KeepStatus = (int)keepRow.Status,
|
||||
Copies = [.. plan.Photos.Where(p => p.Action is PhotoAction.Fetch or PhotoAction.FetchVersion && p.FrameId is not null)
|
||||
.Select(p => new MergeCopy(p.Key, p.Action, p.FrameId!.Value, p.FileName, p.Bytes, p.Sha256))],
|
||||
@@ -485,6 +486,9 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
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));
|
||||
// Held by a third sequence now: asked again before the trash, which that sequence may not wait for.
|
||||
foreach (var sha in failed.Select(f => f.Sha256).Distinct(StringComparer.Ordinal))
|
||||
if (!journal.SettledElsewhere.Contains(sha)) journal.SettledElsewhere.Add(sha);
|
||||
}
|
||||
journal.VerifiedDropFramesVersion = drop.FramesVersion;
|
||||
Save();
|
||||
@@ -522,7 +526,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
}
|
||||
if (!await WinnerInPlaceAsync(replace.WinnerSha256).ConfigureAwait(false))
|
||||
{
|
||||
Keep(replace, "the version that replaces it is not in place");
|
||||
Keep(replace, Loc.L("Archive.Log.KeptReason.NotInPlace"));
|
||||
continue;
|
||||
}
|
||||
try
|
||||
@@ -530,16 +534,17 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
var plan = await owner.Archives.FrameTrash.PlanDeleteAsync(journal.KeepId, [replace.KeepFrameId], null, _ct, journal.JobId).ConfigureAwait(false);
|
||||
if (!plan.CanDelete)
|
||||
{
|
||||
Keep(replace, string.Join(", ", plan.Blocked));
|
||||
Keep(replace, CopyLog.Reasons(plan.Blocked));
|
||||
continue;
|
||||
}
|
||||
await owner.Archives.FrameTrash.DeleteAsync(plan, null, null, _ct, journal.JobId).ConfigureAwait(false);
|
||||
journal.Replaced.Add(replace.Key);
|
||||
Save();
|
||||
context.Log(Loc.L("Archive.Log.CopyReplaced", replace.FileName));
|
||||
}
|
||||
catch (Exception ex) when (ex is StaleDeletePlanException or IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Keep(replace, ex.Message);
|
||||
Keep(replace, CopyLog.Reason(ex));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -548,7 +553,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
{
|
||||
journal.KeptLosers.Add(replace.Key);
|
||||
Save();
|
||||
context.Log($"{replace.FileName}: {why}");
|
||||
context.Log(Loc.L("Archive.Log.CopyKept", replace.FileName, why));
|
||||
}
|
||||
|
||||
/// <summary>Whether a usable frame of the kept sequence holds <paramref name="sha"/>, hashed again.</summary>
|
||||
@@ -608,11 +613,12 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
await RenamesRendersAsync(step.SourceProjectId, copied.Id).ConfigureAwait(false);
|
||||
journal.ProjectsDone.Add(step.SourceProjectId);
|
||||
Save();
|
||||
context.Log(Loc.L("Archive.Log.CopyProject", step.SourceName, step.TargetName));
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
failed++;
|
||||
context.Log($"{step.SourceName}: {ex.Message}");
|
||||
context.Log(Loc.L("Archive.Log.CopyProjectKept", step.SourceName, ex.Message));
|
||||
}
|
||||
}
|
||||
if (failed > 0) throw new InvalidOperationException(Loc.Plural("Errors.Copies.ProjectsKept", failed));
|
||||
@@ -689,6 +695,12 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
await context.ReportAsync(Done(), Total, new JobDetail(JobStep.Trash, _dropTitle)).ConfigureAwait(false);
|
||||
if (await owner.Workspace.HasUnsentAsync(journal.DropId, _ct).ConfigureAwait(false))
|
||||
throw new InvalidOperationException(Loc.L("Errors.Copies.Unsent", _dropTitle));
|
||||
if (await WorkSinceThePlanAsync(drop).ConfigureAwait(false))
|
||||
{
|
||||
// Work saved into the other since the plan (sent home, rendered) never reached the kept one: planned again.
|
||||
ForgetJournal();
|
||||
throw Changed(_dropTitle);
|
||||
}
|
||||
var expected = journal.VerifiedDropFramesVersion ?? throw Changed(_dropTitle);
|
||||
if (drop.FramesVersion != expected) throw Changed(_dropTitle);
|
||||
EnsureDropReadable(drop);
|
||||
@@ -711,9 +723,37 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
context.Log(Loc.L("Archive.Log.MergeTrashed", _dropTitle));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether the other holds work the plan did not see and nothing copied: details or Main settings saved since (its
|
||||
/// settings version moved), a project made or a version added since (missing from the plan, or another head than the
|
||||
/// one it copied), or a render the kept sequence does not hold.
|
||||
/// </summary>
|
||||
private async Task<bool> WorkSinceThePlanAsync(Sequence drop)
|
||||
{
|
||||
if (journal.DropSettingsVersion is { } settings && drop.SettingsVersion != settings) return true;
|
||||
var planned = journal.Projects.ToDictionary(p => p.SourceProjectId);
|
||||
HashSet<string>? keepHeads = null;
|
||||
foreach (var project in await _db.Projects.ListBySequenceAsync(journal.DropId, includeDeleted: false, _ct).ConfigureAwait(false))
|
||||
{
|
||||
if (project.IsMain) continue;
|
||||
if (planned.TryGetValue(project.Id, out var step) && (project.HeadVersionId ?? Guid.Empty) == step.SourceHeadId) continue;
|
||||
// Not planned (or moved on since) is fine only when the kept sequence holds that head already, as the plan saw it.
|
||||
keepHeads ??= await owner.Merger.HeadHashesAsync(
|
||||
await _db.Projects.ListBySequenceAsync(journal.KeepId, includeDeleted: false, _ct).ConfigureAwait(false), _ct).ConfigureAwait(false);
|
||||
if (!await owner.Merger.HeldAlreadyAsync(project, keepHeads, _ct).ConfigureAwait(false)) return true;
|
||||
}
|
||||
var renders = await _db.Renders.ListBySequenceAsync(journal.DropId, _ct).ConfigureAwait(false);
|
||||
if (renders.Count == 0) return false;
|
||||
// A render the plan left because the kept sequence holds the same file stays with the other, as planned.
|
||||
var keepHashes = (await _db.Renders.ListBySequenceAsync(journal.KeepId, _ct).ConfigureAwait(false)).Select(r => r.Sha256).OfType<string>()
|
||||
.ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
return renders.Any(r => !journal.RendersMoved.Contains(r.Id) && (r.Sha256 is null || !keepHashes.Contains(r.Sha256)));
|
||||
}
|
||||
|
||||
/// <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).
|
||||
/// a third sequence that still holds it now), and every photo the verify found in the kept sequence is still there and
|
||||
/// usable (read under its lease).
|
||||
/// </summary>
|
||||
private async Task EnsureVerifiedHeldAsync()
|
||||
{
|
||||
@@ -723,6 +763,18 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
if (dropFrames.Any(f => (f.Flags & CopySides.UnusableFlags) == 0 && !journal.Verified.ContainsKey(f.Id) && !journal.Settled.Contains(f.Id)))
|
||||
throw Changed(_dropTitle);
|
||||
|
||||
// The photos a third sequence held at the verify: one it no longer holds would leave only with the other, never
|
||||
// listed as a last copy. Planned again, the plan lists it.
|
||||
if (journal.SettledElsewhere.Count > 0)
|
||||
{
|
||||
var still = await new CopySides(_db).HeldElsewhereAsync(journal.SettledElsewhere, [journal.DropId, journal.KeepId], _ct).ConfigureAwait(false);
|
||||
if (journal.SettledElsewhere.Any(sha => !still.Contains(sha)))
|
||||
{
|
||||
ForgetJournal();
|
||||
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);
|
||||
|
||||
@@ -55,6 +55,12 @@ internal sealed class MergeJournal
|
||||
/// <summary>The dropped sequence's frames version the plan read (checked before each photo and at the verify).</summary>
|
||||
public int DropFramesVersion { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The dropped sequence's settings version the plan read: the trash refuses another (work sent home to the other since
|
||||
/// the plan, its Main settings or details, would go to the trash unmerged). Null in a journal written before it was kept.
|
||||
/// </summary>
|
||||
public int? DropSettingsVersion { get; set; }
|
||||
|
||||
/// <summary>The kept sequence's statuses before the merge (what its follow-ups make again).</summary>
|
||||
public int KeepStatus { get; set; }
|
||||
|
||||
@@ -90,6 +96,13 @@ internal sealed class MergeJournal
|
||||
/// <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>
|
||||
/// Raw SHA-256 of the drop photos the verify settled because a third sequence held them: asked again under the kept
|
||||
/// sequence's lease before the trash (that sequence may have gone since). Those settled through <see cref="Absent"/> the
|
||||
/// user confirmed as last copies and are not asked again.
|
||||
/// </summary>
|
||||
public List<string> SettledElsewhere { get; set; } = [];
|
||||
|
||||
/// <summary>The dropped sequence's frames version the verify read: the trash refuses another.</summary>
|
||||
public int? VerifiedDropFramesVersion { get; set; }
|
||||
|
||||
|
||||
@@ -144,7 +144,7 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
||||
var losers = steps.Where(s => s.Action == PhotoAction.TrashHere).Select(s => s.FrameId!.Value).ToHashSet();
|
||||
var keepHolds = here.Photos.Where(p => !p.Unusable && p.Sha256 is { Length: > 0 } && !losers.Contains(p.FrameId))
|
||||
.Select(p => p.Sha256!.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
|
||||
// Photos of the other a verify flagged Corrupt (changed since import, or damaged) whose file is still there: the
|
||||
// Photos of the other a verify flagged Corrupt (changed since import, or damaged) or Missing whose file is there: the
|
||||
// comparison leaves them out, so nothing would copy or hash-verify them before their folder goes to the trash. One
|
||||
// whose content now nothing else holds (an edited photo's only copy) blocks the merge until it is resolved.
|
||||
if (online && await DamagedAsync(drop, dropPaths, keepHolds, ct).ConfigureAwait(false)) blocks.Add(CopyBlock.DamagedPhotos);
|
||||
@@ -281,14 +281,15 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether the other sequence holds a frame flagged Corrupt (not Missing) whose file is still there and whose content,
|
||||
/// hashed now (in memory), neither the kept sequence (<paramref name="keepHolds"/>) nor any other sequence of this
|
||||
/// index holds; an unreadable such file counts too.
|
||||
/// Whether the other sequence holds a frame flagged unusable (Corrupt, or Missing by an earlier verify although its file
|
||||
/// is back) whose file is there and whose content, hashed now (in memory), neither the kept sequence
|
||||
/// (<paramref name="keepHolds"/>) nor any other sequence of this index holds; an unreadable such file counts too. The
|
||||
/// comparison leaves such frames out, so nothing else would copy or list them before their folder goes to the trash.
|
||||
/// </summary>
|
||||
private async Task<bool> DamagedAsync(Guid drop, ArchivePaths dropPaths, IReadOnlySet<string> keepHolds, CancellationToken ct)
|
||||
{
|
||||
var flagged = (await _db.Frames.ListBySequenceAsync(drop, cancellationToken: ct).ConfigureAwait(false))
|
||||
.Where(f => (f.Flags & FrameFlags.Corrupt) != 0 && (f.Flags & FrameFlags.Missing) == 0).ToList();
|
||||
.Where(f => (f.Flags & CopySides.UnusableFlags) != 0).ToList();
|
||||
var hashes = new List<string>();
|
||||
foreach (var frame in flagged)
|
||||
{
|
||||
@@ -441,15 +442,20 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>The drop's non-Main projects, each with the name it gets at the kept sequence's home.</summary>
|
||||
/// <summary>
|
||||
/// The drop's non-Main projects, each with the name it gets at the kept sequence's home; one whose head the kept
|
||||
/// sequence's projects hold already (by content: a merge planned again after an earlier run copied it) is not copied again.
|
||||
/// </summary>
|
||||
private async Task<List<ProjectStep>> ProjectStepsAsync(Guid keep, Guid drop, string dropArchiveName, CancellationToken ct)
|
||||
{
|
||||
var taken = (await _db.Projects.ListBySequenceAsync(keep, includeDeleted: false, ct).ConfigureAwait(false)).Select(p => p.Name)
|
||||
.ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var keepProjects = await _db.Projects.ListBySequenceAsync(keep, includeDeleted: false, ct).ConfigureAwait(false);
|
||||
var taken = keepProjects.Select(p => p.Name).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var keepHeads = await HeadHashesAsync(keepProjects, ct).ConfigureAwait(false);
|
||||
var steps = new List<ProjectStep>();
|
||||
foreach (var project in (await _db.Projects.ListBySequenceAsync(drop, includeDeleted: false, ct).ConfigureAwait(false))
|
||||
.Where(p => !p.IsMain).OrderBy(p => p.CreatedAt).ThenBy(p => p.Id))
|
||||
{
|
||||
if (await HeldAlreadyAsync(project, keepHeads, ct).ConfigureAwait(false)) continue;
|
||||
var name = FreeName(project.Name, dropArchiveName, taken);
|
||||
taken.Add(name);
|
||||
steps.Add(new ProjectStep(CopySide.Other, project.Id, project.Name, name, project.HeadNumber, project.HeadVersionId ?? Guid.Empty));
|
||||
@@ -457,6 +463,33 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
||||
return steps;
|
||||
}
|
||||
|
||||
/// <summary>The content hashes of the heads of <paramref name="projects"/> (Main and versionless ones left out; an unreadable head too).</summary>
|
||||
internal async Task<HashSet<string>> HeadHashesAsync(IEnumerable<SequenceProject> projects, CancellationToken ct)
|
||||
{
|
||||
var hashes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var project in projects.Where(p => !p.IsMain && p.HeadVersionId is not null))
|
||||
{
|
||||
if (await HeadHashAsync(project.Id, ct).ConfigureAwait(false) is { } hash) hashes.Add(hash);
|
||||
}
|
||||
return hashes;
|
||||
}
|
||||
|
||||
/// <summary>Whether the head of <paramref name="project"/> is one of <paramref name="heads"/> (by content).</summary>
|
||||
internal async Task<bool> HeldAlreadyAsync(SequenceProject project, IReadOnlySet<string> heads, CancellationToken ct) =>
|
||||
heads.Count > 0 && project.HeadVersionId is not null && await HeadHashAsync(project.Id, ct).ConfigureAwait(false) is { } head && heads.Contains(head);
|
||||
|
||||
private async Task<string?> HeadHashAsync(Guid projectId, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return (await _archives.Projects.HeadAsync(projectId, ct).ConfigureAwait(false)).ContentHash;
|
||||
}
|
||||
catch (Exception ex) when (ex is ProjectException or IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The name itself when free, else "<name> (<archive>)", then " (2)"…, each within <see cref="ProjectService.MaxNameLength"/>.</summary>
|
||||
internal static string FreeName(string name, string archiveName, IReadOnlySet<string> taken)
|
||||
{
|
||||
|
||||
@@ -349,8 +349,9 @@ public sealed class CopyFinder(ChronosDatabase db, FoundCopyStore store, CopySid
|
||||
evidence = Strongest(evidence, score);
|
||||
if (!CopyRules.IsCopy(evidence, score))
|
||||
{
|
||||
if (existing is { State: CopyState.Candidate }) await _store.DeleteAsync(existing.Id, ct).ConfigureAwait(false);
|
||||
return existing is { State: CopyState.Candidate } ? null : existing;
|
||||
// Only while it is still a Candidate: an answer given since it was read (Keep apart, Link) stays, as answered.
|
||||
if (existing is not { State: CopyState.Candidate }) return existing;
|
||||
return await _store.DeleteCandidateAsync(existing.Id, ct).ConfigureAwait(false) ? null : await _store.GetAsync(existing.Id, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var row = await _store.UpsertFoundAsync(new FoundCopy
|
||||
@@ -478,7 +479,7 @@ public sealed class CopyFinder(ChronosDatabase db, FoundCopyStore store, CopySid
|
||||
// Asked local pairs that share nothing any more (photos deleted, a sequence reidentified) are no longer asked.
|
||||
foreach (var stale in all.Where(c => c is { Kind: CopyKind.LocalLocal, State: CopyState.Candidate } && !candidates.ContainsKey((c.LocalId, c.OtherId!.Value))
|
||||
&& !held.Contains(c.LocalId) && !held.Contains(c.OtherId!.Value)))
|
||||
await _store.DeleteAsync(stale.Id, ct).ConfigureAwait(false);
|
||||
await _store.DeleteCandidateAsync(stale.Id, ct).ConfigureAwait(false);
|
||||
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
foreach (var id in touched)
|
||||
@@ -513,7 +514,7 @@ public sealed class CopyFinder(ChronosDatabase db, FoundCopyStore store, CopySid
|
||||
evidence = Strongest(evidence, score);
|
||||
if (!CopyRules.IsCopy(evidence, score))
|
||||
{
|
||||
if (existing is { State: CopyState.Candidate }) await _store.DeleteAsync(existing.Id, ct).ConfigureAwait(false);
|
||||
if (existing is { State: CopyState.Candidate }) await _store.DeleteCandidateAsync(existing.Id, ct).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
var row = await _store.UpsertFoundAsync(new FoundCopy
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Protocol.Client;
|
||||
|
||||
namespace Chronos.Data.Copies;
|
||||
|
||||
/// <summary>The reasons the Integrate and merge logs give for a losing version they kept, in the UI language.</summary>
|
||||
internal static class CopyLog
|
||||
{
|
||||
/// <summary>Why the archive's dry run refused to trash it: one phrase per block ("a job is working on it").</summary>
|
||||
public static string Reasons(IEnumerable<FrameDeleteBlock> blocks) =>
|
||||
string.Join(", ", blocks.Distinct().Select(b => Loc.L("Archive.Log.KeptReason." + b)));
|
||||
|
||||
/// <summary>
|
||||
/// Why a trash step failed: the photos changed meanwhile (a stale dry run), the server's refusal with its reason, or the
|
||||
/// system's message (an I/O error, already in the system's language).
|
||||
/// </summary>
|
||||
public static string Reason(Exception ex)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(ex);
|
||||
return ex switch
|
||||
{
|
||||
StaleDeletePlanException => Loc.L("Archive.Log.KeptReason.FramesChanged"),
|
||||
ChronosApiException => Loc.L("Archive.Log.KeptReason.Refused", ex.Message),
|
||||
_ => ex.Message,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -86,6 +86,15 @@ public sealed record IntegratePlan(Guid CopyId, string Server, Guid LocalId, Gui
|
||||
|
||||
/// <summary>The context the plan was made with (rights, names): the job plans again with it (<see cref="IntegratePlanner"/>).</summary>
|
||||
public CopyPlanContext? Context { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Photos whose server version stays for want of the right to trash it there (Delete, and owner or admin of the server
|
||||
/// sequence): counted in <see cref="LeftOut"/>; the server's Main uses this PC's version of them.
|
||||
/// </summary>
|
||||
public int StaysForDelete { get; init; }
|
||||
|
||||
/// <summary>Photos whose server version the plan trashes there or excludes from the server's Main: the server uses this PC's version.</summary>
|
||||
public int ServerUsesOurs { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>The choices of a merge of two local copies (projects are always copied across: the other's home goes to the trash).</summary>
|
||||
@@ -115,7 +124,8 @@ public sealed record MergePlan(Guid CopyId, Guid KeepId, Guid DropId, MergeChoic
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What the planners need to know of this PC and the signed-in account: names, rights (OwnsOrAdmin: of the server sequence),
|
||||
/// What the planners need to know of this PC and the signed-in account: names, rights (OwnsOrAdmin: the account is an admin
|
||||
/// of the server, which owns every sequence there; owning one is decided per sequence from its owner and <see cref="UserId"/>),
|
||||
/// whether the server keeps projects, the quota left, sequences with unsent workspace work, and every server's originals archive.
|
||||
/// </summary>
|
||||
public sealed record CopyPlanContext(string PcName, string? ServerName, bool CanUpload, bool CanFetch, bool CanEdit, bool CanDelete,
|
||||
|
||||
@@ -45,6 +45,7 @@ public sealed class CopyReviewBuilder(ChronosDatabase db, ProjectService project
|
||||
bool thereKeeps;
|
||||
List<(Guid Id, long Bytes, string? Sha256)> thereRenders;
|
||||
IReadOnlySet<string> capabilities = new HashSet<string>(StringComparer.Ordinal);
|
||||
Guid? remoteOwner = null;
|
||||
if (copy.Kind == CopyKind.LocalLocal)
|
||||
{
|
||||
var other = await SequenceAsync(copy.OtherId!.Value, ct).ConfigureAwait(false);
|
||||
@@ -61,6 +62,7 @@ public sealed class CopyReviewBuilder(ChronosDatabase db, ProjectService project
|
||||
throw new ArgumentException("A pair with a server sequence is reviewed over that server's session.", nameof(remote));
|
||||
var remoteId = copy.RemoteId!.Value;
|
||||
var dto = await remote.GetSequenceAsync(remoteId, ct).ConfigureAwait(false);
|
||||
remoteOwner = dto.OwnerUserId;
|
||||
var manifest = await remote.GetManifestAsync(remoteId, ct).ConfigureAwait(false);
|
||||
var rows = await remote.ListFramesAsync(remoteId, ct).ConfigureAwait(false);
|
||||
var captured = new Dictionary<Guid, DateTime?>(rows.Count);
|
||||
@@ -90,7 +92,7 @@ public sealed class CopyReviewBuilder(ChronosDatabase db, ProjectService project
|
||||
var renders = Renders(hereRenders, thereRenders);
|
||||
var can = copy.Kind == CopyKind.LocalLocal
|
||||
? await LocalCapabilitiesAsync(copy, local, ct).ConfigureAwait(false)
|
||||
: await ServerCapabilitiesAsync(copy, local, photos, details, capabilities, context, ct).ConfigureAwait(false);
|
||||
: await ServerCapabilitiesAsync(copy, local, photos, details, capabilities, context, remoteOwner, ct).ConfigureAwait(false);
|
||||
return new CopyReview(copy, hereFacts, thereFacts, photos, details, projectsView, renders, can);
|
||||
}
|
||||
|
||||
@@ -198,7 +200,7 @@ public sealed class CopyReviewBuilder(ChronosDatabase db, ProjectService project
|
||||
|
||||
/// <summary>What can be done with a local↔server pair, and why not (design §5b, §5c, §6.2).</summary>
|
||||
private async Task<CopyCapabilities> ServerCapabilitiesAsync(FoundCopy copy, Sequence local, CopyComparisonResult photos, IReadOnlyList<DetailLine> details,
|
||||
IReadOnlySet<string> capabilities, CopyPlanContext context, CancellationToken ct)
|
||||
IReadOnlySet<string> capabilities, CopyPlanContext context, Guid? remoteOwner, CancellationToken ct)
|
||||
{
|
||||
var server = copy.Server!;
|
||||
var remoteId = copy.RemoteId!.Value;
|
||||
@@ -217,7 +219,9 @@ public sealed class CopyReviewBuilder(ChronosDatabase db, ProjectService project
|
||||
if (copy.State == CopyState.Integrating || await BusyAsync([local.Id], [remoteId], ct).ConfigureAwait(false)) blocks.Add(CopyBlock.Busy);
|
||||
if (await OfflineAsync(local, ct).ConfigureAwait(false)) blocks.Add(CopyBlock.ArchiveOffline);
|
||||
var linkOnly = !linkTaken && !linked && copy.State is CopyState.Candidate or CopyState.KeptApart && !copy.RemoteGone;
|
||||
return new CopyCapabilities(blocks.Count == 0 && !copy.RemoteGone, linkOnly, context.CanDelete && context.OwnsOrAdmin && !copy.RemoteGone, blocks);
|
||||
// The server deletes frames of a sequence for its owner or an admin only (DeleteFramesAsync), whatever the account's Delete right.
|
||||
var owns = context.OwnsOrAdmin || (context.UserId is { } me && remoteOwner == me);
|
||||
return new CopyCapabilities(blocks.Count == 0 && !copy.RemoteGone, linkOnly, context.CanDelete && owns && !copy.RemoteGone, blocks);
|
||||
}
|
||||
|
||||
/// <summary>What can be done with two local copies: merge them, unless a job works on either, both are linked to one server, or an archive is offline.</summary>
|
||||
|
||||
@@ -276,6 +276,13 @@ public sealed class FoundCopyStore(ChronosDatabase db, TimeProvider? time = null
|
||||
public Task DeleteAsync(Guid id, CancellationToken ct) =>
|
||||
_db.ExecuteAsync("DELETE FROM found_copies WHERE id = $1", [id], ct);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the row only while it still reads as a <see cref="CopyState.Candidate"/>: a Keep apart or Link the user gave
|
||||
/// since detection read it stays. True when the row went.
|
||||
/// </summary>
|
||||
public async Task<bool> DeleteCandidateAsync(Guid id, CancellationToken ct) =>
|
||||
await _db.ExecuteAsync($"DELETE FROM found_copies WHERE id = $1 AND {Effective} = 0", [id], ct).ConfigureAwait(false) == 1;
|
||||
|
||||
/// <summary>
|
||||
/// Moves the pairs and probes of <paramref name="from"/> to <paramref name="to"/> inside the caller's transaction (the one
|
||||
/// <see cref="SyncLinkStore.RekeyAsync"/> moves the links in; design §2.5), after the links moved. On a clash the row
|
||||
|
||||
@@ -196,7 +196,10 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
|
||||
LocalPayload = plan.LocalPayload,
|
||||
RemotePayload = plan.RemotePayload,
|
||||
Projects = [.. plan.Projects],
|
||||
ServerName = plan.Context?.ServerName,
|
||||
};
|
||||
foreach (var step in plan.Photos.Where(p => p.Action is PhotoAction.Send or PhotoAction.SendVersion or PhotoAction.Fetch or PhotoAction.FetchVersion))
|
||||
journal.Names.TryAdd(step.Action == PhotoAction.FetchVersion && step.Sha256 is { Length: > 0 } sha ? sha : step.Key, step.FileName);
|
||||
journal.Save(paths);
|
||||
return journal;
|
||||
}
|
||||
@@ -252,22 +255,23 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
|
||||
var send = journal.Send.Except(journal.Sent, StringComparer.Ordinal).ToList();
|
||||
if (send.Count > 0)
|
||||
{
|
||||
await owner._transfers.SendPhotosAsync(context, remote, journal.LocalId, journal.RemoteId, send, key => DoneAsync(journal.Sent, key))
|
||||
await owner._transfers.SendPhotosAsync(context, remote, journal.LocalId, journal.RemoteId, send, key => DoneAsync(journal.Sent, key, "Archive.Log.CopySent"))
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
var fetch = journal.Fetch.Except(journal.Fetched, StringComparer.Ordinal).ToList();
|
||||
if (fetch.Count > 0)
|
||||
{
|
||||
await owner._transfers.FetchPhotosAsync(context, remote, journal.RemoteId, journal.LocalId, fetch, key => DoneAsync(journal.Fetched, key))
|
||||
.ConfigureAwait(false);
|
||||
await owner._transfers.FetchPhotosAsync(context, remote, journal.RemoteId, journal.LocalId, fetch,
|
||||
key => DoneAsync(journal.Fetched, key, "Archive.Log.CopyFetched")).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private async ValueTask DoneAsync(List<string> list, string key)
|
||||
private async ValueTask DoneAsync(List<string> list, string key, string logKey)
|
||||
{
|
||||
if (list.Contains(key, StringComparer.Ordinal)) return;
|
||||
list.Add(key);
|
||||
Save();
|
||||
context.Log(Loc.L(logKey, journal.Names.GetValueOrDefault(key) ?? key));
|
||||
await context.CheckpointAsync($"photos:{journal.Sent.Count + journal.Fetched.Count}", Done(), Total).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
@@ -301,7 +305,7 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
|
||||
}
|
||||
if (!await WinnerHereAsync(step.WinnerSha256).ConfigureAwait(false))
|
||||
{
|
||||
Keep(step, "the version that replaces it is not in place");
|
||||
Keep(step, Loc.L("Archive.Log.KeptReason.NotInPlace"));
|
||||
return;
|
||||
}
|
||||
try
|
||||
@@ -311,16 +315,17 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
|
||||
.ConfigureAwait(false);
|
||||
if (!plan.CanDelete)
|
||||
{
|
||||
Keep(step, string.Join(", ", plan.Blocked));
|
||||
Keep(step, CopyLog.Reasons(plan.Blocked));
|
||||
return;
|
||||
}
|
||||
await owner.Archives.FrameTrash.DeleteAsync(plan, null, null, _ct, journal.JobId).ConfigureAwait(false);
|
||||
journal.TrashedHere.Add(step.Key);
|
||||
Save();
|
||||
context.Log(Loc.L("Archive.Log.CopyReplaced", step.FileName));
|
||||
}
|
||||
catch (Exception ex) when (ex is StaleDeletePlanException or IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Keep(step, ex.Message);
|
||||
Keep(step, CopyLog.Reason(ex));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -344,7 +349,7 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
|
||||
// The winner on the server, by SHA-256, in a usable frame of a fresh manifest.
|
||||
if (!manifest.Frames.Any(f => (f.Flags & (long)CopySides.UnusableFlags) == 0 && string.Equals(f.Sha256, step.WinnerSha256, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
Keep(step, "the version that replaces it is not in place on the server");
|
||||
Keep(step, Loc.L("Archive.Log.KeptReason.NotInPlaceServer"));
|
||||
return;
|
||||
}
|
||||
try
|
||||
@@ -355,6 +360,7 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
|
||||
await remote.DeleteFramesAsync(journal.RemoteId, new FrameDeleteRequest([step.FrameId], manifest.FramesVersion, DryRun: false), _ct).ConfigureAwait(false);
|
||||
journal.TrashedThere.Add(step.Key);
|
||||
Save();
|
||||
context.Log(Loc.L("Archive.Log.CopyReplaced", step.FileName));
|
||||
}
|
||||
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.NotFound)
|
||||
{
|
||||
@@ -363,7 +369,7 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
|
||||
catch (Exception ex) when (ex is ChronosApiException { IsTransient: false } or NotSupportedException)
|
||||
{
|
||||
// Refused (the frames version moved, no right, would empty it): the photo stays.
|
||||
Keep(step, ex.Message);
|
||||
Keep(step, CopyLog.Reason(ex));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -371,7 +377,7 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
|
||||
{
|
||||
journal.KeptLosers.Add(step.Key);
|
||||
Save();
|
||||
context.Log($"{step.FileName}: {why}");
|
||||
context.Log(Loc.L("Archive.Log.CopyKept", step.FileName, why));
|
||||
}
|
||||
|
||||
/// <summary>Whether a usable frame of the local copy holds <paramref name="sha"/>, its file hashed again now.</summary>
|
||||
@@ -433,7 +439,7 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
|
||||
var (from, to) = step.From == CopySide.ThisPc ? ((IProjectHome?)localHome, serverHome) : (serverHome, localHome);
|
||||
try
|
||||
{
|
||||
if (from is null || to is null) throw new HomeUnavailableException($"The projects of {journal.Server} cannot be reached now.");
|
||||
if (from is null || to is null) throw new HomeUnavailableException(Loc.L("Errors.Copies.ProjectsUnreachable", journal.ServerName ?? journal.Server));
|
||||
if ((await from.ListAsync(_ct).ConfigureAwait(false)).FirstOrDefault(p => p.Id == step.SourceProjectId) is not { } source)
|
||||
{
|
||||
// Deleted at its home since the plan: nothing to copy.
|
||||
@@ -449,12 +455,13 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
|
||||
}, _ct).ConfigureAwait(false);
|
||||
journal.ProjectsDone.Add(step.SourceProjectId);
|
||||
Save();
|
||||
context.Log(Loc.L("Archive.Log.CopyProject", step.SourceName, step.TargetName));
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
journal.ProjectsFailed.Add(step.SourceProjectId);
|
||||
Save();
|
||||
context.Log($"{step.SourceName}: {ex.Message}");
|
||||
context.Log(Loc.L("Archive.Log.CopyProjectKept", step.SourceName, ex.Message));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,6 +36,9 @@ internal sealed class IntegrateJournal
|
||||
|
||||
public string Server { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The name the server is shown by (the log names it); null: its key.</summary>
|
||||
public string? ServerName { get; set; }
|
||||
|
||||
public Guid LocalId { get; set; }
|
||||
|
||||
public Guid RemoteId { get; set; }
|
||||
@@ -53,6 +56,9 @@ internal sealed class IntegrateJournal
|
||||
/// <summary>Photo keys of the server originals fetched (Fetch steps, and the server's key of each FetchVersion).</summary>
|
||||
public List<string> Fetch { get; set; } = [];
|
||||
|
||||
/// <summary>The file name of each key sent or fetched (the log names the photo).</summary>
|
||||
public Dictionary<string, string> Names { get; set; } = new(StringComparer.Ordinal);
|
||||
|
||||
public List<IntegrateTrash> Trash { get; set; } = [];
|
||||
|
||||
/// <summary>The one portable payload both sides get; null when the details stay as they are.</summary>
|
||||
|
||||
@@ -93,11 +93,15 @@ public sealed class IntegratePlanner(SyncService sync, CopySides sides, ProjectS
|
||||
var tombstones = SyncTombstones.FromDtos(here.Removed, there.Removed);
|
||||
|
||||
// Photos, by the policy (the "wins" policies decide the Different class only).
|
||||
var canTrashThere = context.CanDelete && context.OwnsOrAdmin;
|
||||
// The server moves frames of a sequence to its trash for the sequence's owner or an admin only (DeleteFramesAsync),
|
||||
// whatever the account's Delete right; sending into it needs that or the Edit right (UploadService).
|
||||
var owns = context.OwnsOrAdmin || (context.UserId is { } me && dto.OwnerUserId == me);
|
||||
var canTrashThere = context.CanDelete && owns;
|
||||
var steps = new List<PhotoStep>();
|
||||
var excluded = new List<string>();
|
||||
var leftOut = 0;
|
||||
var dropped = new HashSet<string>(StringComparer.Ordinal);
|
||||
var trashedThere = 0;
|
||||
foreach (var photo in comparison.Photos)
|
||||
{
|
||||
switch (photo.Class)
|
||||
@@ -130,11 +134,15 @@ public sealed class IntegratePlanner(SyncService sync, CopySides sides, ProjectS
|
||||
if (canTrashThere)
|
||||
{
|
||||
steps.Add(Step(photo.Key, PhotoAction.TrashThere, photo.There!));
|
||||
trashedThere++;
|
||||
}
|
||||
else
|
||||
{
|
||||
// The server's version stays (no right to trash it there), listed "stays: needs the Delete right";
|
||||
// its Main uses this PC's version, as when both are kept.
|
||||
dropped.Add(photo.Key);
|
||||
leftOut++;
|
||||
if (photo.There!.Sha256 is { Length: > 0 } stays) excluded.Add(tombstones.Canonical(stays)!);
|
||||
}
|
||||
break;
|
||||
case PhotoChoice.TakeThere:
|
||||
@@ -161,6 +169,7 @@ public sealed class IntegratePlanner(SyncService sync, CopySides sides, ProjectS
|
||||
var lines = CopyPayload.Lines(localRaw, localPhotos, remoteRaw, remotePhotos);
|
||||
SyncPayload? payload = null;
|
||||
var changes = 0;
|
||||
var excludedThere = 0;
|
||||
var unchosen = lines.Where(l => !choices.Details.ContainsKey(l.Path)).Select(l => l.Path).Distinct(StringComparer.Ordinal).Count();
|
||||
if (unchosen > 0)
|
||||
{
|
||||
@@ -175,6 +184,7 @@ public sealed class IntegratePlanner(SyncService sync, CopySides sides, ProjectS
|
||||
try
|
||||
{
|
||||
merged = CopyPayload.ExcludeVersions(merged, excluded);
|
||||
excludedThere = excluded.Count;
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or InvalidDataException)
|
||||
{
|
||||
@@ -200,12 +210,12 @@ public sealed class IntegratePlanner(SyncService sync, CopySides sides, ProjectS
|
||||
// Rights.
|
||||
if (steps.Any(s => s.Action is PhotoAction.Send or PhotoAction.SendVersion) && !context.CanUpload) blocks.Add(CopyBlock.NoUploadRight);
|
||||
// Sent into the server sequence: the server allows that to its owner, an admin or an account with Edit only.
|
||||
var owns = context.OwnsOrAdmin || (context.UserId is { } me && dto.OwnerUserId == me);
|
||||
if (steps.Any(s => s.Action is PhotoAction.Send or PhotoAction.SendVersion) && context.CanUpload && !owns && !context.CanEdit)
|
||||
blocks.Add(CopyBlock.NoAddRight);
|
||||
if (steps.Any(s => s.Action is PhotoAction.Fetch or PhotoAction.FetchVersion) && !context.CanFetch) blocks.Add(CopyBlock.NoFetchRight);
|
||||
// Nothing left but versions whose loser stays for want of the Delete right: there is nothing to integrate.
|
||||
if (dropped.Count > 0 && steps.All(s => dropped.Contains(s.Key)) && payload is null && projectSteps.Count == 0) blocks.Add(CopyBlock.NoDeleteRight);
|
||||
// (The payload making the server's Main use this PC's version of those photos does not count: it is the same choice.)
|
||||
if (dropped.Count > 0 && steps.All(s => dropped.Contains(s.Key)) && changes == 0 && projectSteps.Count == 0) blocks.Add(CopyBlock.NoDeleteRight);
|
||||
|
||||
var fingerprint = CopyRules.PlanFingerprint(FingerprintLines(local, manifest, localRaw, remoteRaw, choices, steps, lastCopies, payload, localPortable,
|
||||
remotePortable, projectSteps));
|
||||
@@ -214,6 +224,8 @@ public sealed class IntegratePlanner(SyncService sync, CopySides sides, ProjectS
|
||||
manifest.FramesVersion, manifest.SettingsVersion, fingerprint)
|
||||
{
|
||||
Context = context,
|
||||
StaysForDelete = dropped.Count,
|
||||
ServerUsesOurs = trashedThere + excludedThere,
|
||||
};
|
||||
|
||||
bool Brought(string key) => choices.Photos != CopyPhotoPolicy.ChoosePerPhoto || choices.PerPhoto.GetValueOrDefault(key, PhotoChoice.Leave) == PhotoChoice.Bring;
|
||||
|
||||
@@ -633,6 +633,16 @@ public sealed class SyncService
|
||||
var absorbed = CopyPayload.Moved(plannedRemote, freshRemote);
|
||||
if (absorbed.Count > 0 && !freshRemote.SameAs(final))
|
||||
{
|
||||
// Title, tags, rating and notes the user decided as this PC's (the plan had a line there and the final payload
|
||||
// keeps this PC's value) are never taken over from a server edit made since: no analysis moves them, and they
|
||||
// keep no history. The pair goes back to Linked and the sync shows the conflict. Settings paths are absorbed.
|
||||
var metadata = absorbed.Where(p => p.StartsWith(SyncRules.MetadataPath, StringComparison.Ordinal)).ToList();
|
||||
if (metadata.Count > 0)
|
||||
{
|
||||
var lined = CopyPayload.Moved(plannedLocal, plannedRemote);
|
||||
var notLocal = CopyPayload.Moved(plannedLocal, finalPortable);
|
||||
if (metadata.Any(p => lined.Contains(p) && !notLocal.Contains(p))) throw DetailsChanged();
|
||||
}
|
||||
final = CopyPayload.Merge(final, freshRemote, absorbed.ToDictionary(p => p, _ => CopySide.Other, StringComparer.Ordinal),
|
||||
[.. absorbed.Select(p => new DetailLine(p, null, null))]);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user