feat: found copies foundation (contracts, migration 0012, store, wire, trash and job hooks, keys)

Owner review 6 asks Chronos to recognise the same time-lapse held under different ids on the
server and on this PC, compare the copies, and keep them apart or integrate and sync them. This
lays the shared foundation the later parcels build on, without any UI or detection yet.

- Migration 0012 adds found_copies (local-server and local-local pairs with evidence, scores,
  answer, policy and the 404 record) and copy_probes; every existing link with a local sequence
  becomes a Linked pair, so a server deletion and the per-link policy have a place.
- FoundCopyStore keeps the pairs: upserts that never touch the answer, a compare-and-set of the
  state with an Integrating backstop (a failed or cancelled job reads as the previous state),
  link promotion and demotion, the once-per-refresh 404 count, the merge's links stage
  (session keys, links reset, pairs moved, refused when both are linked on one server), the
  local overlap queries and the probes. SyncLinkStore.RekeyAsync moves pairs and probes with
  the links in the same transaction.
- Contracts for detection, review, plans, the Integrate and MergeSequences jobs (kinds 25/26,
  High level, new detail steps) and the Upload all rule that keeps suspected, kept-apart,
  deleted, busy and server-born sequences here.
- Wire: POST photos/lookup, uploads into a target (IntoTarget/Copied, trailing and optional),
  frames/delete on the client, capabilities photo-lookup and upload-into, cached per remote.
- The trash plans and deletes accept the job that holds the sequence (its own hold is not
  Busy) and a frames version checked under the lease; a Background job never interrupts a
  running one.
- Settings for linking, the photo policy and projects; the en and it keys of design section 9.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-16 19:39:04 +01:00
1 parent 43719bb5c5
commit 283d04d9cd
57 files changed
+3302 -26

No files matched your search

