fix(copies): close the fourth verification round of owner review 6
The fourth verification round of the matches work found 18 defects in the merge, Integrate and Matches surfaces. This commit fixes them: - An Integrate job now carries the planning account's id, so its re-plan decides ownership the way the dialog did. - A merge skips only a project the kept sequence holds a real copy of (name, offset head and history content) and re-points its renders to that copy. - A merge runs its trash checks before the Links stage and records an undo, so an abandoned merge gives the other sequence back its link, session keys and pairs. - The metered hold adopts automatic transfers that were paused before a restart. - Apply in the Compare dialog re-plans when the plan is pending or stale. - The Library's Two versions... lists the second versions a Union merge leaves, each with Drop... (dry run, confirmation, verified partner). A merge job's Open shows that list. - The merge's typed confirmation is the invariant count, and the prompt names it in all 38 languages. - Italian text uses Principale and Gemello. The Main project is named through WorkspaceText in the Projects part and in the twin tooltip. - The session keys tooltip is split into two keys, and To trash... and Delete on server... say why they are disabled. - The capture restores the editor account before the Matches scenes. - Upload again follows SyncHost.CanSendSync (Upload with Edit). - Matches rows trim archive names in the middle on a rebalanced grid; the Projects part rows trim, with the full text in the tooltip. - The sample project targets use ProjectTransplant.FreeName. DECISIONS, CHANGELOG, STATUS 8.7, the request doc and the 16 changed capture baselines are updated. Refs #73 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3c99badcfe
commit
2c06e7ac2b
171 files changed
+1591
-218
No files matched your search
@@ -20,8 +20,10 @@ namespace Chronos.Data.Archiving.Jobs;
|
||||
/// tombstones honoured), move the renders, verify every original of the other is held by the kept one (hashed again on
|
||||
/// both sides) or listed as a last copy, trash the kept sequence's losing versions, write the details, copy the projects,
|
||||
/// move session keys, links and pairs, then move the other to its archive's trash, only while it is still at the frames
|
||||
/// version the verify read and the kept photos verified are still there. A cancel leaves the photos copied so far in the
|
||||
/// kept sequence (nothing of the other is touched before the trash stage) and drops the journal.
|
||||
/// version the verify read and the kept photos verified are still there. Every check that can still abandon the merge runs
|
||||
/// before the links stage changes anything, and again at the trash; a merge abandoned after the links stage (a check that
|
||||
/// fails at the trash, a cancel) gives the other back its keys, links and pairs first (<see cref="MergeLinksUndo"/>). A
|
||||
/// cancel leaves the photos copied so far in the kept sequence and drops the journal.
|
||||
/// </summary>
|
||||
internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger, ArchiveService archives, IProjectCopier projects,
|
||||
IWorkspaceGuard workspace) : ICancelledJobHandler
|
||||
@@ -93,6 +95,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
/// <summary>A cancelled merge: its journal and staging go, and its pair returns to the state it had (when it is still this job's).</summary>
|
||||
private async Task ForgetAsync(Job job, MergeJobParameters parameters, ArchivePaths keepPaths)
|
||||
{
|
||||
await MoveBackAsync(keepPaths, job.Id).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
MergeJournal.Delete(keepPaths, job.Id);
|
||||
@@ -105,6 +108,70 @@ 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>Gives back what the links stage of job <paramref name="jobId"/>'s journal moved (when it has one and the stage began).</summary>
|
||||
private async Task MoveBackAsync(ArchivePaths keepPaths, Guid jobId)
|
||||
{
|
||||
MergeJournal? journal;
|
||||
try
|
||||
{
|
||||
journal = MergeJournal.Read(keepPaths, jobId);
|
||||
}
|
||||
catch (InvalidDataException ex)
|
||||
{
|
||||
Log.Warning("archive", $"The journal of merge {jobId} could not be read: what its links stage moved stays with the kept sequence", ex);
|
||||
return;
|
||||
}
|
||||
if (journal is not null) await MoveBackAsync(journal).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gives the other sequence back what the links stage took (<see cref="MergeJournal.LinksUndo"/>): its rows (session keys,
|
||||
/// links, pairs), then the session keys of both manifests; the journal is set back to before the links stage (not saved).
|
||||
/// Nothing when the stage had not begun, or the other is gone (the trash ran). False when it could not be done.
|
||||
/// </summary>
|
||||
internal async Task<bool> MoveBackAsync(MergeJournal journal)
|
||||
{
|
||||
if (journal.LinksUndo is not { } undo) return true;
|
||||
var ct = CancellationToken.None;
|
||||
try
|
||||
{
|
||||
var drop = await db.Sequences.GetAsync(journal.DropId, ct).ConfigureAwait(false);
|
||||
var keep = await db.Sequences.GetAsync(journal.KeepId, ct).ConfigureAwait(false);
|
||||
if (drop is null || keep is null) return true;
|
||||
await new FoundCopyStore(db).MoveBackAsync(journal.DropId, journal.KeepId, keep.ArchiveId, undo.DropArchiveId, undo.Moved, ct).ConfigureAwait(false);
|
||||
var keys = journal.SessionKeys.ToHashSet(StringComparer.Ordinal);
|
||||
var added = keys.Where(k => !undo.KeepKeysBefore.Contains(k, StringComparer.Ordinal)).ToHashSet(StringComparer.Ordinal);
|
||||
var removed = keys.Where(k => undo.DropKeysBefore.Contains(k, StringComparer.Ordinal)).ToList();
|
||||
if (added.Count > 0 && await db.Archives.GetAsync(keep.ArchiveId, ct).ConfigureAwait(false) is { } keepArchive)
|
||||
{
|
||||
var paths = new ArchivePaths(keepArchive.RootPath);
|
||||
if (File.Exists(paths.Sequence(keep.Folder).ManifestPath))
|
||||
await archives.Writer.UpdateAsync(paths, keep.Id, keep.Folder, manifest =>
|
||||
!manifest.SessionKeys.Any(added.Contains) ? null : manifest with { SessionKeys = [.. manifest.SessionKeys.Where(k => !added.Contains(k))] },
|
||||
ct).ConfigureAwait(false);
|
||||
}
|
||||
if (removed.Count > 0 && await db.Archives.GetAsync(drop.ArchiveId, ct).ConfigureAwait(false) is { } dropArchive)
|
||||
{
|
||||
var paths = new ArchivePaths(dropArchive.RootPath);
|
||||
if (File.Exists(paths.Sequence(drop.Folder).ManifestPath))
|
||||
await archives.Writer.UpdateAsync(paths, drop.Id, drop.Folder, manifest =>
|
||||
removed.All(manifest.SessionKeys.Contains) ? null : manifest with { SessionKeys = [.. manifest.SessionKeys.Union(removed, StringComparer.Ordinal)] },
|
||||
ct).ConfigureAwait(false);
|
||||
}
|
||||
journal.LinksUndo = null;
|
||||
journal.KeepKeysWritten = false;
|
||||
journal.DropKeysRemoved = false;
|
||||
journal.LinksMoved = false;
|
||||
if (journal.Stage > MergeStage.Links) journal.Stage = MergeStage.Links;
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
Log.Warning("archive", $"Merge {journal.JobId}: what its links stage moved could not be given back to the other sequence", ex);
|
||||
return 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
|
||||
@@ -116,6 +183,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
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;
|
||||
await MoveBackAsync(keepPaths, job.Id).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
MergeJournal.Delete(keepPaths, job.Id);
|
||||
@@ -178,6 +246,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
private ArchivePaths _dropPaths = null!;
|
||||
private string _keepTitle = string.Empty;
|
||||
private string _dropTitle = string.Empty;
|
||||
private bool _forget;
|
||||
|
||||
private long Total => journal.Copies.Count + journal.Renders.Count + journal.Replaces.Count + journal.Projects.Count + 4;
|
||||
|
||||
@@ -198,16 +267,24 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
{
|
||||
_ct.ThrowIfCancellationRequested();
|
||||
if (owner.BeforeStage is { } hook) await hook(journal.Stage).ConfigureAwait(false);
|
||||
switch (journal.Stage)
|
||||
try
|
||||
{
|
||||
case MergeStage.Copy: await CopyAsync().ConfigureAwait(false); break;
|
||||
case MergeStage.Renders: await RendersAsync().ConfigureAwait(false); break;
|
||||
case MergeStage.Verify: await VerifyAsync().ConfigureAwait(false); break;
|
||||
case MergeStage.Replace: await ReplaceAsync().ConfigureAwait(false); break;
|
||||
case MergeStage.Details: await DetailsAsync().ConfigureAwait(false); break;
|
||||
case MergeStage.Projects: await ProjectsAsync().ConfigureAwait(false); break;
|
||||
case MergeStage.Links: await LinksAsync().ConfigureAwait(false); break;
|
||||
case MergeStage.Trash: await TrashAsync().ConfigureAwait(false); break;
|
||||
switch (journal.Stage)
|
||||
{
|
||||
case MergeStage.Copy: await CopyAsync().ConfigureAwait(false); break;
|
||||
case MergeStage.Renders: await RendersAsync().ConfigureAwait(false); break;
|
||||
case MergeStage.Verify: await VerifyAsync().ConfigureAwait(false); break;
|
||||
case MergeStage.Replace: await ReplaceAsync().ConfigureAwait(false); break;
|
||||
case MergeStage.Details: await DetailsAsync().ConfigureAwait(false); break;
|
||||
case MergeStage.Projects: await ProjectsAsync().ConfigureAwait(false); break;
|
||||
case MergeStage.Links: await LinksAsync().ConfigureAwait(false); break;
|
||||
case MergeStage.Trash: await TrashAsync().ConfigureAwait(false); break;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
await AbandonAsync().ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
journal.Stage++;
|
||||
Save();
|
||||
@@ -223,16 +300,32 @@ 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()
|
||||
/// <summary>Asks for this run's journal and staging to go as it fails (<see cref="AbandonAsync"/>): what it planned no longer holds.</summary>
|
||||
private void ForgetJournal() => _forget = true;
|
||||
|
||||
/// <summary>
|
||||
/// A stage failed: what the links stage took from the other goes back to it first (a retry runs that stage again, after
|
||||
/// its checks), then the journal goes when <see cref="ForgetJournal"/> asked for it, else it is saved as set back. When
|
||||
/// nothing could be given back, the journal stays (at the stage it reached) so a retry or a cancel tries again.
|
||||
/// </summary>
|
||||
private async Task AbandonAsync()
|
||||
{
|
||||
try
|
||||
var linksBegun = journal.LinksUndo is not null;
|
||||
if (!await owner.MoveBackAsync(journal).ConfigureAwait(false)) return;
|
||||
if (_forget)
|
||||
{
|
||||
MergeJournal.Delete(keepPaths, journal.JobId);
|
||||
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);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
else if (linksBegun)
|
||||
{
|
||||
Log.Warning("archive", $"The stale journal of merge {journal.JobId} was not removed", ex);
|
||||
Save();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -582,6 +675,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
|
||||
private async Task ProjectsAsync()
|
||||
{
|
||||
await RenamesHeldRendersAsync().ConfigureAwait(false);
|
||||
if (journal.Projects.Count == 0) return;
|
||||
var from = new ArchiveProjectHome(_db, owner.Archives.Projects, journal.DropId);
|
||||
var to = new ArchiveProjectHome(_db, owner.Archives.Projects, journal.KeepId);
|
||||
@@ -624,16 +718,33 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
if (failed > 0) throw new InvalidOperationException(Loc.Plural("Errors.Copies.ProjectsKept", failed));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The renders moved to the kept sequence that name a project of the other the plan left because the kept sequence
|
||||
/// holds its copy already name that copy (and its versions), as those of a copied project do.
|
||||
/// </summary>
|
||||
private async Task RenamesHeldRendersAsync()
|
||||
{
|
||||
var planned = journal.Projects.Select(p => p.SourceProjectId).ToHashSet();
|
||||
IReadOnlyList<SequenceProject>? keepProjects = null;
|
||||
foreach (var project in await _db.Projects.ListBySequenceAsync(journal.DropId, includeDeleted: false, _ct).ConfigureAwait(false))
|
||||
{
|
||||
if (project.IsMain || planned.Contains(project.Id)) continue;
|
||||
keepProjects ??= await _db.Projects.ListBySequenceAsync(journal.KeepId, includeDeleted: false, _ct).ConfigureAwait(false);
|
||||
if (await owner.Merger.HeldAsync(project, keepProjects, _dropArchive.Name, _ct).ConfigureAwait(false) is { } held)
|
||||
await RenamesRendersAsync(project.Id, held.KeptId, held.Versions.Select(v => new TransplantMove(v.Key, v.Value))).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The renders moved to the kept sequence name the project copy (and its versions) instead of the other's.</summary>
|
||||
private async Task RenamesRendersAsync(Guid source, Guid copy)
|
||||
private Task RenamesRendersAsync(Guid source, Guid copy) =>
|
||||
RenamesRendersAsync(source, copy, journal.ProjectSteps.GetValueOrDefault(source)?.Moves ?? []);
|
||||
|
||||
private async Task RenamesRendersAsync(Guid source, Guid copy, IEnumerable<TransplantMove> moves)
|
||||
{
|
||||
var access = new DbAccess(_db.Database);
|
||||
if (journal.ProjectSteps.GetValueOrDefault(source) is { } step)
|
||||
{
|
||||
foreach (var move in step.Moves)
|
||||
await access.ExecuteAsync("UPDATE renders SET project_id = $2, project_version_id = $3 WHERE sequence_id = $1 AND project_version_id = $4",
|
||||
[journal.KeepId, copy, move.Copy, move.Source], _ct).ConfigureAwait(false);
|
||||
}
|
||||
foreach (var move in moves)
|
||||
await access.ExecuteAsync("UPDATE renders SET project_id = $2, project_version_id = $3 WHERE sequence_id = $1 AND project_version_id = $4",
|
||||
[journal.KeepId, copy, move.Copy, move.Source], _ct).ConfigureAwait(false);
|
||||
await access.ExecuteAsync("UPDATE renders SET project_id = $2 WHERE sequence_id = $1 AND project_id = $3", [journal.KeepId, copy, source], _ct)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
@@ -645,6 +756,17 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
await context.ReportAsync(Done(), Total, new JobDetail(JobStep.Process)).ConfigureAwait(false);
|
||||
var keep = await _db.Sequences.GetAsync(journal.KeepId, _ct).ConfigureAwait(false) ?? throw new StaleCopyPlanException();
|
||||
var drop = await _db.Sequences.GetAsync(journal.DropId, _ct).ConfigureAwait(false) ?? throw Changed(_dropTitle);
|
||||
if (journal.LinksUndo is null)
|
||||
{
|
||||
// Nothing of the other is touched while a check before the trash can still abandon the merge.
|
||||
await CheckTrashAsync(drop).ConfigureAwait(false);
|
||||
await using (await owner.Archives.Writer.LockAsync(keepPaths, journal.KeepId, _ct).ConfigureAwait(false))
|
||||
await PlanTrashAsync().ConfigureAwait(false);
|
||||
journal.LinksUndo = new MergeLinksUndo(KeysOf(keepPaths, keep), KeysOf(_dropPaths, drop), _dropArchive.Id,
|
||||
await new FoundCopyStore(_db).UndoOfMoveAsync(journal.DropId, journal.KeepId, keepArchive.Id, journal.SessionKeys, journal.CopyId, _ct)
|
||||
.ConfigureAwait(false));
|
||||
Save();
|
||||
}
|
||||
var keys = journal.SessionKeys.ToHashSet(StringComparer.Ordinal);
|
||||
if (!journal.KeepKeysWritten)
|
||||
{
|
||||
@@ -686,13 +808,22 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The session keys of the manifest of <paramref name="sequence"/> (none when it has no manifest).</summary>
|
||||
private static List<string> KeysOf(ArchivePaths paths, Sequence sequence)
|
||||
{
|
||||
var manifest = paths.Sequence(sequence.Folder).ManifestPath;
|
||||
return sequence.Folder.Length > 0 && File.Exists(manifest) ? [.. ManifestStore.ReadSequence(manifest).SessionKeys] : [];
|
||||
}
|
||||
|
||||
// ---- trash ----
|
||||
|
||||
private async Task TrashAsync()
|
||||
/// <summary>
|
||||
/// The checks before the trash that may abandon the merge, run before the links stage and again at the trash: no
|
||||
/// unsent workspace work, no work saved into the other since the plan, the other at the frames version the verify read
|
||||
/// and readable. Returns that frames version.
|
||||
/// </summary>
|
||||
private async Task<int> CheckTrashAsync(Sequence drop)
|
||||
{
|
||||
var drop = await _db.Sequences.GetAsync(journal.DropId, _ct).ConfigureAwait(false);
|
||||
if (drop is null) return; // a run that moved it before its journal said so
|
||||
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))
|
||||
@@ -704,12 +835,28 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
var expected = journal.VerifiedDropFramesVersion ?? throw Changed(_dropTitle);
|
||||
if (drop.FramesVersion != expected) throw Changed(_dropTitle);
|
||||
EnsureDropReadable(drop);
|
||||
return expected;
|
||||
}
|
||||
|
||||
/// <summary>Under the kept sequence's lease: every verified photo is still held, and the trash's dry run of the other is not blocked.</summary>
|
||||
private async Task<DeletePlan> PlanTrashAsync()
|
||||
{
|
||||
await EnsureVerifiedHeldAsync().ConfigureAwait(false);
|
||||
var plan = await owner.Archives.Trash.PlanAsync([journal.DropId], null, _ct, journal.JobId).ConfigureAwait(false);
|
||||
if (plan.Blocked.Count > 0)
|
||||
throw new InvalidOperationException(Loc.L("Errors.Copies.TrashBlocked", _dropTitle, Loc.L("Archive.Delete.Reason." + plan.Blocked[0].Reason)));
|
||||
return plan;
|
||||
}
|
||||
|
||||
private async Task TrashAsync()
|
||||
{
|
||||
var drop = await _db.Sequences.GetAsync(journal.DropId, _ct).ConfigureAwait(false);
|
||||
if (drop is null) return; // a run that moved it before its journal said so
|
||||
await context.ReportAsync(Done(), Total, new JobDetail(JobStep.Trash, _dropTitle)).ConfigureAwait(false);
|
||||
var expected = await CheckTrashAsync(drop).ConfigureAwait(false);
|
||||
await using (await owner.Archives.Writer.LockAsync(keepPaths, journal.KeepId, _ct).ConfigureAwait(false))
|
||||
{
|
||||
await EnsureVerifiedHeldAsync().ConfigureAwait(false);
|
||||
var plan = await owner.Archives.Trash.PlanAsync([journal.DropId], null, _ct, journal.JobId).ConfigureAwait(false);
|
||||
if (plan.Blocked.Count > 0)
|
||||
throw new InvalidOperationException(Loc.L("Errors.Copies.TrashBlocked", _dropTitle, Loc.L("Archive.Delete.Reason." + plan.Blocked[0].Reason)));
|
||||
var plan = await PlanTrashAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await owner.Archives.Trash.DeleteAsync(plan, null, null, _ct, journal.JobId, new Dictionary<Guid, int> { [journal.DropId] = expected })
|
||||
@@ -732,15 +879,14 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
|
||||
{
|
||||
if (journal.DropSettingsVersion is { } settings && drop.SettingsVersion != settings) return true;
|
||||
var planned = journal.Projects.ToDictionary(p => p.SourceProjectId);
|
||||
HashSet<string>? keepHeads = null;
|
||||
IReadOnlyList<SequenceProject>? keepProjects = 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;
|
||||
// Not planned (or moved on since) is fine only when the kept sequence holds a copy of it already, as the plan saw it.
|
||||
keepProjects ??= await _db.Projects.ListBySequenceAsync(journal.KeepId, includeDeleted: false, _ct).ConfigureAwait(false);
|
||||
if (await owner.Merger.HeldAsync(project, keepProjects, _dropArchive.Name, _ct).ConfigureAwait(false) is null) return true;
|
||||
}
|
||||
var renders = await _db.Renders.ListBySequenceAsync(journal.DropId, _ct).ConfigureAwait(false);
|
||||
if (renders.Count == 0) return false;
|
||||
|
||||
@@ -30,6 +30,12 @@ internal sealed record MergeReplace(string Key, Guid KeepFrameId, string FileNam
|
||||
/// <summary>A drop original the verify found in the kept sequence: its SHA-256 now and the keep frame that holds it.</summary>
|
||||
internal sealed record MergeVerified(string Sha256, Guid KeepFrameId);
|
||||
|
||||
/// <summary>
|
||||
/// What a merge's links stage changes, read before it: the session keys each manifest held, the other's archive, and the
|
||||
/// rows <see cref="FoundCopyStore.MoveToKeptAsync"/> moves (<see cref="MoveUndo"/>).
|
||||
/// </summary>
|
||||
internal sealed record MergeLinksUndo(List<string> KeepKeysBefore, List<string> DropKeysBefore, Guid DropArchiveId, MoveUndo Moved);
|
||||
|
||||
/// <summary>
|
||||
/// The journal of a merge (owner review 6, #73; design §5d): <c><keep archive>/.chronos/journal/merge-<job:N>.json</c>,
|
||||
/// written atomically (temp + rename) after each step. It keeps what the confirmed plan decided (a resumed run never plans
|
||||
@@ -123,6 +129,12 @@ internal sealed class MergeJournal
|
||||
|
||||
public bool LinksMoved { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// What the links stage takes from the other sequence, read before its first change: a merge abandoned after it (a check
|
||||
/// before the trash fails, a cancel) gives it back, so the other keeps its keys, links and pairs. Null before the stage.
|
||||
/// </summary>
|
||||
public MergeLinksUndo? LinksUndo { get; set; }
|
||||
|
||||
/// <summary>The journal of job <paramref name="jobId"/> in the archive at <paramref name="paths"/>.</summary>
|
||||
public static string PathFor(ArchivePaths paths, Guid jobId) => Path.Combine(paths.JournalDirectory, $"merge-{jobId:N}.json");
|
||||
|
||||
|
||||
@@ -443,19 +443,18 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
||||
}
|
||||
|
||||
/// <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.
|
||||
/// The drop's non-Main projects, each with the name it gets at the kept sequence's home; one the kept sequence holds a
|
||||
/// copy of already (<see cref="HeldAsync"/>: 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 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;
|
||||
if (await HeldAsync(project, keepProjects, dropArchiveName, ct).ConfigureAwait(false) is not null) 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));
|
||||
@@ -463,26 +462,56 @@ 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)
|
||||
/// <summary>
|
||||
/// The copy of the drop's <paramref name="project"/> a merge made in the kept sequence already, among
|
||||
/// <paramref name="keepProjects"/>: named after it (its name, or the free name a merge gives it), and holding its whole
|
||||
/// history by content after the Main version it was made from (a transplant). Another project that merely has an
|
||||
/// equal head (two projects made from equal Mains) is not one. Null when there is none, or a history cannot be read.
|
||||
/// </summary>
|
||||
internal async Task<HeldProject?> HeldAsync(SequenceProject project, IReadOnlyList<SequenceProject> keepProjects, string dropArchiveName,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var hashes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var project in projects.Where(p => !p.IsMain && p.HeadVersionId is not null))
|
||||
if (project.IsMain || project.HeadVersionId is null || project.HeadNumber <= 0) return null;
|
||||
List<ProjectVersion>? source = null;
|
||||
foreach (var kept in keepProjects.Where(k => !k.IsMain && k.HeadNumber == project.HeadNumber + 1 && NamedAfter(k.Name, project.Name, dropArchiveName)))
|
||||
{
|
||||
if (await HeadHashAsync(project.Id, ct).ConfigureAwait(false) is { } hash) hashes.Add(hash);
|
||||
source ??= await HistoryAsync(project.Id, ct).ConfigureAwait(false);
|
||||
if (source is null || source.Count != project.HeadNumber) return null;
|
||||
if (await HistoryAsync(kept.Id, ct).ConfigureAwait(false) is not { } copy || copy.Count != source.Count + 1) continue;
|
||||
if (!source.Select((v, i) => string.Equals(v.ContentHash, copy[i + 1].ContentHash, StringComparison.OrdinalIgnoreCase)).All(same => same)) continue;
|
||||
return new HeldProject(kept.Id, source.Select((v, i) => (Source: v.Id, Copy: copy[i + 1].Id)).ToDictionary(m => m.Source, m => m.Copy));
|
||||
}
|
||||
return hashes;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <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)
|
||||
/// <summary>Whether <paramref name="kept"/> is a name a merge gives the drop's project <paramref name="name"/> (<see cref="FreeName"/>, or a transplant's numbered one).</summary>
|
||||
private static bool NamedAfter(string kept, string name, string archiveName)
|
||||
{
|
||||
foreach (var stem in (string[])[name, Fit(name, $" ({archiveName})")])
|
||||
{
|
||||
if (string.Equals(kept, stem, StringComparison.OrdinalIgnoreCase)) return true;
|
||||
var open = kept.LastIndexOf(" (", StringComparison.Ordinal);
|
||||
if (open < 0 || !kept.EndsWith(')')
|
||||
|| !int.TryParse(kept.AsSpan(open + 2, kept.Length - open - 3), NumberStyles.None, CultureInfo.InvariantCulture, out var n) || n < 2)
|
||||
continue;
|
||||
if (string.Equals(kept, Fit(stem, string.Create(CultureInfo.InvariantCulture, $" ({n})")), StringComparison.OrdinalIgnoreCase)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>A project's whole history, oldest first; null when it cannot be read.</summary>
|
||||
private async Task<List<ProjectVersion>?> HistoryAsync(Guid projectId, CancellationToken ct)
|
||||
{
|
||||
const int page = 200;
|
||||
try
|
||||
{
|
||||
return (await _archives.Projects.HeadAsync(projectId, ct).ConfigureAwait(false)).ContentHash;
|
||||
var all = new List<ProjectVersion>();
|
||||
while (true)
|
||||
{
|
||||
var next = await _archives.Projects.VersionsAfterAsync(projectId, all.Count == 0 ? 0 : all[^1].Number, page, ct).ConfigureAwait(false);
|
||||
all.AddRange(next);
|
||||
if (next.Count < page) return all;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is ProjectException or IOException or UnauthorizedAccessException)
|
||||
{
|
||||
@@ -501,13 +530,14 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
||||
var candidate = Fit(stem, string.Create(CultureInfo.InvariantCulture, $" ({n})"));
|
||||
if (!taken.Contains(candidate)) return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
static string Fit(string stem, string suffix)
|
||||
{
|
||||
const int max = ProjectService.MaxNameLength;
|
||||
if (suffix.Length >= max) suffix = suffix[..(max / 2)];
|
||||
return (stem.Length + suffix.Length > max ? stem[..(max - suffix.Length)].TrimEnd() : stem) + suffix;
|
||||
}
|
||||
/// <summary>Appends <paramref name="suffix"/>, shortening <paramref name="stem"/> so the whole fits a project name.</summary>
|
||||
private static string Fit(string stem, string suffix)
|
||||
{
|
||||
const int max = ProjectService.MaxNameLength;
|
||||
if (suffix.Length >= max) suffix = suffix[..(max / 2)];
|
||||
return (stem.Length + suffix.Length > max ? stem[..(max - suffix.Length)].TrimEnd() : stem) + suffix;
|
||||
}
|
||||
|
||||
/// <summary>The drop's session keys that move to the kept sequence, and those the kept archive maps to a third sequence already.</summary>
|
||||
@@ -564,3 +594,6 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
|
||||
foreach (var key in skippedKeys) yield return "skipped:" + key;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A copy of a drop project the kept sequence holds already: the kept project and each drop version's copy there.</summary>
|
||||
internal sealed record HeldProject(Guid KeptId, IReadOnlyDictionary<Guid, Guid> Versions);
|
||||
@@ -316,6 +316,46 @@ public sealed class CopyEngine(SyncService sync, ArchiveService archives, Integr
|
||||
Log.Info(LogCategory, $"Pair {copyId} kept here after its server copy was deleted");
|
||||
}
|
||||
|
||||
// ---------------- Two versions in one sequence ----------------
|
||||
|
||||
public Task<IReadOnlyList<PhotoVersions>> VersionsAsync(Guid sequenceId, CancellationToken ct) => _sides.VersionsAsync(sequenceId, ct);
|
||||
|
||||
public async Task<OwnVersionDropPlan> PlanDropOwnVersionAsync(Guid sequenceId, Guid frameId, CancellationToken ct)
|
||||
{
|
||||
var versions = await _sides.VersionsAsync(sequenceId, ct).ConfigureAwait(false);
|
||||
var photo = versions.FirstOrDefault(v => v.FirstFrameId == frameId || v.SecondFrameId == frameId)
|
||||
?? throw new StaleCopyPlanException(Loc.L("Errors.Copies.OtherVersionGone"));
|
||||
var (sha, name, size, partner, partnerName, partnerSha) = frameId == photo.FirstFrameId
|
||||
? (photo.FirstSha256, photo.FirstFileName, photo.FirstSize, photo.SecondFrameId, photo.SecondFileName, photo.SecondSha256)
|
||||
: (photo.SecondSha256, photo.SecondFileName, photo.SecondSize, photo.FirstFrameId, photo.FirstFileName, photo.FirstSha256);
|
||||
var sequence = await Db.Sequences.GetAsync(sequenceId, ct).ConfigureAwait(false) ?? throw new StaleCopyPlanException();
|
||||
var plan = await _archives.FrameTrash.PlanDeleteAsync(sequenceId, [frameId], sequence.FramesVersion, ct).ConfigureAwait(false);
|
||||
// The photo stays (its other version); this version's content may still be held nowhere else.
|
||||
var elsewhere = await _sides.HeldElsewhereAsync([sha], [sequenceId], ct).ConfigureAwait(false);
|
||||
IReadOnlyList<LastCopy> lasts = elsewhere.Contains(sha) ? [] : [new LastCopy(sha, CopySide.ThisPc, name, size)];
|
||||
return new OwnVersionDropPlan(plan, partner, partnerName, partnerSha, lasts);
|
||||
}
|
||||
|
||||
public async Task<int> DropOwnVersionAsync(OwnVersionDropPlan plan, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
var sequenceId = plan.Plan.Sequence.Id;
|
||||
// The other version must still be there and usable, its file hashed again now: the photo never leaves with this one.
|
||||
var partner = await Db.Frames.GetAsync(plan.PartnerFrameId, ct).ConfigureAwait(false);
|
||||
if (partner is null || partner.SequenceId != sequenceId || (partner.Flags & CopySides.UnusableFlags) != 0
|
||||
|| !await HoldsVerifiedAsync(sequenceId, [new CopyPhotoInput(partner.Id, partner.Index, partner.FileName, plan.PartnerSha256, partner.Size, partner.CapturedAt, false)], ct)
|
||||
.ConfigureAwait(false))
|
||||
{
|
||||
Log.Info(LogCategory, $"Sequence {sequenceId}: the version kept is no longer there; nothing went to the trash");
|
||||
throw new StaleCopyPlanException(Loc.L("Errors.Copies.OtherVersionGone"));
|
||||
}
|
||||
if ((await Db.Sequences.GetAsync(sequenceId, ct).ConfigureAwait(false))?.FramesVersion != plan.Plan.Sequence.FramesVersion)
|
||||
throw new StaleCopyPlanException();
|
||||
await _archives.FrameTrash.DeleteAsync(plan.Plan, _context(null).PcName, followUps?.Invoke(), ct).ConfigureAwait(false);
|
||||
Log.Info(LogCategory, $"Sequence {sequenceId}: one version of a photo kept in two went to its archive trash");
|
||||
return plan.Plan.Frames.Count;
|
||||
}
|
||||
|
||||
// ---------------- Deleted on one side ----------------
|
||||
|
||||
public async Task<TrashHerePlan> PlanTrashHereAsync(Guid copyId, IReadOnlyCollection<string> photoKeys, CancellationToken ct)
|
||||
|
||||
@@ -15,6 +15,9 @@ namespace Chronos.Data.Copies;
|
||||
public sealed record IntegrateJobContext(string PcName, string? ServerName, bool CanUpload, bool CanFetch, bool CanEdit, bool CanDelete,
|
||||
bool OwnsOrAdmin, bool KeepsProjects, long? QuotaLeft)
|
||||
{
|
||||
/// <summary>The signed-in account's id when the plan was made: an owner who is not an admin plans the same steps in the job.</summary>
|
||||
public Guid? UserId { get; init; }
|
||||
|
||||
/// <summary>Everything allowed: what a job queued without a context plans with.</summary>
|
||||
public static IntegrateJobContext Permissive { get; } = new(Environment.MachineName, null, true, true, true, true, true, true, null);
|
||||
|
||||
@@ -22,11 +25,13 @@ public sealed record IntegrateJobContext(string PcName, string? ServerName, bool
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
return new(context.PcName, context.ServerName, context.CanUpload, context.CanFetch, context.CanEdit, context.CanDelete, context.OwnsOrAdmin,
|
||||
context.KeepsProjects, context.QuotaLeft);
|
||||
context.KeepsProjects, context.QuotaLeft)
|
||||
{ UserId = context.UserId };
|
||||
}
|
||||
|
||||
public CopyPlanContext ToPlanContext() => new(PcName, ServerName, CanUpload, CanFetch, CanEdit, CanDelete, OwnsOrAdmin, KeepsProjects, QuotaLeft,
|
||||
new HashSet<Guid>(), new HashSet<Guid>());
|
||||
new HashSet<Guid>(), new HashSet<Guid>())
|
||||
{ UserId = UserId };
|
||||
}
|
||||
|
||||
/// <summary>The Integrate job of a local↔server pair (owner review 6, #73; design §5c): its handler and how it is queued.</summary>
|
||||
|
||||
@@ -205,6 +205,15 @@ public sealed record LocalOverlap(Guid Low, Guid High, int SharedHashes, int Sha
|
||||
/// <summary>What the links stage of a merge moved (<see cref="FoundCopyStore.MoveToKeptAsync"/>).</summary>
|
||||
public sealed record MoveResult(int SessionKeys, IReadOnlyList<string> SkippedKeys, int Links, int Pairs);
|
||||
|
||||
/// <summary>
|
||||
/// What a merge's links stage is about to move (<see cref="FoundCopyStore.UndoOfMoveAsync"/>), kept so a merge abandoned
|
||||
/// after it can give it back (<see cref="FoundCopyStore.MoveBackAsync"/>): the session keys, the links and the stored pair rows.
|
||||
/// </summary>
|
||||
public sealed record MoveUndo(IReadOnlyList<string> SessionKeys, IReadOnlyList<MovedLink> Links, IReadOnlyList<FoundCopy> Pairs);
|
||||
|
||||
/// <summary>A sync link a merge's links stage re-points: its server and remote sequence.</summary>
|
||||
public sealed record MovedLink(string Server, Guid RemoteId);
|
||||
|
||||
/// <summary>One side's hints (design §3.1): capture range, camera, median interval and title.</summary>
|
||||
public sealed record CopyHintsInput(DateTime? First, DateTime? Last, string? Camera, double? MedianInterval, string? Title);
|
||||
|
||||
|
||||
@@ -143,6 +143,15 @@ public sealed record TrashTherePlan(Guid CopyId, string Server, Guid RemoteId, I
|
||||
/// <summary>The dry run of moving photos of a pair's local copy to its archive trash, with the ones no other sequence of this index holds.</summary>
|
||||
public sealed record TrashHerePlan(FrameDeletePlan Plan, IReadOnlyList<LastCopy> LastCopies);
|
||||
|
||||
/// <summary>
|
||||
/// The dry run of dropping one of the two versions one sequence keeps of a photo (owner Q3; a Union merge leaves them, and
|
||||
/// its pair is gone): the version's frame goes to the sequence's archive trash, the other version (<see cref="PartnerFrameId"/>)
|
||||
/// stays. Applied only while that other version is still there, usable and verified by content. <see cref="LastCopies"/>:
|
||||
/// the version itself when no other sequence of this index holds its content.
|
||||
/// </summary>
|
||||
public sealed record OwnVersionDropPlan(FrameDeletePlan Plan, Guid PartnerFrameId, string PartnerFileName, string PartnerSha256,
|
||||
IReadOnlyList<LastCopy> LastCopies);
|
||||
|
||||
/// <summary>
|
||||
/// The dry run of dropping one version of a photo kept in two versions (design §4.1, Versions): the version
|
||||
/// <see cref="Key"/> goes to the trash of both sides (this PC's copy and the server's, or both local copies of a merge),
|
||||
|
||||
@@ -6,7 +6,15 @@ 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);
|
||||
public sealed record PhotoVersions(Guid FirstFrameId, string FirstFileName, string FirstSha256, Guid SecondFrameId, string SecondFileName, string SecondSha256)
|
||||
{
|
||||
/// <summary>The photo's capture instant (both versions share it).</summary>
|
||||
public DateTime? CapturedAt { get; init; }
|
||||
|
||||
public long FirstSize { get; init; }
|
||||
|
||||
public long SecondSize { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The two sides of a comparison as <see cref="CopyComparer"/> reads them (owner review 6, #73; design §4.2): a local
|
||||
@@ -67,7 +75,12 @@ public sealed class CopySides(ChronosDatabase db)
|
||||
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()));
|
||||
versions[1].Id, versions[1].FileName, versions[1].Sha256!.ToLowerInvariant())
|
||||
{
|
||||
CapturedAt = versions[0].CapturedAt,
|
||||
FirstSize = versions[0].Size,
|
||||
SecondSize = versions[1].Size,
|
||||
});
|
||||
}
|
||||
return [.. result.OrderBy(v => frames.First(f => f.Id == v.FirstFrameId).Index)];
|
||||
}
|
||||
|
||||
@@ -442,6 +442,69 @@ public sealed class FoundCopyStore(ChronosDatabase db, TimeProvider? time = null
|
||||
}, ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What <see cref="MoveToKeptAsync"/> with these arguments would move, read before it runs so <see cref="MoveBackAsync"/>
|
||||
/// can return it: the session keys it would take from <paramref name="drop"/>, the links naming drop, and the stored rows
|
||||
/// of the pairs naming drop (but <paramref name="exceptCopyId"/>).
|
||||
/// </summary>
|
||||
public async Task<MoveUndo> UndoOfMoveAsync(Guid drop, Guid keep, Guid keepArchiveId, IReadOnlyCollection<string> sessionKeys, Guid? exceptCopyId,
|
||||
CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sessionKeys);
|
||||
var keys = new List<string>();
|
||||
foreach (var key in sessionKeys.Distinct(StringComparer.Ordinal))
|
||||
{
|
||||
var holder = await _db.ScalarAsync<Guid?>("SELECT sequence_id FROM sequence_sessions WHERE archive_id = $1 AND session_key = $2",
|
||||
[keepArchiveId, key], ct).ConfigureAwait(false);
|
||||
if (holder is null || holder == drop) keys.Add(key);
|
||||
}
|
||||
var links = await _db.ListAsync("SELECT server, remote_id FROM sync_links WHERE local_id = $1 ORDER BY server, remote_id", [drop],
|
||||
r => new MovedLink(r.GetString(0), r.GetGuid(1)), ct).ConfigureAwait(false);
|
||||
// The stored rows as they are (their stored state, not the state they read as).
|
||||
var pairs = await _db.ListAsync($"SELECT {Columns}, found_copies.state AS effective_state FROM found_copies WHERE local_id = $1 OR other_id = $1 ORDER BY id",
|
||||
[drop], Map, ct).ConfigureAwait(false);
|
||||
return new MoveUndo(keys, [.. links], [.. pairs.Where(p => p.Id != exceptCopyId && p.LocalId != keep && p.OtherId != keep)]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns what a merge's links stage moved from <paramref name="drop"/> to <paramref name="keep"/> (<paramref name="undo"/>,
|
||||
/// read by <see cref="UndoOfMoveAsync"/> before it), one transaction: the session keys go back to drop in its archive, the
|
||||
/// links naming keep that named drop name drop again (their agreement stays reset: the next comparison settles it), and
|
||||
/// the pairs return to their stored rows. Idempotent; a no-op for what did not move.
|
||||
/// </summary>
|
||||
public Task MoveBackAsync(Guid drop, Guid keep, Guid keepArchiveId, Guid dropArchiveId, MoveUndo undo, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(undo);
|
||||
return _db.InTransactionAsync(async session =>
|
||||
{
|
||||
var inner = new DbAccess(session);
|
||||
foreach (var key in undo.SessionKeys)
|
||||
{
|
||||
await inner.ExecuteAsync("DELETE FROM sequence_sessions WHERE archive_id = $1 AND session_key = $2 AND sequence_id = $3", [keepArchiveId, key, keep], ct)
|
||||
.ConfigureAwait(false);
|
||||
await inner.ExecuteAsync(
|
||||
"INSERT INTO sequence_sessions (archive_id, session_key, sequence_id) VALUES ($1, $2, $3) ON CONFLICT (archive_id, session_key) DO NOTHING",
|
||||
[dropArchiveId, key, drop], ct).ConfigureAwait(false);
|
||||
}
|
||||
foreach (var link in undo.Links)
|
||||
{
|
||||
await inner.ExecuteAsync("UPDATE sync_links SET local_id = $3 WHERE server = $1 AND remote_id = $2 AND local_id = $4", [link.Server, link.RemoteId, drop, keep],
|
||||
ct).ConfigureAwait(false);
|
||||
}
|
||||
var now = _time.GetUtcNow();
|
||||
foreach (var pair in undo.Pairs)
|
||||
{
|
||||
await inner.ExecuteAsync("DELETE FROM found_copies WHERE id = $1", [pair.Id], ct).ConfigureAwait(false);
|
||||
var clash = pair.Kind == CopyKind.LocalServer
|
||||
? await FindRemoteAsync(inner, pair.LocalId, pair.Server!, pair.RemoteId!.Value, ct).ConfigureAwait(false)
|
||||
: await inner.SingleAsync($"{Select} WHERE kind = 1 AND local_id = $1 AND other_id = $2", [pair.LocalId, pair.OtherId!.Value], Map, ct)
|
||||
.ConfigureAwait(false);
|
||||
if (clash is null) await InsertAsync(inner, pair, now, ct).ConfigureAwait(false);
|
||||
}
|
||||
return 0;
|
||||
}, ct);
|
||||
}
|
||||
|
||||
public Task<CopyProbe?> GetProbeAsync(Guid sequenceId, string scope, CancellationToken ct) =>
|
||||
_db.SingleAsync("SELECT sequence_id, scope, frames_version, hashed, probed_at, server_newest FROM copy_probes WHERE sequence_id = $1 AND scope = $2",
|
||||
[sequenceId, scope], r => new CopyProbe(r.GetGuid(0), r.GetString(1), r.GetInt32(2), r.GetInt32(3), r.GetDateTimeOffset(4), r.GetDateTimeOffsetOrNull(5)), ct);
|
||||
|
||||
@@ -65,6 +65,15 @@ public interface ICopyEngine
|
||||
/// </summary>
|
||||
Task<int> DropVersionAsync(DropVersionPlan plan, ISyncRemote? remote, CancellationToken ct);
|
||||
|
||||
/// <summary>The photos local sequence <paramref name="sequenceId"/> keeps in two versions, whatever pair made them (owner Q3).</summary>
|
||||
Task<IReadOnlyList<PhotoVersions>> VersionsAsync(Guid sequenceId, CancellationToken ct);
|
||||
|
||||
/// <summary>The dry run of dropping version <paramref name="frameId"/> of a photo sequence <paramref name="sequenceId"/> keeps in two.</summary>
|
||||
Task<OwnVersionDropPlan> PlanDropOwnVersionAsync(Guid sequenceId, Guid frameId, CancellationToken ct);
|
||||
|
||||
/// <summary>Applies <paramref name="plan"/> while the other version is still there, verified by content; returns the frames moved.</summary>
|
||||
Task<int> DropOwnVersionAsync(OwnVersionDropPlan plan, CancellationToken ct);
|
||||
|
||||
/// <summary>Keeps this PC's sequence of a pair whose server copy was deleted, and stops asking.</summary>
|
||||
Task KeepHereAsync(Guid copyId, CancellationToken ct);
|
||||
|
||||
|
||||
Reference in new issue
Block a user