fix(archive): settle conversions by content and keep their aliases through trash, undo, sync and ingest
Owner review 2, phase 4b, fix round 1 (trash, undo, recovery, sync and ingest). - Replace journal: records a phase (moving, written, undoing) and the name each swapped frame is filed under. Recovery decides "sidecar written" by what the sidecar lists, not by the frames version any writer moves; a failed rollback stays undoing and its failure now stops the writer (as a photo deletion's recovery does). The ingest settles restores and replacements first, so an upload can no longer complete a swap that never happened. - Emptying a Replaced entry re-verifies each replacement where it is now: in the sequence through later conversions (a second conversion no longer strands the first originals), or, when the conversion was deleted, its copy in the trash. The dry run marks such entries "conversion deleted" (fingerprinted, shown on the desktop and the panel), and the confirmed emptying may then erase them instead of keeping them forever. - Undo of a conversion takes exactly the entries its job made (the job id is recorded on the entry), never entries found by time window. - Project positions translated by photo use the sidecar's photo of every frame still there, so positions on a converted frame stay put when another frame went meanwhile. - Sync aliases are equivalence classes: an original converted on both sides is one photo; link-by-content, proxy counting and proxy upload follow aliases; a download into a frame missing here swaps the other encoding into that frame instead of adding a frame. - The ingest answers a converted photo's original (a card or folder imported again, a download) as a duplicate of its conversion and keeps the alias tombstone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 3341a2f845753fc4c5bcba51a3b645f126c95eaf)
This commit is contained in:
1 parent
67a6d51cbe
commit
d0bbd77c92
31 files changed
+1326
-211
No files matched your search
@@ -23,7 +23,15 @@ namespace Chronos.Data.Archiving;
|
||||
/// under its name, and keeps the flags a user or the capture set (<see cref="FrameTrash.ContentFlags"/> come from the
|
||||
/// record).</param>
|
||||
internal sealed record FrameSwap(Guid FrameId, string Incoming, IReadOnlyList<IncomingCompanion> Companions, Func<SidecarFrame, SequenceManifest, string> Name,
|
||||
Func<SidecarFrame, SidecarFrame> Record);
|
||||
Func<SidecarFrame, SidecarFrame> Record)
|
||||
{
|
||||
/// <summary>
|
||||
/// The frame's original is gone (a frame flagged missing whose photo comes back in another encoding, from the other side
|
||||
/// of a sync link): the incoming file takes its place alone and nothing of the frame goes to the trash. The swap is
|
||||
/// refused while a file is at the frame's place.
|
||||
/// </summary>
|
||||
public bool Missing { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>A companion that comes in with its photo: where it is (relative to the archive root), and what its name adds to the photo's stem.</summary>
|
||||
internal sealed record IncomingCompanion(string From, string Tail);
|
||||
@@ -44,30 +52,89 @@ internal sealed record ConsumedEntry(string Record, string Folder, string Lease,
|
||||
/// <param name="Other">Relative to the archive root: the trash entry an outgoing file goes to, or where an incoming file comes from.</param>
|
||||
internal sealed record SwapMove(string Place, string Other);
|
||||
|
||||
/// <summary>What a replacement did: the trash entry of the files that went, the sequence as it is now, and its statuses before.</summary>
|
||||
internal sealed record ReplaceResult(TrashEntry Entry, Sequence Sequence, SequenceStatus Had);
|
||||
/// <summary>
|
||||
/// What a replacement did: the trash entry of the files that went (null when none went: every frame swapped had lost its
|
||||
/// original), the sequence as it is now, and its statuses before.
|
||||
/// </summary>
|
||||
internal sealed record ReplaceResult(TrashEntry? Entry, Sequence Sequence, SequenceStatus Had);
|
||||
|
||||
/// <summary>How far a frame replacement got (<see cref="FrameReplaceJournal.Phase"/>).</summary>
|
||||
internal enum ReplacePhase
|
||||
{
|
||||
/// <summary>Files are moving: whether the sidecar was written is told by what it lists (<see cref="FrameReplaceJournal.Written"/>).</summary>
|
||||
Moving,
|
||||
|
||||
/// <summary>The sidecar is written: the replacement stands, and only its completion may be left.</summary>
|
||||
Written,
|
||||
|
||||
/// <summary>
|
||||
/// The replacement failed before its sidecar was written and its files are going back: it is only ever undone, whatever
|
||||
/// another writer does to the sidecar meanwhile.
|
||||
/// </summary>
|
||||
Undoing,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Write-ahead record of a frame replacement (<c>.chronos/replace.pending.json</c>, owner review 2, R7): the sidecar's frames
|
||||
/// version before it, the new trash entry (its record pending until the sidecar is written), every file that leaves the
|
||||
/// sequence for the entry and every file that comes in, whether the entry holds a copy of <c>analysis.json</c>, and the
|
||||
/// entry the incoming files come from (an undo). Written under the sequence's lease before the first move and removed once
|
||||
/// the replacement is settled, so the next writer of the sequence (<see cref="SequenceWriter.ReadLocked"/>) undoes one a
|
||||
/// crash interrupted before its sidecar was written, and completes one interrupted after.
|
||||
/// sequence for the entry and every file that comes in, the name each swapped frame is filed under, whether the entry holds
|
||||
/// a copy of <c>analysis.json</c>, the entry the incoming files come from (an undo), and how far it got
|
||||
/// (<see cref="Phase"/>). Written under the sequence's lease before the first move and removed once the replacement is
|
||||
/// settled, so the next writer of the sequence (<see cref="SequenceWriter.ReadLocked"/>) undoes one a crash or a failure
|
||||
/// interrupted before its sidecar was written, and completes one interrupted after.
|
||||
/// </summary>
|
||||
/// <param name="Record">The new entry's record, relative to the archive root (its name once the replacement is complete).</param>
|
||||
/// <param name="Folder">The new entry's folder, relative to the archive root.</param>
|
||||
/// <param name="Record">The new entry's record, relative to the archive root (its name once the replacement is complete); null
|
||||
/// when no file leaves the sequence (no entry).</param>
|
||||
/// <param name="Folder">The new entry's folder, relative to the archive root; null with <paramref name="Record"/>.</param>
|
||||
/// <param name="Out">Files that leave the sequence for the new entry.</param>
|
||||
/// <param name="In">Files that come into the sequence.</param>
|
||||
internal sealed record FrameReplaceJournal(int FramesVersion, string Record, string Folder, IReadOnlyList<SwapMove> Out, IReadOnlyList<SwapMove> In,
|
||||
internal sealed record FrameReplaceJournal(int FramesVersion, string? Record, string? Folder, IReadOnlyList<SwapMove> Out, IReadOnlyList<SwapMove> In,
|
||||
bool Analysis, ConsumedEntry? Consumed)
|
||||
{
|
||||
/// <summary>How far the replacement got; a journal of an earlier build has none (<see cref="ReplacePhase.Moving"/>).</summary>
|
||||
public ReplacePhase Phase { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The name each swapped frame is filed under (frame id → place relative to the sequence folder); null in a journal of an
|
||||
/// earlier build. Each name was claimed free of every file present and every name the sidecar held before, so the
|
||||
/// sidecar before the replacement never lists one of them under its frame.
|
||||
/// </summary>
|
||||
public IReadOnlyDictionary<Guid, string>? Names { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Whether <paramref name="manifest"/>, read under the sequence's lease, is the sidecar this replacement wrote (or one
|
||||
/// written after it): a swapped frame lists its new name (<see cref="Names"/>; the sidecar is written whole, so one is
|
||||
/// all). Told by content, not by the frames version, which any other writer moves too. A journal of an earlier build,
|
||||
/// without names, still tells by the version.
|
||||
/// </summary>
|
||||
public bool Written(SequenceManifest manifest) => Names is { Count: > 0 } names
|
||||
? manifest.Frames.Any(f => names.TryGetValue(f.Id, out var name) && string.Equals(f.File, name, StringComparison.OrdinalIgnoreCase))
|
||||
: manifest.Versions.Frames != FramesVersion;
|
||||
|
||||
public void Write(SequencePaths sequence)
|
||||
{
|
||||
System.IO.Directory.CreateDirectory(sequence.MetaDirectory);
|
||||
AtomicFile.WriteAllBytes(sequence.ReplaceJournalPath, JsonSerializer.SerializeToUtf8Bytes(this, TrashJson.Default.FrameReplaceJournal));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The journal at <paramref name="phase"/>, written over the sequence's. One that cannot be written (logged) keeps the
|
||||
/// phase before, and the sidecar's content still tells what happened (<see cref="Written"/>).
|
||||
/// </summary>
|
||||
public FrameReplaceJournal Mark(SequencePaths sequence, ReplacePhase phase)
|
||||
{
|
||||
var marked = this with { Phase = phase };
|
||||
try
|
||||
{
|
||||
marked.Write(sequence);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("archive", $"The journal of a frame replacement in {sequence.RelativeFolder} could not record {phase}; the sidecar tells", ex);
|
||||
}
|
||||
return marked;
|
||||
}
|
||||
|
||||
/// <summary>The journal of a sequence; null when it is torn (written by a process that died while writing it: nothing moved yet).</summary>
|
||||
public static FrameReplaceJournal? Read(SequencePaths sequence)
|
||||
{
|
||||
@@ -110,15 +177,17 @@ public sealed partial class FrameTrash
|
||||
/// again) and the project's positions stay on their frames. A journal (<see cref="FrameReplaceJournal"/>) makes it all
|
||||
/// or nothing: a failure before the sidecar is written puts every file back, and a crash is undone or completed by the
|
||||
/// next writer of the sequence. Returns null, nothing touched, when the sequence is gone, its frames changed, a swapped
|
||||
/// frame's original is not there whole or was never hashed, or <paramref name="unchanged"/> said no.
|
||||
/// frame's original is not there whole (there at all, for a <see cref="FrameSwap.Missing"/> swap) or was never hashed, or
|
||||
/// <paramref name="unchanged"/> said no. When every frame swapped had lost its original, no entry is made.
|
||||
/// </summary>
|
||||
/// <param name="replacedBy">Who asked (user name or client), kept in the trash record.</param>
|
||||
/// <param name="jobId">The job that asked (a conversion), kept in the trash record so its Undo takes back exactly its entries.</param>
|
||||
/// <param name="consumed">The trash entry the incoming files come from (an undo), settled once the sidecar is written.</param>
|
||||
/// <exception cref="ArchiveOfflineException">The archive is offline or read-only; nothing moved.</exception>
|
||||
/// <exception cref="LeaseUnavailableException">The sequence is busy, or holds a restore or a replacement not settled yet.</exception>
|
||||
/// <exception cref="IOException">An incoming file is missing, or a file could not move; nothing changed.</exception>
|
||||
internal async Task<ReplaceResult?> ReplaceAsync(Archive archive, Guid sequenceId, int? framesVersion, IReadOnlyList<FrameSwap> swaps, string? replacedBy,
|
||||
ConsumedEntry? consumed, Func<SequenceManifest, SequencePaths, CancellationToken, Task<bool>>? unchanged, CancellationToken cancellationToken)
|
||||
Guid? jobId, ConsumedEntry? consumed, Func<SequenceManifest, SequencePaths, CancellationToken, Task<bool>>? unchanged, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
ArgumentNullException.ThrowIfNull(swaps);
|
||||
@@ -129,7 +198,7 @@ public sealed partial class FrameTrash
|
||||
Sequence row;
|
||||
SequencePaths folder;
|
||||
SequenceStatus had;
|
||||
TrashEntry entry;
|
||||
TrashEntry? entry;
|
||||
SequenceManifest updated;
|
||||
bool indexed;
|
||||
await using (await _writer.LockAsync(paths, sequenceId, cancellationToken).ConfigureAwait(false))
|
||||
@@ -149,7 +218,8 @@ public sealed partial class FrameTrash
|
||||
{
|
||||
if (!byId.TryGetValue(swap.FrameId, out var current) || current.Sha256 is null || swapped.ContainsKey(swap.FrameId)) return null;
|
||||
var file = new FileInfo(folder.File(current.File));
|
||||
if (!file.Exists || file.Length != current.Size) return null;
|
||||
// An original gives its place up whole; a frame that lost its original takes the incoming file only while it has none.
|
||||
if (swap.Missing ? file.Exists : !file.Exists || file.Length != current.Size) return null;
|
||||
var next = swap.Record(current);
|
||||
if (next.Sha256 is null) throw new ArgumentException($"The record that replaces {current.File} names no content.", nameof(swaps));
|
||||
swapped[swap.FrameId] = next;
|
||||
@@ -160,9 +230,10 @@ public sealed partial class FrameTrash
|
||||
var inStep = await _indexer.InStepAsync(archive, folder, manifest, cancellationToken).ConfigureAwait(false);
|
||||
var photosChanged = !inStep && await _indexer.PhotosChangedAsync(archive, folder, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var missing = swaps.Where(s => s.Missing).Select(s => s.FrameId).ToHashSet();
|
||||
var leaving = manifest.Frames.Where(f => swapped.ContainsKey(f.Id)).ToList();
|
||||
var kept = manifest.Frames.Where(f => !swapped.ContainsKey(f.Id)).ToList();
|
||||
var photos = (await TrashedAsync(folder, leaving, kept, cancellationToken).ConfigureAwait(false))
|
||||
var photos = (await TrashedAsync(folder, [.. leaving.Where(f => !missing.Contains(f.Id))], kept, cancellationToken).ConfigureAwait(false))
|
||||
.Select(p => p with { Replacement = swapped[p.Frame.Id].Sha256!.ToLowerInvariant() }).ToList();
|
||||
var (incoming, names) = Incoming(folder, manifest, swaps, byId);
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
@@ -173,31 +244,49 @@ public sealed partial class FrameTrash
|
||||
Removed = WithAliases(manifest.Removed, leaving, swapped, kept, now),
|
||||
};
|
||||
|
||||
var trash = Directory(paths);
|
||||
System.IO.Directory.CreateDirectory(trash);
|
||||
var name = EntryName(trash, sequenceId);
|
||||
var entryFolder = Path.Combine(trash, name);
|
||||
var recordPath = entryFolder + RecordExtension;
|
||||
// The entry of what leaves; none when nothing does (every frame swapped had lost its original).
|
||||
string? name = null;
|
||||
string? entryFolder = null;
|
||||
string? recordPath = null;
|
||||
PhotoTrashRecord? record = null;
|
||||
var analysis = new FileInfo(folder.AnalysisPath);
|
||||
List<TrashedFile>? leftovers = analysis.Exists
|
||||
? [new TrashedFile(ArchiveLayout.MetaFolder + "/" + ArchiveLayout.AnalysisFile, AnalysisCopy, analysis.Length, null)]
|
||||
: null;
|
||||
var record = new PhotoTrashRecord(TrashKind.Replaced, sequenceId, row.DisplayTitle, row.Folder, photos,
|
||||
photos.Sum(p => p.Files.Sum(f => f.Size)) + (leftovers?.Sum(f => f.Size) ?? 0), now, replacedBy, leftovers);
|
||||
var outgoing = photos.SelectMany(p => p.Files).Select(f => new SwapMove(f.From, paths.ToRelative(Path.Combine(entryFolder, f.Path)))).ToList();
|
||||
var journal = new FrameReplaceJournal(manifest.Versions.Frames, paths.ToRelative(recordPath), paths.ToRelative(entryFolder), outgoing, incoming,
|
||||
analysis.Exists, consumed);
|
||||
var copiesAnalysis = false;
|
||||
List<SwapMove> outgoing = [];
|
||||
if (photos.Count > 0)
|
||||
{
|
||||
var trash = Directory(paths);
|
||||
System.IO.Directory.CreateDirectory(trash);
|
||||
name = EntryName(trash, sequenceId);
|
||||
entryFolder = Path.Combine(trash, name);
|
||||
recordPath = entryFolder + RecordExtension;
|
||||
copiesAnalysis = analysis.Exists;
|
||||
List<TrashedFile>? leftovers = copiesAnalysis
|
||||
? [new TrashedFile(ArchiveLayout.MetaFolder + "/" + ArchiveLayout.AnalysisFile, AnalysisCopy, analysis.Length, null)]
|
||||
: null;
|
||||
record = new PhotoTrashRecord(TrashKind.Replaced, sequenceId, row.DisplayTitle, row.Folder, photos,
|
||||
photos.Sum(p => p.Files.Sum(f => f.Size)) + (leftovers?.Sum(f => f.Size) ?? 0), now, replacedBy, leftovers, jobId);
|
||||
var folderPath = entryFolder;
|
||||
outgoing = [.. photos.SelectMany(p => p.Files).Select(f => new SwapMove(f.From, paths.ToRelative(Path.Combine(folderPath, f.Path))))];
|
||||
}
|
||||
var journal = new FrameReplaceJournal(manifest.Versions.Frames, recordPath is null ? null : paths.ToRelative(recordPath),
|
||||
entryFolder is null ? null : paths.ToRelative(entryFolder), outgoing, incoming, copiesAnalysis, consumed)
|
||||
{
|
||||
Names = names,
|
||||
};
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
// The journal first: a crash from here until the sidecar is written puts every file back (ReadLocked).
|
||||
journal.Write(folder);
|
||||
// Under a name the trash does not list until the sidecar is written: half an entry is never restored or emptied.
|
||||
AtomicFile.WriteAllText(FrameRemovalJournal.PendingRecord(recordPath), JsonSerializer.Serialize(record, TrashJson.Default.PhotoTrashRecord));
|
||||
System.IO.Directory.CreateDirectory(entryFolder);
|
||||
if (record is not null)
|
||||
{
|
||||
// Under a name the trash does not list until the sidecar is written: half an entry is never restored or emptied.
|
||||
AtomicFile.WriteAllText(FrameRemovalJournal.PendingRecord(recordPath!), JsonSerializer.Serialize(record, TrashJson.Default.PhotoTrashRecord));
|
||||
System.IO.Directory.CreateDirectory(entryFolder!);
|
||||
}
|
||||
var movedOut = new List<SwapMove>();
|
||||
var movedIn = new List<SwapMove>();
|
||||
try
|
||||
{
|
||||
if (analysis.Exists) File.Copy(analysis.FullName, Path.Combine(entryFolder, AnalysisCopy), overwrite: false);
|
||||
if (copiesAnalysis) File.Copy(analysis.FullName, Path.Combine(entryFolder!, AnalysisCopy), overwrite: false);
|
||||
foreach (var move in outgoing)
|
||||
{
|
||||
MoveFile(folder.File(move.Place), paths.FromRelative(move.Other));
|
||||
@@ -214,27 +303,41 @@ public sealed partial class FrameTrash
|
||||
{
|
||||
// A file is open elsewhere, or the sidecar cannot be written: what moved goes back, and nothing changed.
|
||||
Log.Warning("archive", $"{row.DisplayTitle}: the frames could not be replaced; the files that moved go back", ex);
|
||||
UndoReplace(folder, movedOut, movedIn, journal);
|
||||
try
|
||||
{
|
||||
// Undone from here on, whatever happens to the sidecar until it is.
|
||||
UndoReplace(folder, movedOut, movedIn, journal.Mark(folder, ReplacePhase.Undoing));
|
||||
}
|
||||
catch (Exception again) when (again is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Error("archive", $"{row.DisplayTitle}: the files that moved could not all go back; the next writer of the sequence puts them back first", again);
|
||||
}
|
||||
throw;
|
||||
}
|
||||
CompleteReplace(folder, journal, consumed?.Lease);
|
||||
Log.Info("archive", $"{row.DisplayTitle}: {photos.Count} frame(s) replaced; the files they had are in the trash ({name}, {record.Bytes} bytes)");
|
||||
CompleteReplace(folder, journal.Mark(folder, ReplacePhase.Written), consumed?.Lease);
|
||||
Log.Info("archive", record is null
|
||||
? $"{row.DisplayTitle}: {swaps.Count} missing frame(s) took their photo back in another encoding"
|
||||
: $"{row.DisplayTitle}: {leaving.Count} frame(s) replaced; the files they had are in the trash ({name}, {record.Bytes} bytes)");
|
||||
// The files have moved: the index follows to the end, whatever the caller cancels meanwhile.
|
||||
indexed = await IndexAsync(archive, folder, updated, photosChanged, row.DisplayTitle).ConfigureAwait(false);
|
||||
DropProxies(folder, leaving);
|
||||
entry = Entry(archive.Id, name, record);
|
||||
entry = record is null ? null : Entry(archive.Id, name!, record);
|
||||
}
|
||||
var sequence = await RowAsync(row, updated, indexed).ConfigureAwait(false);
|
||||
return new ReplaceResult(entry, sequence, had);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Settles the replacement a crash interrupted (<see cref="FrameReplaceJournal"/>), if any; the caller holds the
|
||||
/// sequence's lease, and <paramref name="heldLease"/> when it holds a trash entry's lease too. While
|
||||
/// <paramref name="manifest"/> is at the journal's frames version the sidecar was not written: every file that moved
|
||||
/// goes back (one whose place is taken again stays, logged, and keeps the journal) and the new entry goes. Otherwise the
|
||||
/// replacement stands and is completed (<see cref="CompleteReplace"/>).
|
||||
/// Settles the replacement a crash or a failure interrupted (<see cref="FrameReplaceJournal"/>), if any; the caller holds
|
||||
/// the sequence's lease, and <paramref name="heldLease"/> when it holds a trash entry's lease too. A replacement whose
|
||||
/// sidecar was written (<see cref="ReplacePhase.Written"/>, or told by what <paramref name="manifest"/> lists:
|
||||
/// <see cref="FrameReplaceJournal.Written"/>) stands and is completed (<see cref="CompleteReplace"/>). Any other is undone,
|
||||
/// and stays undoing from then on (<see cref="ReplacePhase.Undoing"/>): every file that moved goes back (one whose place is
|
||||
/// taken again stays, logged, in the entry, which is then listed) and the new entry goes.
|
||||
/// </summary>
|
||||
/// <exception cref="IOException">A file could not go back (open elsewhere): the journal stays, and the writer goes no
|
||||
/// further, as a photo deletion's recovery does.</exception>
|
||||
/// <exception cref="UnauthorizedAccessException">The same, for want of access.</exception>
|
||||
internal static void RecoverReplace(SequencePaths sequence, SequenceManifest manifest, string? heldLease = null)
|
||||
{
|
||||
if (!File.Exists(sequence.ReplaceJournalPath)) return;
|
||||
@@ -243,15 +346,22 @@ public sealed partial class FrameTrash
|
||||
FrameReplaceJournal.Delete(sequence);
|
||||
return;
|
||||
}
|
||||
if (manifest.Versions.Frames == journal.FramesVersion)
|
||||
{
|
||||
Log.Warning("archive", $"An interrupted frame replacement in {sequence.RelativeFolder} is undone");
|
||||
UndoReplace(sequence, journal.Out, journal.In, journal, onlyPresent: true);
|
||||
}
|
||||
else
|
||||
if (journal.Phase == ReplacePhase.Written || (journal.Phase == ReplacePhase.Moving && journal.Written(manifest)))
|
||||
{
|
||||
Log.Warning("archive", $"An interrupted frame replacement in {sequence.RelativeFolder} is completed");
|
||||
CompleteReplace(sequence, journal, heldLease);
|
||||
return;
|
||||
}
|
||||
Log.Warning("archive", $"An interrupted frame replacement in {sequence.RelativeFolder} is undone");
|
||||
try
|
||||
{
|
||||
UndoReplace(sequence, journal.Out, journal.In, journal.Phase == ReplacePhase.Undoing ? journal : journal.Mark(sequence, ReplacePhase.Undoing),
|
||||
onlyPresent: true);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Error("archive", $"An interrupted frame replacement in {sequence.RelativeFolder} could not be undone yet; nothing is written to the sequence until it is", ex);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -335,44 +445,40 @@ public sealed partial class FrameTrash
|
||||
/// <summary>
|
||||
/// Puts back what a replacement moved before its sidecar was written (incoming files back where they came from, the
|
||||
/// files that left back into the sequence) and removes its entry and journal. With <paramref name="onlyPresent"/> (a
|
||||
/// recovery) a file not at its new place, or whose old place is taken, is left where it is (logged); the journal and the
|
||||
/// entry then stay, and the entry is listed under its record's own name. A failure (logged) keeps the journal, and the
|
||||
/// next writer of the sequence tries again.
|
||||
/// recovery) a file not at its new place, or whose old place is taken, is left where it is (logged); the journal then
|
||||
/// goes and the entry stays, listed under its record's own name.
|
||||
/// </summary>
|
||||
/// <exception cref="IOException">A file could not move (open elsewhere): the journal stays for the next writer of the sequence.</exception>
|
||||
/// <exception cref="UnauthorizedAccessException">The same, for want of access.</exception>
|
||||
private static void UndoReplace(SequencePaths folder, IReadOnlyList<SwapMove> movedOut, IReadOnlyList<SwapMove> movedIn, FrameReplaceJournal journal,
|
||||
bool onlyPresent = false)
|
||||
{
|
||||
var archive = folder.Archive;
|
||||
var recordPath = archive.FromRelative(journal.Record);
|
||||
var entryFolder = archive.FromRelative(journal.Folder);
|
||||
var recordPath = journal.Record is { } record ? archive.FromRelative(record) : null;
|
||||
var entryFolder = journal.Folder is { } entry ? archive.FromRelative(entry) : null;
|
||||
var stuck = 0;
|
||||
try
|
||||
foreach (var move in movedIn.Reverse())
|
||||
{
|
||||
foreach (var move in movedIn.Reverse())
|
||||
{
|
||||
if (!Back(folder.File(move.Place), archive.FromRelative(move.Other))) stuck++;
|
||||
}
|
||||
foreach (var move in movedOut.Reverse())
|
||||
{
|
||||
if (!Back(archive.FromRelative(move.Other), folder.File(move.Place))) stuck++;
|
||||
}
|
||||
if (!Back(folder.File(move.Place), archive.FromRelative(move.Other))) stuck++;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
foreach (var move in movedOut.Reverse())
|
||||
{
|
||||
Log.Error("archive", $"A frame replacement in {folder.RelativeFolder} could not be undone; the journal puts it back later", ex);
|
||||
return;
|
||||
if (!Back(archive.FromRelative(move.Other), folder.File(move.Place))) stuck++;
|
||||
}
|
||||
if (stuck > 0)
|
||||
{
|
||||
// What could not go back is in the entry, listed, restorable and erasable like any entry.
|
||||
FrameRemovalJournal.Publish(recordPath);
|
||||
if (recordPath is not null) FrameRemovalJournal.Publish(recordPath);
|
||||
FrameReplaceJournal.Delete(folder);
|
||||
return;
|
||||
}
|
||||
var copy = Path.Combine(entryFolder, AnalysisCopy);
|
||||
if (journal.Analysis && File.Exists(copy)) File.Delete(copy);
|
||||
if (File.Exists(FrameRemovalJournal.PendingRecord(recordPath))) File.Delete(FrameRemovalJournal.PendingRecord(recordPath));
|
||||
FrameRemovalJournal.RemoveEmpty(entryFolder);
|
||||
if (entryFolder is not null)
|
||||
{
|
||||
var copy = Path.Combine(entryFolder, AnalysisCopy);
|
||||
if (journal.Analysis && File.Exists(copy)) File.Delete(copy);
|
||||
FrameRemovalJournal.RemoveEmpty(entryFolder);
|
||||
}
|
||||
if (recordPath is not null && File.Exists(FrameRemovalJournal.PendingRecord(recordPath))) File.Delete(FrameRemovalJournal.PendingRecord(recordPath));
|
||||
FrameReplaceJournal.Delete(folder);
|
||||
|
||||
bool Back(string from, string to)
|
||||
@@ -406,7 +512,7 @@ public sealed partial class FrameTrash
|
||||
var archive = folder.Archive;
|
||||
try
|
||||
{
|
||||
FrameRemovalJournal.Publish(archive.FromRelative(journal.Record));
|
||||
if (journal.Record is { } record) FrameRemovalJournal.Publish(archive.FromRelative(record));
|
||||
if (journal.Consumed is { } consumed && !Settle(folder, consumed, heldLease)) return;
|
||||
FrameReplaceJournal.Delete(folder);
|
||||
}
|
||||
@@ -510,10 +616,52 @@ public sealed partial class FrameTrash
|
||||
var copy = Path.Combine(entryFolder, AnalysisCopy);
|
||||
var analysis = record.Leftovers?.Any(f => f.Path == AnalysisCopy) == true && File.Exists(copy) ? paths.ToRelative(copy) : null;
|
||||
var consumed = new ConsumedEntry(paths.ToRelative(recordPath), paths.ToRelative(entryFolder), lease, [.. record.Photos.Select(p => p.Frame.Id)], analysis);
|
||||
return await ReplaceAsync(archive, sequence.Id, null, swaps, null, consumed, (manifest, folder, ct) => SwappableAsync(record, manifest, folder, ct),
|
||||
return await ReplaceAsync(archive, sequence.Id, null, swaps, null, null, consumed, (manifest, folder, ct) => SwappableAsync(record, manifest, folder, ct),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gives a frame whose original is missing its photo back in another encoding (owner review 2, R7): a verified copy of
|
||||
/// what replaced it, or of what it replaced, fetched from the other side of a sync link, where the photo was converted
|
||||
/// (<see cref="Sync.SyncTombstones"/> counts both as one photo). Under the sequence's lease, while the frame still holds
|
||||
/// <paramref name="sha256"/> and has no file, <paramref name="staged"/> takes its place (<see cref="ReplaceAsync"/>,
|
||||
/// <see cref="FrameSwap.Missing"/>): the same id and index, the user's flags, a record read from the file as filing reads
|
||||
/// one (named as the frame with the file's extension), the old content as its source and a tombstone naming the new one,
|
||||
/// so the photo is neither filed twice nor missing. Nothing goes to the trash. False, nothing touched, when the frame
|
||||
/// changed or its file is back.
|
||||
/// </summary>
|
||||
/// <param name="staged">The verified copy, inside the archive (its staging); moved in.</param>
|
||||
/// <param name="fileName">The copy's name on the other side, whose extension the frame's file takes.</param>
|
||||
internal async Task<bool> ReplaceMissingAsync(Archive archive, Guid sequenceId, Guid frameId, string sha256, string staged, string stagedSha256,
|
||||
string fileName, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
var size = new FileInfo(staged).Length;
|
||||
var metadata = Core.Metadata.MetadataReader.Read(staged, cancellationToken);
|
||||
var extension = Path.GetExtension(fileName);
|
||||
var swap = new FrameSwap(frameId, paths.ToRelative(staged), [], Named, Read) { Missing = true };
|
||||
var replaced = await ReplaceAsync(archive, sequenceId, null, [swap], null, null, null,
|
||||
(manifest, _, _) => Task.FromResult(manifest.Frames.Any(f => f.Id == frameId && string.Equals(f.Sha256, sha256, StringComparison.OrdinalIgnoreCase))),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
return replaced is not null;
|
||||
|
||||
string Named(SidecarFrame current, SequenceManifest _) => extension.Length > 1 ? Path.ChangeExtension(current.File, extension) : current.File;
|
||||
|
||||
// The file's own facts, at the frame's capture time, with the content it had as its source.
|
||||
SidecarFrame Read(SidecarFrame current)
|
||||
{
|
||||
var read = SequenceFrames.FromMetadata(current.Id, current.File, current.Original, size, stagedSha256, metadata, current.CapturedAt);
|
||||
return read with
|
||||
{
|
||||
CapturedAt = current.CapturedAt ?? read.CapturedAt,
|
||||
UtcOffset = current.UtcOffset ?? read.UtcOffset,
|
||||
TimeSource = current.CapturedAt is null ? read.TimeSource : current.TimeSource,
|
||||
Source = new FrameSource { Sha256 = current.Sha256, Format = current.Format, File = current.File, Size = current.Size },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A replaced entry's record without its copy of <c>analysis.json</c> once no photo is left in it (all of them filed into
|
||||
/// a new sequence, which is analysed again): the copy, derived from those photos, goes with the entry.
|
||||
|
||||
Reference in new issue
Block a user