+8 -4
View File
@@ -145,9 +145,11 @@ public sealed partial class FrameTrash
/// The dry run: the frames of <paramref name="frameIds"/> that go and their size, or why they cannot go. With
/// <paramref name="expectedFramesVersion"/>, frames that changed since the caller read that version block the plan.
/// </summary>
/// <param name="exceptJob">The job asking, when the step runs inside a job that targets the sequence (an Integrate or a
/// merge, owner review 6): its own hold does not make the sequence busy.</param>
/// <exception cref="ArgumentException">The sequence is not in the index, or no frame is named.</exception>
public async Task<FrameDeletePlan> PlanDeleteAsync(Guid sequenceId, IReadOnlyList<Guid> frameIds, int? expectedFramesVersion = null,
CancellationToken cancellationToken = default)
CancellationToken cancellationToken = default, Guid? exceptJob = null)
{
ArgumentNullException.ThrowIfNull(frameIds);
if (frameIds.Count == 0) throw new ArgumentException("No frame is named.", nameof(frameIds));
@@ -162,7 +164,7 @@ public sealed partial class FrameTrash
var paths = new ArchivePaths(archive.RootPath);
var online = ArchiveVolume.Probe(paths) == ArchiveAvailability.Online;
if (!online) blocked.Add(FrameDeleteBlock.Offline);
var busy = await _trash.BusyAsync(cancellationToken).ConfigureAwait(false);
var busy = await _trash.BusyAsync(exceptJob, cancellationToken).ConfigureAwait(false);
if (busy.Contains(sequence.Id) || busy.Contains(sequence.ArchiveId)) blocked.Add(FrameDeleteBlock.Busy);
if (frames.Count != wanted.Count || (expectedFramesVersion is { } expected && expected != sequence.FramesVersion)) blocked.Add(FrameDeleteBlock.FramesChanged);
if (frames.Count > 0 && frames.Count == all.Count) blocked.Add(FrameDeleteBlock.WouldEmpty);
@@ -210,16 +212,18 @@ public sealed partial class FrameTrash
/// written the deletion stands: an index that cannot follow (logged) is resynced by the next scan.
/// </summary>
/// <param name="deletedBy">Who asked (user name or client), kept in the trash record.</param>
/// <param name="exceptJob">The job asking, when it targets the sequence itself (see <see cref="PlanDeleteAsync"/>).</param>
/// <exception cref="StaleDeletePlanException">The plan is blocked, or the sequence changed since it was made; nothing moved.</exception>
/// <exception cref="ArchiveOfflineException">The archive went offline; nothing moved.</exception>
/// <exception cref="IOException">A file is open elsewhere, or the sidecar could not be written; nothing moved.</exception>
public async Task<FrameDeleteResult> DeleteAsync(FrameDeletePlan plan, string? deletedBy = null, JobEngine? followUps = null,
CancellationToken cancellationToken = default)
CancellationToken cancellationToken = default, Guid? exceptJob = null)
{
ArgumentNullException.ThrowIfNull(plan);
var id = plan.Sequence.Id;
if (!plan.CanDelete) throw new StaleDeletePlanException(id);
var revised = await PlanDeleteAsync(id, [.. plan.Frames.Select(f => f.Id)], plan.Sequence.FramesVersion, cancellationToken).ConfigureAwait(false);
var revised = await PlanDeleteAsync(id, [.. plan.Frames.Select(f => f.Id)], plan.Sequence.FramesVersion, cancellationToken, exceptJob)
.ConfigureAwait(false);
var archive = await ArchiveOfAsync(revised.Sequence, cancellationToken).ConfigureAwait(false);
var paths = new ArchivePaths(archive.RootPath);
// Offline since the plan: said as such (ArchiveOfflineException), not as a stale plan.
+20 -8
View File
@@ -148,10 +148,13 @@ public sealed partial class SequenceTrash
/// <summary>The dry run: for each sequence, where its folder goes and how many files and bytes it holds, or why it cannot go.</summary>
/// <param name="progress">Sequences checked so far.</param>
/// <param name="exceptJob">The job asking, when the step runs inside a job that targets the sequences (a merge, owner
/// review 6): its own hold does not make them busy.</param>
/// <exception cref="ArgumentException">A sequence is not in the index.</exception>
public async Task<DeletePlan> PlanAsync(IReadOnlyList<Guid> sequenceIds, IProgress<int>? progress = null, CancellationToken cancellationToken = default)
public async Task<DeletePlan> PlanAsync(IReadOnlyList<Guid> sequenceIds, IProgress<int>? progress = null, CancellationToken cancellationToken = default,
Guid? exceptJob = null)
{
var busy = await BusyAsync(cancellationToken).ConfigureAwait(false);
var busy = await BusyAsync(exceptJob, cancellationToken).ConfigureAwait(false);
var archives = new Dictionary<Guid, ArchiveContext?>();
var steps = new List<DeleteStep>();
var blocked = new List<BlockedDelete>();
@@ -197,16 +200,24 @@ public sealed partial class SequenceTrash
/// busy; sequences before it are in the trash.</exception>
/// <exception cref="InvalidDataException">The sidecar of a sequence with an interrupted journal is damaged; sequences
/// before it are in the trash.</exception>
/// <param name="exceptJob">The job asking, when it targets the sequences itself (see <see cref="PlanAsync"/>).</param>
/// <param name="expectedFramesVersions">
/// The frames version each sequence must still have, checked under the sequence's lease just before its folder moves (a
/// merge: a photo added to the dropped sequence meanwhile refuses that step with <see cref="StaleDeletePlanException"/>,
/// nothing of it moved). Sequences it does not name are not checked.
/// </param>
public async Task<IReadOnlyList<TrashEntry>> DeleteAsync(DeletePlan plan, string? deletedBy = null, IProgress<int>? progress = null,
CancellationToken cancellationToken = default)
CancellationToken cancellationToken = default, Guid? exceptJob = null, IReadOnlyDictionary<Guid, int>? expectedFramesVersions = null)
{
ArgumentNullException.ThrowIfNull(plan);
await RevalidateAsync(plan, cancellationToken).ConfigureAwait(false);
await RevalidateAsync(plan, exceptJob, cancellationToken).ConfigureAwait(false);
var entries = new List<TrashEntry>(plan.Steps.Count);
for (var i = 0; i < plan.Steps.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
if (await DeleteOneAsync(plan.Steps[i], deletedBy, cancellationToken).ConfigureAwait(false) is { } entry) entries.Add(entry);
var step = plan.Steps[i];
int? expected = expectedFramesVersions is not null && expectedFramesVersions.TryGetValue(step.Sequence.Id, out var version) ? version : null;
if (await DeleteOneAsync(step, deletedBy, expected, cancellationToken).ConfigureAwait(false) is { } entry) entries.Add(entry);
progress?.Report(i + 1);
}
return entries;
@@ -350,9 +361,9 @@ public sealed partial class SequenceTrash
}
/// <summary>Checks the plan again just before anything moves, without measuring the folders again; any change refuses it whole.</summary>
private async Task RevalidateAsync(DeletePlan plan, CancellationToken cancellationToken)
private async Task RevalidateAsync(DeletePlan plan, Guid? exceptJob, CancellationToken cancellationToken)
{
var busy = await BusyAsync(cancellationToken).ConfigureAwait(false);
var busy = await BusyAsync(exceptJob, cancellationToken).ConfigureAwait(false);
var archives = new Dictionary<Guid, ArchiveContext?>();
foreach (var step in plan.Steps)
{
@@ -370,7 +381,7 @@ public sealed partial class SequenceTrash
}
}
private async Task<TrashEntry?> DeleteOneAsync(DeleteStep step, string? deletedBy, CancellationToken cancellationToken)
private async Task<TrashEntry?> DeleteOneAsync(DeleteStep step, string? deletedBy, int? expectedFramesVersion, CancellationToken cancellationToken)
{
var sequence = step.Sequence;
var archive = await _db.Archives.GetAsync(sequence.ArchiveId, cancellationToken).ConfigureAwait(false)
@@ -383,6 +394,7 @@ public sealed partial class SequenceTrash
{
var row = await _db.Sequences.GetAsync(sequence.Id, cancellationToken).ConfigureAwait(false);
if (row is null || row.Folder != sequence.Folder) throw new StaleDeletePlanException(sequence.Id);
if (expectedFramesVersion is { } expected && row.FramesVersion != expected) throw new StaleDeletePlanException(sequence.Id);
if (step.TrashFolder is null)
{
await RemoveRowsAsync(archive.Id, row, cancellationToken).ConfigureAwait(false);
@@ -0,0 +1,57 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Chronos.Data.Copies;
/// <summary>
/// The parameters of a <see cref="Core.Model.JobKind.Integrate"/> job: the pair, the choices the job plans again from, the
/// fingerprint of the plan the user confirmed, and whether new photos move by themselves once it is done.
/// </summary>
public sealed record IntegrateJobParameters(Guid CopyId, string Server, Guid LocalId, Guid RemoteId, IntegrateChoices Choices,
string Fingerprint, bool AutoPhotos)
{
public string ToJson() => JsonSerializer.Serialize(this, CopyJobJson.Default.IntegrateJobParameters);
/// <summary>The parameters in <paramref name="json"/>; null when it holds none.</summary>
public static IntegrateJobParameters? Read(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return null;
try
{
return JsonSerializer.Deserialize(json, CopyJobJson.Default.IntegrateJobParameters) is { Server.Length: > 0, Choices: not null } p ? p : null;
}
catch (JsonException)
{
return null;
}
}
}
/// <summary>
/// The parameters of a <see cref="Core.Model.JobKind.MergeSequences"/> job: the pair, the sequence kept and the one that goes
/// to the trash, the choices the job plans again from, and the fingerprint of the plan the user confirmed.
/// </summary>
public sealed record MergeJobParameters(Guid CopyId, Guid KeepId, Guid DropId, MergeChoices Choices, string Fingerprint)
{
public string ToJson() => JsonSerializer.Serialize(this, CopyJobJson.Default.MergeJobParameters);
/// <summary>The parameters in <paramref name="json"/>; null when it holds none.</summary>
public static MergeJobParameters? Read(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return null;
try
{
return JsonSerializer.Deserialize(json, CopyJobJson.Default.MergeJobParameters) is { Choices: not null } p ? p : null;
}
catch (JsonException)
{
return null;
}
}
}
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, UseStringEnumConverter = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
[JsonSerializable(typeof(IntegrateJobParameters))]
[JsonSerializable(typeof(MergeJobParameters))]
internal sealed partial class CopyJobJson : JsonSerializerContext;
+209
View File
@@ -0,0 +1,209 @@
namespace Chronos.Data.Copies;
/// <summary>What a found copy pairs (owner review 6, #73); stored as a number.</summary>
public enum CopyKind
{
/// <summary>A local sequence and a sequence of a server.</summary>
LocalServer = 0,
/// <summary>Two local sequences of this index (stored ordered, the smaller id first).</summary>
LocalLocal = 1,
}
/// <summary>Strongest evidence the pair was found by (stored as a number; never reordered).</summary>
public enum CopyEvidence
{
Link = 0,
SessionKey = 1,
Hashes = 2,
SizeAndTime = 3,
Hints = 4,
}
/// <summary>Where a found copy stands (stored as a number; never reordered).</summary>
public enum CopyState
{
/// <summary>Found and not answered: the user is asked.</summary>
Candidate = 0,
/// <summary>The user kept the two apart; asked again only by a large later change.</summary>
KeptApart = 1,
/// <summary>Linked: sync compares the two; photos move on Upload and Download.</summary>
Linked = 2,
/// <summary>An Integrate or Merge job works on the pair.</summary>
Integrating = 3,
/// <summary>Integrated: linked, and new photos may move by themselves (<see cref="FoundCopy.AutoPhotos"/>).</summary>
Integrated = 4,
}
/// <summary>Settings › Server › Link matches (owner review 6, Q1).</summary>
public enum CopyLinking
{
AskAlways = 0,
WhenIdentical = 1,
WhenHalfShared = 2,
}
/// <summary>
/// Settings › Server › Integrate photos and the dialog's photo choice (owner review 6, Q3). ThisPcWins / OtherWins decide
/// the Different class only; for a local pair ThisPcWins = the kept sequence wins.
/// </summary>
public enum CopyPhotoPolicy
{
Union = 0,
ChoosePerPhoto = 1,
ThisPcWins = 2,
OtherWins = 3,
}
/// <summary>Settings › Server › Integrate projects and the dialog's projects choice (owner review 6, Q5). A merge always copies across.</summary>
public enum CopyProjects
{
CopyAcross = 0,
Leave = 1,
}
/// <summary>A side of a pair: this PC's copy (the kept one of a merge) or the other one.</summary>
public enum CopySide
{
ThisPc = 0,
Other = 1,
}
/// <summary>What detection does with a pair that has no answer yet (<c>CopyRules.Decide</c>).</summary>
public enum CopyDecision
{
/// <summary>Not a pair: nothing is kept.</summary>
None = 0,
/// <summary>Shown as a match found; nothing is linked until the user chooses.</summary>
Ask = 1,
/// <summary>Linked by itself, as the Link matches setting allows.</summary>
Link = 2,
}
/// <summary>The counts of an exact comparison (design §4); ratios in per mille.</summary>
public sealed record CopyScore(int Shared, int SharedUnhashed, int SharedRemoved, int OnlyHere, int OnlyThere, int Differs,
int DeletedHere, int DeletedThere, int Versions, int LocalPhotos, int OtherPhotos, int Containment, int Overlap, int Hints)
{
public static CopyScore None { get; } = new(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
/// <summary>
/// Exactly the same photos: nothing only on one side, nothing different, nothing deleted on one side only, and something
/// shared (owner Q1 "exactly the same photos").
/// </summary>
public bool Identical => OnlyHere == 0 && OnlyThere == 0 && Differs == 0 && DeletedHere == 0 && DeletedThere == 0
&& Shared + SharedUnhashed > 0;
/// <summary>Every shared photo is known by SHA-256 on both sides.</summary>
public bool ByHash => SharedUnhashed == 0;
}
/// <summary>
/// Two copies of one time-lapse whose ids differ (a row of <c>found_copies</c>): a local sequence and a sequence of a server,
/// or two local sequences, with the evidence, the scores of the last comparison, the user's answer and the pair's policy.
/// </summary>
public sealed record FoundCopy
{
public required Guid Id { get; init; }
public required CopyKind Kind { get; init; }
/// <summary>The local sequence; for a local pair the smaller id of the two (<see cref="FoundCopyStore.Order"/>).</summary>
public required Guid LocalId { get; init; }
/// <summary>The server's key (kind 0).</summary>
public string? Server { get; init; }
/// <summary>The server's sequence (kind 0).</summary>
public Guid? RemoteId { get; init; }
/// <summary>The other local sequence (kind 1).</summary>
public Guid? OtherId { get; init; }
public required CopyEvidence Evidence { get; init; }
public CopyState State { get; init; }
/// <summary>The state before Integrating (Candidate, Linked): what a cancelled or failed job returns the pair to.</summary>
public CopyState? PreviousState { get; init; }
public CopyScore Score { get; init; } = CopyScore.None;
public int LocalFramesVersion { get; init; }
public int OtherFramesVersion { get; init; }
public required string Fingerprint { get; init; }
public string? AnsweredFingerprint { get; init; }
public int? AnsweredShared { get; init; }
/// <summary>New photos move both ways by themselves (an integrated pair whose plan left nothing out).</summary>
public bool AutoPhotos { get; init; }
/// <summary>The Integrate or Merge job of an Integrating pair.</summary>
public Guid? JobId { get; init; }
public DateTimeOffset? RemoteGoneAt { get; init; }
/// <summary>404 answers for the remote side, by the server with the link key's own id, on distinct refreshes (design §6.3).</summary>
public int RemoteGoneHits { get; init; }
public DateTimeOffset FoundAt { get; init; }
public DateTimeOffset UpdatedAt { get; init; }
public DateTimeOffset? AnsweredAt { get; init; }
/// <summary>The server confirmed the deletion twice (design §6.3): the pair reads "deleted on server".</summary>
public bool RemoteGone => RemoteGoneHits >= 2;
/// <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>
public bool NeedsAttention => State == CopyState.Candidate || (RemoteGone && State != CopyState.KeptApart)
|| (State is CopyState.Integrated or CopyState.Linked && (Score.DeletedThere > 0 || Score.DeletedHere > 0));
/// <summary>Whether <paramref name="sequenceId"/> is one of the pair's local sequences.</summary>
public bool Names(Guid sequenceId) => LocalId == sequenceId || OtherId == sequenceId;
}
/// <summary>What detection last sent or compared of a local sequence, per scope (a server key, or "" for this PC's archives).</summary>
public sealed record CopyProbe(Guid SequenceId, string Scope, int FramesVersion, int Hashed, DateTimeOffset ProbedAt);
/// <summary>What one detection run found: new pairs, pairs it linked by itself, and kept-apart pairs that ask again.</summary>
public sealed record CopyFindResult(IReadOnlyList<FoundCopy> New, IReadOnlyList<FoundCopy> AutoLinked, IReadOnlyList<FoundCopy> AskedAgain)
{
public static CopyFindResult Empty { get; } = new([], [], []);
public bool IsEmpty => New.Count == 0 && AutoLinked.Count == 0 && AskedAgain.Count == 0;
}
/// <summary>
/// What a state change records (<see cref="FoundCopyStore.SetStateAsync"/>): the fingerprint and shared count a Keep apart
/// was given, the job of an Integrating pair, the pair's auto-photos policy; null members leave the stored value.
/// </summary>
public sealed record CopyAnswer(string? Fingerprint, int? Shared, Guid? JobId, bool? AutoPhotos, DateTimeOffset At);
/// <summary>Two local sequences sharing content: SHA-256 counts, tombstoned content, size and capture time (design §2.4).</summary>
public sealed record LocalOverlap(Guid Low, Guid High, int SharedHashes, int SharedRemoved, int SharedUnhashed);
/// <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>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);
/// <summary>
/// The inputs of 1.1's gate: both unlinked, first captures (to the second), camera models, local hashed count, the server's
/// frame count, and the shared canonical hash count.
/// </summary>
public sealed record SameOriginalsInput(bool BothUnlinked, DateTime? LocalFirst, DateTime? RemoteFirst, string? LocalCamera,
string? RemoteCamera, int LocalHashed, int RemoteFrames, int SharedCanonical);
+173
View File
@@ -0,0 +1,173 @@
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
namespace Chronos.Data.Copies;
/// <summary>The user's choice for one photo under Choose each (nothing preselected: <see cref="Leave"/>).</summary>
public enum PhotoChoice
{
Leave = 0,
Bring = 1,
KeepBoth = 2,
TakeHere = 3,
TakeThere = 4,
}
/// <summary>What a plan does with one photo.</summary>
public enum PhotoAction
{
Send = 0,
Fetch = 1,
SendVersion = 2,
FetchVersion = 3,
TrashHere = 4,
TrashThere = 5,
}
/// <summary>Why a plan cannot be applied (each maps to one <c>Errors.Copies.*</c> key).</summary>
public enum CopyBlock
{
NeedsNewerServer,
NoUploadRight,
NoFetchRight,
NoEditRight,
NoDeleteRight,
LinkTaken,
NoSpace,
Busy,
ArchiveOffline,
DetailsUnchosen,
FolderMoved,
UnsentWorkspace,
BothLinked,
TrashBlocked,
KeptUnchosen,
ChangedFile,
}
/// <summary>The choices of an Integrate: photo policy, per-photo choices (by photo key), per-detail sides (by path), projects.</summary>
public sealed record IntegrateChoices(CopyPhotoPolicy Photos, IReadOnlyDictionary<string, PhotoChoice> PerPhoto,
IReadOnlyDictionary<string, CopySide> Details, CopyProjects Projects);
/// <summary>One photo step of a plan: the photo's key, what is done, the frame it starts from, its name, size and SHA-256.</summary>
public sealed record PhotoStep(string Key, PhotoAction Action, Guid? FrameId, string FileName, long Bytes, string? Sha256);
/// <summary>A photo a trash step takes whose raw SHA-256 nothing else holds (no other frame of this index, nor the other side).</summary>
public sealed record LastCopy(string Key, CopySide Side, string FileName, long Bytes);
/// <summary>A project copied across: from which side, the source, the name it gets at the other home, its versions and head.</summary>
public sealed record ProjectStep(CopySide From, Guid SourceProjectId, string SourceName, string TargetName, int Versions, Guid SourceHeadId);
/// <summary>
/// The dry run of an Integrate of a local sequence with a server sequence (design §5c). Payload is the one portable payload
/// both sides get; LocalPayload and RemotePayload are each side's as planned (the apply-time content check).
/// </summary>
public sealed record IntegratePlan(Guid CopyId, string Server, Guid LocalId, Guid RemoteId, IntegrateChoices Choices,
IReadOnlyList<PhotoStep> Photos, IReadOnlyList<LastCopy> LastCopies, int LeftOut, SyncPayload? Payload,
SyncPayload? LocalPayload, SyncPayload? RemotePayload, int DetailChanges, IReadOnlyList<ProjectStep> Projects,
long FetchBytes, long SendBytes, long FreeBytes, long? QuotaLeftBytes, IReadOnlyList<CopyBlock> Blocks,
int LocalFramesVersion, int LocalSettingsVersion, int RemoteFramesVersion, int RemoteSettingsVersion, string Fingerprint)
{
public bool CanApply => Blocks.Count == 0;
public bool Destructive => Photos.Any(p => p.Action is PhotoAction.TrashHere or PhotoAction.TrashThere);
/// <summary>New photos move by themselves afterwards only when the plan leaves nothing on one side only (design §6.1).</summary>
public bool AutoPhotos => LeftOut == 0;
}
/// <summary>The choices of a merge of two local copies (projects are always copied across: the other's home goes to the trash).</summary>
public sealed record MergeChoices(CopyPhotoPolicy Photos, IReadOnlyDictionary<string, PhotoChoice> PerPhoto,
IReadOnlyDictionary<string, CopySide> Details);
/// <summary>A render of the dropped sequence that moves to the kept one (its row keeps its id).</summary>
public sealed record RenderStep(Guid RenderId, string FileName, long Bytes, string? Sha256);
/// <summary>The dry run of a merge of two local sequences into the kept one (design §5d).</summary>
public sealed record MergePlan(Guid CopyId, Guid KeepId, Guid DropId, MergeChoices Choices, IReadOnlyList<PhotoStep> Photos,
IReadOnlyList<LastCopy> LastCopies, IReadOnlyList<RenderStep> Renders, SyncPayload? Payload, int DetailChanges,
IReadOnlyList<ProjectStep> Projects, IReadOnlyList<string> SessionKeys, IReadOnlyList<string> SkippedSessionKeys,
IReadOnlyList<string> Links, DeletePlan Trash, long CopyBytes, long FreeBytes, IReadOnlyList<CopyBlock> Blocks,
int KeepFramesVersion, int KeepSettingsVersion, int DropFramesVersion, int DropSettingsVersion, string Fingerprint)
{
public bool CanApply => Blocks.Count == 0;
}
/// <summary>
/// What the planners need to know of this PC and the signed-in account: names, rights (OwnsOrAdmin: of the server sequence),
/// 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,
bool OwnsOrAdmin, bool KeepsProjects, long? QuotaLeft, IReadOnlySet<Guid> UnsentWorkspaceSequences,
IReadOnlySet<Guid> ServerOriginalsArchives);
/// <summary>The server-side dry run of moving photos of a pair's server sequence to the server's trash (design §6.2).</summary>
public sealed record TrashTherePlan(Guid CopyId, string Server, Guid RemoteId, IReadOnlyList<Guid> FrameIds, IReadOnlyList<string> Keys, int Photos,
long Bytes, int FramesVersion, IReadOnlyList<LastCopy> LastCopies);
/// <summary>
/// The journal of one project copied to another home: the intended name, when it was asked, the copy once made, the version
/// the copy was made from, and the versions pushed so far (source version id to the copy's).
/// </summary>
public sealed record TransplantStep(string Intent, DateTimeOffset Asked, Guid? TargetId, Guid? BaseId, int BaseNumber,
IReadOnlyList<TransplantMove> Moves);
/// <summary>A version of the source project and its copy at the other home.</summary>
public sealed record TransplantMove(Guid Source, Guid Copy);
/// <summary>Copies a project with its whole history from one home to another (ProjectTransplant).</summary>
public interface IProjectCopier
{
Task<SequenceProject> CopyAsync(IProjectHome from, SequenceProject source, IProjectHome to, string name,
TransplantStep? journal, Func<TransplantStep, ValueTask> save, CancellationToken ct);
}
/// <summary>Whether a sequence has workspace projects with unsent versions or unsaved work (a merge waits for them).</summary>
public interface IWorkspaceGuard
{
Task<bool> HasUnsentAsync(Guid sequenceId, CancellationToken ct);
}
/// <summary>The sequences changed since the plan was made: nothing was applied; the pair goes back to its previous state.</summary>
public sealed class StaleCopyPlanException : InvalidOperationException
{
public StaleCopyPlanException()
: base(Loc.L("Errors.Copies.StalePlan"))
{
}
public StaleCopyPlanException(string message)
: base(message)
{
}
public StaleCopyPlanException(string message, Exception inner)
: base(message, inner)
{
}
}
/// <summary>A sequence of the pair is already linked to another sequence of that server: nothing was changed.</summary>
public sealed class CopyLinkTakenException : InvalidOperationException
{
public CopyLinkTakenException()
: base(Loc.L("Errors.Copies.LinkTaken", string.Empty, string.Empty))
{
}
public CopyLinkTakenException(string message)
: base(message)
{
}
public CopyLinkTakenException(string message, Exception inner)
: base(message, inner)
{
}
/// <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));
}
@@ -0,0 +1,42 @@
using Chronos.Core.Model;
using Chronos.Data.Sync;
namespace Chronos.Data.Copies;
/// <summary>One difference of title, tags, rating, notes or settings between two copies (a JSON path, both values as shown).</summary>
public sealed record DetailLine(string Path, string? Here, string? There);
/// <summary>A project of one home, as the Projects part lists it.</summary>
public sealed record ProjectLine(Guid Id, string Name, bool IsMain, int Versions, Guid HeadId, string HeadHash, DateTimeOffset UpdatedAt);
/// <summary>
/// Both homes' projects. MainSame: the two Main heads make the same choices; ThereKeepsProjects: the other home keeps
/// projects (a server without the <c>projects</c> capability keeps none).
/// </summary>
public sealed record CopyProjectsView(IReadOnlyList<ProjectLine> Here, IReadOnlyList<ProjectLine> There, bool MainSame, bool ThereKeepsProjects);
/// <summary>Renders of each side, and those both hold (by render id, or by SHA-256 where both record one).</summary>
public sealed record CopyRendersView(int Here, int There, int Shared, long HereBytes, long ThereBytes);
/// <summary>
/// The facts of one side: title, where it lies (archive or server name), photos, bytes, capture range, camera, hashed count,
/// origin, the servers the local copy is linked to, and whether it lies in a server's originals archive.
/// </summary>
public sealed record CopyFacts(string Title, string Where, Guid? ArchiveId, int Photos, long Bytes, DateTime? First, DateTime? Last,
string? Camera, int Hashed, SequenceOrigin? Origin, IReadOnlyList<string> Servers, bool InOriginalsArchive);
/// <summary>What the Compare dialog shows of a pair: both sides, the photos, the details line by line, projects, renders, and what can be done.</summary>
public sealed record CopyReview(FoundCopy Copy, CopyFacts Here, CopyFacts There, CopyComparisonResult Photos,
IReadOnlyList<DetailLine> Details, CopyProjectsView Projects, CopyRendersView Renders, CopyCapabilities Can);
/// <summary>Whether Integrate (or Merge), Link only and Delete on server are possible, and why not (<see cref="CopyBlock"/>s).</summary>
public sealed record CopyCapabilities(bool Integrate, bool LinkOnly, bool DeleteThere, IReadOnlyList<CopyBlock> Blocks);
/// <summary>A row of Server › Matches: the pair with the facts of both sides (the other side's from the server listing or the other archive).</summary>
public sealed record FoundCopyView(FoundCopy Copy, CopyFacts Here, CopyFacts There);
/// <summary>
/// The same time-lapse with workspace projects at two homes (a linked or integrated pair): the Edit picker marks each as the
/// other's twin. LocalHome names the local copy's archive; a project name is null when that home has no workspace project.
/// </summary>
public sealed record CopyTwin(Guid CopyId, Guid LocalId, string LocalHome, string? LocalProject, string Server, Guid RemoteId, string? ServerProject);
+565
View File
@@ -0,0 +1,565 @@
using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Repositories;
using Chronos.Data.Sync;
namespace Chronos.Data.Copies;
/// <summary>
/// The <c>found_copies</c> and <c>copy_probes</c> tables (owner review 6, #73; migration 0012): pairs of copies of one
/// time-lapse, their scores, answers and policies, and what detection last probed. <c>sync_links</c> stays the 1:1 record a
/// sync compares; every link has a row here too (evidence <see cref="CopyEvidence.Link"/>). A local pair is stored once,
/// ordered (<see cref="Order"/>).
/// </summary>
public sealed class FoundCopyStore(ChronosDatabase db, TimeProvider? time = null)
{
private const string Columns =
"id, kind, local_id, server, remote_id, other_id, evidence, state, shared, shared_unhashed, shared_removed, only_here, only_there, " +
"differs, deleted_here, deleted_there, versions, local_photos, other_photos, containment, overlap, hints, local_frames_version, " +
"other_frames_version, fingerprint, answered_fingerprint, answered_shared, auto_photos, job_id, previous_state, remote_gone_at, " +
"remote_gone_hits, found_at, updated_at, answered_at";
/// <summary>
/// The state a row reads as: an Integrating row whose job is Failed, Cancelled or missing reads as its previous state
/// (the backstop for a crash before the job could set it back; a Done job's handler sets the end state itself).
/// </summary>
private const string Effective =
"(CASE WHEN found_copies.state = 3 AND (found_copies.job_id IS NULL OR NOT EXISTS (SELECT 1 FROM jobs j " +
"WHERE j.id = found_copies.job_id AND j.state NOT IN (4, 5))) THEN COALESCE(found_copies.previous_state, 0) " +
"ELSE found_copies.state END)";
private static readonly string Select = $"SELECT {Columns}, {Effective} AS effective_state FROM found_copies";
private static readonly string ProbeUpsert = SqlDialect.Upsert("copy_probes", ["sequence_id", "scope", "frames_version", "hashed", "probed_at"], 2);
/// <summary>The refresh that last counted a 404 for each remote, per database (a refresh id is new after every start).</summary>
private static readonly ConditionalWeakTable<IDatabase, ConcurrentDictionary<(string Server, Guid RemoteId), Guid>> GoneRefreshes = new();
private static readonly CopyState[] Ranks = [CopyState.Candidate, CopyState.Linked, CopyState.KeptApart, CopyState.Integrated, CopyState.Integrating];
private readonly DbAccess _db = new(db.Database);
private readonly TimeProvider _time = time ?? TimeProvider.System;
/// <summary>The order a local pair is stored in: the smaller id by ordinal comparison of the "D" strings (PostgreSQL's uuid order).</summary>
public static (Guid Low, Guid High) Order(Guid a, Guid b) =>
string.CompareOrdinal(a.ToString("D"), b.ToString("D")) <= 0 ? (a, b) : (b, a);
/// <summary>Every row, oldest first.</summary>
public Task<IReadOnlyList<FoundCopy>> ListAsync(CancellationToken ct) =>
_db.ListAsync($"{Select} ORDER BY found_at, id", [], Map, ct);
/// <summary>The local↔server rows of <paramref name="server"/>.</summary>
public Task<IReadOnlyList<FoundCopy>> ListByServerAsync(string server, CancellationToken ct) =>
_db.ListAsync($"{Select} WHERE kind = 0 AND server = $1 ORDER BY found_at, id", [server], Map, ct);
/// <summary>The rows naming <paramref name="sequenceId"/> on either local side.</summary>
public Task<IReadOnlyList<FoundCopy>> ListByLocalAsync(Guid sequenceId, CancellationToken ct) =>
_db.ListAsync($"{Select} WHERE local_id = $1 OR other_id = $1 ORDER BY found_at, id", [sequenceId], Map, ct);
public Task<FoundCopy?> GetAsync(Guid id, CancellationToken ct) =>
_db.SingleAsync($"{Select} WHERE id = $1", [id], Map, ct);
public Task<FoundCopy?> FindRemoteAsync(Guid localId, string server, Guid remoteId, CancellationToken ct) =>
FindRemoteAsync(_db, localId, server, remoteId, ct);
public Task<FoundCopy?> FindLocalAsync(Guid a, Guid b, CancellationToken ct)
{
var (low, high) = Order(a, b);
return _db.SingleAsync($"{Select} WHERE kind = 1 AND local_id = $1 AND other_id = $2", [low, high], Map, ct);
}
/// <summary>
/// Inserts a new row, or updates evidence (the stronger is kept), scores, versions and fingerprint of the row of the same
/// pair; never its state, answer, policy or job (those change only through <see cref="SetStateAsync"/>). A local pair
/// given in the other order is stored ordered, its sides swapped. Returns the stored row.
/// </summary>
public async Task<FoundCopy> UpsertFoundAsync(FoundCopy copy, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(copy);
copy = Normalised(copy);
var now = _time.GetUtcNow();
return await _db.InTransactionAsync(async session =>
{
var inner = new DbAccess(session);
var existing = copy.Kind == CopyKind.LocalServer
? await FindRemoteAsync(inner, copy.LocalId, copy.Server!, copy.RemoteId!.Value, ct).ConfigureAwait(false)
: await inner.SingleAsync($"{Select} WHERE kind = 1 AND local_id = $1 AND other_id = $2", [copy.LocalId, copy.OtherId!.Value], Map, ct)
.ConfigureAwait(false);
var s = copy.Score;
if (existing is null)
{
var id = copy.Id == Guid.Empty ? Guid.NewGuid() : copy.Id;
await InsertAsync(inner, copy with { Id = id, FoundAt = copy.FoundAt == default ? now : copy.FoundAt }, now, ct).ConfigureAwait(false);
return (await inner.SingleAsync($"{Select} WHERE id = $1", [id], Map, ct).ConfigureAwait(false))!;
}
await inner.ExecuteAsync(
"UPDATE found_copies SET evidence = $2, shared = $3, shared_unhashed = $4, shared_removed = $5, only_here = $6, only_there = $7, " +
"differs = $8, deleted_here = $9, deleted_there = $10, versions = $11, local_photos = $12, other_photos = $13, containment = $14, " +
"overlap = $15, hints = $16, local_frames_version = $17, other_frames_version = $18, fingerprint = $19, updated_at = $20 WHERE id = $1",
[
existing.Id, Math.Min((int)existing.Evidence, (int)copy.Evidence), s.Shared, s.SharedUnhashed, s.SharedRemoved, s.OnlyHere,
s.OnlyThere, s.Differs, s.DeletedHere, s.DeletedThere, s.Versions, s.LocalPhotos, s.OtherPhotos, s.Containment, s.Overlap,
s.Hints, copy.LocalFramesVersion, copy.OtherFramesVersion, copy.Fingerprint, now,
], ct).ConfigureAwait(false);
return (await inner.SingleAsync($"{Select} WHERE id = $1", [existing.Id], Map, ct).ConfigureAwait(false))!;
}, ct).ConfigureAwait(false);
}
/// <summary>
/// Compare-and-set of the state (<paramref name="expected"/> null: any), against the state the row reads as. False when
/// the row moved on meanwhile or is gone. Entering <see cref="CopyState.Integrating"/> needs the job
/// (<see cref="CopyAnswer.JobId"/>) and stores the state it leaves as <see cref="FoundCopy.PreviousState"/>; leaving it
/// clears both. The answer's fingerprint and shared count (a Keep apart) and its time are recorded when given; auto
/// photos hold only for <see cref="CopyState.Integrated"/> (any other state clears them).
/// </summary>
public async Task<bool> SetStateAsync(Guid id, CopyState? expected, CopyState state, CopyAnswer? answer, CancellationToken ct)
{
if (state == CopyState.Integrating && answer?.JobId is null)
throw new ArgumentException("A pair enters Integrating with the job that integrates it.", nameof(answer));
var now = _time.GetUtcNow();
var integrating = state == CopyState.Integrating;
var changed = await _db.ExecuteAsync(
"UPDATE found_copies SET " +
$"previous_state = {(integrating ? $"CASE WHEN {Effective} = 3 THEN previous_state ELSE {Effective} END" : "NULL")}, " +
$"job_id = {(integrating ? "$3" : "NULL")}, " +
"state = $2, " +
"answered_fingerprint = COALESCE($4, answered_fingerprint), " +
"answered_shared = COALESCE($5, answered_shared), " +
"answered_at = COALESCE($6, answered_at), " +
"auto_photos = CASE WHEN $2 = 4 THEN COALESCE($7, auto_photos) ELSE $8 END, " +
"updated_at = $9 " +
$"WHERE id = $1{(expected is { } e ? $" AND {Effective} = {(int)e}" : string.Empty)}",
[
id, (int)state, answer?.JobId, DbParam.Text(answer?.Fingerprint), answer?.Shared,
(DateTimeOffset?)answer?.At, answer?.AutoPhotos, false, now,
], ct).ConfigureAwait(false);
return changed == 1;
}
/// <summary>The counts of a new exact comparison, at the frames versions it read.</summary>
public Task UpdateScoreAsync(Guid id, CopyScore score, int localFramesVersion, int otherFramesVersion, string fingerprint, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(score);
ArgumentNullException.ThrowIfNull(fingerprint);
var s = score;
return _db.ExecuteAsync(
"UPDATE found_copies SET shared = $2, shared_unhashed = $3, shared_removed = $4, only_here = $5, only_there = $6, differs = $7, " +
"deleted_here = $8, deleted_there = $9, versions = $10, local_photos = $11, other_photos = $12, containment = $13, overlap = $14, " +
"hints = $15, local_frames_version = $16, other_frames_version = $17, fingerprint = $18, updated_at = $19 WHERE id = $1",
[
id, s.Shared, s.SharedUnhashed, s.SharedRemoved, s.OnlyHere, s.OnlyThere, s.Differs, s.DeletedHere, s.DeletedThere, s.Versions,
s.LocalPhotos, s.OtherPhotos, s.Containment, s.Overlap, s.Hints, localFramesVersion, otherFramesVersion, fingerprint, _time.GetUtcNow(),
], ct);
}
/// <summary>
/// The row of a link (evidence Link, state Linked) when it has none; the link's row otherwise kept (moved to Linked when it
/// was a Candidate). Any other Linked or Integrated row of the same server sequence, or of the same local sequence and
/// server, is demoted to Candidate (a link re-pointed to another copy: sync_links holds one link per side and server).
/// </summary>
public Task<FoundCopy> EnsureLinkedAsync(string server, Guid remoteId, Guid localId, CancellationToken ct)
{
ArgumentException.ThrowIfNullOrWhiteSpace(server);
return _db.InTransactionAsync(session => EnsureLinkedAsync(new DbAccess(session), server, remoteId, localId, ct), ct);
}
private async Task<FoundCopy> EnsureLinkedAsync(DbAccess inner, string server, Guid remoteId, Guid localId, CancellationToken ct)
{
var now = _time.GetUtcNow();
var row = await FindRemoteAsync(inner, localId, server, remoteId, ct).ConfigureAwait(false);
if (row is null)
{
row = LinkRow(server, remoteId, localId, now);
await InsertAsync(inner, row, now, ct).ConfigureAwait(false);
}
else if (row.State == CopyState.Candidate)
{
await inner.ExecuteAsync("UPDATE found_copies SET state = 2, previous_state = NULL, job_id = NULL, auto_photos = $2, updated_at = $3 WHERE id = $1",
[row.Id, false, now], ct).ConfigureAwait(false);
}
await DemoteAsync(inner, server, remoteId, localId, now, ct).ConfigureAwait(false);
return (await inner.SingleAsync($"{Select} WHERE id = $1", [row.Id], Map, ct).ConfigureAwait(false))!;
}
/// <summary>
/// A 404 for the remote side (design §6.3): nothing when <paramref name="localId"/> is null (an observation-only link);
/// else the pair's row (made when the link had none) counts one hit per <paramref name="refreshId"/> and every Candidate
/// row naming that remote is deleted.
/// </summary>
public async Task MarkRemoteGoneAsync(string server, Guid remoteId, Guid? localId, Guid refreshId, DateTimeOffset at, CancellationToken ct)
{
ArgumentException.ThrowIfNullOrWhiteSpace(server);
if (localId is not { } local) return;
var refreshes = GoneRefreshes.GetOrCreateValue(db.Database);
var counted = refreshes.TryGetValue((server, remoteId), out var last) && last == refreshId;
await _db.InTransactionAsync(async session =>
{
var inner = new DbAccess(session);
var row = await FindRemoteAsync(inner, local, server, remoteId, ct).ConfigureAwait(false);
if (row is null)
{
row = LinkRow(server, remoteId, local, _time.GetUtcNow());
await InsertAsync(inner, row, _time.GetUtcNow(), ct).ConfigureAwait(false);
}
if (!counted)
{
await inner.ExecuteAsync(
"UPDATE found_copies SET remote_gone_hits = remote_gone_hits + 1, remote_gone_at = COALESCE(remote_gone_at, $2), updated_at = $3 WHERE id = $1",
[row.Id, at, _time.GetUtcNow()], ct).ConfigureAwait(false);
}
await inner.ExecuteAsync($"DELETE FROM found_copies WHERE kind = 0 AND server = $1 AND remote_id = $2 AND id <> $3 AND {Effective} = 0",
[server, remoteId, row.Id], ct).ConfigureAwait(false);
return 0;
}, ct).ConfigureAwait(false);
refreshes[(server, remoteId)] = refreshId;
}
/// <summary>The server answered for the remote again: hits back to 0, no gone time.</summary>
public Task ClearRemoteGoneAsync(string server, Guid remoteId, CancellationToken ct)
{
if (GoneRefreshes.TryGetValue(db.Database, out var refreshes)) refreshes.TryRemove((server, remoteId), out _);
return _db.ExecuteAsync(
"UPDATE found_copies SET remote_gone_hits = 0, remote_gone_at = NULL, updated_at = $3 " +
"WHERE kind = 0 AND server = $1 AND remote_id = $2 AND (remote_gone_hits <> 0 OR remote_gone_at IS NOT NULL)",
[server, remoteId, _time.GetUtcNow()], ct);
}
public Task DeleteAsync(Guid id, CancellationToken ct) =>
_db.ExecuteAsync("DELETE FROM found_copies WHERE id = $1", [id], ct);
/// <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
/// matching the link that survived wins (the moved one when its remote is in <paramref name="survivingLinkRemotes"/>, the
/// one already under the new key otherwise); else the higher state (Integrating, Integrated, Kept apart, Linked,
/// Candidate), then the newer update. Linked and Integrated rows no surviving link backs become Candidates.
/// </summary>
internal async Task<(int Moved, int Dropped)> RekeyAsync(IDbSession session, string from, string to, IReadOnlySet<Guid> survivingLinkRemotes,
CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(session);
ArgumentNullException.ThrowIfNull(survivingLinkRemotes);
if (string.Equals(from, to, StringComparison.Ordinal)) return (0, 0);
var inner = new DbAccess(session);
var now = _time.GetUtcNow();
var old = await inner.ListAsync($"{Select} WHERE kind = 0 AND server = $1 ORDER BY found_at, id", [from], Map, ct).ConfigureAwait(false);
var current = (await inner.ListAsync($"{Select} WHERE kind = 0 AND server = $1 ORDER BY found_at, id", [to], Map, ct).ConfigureAwait(false)).ToList();
var links = (await inner.ListAsync("SELECT remote_id, local_id FROM sync_links WHERE server = $1 AND local_id IS NOT NULL", [to],
r => (Remote: r.GetGuid(0), Local: r.GetGuid(1)), ct).ConfigureAwait(false)).ToDictionary(l => l.Remote, l => l.Local);
var (moved, dropped) = (0, 0);
foreach (var row in old)
{
var clash = current.FirstOrDefault(c => c.LocalId == row.LocalId && c.RemoteId == row.RemoteId);
if (clash is not null)
{
var backed = links.TryGetValue(row.RemoteId!.Value, out var linked) && linked == row.LocalId;
var keepMoved = backed ? survivingLinkRemotes.Contains(row.RemoteId.Value) : Wins(row, clash);
var loser = keepMoved ? clash : row;
await inner.ExecuteAsync("DELETE FROM found_copies WHERE id = $1", [loser.Id], ct).ConfigureAwait(false);
dropped++;
if (!keepMoved) continue;
current.Remove(clash);
}
await inner.ExecuteAsync("UPDATE found_copies SET server = $2 WHERE id = $1", [row.Id, to], ct).ConfigureAwait(false);
current.Add(row with { Server = to });
moved++;
}
// Rows no link backs any more (a link of the old key lost to the new key's, or the other way round).
foreach (var row in current.Where(c => c.State is CopyState.Linked or CopyState.Integrated))
{
if (links.TryGetValue(row.RemoteId!.Value, out var local) && local == row.LocalId) continue;
if (!links.ContainsKey(row.RemoteId.Value) && !links.ContainsValue(row.LocalId)) continue;
await inner.ExecuteAsync("UPDATE found_copies SET state = 0, auto_photos = $2, updated_at = $3 WHERE id = $1 AND state IN (2, 4)",
[row.Id, false, now], ct).ConfigureAwait(false);
}
await inner.ExecuteAsync(
"DELETE FROM copy_probes WHERE scope = $1 AND sequence_id IN (SELECT sequence_id FROM copy_probes WHERE scope = $2)", [from, to], ct)
.ConfigureAwait(false);
await inner.ExecuteAsync("UPDATE copy_probes SET scope = $2 WHERE scope = $1", [from, to], ct).ConfigureAwait(false);
return (moved, dropped);
static bool Wins(FoundCopy moving, FoundCopy staying)
{
var (a, b) = (Array.IndexOf(Ranks, moving.State), Array.IndexOf(Ranks, staying.State));
return a != b ? a > b : moving.UpdatedAt > staying.UpdatedAt;
}
}
/// <summary>
/// The links stage of a merge (design §5d), one transaction: session keys, links and pairs of <paramref name="drop"/>
/// move to <paramref name="keep"/>. A key <paramref name="keepArchiveId"/> already maps to a third sequence is skipped
/// (returned in <see cref="MoveResult.SkippedKeys"/>). Links take keep with their agreement reset (the next comparison
/// agrees equal payloads and makes a Conflict of different ones, never a push). Pairs naming drop name keep; a pair of
/// keep with itself is deleted; on a clash keep's row stays; moved Integrated pairs become Linked without auto photos.
/// The pair <paramref name="exceptCopyId"/> (the merge's own) is left untouched. Refused before any change
/// (<see cref="CopyLinkTakenException"/>) when keep and drop are linked to sequences of one server. Idempotent.
/// </summary>
public Task<MoveResult> MoveToKeptAsync(Guid drop, Guid keep, Guid keepArchiveId, IReadOnlyCollection<string> sessionKeys, Guid? exceptCopyId,
CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(sessionKeys);
if (drop == keep) throw new ArgumentException("A sequence is never merged into itself.", nameof(keep));
var now = _time.GetUtcNow();
return _db.InTransactionAsync(async session =>
{
var inner = new DbAccess(session);
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));
// (1) Session keys.
var (keys, skipped) = (0, new List<string>());
foreach (var key in sessionKeys.Distinct(StringComparer.Ordinal))
{
var holder = await inner.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)
{
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",
[keepArchiveId, key, keep], ct).ConfigureAwait(false);
keys++;
}
else if (holder == drop)
{
await inner.ExecuteAsync("UPDATE sequence_sessions SET sequence_id = $3 WHERE archive_id = $1 AND session_key = $2",
[keepArchiveId, key, keep], ct).ConfigureAwait(false);
keys++;
}
else if (holder != keep)
{
skipped.Add(key);
continue;
}
await inner.ExecuteAsync("DELETE FROM sequence_sessions WHERE sequence_id = $1 AND session_key = $2", [drop, key], ct).ConfigureAwait(false);
}
// (2) Links, with the agreement reset as SyncService's LinkAsync resets a link it points at another copy.
var links = await inner.ExecuteAsync(
"UPDATE sync_links SET local_id = $2, base_local_settings = NULL, base_remote_settings = NULL, diff_local_frames = NULL, " +
"diff_remote_frames = NULL, diff_local_renders = NULL, diff_remote_renders = NULL, diff_remote_updated_at = NULL, missing_remote = 0, " +
"missing_local = 0, exports_to_get = 0, exports_to_get_bytes = 0, exports_to_send = 0, exports_to_send_bytes = 0, " +
"conflict_local_settings = NULL, conflict_remote_settings = NULL, conflict_remote = NULL WHERE local_id = $1",
[drop, keep], ct).ConfigureAwait(false);
// (3) Pairs.
var pairs = 0;
var rows = await inner.ListAsync($"{Select} WHERE local_id = $1 OR other_id = $1 ORDER BY found_at, id", [drop], Map, ct).ConfigureAwait(false);
foreach (var row in rows.Where(r => r.Id != exceptCopyId))
{
var state = row.State == CopyState.Integrated ? CopyState.Linked : row.State;
if (row.Kind == CopyKind.LocalServer)
{
if (await FindRemoteAsync(inner, keep, row.Server!, row.RemoteId!.Value, ct).ConfigureAwait(false) is not null)
{
await inner.ExecuteAsync("DELETE FROM found_copies WHERE id = $1", [row.Id], ct).ConfigureAwait(false);
continue;
}
await inner.ExecuteAsync(
"UPDATE found_copies SET local_id = $2, state = $3, auto_photos = $4, local_frames_version = -1, updated_at = $5 WHERE id = $1",
[row.Id, keep, (int)state, false, now], ct).ConfigureAwait(false);
pairs++;
continue;
}
var other = row.LocalId == drop ? row.OtherId!.Value : row.LocalId;
if (other == keep)
{
await inner.ExecuteAsync("DELETE FROM found_copies WHERE id = $1", [row.Id], ct).ConfigureAwait(false);
continue;
}
var (low, high) = Order(keep, other);
if (await inner.SingleAsync($"{Select} WHERE kind = 1 AND local_id = $1 AND other_id = $2", [low, high], Map, ct).ConfigureAwait(false) is not null)
{
await inner.ExecuteAsync("DELETE FROM found_copies WHERE id = $1", [row.Id], ct).ConfigureAwait(false);
continue;
}
await inner.ExecuteAsync(
"UPDATE found_copies SET local_id = $2, other_id = $3, state = $4, auto_photos = $5, local_frames_version = -1, " +
"other_frames_version = -1, updated_at = $6 WHERE id = $1",
[row.Id, low, high, (int)state, false, now], ct).ConfigureAwait(false);
pairs++;
}
return new MoveResult(keys, skipped, links, pairs);
}, ct);
}
public Task<CopyProbe?> GetProbeAsync(Guid sequenceId, string scope, CancellationToken ct) =>
_db.SingleAsync("SELECT sequence_id, scope, frames_version, hashed, probed_at 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)), ct);
public Task SetProbeAsync(CopyProbe probe, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(probe);
return _db.ExecuteAsync(ProbeUpsert, [probe.SequenceId, probe.Scope, probe.FramesVersion, probe.Hashed, probe.ProbedAt], ct);
}
/// <summary>Forgets what was probed in <paramref name="scope"/>: the next detection probes every sequence again (Find matches).</summary>
public Task ResetProbesAsync(string scope, CancellationToken ct) =>
_db.ExecuteAsync("DELETE FROM copy_probes WHERE scope = $1", [scope], ct);
/// <summary>
/// Local pairs sharing SHA-256 (frames ⋈ frames), tombstoned content (frame_removals ⋈ frames) and, only while the index
/// has unhashed frames, size and capture time (frames ⋈ frames), one row per pair, ordered (<see cref="Order"/>).
/// </summary>
public async Task<IReadOnlyList<LocalOverlap>> LocalOverlapsAsync(CancellationToken ct)
{
var pairs = new Dictionary<(Guid, Guid), (int Hashes, int Removed, int Unhashed)>();
var byHash = await _db.ListAsync(
"SELECT a.sequence_id, b.sequence_id, count(DISTINCT a.sha256) FROM frames a " +
"JOIN frames b ON b.sha256 = a.sha256 AND b.sequence_id > a.sequence_id " +
"WHERE a.sha256 IS NOT NULL AND a.sha256 <> '' GROUP BY a.sequence_id, b.sequence_id",
[], Row, ct).ConfigureAwait(false);
foreach (var (a, b, n) in byHash) Add(a, b, n, 0, 0);
var byRemoval = await _db.ListAsync(
"SELECT r.sequence_id, f.sequence_id, count(DISTINCT r.sha256) FROM frame_removals r " +
"JOIN frames f ON f.sha256 = r.sha256 AND f.sequence_id <> r.sequence_id GROUP BY r.sequence_id, f.sequence_id",
[], Row, ct).ConfigureAwait(false);
foreach (var (a, b, n) in byRemoval) Add(a, b, 0, n, 0);
var unhashed = await _db.ScalarAsync<long?>("SELECT 1 FROM frames WHERE sha256 IS NULL OR sha256 = '' LIMIT 1", [], ct).ConfigureAwait(false);
if (unhashed is not null)
{
var bySize = await _db.ListAsync(
"SELECT a.sequence_id, b.sequence_id, count(*) FROM frames a " +
"JOIN frames b ON b.captured_at = a.captured_at AND b.size = a.size AND b.sequence_id > a.sequence_id " +
"WHERE a.captured_at IS NOT NULL AND (a.sha256 IS NULL OR a.sha256 = '' OR b.sha256 IS NULL OR b.sha256 = '') " +
"GROUP BY a.sequence_id, b.sequence_id",
[], Row, ct).ConfigureAwait(false);
foreach (var (a, b, n) in bySize) Add(a, b, 0, 0, n);
}
return [.. pairs.Select(p => new LocalOverlap(p.Key.Item1, p.Key.Item2, p.Value.Hashes, p.Value.Removed, p.Value.Unhashed))
.OrderBy(o => o.Low.ToString("D"), StringComparer.Ordinal).ThenBy(o => o.High.ToString("D"), StringComparer.Ordinal)];
void Add(Guid a, Guid b, int hashes, int removed, int unhashedCount)
{
var key = Order(a, b);
var known = pairs.GetValueOrDefault(key);
pairs[key] = (known.Hashes + hashes, known.Removed + removed, known.Unhashed + unhashedCount);
}
static (Guid, Guid, int) Row(DbRow r) => (r.GetGuid(0), r.GetGuid(1), r.GetInt32(2));
}
/// <summary>The download back-references <c>chronos-sync:&lt;remoteId:N&gt;</c> of local sequences (sequence_sessions).</summary>
public async Task<IReadOnlyList<(Guid SequenceId, Guid RemoteId)>> SyncSessionKeysAsync(CancellationToken ct)
{
const string prefix = "chronos-sync:";
var rows = await _db.ListAsync("SELECT sequence_id, session_key FROM sequence_sessions WHERE session_key LIKE $1 ORDER BY sequence_id, session_key",
[prefix + "%"], r => (Sequence: r.GetGuid(0), Key: r.GetString(1)), ct).ConfigureAwait(false);
var result = new List<(Guid, Guid)>();
foreach (var (sequence, key) in rows)
{
if (!key.StartsWith(prefix, StringComparison.Ordinal)) continue;
if (Guid.TryParseExact(key.AsSpan(prefix.Length), "N", out var remote)) result.Add((sequence, remote));
}
return [.. result.Distinct()];
}
// ---------------- Helpers ----------------
private static Task<FoundCopy?> FindRemoteAsync(DbAccess access, Guid localId, string server, Guid remoteId, CancellationToken ct) =>
access.SingleAsync($"{Select} WHERE kind = 0 AND local_id = $1 AND server = $2 AND remote_id = $3", [localId, server, remoteId], Map, ct);
/// <summary>Linked and Integrated rows of the server sequence with another local copy, or of the local copy with another server sequence, become Candidates.</summary>
private static Task<int> DemoteAsync(DbAccess access, string server, Guid remoteId, Guid localId, DateTimeOffset now, CancellationToken ct) =>
access.ExecuteAsync(
"UPDATE found_copies SET state = 0, auto_photos = $4, updated_at = $5 WHERE kind = 0 AND server = $1 AND state IN (2, 4) " +
"AND ((remote_id = $2 AND local_id <> $3) OR (local_id = $3 AND remote_id <> $2))",
[server, remoteId, localId, false, now], ct);
private static FoundCopy LinkRow(string server, Guid remoteId, Guid localId, DateTimeOffset now) => new()
{
Id = Guid.NewGuid(),
Kind = CopyKind.LocalServer,
LocalId = localId,
Server = server,
RemoteId = remoteId,
Evidence = CopyEvidence.Link,
State = CopyState.Linked,
Fingerprint = "link",
FoundAt = now,
UpdatedAt = now,
};
private static Task<int> InsertAsync(DbAccess access, FoundCopy c, DateTimeOffset now, CancellationToken ct)
{
var s = c.Score;
return access.ExecuteAsync(
$"INSERT INTO found_copies ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, " +
"$21, $22, $23, $24, $25, $26, $27, $28, $29, $30, $31, $32, $33, $34, $35)",
[
c.Id, (int)c.Kind, c.LocalId, DbParam.Text(c.Server), c.RemoteId, c.OtherId, (int)c.Evidence, (int)c.State, s.Shared, s.SharedUnhashed,
s.SharedRemoved, s.OnlyHere, s.OnlyThere, s.Differs, s.DeletedHere, s.DeletedThere, s.Versions, s.LocalPhotos, s.OtherPhotos,
s.Containment, s.Overlap, s.Hints, c.LocalFramesVersion, c.OtherFramesVersion, c.Fingerprint, DbParam.Text(c.AnsweredFingerprint),
c.AnsweredShared, c.AutoPhotos, c.JobId, (int?)c.PreviousState, c.RemoteGoneAt, c.RemoteGoneHits,
c.FoundAt == default ? now : c.FoundAt, now, c.AnsweredAt,
], ct);
}
/// <summary>A local pair in its stored order (its sides swapped when given the other way round); a server pair as given, checked.</summary>
private static FoundCopy Normalised(FoundCopy copy)
{
if (copy.Kind == CopyKind.LocalServer)
{
if (string.IsNullOrWhiteSpace(copy.Server) || copy.RemoteId is null || copy.OtherId is not null)
throw new ArgumentException("A local↔server pair names a server and its sequence, and no other local sequence.", nameof(copy));
return copy;
}
if (copy.OtherId is not { } other || other == copy.LocalId || copy.Server is not null || copy.RemoteId is not null)
throw new ArgumentException("A local pair names two different local sequences and no server.", nameof(copy));
var (low, _) = Order(copy.LocalId, other);
if (low == copy.LocalId) return copy;
var s = copy.Score;
return copy with
{
LocalId = other,
OtherId = copy.LocalId,
LocalFramesVersion = copy.OtherFramesVersion,
OtherFramesVersion = copy.LocalFramesVersion,
Score = s with
{
OnlyHere = s.OnlyThere,
OnlyThere = s.OnlyHere,
DeletedHere = s.DeletedThere,
DeletedThere = s.DeletedHere,
LocalPhotos = s.OtherPhotos,
OtherPhotos = s.LocalPhotos,
},
};
}
private static FoundCopy Map(DbRow r)
{
var stored = (CopyState)r.GetInt32(7);
var state = (CopyState)r.GetInt32(35);
var live = state == stored;
return new FoundCopy
{
Id = r.GetGuid(0),
Kind = (CopyKind)r.GetInt32(1),
LocalId = r.GetGuid(2),
Server = r.GetStringOrNull(3),
RemoteId = r.GetGuidOrNull(4),
OtherId = r.GetGuidOrNull(5),
Evidence = (CopyEvidence)r.GetInt32(6),
State = state,
Score = new CopyScore(r.GetInt32(8), r.GetInt32(9), r.GetInt32(10), r.GetInt32(11), r.GetInt32(12), r.GetInt32(13), r.GetInt32(14),
r.GetInt32(15), r.GetInt32(16), r.GetInt32(17), r.GetInt32(18), r.GetInt32(19), r.GetInt32(20), r.GetInt32(21)),
LocalFramesVersion = r.GetInt32(22),
OtherFramesVersion = r.GetInt32(23),
Fingerprint = r.GetString(24),
AnsweredFingerprint = r.GetStringOrNull(25),
AnsweredShared = r.GetInt32OrNull(26),
AutoPhotos = r.GetBool(27),
JobId = live ? r.GetGuidOrNull(28) : null,
PreviousState = live && r.GetInt32OrNull(29) is { } previous ? (CopyState)previous : null,
RemoteGoneAt = r.GetDateTimeOffsetOrNull(30),
RemoteGoneHits = r.GetInt32(31),
FoundAt = r.GetDateTimeOffset(32),
UpdatedAt = r.GetDateTimeOffset(33),
AnsweredAt = r.GetDateTimeOffsetOrNull(34),
};
}
}
+61
View File
@@ -0,0 +1,61 @@
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Data.Sync;
namespace Chronos.Data.Copies;
/// <summary>
/// Matches (owner review 6, #73): two copies of one time-lapse found here and on a server, or twice on this PC; compared,
/// integrated, merged, kept apart, linked or unlinked. Every change that moves files is planned first (a dry run), then
/// applied by a job that re-plans and refuses a changed plan.
/// </summary>
public interface ICopyEngine
{
/// <summary>A detection run found something (new pairs, pairs linked by themselves, kept-apart pairs that ask again).</summary>
event Action<CopyFindResult>? Found;
/// <summary>Every listed pair with the facts of both sides.</summary>
Task<IReadOnlyList<FoundCopyView>> ListAsync(CancellationToken ct);
/// <summary>Looks for matches now: on <paramref name="remote"/>'s server when given, and among this PC's archives always.</summary>
Task<CopyFindResult> FindAsync(ISyncRemote? remote, CancellationToken ct);
/// <summary>Both sides of a pair compared photo by photo, detail by detail, with projects and renders.</summary>
Task<CopyReview> CompareAsync(Guid copyId, ISyncRemote? remote, CancellationToken ct);
Task<IntegratePlan> PlanIntegrateAsync(Guid copyId, ISyncRemote remote, IntegrateChoices choices, CancellationToken ct);
Task<Job> EnqueueIntegrateAsync(JobEngine engine, IntegratePlan plan, CancellationToken ct);
/// <summary>The plan of a merge of a local pair; <paramref name="keepId"/> null leaves the kept sequence unchosen unless one is preselected.</summary>
Task<MergePlan> PlanMergeAsync(Guid copyId, Guid? keepId, MergeChoices choices, CancellationToken ct);
Task<Job> EnqueueMergeAsync(JobEngine engine, MergePlan plan, CancellationToken ct);
Task KeepApartAsync(Guid copyId, CancellationToken ct);
Task AskAgainAsync(Guid copyId, CancellationToken ct);
Task LinkAsync(Guid copyId, ISyncRemote remote, CancellationToken ct);
Task UnlinkAsync(Guid copyId, ISyncRemote? remote, CancellationToken ct);
/// <summary>The dry run of moving photos of the local copy (by photo key) to its archive trash.</summary>
Task<FrameDeletePlan> PlanTrashHereAsync(Guid copyId, IReadOnlyCollection<string> photoKeys, CancellationToken ct);
/// <summary>Applies <paramref name="plan"/>, refusing photos no longer deleted on the other side; returns the photos moved.</summary>
Task<int> TrashHereAsync(Guid copyId, FrameDeletePlan plan, ISyncRemote? remote, CancellationToken ct);
/// <summary>The server's dry run of moving photos of the server copy (by photo key) to the server's trash.</summary>
Task<TrashTherePlan> PlanTrashThereAsync(Guid copyId, ISyncRemote remote, IReadOnlyCollection<string> photoKeys, CancellationToken ct);
/// <summary>Applies <paramref name="plan"/> on the server at the plan's frames version; returns the photos moved.</summary>
Task<int> TrashThereAsync(TrashTherePlan plan, ISyncRemote remote, 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);
/// <summary>Linked or integrated pairs with workspace projects at both homes (the Edit picker's twins).</summary>
Task<IReadOnlyList<CopyTwin>> TwinsAsync(CancellationToken ct);
}
+77
View File
@@ -0,0 +1,77 @@
using Chronos.Data.Sync;
namespace Chronos.Data.Copies;
/// <summary>Why Upload all local left a sequence out (owner review 6, Q8).</summary>
public enum UploadSkip
{
/// <summary>In a match nobody answered yet: it may be on the server already.</summary>
SuspectedCopy,
/// <summary>The user kept it apart from a match.</summary>
KeptApart,
/// <summary>It lies in a server's originals archive: it came from a server.</summary>
ServerOriginals,
/// <summary>The server deleted its copy (a 404 for the linked sequence).</summary>
DeletedOnServer,
/// <summary>An Integrate or Merge job holds it, or will.</summary>
Busy,
}
/// <summary>
/// Which local-only sequences Upload all local sends (design §6.4, owner review 6, Q8): suspected copies, kept-apart ones,
/// those the server deleted, those an Integrate or Merge holds and those in any server's originals archive are skipped and
/// flagged, never uploaded as new server sequences. Pure.
/// </summary>
public static class UploadAllRule
{
/// <summary>
/// Splits <paramref name="localOnly"/> into the entries to upload and those skipped with the reason.
/// <paramref name="copies"/> are every pair of the index (any server, and local pairs); <paramref name="serverOriginalsArchives"/>
/// every known server's originals archive (the current one's too); <paramref name="busy"/> the targets of pending or
/// running Integrate and MergeSequences jobs. An entry without a local sequence is neither.
/// </summary>
public static (IReadOnlyList<SyncEntry> Upload, IReadOnlyList<(SyncEntry Entry, UploadSkip Why)> Skipped) Select(
IEnumerable<SyncEntry> localOnly, IReadOnlyCollection<FoundCopy> copies, IReadOnlySet<Guid> serverOriginalsArchives,
IReadOnlySet<Guid> busy)
{
ArgumentNullException.ThrowIfNull(localOnly);
ArgumentNullException.ThrowIfNull(copies);
ArgumentNullException.ThrowIfNull(serverOriginalsArchives);
ArgumentNullException.ThrowIfNull(busy);
var bySequence = new Dictionary<Guid, List<FoundCopy>>();
foreach (var copy in copies)
{
Add(copy.LocalId, copy);
if (copy.OtherId is { } other) Add(other, copy);
}
var upload = new List<SyncEntry>();
var skipped = new List<(SyncEntry, UploadSkip)>();
foreach (var entry in localOnly)
{
if (entry.Local is not { } local) continue;
var pairs = bySequence.GetValueOrDefault(local.Id) ?? [];
UploadSkip? why =
busy.Contains(local.Id) || pairs.Any(p => p.State == CopyState.Integrating) ? UploadSkip.Busy
: pairs.Any(p => p.Kind == CopyKind.LocalServer && p.RemoteGoneHits >= 1) ? UploadSkip.DeletedOnServer
: pairs.Any(p => p.State == CopyState.KeptApart) ? UploadSkip.KeptApart
: pairs.Any(p => p.State == CopyState.Candidate) ? UploadSkip.SuspectedCopy
: serverOriginalsArchives.Contains(local.ArchiveId) ? UploadSkip.ServerOriginals
: null;
if (why is { } reason) skipped.Add((entry, reason));
else upload.Add(entry);
}
return (upload, skipped);
void Add(Guid id, FoundCopy copy)
{
if (!bySequence.TryGetValue(id, out var list)) bySequence[id] = list = [];
list.Add(copy);
}
}
}
+2 -1
View File
@@ -279,7 +279,8 @@ public sealed class JobEngine : IAsyncDisposable
var lowest = running.MinBy(r => queue.LevelOf(r.Job.Kind))!;
if (queue.LevelOf(lowest.Job.Kind) == JobKindPriority.High) return false;
var next = await PeekAsync(queue, lowest, cancellationToken).ConfigureAwait(false);
if (next is null || !queue.Interrupts(next.Kind, lowest.Job.Kind)) return false;
// A background job (automatic transfers of integrated pairs, owner review 6) waits for the running one instead.
if (next is null || next.Priority == JobPriority.Background || !queue.Interrupts(next.Kind, lowest.Job.Kind)) return false;
if (!lowest.Yield(next)) return false;
Log.Info("jobs", $"{lowest.Job.Kind} job {lowest.Job.Id} yields to {next.Kind} job {next.Id} (priority queue)");
return true;
+4 -1
View File
@@ -25,7 +25,8 @@ public sealed record JobPriorityQueue
/// The levels a kind has unless the user changed it: renders, imports and downloads first, and the copy of a project's
/// media into the workspace, which Edit waits for (owner review 2, R8), a workspace's local render and the move of the
/// workspace folder, which Edit is held for (phase 5c), and the copy of videos into the videos folder, a transfer the user
/// waits for like a download (owner review 1, R9); a local render's sending home at the normal level; the long
/// waits for like a download (owner review 1, R9), and the integration and merge of two copies of a sequence the user
/// started (owner review 6); a local render's sending home at the normal level; the long
/// passes that resume anywhere, and the housekeeping of the schedules (backups, clean-ups), last.
/// </summary>
public static IReadOnlyDictionary<JobKind, JobKindPriority> DefaultLevels { get; } = new Dictionary<JobKind, JobKindPriority>
@@ -38,6 +39,8 @@ public sealed record JobPriorityQueue
[JobKind.WorkspaceSend] = JobKindPriority.Normal,
[JobKind.WorkspaceMove] = JobKindPriority.High,
[JobKind.VideoCopy] = JobKindPriority.High,
[JobKind.Integrate] = JobKindPriority.High,
[JobKind.MergeSequences] = JobKindPriority.High,
[JobKind.Verify] = JobKindPriority.Low,
[JobKind.Proxies] = JobKindPriority.Low,
[JobKind.Backup] = JobKindPriority.Low,
@@ -0,0 +1,59 @@
-- Found copies (owner review 6, #73): see sqlite/0012_found_copies.sql. Mirrors it.
CREATE TABLE found_copies (
id uuid PRIMARY KEY,
kind integer NOT NULL,
local_id uuid NOT NULL REFERENCES sequences (id) ON DELETE CASCADE,
server text COLLATE "C",
remote_id uuid,
other_id uuid REFERENCES sequences (id) ON DELETE CASCADE,
evidence integer NOT NULL,
state integer NOT NULL DEFAULT 0,
shared integer NOT NULL DEFAULT 0,
shared_unhashed integer NOT NULL DEFAULT 0,
shared_removed integer NOT NULL DEFAULT 0,
only_here integer NOT NULL DEFAULT 0,
only_there integer NOT NULL DEFAULT 0,
differs integer NOT NULL DEFAULT 0,
deleted_here integer NOT NULL DEFAULT 0,
deleted_there integer NOT NULL DEFAULT 0,
versions integer NOT NULL DEFAULT 0,
local_photos integer NOT NULL DEFAULT 0,
other_photos integer NOT NULL DEFAULT 0,
containment integer NOT NULL DEFAULT 0,
overlap integer NOT NULL DEFAULT 0,
hints integer NOT NULL DEFAULT 0,
local_frames_version integer NOT NULL DEFAULT 0,
other_frames_version integer NOT NULL DEFAULT 0,
fingerprint text NOT NULL,
answered_fingerprint text,
answered_shared integer,
auto_photos boolean NOT NULL DEFAULT false,
job_id uuid,
previous_state integer,
remote_gone_at timestamptz,
remote_gone_hits integer NOT NULL DEFAULT 0,
found_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL,
answered_at timestamptz,
CHECK ((kind = 0 AND server IS NOT NULL AND remote_id IS NOT NULL AND other_id IS NULL)
OR (kind = 1 AND server IS NULL AND remote_id IS NULL AND other_id IS NOT NULL AND other_id <> local_id))
);
CREATE UNIQUE INDEX ux_found_copies_remote ON found_copies (local_id, server, remote_id) WHERE kind = 0;
CREATE UNIQUE INDEX ux_found_copies_local ON found_copies (local_id, other_id) WHERE kind = 1;
CREATE INDEX ix_found_copies_server ON found_copies (server, remote_id);
CREATE INDEX ix_found_copies_other ON found_copies (other_id);
CREATE INDEX ix_found_copies_state ON found_copies (state);
CREATE TABLE copy_probes (
sequence_id uuid NOT NULL REFERENCES sequences (id) ON DELETE CASCADE,
scope text COLLATE "C" NOT NULL,
frames_version integer NOT NULL,
hashed integer NOT NULL,
probed_at timestamptz NOT NULL,
PRIMARY KEY (sequence_id, scope)
);
INSERT INTO found_copies (id, kind, local_id, server, remote_id, evidence, state, fingerprint, found_at, updated_at)
SELECT gen_random_uuid(), 0, local_id, server, remote_id, 0, 2, 'link', now(), now()
FROM sync_links WHERE local_id IS NOT NULL;
@@ -0,0 +1,74 @@
-- Found copies (owner review 6, #73): two copies of one time-lapse whose ids differ, a local sequence and a sequence of a
-- server (kind 0) or two local sequences of this index (kind 1), with the evidence, the scores of the last comparison, the
-- user's answer and, once integrated, the pair's policy. A pair is never two links: sync_links stays the 1:1 per server
-- record a sync compares; every link has a row here too (evidence 0, state 2), so a server deletion and the per-link policy
-- have a place. Scores are counts and per-mille ratios of the last exact comparison, at the frames versions it read. The
-- answered_* columns keep what a "Keep apart" was given, so only a large later change asks again. remote_gone_* record a
-- server's 404 for the remote side (two answers on two refreshes before the pair reads "deleted on server"). Local columns
-- cascade: a sequence deleted into the trash (or removed by Rebuild, Orphans or Reidentify) takes its pairs along; the
-- next detection finds such a pair again as a candidate (DECISIONS). Mirrors postgres/0012_found_copies.sql.
CREATE TABLE found_copies (
id TEXT NOT NULL PRIMARY KEY,
kind INTEGER NOT NULL,
local_id TEXT NOT NULL REFERENCES sequences (id) ON DELETE CASCADE,
server TEXT,
remote_id TEXT,
other_id TEXT REFERENCES sequences (id) ON DELETE CASCADE,
evidence INTEGER NOT NULL,
state INTEGER NOT NULL DEFAULT 0,
shared INTEGER NOT NULL DEFAULT 0,
shared_unhashed INTEGER NOT NULL DEFAULT 0,
shared_removed INTEGER NOT NULL DEFAULT 0,
only_here INTEGER NOT NULL DEFAULT 0,
only_there INTEGER NOT NULL DEFAULT 0,
differs INTEGER NOT NULL DEFAULT 0,
deleted_here INTEGER NOT NULL DEFAULT 0,
deleted_there INTEGER NOT NULL DEFAULT 0,
versions INTEGER NOT NULL DEFAULT 0,
local_photos INTEGER NOT NULL DEFAULT 0,
other_photos INTEGER NOT NULL DEFAULT 0,
containment INTEGER NOT NULL DEFAULT 0,
overlap INTEGER NOT NULL DEFAULT 0,
hints INTEGER NOT NULL DEFAULT 0,
local_frames_version INTEGER NOT NULL DEFAULT 0,
other_frames_version INTEGER NOT NULL DEFAULT 0,
fingerprint TEXT NOT NULL,
answered_fingerprint TEXT,
answered_shared INTEGER,
auto_photos INTEGER NOT NULL DEFAULT 0,
job_id TEXT,
previous_state INTEGER,
remote_gone_at TEXT,
remote_gone_hits INTEGER NOT NULL DEFAULT 0,
found_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
answered_at TEXT,
CHECK ((kind = 0 AND server IS NOT NULL AND remote_id IS NOT NULL AND other_id IS NULL)
OR (kind = 1 AND server IS NULL AND remote_id IS NULL AND other_id IS NOT NULL AND other_id <> local_id))
);
CREATE UNIQUE INDEX ux_found_copies_remote ON found_copies (local_id, server, remote_id) WHERE kind = 0;
CREATE UNIQUE INDEX ux_found_copies_local ON found_copies (local_id, other_id) WHERE kind = 1;
CREATE INDEX ix_found_copies_server ON found_copies (server, remote_id);
CREATE INDEX ix_found_copies_other ON found_copies (other_id);
CREATE INDEX ix_found_copies_state ON found_copies (state);
-- What detection last sent or compared of each local sequence, per scope (a server key, or '' for this PC's archives):
-- a sequence whose frames version and hashed count are unchanged is not probed again.
CREATE TABLE copy_probes (
sequence_id TEXT NOT NULL REFERENCES sequences (id) ON DELETE CASCADE,
scope TEXT NOT NULL,
frames_version INTEGER NOT NULL,
hashed INTEGER NOT NULL,
probed_at TEXT NOT NULL,
PRIMARY KEY (sequence_id, scope)
);
-- Every existing link is a linked pair (no score yet: the next comparison fills it). Ids are random v4 UUIDs.
INSERT INTO found_copies (id, kind, local_id, server, remote_id, evidence, state, fingerprint, found_at, updated_at)
SELECT lower(substr(h, 1, 8) || '-' || substr(h, 9, 4) || '-4' || substr(h, 14, 3) || '-'
|| substr('89ab', 1 + (abs(random()) % 4), 1) || substr(h, 18, 3) || '-' || substr(h, 21, 12)),
0, local_id, server, remote_id, 0, 2, 'link', ts, ts
FROM (SELECT hex(randomblob(16)) AS h, local_id, server, remote_id,
strftime('%Y-%m-%dT%H:%M:%f', 'now') || '000Z' AS ts
FROM sync_links WHERE local_id IS NOT NULL);
@@ -0,0 +1,43 @@
using Chronos.Data.Copies;
using Chronos.Protocol;
namespace Chronos.Data.Sync;
/// <summary>Where a photo of a pair stands (design §4.1); each photo lands in exactly one class.</summary>
public enum PhotoClass
{
Same,
SameUnhashed,
OnlyHere,
OnlyThere,
Differs,
Converted,
DeletedHere,
DeletedThere,
Versions,
}
/// <summary>
/// One side's frame as the comparison reads it (local frames, or the server's manifest and frames). Unusable: the frame is
/// flagged Missing or Corrupt (it holds nothing; the other side's copy repairs it).
/// </summary>
public sealed record CopyPhotoInput(Guid FrameId, int Index, string FileName, string? Sha256, long Size, DateTime? CapturedAt, bool Unusable);
/// <summary>One side of a comparison: its frames and its tombstones.</summary>
public sealed record CopySideInput(IReadOnlyList<CopyPhotoInput> Photos, IReadOnlyList<RemovedPhotoDto> Removed);
/// <summary>
/// A compared photo. Key: canonical SHA-256, or "u:&lt;size&gt;:&lt;capture ms ticks&gt;" while unhashed. Occurrences count
/// the copies of the photo inside each side; Bytes is its size on the side that holds it (Differs: here's).
/// </summary>
public sealed record ComparedPhoto(PhotoClass Class, string Key, CopyPhotoInput? Here, CopyPhotoInput? There,
int HereOccurrences, int ThereOccurrences, long Bytes, bool RepairsHere = false, bool RepairsThere = false);
/// <summary>The count and bytes of one class on each side.</summary>
public sealed record PhotoClassTotal(PhotoClass Class, int Count, long HereBytes, long ThereBytes);
/// <summary>The outcome of comparing two sides photo by photo.</summary>
public sealed record CopyComparisonResult(IReadOnlyList<ComparedPhoto> Photos, IReadOnlyList<PhotoClassTotal> Totals, CopyScore Score)
{
public IEnumerable<ComparedPhoto> Of(PhotoClass c) => Photos.Where(p => p.Class == c);
}
+7 -2
View File
@@ -1,5 +1,6 @@
using System.Text.Json;
using Chronos.Core.Model;
using Chronos.Data.Copies;
using Chronos.Data.Repositories;
namespace Chronos.Data.Sync;
@@ -47,7 +48,8 @@ internal sealed class SyncLinkStore(ChronosDatabase db)
/// Moves every link of <paramref name="from"/> to <paramref name="to"/> in one transaction (owner review 5, #66: an address
/// key becomes the server's id key). Where <paramref name="to"/> already links the same server sequence, or the same local
/// copy, the row compared last (<see cref="SyncLink.SyncedAt"/>, never compared counting oldest) is kept and the other
/// deleted: link rows are recomputed by the next comparison, so nothing is lost.
/// deleted: link rows are recomputed by the next comparison, so nothing is lost. The server's found copies and probes move
/// in the same transaction (<see cref="FoundCopyStore.RekeyAsync"/>), the pair of the surviving link winning a clash.
/// </summary>
public async Task<(int Moved, int Dropped)> RekeyAsync(string from, string to, CancellationToken cancellationToken)
{
@@ -59,7 +61,7 @@ internal sealed class SyncLinkStore(ChronosDatabase db)
var inner = new DbAccess(session);
var old = await inner.ListAsync($"SELECT {Columns} FROM sync_links WHERE server = $1 ORDER BY remote_id", [from], Map, cancellationToken)
.ConfigureAwait(false);
if (old.Count == 0) return (0, 0);
var surviving = new HashSet<Guid>();
var current = (await inner.ListAsync($"SELECT {Columns} FROM sync_links WHERE server = $1 ORDER BY remote_id", [to], Map, cancellationToken)
.ConfigureAwait(false)).ToList();
var (moved, dropped) = (0, 0);
@@ -81,8 +83,11 @@ internal sealed class SyncLinkStore(ChronosDatabase db)
await inner.ExecuteAsync("UPDATE sync_links SET server = $3 WHERE server = $1 AND remote_id = $2", [from, link.RemoteId, to], cancellationToken)
.ConfigureAwait(false);
current.Add(link with { Server = to });
surviving.Add(link.RemoteId);
moved++;
}
// The pairs and probes of the server move with its links, in this transaction (owner review 6, #73).
await new FoundCopyStore(db).RekeyAsync(session, from, to, surviving, cancellationToken).ConfigureAwait(false);
return (moved, dropped);
}, cancellationToken).ConfigureAwait(false);
+4 -1
View File
@@ -1,4 +1,5 @@
using Chronos.Core.Model;
using Chronos.Data.Copies;
namespace Chronos.Data.Sync;
@@ -172,7 +173,9 @@ public sealed record SyncSnapshot(string Server, IReadOnlyList<SyncEntry> Entrie
/// <param name="AutoSyncSettings">Send and take settings changed on one side only (Server.html "Sync projects automatically").</param>
/// <param name="KeepProxiesOffline">Keep the proxy caches of server sequences this PC opened with proxies up to date.</param>
/// <param name="CanEdit">The account may change server sequences; without it this PC's edits are never sent.</param>
public sealed record SyncPolicy(bool AutoSyncSettings = true, bool KeepProxiesOffline = false, bool CanEdit = true);
/// <param name="Linking">What a refresh does with a match it finds (Settings › Server › Link matches, owner review 6, Q1).</param>
public sealed record SyncPolicy(bool AutoSyncSettings = true, bool KeepProxiesOffline = false, bool CanEdit = true,
CopyLinking Linking = CopyLinking.AskAlways);
/// <summary>
/// A conflict could not be settled as the user chose because one side changed again after it was shown; the
+58
View File
@@ -92,6 +92,36 @@ public interface ISyncRemote : IDisposable
/// then fail every render of them. A remote that cannot say reads this Chronos's.
/// </summary>
Task<int> SettingsFormatAsync(CancellationToken cancellationToken) => Task.FromResult(Core.Project.ProjectSettings.CurrentVersion);
/// <summary>
/// The capabilities the server announces (<see cref="ServerInfo.Capabilities"/>, names of <see cref="ServerCapabilities"/>).
/// A remote that cannot say announces none: callers take the path of an older server.
/// </summary>
Task<IReadOnlySet<string>> CapabilitiesAsync(CancellationToken cancellationToken) =>
Task.FromResult<IReadOnlySet<string>>(new HashSet<string>(StringComparer.Ordinal));
/// <summary>
/// Which server sequences hold sampled photos of local sequences (owner review 6, #73; <see cref="ServerCapabilities.PhotoLookup"/>).
/// See <see cref="ChronosClient.LookupPhotosAsync"/>. A remote without the call throws <see cref="NotSupportedException"/>.
/// </summary>
Task<PhotoLookupResponse> LookupPhotosAsync(PhotoLookupRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
/// <summary>
/// Upload of one original into <paramref name="sequenceId"/> that the server files there even when another of its
/// sequences holds the photo (<see cref="StartUploadRequest.IntoTarget"/>, owner review 6; <see cref="ServerCapabilities.UploadInto"/>).
/// Null when the target deleted the photo. A remote without the call throws <see cref="NotSupportedException"/>.
/// </summary>
Task<CompleteUploadResponse?> UploadFileIntoAsync(string path, Guid sequenceId, string sha256, DateTime? capturedAt,
CancellationToken cancellationToken) => throw new NotSupportedException();
/// <summary>
/// Moves frames of a server sequence into the server's trash, or with <see cref="FrameDeleteRequest.DryRun"/> answers the
/// plan only (owner review 6, #73). A 409 <see cref="ChronosApiException"/> means the frames moved since
/// <see cref="FrameDeleteRequest.ExpectedFramesVersion"/>, 403 that the account may not. A remote without the call throws
/// <see cref="NotSupportedException"/>.
/// </summary>
Task<FrameDeleteResultDto> DeleteFramesAsync(Guid sequenceId, FrameDeleteRequest request, CancellationToken cancellationToken) =>
throw new NotSupportedException();
}
/// <summary>
@@ -141,6 +171,34 @@ public sealed class ChronosSyncRemote(ChronosClient client, bool ownsClient, str
/// <summary>The settings format the server announced, and when it was read (a <see cref="System.Diagnostics.Stopwatch"/> timestamp).</summary>
private sealed record KnownFormat(int Format, long Read);
private Task<IReadOnlySet<string>>? _capabilities;
/// <summary>Read from <c>server/info</c> once per remote (a remote lives for one session; an update of the server ends it).</summary>
public Task<IReadOnlySet<string>> CapabilitiesAsync(CancellationToken cancellationToken)
{
var known = Volatile.Read(ref _capabilities);
if (known is { IsFaulted: false, IsCanceled: false }) return known;
var read = ReadCapabilitiesAsync(cancellationToken);
Volatile.Write(ref _capabilities, read);
return read;
}
private async Task<IReadOnlySet<string>> ReadCapabilitiesAsync(CancellationToken cancellationToken)
{
var info = await client.GetInfoAsync(cancellationToken).ConfigureAwait(false);
return new HashSet<string>(info.Capabilities ?? [], StringComparer.Ordinal);
}
public Task<PhotoLookupResponse> LookupPhotosAsync(PhotoLookupRequest request, CancellationToken cancellationToken) =>
client.LookupPhotosAsync(request, cancellationToken);
public Task<CompleteUploadResponse?> UploadFileIntoAsync(string path, Guid sequenceId, string sha256, DateTime? capturedAt,
CancellationToken cancellationToken) =>
client.UploadFileIntoAsync(path, sequenceId, capturedAt, sha256, null, cancellationToken);
public Task<FrameDeleteResultDto> DeleteFramesAsync(Guid sequenceId, FrameDeleteRequest request, CancellationToken cancellationToken) =>
client.DeleteFramesAsync(sequenceId, request, cancellationToken);
public string Server { get; } = string.IsNullOrWhiteSpace(server) ? SyncService.ServerKey(client.BaseAddress) : server;
public async Task<IReadOnlyList<SequenceDto>> ListSequencesAsync(CancellationToken cancellationToken)