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:
Alby96 committed 2026-10-27 22:13:36 +01:00
1 parent 67a6d51cbe
commit d0bbd77c92
31 files changed
+1326 -211

No files matched your search

+4 -7
View File
@@ -51,9 +51,9 @@ public static class ConvertUndo
public static bool Replaces(Job job) => Parameters(job) is { Mode: ConvertMode.Replace };
/// <summary>
/// The trash entries an undo of <paramref name="job"/> restores: of each sequence it converted, the newest entry of replaced
/// originals made while it ran (from when it was queued to when it ended, so an entry an undo made of the converted files
/// is never taken for the originals).
/// The trash entries an undo of <paramref name="job"/> restores: the entries of replaced originals the job itself made
/// (each records the job, <see cref="TrashEntry.JobId"/>), still in the trash, oldest first. Never one made by anything
/// else meanwhile, such as the entry of converted files a restore from Maintenance › Trash makes while the job runs.
/// </summary>
public static IReadOnlyList<TrashEntry> Entries(Job job, ConvertJobParameters parameters, IEnumerable<TrashEntry> trash)
{
@@ -63,10 +63,7 @@ public static class ConvertUndo
var converted = parameters.Sequences.Select(s => s.Id).ToHashSet();
return
[
.. trash.Where(e => e.Kind == TrashKind.Replaced && e.ArchiveId == parameters.ArchiveId && converted.Contains(e.SequenceId) && e.DeletedAt >= job.Created
&& (job.Finished is not { } finished || e.DeletedAt <= finished))
.GroupBy(e => e.SequenceId)
.Select(g => g.MaxBy(e => e.DeletedAt)!)
.. trash.Where(e => e.Kind == TrashKind.Replaced && e.JobId == job.Id && e.ArchiveId == parameters.ArchiveId && converted.Contains(e.SequenceId))
.OrderBy(e => e.DeletedAt),
];
}
@@ -38,14 +38,19 @@ public static class TrashEmptyPlans
/// <summary>"Photos", "Sequence", "Replaced".</summary>
public static string KindText(TrashKind kind) => Loc.L("Archive.Trash.Kind." + kind);
/// <summary>The confirmation of erasing the planned entries for good; null when the plan holds none.</summary>
/// <summary>
/// The confirmation of erasing the planned entries for good; null when the plan holds none. An entry of replaced originals
/// whose conversion was deleted since says so (<see cref="TrashEntry.ConversionDeleted"/>): erasing it may erase the last
/// copy of those photos.
/// </summary>
public static ConfirmRequest? Request(TrashEmptyPlan plan)
{
ArgumentNullException.ThrowIfNull(plan);
if (plan.Entries.Count == 0) return null;
var count = plan.Entries.Count.ToString(CultureInfo.InvariantCulture);
var lines = plan.Entries.Take(DeletePlans.ListedLines).Select(e => Loc.L("Archive.Delete.Line", e.Title,
KindText(e.Kind) + Loc.Separator + Loc.Plural("Shell.Status.Photos", e.Frames), Formatting.Bytes(e.Bytes))).ToList();
KindText(e.Kind) + Loc.Separator + Loc.Plural("Shell.Status.Photos", e.Frames)
+ (e.ConversionDeleted ? Loc.Separator + Loc.L("Archive.Trash.ConversionDeleted") : string.Empty), Formatting.Bytes(e.Bytes))).ToList();
if (plan.Entries.Count > DeletePlans.ListedLines) lines.Add(Loc.Plural("Archive.Delete.More", plan.Entries.Count - DeletePlans.ListedLines));
return new ConfirmRequest
{
+42 -1
View File
@@ -38,7 +38,9 @@ internal sealed record SequenceTarget(string Key, string? Title, string? Preferr
/// other processes out meanwhile, and a write-ahead journal repairs a batch interrupted by a crash. A file whose
/// SHA-256 an intact frame of the sequence already holds is reported as a duplicate and left in staging; a frame with
/// that SHA-256 that is flagged missing or corrupt, or whose file is gone or has another size, is repaired with it
/// instead (its damaged file kept beside it). A sequence created without photos gets its folder with its first frame.
/// instead (its damaged file kept beside it). A file whose content a conversion replaced in the sequence is a duplicate of
/// the intact frame that holds what replaced it (owner review 2, R7). A sequence created without photos gets its folder
/// with its first frame. A restore from the trash or a frame replacement of the sequence not settled yet refuses the commit.
/// </summary>
public sealed class ArchiveIngest : IArchiveIngest
{
@@ -307,6 +309,10 @@ public sealed class ArchiveIngest : IArchiveIngest
{
var sequence = await SequenceWriter.FolderAsync(_db, paths, row, cancellationToken).ConfigureAwait(false);
var manifest = SequenceWriter.ReadLocked(sequence, sequenceId);
// A restore from the trash or a frame replacement not settled yet (its entry busy) is settled before frames are
// filed beside it, as every writer of the frames does: the commit fails and is tried again (an upload's client).
FrameTrash.EnsureSettled(sequence);
FrameTrash.EnsureReplaced(sequence);
// Asked before this batch changes the folder: whether this index holds it as it is (ArchiveIndexer.InStepAsync), and
// when it does not, whether photos were copied in or removed by hand since the last scan, which this batch's
// resync leaves to the next one (ArchiveIndexer.PhotosChangedAsync).
@@ -315,6 +321,7 @@ public sealed class ArchiveIngest : IArchiveIngest
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);
var replacedBy = Replacements(manifest);
// 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);
@@ -348,6 +355,14 @@ public sealed class ArchiveIngest : IArchiveIngest
repairs.Add((p, damaged));
continue;
}
// A photo a conversion replaced here (owner review 2, R7) is in the sequence as what replaced it: a card or a
// folder imported again, or a download of the original, is a duplicate of that frame, and the tombstone that
// makes sync count both as one photo stays. A replacement no longer intact leaves the photo to be filed again.
if (ReplacedBy(sequence, p.Frame.Sha256, replacedBy, held) is { } replacement)
{
duplicates.Add((p, replacement.Id));
continue;
}
var frame = SequenceFrames.FromMetadata(Guid.CreateVersion7(), p.Frame.NamingFile, p.Frame.OriginalFileName, p.Frame.Size,
p.Frame.Sha256, p.Frame.Metadata, p.Frame.ClientCapturedAt);
filed[p.Frame.Sha256] = frame.Id;
@@ -411,6 +426,32 @@ public sealed class ArchiveIngest : IArchiveIngest
}
}
/// <summary>The sequence's Replaced tombstones (owner review 2, R7): each content a conversion replaced, and what replaced it.</summary>
private static Dictionary<string, string> Replacements(SequenceManifest manifest)
{
var replaced = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var removal in manifest.Removed ?? [])
{
if (removal.Reason == RemovalReason.Replaced && removal.Replacement is { Length: > 0 } replacement) replaced[removal.Sha256] = replacement;
}
return replaced;
}
/// <summary>
/// The intact frame that holds what replaced <paramref name="sha256"/> in the sequence, followed through later conversions
/// (a conversion of a conversion); null when the content was not replaced, or no frame holds a replacement intact.
/// </summary>
private static SidecarFrame? ReplacedBy(SequencePaths sequence, string sha256, IReadOnlyDictionary<string, string> replacements,
ILookup<string, SidecarFrame> held)
{
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { sha256 };
for (var current = sha256; replacements.TryGetValue(current, out var next) && seen.Add(next); current = next)
{
if (held[next].FirstOrDefault(f => IsIntact(sequence, f)) is { } frame) return frame;
}
return null;
}
/// <summary>Whether a frame filed by the batch holds content the sequence's tombstones name.</summary>
private static bool Readded(SequenceManifest manifest, List<SidecarFrame> moved)
{
+219 -71
View File
@@ -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.
+8 -3
View File
@@ -237,7 +237,7 @@ public sealed partial class FrameTrash
if ((await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false))?.Folder != revised.Sequence.Folder)
throw new StaleDeletePlanException(id);
var manifest = SequenceWriter.ReadLocked(folder, id);
// A replacement not settled yet tells by the frames version whether its sidecar was written: none moves under it.
// A replacement not settled yet (the entry its files came from busy) is settled first: nothing moves under it.
EnsureReplaced(folder);
var plannedPaths = plan.Frames.ToDictionary(f => f.Id, f => f.RelativePath);
var planned = plannedPaths.Keys.ToHashSet();
@@ -676,7 +676,10 @@ public sealed partial class FrameTrash
private static TrashEntry Entry(Guid archiveId, string folderName, PhotoTrashRecord record) =>
new(archiveId, EntryPrefix + folderName, record.SequenceId, record.SequenceTitle, record.SequenceFolder, record.Photos.Count,
record.Photos.Sum(p => p.Files.Count) + (record.Leftovers?.Count ?? 0), record.Bytes, record.DeletedAt, record.DeletedBy, record.Kind);
record.Photos.Sum(p => p.Files.Count) + (record.Leftovers?.Count ?? 0), record.Bytes, record.DeletedAt, record.DeletedBy, record.Kind)
{
JobId = record.JobId,
};
private static PhotoTrashRecord? ReadRecord(string path)
{
@@ -699,8 +702,10 @@ public sealed partial class FrameTrash
/// </summary>
/// <param name="Leftovers">Files of the entry whose photo is back in a sequence without them (a companion whose name was
/// taken there): counted and erased with the entry, never restored.</param>
/// <param name="JobId">The job that made the entry (a conversion's Replace, owner review 2, R7), whose Undo takes back exactly
/// its own entries; null for an entry a user's action made.</param>
internal sealed record PhotoTrashRecord(TrashKind Kind, Guid SequenceId, string SequenceTitle, string SequenceFolder, IReadOnlyList<TrashedPhoto> Photos,
long Bytes, DateTimeOffset DeletedAt, string? DeletedBy, IReadOnlyList<TrashedFile>? Leftovers = null);
long Bytes, DateTimeOffset DeletedAt, string? DeletedBy, IReadOnlyList<TrashedFile>? Leftovers = null, Guid? JobId = null);
/// <summary>One photo of a photo entry: its frame record, its files (the original first) and, when replaced, the replacement's SHA-256.</summary>
internal sealed record TrashedPhoto(SidecarFrame Frame, IReadOnlyList<TrashedFile> Files, string? Replacement);
+3 -3
View File
@@ -361,7 +361,7 @@ public sealed class MassConverter
try
{
return mode == ConvertMode.Replace
? await ReplaceAsync(archive, paths, row, planned, ready, staging, options, by.Name, cancellationToken).ConfigureAwait(false)
? await ReplaceAsync(archive, paths, row, planned, ready, staging, options, jobId, by.Name, cancellationToken).ConfigureAwait(false)
: await CreateAsync(archive, paths, row, planned, ready, staging, options, key, by.Id, cancellationToken).ConfigureAwait(false);
}
catch (LeaseUnavailableException ex)
@@ -546,7 +546,7 @@ public sealed class MassConverter
/// every file there.
/// </summary>
private async Task<StepDone> ReplaceAsync(Archive archive, ArchivePaths paths, Sequence row, ConvertSequencePlan planned,
Dictionary<Guid, StagedConversion> ready, string staging, ConvertOptions options, string? replacedBy, CancellationToken cancellationToken)
Dictionary<Guid, StagedConversion> ready, string staging, ConvertOptions options, Guid jobId, string? replacedBy, CancellationToken cancellationToken)
{
var template = PathTemplate.Parse(archive.FileTemplate);
var swaps = planned.Frames.Select(f =>
@@ -555,7 +555,7 @@ public sealed class MassConverter
return new FrameSwap(f.FrameId, paths.ToRelative(Path.Combine(staging, conversion.File)), [], (current, sequence) => options.FileName(template, current, sequence),
current => Converted(current, conversion, options));
}).ToList();
var replaced = await _frames.ReplaceAsync(archive, row.Id, null, swaps, replacedBy, null, (now, _, _) => Task.FromResult(Holds(now, planned)),
var replaced = await _frames.ReplaceAsync(archive, row.Id, null, swaps, replacedBy, jobId, null, (now, _, _) => Task.FromResult(Holds(now, planned)),
cancellationToken).ConfigureAwait(false);
if (replaced is null) return new StepDone(Result(row, ConvertOutcome.Changed));
return new StepDone(Result(row, ConvertOutcome.Converted, swaps.Count), replaced.Had, _frames.FollowUps(archive, replaced.Sequence, replaced.Had));
@@ -57,26 +57,30 @@ internal static class ProjectPositions
/// Indexed frames are no longer in the sidecar (photos deleted into the trash, here or by another process sharing the
/// archive, owner review 2, R6): the positions are translated by photo from the index's frames to the sidecar's
/// (<see cref="ProjectSettings.TranslateFramePositions"/>), so those on the photos that went wait as pending frames
/// and take their place again when the photos come back (a restore), and the others follow their photos.
/// and take their place again when the photos come back (a restore), and the others follow their photos. A frame still
/// in the sidecar is its photo as the sidecar has it, so one whose file a conversion replaced meanwhile (R7: the same
/// frame, another SHA-256) keeps its positions.
/// </summary>
private static async Task<PositionMove?> RemovedAsync(ChronosRepositories db, Guid sequenceId, string project, SequenceManifest manifest,
CancellationToken cancellationToken)
{
var current = manifest.Frames.ToDictionary(f => f.Id);
var before = new List<(int, FramePhoto)>();
for (var after = -1; ;)
{
var page = await db.Frames.ListBySequenceAsync(sequenceId, after, PageSize, cancellationToken).ConfigureAwait(false);
before.AddRange(page.Select(f => (f.Index, new FramePhoto(f.Sha256, f.Size, f.CapturedAt))));
before.AddRange(page.Select(f => (f.Index, current.TryGetValue(f.Id, out var now) ? Photo(now) : new FramePhoto(f.Sha256, f.Size, f.CapturedAt))));
if (page.Count < PageSize) break;
after = page[^1].Index;
}
var to = new FramePhotos(manifest.Frames.Select(f => (f.I, new FramePhoto(f.Sha256, f.Size, f.CapturedAt))));
var to = new FramePhotos(manifest.Frames.Select(f => (f.I, Photo(f))));
var translated = ProjectSettings.TranslateFramePositions(project, new FramePhotos(before), to);
if (translated is null) return null;
var hero = HeroOf(project) is null && HeroOf(translated) is { } index ? manifest.Frames.FirstOrDefault(f => f.I == index)?.Id : null;
return new PositionMove(project, translated, hero);
}
private static FramePhoto Photo(SidecarFrame frame) => new(frame.Sha256, frame.Size, frame.CapturedAt);
/// <summary>
/// The index's copy of the project with the pending frames whose photos <paramref name="manifest"/> now holds put in
@@ -37,7 +37,8 @@ public sealed partial class SequenceTrash
/// <summary>
/// The dry run of emptying the trash: <paramref name="names"/> of the entries to erase (null: every entry), each
/// measured on disk, and the plan's fingerprint (<see cref="Fingerprint"/>). Reads only.
/// measured on disk, each replaced entry whose conversion was deleted since said so (<see cref="TrashEntry.ConversionDeleted"/>),
/// and the plan's fingerprint (<see cref="Fingerprint"/>). Reads only.
/// </summary>
public async Task<TrashEmptyPlan> PlanEmptyAsync(Archive archive, IReadOnlyList<string>? names = null, CancellationToken cancellationToken = default)
{
@@ -52,6 +53,7 @@ public sealed partial class SequenceTrash
var (files, bytes) = Directory.Exists(folder) ? Measure(folder, cancellationToken) : (0, 0L);
return e with { Files = files, Bytes = bytes };
}).ToList(), cancellationToken).ConfigureAwait(false);
for (var i = 0; i < measured.Count; i++) measured[i] = await PlannedAsync(paths, measured[i], cancellationToken).ConfigureAwait(false);
var unknown = names?.Where(n => !listed.Any(e => e.Name == n)).Distinct(StringComparer.Ordinal).ToList() ?? [];
return new TrashEmptyPlan(archive.Id, measured, measured.Sum(e => e.Bytes), Fingerprint(measured), unknown);
}
@@ -68,11 +70,15 @@ public sealed partial class SequenceTrash
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text.ToString())));
}
/// <summary>What identifies one entry as planned: its kind, name, files and bytes on disk, and when it was deleted.</summary>
/// <summary>
/// What identifies one entry as planned: its kind, name, files and bytes on disk, when it was deleted, and for a replaced
/// entry whether its conversion was deleted (<see cref="TrashEntry.ConversionDeleted"/>), which the dry run says.
/// </summary>
public static string EntryFingerprint(TrashEntry entry)
{
ArgumentNullException.ThrowIfNull(entry);
return string.Create(CultureInfo.InvariantCulture, $"{entry.Kind}|{entry.Name}|{entry.Files}|{entry.Bytes}|{entry.DeletedAt.UtcTicks}");
var planned = string.Create(CultureInfo.InvariantCulture, $"{entry.Kind}|{entry.Name}|{entry.Files}|{entry.Bytes}|{entry.DeletedAt.UtcTicks}");
return entry.ConversionDeleted ? planned + "|conversion-deleted" : planned;
}
/// <summary>
@@ -81,8 +87,9 @@ public sealed partial class SequenceTrash
/// hold exactly the planned entries (<see cref="EmptyTrashParameters.Fingerprint"/>), else nothing is erased; a run
/// resumed after a stop checks each remaining entry against its own fingerprint, keeps one that changed and skips one
/// that is gone, and each entry is checked against its fingerprint once more under its lease, just before it goes. A
/// <see cref="TrashKind.Replaced"/> entry is erased only while every replacement still matches its
/// SHA-256 in the sequence (re-hashed now); otherwise it is kept. Leftovers of an interrupted erase are deleted first.
/// <see cref="TrashKind.Replaced"/> entry is erased only while every replacement still matches its SHA-256 where it is now
/// (re-hashed now: in the sequence, or in the trash when its conversion was deleted, as the dry run said); otherwise it is
/// kept. Leftovers of an interrupted erase are deleted first.
/// </summary>
/// <param name="progress">Entries done so far (the resume point) and their number.</param>
/// <exception cref="StaleTrashPlanException">The trash no longer holds exactly the planned entries; nothing was erased.</exception>
@@ -111,7 +118,7 @@ public sealed partial class SequenceTrash
refused.Add(entry.Title);
Log.Warning("archive", $"Trash entry {entry.Name} changed since the emptying was planned; it is kept");
}
else if (await EraseAsync(paths, entry, item.Fingerprint, cancellationToken).ConfigureAwait(false))
else if (await EraseAsync(archive, paths, entry, item.Fingerprint, cancellationToken).ConfigureAwait(false))
{
erased++;
bytes += entry.Bytes;
@@ -131,19 +138,19 @@ public sealed partial class SequenceTrash
/// planned <paramref name="fingerprint"/> (another host sharing the archive may have restored the entry and deleted the
/// same sequence again since); false (logged) when it changed, or a replaced entry's replacements no longer match.
/// </summary>
private async Task<bool> EraseAsync(ArchivePaths paths, TrashEntry entry, string fingerprint, CancellationToken cancellationToken)
private async Task<bool> EraseAsync(Archive archive, ArchivePaths paths, TrashEntry entry, string fingerprint, CancellationToken cancellationToken)
{
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, EntryLease(entry.Name), _writer.Options.Owner, _writer.Options.LeaseWait,
_writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
{
var (folder, record) = Location(paths, entry);
if (!Directory.Exists(folder) || !File.Exists(record)) return false;
if (Reread(paths, entry, cancellationToken) is not { } now || EntryFingerprint(now) != fingerprint)
if (await RereadAsync(paths, entry, cancellationToken).ConfigureAwait(false) is not { } now || EntryFingerprint(now) != fingerprint)
{
Log.Warning("archive", $"Trash entry {entry.Name} changed since the emptying was planned; it is kept");
return false;
}
if (entry.Kind == TrashKind.Replaced && !await ReplacementsHoldAsync(paths, entry, cancellationToken).ConfigureAwait(false))
if (entry.Kind == TrashKind.Replaced && !await ReplacementsHoldAsync(archive, paths, entry, cancellationToken).ConfigureAwait(false))
{
Log.Warning("archive", $"Trash entry {entry.Name} is kept: a replacement of its originals no longer matches");
return false;
@@ -153,41 +160,17 @@ public sealed partial class SequenceTrash
Directory.Move(folder, aside);
File.Delete(record);
Erase(aside);
Log.Info("archive", $"Trash entry {entry.Name} ({entry.Title}, {entry.Files} files, {entry.Bytes} bytes) erased");
Log.Info("archive", $"Trash entry {entry.Name} ({entry.Title}, {entry.Files} files, {entry.Bytes} bytes) erased"
+ (now.ConversionDeleted ? "; the conversion of its originals had been deleted" : string.Empty));
return true;
}
}
/// <summary>
/// Whether every photo of a replaced entry still has its replacement in the sequence: a frame holding the replacement's
/// SHA-256 whose file hashes to it now. The originals are erased only then (a later phase's conversion).
/// An entry as the trash lists it and the emptying plans it (<see cref="PlannedAsync"/>), from its record and folder as
/// they are now; null when its record cannot be read.
/// </summary>
private async Task<bool> ReplacementsHoldAsync(ArchivePaths paths, TrashEntry entry, CancellationToken cancellationToken)
{
if (FrameTrash.ReadEntry(paths, entry.Name) is not { } record) return false;
foreach (var photo in record.Photos)
{
if (photo.Replacement is not { } replacement) return false;
var holders = (await _db.Frames.FindBySha256Async(replacement.ToLowerInvariant(), cancellationToken).ConfigureAwait(false))
.Where(f => f.SequenceId == record.SequenceId).ToList();
var verified = false;
foreach (var frame in holders)
{
var file = paths.FromRelative(frame.RelativePath);
if (!File.Exists(file)) continue;
if (string.Equals(await ContentHash.Sha256Async(file, null, cancellationToken).ConfigureAwait(false), replacement, StringComparison.OrdinalIgnoreCase))
{
verified = true;
break;
}
}
if (!verified) return false;
}
return true;
}
/// <summary>An entry as the trash lists it, from its record and folder as they are now; null when its record cannot be read.</summary>
private static TrashEntry? Reread(ArchivePaths paths, TrashEntry entry, CancellationToken cancellationToken)
private async Task<TrashEntry?> RereadAsync(ArchivePaths paths, TrashEntry entry, CancellationToken cancellationToken)
{
var (folder, recordPath) = Location(paths, entry);
var now = FrameTrash.IsPhotoEntry(entry.Name)
@@ -195,7 +178,7 @@ public sealed partial class SequenceTrash
: ReadRecord(recordPath) is { } record ? Entry(entry.ArchiveId, Path.GetFileName(entry.Name), record) : null;
if (now is null) return null;
var (files, bytes) = Measure(folder, cancellationToken);
return now with { Files = files, Bytes = bytes };
return await PlannedAsync(paths, now with { Files = files, Bytes = bytes }, cancellationToken).ConfigureAwait(false);
}
/// <summary>The folder and record of an entry of either kind.</summary>
@@ -0,0 +1,181 @@
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.Model;
namespace Chronos.Data.Archiving;
/// <summary>
/// Where the replacements of a replaced entry's originals are now (owner review 2, R7), for the emptying of the trash: in
/// the sequence (the replacement, or what replaced it in turn: a conversion of a conversion, followed through the sequence's
/// Replaced tombstones), in the trash (the conversion deleted as photos or with its sequence, or the original of a later
/// conversion), or nowhere (deleted and erased).
/// </summary>
public sealed partial class SequenceTrash
{
/// <summary>Links a replacement chain may have at most (a conversion of a conversion…), as sync follows them.</summary>
private const int ReplacementSteps = 8;
/// <summary>
/// <paramref name="entry"/> as an emptying plans it: a replaced entry is <see cref="TrashEntry.ConversionDeleted"/> when
/// the replacement of one of its photos is held by no frame of its sequence any more (the user deleted that photo, or the
/// whole sequence), so the dry run says so. Reads the index and the entry's record; hashes nothing.
/// </summary>
private async Task<TrashEntry> PlannedAsync(ArchivePaths paths, TrashEntry entry, CancellationToken cancellationToken)
{
if (entry.Kind != TrashKind.Replaced || FrameTrash.ReadEntry(paths, entry.Name) is not { } record) return entry;
var links = await LinksAsync(record.SequenceId, cancellationToken).ConfigureAwait(false);
foreach (var photo in record.Photos)
{
if (photo.Replacement is { } replacement && await InSequenceAsync(record.SequenceId, links, replacement, cancellationToken).ConfigureAwait(false) is null)
return entry with { ConversionDeleted = true };
}
return entry;
}
/// <summary>
/// Whether every photo of a replaced entry may be erased now, checked where its replacement is now. One its sequence holds
/// (followed through later conversions) must hash to it there, re-read now: the originals are never erased while their
/// conversion is damaged. One its sequence no longer holds was deleted, as the confirmed dry run said
/// (<see cref="TrashEntry.ConversionDeleted"/>): a copy the trash still holds (the deleted photos, the originals of a later
/// conversion, the deleted sequence) must hash to it too, and one erased since leaves nothing to keep the originals for.
/// </summary>
private async Task<bool> ReplacementsHoldAsync(Archive archive, ArchivePaths paths, TrashEntry entry, CancellationToken cancellationToken)
{
if (FrameTrash.ReadEntry(paths, entry.Name) is not { } record) return false;
var links = await LinksAsync(record.SequenceId, cancellationToken).ConfigureAwait(false);
TrashCopies? copies = null;
foreach (var photo in record.Photos)
{
if (photo.Replacement is not { } replacement) return false;
if (await InSequenceAsync(record.SequenceId, links, replacement, cancellationToken).ConfigureAwait(false) is { } held)
{
if (!await AnyHashesAsync(held.Frames.Select(f => (paths.FromRelative(f.RelativePath), held.Sha256)), cancellationToken).ConfigureAwait(false))
return false;
continue;
}
copies ??= Copies(archive, paths, entry.Name, record.SequenceId, links, cancellationToken);
var found = copies.Of(replacement);
if (found.Count > 0 && !await AnyHashesAsync(found, cancellationToken).ConfigureAwait(false)) return false;
}
return true;
}
/// <summary>The Replaced tombstones of a sequence in the index: each content and what replaced it (lower-case SHA-256).</summary>
private async Task<Dictionary<string, string>> LinksAsync(Guid sequenceId, CancellationToken cancellationToken)
{
var links = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var removal in await _db.FrameRemovals.ListBySequenceAsync(sequenceId, cancellationToken).ConfigureAwait(false))
{
if (removal.Reason == RemovalReason.Replaced && removal.ReplacementSha256 is { Length: > 0 } replacement)
links[removal.Sha256.ToLowerInvariant()] = replacement.ToLowerInvariant();
}
return links;
}
/// <summary>
/// The frames of the sequence that hold <paramref name="replacement"/>, or what replaced it in turn (<paramref name="links"/>),
/// and that content; null when no frame of the sequence holds any of them (it is not in the index, or was deleted).
/// </summary>
private async Task<(string Sha256, IReadOnlyList<Frame> Frames)?> InSequenceAsync(Guid sequenceId, IReadOnlyDictionary<string, string> links,
string replacement, CancellationToken cancellationToken)
{
var sha = replacement.ToLowerInvariant();
var seen = new HashSet<string>(StringComparer.Ordinal);
for (var step = 0; step <= ReplacementSteps && seen.Add(sha); step++)
{
var holders = (await _db.Frames.FindBySha256Async(sha, cancellationToken).ConfigureAwait(false)).Where(f => f.SequenceId == sequenceId).ToList();
if (holders.Count > 0) return (sha, holders);
if (!links.TryGetValue(sha, out var next)) break;
sha = next;
}
return null;
}
/// <summary>
/// What the trash holds of a sequence's photos, but the entry <paramref name="except"/> (the one being erased): the files of
/// its photo entries (deleted photos, replaced originals) and of its own entry when the whole sequence is in the trash, by
/// content, and the replacements those entries name. Read from their records and sidecars; an unreadable one adds nothing.
/// </summary>
private static TrashCopies Copies(Archive archive, ArchivePaths paths, string except, Guid sequenceId, IReadOnlyDictionary<string, string> links,
CancellationToken cancellationToken)
{
var copies = new TrashCopies(links);
foreach (var listed in FrameTrash.List(archive, cancellationToken).Where(e => e.SequenceId == sequenceId && e.Name != except))
{
if (FrameTrash.ReadEntry(paths, listed.Name) is not { } record) continue;
var (folder, _) = FrameTrash.Location(paths, listed.Name);
foreach (var photo in record.Photos)
{
if (photo.Files.Count > 0 && (photo.Files[0].Sha256 ?? photo.Frame.Sha256) is { } sha) copies.Add(sha, Path.Combine(folder, photo.Files[0].Path));
if (photo.Frame.Sha256 is { } original && photo.Replacement is { } replacement) copies.Link(original, replacement);
}
}
var trash = TrashDirectory(paths);
if (!Directory.Exists(trash)) return copies;
foreach (var recordPath in Directory.EnumerateFiles(trash, "*" + RecordExtension))
{
cancellationToken.ThrowIfCancellationRequested();
var folder = Path.Combine(trash, Path.GetFileNameWithoutExtension(recordPath));
if (!Directory.Exists(folder) || ReadRecord(recordPath)?.Sequence.Id != sequenceId) continue;
var deleted = paths.Sequence(paths.ToRelative(folder));
SequenceManifest manifest;
try
{
manifest = ManifestStore.ReadSequence(deleted.ManifestPath);
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
Log.Warning("archive", $"The sidecar of trash entry {Path.GetFileName(folder)} cannot be read; its photos are not looked at", ex);
continue;
}
foreach (var frame in manifest.Frames.Where(f => f.Sha256 is not null)) copies.Add(frame.Sha256!, deleted.File(frame.File));
foreach (var removed in manifest.Removed ?? [])
{
if (removed.Reason == RemovalReason.Replaced && removed.Replacement is { } replacement) copies.Link(removed.Sha256, replacement);
}
}
return copies;
}
/// <summary>Whether one of <paramref name="files"/> is there and hashes to its SHA-256 now.</summary>
private static async Task<bool> AnyHashesAsync(IEnumerable<(string Path, string Sha256)> files, CancellationToken cancellationToken)
{
foreach (var (path, sha) in files)
{
if (!File.Exists(path)) continue;
if (string.Equals(await ContentHash.Sha256Async(path, null, cancellationToken).ConfigureAwait(false), sha, StringComparison.OrdinalIgnoreCase)) return true;
}
return false;
}
/// <summary>Copies of a sequence's photos in the trash by content, and the replacement links known (<see cref="Copies"/>).</summary>
private sealed class TrashCopies(IReadOnlyDictionary<string, string> links)
{
private readonly Dictionary<string, string> _links = new(links, StringComparer.Ordinal);
private readonly Dictionary<string, List<string>> _files = new(StringComparer.Ordinal);
public void Add(string sha256, string path)
{
var sha = sha256.ToLowerInvariant();
if (!_files.TryGetValue(sha, out var paths)) _files[sha] = paths = [];
paths.Add(path);
}
public void Link(string sha256, string replacement) => _links.TryAdd(sha256.ToLowerInvariant(), replacement.ToLowerInvariant());
/// <summary>The copies of <paramref name="replacement"/> and of what replaced it in turn, each with the content it must hash to.</summary>
public List<(string Path, string Sha256)> Of(string replacement)
{
var found = new List<(string, string)>();
var sha = replacement.ToLowerInvariant();
var seen = new HashSet<string>(StringComparer.Ordinal);
for (var step = 0; step <= ReplacementSteps && seen.Add(sha); step++)
{
if (_files.TryGetValue(sha, out var paths)) found.AddRange(paths.Select(p => (p, sha)));
if (!_links.TryGetValue(sha, out var next)) break;
sha = next;
}
return found;
}
}
}
+12 -1
View File
@@ -68,7 +68,18 @@ public enum TrashKind
/// <param name="Folder">Archive-relative folder the sequence came from (and returns to when it is free).</param>
/// <param name="Frames">Photos the entry holds.</param>
public sealed record TrashEntry(Guid ArchiveId, string Name, Guid SequenceId, string Title, string Folder, int Frames, int Files, long Bytes,
DateTimeOffset DeletedAt, string? DeletedBy, TrashKind Kind = TrashKind.Sequence);
DateTimeOffset DeletedAt, string? DeletedBy, TrashKind Kind = TrashKind.Sequence)
{
/// <summary>The job that made the entry (a conversion's Replace, owner review 2, R7); null for one a user's action made.</summary>
public Guid? JobId { get; init; }
/// <summary>
/// A <see cref="TrashKind.Replaced"/> entry whose conversion was deleted since: a photo's replacement (followed through
/// later conversions) is no longer in its sequence, so erasing the entry may erase the last copy of that photo. Set by the
/// dry run of an emptying (<see cref="SequenceTrash.PlanEmptyAsync"/>), which says so; false in a plain listing.
/// </summary>
public bool ConversionDeleted { get; init; }
}
/// <summary>The plan no longer matches the index or the jobs (a sequence moved, vanished or got busy since it was made); nothing was deleted.</summary>
public sealed class StaleDeletePlanException(Guid sequenceId) : InvalidOperationException(Loc.L("Archive.Error.StalePlan"))
+6 -4
View File
@@ -192,10 +192,11 @@ public static class SyncRules
/// and not verified) stands for a wanted frame of its size that no hash matched (by size, not name: the server names
/// its copy by its own template); the upload hashes it before making the proxy. A wanted frame the server has not
/// hashed is the local original of its size and capture time (<paramref name="captured"/>, by server frame id), as
/// <see cref="ProxyOriginal"/> finds it for the upload.
/// <see cref="ProxyOriginal"/> finds it for the upload. A wanted frame whose photo this PC holds in another encoding (a
/// conversion on either side, <paramref name="tombstones"/>) is made from that one, as the upload makes it.
/// </summary>
public static int ProxiesToSend(SequenceManifest manifest, IReadOnlyCollection<Frame> local, ImageDecoder decoder,
IReadOnlyDictionary<Guid, DateTime?>? captured = null)
IReadOnlyDictionary<Guid, DateTime?>? captured = null, SyncTombstones? tombstones = null)
{
ArgumentNullException.ThrowIfNull(manifest);
IReadOnlyList<Frame> frames = [.. local];
@@ -207,12 +208,13 @@ public static class SyncRules
{
if (ProxyOriginal(frame, captured?.GetValueOrDefault(frame.Id), frames, photos) is { } original && taken.Add(original.Id) && Readable(original)) count++;
}
var hashed = frames.Where(f => !string.IsNullOrEmpty(f.Sha256)).ToLookup(f => f.Sha256!.ToLowerInvariant(), StringComparer.Ordinal);
var aliases = tombstones ?? SyncTombstones.None;
var hashed = frames.Where(f => !string.IsNullOrEmpty(f.Sha256)).ToLookup(f => aliases.Canonical(f.Sha256)!, StringComparer.Ordinal);
var unhashed = frames.Where(f => string.IsNullOrEmpty(f.Sha256) && Readable(f) && !taken.Contains(f.Id)).GroupBy(f => f.Size)
.ToDictionary(g => g.Key, g => g.Count());
foreach (var frame in manifest.Frames.Where(f => f.WantsProxy && f.Sha256.Length > 0))
{
var sha = frame.Sha256.ToLowerInvariant();
var sha = aliases.Canonical(frame.Sha256)!;
if (hashed.Contains(sha))
{
if (hashed[sha].Any(Readable)) count++;
+11 -5
View File
@@ -546,7 +546,7 @@ public sealed class SyncService
var (missingRemote, missingLocal) = SyncRules.CompareOriginals([.. present.Select(f => new FramePhoto(f.Sha256, f.Size, f.CapturedAt))],
[.. manifest.Frames.Select(f => new FramePhoto(f.Sha256, f.Size, captured?.GetValueOrDefault(f.Id)))], tombstones);
// Proxies the server asks for that this PC can make from its originals travel with an upload too (BRIEF §2.3).
var proxies = policy.CanEdit && manifest.Proxies is not null ? SyncRules.ProxiesToSend(manifest, present, Options.Archive.Decoder, captured) : 0;
var proxies = policy.CanEdit && manifest.Proxies is not null ? SyncRules.ProxiesToSend(manifest, present, Options.Archive.Decoder, captured, tombstones) : 0;
// Those change without the server's frame counters moving: while some may be made here, the server's next
// change of the sequence brings a new comparison.
var watch = policy.CanEdit && (proxies > 0 || SyncRules.MakesProxiesFor(present, Options.Archive.Decoder));
@@ -714,13 +714,19 @@ public sealed class SyncService
}
}
/// <summary>
/// Whether at least half of the smaller side's originals are the other side's by content: a photo either side replaced by
/// a converted file counts as its replacement (owner review 2, R7), as the comparison of linked pairs counts it, so a copy
/// converted on one side before the two were linked is still found.
/// </summary>
private async Task<bool> SameOriginalsAsync(ISyncRemote remote, Sequence local, SequenceDto dto, CancellationToken cancellationToken)
{
var hashes = (await SequenceFrames.ListAsync(_db, local.Id, cancellationToken).ConfigureAwait(false))
.Select(f => f.Sha256?.ToLowerInvariant()).OfType<string>().ToHashSet(StringComparer.Ordinal);
if (hashes.Count == 0) return false;
var frames = await SequenceFrames.ListAsync(_db, local.Id, cancellationToken).ConfigureAwait(false);
if (!frames.Any(f => !string.IsNullOrEmpty(f.Sha256))) return false;
var manifest = await remote.GetManifestAsync(dto.Id, cancellationToken).ConfigureAwait(false);
var shared = manifest.Frames.Select(f => f.Sha256.ToLowerInvariant()).Distinct(StringComparer.Ordinal).Count(hashes.Contains);
var tombstones = new SyncTombstones(await _db.FrameRemovals.ListBySequenceAsync(local.Id, cancellationToken).ConfigureAwait(false), manifest.Removed);
var hashes = frames.Where(f => !string.IsNullOrEmpty(f.Sha256)).Select(f => tombstones.Canonical(f.Sha256)!).ToHashSet(StringComparer.Ordinal);
var shared = manifest.Frames.Where(f => f.Sha256.Length > 0).Select(f => tombstones.Canonical(f.Sha256)!).Distinct(StringComparer.Ordinal).Count(hashes.Contains);
return shared > 0 && shared * 2 >= Math.Min(hashes.Count, manifest.Frames.Count);
}
+64 -23
View File
@@ -8,33 +8,42 @@ namespace Chronos.Data.Sync;
/// The photos each copy of a linked pair removed (owner review 2, R6; BRIEF §14.5): a photo one side deleted is not
/// offered to it again (no upload of what the server deleted, no download of what this PC deleted; local files are never
/// deleted by sync), and a photo one side replaced by a converted file is the same photo as its replacement on either side
/// (an alias: both are compared, matched and translated as the replacement). No I/O.
/// (R7). Replacements are links between encodings of one photo, from either side and in either direction (a conversion, a
/// conversion of a conversion, its undo): every photo they link is compared, matched and translated as one, however many
/// encodings each side made of it (each side converting its own copy gives two, which are still one photo). No I/O; safe
/// to read from several threads once made.
/// </summary>
public sealed class SyncTombstones
{
/// <summary>Links a replacement chain may have at most (a conversion of a conversion…); longer ones stop there.</summary>
private const int MaxAliasSteps = 8;
private readonly HashSet<string> _deletedLocally;
private readonly HashSet<string> _deletedRemotely;
private readonly Dictionary<string, string> _aliases;
/// <summary>Each SHA-256 a replacement links, and the one its photo is compared as (the ordinal-smallest of them).</summary>
private readonly Dictionary<string, string> _canonical;
public SyncTombstones(IEnumerable<FrameRemoval> local, IEnumerable<RemovedPhotoDto>? remote)
{
ArgumentNullException.ThrowIfNull(local);
_deletedLocally = new HashSet<string>(StringComparer.Ordinal);
_deletedRemotely = new HashSet<string>(StringComparer.Ordinal);
_aliases = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var removal in local) Add(removal.Sha256, removal.ReplacementSha256, removal.Reason == RemovalReason.Replaced, _deletedLocally);
var deletedLocally = new List<string>();
var deletedRemotely = new List<string>();
var links = new List<(string, string)>();
foreach (var removal in local) Add(removal.Sha256, removal.ReplacementSha256, removal.Reason == RemovalReason.Replaced, deletedLocally, links);
foreach (var removal in remote ?? [])
Add(removal.Sha256, removal.Replacement, string.Equals(removal.Reason, Wire(RemovalReason.Replaced), StringComparison.OrdinalIgnoreCase), _deletedRemotely);
{
Add(removal.Sha256, removal.Replacement, string.Equals(removal.Reason, Wire(RemovalReason.Replaced), StringComparison.OrdinalIgnoreCase),
deletedRemotely, links);
}
_canonical = Classes(links);
// A deletion covers every encoding of the photo deleted: kept by the photo's canonical SHA-256.
_deletedLocally = deletedLocally.Select(sha => Canonical(sha)!).ToHashSet(StringComparer.Ordinal);
_deletedRemotely = deletedRemotely.Select(sha => Canonical(sha)!).ToHashSet(StringComparer.Ordinal);
}
/// <summary>No photo removed on either side.</summary>
public static SyncTombstones None { get; } = new([], null);
/// <summary>Whether either side removed or replaced anything.</summary>
public bool IsEmpty => _deletedLocally.Count == 0 && _deletedRemotely.Count == 0 && _aliases.Count == 0;
public bool IsEmpty => _deletedLocally.Count == 0 && _deletedRemotely.Count == 0 && _canonical.Count == 0;
/// <summary>The wire name of a removal reason (<c>deleted</c>, <c>replaced</c>).</summary>
public static string Wire(RemovalReason reason) => reason.ToString().ToLowerInvariant();
@@ -44,38 +53,70 @@ public sealed class SyncTombstones
[.. removals.Select(r => new RemovedPhotoDto(r.Sha256, r.ReplacementSha256, Wire(r.Reason), r.RemovedAt))];
/// <summary>
/// The SHA-256 a photo is compared as: the end of its replacement chain on either side, lower-case; null or empty
/// (not hashed yet) stays as it is.
/// The SHA-256 a photo is compared as, lower-case: of the encodings replacements link it to on either side, the
/// ordinal-smallest, so the same photo compares the same whichever side converted it and in whatever order the links
/// came; its own SHA-256 when nothing links it. Null or empty (not hashed yet) stays as it is.
/// </summary>
public string? Canonical(string? sha256)
{
if (string.IsNullOrEmpty(sha256)) return sha256;
var current = sha256.ToLowerInvariant();
for (var step = 0; step < MaxAliasSteps && _aliases.TryGetValue(current, out var next); step++) current = next;
return current;
var sha = sha256.ToLowerInvariant();
return _canonical.TryGetValue(sha, out var canonical) ? canonical : sha;
}
/// <summary>The photo as it is compared (<see cref="Canonical(string?)"/>).</summary>
public FramePhoto Canonical(FramePhoto photo)
{
ArgumentNullException.ThrowIfNull(photo);
return photo.IsHashed && _aliases.Count > 0 ? photo with { Sha256 = Canonical(photo.Sha256) } : photo;
return photo.IsHashed && _canonical.Count > 0 ? photo with { Sha256 = Canonical(photo.Sha256) } : photo;
}
/// <summary>This PC deleted the photo (or what replaced it): the server's copy is not downloaded.</summary>
/// <summary>This PC deleted the photo (in any of its encodings): the server's copy is not downloaded.</summary>
public bool DeletedLocally(string? sha256) => Deleted(sha256, _deletedLocally);
/// <summary>The server deleted the photo (or what replaced it): this PC's copy is not uploaded.</summary>
/// <summary>The server deleted the photo (in any of its encodings): this PC's copy is not uploaded.</summary>
public bool DeletedRemotely(string? sha256) => Deleted(sha256, _deletedRemotely);
private bool Deleted(string? sha256, HashSet<string> deleted) =>
!string.IsNullOrEmpty(sha256) && deleted.Count > 0 && (deleted.Contains(sha256.ToLowerInvariant()) || deleted.Contains(Canonical(sha256)!));
private bool Deleted(string? sha256, HashSet<string> deleted) => !string.IsNullOrEmpty(sha256) && deleted.Count > 0 && deleted.Contains(Canonical(sha256)!);
private void Add(string sha256, string? replacement, bool replaced, HashSet<string> deleted)
private static void Add(string sha256, string? replacement, bool replaced, List<string> deleted, List<(string, string)> links)
{
if (string.IsNullOrEmpty(sha256)) return;
var sha = sha256.ToLowerInvariant();
if (replaced && !string.IsNullOrEmpty(replacement)) _aliases[sha] = replacement.ToLowerInvariant();
if (replaced && !string.IsNullOrEmpty(replacement)) links.Add((sha, replacement.ToLowerInvariant()));
else deleted.Add(sha);
}
/// <summary>
/// The photos the links join (union-find), each SHA-256 linked to the ordinal-smallest of its photo: a root is always the
/// smallest of what it joins, so the result does not depend on the order of the links.
/// </summary>
private static Dictionary<string, string> Classes(List<(string A, string B)> links)
{
var parent = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var (a, b) in links)
{
if (a == b) continue;
parent.TryAdd(a, a);
parent.TryAdd(b, b);
var (x, y) = (Find(a), Find(b));
if (x == y) continue;
if (string.CompareOrdinal(x, y) < 0) parent[y] = x;
else parent[x] = y;
}
return parent.Keys.ToList().ToDictionary(k => k, Find, StringComparer.Ordinal);
string Find(string sha)
{
var root = sha;
while (parent[root] != root) root = parent[root];
while (parent[sha] != root)
{
var next = parent[sha];
parent[sha] = root;
sha = next;
}
return root;
}
}
}
+87 -22
View File
@@ -26,7 +26,8 @@ namespace Chronos.Data.Sync;
/// which names them and writes the sidecar; the first original creates the local
/// sequence, which then takes the server's settings. Frames of the local copy not hashed yet are hashed first (so the
/// server's copies of them are recognised), and originals flagged missing here are restored to their recorded place in
/// the folder the sequence is in (never one it left).
/// the folder the sequence is in (never one it left; one the server holds in another encoding, a conversion on either
/// side, takes the frame's place under its id instead).
/// Proxy downloads fill the proxy cache. Renders travel on request: this PC's to the server (hash-verified chunked
/// upload) and the server's into the local copy's exports. A resumed job skips what is already on the other side, so
/// pausing or a crash loses at most the files in flight.
@@ -111,10 +112,11 @@ internal sealed class SyncTransfers(SyncService sync)
/// <summary>
/// The proxies the server asks for (<see cref="ManifestFrame.WantsProxy"/>) that this PC's decoders can make from its
/// originals (by their archived SHA-256, or the one <paramref name="hashes"/> holds for an original the index has none
/// for; by size and capture time for a frame the server has not hashed, <see cref="SyncRules.ProxyOriginal"/>), made as
/// the server's proxy policy says with the server's capture data, and sent. One the server refuses is
/// counted in the job log; a server that makes no proxies, or an account that may not send them, ends the pass; a
/// server busy or out of reach fails the job like an original would.
/// for, compared as the photo either side's conversions make it, <see cref="SyncTombstones"/>: a frame this PC converted
/// makes the proxy of the server's original; by size and capture time for a frame the server has not hashed,
/// <see cref="SyncRules.ProxyOriginal"/>), made as the server's proxy policy says with the server's capture data, and
/// sent. One the server refuses is counted in the job log; a server that makes no proxies, or an account that may not
/// send them, ends the pass; a server busy or out of reach fails the job like an original would.
/// </summary>
private async Task SendProxiesAsync(JobContext context, ISyncRemote remote, Guid remoteId, Sequence local, ArchivePaths paths, IReadOnlyList<Frame> frames,
IReadOnlyDictionary<Guid, string> hashes)
@@ -123,10 +125,11 @@ internal sealed class SyncTransfers(SyncService sync)
var manifest = await remote.GetManifestAsync(remoteId, ct).ConfigureAwait(false);
var wanted = manifest.Frames.Where(f => f.WantsProxy).ToList();
if (manifest.Proxies is not { } spec || wanted.Count == 0) return;
var tombstones = new SyncTombstones(await sync.Database.FrameRemovals.ListBySequenceAsync(local.Id, ct).ConfigureAwait(false), manifest.Removed);
var originals = new Dictionary<string, Frame>(StringComparer.Ordinal);
foreach (var frame in frames)
{
if ((frame.Sha256 ?? hashes.GetValueOrDefault(frame.Id)) is { } sha) originals.TryAdd(sha.ToLowerInvariant(), frame);
if ((frame.Sha256 ?? hashes.GetValueOrDefault(frame.Id)) is { } sha) originals.TryAdd(tombstones.Canonical(sha)!, frame);
}
var records = (await remote.ListFramesAsync(remoteId, ct).ConfigureAwait(false)).ToDictionary(f => f.Id);
var photos = SyncRules.Photos(frames);
@@ -144,7 +147,7 @@ internal sealed class SyncTransfers(SyncService sync)
// A frame the server has not hashed yet is this PC's original of its size and capture time.
var original = frame.Sha256.Length == 0
? SyncRules.ProxyOriginal(frame, record?.CapturedAt, frames, photos)
: originals.GetValueOrDefault(frame.Sha256.ToLowerInvariant());
: originals.GetValueOrDefault(tombstones.Canonical(frame.Sha256)!);
var jpeg = original is not null && record is not null
? await Task.Run(() => MakeProxy(decoder, paths.FromRelative(original.RelativePath), RenderNodeClient.ToFrame(record), camera, spec, frame.FileName,
token), token).ConfigureAwait(false)
@@ -211,11 +214,22 @@ internal sealed class SyncTransfers(SyncService sync)
var manifest = await remote.GetManifestAsync(remoteId, ct).ConfigureAwait(false);
var captured = (await remote.ListFramesAsync(remoteId, ct).ConfigureAwait(false)).ToDictionary(f => f.Id, f => f.CapturedAt);
var (have, restore, photos) = local is null ? ([], [], new FramePhotos([])) : await LocalContentAsync(archive, local, ct).ConfigureAwait(false);
var (have, restore, photos, missing) = local is null ? ([], [], new FramePhotos([]), []) : await LocalContentAsync(archive, local, ct).ConfigureAwait(false);
// A photo this PC deleted is not fetched again; one replaced here by a converted file is here as its replacement (owner review 2, R6).
var tombstones = local is null ? SyncTombstones.None
: new SyncTombstones(await db.FrameRemovals.ListBySequenceAsync(local.Id, ct).ConfigureAwait(false), manifest.Removed);
if (!tombstones.IsEmpty) have = [.. have.Select(h => tombstones.Canonical(h)!)];
// A frame flagged missing here whose photo the server holds in another encoding (a conversion on either side, R7): the
// copy fetched takes that frame's place under its id, rather than coming in as a frame of its own beside it.
// One whose own encoding the server holds too is restored from that one instead, and one whose photo another frame
// here holds intact stays as it is, as a restore leaves it.
var byAlias = new ConcurrentDictionary<string, Frame>(StringComparer.Ordinal);
if (!tombstones.IsEmpty)
{
var served = manifest.Frames.Where(f => f.Sha256.Length > 0).Select(f => f.Sha256.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
foreach (var frame in missing.Where(f => !served.Contains(f.Sha256!.ToLowerInvariant()) && !have.Contains(tombstones.Canonical(f.Sha256)!)))
byAlias.TryAdd(tombstones.Canonical(frame.Sha256)!, frame);
}
// An original the server has not hashed yet (adopted there, not verified) is here when an original of its size and
// capture time is; each one is fetched on its own and hashed here.
var wanted = manifest.Frames
@@ -247,6 +261,7 @@ internal sealed class SyncTransfers(SyncService sync)
var sequenceId = local?.Id;
var refused = 0;
var restores = new ConcurrentBag<(string Staged, Guid FrameId)>();
var aliases = new ConcurrentBag<AliasCopy>();
await Parallel.ForEachAsync(rest, Workers(sync.Options.Downloads, ct), async (frame, token) =>
{
var (staged, sha) = await FetchOriginalAsync(remote, frame, staging, token).ConfigureAwait(false);
@@ -254,6 +269,11 @@ internal sealed class SyncTransfers(SyncService sync)
{
restores.Add((staged, frameId));
}
else if (byAlias.TryRemove(tombstones.Canonical(sha)!, out var lost))
{
// This encoding takes the place of the one missing here, after the transfers as the restores do.
aliases.Add(new AliasCopy(staged, sha, lost, frame.FileName));
}
else if (frame.Sha256.Length == 0 && (tombstones.DeletedLocally(sha) || have.Contains(tombstones.Canonical(sha)!)))
{
// An original the server has not hashed is known by content only now: one this PC deleted (or holds as
@@ -269,30 +289,33 @@ internal sealed class SyncTransfers(SyncService sync)
await progress.StepAsync().ConfigureAwait(false);
}).ConfigureAwait(false);
// Null when the sequence is not in the folder the index has: the copies stay staged for the next attempt.
var restored = restores.IsEmpty ? 0 : await RestoreAsync(local!, paths, restores, ct).ConfigureAwait(false);
if (restored is not null) TryDeleteDirectory(staging);
// Restored originals are checked against their records, which clears their missing flag.
if (restored > 0) await VerifyAsync(archive, local!.Id, ct).ConfigureAwait(false);
var restored = restores.IsEmpty && aliases.IsEmpty ? 0 : await RestoreAsync(local!, paths, restores, ct).ConfigureAwait(false);
var (swapped, moved) = restored is null || aliases.IsEmpty ? (0, restored is null)
: await SwapAliasesAsync(context, archive, local!, paths, aliases, ct).ConfigureAwait(false);
if (!moved) TryDeleteDirectory(staging);
// Restored originals are checked against their records, which clears their missing flag (and reads the tier of a
// frame that took another encoding).
if (restored + swapped > 0) await VerifyAsync(archive, local!.Id, ct).ConfigureAwait(false);
if (created) await sync.TakeAllAsync(remote, remoteId, ct).ConfigureAwait(false);
await sync.RecompareAsync(remote, remoteId, ct).ConfigureAwait(false);
if (sequenceId is { } downloaded && wanted.Count > restores.Count + refused)
if (sequenceId is { } downloaded && wanted.Count > restores.Count + aliases.Count + refused)
{
var label = local!.DisplayTitle;
await EnqueueFollowUpAsync(context, ArchiveJobs.Thumbnails([downloaded], label)).ConfigureAwait(false);
await EnqueueFollowUpAsync(context, ProcessingJobs.LightAnalysis([downloaded], label)).ConfigureAwait(false);
}
if (restored is null) throw new InvalidOperationException(Loc.L("Errors.Archive.FolderMoved"));
if (moved) throw new InvalidOperationException(Loc.L("Errors.Archive.FolderMoved"));
}
/// <summary>
/// The originals a local copy holds (lower-case SHA-256, and their photos for server frames not hashed yet) and the
/// frame each original flagged missing restores. Frames not hashed yet (an adopted folder never verified) are hashed
/// first through the archive's verify, so the server's copies of them are recognised instead of committed again as
/// duplicates.
/// The originals a local copy holds (lower-case SHA-256, and their photos for server frames not hashed yet), the frame
/// each original flagged missing restores, and the frames flagged missing whose content no intact frame holds. Frames
/// not hashed yet (an adopted folder never verified) are hashed first through the archive's verify, so the server's
/// copies of them are recognised instead of committed again as duplicates.
/// </summary>
private async Task<(HashSet<string> Have, Dictionary<string, Guid> Restore, FramePhotos Photos)> LocalContentAsync(Archive archive, Sequence local,
CancellationToken ct)
private async Task<(HashSet<string> Have, Dictionary<string, Guid> Restore, FramePhotos Photos, IReadOnlyList<Frame> Missing)> LocalContentAsync(
Archive archive, Sequence local, CancellationToken ct)
{
var frames = await SequenceFrames.ListAsync(sync.Database, local.Id, ct).ConfigureAwait(false);
if (frames.Any(f => f.Sha256 is null && (f.Flags & FrameFlags.Missing) == 0))
@@ -303,13 +326,16 @@ internal sealed class SyncTransfers(SyncService sync)
var have = frames.Where(f => (f.Flags & FrameFlags.Missing) == 0 && f.Sha256 is not null).Select(f => f.Sha256!.ToLowerInvariant())
.ToHashSet(StringComparer.Ordinal);
var restore = new Dictionary<string, Guid>(StringComparer.Ordinal);
var missing = new List<Frame>();
foreach (var frame in frames.Where(f => (f.Flags & FrameFlags.Missing) != 0 && f.Sha256 is not null))
{
var sha = frame.Sha256!.ToLowerInvariant();
if (!have.Contains(sha)) restore.TryAdd(sha, frame.Id);
if (have.Contains(sha)) continue;
restore.TryAdd(sha, frame.Id);
missing.Add(frame);
}
var photos = SyncRules.Photos([.. frames.Where(f => (f.Flags & FrameFlags.Missing) == 0)]);
return (have, restore, photos);
return (have, restore, photos, missing);
}
private Task VerifyAsync(Archive archive, Guid sequenceId, CancellationToken ct) =>
@@ -344,6 +370,45 @@ internal sealed class SyncTransfers(SyncService sync)
return restored;
}, ct);
/// <summary>
/// Gives each frame flagged missing here whose photo the server holds only in another encoding (a conversion on either
/// side, owner review 2, R7) the verified copy fetched (<see cref="FrameTrash.ReplaceMissingAsync"/>: under the sequence's
/// lease, in its folder as the index has it then, whose sidecar must be the sequence's, <see cref="SequenceWriter.ReadLocked"/>).
/// Run after the transfers, once <see cref="RestoreAsync"/> found the sequence in that folder. Returns how many took their
/// frame's place; the copy of a frame that changed meanwhile, or whose file came back, is dropped (logged). Moved, with the
/// copies not swapped yet kept in staging for the next attempt, when the sequence left that folder meanwhile.
/// </summary>
private async Task<(int Swapped, bool Moved)> SwapAliasesAsync(JobContext context, Archive archive, Sequence local, ArchivePaths paths,
IEnumerable<AliasCopy> aliases, CancellationToken ct)
{
var swapped = 0;
foreach (var alias in aliases)
{
try
{
if (await sync.Archives.FrameTrash.ReplaceMissingAsync(archive, local.Id, alias.Lost.Id, alias.Lost.Sha256!, alias.Staged, alias.Sha256,
alias.FileName, ct).ConfigureAwait(false))
{
swapped++;
continue;
}
}
catch (Exception ex) when (ex is InvalidDataException or DirectoryNotFoundException or FileNotFoundException)
{
// Another index moved the sequence away, maybe another one into the folder it left: nothing is filed there.
if (await sync.Database.Sequences.GetAsync(local.Id, ct).ConfigureAwait(false) is { } row && SequenceFolders.Holds(paths.Sequence(row.Folder), row.Id))
throw;
return (swapped, true);
}
File.Delete(alias.Staged);
context.Log($"{alias.FileName}: its frame here changed meanwhile, not downloaded");
}
return (swapped, false);
}
/// <summary>A verified copy fetched in another encoding of a frame flagged missing here (<see cref="SwapAliasesAsync"/>).</summary>
private sealed record AliasCopy(string Staged, string Sha256, Frame Lost, string FileName);
/// <summary>Puts a verified copy of an original flagged missing back where its record says; a file that reappeared meanwhile is kept.</summary>
private static void Restore(string staged, string place)
{
+3 -2
View File
@@ -16,10 +16,11 @@ public sealed record FrameDeleteResultDto(Guid SequenceId, int Photos, long Byte
/// <summary>
/// An entry of the archive's trash (<c>GET /api/v1/archive/trash</c>): a deleted sequence (<see cref="Kind"/> <c>sequence</c>)
/// or photos deleted from one (<c>photos</c>; <c>replaced</c> for originals a conversion replaced). <see cref="Name"/>
/// identifies it in restore and empty requests.
/// identifies it in restore and empty requests. In the dry run of an emptying, <see cref="ConversionDeleted"/> marks
/// replaced originals whose conversion was deleted since, which may be the last copy of their photos.
/// </summary>
public sealed record TrashEntryDto(string Name, string Kind, Guid SequenceId, string Title, string Folder, int Photos, int Files, long Bytes,
string? DeletedBy, DateTimeOffset DeletedAt);
string? DeletedBy, DateTimeOffset DeletedAt, bool ConversionDeleted = false);
/// <summary><c>GET /api/v1/archive/trash</c>: the entries, newest first, and their total size.</summary>
public sealed record TrashListDto(IReadOnlyList<TrashEntryDto> Entries, long Bytes);
@@ -136,7 +136,9 @@ export async function renderTrash(root, { api, setMeta, actions, onEvent }, { ba
const confirmed = await confirmDialog({
title: t("Admin.Trash.EmptyTitle"),
body: [plural("Admin.Trash.EmptyBody", plan.files, formatBytes(plan.bytes)), t("Admin.Trash.EmptyFinal")].join(" "),
list: plan.entries.map((e) => t("Admin.Trash.PlanItem", kindLabel(e.kind), e.title, formatBytes(e.bytes))),
// Replaced originals whose conversion was deleted since may be the last copy of their photos: the list says so.
list: plan.entries.map((e) => t("Admin.Trash.PlanItem",
e.conversionDeleted ? `${kindLabel(e.kind)} · ${t("Admin.Trash.ConversionDeleted")}` : kindLabel(e.kind), e.title, formatBytes(e.bytes))),
confirm: t("Admin.Trash.EmptyConfirm"),
confirmTip: t("Admin.Trash.EmptyConfirm.Tip"),
cancel: t("Admin.Common.Keep"),
+1 -1
View File
@@ -33,7 +33,7 @@ public static partial class TrashEndpoints
public static bool IsEntryName(string? name) => name is not null && EntryName().IsMatch(name);
public static TrashEntryDto Entry(TrashEntry e) =>
new(e.Name, e.Kind.ToString().ToLowerInvariant(), e.SequenceId, e.Title, e.Folder, e.Frames, e.Files, e.Bytes, e.DeletedBy, e.DeletedAt);
new(e.Name, e.Kind.ToString().ToLowerInvariant(), e.SequenceId, e.Title, e.Folder, e.Frames, e.Files, e.Bytes, e.DeletedBy, e.DeletedAt, e.ConversionDeleted);
/// <summary>The entries newest first with their total size (a read-only archive lists them too); 503 <c>archive_offline</c>.</summary>
private static async Task<IResult> ListAsync(HttpContext context, ChronosDatabase db, ServerArchive archive, [FromServices] ArchiveService? archives)