feat(archive): merge two local sequences into the kept one (owner review 6, P4)
SequenceMerger plans the merge of a local pair (kept sequence, photos copied by policy, last copies, renders, details, projects, session keys, links, blocks and a fingerprint) and queues the MergeSequences job. MergeJobHandler applies the confirmed plan through a journal, so every stage resumes: copy and file the other's photos, move renders, hash-verify every original of the other in the kept one (or list it as a last copy), trash the kept one's losing versions, write the details (SequencePayloadWriter), copy projects, move keys and links, then move the other to its archive's trash only at the verified frames version. A cancel drops the journal and returns the pair to its previous state. Refs #73 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9912baf78a
commit
b4070ddfd4
6 files changed
+2062
No files matched your search
@@ -0,0 +1,439 @@
|
||||
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);
|
||||
|
||||
internal ChronosDatabase Db => _db;
|
||||
|
||||
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);
|
||||
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();
|
||||
if (links.GroupBy(l => l.Server, StringComparer.Ordinal).Any(g => g.Select(l => l.Local).Distinct().Count() > 1)) 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);
|
||||
}
|
||||
|
||||
/// <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);
|
||||
var (keepTitle, dropTitle) = (keep?.DisplayTitle ?? string.Empty, drop?.DisplayTitle ?? string.Empty);
|
||||
return plan.Blocks[0] switch
|
||||
{
|
||||
CopyBlock.Busy => Loc.L("Errors.Copies.Busy"),
|
||||
CopyBlock.ArchiveOffline => Loc.L("Errors.Copies.ArchiveOffline", dropTitle),
|
||||
CopyBlock.FolderMoved => Loc.L("Errors.Copies.FolderMoved", dropTitle),
|
||||
CopyBlock.NoSpace => Loc.L("Errors.Copies.NoSpace", keepTitle, Size(plan.CopyBytes + SpaceReserve)),
|
||||
CopyBlock.BothLinked => Loc.L("Errors.Copies.BothLinked", 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", 1),
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user