fix(archive): settle trash journals under their leases and say why restored photos stayed
Second fix round of owner review 2, phase 3 (engine, server, desktop). - A photo never hashed whose original is missing can be deleted again: it goes into its trash record without a file and without a tombstone (nothing is left to name), stays listed until Empty erases it, and a restore keeps it with the reason "no file". FrameDeleteBlock.Unhashable now blocks only a present original that cannot be read; the API answers it as 409 photo_unreadable naming the photo, and every block has its own code and message. - Deleting a whole sequence first settles an interrupted photo deletion, restore or ingest of it (ReadLocked under its lease), so no journal or half entry travels into the sequence's trash entry; it refuses while a restore into it waits for its busy entry. - FrameTrash.Settle takes the photo entry's lease and leaves the journal for later while the entry is busy (an emptying), so it never races EraseAsync; meanwhile no other restore writes its journal over it and scans do not adopt its files. - The hashes computed for frames that stay (to find a twin of a deleted photo) go into the sidecar and index, and only a frame whose first and last 64 KiB match a deleted photo's is read whole. - A restore into a new sequence rewrites its record after each photo filed, so a crash or a database failure never leaves filed photos listed. - An upload completion no longer has a window before the commit: the ingest checks the sidecar's tombstones under the sequence lease a deletion takes (IngestRequest.RefuseRemoved), unless the upload asked to bring it back. - A restore reports each kept photo with its reason (no longer matches its record, could not be moved back, already in the sequence, had no file); the desktop line and the API message say so in en and it, and the tooltip holds the whole sentence. The desktop tells TrashMismatchException by its type. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 1858f1f450a35fb8383ede8d80ce5f8de9b7ceac)
This commit is contained in:
1 parent
a133306fb0
commit
4518ffe655
29 files changed
+856
-162
No files matched your search
@@ -28,8 +28,10 @@ public enum FrameDeleteBlock
|
||||
WouldEmpty,
|
||||
|
||||
/// <summary>
|
||||
/// A photo named was never hashed and its original is missing (<see cref="FrameDeletePlan.Unhashable"/>): no tombstone
|
||||
/// could tell sync it was deleted, so a copy elsewhere would come back. A verify or a scan settles it first.
|
||||
/// A photo named was never hashed and its original is on disk but cannot be read (another program holds it, or no
|
||||
/// access; <see cref="FrameDeletePlan.Unhashable"/>): it is hashed as it goes, for the tombstone that tells sync it was
|
||||
/// deleted, so it waits until it can be read. One whose original is missing is not blocked: it goes without a file and
|
||||
/// without a tombstone, as there is no content left to name.
|
||||
/// </summary>
|
||||
Unhashable,
|
||||
}
|
||||
@@ -42,18 +44,52 @@ public sealed record FrameDeletePlan(Sequence Sequence, IReadOnlyList<Frame> Fra
|
||||
{
|
||||
public bool CanDelete => Blocked.Count == 0 && Frames.Count > 0;
|
||||
|
||||
/// <summary>The frames named that block the plan as <see cref="FrameDeleteBlock.Unhashable"/>.</summary>
|
||||
/// <summary>The frames named that block the plan as <see cref="FrameDeleteBlock.Unhashable"/>, in index order.</summary>
|
||||
public IReadOnlyList<Frame> Unhashable { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <summary>What a photo deletion did: the trash entry made and the sequence as it is now.</summary>
|
||||
public sealed record FrameDeleteResult(TrashEntry Entry, Sequence Sequence);
|
||||
|
||||
/// <summary>Why a photo stayed in the trash when its entry was restored.</summary>
|
||||
public enum KeptReason
|
||||
{
|
||||
/// <summary>A file of it no longer matches its record (changed, or gone from the entry).</summary>
|
||||
Mismatch,
|
||||
|
||||
/// <summary>Its files match, but they could not be moved back (open elsewhere, no access, or the archive refused them).</summary>
|
||||
NotMoved,
|
||||
|
||||
/// <summary>The sequence holds its content again (restored before, or filed again since): the trash keeps its copy.</summary>
|
||||
InSequence,
|
||||
|
||||
/// <summary>Its original was already missing when it was deleted: the entry holds its record without a file.</summary>
|
||||
NoFile,
|
||||
}
|
||||
|
||||
/// <summary>A photo a restore left in the trash: its name (as on the card or upload source) and why.</summary>
|
||||
public sealed record KeptPhoto(string Name, KeptReason Reason)
|
||||
{
|
||||
/// <summary>"2 photos stayed in the trash: they no longer match their record." in <paramref name="culture"/>.</summary>
|
||||
public static string Sentence(KeptReason reason, int count, System.Globalization.CultureInfo culture) =>
|
||||
Core.Localization.Loc.Text(reason switch
|
||||
{
|
||||
KeptReason.Mismatch => "Archive.Trash.Kept.Mismatch",
|
||||
KeptReason.NotMoved => "Archive.Trash.Kept.NotMoved",
|
||||
KeptReason.InSequence => "Archive.Trash.Kept.InSequence",
|
||||
_ => "Archive.Trash.Kept.NoFile",
|
||||
}, [count], culture);
|
||||
|
||||
/// <summary>One sentence per reason, in the order of <see cref="KeptReason"/>, each counting its photos.</summary>
|
||||
public static IReadOnlyList<string> Sentences(IEnumerable<KeptPhoto> kept, System.Globalization.CultureInfo culture) =>
|
||||
[.. kept.GroupBy(k => k.Reason).OrderBy(g => g.Key).Select(g => Sentence(g.Key, g.Count(), culture))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What a restore of photos did: the sequence they went back into (a new one when theirs is gone), how many came back, and
|
||||
/// the files kept in the trash because they no longer match their record (or their photo is in the sequence again).
|
||||
/// the photos kept in the trash, each with why (<see cref="KeptReason"/>).
|
||||
/// </summary>
|
||||
public sealed record PhotoRestoreResult(Sequence Sequence, int Restored, IReadOnlyList<string> Kept, bool NewSequence);
|
||||
public sealed record PhotoRestoreResult(Sequence Sequence, int Restored, IReadOnlyList<KeptPhoto> Kept, bool NewSequence);
|
||||
|
||||
/// <summary>
|
||||
/// Deleting photos of a sequence without erasing anything (owner review 2, R6; BRIEF §0.2 rule 8): <see cref="PlanDeleteAsync"/>
|
||||
@@ -126,32 +162,40 @@ public sealed partial class FrameTrash
|
||||
if (busy.Contains(sequence.Id) || busy.Contains(sequence.ArchiveId)) blocked.Add(FrameDeleteBlock.Busy);
|
||||
if (frames.Count != wanted.Count || (expectedFramesVersion is { } expected && expected != sequence.FramesVersion)) blocked.Add(FrameDeleteBlock.FramesChanged);
|
||||
if (frames.Count > 0 && frames.Count == all.Count) blocked.Add(FrameDeleteBlock.WouldEmpty);
|
||||
// A photo without a hash is hashed as it goes; one whose original is gone as well could leave no tombstone.
|
||||
var unhashable = online ? Unhashable(paths, frames) : [];
|
||||
// A photo without a hash is hashed as it goes, for its tombstone: one whose original cannot be read waits.
|
||||
var unhashable = online ? Unreadable(paths, frames) : [];
|
||||
if (unhashable.Count > 0) blocked.Add(FrameDeleteBlock.Unhashable);
|
||||
return new FrameDeletePlan(sequence, frames, frames.Sum(f => f.Size), blocked) { Unhashable = unhashable };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The frames never hashed whose original is not on disk, in index order; a directory holding many of them is listed
|
||||
/// once rather than asked about each (a share answers one listing faster than thousands of lookups).
|
||||
/// The frames never hashed whose original is on disk but cannot be opened for reading, in index order: the first
|
||||
/// <c>256</c> of them are opened (nothing is read), so a dry run of thousands stays quick on a share; one past those that
|
||||
/// cannot be read refuses the deletion itself, which hashes them (an <see cref="IOException"/>, nothing moved). A missing
|
||||
/// original is no reason: nothing is left to hash.
|
||||
/// </summary>
|
||||
private static List<Frame> Unhashable(ArchivePaths paths, IReadOnlyList<Frame> frames)
|
||||
private static List<Frame> Unreadable(ArchivePaths paths, IReadOnlyList<Frame> frames)
|
||||
{
|
||||
const int Lookups = 64;
|
||||
var names = OperatingSystem.IsWindows() || OperatingSystem.IsMacOS() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal;
|
||||
var missing = new List<Frame>();
|
||||
foreach (var directory in frames.Where(f => f.Sha256 is null).GroupBy(f => Path.GetDirectoryName(paths.FromRelative(f.RelativePath)) ?? string.Empty))
|
||||
const int Probes = 256;
|
||||
return [.. frames.Where(f => f.Sha256 is null).OrderBy(f => f.Index).Take(Probes).Where(f => !CanRead(paths.FromRelative(f.RelativePath)))];
|
||||
}
|
||||
|
||||
/// <summary>Whether a file opens for reading; one that is not there counts as readable (there is nothing to read).</summary>
|
||||
private static bool CanRead(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (directory.Count() <= Lookups || !System.IO.Directory.Exists(directory.Key))
|
||||
{
|
||||
missing.AddRange(directory.Where(f => !File.Exists(paths.FromRelative(f.RelativePath))));
|
||||
continue;
|
||||
}
|
||||
var present = System.IO.Directory.EnumerateFiles(directory.Key).Select(p => Path.GetFileName(p)).ToHashSet(names);
|
||||
missing.AddRange(directory.Where(f => !present.Contains(Path.GetFileName(paths.FromRelative(f.RelativePath)))));
|
||||
using var handle = File.OpenHandle(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is FileNotFoundException or DirectoryNotFoundException)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return [.. missing.OrderBy(f => f.Index)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -202,8 +246,10 @@ public sealed partial class FrameTrash
|
||||
var name = EntryName(trash, id);
|
||||
var entryFolder = Path.Combine(trash, name);
|
||||
var recordPath = entryFolder + RecordExtension;
|
||||
var photos = await TrashedAsync(folder, id, removed, kept, cancellationToken).ConfigureAwait(false);
|
||||
var held = await HeldAsync(folder, kept, photos, cancellationToken).ConfigureAwait(false);
|
||||
var photos = await TrashedAsync(folder, removed, kept, cancellationToken).ConfigureAwait(false);
|
||||
var (held, hashed) = await HeldAsync(folder, kept, photos, cancellationToken).ConfigureAwait(false);
|
||||
// The hashes computed for frames that stay go into the sidecar with them: a later deletion does not read them again.
|
||||
if (hashed.Count > 0) kept = [.. kept.Select(f => hashed.TryGetValue(f.Id, out var sha) ? f with { Sha256 = sha } : f)];
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var record = new PhotoTrashRecord(TrashKind.Photos, id, revised.Sequence.DisplayTitle, revised.Sequence.Folder, photos,
|
||||
photos.Sum(p => p.Files.Sum(f => f.Size)), now, deletedBy);
|
||||
@@ -290,11 +336,12 @@ public sealed partial class FrameTrash
|
||||
/// <summary>
|
||||
/// The files of each frame that goes: its original (with the hash it was archived with, or one computed now for a frame
|
||||
/// never hashed) under the entry's <c>originals/</c>, and an XMP companion (<c>IMG_0001.xmp</c>, <c>IMG_0001.CR2.xmp</c>)
|
||||
/// no frame that stays shares. A frame whose original is missing goes without a file; one never hashed as well refuses
|
||||
/// the plan (<see cref="FrameDeleteBlock.Unhashable"/>).
|
||||
/// no frame that stays shares. A frame whose original is missing goes without a file: its record stays in the entry,
|
||||
/// which cannot bring it back, and one never hashed leaves no tombstone either, so a copy of it elsewhere (another PC,
|
||||
/// a card) is not known to be deleted.
|
||||
/// </summary>
|
||||
/// <exception cref="StaleDeletePlanException">A frame never hashed has lost its original since the plan.</exception>
|
||||
private static async Task<List<TrashedPhoto>> TrashedAsync(SequencePaths folder, Guid sequenceId, List<SidecarFrame> removed, List<SidecarFrame> kept,
|
||||
/// <exception cref="IOException">An original never hashed cannot be read; nothing moved.</exception>
|
||||
private static async Task<List<TrashedPhoto>> TrashedAsync(SequencePaths folder, List<SidecarFrame> removed, List<SidecarFrame> kept,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var used = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
@@ -322,32 +369,66 @@ public sealed partial class FrameTrash
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (sha is null)
|
||||
{
|
||||
throw new StaleDeletePlanException(sequenceId);
|
||||
}
|
||||
photos.Add(new TrashedPhoto(frame with { Sha256 = sha }, files, null));
|
||||
}
|
||||
return photos;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The SHA-256 the frames that stay hold: those of their sidecar, and that of each one never hashed whose size is a
|
||||
/// deleted photo's (hashed now), so a duplicate that stays keeps its content out of the tombstones.
|
||||
/// The SHA-256 the frames that stay hold, so a duplicate that stays keeps its content out of the tombstones: those of
|
||||
/// their sidecar, and that of each one never hashed that may hold a deleted photo's content, hashed now (returned by
|
||||
/// frame, for the sidecar). The work is bounded: only a frame with a deleted photo's size is looked at, and only one
|
||||
/// whose first and last 64 KiB match that photo's (<see cref="EdgesAsync"/>) is read whole, so a sequence of raw files of
|
||||
/// one size reads 128 KiB a frame, not every file.
|
||||
/// </summary>
|
||||
private static async Task<HashSet<string>> HeldAsync(SequencePaths folder, List<SidecarFrame> kept, List<TrashedPhoto> photos,
|
||||
CancellationToken cancellationToken)
|
||||
private static async Task<(HashSet<string> Held, Dictionary<Guid, string> Hashed)> HeldAsync(SequencePaths folder, List<SidecarFrame> kept,
|
||||
List<TrashedPhoto> photos, CancellationToken cancellationToken)
|
||||
{
|
||||
var held = kept.Where(f => f.Sha256 is not null).Select(f => f.Sha256!).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var sizes = photos.Where(p => p.Files.Count > 0).Select(p => p.Files[0].Size).ToHashSet();
|
||||
foreach (var frame in kept.Where(f => f.Sha256 is null && sizes.Contains(f.Size)))
|
||||
var hashed = new Dictionary<Guid, string>();
|
||||
var deleted = photos.Where(p => p.Files.Count > 0).GroupBy(p => p.Files[0].Size).ToDictionary(g => g.Key, g => g.Select(p => p.Files[0].From).ToList());
|
||||
var edges = new Dictionary<long, HashSet<string>>();
|
||||
foreach (var frame in kept.Where(f => f.Sha256 is null && deleted.ContainsKey(f.Size)))
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var file = new FileInfo(folder.File(frame.File));
|
||||
if (file.Exists && sizes.Contains(file.Length))
|
||||
held.Add(await ContentHash.Sha256Async(file.FullName, null, cancellationToken).ConfigureAwait(false));
|
||||
if (!file.Exists || file.Length != frame.Size) continue;
|
||||
if (!edges.TryGetValue(frame.Size, out var known))
|
||||
{
|
||||
// The deleted photos of that size are still in place: the moves come later.
|
||||
known = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var from in deleted[frame.Size]) known.Add(await EdgesAsync(folder.File(from), cancellationToken).ConfigureAwait(false));
|
||||
edges[frame.Size] = known;
|
||||
}
|
||||
if (!known.Contains(await EdgesAsync(file.FullName, cancellationToken).ConfigureAwait(false))) continue;
|
||||
var sha = await ContentHash.Sha256Async(file.FullName, null, cancellationToken).ConfigureAwait(false);
|
||||
hashed[frame.Id] = sha;
|
||||
held.Add(sha);
|
||||
}
|
||||
return held;
|
||||
return (held, hashed);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SHA-256 of a file's first and last 64 KiB (the whole file when smaller): two files of one size whose edges differ
|
||||
/// differ in content, so only those whose edges match need a full hash.
|
||||
/// </summary>
|
||||
private static async Task<string> EdgesAsync(string path, CancellationToken cancellationToken)
|
||||
{
|
||||
const int Edge = 64 * 1024;
|
||||
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, 1,
|
||||
FileOptions.Asynchronous | FileOptions.RandomAccess);
|
||||
using var hash = System.Security.Cryptography.IncrementalHash.CreateHash(System.Security.Cryptography.HashAlgorithmName.SHA256);
|
||||
var buffer = new byte[Edge];
|
||||
var length = stream.Length;
|
||||
var read = await stream.ReadAtLeastAsync(buffer, (int)System.Math.Min(Edge, length), throwOnEndOfStream: false, cancellationToken).ConfigureAwait(false);
|
||||
hash.AppendData(buffer, 0, read);
|
||||
if (length > Edge)
|
||||
{
|
||||
stream.Position = System.Math.Max(Edge, length - Edge);
|
||||
read = await stream.ReadAtLeastAsync(buffer, (int)(length - stream.Position), throwOnEndOfStream: false, cancellationToken).ConfigureAwait(false);
|
||||
hash.AppendData(buffer, 0, read);
|
||||
}
|
||||
return Convert.ToHexStringLower(hash.GetHashAndReset());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
Reference in new issue
Block a user