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
@@ -257,10 +257,19 @@ public sealed class ArchiveIndexer
|
||||
/// sidecar then tells every host, so the follow-ups make them again (the images on a server,
|
||||
/// <see cref="ArchiveServiceOptions.ImagesAfterScan"/>).
|
||||
/// </summary>
|
||||
private static SequenceManifest? Reconcile(SequencePaths sequence, SequenceManifest manifest, CancellationToken cancellationToken) =>
|
||||
SequenceAdopter.Reconcile(sequence, manifest, cancellationToken) is { } reconciled
|
||||
private static SequenceManifest? Reconcile(SequencePaths sequence, SequenceManifest manifest, CancellationToken cancellationToken)
|
||||
{
|
||||
// A restore from the trash that could not be settled yet (its entry busy) may have photos in the folder its sidecar
|
||||
// does not list: they are its own, not photos to adopt, until a later writer settles it.
|
||||
if (File.Exists(sequence.RestoreJournalPath))
|
||||
{
|
||||
Log.Info("archive", $"{sequence.RelativeFolder} is not reconciled while a restore from the trash into it waits");
|
||||
return null;
|
||||
}
|
||||
return SequenceAdopter.Reconcile(sequence, manifest, cancellationToken) is { } reconciled
|
||||
? reconciled with { Status = reconciled.Status & ~CoveringStatus }
|
||||
: null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies <paramref name="edit"/> to the sidecar (null writes nothing) and indexes the result, both under the sequence
|
||||
|
||||
@@ -12,8 +12,9 @@ namespace Chronos.Data.Archiving;
|
||||
|
||||
/// <summary>A verified staged file and how to name it.</summary>
|
||||
/// <param name="PlannedName">Name chosen by an import plan; null = the archive's file template.</param>
|
||||
/// <param name="RefuseRemoved">See <see cref="IngestRequest.RefuseRemoved"/>.</param>
|
||||
internal sealed record StagedFrame(string StagedPath, string OriginalFileName, long Size, string Sha256, FrameMetadata Metadata,
|
||||
DateTime? ClientCapturedAt, string? PlannedName);
|
||||
DateTime? ClientCapturedAt, string? PlannedName, bool RefuseRemoved = false);
|
||||
|
||||
/// <summary>A sequence found or created by key (upload session, card session, or a new title).</summary>
|
||||
/// <param name="PreferredFolder">Folder of an import plan; null = the archive's folder template.</param>
|
||||
@@ -54,7 +55,7 @@ public sealed class ArchiveIngest : IArchiveIngest
|
||||
if (!staged.Exists || staged.Length != request.Size)
|
||||
throw new FileNotFoundException("The staged file is missing or has another size.", request.StagedPath);
|
||||
var frame = new StagedFrame(request.StagedPath, request.OriginalFileName, request.Size, request.Sha256,
|
||||
MetadataReader.Read(request.StagedPath, cancellationToken), request.ClientCapturedAt, null);
|
||||
MetadataReader.Read(request.StagedPath, cancellationToken), request.ClientCapturedAt, null, request.RefuseRemoved);
|
||||
|
||||
Guid sequenceId;
|
||||
if (request.SequenceId is { } id)
|
||||
@@ -297,6 +298,7 @@ public sealed class ArchiveIngest : IArchiveIngest
|
||||
var photosChanged = !inStep && await _indexer.PhotosChangedAsync(archive, sequence, cancellationToken).ConfigureAwait(false);
|
||||
var before = manifest.Frames.Count;
|
||||
var held = manifest.Frames.Where(f => f.Sha256 is not null).ToLookup(f => f.Sha256!, StringComparer.OrdinalIgnoreCase);
|
||||
var tombstoned = (manifest.Removed ?? []).Select(r => r.Sha256).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
// Content this batch files (new frames and repairs): another copy of it in the batch is a duplicate of that frame.
|
||||
var filed = new Dictionary<string, Guid>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
@@ -305,6 +307,13 @@ public sealed class ArchiveIngest : IArchiveIngest
|
||||
var duplicates = new List<(Pending Pending, Guid FrameId)>();
|
||||
foreach (var p in batch)
|
||||
{
|
||||
// Deleted from the sequence (its tombstone, and no frame holds the content) and not asked back: checked under the
|
||||
// lease a deletion takes, so none lands between this check and the commit (owner review 2, R6).
|
||||
if (p.Frame.RefuseRemoved && tombstoned.Contains(p.Frame.Sha256) && !held[p.Frame.Sha256].Any())
|
||||
{
|
||||
p.Completion.TrySetException(new PhotoRemovedException(sequenceId, p.Frame.Sha256));
|
||||
continue;
|
||||
}
|
||||
if (filed.TryGetValue(p.Frame.Sha256, out var same))
|
||||
{
|
||||
duplicates.Add((p, same));
|
||||
|
||||
@@ -364,7 +364,7 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
CancellationToken cancellationToken = default) =>
|
||||
Trash.DeleteAsync(plan, deletedBy, progress, cancellationToken);
|
||||
|
||||
/// <summary>The sequences in an archive's trash, newest first.</summary>
|
||||
/// <summary>The entries of an archive's trash, newest first: deleted sequences and photos deleted from sequences (<see cref="SequenceTrash.ListAsync"/>).</summary>
|
||||
public async Task<IReadOnlyList<TrashEntry>> ListTrashAsync(Guid archiveId, CancellationToken cancellationToken = default) =>
|
||||
await Trash.ListAsync(await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
@@ -379,6 +379,9 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
/// </summary>
|
||||
/// <exception cref="DirectoryNotFoundException">The entry is not in the trash.</exception>
|
||||
/// <exception cref="SequenceInLibraryException">A sequence entry whose sequence is in the index already.</exception>
|
||||
/// <exception cref="TrashMismatchException">No file of a photo entry matches its record; nothing moved.</exception>
|
||||
/// <exception cref="InvalidDataException">A sidecar is damaged or another sequence's (the trashed folder's own, or that of
|
||||
/// the sequence the photos go back into); nothing moved.</exception>
|
||||
public async Task<TrashRestoreResult> RestoreEntryAsync(Guid archiveId, string entryName, JobEngine? followUps = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
@@ -469,9 +472,9 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
|
||||
/// <summary>
|
||||
/// What a restore from the trash did: the kind of entry, the sequence restored (or the one the photos went back into),
|
||||
/// and for photos how many came back, the files kept in the trash and whether they went into a new sequence.
|
||||
/// and for photos how many came back, the photos kept in the trash (each with why) and whether they went into a new sequence.
|
||||
/// </summary>
|
||||
public sealed record TrashRestoreResult(TrashKind Kind, Sequence Sequence, int Photos, IReadOnlyList<string> Kept, bool NewSequence);
|
||||
public sealed record TrashRestoreResult(TrashKind Kind, Sequence Sequence, int Photos, IReadOnlyList<KeptPhoto> Kept, bool NewSequence);
|
||||
|
||||
/// <summary>The fields of a sequence the user describes it with (sidecar and index).</summary>
|
||||
public sealed record SequenceInfo(string? Title, IReadOnlyList<string> Tags, int Rating, string? Notes);
|
||||
|
||||
@@ -20,20 +20,26 @@ public sealed partial class FrameTrash
|
||||
/// </summary>
|
||||
private const string RestoringFolder = ".restoring";
|
||||
|
||||
/// <summary>Who takes an entry's lease while settling a restore another writer of its sequence finds (<see cref="Settle"/>).</summary>
|
||||
private static readonly string SettleOwner = "chronos@" + Environment.MachineName;
|
||||
|
||||
/// <summary>
|
||||
/// Brings the photos of a trash entry back. Each file is re-hashed against its record: a file that no longer matches
|
||||
/// (or is missing) stays in the trash with its photo, which is reported, as is a photo whose content an intact frame of
|
||||
/// the sequence holds again. The others move back to their places (a name taken since, or one of its companions',
|
||||
/// gets <c>_2</c>, <c>_3</c>…) with the same frame records, inserted by capture time, and their tombstones go; a
|
||||
/// journal (<see cref="FrameRestoreJournal"/>) settles a restore a crash interrupted, and once the first file moves
|
||||
/// the restore runs to its end whatever the caller cancels. When the sequence is gone (deleted, or never indexed in
|
||||
/// this archive), they go into a new sequence through the archive ingest, titled and placed as theirs was; a cancel
|
||||
/// there stops before the next photo, with the record kept true. The entry goes once nothing is left in it.
|
||||
/// the sequence holds again, and one whose files could not move. Each kept photo says why (<see cref="KeptReason"/>).
|
||||
/// The others move back to their places (a name taken since, or one of its companions', gets <c>_2</c>, <c>_3</c>…)
|
||||
/// with the same frame records, inserted by capture time, and their tombstones go; a journal
|
||||
/// (<see cref="FrameRestoreJournal"/>) settles a restore a crash interrupted, and once the first file moves the restore
|
||||
/// runs to its end whatever the caller cancels. When the sequence is gone (deleted, or never indexed in this archive),
|
||||
/// they go into a new sequence through the archive ingest, titled and placed as theirs was, the record rewritten after
|
||||
/// each photo filed; a cancel there stops before the next photo. The entry goes once nothing is left in it.
|
||||
/// </summary>
|
||||
/// <param name="name">The entry's <see cref="TrashEntry.Name"/> (<c>photos-…</c>).</param>
|
||||
/// <exception cref="DirectoryNotFoundException">The entry is not in the trash.</exception>
|
||||
/// <exception cref="TrashMismatchException">No file of the entry matches its record; nothing moved.</exception>
|
||||
/// <exception cref="InvalidDataException">The sequence's sidecar is damaged or belongs to another sequence; nothing moved.</exception>
|
||||
/// <exception cref="LeaseUnavailableException">The entry or the sequence is busy, or the sequence holds a restore of another
|
||||
/// entry that is busy and not settled yet; nothing moved.</exception>
|
||||
public async Task<PhotoRestoreResult> RestoreAsync(Archive archive, string name, JobEngine? followUps = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
@@ -42,8 +48,10 @@ public sealed partial class FrameTrash
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
var entryFolder = Path.Combine(Directory(paths), DiskName(name));
|
||||
var recordPath = entryFolder + RecordExtension;
|
||||
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, SequenceTrash.EntryLease(name), _writer.Options.Owner, _writer.Options.LeaseWait,
|
||||
_writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
|
||||
// The entry's lease by the name the trash lists it under, the one an emptying and a settle take.
|
||||
var lease = SequenceTrash.EntryLease(EntryPrefix + DiskName(name));
|
||||
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, lease, _writer.Options.Owner, _writer.Options.LeaseWait, _writer.Options.LeaseDuration,
|
||||
cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (!System.IO.Directory.Exists(entryFolder) || ReadRecord(recordPath) is not { } listed)
|
||||
throw new DirectoryNotFoundException($"{name} is not in the trash of {archive.Name}.");
|
||||
@@ -52,7 +60,10 @@ public sealed partial class FrameTrash
|
||||
// What an earlier restore a crash interrupted left half-way is settled first, so the record read next is true.
|
||||
Unstage(entryFolder);
|
||||
if (into is not null && File.Exists(paths.Sequence(into.Folder).RestoreJournalPath))
|
||||
await _writer.UpdateAsync(paths, into.Id, into.Folder, _ => null, cancellationToken).ConfigureAwait(false);
|
||||
{
|
||||
await using (await _writer.LockAsync(paths, into.Id, cancellationToken).ConfigureAwait(false))
|
||||
SequenceWriter.ReadLocked(paths.Sequence(into.Folder), into.Id, lease);
|
||||
}
|
||||
if (!System.IO.Directory.Exists(entryFolder) || ReadRecord(recordPath) is not { } record)
|
||||
throw new DirectoryNotFoundException($"{name} is not in the trash of {archive.Name}.");
|
||||
var (intact, kept) = await CheckAsync(entryFolder, record, cancellationToken).ConfigureAwait(false);
|
||||
@@ -60,29 +71,30 @@ public sealed partial class FrameTrash
|
||||
if (intact.Count == 0) throw new TrashMismatchException();
|
||||
var had = into?.Status ?? SequenceStatus.None;
|
||||
PhotoRestoreResult result;
|
||||
List<TrashedPhoto> stays;
|
||||
List<Stay> stays;
|
||||
var stopped = false;
|
||||
if (into is not null)
|
||||
{
|
||||
// The record is settled under the sequence's lease, with the sidecar.
|
||||
(result, var left) = await IntoSequenceAsync(archive, paths, into, recordPath, entryFolder, intact, cancellationToken).ConfigureAwait(false);
|
||||
(result, var left) = await IntoSequenceAsync(archive, paths, into, recordPath, entryFolder, lease, intact, cancellationToken).ConfigureAwait(false);
|
||||
stays = [.. kept, .. left];
|
||||
}
|
||||
else
|
||||
{
|
||||
var restore = await IntoNewSequenceAsync(archive, paths, record, entryFolder, intact, cancellationToken).ConfigureAwait(false);
|
||||
var restore = await IntoNewSequenceAsync(archive, paths, record, recordPath, entryFolder, intact, cancellationToken).ConfigureAwait(false);
|
||||
stays = [.. kept, .. restore.Left];
|
||||
Rewrite(recordPath, entryFolder, record with { Photos = stays, Leftovers = Merge(record.Leftovers, restore.Leftovers) });
|
||||
Rewrite(recordPath, entryFolder, record with { Photos = [.. stays.Select(s => s.Photo)], Leftovers = Merge(record.Leftovers, restore.Leftovers) });
|
||||
restore.Failure?.Throw();
|
||||
stopped = restore.Stopped;
|
||||
if (stopped && restore.Restored == 0) throw new OperationCanceledException(cancellationToken);
|
||||
if (restore.SequenceId is not { } id) throw new IOException(Core.Localization.Loc.L("Archive.Error.TrashMismatch"));
|
||||
if (restore.SequenceId is not { } id)
|
||||
throw new IOException($"No photo of trash entry {Path.GetFileName(entryFolder)} could be filed into a new sequence; they stay in the trash.");
|
||||
var row = await _db.Sequences.GetAsync(id, CancellationToken.None).ConfigureAwait(false)
|
||||
?? throw new InvalidOperationException($"The photos of {record.SequenceTitle} were restored but their sequence is not indexed.");
|
||||
result = new PhotoRestoreResult(row, restore.Restored, [], true);
|
||||
}
|
||||
Log.Info("archive", $"{record.SequenceTitle}: {result.Restored} photo(s) restored from the trash, {stays.Count} kept there");
|
||||
var all = result with { Kept = [.. stays.Select(p => p.Frame.Original ?? Path.GetFileName(p.Frame.File))] };
|
||||
var all = result with { Kept = [.. stays.Select(s => new KeptPhoto(s.Photo.Frame.Original ?? Path.GetFileName(s.Photo.Frame.File), s.Reason))] };
|
||||
if (result.Restored > 0) await QueueAsync(followUps, archive, all.Sequence, had, CancellationToken.None).ConfigureAwait(false);
|
||||
// A cancel stopped a restore into a new sequence before its last photo: those not done stay in the trash, listed.
|
||||
if (stopped) throw new OperationCanceledException(cancellationToken);
|
||||
@@ -90,15 +102,26 @@ public sealed partial class FrameTrash
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Each photo whose files all match their record (size and SHA-256), and those that stay in the trash.</summary>
|
||||
private static async Task<(List<TrashedPhoto> Intact, List<TrashedPhoto> Kept)> CheckAsync(string entryFolder, PhotoTrashRecord record,
|
||||
/// <summary>A photo a restore leaves in its entry, and why.</summary>
|
||||
private sealed record Stay(TrashedPhoto Photo, KeptReason Reason);
|
||||
|
||||
/// <summary>
|
||||
/// Each photo whose files all match their record (size and SHA-256), and those that stay in the trash: a file that does
|
||||
/// not match, or no file at all (its original was missing when it was deleted).
|
||||
/// </summary>
|
||||
private static async Task<(List<TrashedPhoto> Intact, List<Stay> Kept)> CheckAsync(string entryFolder, PhotoTrashRecord record,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var intact = new List<TrashedPhoto>();
|
||||
var kept = new List<TrashedPhoto>();
|
||||
var kept = new List<Stay>();
|
||||
foreach (var photo in record.Photos)
|
||||
{
|
||||
var ok = photo.Files.Count > 0;
|
||||
if (photo.Files.Count == 0)
|
||||
{
|
||||
kept.Add(new Stay(photo, KeptReason.NoFile));
|
||||
continue;
|
||||
}
|
||||
var ok = true;
|
||||
foreach (var file in photo.Files)
|
||||
{
|
||||
var path = Path.Combine(entryFolder, file.Path);
|
||||
@@ -112,7 +135,8 @@ public sealed partial class FrameTrash
|
||||
break;
|
||||
}
|
||||
}
|
||||
(ok ? intact : kept).Add(photo);
|
||||
if (ok) intact.Add(photo);
|
||||
else kept.Add(new Stay(photo, KeptReason.Mismatch));
|
||||
}
|
||||
return (intact, kept);
|
||||
}
|
||||
@@ -122,17 +146,20 @@ public sealed partial class FrameTrash
|
||||
/// move, then every move to its end, the sidecar, and the record settled (<see cref="Settle"/>). Returns what came
|
||||
/// back and the photos left in the trash.
|
||||
/// </summary>
|
||||
private async Task<(PhotoRestoreResult, List<TrashedPhoto>)> IntoSequenceAsync(Archive archive, ArchivePaths paths, Sequence sequence, string recordPath,
|
||||
string entryFolder, List<TrashedPhoto> intact, CancellationToken cancellationToken)
|
||||
/// <param name="lease">The entry's lease, which the caller holds.</param>
|
||||
private async Task<(PhotoRestoreResult, List<Stay>)> IntoSequenceAsync(Archive archive, ArchivePaths paths, Sequence sequence, string recordPath,
|
||||
string entryFolder, string lease, List<TrashedPhoto> intact, CancellationToken cancellationToken)
|
||||
{
|
||||
var folder = paths.Sequence(sequence.Folder);
|
||||
var left = new List<TrashedPhoto>();
|
||||
var left = new List<Stay>();
|
||||
int restored;
|
||||
SequenceManifest updated;
|
||||
var indexed = true;
|
||||
await using (await _writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var manifest = SequenceWriter.ReadLocked(folder, sequence.Id);
|
||||
var manifest = SequenceWriter.ReadLocked(folder, sequence.Id, lease);
|
||||
// A restore of another entry, busy now, is not settled yet: its journal is not written over.
|
||||
EnsureSettled(folder);
|
||||
var inStep = await _indexer.InStepAsync(archive, folder, manifest, cancellationToken).ConfigureAwait(false);
|
||||
var photosChanged = !inStep && await _indexer.PhotosChangedAsync(archive, folder, cancellationToken).ConfigureAwait(false);
|
||||
var ids = manifest.Frames.Select(f => f.Id).ToHashSet();
|
||||
@@ -145,7 +172,7 @@ public sealed partial class FrameTrash
|
||||
// still holds the content counts; a missing or damaged one leaves the trash's copy to come back.
|
||||
if (ids.Contains(photo.Frame.Id) || (photo.Frame.Sha256 is { } sha && holders[sha].Any(f => ArchiveIngest.IsIntact(folder, f))))
|
||||
{
|
||||
left.Add(photo);
|
||||
left.Add(new Stay(photo, KeptReason.InSequence));
|
||||
continue;
|
||||
}
|
||||
var original = photo.Files[0];
|
||||
@@ -171,7 +198,7 @@ public sealed partial class FrameTrash
|
||||
foreach (var (photo, frame, moves) in planned)
|
||||
{
|
||||
if (MoveIn(paths, folder, moves.Moves)) back.Add(frame);
|
||||
else left.Add(photo);
|
||||
else left.Add(new Stay(photo, KeptReason.NotMoved));
|
||||
}
|
||||
updated = manifest;
|
||||
if (back.Count > 0)
|
||||
@@ -191,11 +218,11 @@ public sealed partial class FrameTrash
|
||||
{
|
||||
// The sidecar lists none of them: their files go back into the entry, whose record is as it was.
|
||||
Log.Warning("archive", $"{sequence.DisplayTitle}: the sidecar could not take the photos restored; they go back into the trash", ex);
|
||||
Settle(folder, manifest, journal);
|
||||
Settle(folder, manifest, journal, lease);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
Settle(folder, updated, journal);
|
||||
Settle(folder, updated, journal, lease);
|
||||
restored = back.Count;
|
||||
if (restored > 0)
|
||||
{
|
||||
@@ -246,15 +273,29 @@ public sealed partial class FrameTrash
|
||||
/// read or written under the sequence's lease, has it: each photo the sidecar lists again leaves the entry's record (a
|
||||
/// companion of it still in the entry stays there as one of the record's leftovers), and each file of the others that
|
||||
/// reached the sequence goes back into the entry, whose record still lists it (unless the entry was emptied since: the
|
||||
/// file then stays where it is, logged, for a scan to adopt). Then the journal goes. A failure (logged) keeps the
|
||||
/// journal, and the next writer of the sequence settles it again.
|
||||
/// file then stays where it is, logged, for a scan to adopt). Then the journal goes. All of it under the entry's lease
|
||||
/// as well, which an emptying holds: an entry busy now (or a failure, logged) keeps the journal, and the next writer of
|
||||
/// the sequence settles it (<see cref="EnsureSettled"/> keeps writers that would add files from going on meanwhile).
|
||||
/// </summary>
|
||||
internal static void Settle(SequencePaths sequence, SequenceManifest manifest, FrameRestoreJournal journal)
|
||||
/// <param name="heldLease">The entry lease the caller holds already (its own restore), if any.</param>
|
||||
internal static void Settle(SequencePaths sequence, SequenceManifest manifest, FrameRestoreJournal journal, string? heldLease = null)
|
||||
{
|
||||
var archive = sequence.Archive;
|
||||
var recordPath = archive.FromRelative(journal.Record);
|
||||
var entryFolder = archive.FromRelative(journal.Folder);
|
||||
var listed = manifest.Frames.Select(f => f.Id).ToHashSet();
|
||||
var lease = EntryLease(entryFolder);
|
||||
LeaseFile? taken = null;
|
||||
if (lease != heldLease)
|
||||
{
|
||||
taken = LeaseFile.TryAcquire(archive.LocksDirectory, lease, SettleOwner);
|
||||
if (taken is null)
|
||||
{
|
||||
Log.Info("archive", $"A restore from the trash into {sequence.RelativeFolder} waits: its entry {Path.GetFileName(entryFolder)} is busy");
|
||||
return;
|
||||
}
|
||||
}
|
||||
using var held = taken;
|
||||
try
|
||||
{
|
||||
var record = ReadRecord(recordPath);
|
||||
@@ -299,14 +340,17 @@ public sealed partial class FrameTrash
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Settles the restore a crash interrupted (<see cref="Settle"/>), if any; the caller holds the sequence's lease.</summary>
|
||||
internal static void RecoverRestore(SequencePaths sequence, SequenceManifest manifest)
|
||||
/// <summary>
|
||||
/// Settles the restore a crash interrupted (<see cref="Settle"/>), if any; the caller holds the sequence's lease, and
|
||||
/// <paramref name="heldLease"/> when it holds an entry's lease too.
|
||||
/// </summary>
|
||||
internal static void RecoverRestore(SequencePaths sequence, SequenceManifest manifest, string? heldLease = null)
|
||||
{
|
||||
if (!File.Exists(sequence.RestoreJournalPath)) return;
|
||||
if (FrameRestoreJournal.Read(sequence) is { } journal)
|
||||
{
|
||||
Log.Warning("archive", $"An interrupted restore from the trash into {sequence.RelativeFolder} is settled");
|
||||
Settle(sequence, manifest, journal);
|
||||
Log.Warning("archive", $"An interrupted restore from the trash into {sequence.RelativeFolder} is settled unless its entry is busy");
|
||||
Settle(sequence, manifest, journal, heldLease);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -314,11 +358,28 @@ public sealed partial class FrameTrash
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Refuses to go on while a restore into <paramref name="sequence"/> is still not settled after
|
||||
/// <see cref="SequenceWriter.ReadLocked"/> (its entry was busy, or a file could not move): a writer that would write
|
||||
/// another journal over it, or move the sequence's folder away with it, waits until it is. The caller holds the
|
||||
/// sequence's lease.
|
||||
/// </summary>
|
||||
/// <exception cref="LeaseUnavailableException">The restore is not settled; nothing was changed.</exception>
|
||||
internal static void EnsureSettled(SequencePaths sequence)
|
||||
{
|
||||
if (!File.Exists(sequence.RestoreJournalPath)) return;
|
||||
var lease = FrameRestoreJournal.Read(sequence) is { } journal ? EntryLease(sequence.Archive.FromRelative(journal.Folder)) : "restore";
|
||||
throw new LeaseUnavailableException(lease, LeaseFile.Holder(sequence.Archive.LocksDirectory, lease));
|
||||
}
|
||||
|
||||
/// <summary>The lease of the photo entry in <paramref name="entryFolder"/>, as a restore and an emptying of it take it.</summary>
|
||||
private static string EntryLease(string entryFolder) => SequenceTrash.EntryLease(EntryPrefix + Path.GetFileName(entryFolder));
|
||||
|
||||
/// <summary>
|
||||
/// What a restore into a new sequence did: the photos left in the trash, the companions that did not follow theirs, and
|
||||
/// what stopped it before its last photo (a failure other than a file's, or a cancel).
|
||||
/// </summary>
|
||||
private sealed record NewSequenceRestore(Guid? SequenceId, int Restored, List<TrashedPhoto> Left, List<TrashedFile> Leftovers, ExceptionDispatchInfo? Failure,
|
||||
private sealed record NewSequenceRestore(Guid? SequenceId, int Restored, List<Stay> Left, List<TrashedFile> Leftovers, ExceptionDispatchInfo? Failure,
|
||||
bool Stopped);
|
||||
|
||||
/// <summary>
|
||||
@@ -327,13 +388,15 @@ public sealed partial class FrameTrash
|
||||
/// that is free, and keyed by its id, so every entry of that sequence comes back into the same new one. Each original
|
||||
/// is staged inside its own entry (<see cref="RestoringFolder"/>); once it leaves the entry its commit runs to the end,
|
||||
/// and when it is not filed, whatever the failure, it goes back. Companions follow their photo under a name chosen so
|
||||
/// that theirs are free. A cancel, or a failure other than a file's, stops before the next photo.
|
||||
/// that theirs are free. The record is rewritten after each photo filed, so a crash or a failure later never leaves it
|
||||
/// listing one that is back. A cancel, or a failure other than a file's, stops before the next photo.
|
||||
/// </summary>
|
||||
private async Task<NewSequenceRestore> IntoNewSequenceAsync(Archive archive, ArchivePaths paths, PhotoTrashRecord record, string entryFolder,
|
||||
List<TrashedPhoto> intact, CancellationToken cancellationToken)
|
||||
private async Task<NewSequenceRestore> IntoNewSequenceAsync(Archive archive, ArchivePaths paths, PhotoTrashRecord record, string recordPath,
|
||||
string entryFolder, List<TrashedPhoto> intact, CancellationToken cancellationToken)
|
||||
{
|
||||
var left = new List<TrashedPhoto>();
|
||||
var left = new List<Stay>();
|
||||
var leftovers = new List<TrashedFile>();
|
||||
var filed = new HashSet<Guid>();
|
||||
var staging = Path.Combine(entryFolder, RestoringFolder);
|
||||
var key = $"trash:{record.SequenceId:N}";
|
||||
var target = new SequenceTarget(key, record.SequenceTitle, record.SequenceFolder.Length > 0 ? record.SequenceFolder : null, null);
|
||||
@@ -348,7 +411,7 @@ public sealed partial class FrameTrash
|
||||
stopped |= failure is null && cancellationToken.IsCancellationRequested;
|
||||
if (failure is not null || stopped)
|
||||
{
|
||||
left.Add(photo);
|
||||
left.Add(new Stay(photo, KeptReason.NotMoved));
|
||||
continue;
|
||||
}
|
||||
if (folder is null && sequenceId is { } known && await _db.Sequences.GetAsync(known, CancellationToken.None).ConfigureAwait(false) is { } row)
|
||||
@@ -365,7 +428,7 @@ public sealed partial class FrameTrash
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("archive", $"{original.Path} could not be staged for a restore; it stays in the trash", ex);
|
||||
left.Add(photo);
|
||||
left.Add(new Stay(photo, KeptReason.NotMoved));
|
||||
continue;
|
||||
}
|
||||
IngestResult? result = null;
|
||||
@@ -393,15 +456,17 @@ public sealed partial class FrameTrash
|
||||
{
|
||||
Log.Error("archive", $"{original.Path} stays staged in its trash entry; the next restore puts it back", ex);
|
||||
}
|
||||
left.Add(photo);
|
||||
left.Add(new Stay(photo, result is { Duplicate: true } ? KeptReason.InSequence : KeptReason.NotMoved));
|
||||
continue;
|
||||
}
|
||||
restored++;
|
||||
filed.Add(photo.Frame.Id);
|
||||
if (result is null)
|
||||
{
|
||||
// Filed although its commit failed afterwards (the ingest's journal completes it): where is not known, so its
|
||||
// companions stay in the trash.
|
||||
leftovers.AddRange(photo.Files.Skip(1));
|
||||
Follow();
|
||||
continue;
|
||||
}
|
||||
sequenceId ??= result.SequenceId;
|
||||
@@ -423,11 +488,30 @@ public sealed partial class FrameTrash
|
||||
leftovers.Add(companion);
|
||||
}
|
||||
}
|
||||
Follow();
|
||||
}
|
||||
// A photo filed by a commit that failed afterwards may be the first in the new sequence.
|
||||
if (sequenceId is null && restored > 0)
|
||||
sequenceId = await _db.Sequences.FindBySessionKeyAsync(archive.Id, key, CancellationToken.None).ConfigureAwait(false);
|
||||
return new NewSequenceRestore(sequenceId, restored, left, leftovers, failure, stopped);
|
||||
|
||||
// The record without the photos filed so far, and with the companions that did not follow; a record that cannot be
|
||||
// written now (logged) is written once more when the restore ends.
|
||||
void Follow()
|
||||
{
|
||||
try
|
||||
{
|
||||
Rewrite(recordPath, entryFolder, record with
|
||||
{
|
||||
Photos = [.. record.Photos.Where(p => !filed.Contains(p.Frame.Id))],
|
||||
Leftovers = Merge(record.Leftovers, leftovers),
|
||||
});
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("archive", $"Trash record {recordPath} does not follow the photos restored yet; it is written again at the end", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Puts back into an entry what a restore into a new sequence left staged in it (a crash, or a file that could not move back).</summary>
|
||||
@@ -449,12 +533,19 @@ public sealed partial class FrameTrash
|
||||
FrameRemovalJournal.RemoveEmpty(staging);
|
||||
}
|
||||
|
||||
/// <summary>Rewrites an entry's record with what it still holds; when nothing is left in its folder, the record goes too.</summary>
|
||||
/// <summary>
|
||||
/// Rewrites an entry's record with what it still holds; when it lists nothing and nothing is left in its folder, the
|
||||
/// record goes too. While it lists a photo, its folder stays (empty when only photos without a file are left), so the
|
||||
/// entry stays listed and Empty can erase it.
|
||||
/// </summary>
|
||||
private static void Rewrite(string recordPath, string entryFolder, PhotoTrashRecord record)
|
||||
{
|
||||
FrameRemovalJournal.RemoveEmpty(entryFolder);
|
||||
var done = record.Photos.Count == 0 && record.Leftovers is not { Count: > 0 };
|
||||
if (done) FrameRemovalJournal.RemoveEmpty(entryFolder);
|
||||
else if (System.IO.Directory.Exists(entryFolder))
|
||||
foreach (var child in System.IO.Directory.EnumerateDirectories(entryFolder).ToList()) FrameRemovalJournal.RemoveEmpty(child);
|
||||
// Only an entry left without a file goes; anything still in its folder keeps it listed, never erased by a restore.
|
||||
if (record.Photos.Count == 0 && record.Leftovers is not { Count: > 0 } && !System.IO.Directory.Exists(entryFolder))
|
||||
if (done && !System.IO.Directory.Exists(entryFolder))
|
||||
{
|
||||
File.Delete(recordPath);
|
||||
return;
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -5,6 +5,10 @@ namespace Chronos.Data.Archiving;
|
||||
/// Exactly one of <see cref="SequenceId"/>, <see cref="NewSequenceTitle"/> or <see cref="SessionKey"/> selects the target:
|
||||
/// an existing sequence, a new one with that title, or the sequence grouped automatically by session.
|
||||
/// </summary>
|
||||
/// <param name="RefuseRemoved">Content the target sequence tombstoned (a photo deleted from it, none of its frames holding
|
||||
/// that content) is refused with <see cref="PhotoRemovedException"/>, checked under the sequence's lease with the commit, so
|
||||
/// no deletion lands in between: an upload that does not ask to bring the photo back. Otherwise filing it drops the
|
||||
/// tombstone (a card imported again, a sync download, an explicit upload again).</param>
|
||||
public sealed record IngestRequest(
|
||||
Guid ArchiveId,
|
||||
Guid? SequenceId,
|
||||
@@ -15,7 +19,18 @@ public sealed record IngestRequest(
|
||||
long Size,
|
||||
string Sha256,
|
||||
DateTime? ClientCapturedAt,
|
||||
Guid? UserId);
|
||||
Guid? UserId,
|
||||
bool RefuseRemoved = false);
|
||||
|
||||
/// <summary>
|
||||
/// The target sequence tombstoned the content of an <see cref="IngestRequest"/> that refuses it
|
||||
/// (<see cref="IngestRequest.RefuseRemoved"/>): the photo was deleted from it. Nothing was filed; the staged file stays.
|
||||
/// </summary>
|
||||
public sealed class PhotoRemovedException(Guid sequenceId, string sha256)
|
||||
: InvalidOperationException($"Sequence {sequenceId} tombstoned {sha256}: the photo was deleted from it and is not filed again.")
|
||||
{
|
||||
public Guid SequenceId { get; } = sequenceId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The committed frame; <see cref="Duplicate"/> when an intact frame of the sequence already held that SHA-256 (the file
|
||||
|
||||
@@ -175,6 +175,10 @@ public sealed partial class SequenceTrash
|
||||
/// <param name="progress">Sequences moved so far.</param>
|
||||
/// <exception cref="StaleDeletePlanException">A sequence moved, vanished or got busy since the plan; nothing was deleted.</exception>
|
||||
/// <exception cref="ArchiveOfflineException">An archive is offline; sequences before it are in the trash.</exception>
|
||||
/// <exception cref="LeaseUnavailableException">A sequence, or the trash entry of a restore into it a crash interrupted, is
|
||||
/// busy; sequences before it are in the trash.</exception>
|
||||
/// <exception cref="InvalidDataException">The sidecar of a sequence with an interrupted journal is damaged; sequences
|
||||
/// before it are in the trash.</exception>
|
||||
public async Task<IReadOnlyList<TrashEntry>> DeleteAsync(DeletePlan plan, string? deletedBy = null, IProgress<int>? progress = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
@@ -369,13 +373,25 @@ public sealed partial class SequenceTrash
|
||||
var folder = paths.Sequence(sequence.Folder);
|
||||
if (!Directory.Exists(folder.Folder) || (File.Exists(folder.ManifestPath) && SidecarId(folder.ManifestPath) != sequence.Id))
|
||||
throw new StaleDeletePlanException(sequence.Id);
|
||||
// A photo deletion, a restore from the trash or an ingest a crash interrupted is settled first, as any writer does
|
||||
// (SequenceWriter.ReadLocked): neither its journal nor the files it moved travel into this entry, where emptying it
|
||||
// would erase them while their own entry still lists them. A restore whose entry is busy keeps the folder here.
|
||||
var (files, bytes) = (step.Files, step.Bytes);
|
||||
if (File.Exists(folder.ManifestPath) && (File.Exists(folder.RemovalJournalPath) || File.Exists(folder.RestoreJournalPath)
|
||||
|| File.Exists(folder.IngestJournalPath)))
|
||||
{
|
||||
SequenceWriter.ReadLocked(folder, sequence.Id);
|
||||
FrameTrash.EnsureSettled(folder);
|
||||
// Files came back into the folder, or left it: the record counts what moves.
|
||||
(files, bytes) = Measure(folder.Folder, cancellationToken);
|
||||
}
|
||||
var trash = TrashDirectory(paths);
|
||||
Directory.CreateDirectory(trash);
|
||||
var name = EntryName(paths, sequence.Id, new HashSet<string>());
|
||||
var target = Path.Combine(trash, name);
|
||||
var tombstones = await _db.FrameRemovals.ListBySequenceAsync(sequence.Id, cancellationToken).ConfigureAwait(false);
|
||||
var record = new TrashRecord(row, await _db.Renders.ListBySequenceAsync(sequence.Id, cancellationToken).ConfigureAwait(false), step.Files,
|
||||
step.Bytes, DateTimeOffset.UtcNow, deletedBy, tombstones.Count > 0 ? SequenceMapping.ToTombstones(tombstones) : null);
|
||||
var record = new TrashRecord(row, await _db.Renders.ListBySequenceAsync(sequence.Id, cancellationToken).ConfigureAwait(false), files,
|
||||
bytes, DateTimeOffset.UtcNow, deletedBy, tombstones.Count > 0 ? SequenceMapping.ToTombstones(tombstones) : null);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
// The record first: a crash before the move leaves a record without a folder, which the listing ignores.
|
||||
var recordPath = target + RecordExtension;
|
||||
@@ -401,7 +417,7 @@ public sealed partial class SequenceTrash
|
||||
if (MoveBack(target, folder.Folder)) File.Delete(recordPath);
|
||||
throw;
|
||||
}
|
||||
Log.Info("archive", $"{row.DisplayTitle} moved to the trash: {row.Folder} → {name} ({step.Files} files, {step.Bytes} bytes)");
|
||||
Log.Info("archive", $"{row.DisplayTitle} moved to the trash: {row.Folder} → {name} ({files} files, {bytes} bytes)");
|
||||
return Entry(archive.Id, name, record);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,17 +89,18 @@ internal sealed class SequenceWriter(ArchiveServiceOptions options)
|
||||
|
||||
/// <summary>
|
||||
/// Reads the sidecar of a locked sequence, undoing an interrupted photo deletion (<see cref="FrameRemovalJournal"/>),
|
||||
/// settling an interrupted restore from the trash (<see cref="FrameRestoreJournal"/>) and completing an interrupted
|
||||
/// ingest batch first.
|
||||
/// settling an interrupted restore from the trash (<see cref="FrameRestoreJournal"/>; left for later while its trash
|
||||
/// entry is busy) and completing an interrupted ingest batch first.
|
||||
/// </summary>
|
||||
/// <param name="heldEntryLease">The trash entry lease the caller holds already (a restore of that entry), if any.</param>
|
||||
/// <exception cref="InvalidDataException">The sidecar in the folder belongs to another sequence.</exception>
|
||||
public static SequenceManifest ReadLocked(SequencePaths sequence, Guid sequenceId)
|
||||
public static SequenceManifest ReadLocked(SequencePaths sequence, Guid sequenceId, string? heldEntryLease = null)
|
||||
{
|
||||
var manifest = ManifestStore.ReadSequence(sequence.ManifestPath);
|
||||
if (manifest.Id != sequenceId)
|
||||
throw new InvalidDataException($"{sequence.ManifestPath} belongs to sequence {manifest.Id}, not {sequenceId}.");
|
||||
FrameRemovalJournal.Recover(sequence, manifest);
|
||||
FrameTrash.RecoverRestore(sequence, manifest);
|
||||
FrameTrash.RecoverRestore(sequence, manifest, heldEntryLease);
|
||||
if (IngestJournal.Recover(sequence, manifest) is { } recovered)
|
||||
{
|
||||
ManifestStore.WriteSequence(sequence.ManifestPath, recovered);
|
||||
|
||||
Reference in new issue
Block a user