using System.Collections.Concurrent;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Chronos.Core.Archiving;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Copies;
using Chronos.Data.Jobs;
using Chronos.Data.Projects;
using Chronos.Data.Repositories;
using Chronos.Data.Sync;
namespace Chronos.Data.Archiving;
///
/// Merges two local copies of one time-lapse into the one kept (owner review 6, #73; design §5d; BRIEF §12.5 Merge): the
/// dry run () says which photos
/// of the other copy are copied into the kept one, which go to the trash with it and are held nowhere else (last copies),
/// the renders and projects that move, the details written, the session keys and links that follow, and what blocks it;
/// queues the job that applies exactly that plan
/// (), every photo hash-verified in the kept sequence before the other goes to its archive's trash.
///
public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives, CopySides sides)
{
/// The free space a merge leaves on the kept sequence's volume beyond what it copies.
public const long SpaceReserve = 512L << 20;
private readonly ChronosDatabase _db = db ?? throw new ArgumentNullException(nameof(db));
private readonly ArchiveService _archives = archives ?? throw new ArgumentNullException(nameof(archives));
private readonly CopySides _sides = sides ?? throw new ArgumentNullException(nameof(sides));
private readonly DbAccess _access = new(db.Database);
///
/// The hashes the dry runs read of the other sequence's files, by frame, with the size and last write time they were read
/// at: a plan made again (every change of choice in the dialog) reads only the files that are new or changed. Kept in
/// memory only, as a dry run writes nothing to the index; the job's Verify stage hashes every file again.
///
private readonly ConcurrentDictionary _hashes = new();
/// The most hashes keeps before it starts again.
private const int HashesKept = 200_000;
private int _filesHashed;
/// Files the dry runs read and hashed so far (tests: a plan made again reads only what changed).
internal int FilesHashed => Volatile.Read(ref _filesHashed);
/// The name a server key is shown by (default: the key): the links a merge moves and the server both are linked to.
public Func? ServerNames { get; init; }
internal ChronosDatabase Db => _db;
/// The name is shown by.
internal string ServerName(string key) => ServerNames?.Invoke(key) is { Length: > 0 } name ? name : key;
internal ArchiveService Archives => _archives;
/// The handler of jobs; register it on the .
public static IJobHandler CreateHandler(ChronosDatabase db, SequenceMerger merger, ArchiveService archives, IProjectCopier projects,
IWorkspaceGuard workspace) => new MergeJobHandler(db, merger, archives, projects, workspace);
///
/// The dry run of merging the pair : is kept and the other goes to the
/// trash. With null the kept one is preselected only when exactly one of the two is linked to a
/// server and lies in a server's originals archive; otherwise the plan is made keeping the one that is not
/// and blocks with .
///
/// The pair is not a local pair of these sequences, or a sequence is not in the index.
public Task PlanAsync(Guid copyId, Guid? keepId, Guid otherId, MergeChoices choices, CopyPlanContext context, CancellationToken ct) =>
PlanAsync(copyId, keepId, otherId, choices, context, null, ct);
/// The dry run, with the jobs of (the merge job planning again) not counted as busy.
internal async Task PlanAsync(Guid copyId, Guid? keepId, Guid otherId, MergeChoices choices, CopyPlanContext context, Guid? exceptJob,
CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(choices);
ArgumentNullException.ThrowIfNull(context);
var copy = await new FoundCopyStore(_db).GetAsync(copyId, ct).ConfigureAwait(false)
?? throw new ArgumentException($"Unknown pair {copyId}.", nameof(copyId));
if (copy is not { Kind: CopyKind.LocalLocal, OtherId: { } second } || !copy.Names(otherId))
throw new ArgumentException($"Pair {copyId} is not a local pair of sequence {otherId}.", nameof(otherId));
var first = copy.LocalId;
var blocks = new List();
Guid keep, drop;
if (keepId is { } chosen)
{
if (!copy.Names(chosen)) throw new ArgumentException($"Sequence {chosen} is not one of pair {copyId}.", nameof(keepId));
(keep, drop) = (chosen, chosen == first ? second : first);
}
else if (await PreselectAsync(first, second, context, ct).ConfigureAwait(false) is { } preselected)
{
(keep, drop) = (preselected, preselected == first ? second : first);
}
else
{
(keep, drop) = (otherId == first ? second : first, otherId);
blocks.Add(CopyBlock.KeptUnchosen);
}
var keepRow = await _db.Sequences.GetAsync(keep, ct).ConfigureAwait(false) ?? throw new ArgumentException($"Unknown sequence {keep}.", nameof(copyId));
var dropRow = await _db.Sequences.GetAsync(drop, ct).ConfigureAwait(false) ?? throw new ArgumentException($"Unknown sequence {drop}.", nameof(copyId));
var keepArchive = await _db.Archives.GetAsync(keepRow.ArchiveId, ct).ConfigureAwait(false)
?? throw new ArgumentException($"Unknown archive {keepRow.ArchiveId}.", nameof(copyId));
var dropArchive = await _db.Archives.GetAsync(dropRow.ArchiveId, ct).ConfigureAwait(false)
?? throw new ArgumentException($"Unknown archive {dropRow.ArchiveId}.", nameof(copyId));
var keepPaths = new ArchivePaths(keepArchive.RootPath);
var dropPaths = new ArchivePaths(dropArchive.RootPath);
// Where the two are: online, in the folders the index has, not worked on by a job.
var online = ArchiveVolume.Probe(keepPaths) == ArchiveAvailability.Online && ArchiveVolume.Probe(dropPaths) == ArchiveAvailability.Online;
if (!online) blocks.Add(CopyBlock.ArchiveOffline);
else if (Moved(keepPaths, keepRow) || Moved(dropPaths, dropRow)) blocks.Add(CopyBlock.FolderMoved);
// Photos of the other this index has not read (copied in by hand, filed by another index sharing the archive) would
// go to the trash with its folder, never copied nor listed: a scan reads them first.
else if (await FolderChangedAsync(dropArchive, dropPaths, dropRow, ct).ConfigureAwait(false)) blocks.Add(CopyBlock.FolderChanged);
if (await BusyAsync([keep, drop, keepRow.ArchiveId, dropRow.ArchiveId], exceptJob, ct).ConfigureAwait(false)) blocks.Add(CopyBlock.Busy);
if (context.UnsentWorkspaceSequences.Contains(drop)) blocks.Add(CopyBlock.UnsentWorkspace);
// Photos: keep is "here", drop is "there".
var here = await _sides.LocalAsync(keep, ct).ConfigureAwait(false);
var there = await _sides.LocalAsync(drop, ct).ConfigureAwait(false);
var comparison = CopyComparer.Compare(here, there);
if (online && await HashOnlyThereAsync(comparison, there, dropPaths, ct).ConfigureAwait(false) is { } hashed)
{
// Compared by content now: a photo the kept sequence deleted reads Deleted here (a last copy when nothing else
// holds it), never a copy the kept sequence's tombstone refuses.
there = hashed;
comparison = CopyComparer.Compare(here, there);
}
// The kept sequence's unhashed frames matched by size and time with a hashed photo of the other, hashed now (in
// memory): the same content is held (never a last copy); another content is a second photo the merge copies in.
var freshHere = online ? await HashUnhashedHereAsync(comparison, keepPaths, ct).ConfigureAwait(false) : new Dictionary();
var keepTombstones = here.Removed.Select(r => r.Sha256).ToHashSet(StringComparer.OrdinalIgnoreCase);
var steps = new List();
var excluded = new List();
var unchosen = 0;
foreach (var photo in comparison.Photos)
{
switch (photo.Class)
{
case PhotoClass.OnlyThere:
// Every photo only the other holds is copied: it goes to the trash, nothing it alone holds stays behind.
steps.Add(Step(photo.Key, PhotoAction.Fetch, photo.There!));
break;
case PhotoClass.SameUnhashed when photo is { Here: { } mine, There.Sha256: { Length: > 0 } theirs }
&& freshHere.TryGetValue(mine.FrameId, out var fresh)
&& !string.Equals(fresh, theirs, StringComparison.OrdinalIgnoreCase)
&& !keepTombstones.Contains(theirs):
// Another photo after all (design §5d step 4): the other's version is copied into the kept one as a
// second version, whatever the policy (nothing chose between the two), and left out of its projects.
steps.Add(Step(photo.Key, PhotoAction.FetchVersion, photo.There!));
excluded.Add(theirs.ToLowerInvariant());
break;
case PhotoClass.Differs:
// Under Choose each a photo nobody chose blocks: its other version would go to the trash unasked (Leave,
// which a merge does not offer, keeps the kept sequence's version as Kept does).
if (choices.Photos == CopyPhotoPolicy.ChoosePerPhoto && !choices.PerPhoto.ContainsKey(photo.Key)) unchosen++;
var choice = choices.Photos switch
{
CopyPhotoPolicy.Union => PhotoChoice.KeepBoth,
CopyPhotoPolicy.ThisPcWins => PhotoChoice.TakeHere,
CopyPhotoPolicy.OtherWins => PhotoChoice.TakeThere,
_ => choices.PerPhoto.GetValueOrDefault(photo.Key, PhotoChoice.Leave),
};
if (choice is PhotoChoice.KeepBoth or PhotoChoice.TakeThere) steps.Add(Step(photo.Key, PhotoAction.FetchVersion, photo.There!));
if (choice == PhotoChoice.KeepBoth && photo.There!.Sha256 is { Length: > 0 } version) excluded.Add(version.ToLowerInvariant());
if (choice == PhotoChoice.TakeThere) steps.Add(Step(photo.Key, PhotoAction.TrashHere, photo.Here!));
break;
}
}
if (unchosen > 0) blocks.Add(CopyBlock.PhotosUnchosen);
// Last copies: drop originals nothing will hold once the copies are made (losers, tombstoned in keep, converted), and
// keep's losing versions nothing else holds.
var fetched = steps.Where(s => s.Action is PhotoAction.Fetch or PhotoAction.FetchVersion).Select(s => s.Sha256).OfType()
.Select(s => s.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
var losers = steps.Where(s => s.Action == PhotoAction.TrashHere).Select(s => s.FrameId!.Value).ToHashSet();
var keepHolds = here.Photos.Where(p => !p.Unusable && p.Sha256 is { Length: > 0 } && !losers.Contains(p.FrameId))
.Select(p => p.Sha256!.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
keepHolds.UnionWith(freshHere.Values);
// Photos of the other a verify flagged Corrupt (changed since import, or damaged) or Missing whose file is there: the
// comparison leaves them out, so nothing would copy or hash-verify them before their folder goes to the trash. One
// whose content now nothing else holds (an edited photo's only copy) blocks the merge until it is resolved.
if (online && await DamagedAsync(drop, dropPaths, keepHolds, ct).ConfigureAwait(false)) blocks.Add(CopyBlock.DamagedPhotos);
var absent = new List();
foreach (var frame in there.Photos.Where(p => !p.Unusable && p.Sha256 is { Length: > 0 }))
{
var sha = frame.Sha256!.ToLowerInvariant();
if (keepHolds.Contains(sha) || fetched.Contains(sha) || absent.Any(a => string.Equals(a.Sha256, sha, StringComparison.OrdinalIgnoreCase))) continue;
absent.Add(frame with { Sha256 = sha });
}
var lastCopies = new List();
var heldElsewhere = await _sides.HeldElsewhereAsync([.. absent.Select(a => a.Sha256!)], [drop], ct).ConfigureAwait(false);
foreach (var frame in absent.Where(a => !heldElsewhere.Contains(a.Sha256!)))
lastCopies.Add(new LastCopy(frame.Sha256!, CopySide.Other, frame.FileName, frame.Size));
var loserSteps = steps.Where(s => s.Action == PhotoAction.TrashHere && s.Sha256 is { Length: > 0 }).ToList();
if (loserSteps.Count > 0)
{
var loserHeld = await _sides.HeldElsewhereAsync([.. loserSteps.Select(s => s.Sha256!)], [keep, drop], ct).ConfigureAwait(false);
foreach (var step in loserSteps)
{
var sha = step.Sha256!.ToLowerInvariant();
if (loserHeld.Contains(sha) || keepHolds.Contains(sha)) continue;
lastCopies.Add(new LastCopy(sha, CopySide.ThisPc, step.FileName, step.Bytes));
}
}
// Renders the kept sequence lacks (by id and SHA-256) move to it.
var keepRenders = await _db.Renders.ListBySequenceAsync(keep, ct).ConfigureAwait(false);
var keepRenderHashes = keepRenders.Select(r => r.Sha256).OfType().ToHashSet(StringComparer.OrdinalIgnoreCase);
var renders = (await _db.Renders.ListBySequenceAsync(drop, ct).ConfigureAwait(false))
.Where(r => keepRenders.All(k => k.Id != r.Id) && (r.Sha256 is null || !keepRenderHashes.Contains(r.Sha256)))
.OrderBy(r => r.Created).ThenBy(r => r.Id)
.Select(r => new RenderStep(r.Id, Path.GetFileName(r.OutputPath.Replace('\\', '/').TrimEnd('/')), r.Bytes, r.Sha256)).ToList();
// Details, line by line, applied to the kept sequence only.
var keepRemovals = await _db.FrameRemovals.ListBySequenceAsync(keep, ct).ConfigureAwait(false);
var dropRemovals = await _db.FrameRemovals.ListBySequenceAsync(drop, ct).ConfigureAwait(false);
var keepPhotos = await SequencePayloadWriter.PhotosAsync(_db, keep, dropRemovals, ct).ConfigureAwait(false);
var dropPhotos = await SequencePayloadWriter.PhotosAsync(_db, drop, keepRemovals, ct).ConfigureAwait(false);
var lines = CopyPayload.Lines(SyncPayload.Of(keepRow), keepPhotos, SyncPayload.Of(dropRow), dropPhotos);
SyncPayload? payload = null;
var changes = 0;
if (lines.Any(l => !choices.Details.ContainsKey(l.Path)))
{
blocks.Add(CopyBlock.DetailsUnchosen);
}
else
{
changes = lines.DistinctBy(l => l.Path, StringComparer.Ordinal).Count(l => choices.Details[l.Path] == CopySide.Other);
if (changes > 0 || excluded.Count > 0)
{
var mine = CopyPayload.Portable(SyncPayload.Of(keepRow), keepPhotos);
var merged = changes > 0 ? CopyPayload.Merge(mine, CopyPayload.Portable(SyncPayload.Of(dropRow), dropPhotos), choices.Details, lines) : mine;
try
{
merged = CopyPayload.ExcludeVersions(merged, excluded);
}
catch (Exception ex) when (ex is JsonException or InvalidDataException)
{
// Settings that are not a project of this Chronos: the incoming versions stay included.
}
payload = merged.SameAs(mine) && changes == 0 ? null : merged;
}
}
// Projects are always copied across: the other's home goes to the trash.
var projects = await ProjectStepsAsync(keep, drop, dropArchive.Name, ct).ConfigureAwait(false);
// Session keys and links follow the kept sequence.
var (sessionKeys, skippedKeys) = await SessionKeysAsync(keep, drop, keepRow.ArchiveId, ct).ConfigureAwait(false);
var links = await _access.ListAsync("SELECT server, local_id FROM sync_links WHERE local_id = $1 OR local_id = $2", [keep, drop],
r => (Server: r.GetString(0), Local: r.GetGuid(1)), ct).ConfigureAwait(false);
var moved = links.Where(l => l.Local == drop).Select(l => l.Server).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToList();
var bothLinked = links.GroupBy(l => l.Server, StringComparer.Ordinal).FirstOrDefault(g => g.Select(l => l.Local).Distinct().Count() > 1)?.Key;
if (bothLinked is not null) blocks.Add(CopyBlock.BothLinked);
// The other goes to the trash.
var trash = await _archives.Trash.PlanAsync([drop], null, ct, exceptJob).ConfigureAwait(false);
if (trash.Blocked.Any(b => b.Reason is not (DeleteBlock.Busy or DeleteBlock.Offline))) blocks.Add(CopyBlock.TrashBlocked);
else if (trash.Blocked.Any(b => b.Reason == DeleteBlock.Busy) && !blocks.Contains(CopyBlock.Busy)) blocks.Add(CopyBlock.Busy);
// Space on the kept sequence's volume.
var copyBytes = steps.Where(s => s.Action is PhotoAction.Fetch or PhotoAction.FetchVersion).Sum(s => s.Bytes) + renders.Sum(r => r.Bytes);
var free = online ? FreeSpace(keepPaths) : null;
if (free is { } bytes && copyBytes + SpaceReserve > bytes) blocks.Add(CopyBlock.NoSpace);
// Details are in the fingerprint as they read now: an edit that keeps the versions (a title) still moves it.
var keepStamp = await StampAsync(keep, ct).ConfigureAwait(false) + ":" + PayloadHash(SyncPayload.Of(keepRow));
var dropStamp = await StampAsync(drop, ct).ConfigureAwait(false) + ":" + PayloadHash(SyncPayload.Of(dropRow));
var fingerprint = CopyRules.PlanFingerprint(FingerprintLines(keepRow, dropRow, keepStamp, dropStamp, choices, steps, lastCopies, renders, payload,
projects, sessionKeys, skippedKeys));
return new MergePlan(copyId, keep, drop, choices, steps, lastCopies, renders, payload, changes, projects, sessionKeys, skippedKeys, moved, trash,
copyBytes, free ?? -1, [.. blocks.Distinct()], keepRow.FramesVersion, keepRow.SettingsVersion, dropRow.FramesVersion, dropRow.SettingsVersion,
fingerprint)
{
LinkNames = [.. moved.Select(ServerName)],
BothLinkedServer = bothLinked is null ? null : ServerName(bothLinked),
DeletedInOther = comparison.Photos.Count(p => p.Class == PhotoClass.DeletedThere),
PhotosUnchosen = unchosen,
};
}
///
/// The other's unhashed photos only it holds, hashed now (in memory: a dry run writes nothing); null when there are none.
/// Matched by size and time only they would be copied blindly, even a photo whose content the kept sequence deleted.
///
private async Task HashOnlyThereAsync(CopyComparisonResult comparison, CopySideInput there, ArchivePaths dropPaths, CancellationToken ct)
{
var keys = comparison.Photos.Where(p => p.Class == PhotoClass.OnlyThere && p.Key.StartsWith(CopyComparer.UnhashedPrefix, StringComparison.Ordinal))
.Select(p => p.Key).ToHashSet(StringComparer.Ordinal);
if (keys.Count == 0) return null;
var photos = new List(there.Photos.Count);
var changed = false;
foreach (var photo in there.Photos)
{
if (photo.Unusable || photo.Sha256 is { Length: > 0 } || !keys.Contains(CopyComparer.UnhashedKey(photo.Size, photo.CapturedAt, photo.FrameId))
|| await _db.Frames.GetAsync(photo.FrameId, ct).ConfigureAwait(false) is not { } frame)
{
photos.Add(photo);
continue;
}
try
{
var sha = await HashAsync(frame.Id, dropPaths.FromRelative(frame.RelativePath), ct).ConfigureAwait(false);
photos.Add(photo with { Sha256 = sha });
changed = true;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// Unreadable now: left as it is (the job's copy fails on it and says which file).
photos.Add(photo);
}
}
return changed ? there with { Photos = photos } : null;
}
///
/// The SHA-256 of each unhashed frame of the kept sequence that the comparison matched by size and time only
/// () with a hashed photo of the other, read now (in memory), by frame. Without it a
/// photo of the other read as held by the kept sequence would be listed as a last copy when the content is the same,
/// and go to the trash with the other when it is not. A file that cannot be read is left out.
///
private async Task> HashUnhashedHereAsync(CopyComparisonResult comparison, ArchivePaths keepPaths, CancellationToken ct)
{
var result = new Dictionary();
foreach (var photo in comparison.Photos)
{
if (photo is not { Class: PhotoClass.SameUnhashed, Here: { Sha256: null or { Length: 0 } } mine, There.Sha256: { Length: > 0 } }) continue;
if (await _db.Frames.GetAsync(mine.FrameId, ct).ConfigureAwait(false) is not { } frame) continue;
try
{
result[frame.Id] = await HashAsync(frame.Id, keepPaths.FromRelative(frame.RelativePath), ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// Unreadable now: compared as before (the other's photo is listed as a last copy).
}
}
return result;
}
///
/// Whether the other sequence holds a frame flagged unusable (Corrupt, or Missing by an earlier verify although its file
/// is back) whose file is there and whose content, hashed now (in memory), neither the kept sequence
/// () nor any other sequence of this index holds; an unreadable such file counts too. The
/// comparison leaves such frames out, so nothing else would copy or list them before their folder goes to the trash.
///
private async Task DamagedAsync(Guid drop, ArchivePaths dropPaths, IReadOnlySet keepHolds, CancellationToken ct)
{
var flagged = (await _db.Frames.ListBySequenceAsync(drop, cancellationToken: ct).ConfigureAwait(false))
.Where(f => (f.Flags & CopySides.UnusableFlags) != 0).ToList();
var hashes = new List();
foreach (var frame in flagged)
{
var path = dropPaths.FromRelative(frame.RelativePath);
if (!File.Exists(path)) continue;
try
{
var sha = await HashAsync(frame.Id, path, ct).ConfigureAwait(false);
if (!keepHolds.Contains(sha)) hashes.Add(sha);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return true;
}
}
if (hashes.Count == 0) return false;
var held = await _sides.HeldElsewhereAsync(hashes, [drop], ct).ConfigureAwait(false);
return hashes.Any(h => !held.Contains(h));
}
///
/// The SHA-256 (lower-case) of the file of frame : the one read
/// before while the file keeps its size and last write time (), else read now.
///
private async Task HashAsync(Guid frameId, string path, CancellationToken ct)
{
var file = new FileInfo(path);
if (!file.Exists) throw new FileNotFoundException("The photo is not there.", path);
var (length, written) = (file.Length, file.LastWriteTimeUtc);
if (_hashes.TryGetValue(frameId, out var known) && known.Length == length && known.Written == written) return known.Sha256;
var sha = (await ContentHash.Sha256Async(path, null, ct).ConfigureAwait(false)).ToLowerInvariant();
Interlocked.Increment(ref _filesHashed);
if (_hashes.Count >= HashesKept) _hashes.Clear();
_hashes[frameId] = (length, written, sha);
return sha;
}
///
/// Whether the other sequence's folder holds photos this index has not read: photos copied in or removed since the
/// photo directory's recorded stamp (), or a sidecar whose frames are not
/// the row's (another index of the archive filed or dropped photos). A sidecar that cannot be read, or names another
/// sequence, counts. A sidecar rewritten without new frames does not (the merge's own session-key moves rewrite it).
///
internal async Task FolderChangedAsync(Archive archive, ArchivePaths paths, Sequence row, CancellationToken ct)
{
var folder = paths.Sequence(row.Folder);
if (!File.Exists(folder.ManifestPath)) return false;
SequenceManifest manifest;
try
{
manifest = ManifestStore.ReadSequence(folder.ManifestPath);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or JsonException)
{
return true;
}
if (manifest.Id != row.Id) return true;
var indexed = await _db.Sequences.GetAsync(row.Id, ct).ConfigureAwait(false);
return indexed is null || indexed.FramesVersion != manifest.Versions.Frames
|| await _archives.Indexer.PhotosChangedAsync(archive, folder, ct).ConfigureAwait(false);
}
///
/// Queues the job that applies : the pair goes to (its state
/// before kept as the previous one), the job targets the kept sequence, then the other (both held from other jobs).
///
/// The kept sequence's title, for the job's label ("Merge into {title}").
/// The plan is blocked, or the pair is already being merged or integrated.
/// The pair changed state since the plan.
public async Task EnqueueAsync(JobEngine engine, FoundCopyStore store, MergePlan plan, string title, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(engine);
ArgumentNullException.ThrowIfNull(store);
ArgumentNullException.ThrowIfNull(plan);
if (!plan.CanApply) throw new InvalidOperationException($"The merge plan is blocked: {string.Join(", ", plan.Blocks)}.");
var copy = await store.GetAsync(plan.CopyId, ct).ConfigureAwait(false) ?? throw new StaleCopyPlanException();
if (copy.State == CopyState.Integrating) throw new InvalidOperationException(Loc.L("Errors.Copies.Busy"));
var id = Guid.CreateVersion7();
if (!await store.SetStateAsync(plan.CopyId, copy.State, CopyState.Integrating, new CopyAnswer(null, null, id, null, DateTimeOffset.UtcNow), ct)
.ConfigureAwait(false))
throw new StaleCopyPlanException();
var parameters = new MergeJobParameters(plan.CopyId, plan.KeepId, plan.DropId, plan.Choices, plan.Fingerprint);
try
{
return await engine.EnqueueAsync(id, JobKind.MergeSequences, [plan.KeepId, plan.DropId], Loc.L("Jobs.Target.Merge", title), parameters.ToJson(),
JobPriority.User, null, ct).ConfigureAwait(false);
}
catch
{
await store.SetStateAsync(plan.CopyId, CopyState.Integrating, copy.State, null, CancellationToken.None).ConfigureAwait(false);
throw;
}
}
/// The sentence a job fails with for the first block of a plan it made again.
internal async Task BlockMessageAsync(MergePlan plan, CancellationToken ct)
{
var keep = await _db.Sequences.GetAsync(plan.KeepId, ct).ConfigureAwait(false);
var drop = await _db.Sequences.GetAsync(plan.DropId, ct).ConfigureAwait(false);
return BlockText(plan, plan.Blocks[0], keep?.DisplayTitle ?? string.Empty, drop?.DisplayTitle ?? string.Empty);
}
///
/// The sentence of of a merge plan, the one the dialog shows and the job fails with: the kept
/// sequence for space, the other for where it lies and its trash, the server both are linked to by its name.
///
public static string BlockText(MergePlan plan, CopyBlock block, string keepTitle, string dropTitle, int unchosen = 1)
{
ArgumentNullException.ThrowIfNull(plan);
return block switch
{
CopyBlock.Busy => Loc.L("Errors.Copies.Busy"),
CopyBlock.ArchiveOffline or CopyBlock.FolderMoved or CopyBlock.ChangedFile or CopyBlock.DamagedPhotos or CopyBlock.FolderChanged
=> Loc.L("Errors.Copies." + block, dropTitle),
CopyBlock.PhotosUnchosen => Loc.L("Errors.Copies.PhotosUnchosen"),
CopyBlock.NoSpace => Loc.L("Errors.Copies.NoSpace", keepTitle, Size(plan.CopyBytes + SpaceReserve)),
CopyBlock.BothLinked => Loc.L("Errors.Copies.BothLinked", plan.BothLinkedServer ?? string.Empty),
CopyBlock.UnsentWorkspace => Loc.L("Errors.Copies.Unsent", dropTitle),
CopyBlock.TrashBlocked => Loc.L("Errors.Copies.TrashBlocked", dropTitle,
plan.Trash.Blocked.Select(b => Loc.L("Archive.Delete.Reason." + b.Reason)).FirstOrDefault() ?? string.Empty),
CopyBlock.DetailsUnchosen => Loc.Plural("Errors.Copies.DetailsUnchosen", Math.Max(1, unchosen)),
CopyBlock.KeptUnchosen => Loc.L("Errors.Copies.KeptUnchosen"),
_ => Loc.L("Errors.Copies.StalePlan"),
};
}
/// Free bytes on the kept archive's volume (its root and its staging folder, the tighter); null when they cannot be measured.
internal long? FreeSpace(ArchivePaths paths)
{
long? free = null;
foreach (var folder in (string[])[paths.Root, paths.StagingDirectory])
{
if (!Directory.Exists(folder) || Measure(folder) is not { } bytes) continue;
free = free is { } known ? Math.Min(known, bytes) : bytes;
}
return free;
long? Measure(string folder)
{
if (_archives.FreeSpace is { } measure) return measure(folder);
try
{
return new DriveInfo(OperatingSystem.IsWindows() ? Path.GetPathRoot(folder)! : folder).AvailableFreeSpace;
}
catch (Exception ex) when (ex is ArgumentException or IOException or UnauthorizedAccessException)
{
return null;
}
}
}
private static string Size(long bytes) => bytes >= 1_000_000_000
? Loc.L("Common.Size.GB", (bytes / 1e9).ToString("0.0", Loc.Culture))
: Loc.L("Common.Size.MB", (bytes / 1e6).ToString("0", Loc.Culture));
private static PhotoStep Step(string key, PhotoAction action, CopyPhotoInput frame) =>
new(key, action, frame.FrameId, frame.FileName, frame.Size, string.IsNullOrEmpty(frame.Sha256) ? null : frame.Sha256.ToLowerInvariant());
private static bool Moved(ArchivePaths paths, Sequence sequence) =>
sequence.Folder.Length > 0 && !SequenceFolders.Holds(paths.Sequence(sequence.Folder), sequence.Id);
///
/// The kept sequence preselected: the one of the two that is linked to a server and lies in a server's originals archive,
/// when exactly one is (owner review 5 homes: a server's originals stay in its archive); null otherwise.
///
private async Task PreselectAsync(Guid a, Guid b, CopyPlanContext context, CancellationToken ct)
{
if (context.ServerOriginalsArchives.Count == 0) return null;
var linked = await _access.ListAsync("SELECT DISTINCT local_id FROM sync_links WHERE local_id = $1 OR local_id = $2", [a, b], r => r.GetGuid(0), ct)
.ConfigureAwait(false);
var candidates = new List();
foreach (var id in linked)
{
if (await _db.Sequences.GetAsync(id, ct).ConfigureAwait(false) is { } row && context.ServerOriginalsArchives.Contains(row.ArchiveId)) candidates.Add(id);
}
return candidates.Count == 1 ? candidates[0] : null;
}
/// Whether a queued, running or paused job (but ) targets any of .
private async Task BusyAsync(IReadOnlyCollection targets, Guid? exceptJob, CancellationToken ct)
{
var rows = await _access.ListAsync(
$"SELECT id, target_ids FROM jobs WHERE state IN ({(int)JobState.Queued}, {(int)JobState.Running}, {(int)JobState.Paused})", [],
r => (Id: r.GetGuid(0), Targets: r.GetString(1)), ct).ConfigureAwait(false);
var wanted = targets.ToHashSet();
foreach (var (id, ids) in rows)
{
if (id == exceptJob || ids.Length == 0) continue;
foreach (var part in ids.Split(','))
{
if (Guid.TryParse(part, out var target) && wanted.Contains(target)) return true;
}
}
return false;
}
///
/// 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 (: a merge planned again after an earlier run copied it) is not copied again.
///
private async Task> 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 steps = new List();
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 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));
}
return steps;
}
///
/// The copy of the drop's a merge made in the kept sequence already, among
/// : 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.
///
internal async Task HeldAsync(SequenceProject project, IReadOnlyList keepProjects, string dropArchiveName,
CancellationToken ct)
{
if (project.IsMain || project.HeadVersionId is null || project.HeadNumber <= 0) return null;
List? source = null;
foreach (var kept in keepProjects.Where(k => !k.IsMain && k.HeadNumber == project.HeadNumber + 1 && NamedAfter(k.Name, project.Name, dropArchiveName)))
{
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 null;
}
/// Whether is a name a merge gives the drop's project (, or a transplant's numbered one).
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;
}
/// A project's whole history, oldest first; null when it cannot be read.
private async Task?> HistoryAsync(Guid projectId, CancellationToken ct)
{
const int page = 200;
try
{
var all = new List();
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)
{
return null;
}
}
/// The name itself when free, else "<name> (<archive>)", then " (2)"…, each within .
internal static string FreeName(string name, string archiveName, IReadOnlySet taken)
{
if (!taken.Contains(name)) return name;
var stem = Fit(name, $" ({archiveName})");
if (!taken.Contains(stem)) return stem;
for (var n = 2; ; n++)
{
var candidate = Fit(stem, string.Create(CultureInfo.InvariantCulture, $" ({n})"));
if (!taken.Contains(candidate)) return candidate;
}
}
/// Appends , shortening so the whole fits a project name.
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;
}
/// The drop's session keys that move to the kept sequence, and those the kept archive maps to a third sequence already.
private async Task<(List Moved, List Skipped)> SessionKeysAsync(Guid keep, Guid drop, Guid keepArchiveId, CancellationToken ct)
{
var keys = await _access.ListAsync("SELECT session_key FROM sequence_sessions WHERE sequence_id = $1 ORDER BY session_key", [drop],
r => r.GetString(0), ct).ConfigureAwait(false);
var (moved, skipped) = (new List(), new List());
foreach (var key in keys.Distinct(StringComparer.Ordinal))
{
var holder = await _db.Sequences.FindBySessionKeyAsync(keepArchiveId, key, ct).ConfigureAwait(false);
if (holder is null || holder == keep || holder == drop) moved.Add(key);
else skipped.Add(key);
}
return (moved, skipped);
}
///
/// What a sequence's photos are in the index, beyond its versions: how many, their bytes, how many are hashed, flagged
/// missing, corrupt, read from the preview only or undecodable (a verify or a decode records those without another
/// frames version), and its tombstones. Of this sequence alone: an import elsewhere in its archive leaves it as it was.
///
private async Task StampAsync(Guid sequenceId, CancellationToken ct)
{
var flags = string.Join(", ", new[] { FrameFlags.Missing, FrameFlags.Corrupt, FrameFlags.PreviewOnly, FrameFlags.Undecodable }
.Select(flag => $"CAST(COALESCE(SUM(CASE WHEN (flags & {(int)flag}) <> 0 THEN 1 ELSE 0 END), 0) AS BIGINT)"));
var photos = await _access.SingleAsync(
$"SELECT CAST(count(*) AS BIGINT), CAST(COALESCE(SUM(size), 0) AS BIGINT), CAST(COALESCE(SUM(CASE WHEN sha256 IS NULL OR sha256 = '' THEN 0 ELSE 1 END), 0) AS BIGINT), {flags} FROM frames WHERE sequence_id = $1",
[sequenceId], r => string.Join(':', Enumerable.Range(0, 7).Select(i => r.GetInt64(i).ToString(CultureInfo.InvariantCulture))), ct).ConfigureAwait(false);
var removals = await _access.ScalarAsync("SELECT count(*) FROM frame_removals WHERE sequence_id = $1", [sequenceId], ct).ConfigureAwait(false);
return string.Create(CultureInfo.InvariantCulture, $"{photos}:{removals}");
}
private static string PayloadHash(SyncPayload payload) =>
Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(payload, SyncPayloadJson.Default.SyncPayload))));
private static IEnumerable FingerprintLines(Sequence keep, Sequence drop, string keepStamp, string dropStamp, MergeChoices choices,
List steps, List lastCopies, List renders, SyncPayload? payload, List projects,
List sessionKeys, List skippedKeys)
{
var inv = CultureInfo.InvariantCulture;
yield return string.Create(inv, $"keep:{keep.Id:N}:{keep.FramesVersion}:{keep.SettingsVersion}:{keepStamp}");
yield return string.Create(inv, $"drop:{drop.Id:N}:{drop.FramesVersion}:{drop.SettingsVersion}:{dropStamp}");
yield return $"policy:{choices.Photos}";
foreach (var (key, choice) in choices.PerPhoto.OrderBy(p => p.Key, StringComparer.Ordinal)) yield return $"choice:{key}:{choice}";
foreach (var (path, side) in choices.Details.OrderBy(p => p.Key, StringComparer.Ordinal)) yield return $"detail:{path}:{side}";
foreach (var line in steps.Select(s => $"{s.Action}:{s.Key}").Order(StringComparer.Ordinal)) yield return line;
foreach (var line in lastCopies.Select(l => $"last:{l.Side}:{l.Key}").Order(StringComparer.Ordinal)) yield return line;
foreach (var render in renders) yield return string.Create(inv, $"render:{render.RenderId:N}:{render.Sha256}");
if (payload is not null)
yield return "payload:" + PayloadHash(payload);
foreach (var project in projects) yield return string.Create(inv, $"{project.From}:{project.SourceProjectId:N}:{project.SourceHeadId:N}:{project.TargetName}");
foreach (var key in sessionKeys) yield return "session:" + key;
foreach (var key in skippedKeys) yield return "skipped:" + key;
}
}
/// A copy of a drop project the kept sequence holds already: the kept project and each drop version's copy there.
internal sealed record HeldProject(Guid KeptId, IReadOnlyDictionary Versions);