A merge could still trash photos it never verified, resume against a pair the user had answered meanwhile, and take different unhashed photos for copies; the dialog and the lists worded several facts wrongly or lost them on refresh. - Merge: a retry resumes only while the pair is still the job's; Verify requires the other archive online and its folder in place, stops on an unreadable photo, files a differing unhashed photo as a second version and must cover every frame before Trash; the plan hashes unmatched unhashed photos first, lists "Deleted in the other" and names the relinked servers; second versions stay discoverable (CopySides.VersionsAsync). - Integrate: a retry after a failure before the journal runs again. - Sync: a sequence back after a 404 stays Linked while its link holds; a local cull no longer asks for attention. - Block lines of both planners name the right sequence, archive, server and space through one formatter. - Compare dialog: one Details row per setting with worded values, Projects headings, Choose focuses the kept-sequence radios, the photo selection reaches rows outside the viewport, the Replace confirmation lists the losers per side, plan lines read as queued. - Matches and Library: counts first and grouped, integrating shown as a share, local matches name the other archive, the Library keeps its match and "deleted on server" statuses across a refresh. Refs #73 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
501 lines
31 KiB
C#
501 lines
31 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// 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 (<see cref="PlanAsync(Guid, Guid?, Guid, MergeChoices, CopyPlanContext, CancellationToken)"/>) 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;
|
|
/// <see cref="EnqueueAsync"/> queues the <see cref="JobKind.MergeSequences"/> job that applies exactly that plan
|
|
/// (<see cref="CreateHandler"/>), every photo hash-verified in the kept sequence before the other goes to its archive's trash.
|
|
/// </summary>
|
|
public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives, CopySides sides)
|
|
{
|
|
/// <summary>The free space a merge leaves on the kept sequence's volume beyond what it copies.</summary>
|
|
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);
|
|
|
|
/// <summary>The name a server key is shown by (default: the key): the links a merge moves and the server both are linked to.</summary>
|
|
public Func<string, string?>? ServerNames { get; init; }
|
|
|
|
internal ChronosDatabase Db => _db;
|
|
|
|
/// <summary>The name <paramref name="key"/> is shown by.</summary>
|
|
internal string ServerName(string key) => ServerNames?.Invoke(key) is { Length: > 0 } name ? name : key;
|
|
|
|
internal ArchiveService Archives => _archives;
|
|
|
|
/// <summary>The handler of <see cref="JobKind.MergeSequences"/> jobs; register it on the <see cref="JobEngine"/>.</summary>
|
|
public static IJobHandler CreateHandler(ChronosDatabase db, SequenceMerger merger, ArchiveService archives, IProjectCopier projects,
|
|
IWorkspaceGuard workspace) => new MergeJobHandler(db, merger, archives, projects, workspace);
|
|
|
|
/// <summary>
|
|
/// The dry run of merging the pair <paramref name="copyId"/>: <paramref name="keepId"/> is kept and the other goes to the
|
|
/// trash. With <paramref name="keepId"/> 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
|
|
/// <paramref name="otherId"/> and blocks with <see cref="CopyBlock.KeptUnchosen"/>.
|
|
/// </summary>
|
|
/// <exception cref="ArgumentException">The pair is not a local pair of these sequences, or a sequence is not in the index.</exception>
|
|
public Task<MergePlan> PlanAsync(Guid copyId, Guid? keepId, Guid otherId, MergeChoices choices, CopyPlanContext context, CancellationToken ct) =>
|
|
PlanAsync(copyId, keepId, otherId, choices, context, null, ct);
|
|
|
|
/// <summary>The dry run, with the jobs of <paramref name="exceptJob"/> (the merge job planning again) not counted as busy.</summary>
|
|
internal async Task<MergePlan> 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<CopyBlock>();
|
|
|
|
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);
|
|
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);
|
|
}
|
|
var steps = new List<PhotoStep>();
|
|
var excluded = new List<string>();
|
|
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.Differs:
|
|
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;
|
|
}
|
|
}
|
|
|
|
// 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<string>()
|
|
.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);
|
|
var absent = new List<CopyPhotoInput>();
|
|
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<LastCopy>();
|
|
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<string>().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),
|
|
};
|
|
}
|
|
|
|
/// <summary>
|
|
/// The other's unhashed photos only it holds, hashed now (in memory: a dry run writes nothing); null when there are none.
|
|
/// Matched by size and time only they would be copied blindly, even a photo whose content the kept sequence deleted.
|
|
/// </summary>
|
|
private async Task<CopySideInput?> HashOnlyThereAsync(CopyComparisonResult comparison, CopySideInput there, ArchivePaths dropPaths, CancellationToken ct)
|
|
{
|
|
var keys = comparison.Photos.Where(p => p.Class == PhotoClass.OnlyThere && p.Key.StartsWith(CopyComparer.UnhashedPrefix, StringComparison.Ordinal))
|
|
.Select(p => p.Key).ToHashSet(StringComparer.Ordinal);
|
|
if (keys.Count == 0) return null;
|
|
var photos = new List<CopyPhotoInput>(there.Photos.Count);
|
|
var changed = false;
|
|
foreach (var photo in there.Photos)
|
|
{
|
|
if (photo.Unusable || photo.Sha256 is { Length: > 0 } || !keys.Contains(CopyComparer.UnhashedKey(photo.Size, photo.CapturedAt, photo.FrameId))
|
|
|| await _db.Frames.GetAsync(photo.FrameId, ct).ConfigureAwait(false) is not { } frame)
|
|
{
|
|
photos.Add(photo);
|
|
continue;
|
|
}
|
|
try
|
|
{
|
|
var sha = await ContentHash.Sha256Async(dropPaths.FromRelative(frame.RelativePath), null, ct).ConfigureAwait(false);
|
|
photos.Add(photo with { Sha256 = sha.ToLowerInvariant() });
|
|
changed = true;
|
|
}
|
|
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
|
{
|
|
// Unreadable now: left as it is (the job's copy fails on it and says which file).
|
|
photos.Add(photo);
|
|
}
|
|
}
|
|
return changed ? there with { Photos = photos } : null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Queues the job that applies <paramref name="plan"/>: the pair goes to <see cref="CopyState.Integrating"/> (its state
|
|
/// before kept as the previous one), the job targets the kept sequence, then the other (both held from other jobs).
|
|
/// </summary>
|
|
/// <param name="title">The kept sequence's title, for the job's label ("Merge into {title}").</param>
|
|
/// <exception cref="InvalidOperationException">The plan is blocked, or the pair is already being merged or integrated.</exception>
|
|
/// <exception cref="StaleCopyPlanException">The pair changed state since the plan.</exception>
|
|
public async Task<Job> 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;
|
|
}
|
|
}
|
|
|
|
/// <summary>The sentence a job fails with for the first block of a plan it made again.</summary>
|
|
internal async Task<string> 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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// The sentence of <paramref name="block"/> of a merge plan, the one the dialog shows and the job fails with: the kept
|
|
/// sequence for space, the other for where it lies and its trash, the server both are linked to by its name.
|
|
/// </summary>
|
|
public static string BlockText(MergePlan plan, CopyBlock block, string keepTitle, string dropTitle, int unchosen = 1)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(plan);
|
|
return block switch
|
|
{
|
|
CopyBlock.Busy => Loc.L("Errors.Copies.Busy"),
|
|
CopyBlock.ArchiveOffline or CopyBlock.FolderMoved or CopyBlock.ChangedFile => Loc.L("Errors.Copies." + block, dropTitle),
|
|
CopyBlock.NoSpace => Loc.L("Errors.Copies.NoSpace", keepTitle, Size(plan.CopyBytes + SpaceReserve)),
|
|
CopyBlock.BothLinked => Loc.L("Errors.Copies.BothLinked", 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"),
|
|
};
|
|
}
|
|
|
|
/// <summary>Free bytes on the kept archive's volume (its root and its staging folder, the tighter); null when they cannot be measured.</summary>
|
|
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);
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
private async Task<Guid?> 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<Guid>();
|
|
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;
|
|
}
|
|
|
|
/// <summary>Whether a queued, running or paused job (but <paramref name="exceptJob"/>) targets any of <paramref name="targets"/>.</summary>
|
|
private async Task<bool> BusyAsync(IReadOnlyCollection<Guid> 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;
|
|
}
|
|
|
|
/// <summary>The drop's non-Main projects, each with the name it gets at the kept sequence's home.</summary>
|
|
private async Task<List<ProjectStep>> ProjectStepsAsync(Guid keep, Guid drop, string dropArchiveName, CancellationToken ct)
|
|
{
|
|
var taken = (await _db.Projects.ListBySequenceAsync(keep, includeDeleted: false, ct).ConfigureAwait(false)).Select(p => p.Name)
|
|
.ToHashSet(StringComparer.OrdinalIgnoreCase);
|
|
var steps = new List<ProjectStep>();
|
|
foreach (var project in (await _db.Projects.ListBySequenceAsync(drop, includeDeleted: false, ct).ConfigureAwait(false))
|
|
.Where(p => !p.IsMain).OrderBy(p => p.CreatedAt).ThenBy(p => p.Id))
|
|
{
|
|
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;
|
|
}
|
|
|
|
/// <summary>The name itself when free, else "<name> (<archive>)", then " (2)"…, each within <see cref="ProjectService.MaxNameLength"/>.</summary>
|
|
internal static string FreeName(string name, string archiveName, IReadOnlySet<string> taken)
|
|
{
|
|
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;
|
|
}
|
|
|
|
static string Fit(string stem, string suffix)
|
|
{
|
|
const int max = ProjectService.MaxNameLength;
|
|
if (suffix.Length >= max) suffix = suffix[..(max / 2)];
|
|
return (stem.Length + suffix.Length > max ? stem[..(max - suffix.Length)].TrimEnd() : stem) + suffix;
|
|
}
|
|
}
|
|
|
|
/// <summary>The drop's session keys that move to the kept sequence, and those the kept archive maps to a third sequence already.</summary>
|
|
private async Task<(List<string> Moved, List<string> 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<string>(), new List<string>());
|
|
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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
private async Task<string> 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<long>("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<string> FingerprintLines(Sequence keep, Sequence drop, string keepStamp, string dropStamp, MergeChoices choices,
|
|
List<PhotoStep> steps, List<LastCopy> lastCopies, List<RenderStep> renders, SyncPayload? payload, List<ProjectStep> projects,
|
|
List<string> sessionKeys, List<string> 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;
|
|
}
|
|
}
|