Files
Chronos/src/Chronos.Data/Archiving/SequenceTrash.Empty.cs
T
Alby96andClaude Opus 5.5 45e6911082 feat(jobs): every job handler reports a structured progress detail
The job list showed a bar and a free-text line that each handler worded
its own way. Each handler now reports its step, the item it is on, photo
x of y and sequence/folder/output/step n of m through the P2.1 JobContext
detail. Clients can word and lay that out themselves, and the 2/s
throttle keeps the cost low: counts within a step go through
ReportItemAsync, which allocates nothing.

- scan: List, then Index (folder n of m, photo x of y as an adopted or
  reconciled folder is read) or Check, then FollowUps
- verify, thumbs, proxies, deep analysis: photo x of y of sequence n of m;
  light analysis: sequence n of m; a thumbnail/proxy checkpoint carries
  the frame count it saves
- convert: Verify (resume), Convert photo x of y, Replace; reorganize:
  step n of m with the title; import: the file being copied, photo x of y
- maintenance: the step key, step n of 5, then Check; duplicates, orphans
  and backup run with no count; cleanup names step n of m; empty trash:
  entry n of m
- render (local, workspace, render node): Analyse, Encode (frames of the
  last output, output n of m in a batch), Verify; sync, video copy,
  workspace copy/send/move: Upload/Download/CopyProxy/CopyOriginal/
  CopyVideo/Reorganize with their items and counts

The detail carries keys and names only, never localized text. The
existing Message strings stay for clients that still show them.

Refs #65

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:38:05 +01:00

354 lines
21 KiB
C#

using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Archiving.Jobs;
namespace Chronos.Data.Archiving;
/// <summary>
/// The dry run of emptying an archive's trash (owner review 2, R6; BRIEF §0.2 rule 8): the entries that would be erased,
/// with the files and bytes their folders hold now, and a fingerprint of exactly those entries. Erasing
/// (<see cref="JobKind.EmptyTrash"/>) refuses a plan whose fingerprint no longer matches the trash.
/// </summary>
/// <param name="Unknown">Names asked for that the trash does not hold.</param>
public sealed record TrashEmptyPlan(Guid ArchiveId, IReadOnlyList<TrashEntry> Entries, long Bytes, string Fingerprint, IReadOnlyList<string> Unknown)
{
public int Files => Entries.Sum(e => e.Files);
public int Photos => Entries.Sum(e => e.Frames);
}
/// <summary>What an emptying erased, and the entries it kept, each with why (<see cref="TrashKept"/>).</summary>
public sealed record TrashEmptyResult(int Erased, long Bytes, IReadOnlyList<TrashKept> Refused);
/// <summary>An entry an emptying kept in the trash: its title and why.</summary>
public sealed record TrashKept(string Title, TrashKeptReason Reason)
{
/// <summary>
/// "Kept in the trash, changed after the plan: Etna", a job log line in the current culture; where something settles the
/// reason, the line says what.
/// </summary>
public string LogLine => Loc.L(Reason switch
{
TrashKeptReason.Mismatch => "Archive.Log.TrashKeptMismatch",
TrashKeptReason.Unknown => "Archive.Log.TrashKeptUnknown",
TrashKeptReason.Busy => "Archive.Log.TrashKeptBusy",
TrashKeptReason.Unhashed => "Archive.Log.TrashKeptUnhashed",
TrashKeptReason.Unreadable => "Archive.Log.TrashKeptUnreadable",
TrashKeptReason.StaleIndex => "Archive.Log.TrashKeptStaleIndex",
_ => "Archive.Log.TrashKept",
}, Title);
}
/// <summary>
/// Why an emptying kept an entry in the trash. For an entry of replaced originals (owner review 2, R7), all but
/// <see cref="Changed"/> and <see cref="Busy"/> are about where the archive shows their conversions: they are erased only
/// while each conversion is there and matches, or once the archive itself shows it deleted, as the dry run said.
/// </summary>
public enum TrashKeptReason
{
/// <summary>The entry changed since the emptying was planned (restored, or deleted again, meanwhile), or is gone.</summary>
Changed,
/// <summary>
/// A conversion of its originals no longer matches its content, in its sequence or in the trash, or its frame holds other
/// content now (its file changed since the conversion).
/// </summary>
Mismatch,
/// <summary>
/// The archive does not show what became of a conversion of its originals: its sequence's sidecar holds none of it and no
/// tombstone says it was deleted (a sidecar rebuilt from the photos keeps only what one index knew), or the sequence is
/// nowhere in the archive and the trash has no record of erasing it. Nothing in the archive settles it: restoring the
/// entry keeps its photos.
/// </summary>
Unknown,
/// <summary>Its sequence is busy: another writer holds it, or a change to it is not settled yet.</summary>
Busy,
/// <summary>A frame of its sequence that may hold a conversion of its originals was never hashed: a verify of the sequence settles it.</summary>
Unhashed,
/// <summary>
/// A sidecar where its sequence may be cannot be read, or photos there have none: a scan of the archive rebuilds or adopts
/// it (what the new sidecar shows then decides).
/// </summary>
Unreadable,
/// <summary>
/// This index lists its sequence in a folder that no longer holds it, the archive holds it nowhere else and the trash has no
/// record of erasing it: a rebuild of the index drops that row (restoring the entry then brings its photos back as a new
/// sequence).
/// </summary>
StaleIndex,
}
/// <summary>The trash changed after the emptying was planned (an entry came, went or changed); nothing was erased.</summary>
public sealed class StaleTrashPlanException() : InvalidOperationException(Loc.L("Archive.Error.TrashChanged"));
public sealed partial class SequenceTrash
{
/// <summary>Folder inside the trash that entries move into before they are erased, so a listing never sees half an entry.</summary>
private const string ErasingFolder = ".erasing";
/// <summary>The lease that keeps a restore and an erasing of one entry apart.</summary>
internal static string EntryLease(string name) => "trash-" + name;
/// <summary>
/// The dry run of emptying the trash: <paramref name="names"/> of the entries to erase (null: every entry), each
/// 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 Task<TrashEmptyPlan> PlanEmptyAsync(Archive archive, IReadOnlyList<string>? names = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(archive);
var paths = new ArchivePaths(archive.RootPath);
return PlanEmptyAsync(archive, paths, names, new SidecarWalk(paths), cancellationToken);
}
/// <summary>The dry run, finding the sequences of replaced entries that moved through <paramref name="walk"/> (made at most once).</summary>
private async Task<TrashEmptyPlan> PlanEmptyAsync(Archive archive, ArchivePaths paths, IReadOnlyList<string>? names, SidecarWalk walk,
CancellationToken cancellationToken)
{
var listed = await ListAsync(archive, cancellationToken).ConfigureAwait(false);
var wanted = names?.ToHashSet(StringComparer.Ordinal);
var chosen = wanted is null ? listed : [.. listed.Where(e => wanted.Contains(e.Name))];
var measured = await Task.Run(() => chosen.Select(e =>
{
var (folder, _) = Location(paths, e);
var (files, bytes) = Directory.Exists(folder) ? Measure(folder, cancellationToken) : (0, 0L);
return e with { Files = files, Bytes = bytes };
}).ToList(), cancellationToken).ConfigureAwait(false);
// The sequences of replaced entries, found once for the whole plan.
var located = new Dictionary<Guid, Located>();
for (var i = 0; i < measured.Count; i++) measured[i] = await PlannedAsync(archive, paths, measured[i], located, walk, 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);
}
/// <summary>
/// Fingerprint of a set of entries: SHA-256 of each one's <see cref="EntryFingerprint"/> in name order. The same
/// entries with the same files on disk give the same fingerprint whatever order they were listed in.
/// </summary>
public static string Fingerprint(IEnumerable<TrashEntry> entries)
{
ArgumentNullException.ThrowIfNull(entries);
var text = new StringBuilder();
foreach (var entry in entries.OrderBy(e => e.Name, StringComparer.Ordinal)) text.Append(EntryFingerprint(entry)).Append('\n');
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, 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);
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>
/// Erases the entries of <paramref name="parameters"/> from <paramref name="start"/> on, one at a time under its lease,
/// each moved aside whole and then deleted (a listing never shows half an entry). From the start, the trash must still
/// 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 weighed under its sequence's lease as well, against the archive as it is then
/// (<see cref="Survey"/>): it is erased only while every conversion of its originals still matches its SHA-256 where the
/// archive shows it (re-hashed now: in the sequence, or a copy the trash holds when its conversion was deleted, as the
/// dry run said); otherwise, or when the archive cannot tell, it is kept, with why. Leftovers of an interrupted erase are
/// deleted first; the sequences of replaced entries that moved are looked up in one walk of the archive for the whole run
/// (<see cref="SidecarWalk"/>), and the records of erased sequences no replaced entry needs any more go at the end
/// (<see cref="SweepErasures"/>).
/// </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>
internal Task<TrashEmptyResult> EmptyAsync(Archive archive, EmptyTrashParameters parameters, int start, Func<int, int, ValueTask> progress,
CancellationToken cancellationToken) =>
EmptyAsync(archive, parameters, start, progress, null, cancellationToken);
/// <inheritdoc cref="EmptyAsync(Archive, EmptyTrashParameters, int, Func{int, int, ValueTask}, CancellationToken)"/>
/// <param name="erasing">
/// Told before each entry with the entries done, their number and the entry's title (null when the trash no longer holds it).
/// </param>
internal async Task<TrashEmptyResult> EmptyAsync(Archive archive, EmptyTrashParameters parameters, int start, Func<int, int, ValueTask> progress,
Func<int, int, string?, ValueTask>? erasing, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(archive);
ArgumentNullException.ThrowIfNull(parameters);
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
SweepErasing(paths);
var items = parameters.Entries;
var walk = new SidecarWalk(paths);
var current = await PlanEmptyAsync(archive, paths, [.. items.Skip(start).Select(i => i.Name)], walk, cancellationToken).ConfigureAwait(false);
if (start == 0 && (current.Fingerprint != parameters.Fingerprint || current.Unknown.Count > 0)) throw new StaleTrashPlanException();
var refused = new List<TrashKept>();
int erased = 0;
long bytes = 0;
for (var i = start; i < items.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
var item = items[i];
var found = current.Entries.FirstOrDefault(e => e.Name == item.Name);
if (erasing is not null) await erasing(i, items.Count, found?.Title).ConfigureAwait(false);
if (found is { } entry)
{
if (EntryFingerprint(entry) != item.Fingerprint)
{
refused.Add(new TrashKept(entry.Title, TrashKeptReason.Changed));
Log.Warning("archive", $"Trash entry {entry.Name} changed since the emptying was planned; it is kept");
}
else if (await EraseAsync(archive, paths, entry, item.Fingerprint, walk, cancellationToken).ConfigureAwait(false) is { } reason)
{
refused.Add(new TrashKept(entry.Title, reason));
}
else
{
erased++;
bytes += entry.Bytes;
}
}
await progress(i + 1, items.Count).ConfigureAwait(false);
}
SweepErasures(archive, paths, cancellationToken);
return new TrashEmptyResult(erased, bytes, refused);
}
/// <summary>
/// Erases one entry under its lease, once its record read and its folder measured again under it still give the
/// planned <paramref name="fingerprint"/> (another host sharing the archive may have restored the entry and deleted the
/// same sequence again since). A replaced entry is weighed under its sequence's lease too, so no writer of the sequence
/// moves its conversions meanwhile, and only once what a writer left unsettled in the sequence is settled (an undo whose
/// completion waited for this entry's lease takes photos out of it): the archive must tell where each conversion is (as
/// the dry run said, which the fingerprint holds), and each must still match. A deleted sequence that a replaced entry
/// still in the trash came from leaves a record of its erasing (<see cref="RecordErasureAsync"/>). Returns null once erased,
/// else why the entry is kept (logged).
/// </summary>
private async Task<TrashKeptReason?> EraseAsync(Archive archive, ArchivePaths paths, TrashEntry entry, string fingerprint, SidecarWalk walk,
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 TrashKeptReason.Changed;
IAsyncDisposable? sequence = null;
if (entry.Kind == TrashKind.Replaced)
{
try
{
sequence = await _writer.LockAsync(paths, entry.SequenceId, cancellationToken).ConfigureAwait(false);
}
catch (LeaseUnavailableException ex)
{
Log.Warning("archive", $"Trash entry {entry.Name} is kept: its sequence is busy", ex);
return TrashKeptReason.Busy;
}
}
await using (sequence)
{
// Settled before the entry is read again, so what is read is what an erase takes.
var located = sequence is null ? null : await LocateAsync(archive, paths, entry, walk, EntryLease(entry.Name), cancellationToken).ConfigureAwait(false);
var (now, survey) = Reread(archive, paths, entry, located, cancellationToken);
if (survey?.Kept is { } kept)
{
Log.Warning("archive", $"Trash entry {entry.Name} is kept ({kept}): the archive does not show the conversions of its originals whole");
return kept;
}
if (now is null || EntryFingerprint(now) != fingerprint)
{
Log.Warning("archive", $"Trash entry {entry.Name} changed since the emptying was planned; it is kept");
return TrashKeptReason.Changed;
}
if (survey is not null && !await MatchAsync(survey, cancellationToken).ConfigureAwait(false))
{
Log.Warning("archive", $"Trash entry {entry.Name} is kept: a conversion of its originals no longer matches");
return TrashKeptReason.Mismatch;
}
var aside = Path.Combine(TrashDirectory(paths), ErasingFolder, Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(Path.GetDirectoryName(aside)!);
// Before the folder goes: once it has, the archive alone tells a replaced entry of that sequence what became of it.
if (entry.Kind == TrashKind.Sequence) await RecordErasureAsync(archive, paths, now, walk, cancellationToken).ConfigureAwait(false);
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"
+ (now.ConversionDeleted ? "; the conversion of its originals had been deleted" : string.Empty));
return null;
}
}
}
/// <summary>
/// An entry as the trash lists it and an erase plans it, from its record and folder as they are now, and a replaced
/// entry's survey against where its sequence was found under its lease (<paramref name="located"/>, which says whether the
/// conversion of one of its photos was deleted, <see cref="TrashEntry.ConversionDeleted"/>); a null entry when its record
/// cannot be read or its folder is gone.
/// </summary>
private static (TrashEntry? Entry, ConversionSurvey? Survey) Reread(Archive archive, ArchivePaths paths, TrashEntry entry, Located? located,
CancellationToken cancellationToken)
{
var (folder, recordPath) = Location(paths, entry);
var now = FrameTrash.IsPhotoEntry(entry.Name) ? FrameTrash.ReadListed(paths, entry.ArchiveId, entry.Name)
: Videos.VideoTrashNames.IsEntryName(entry.Name) ? Videos.VideoTrash.ReadListed(paths, entry.ArchiveId, entry.Name)
: ReadRecord(recordPath) is { } record ? Entry(entry.ArchiveId, Path.GetFileName(entry.Name), record) : null;
if (now is null || !Directory.Exists(folder)) return (null, null);
var (files, bytes) = Measure(folder, cancellationToken);
now = now with { Files = files, Bytes = bytes };
if (located is null) return (now, null);
if (FrameTrash.ReadEntry(paths, entry.Name) is not { } photos) return (null, null);
var survey = Survey(archive, paths, entry.Name, photos, located, cancellationToken);
return (survey.Deleted ? now with { ConversionDeleted = true } : now, survey);
}
/// <summary>
/// <paramref name="entry"/> as an emptying plans it: a replaced entry is <see cref="TrashEntry.ConversionDeleted"/> when the
/// archive shows the conversion of one of its photos deleted (<see cref="Survey"/>), so the dry run says so. Its sequence
/// is found once per plan (<paramref name="located"/>, through <paramref name="walk"/> when it moved). Reads sidecars and
/// records; hashes nothing.
/// </summary>
private async Task<TrashEntry> PlannedAsync(Archive archive, ArchivePaths paths, TrashEntry entry, Dictionary<Guid, Located> located, SidecarWalk walk,
CancellationToken cancellationToken)
{
if (entry.Kind != TrashKind.Replaced || FrameTrash.ReadEntry(paths, entry.Name) is not { } record) return entry;
if (!located.TryGetValue(entry.SequenceId, out var where))
located[entry.SequenceId] = where = await LocateAsync(archive, paths, entry, walk, null, cancellationToken).ConfigureAwait(false);
return Survey(archive, paths, entry.Name, record, where, cancellationToken).Deleted ? entry with { ConversionDeleted = true } : entry;
}
/// <summary>The folder and record of an entry of any kind (a sequence, photos, or a video: owner review 1, R9).</summary>
private static (string Folder, string Record) Location(ArchivePaths paths, TrashEntry entry)
{
if (FrameTrash.IsPhotoEntry(entry.Name)) return FrameTrash.Location(paths, entry.Name);
if (Videos.VideoTrashNames.IsEntryName(entry.Name)) return Videos.VideoTrash.Location(paths, entry.Name);
var folder = Path.Combine(TrashDirectory(paths), Path.GetFileName(entry.Name));
return (folder, folder + RecordExtension);
}
/// <summary>Deletes what an interrupted erase left aside: those entries were confirmed and had left the listing already.</summary>
private static void SweepErasing(ArchivePaths paths)
{
var erasing = Path.Combine(TrashDirectory(paths), ErasingFolder);
if (!Directory.Exists(erasing)) return;
foreach (var leftover in Directory.EnumerateDirectories(erasing)) Erase(leftover);
}
/// <summary>Deletes a folder and everything in it, read-only files included; one that is gone already is fine.</summary>
internal static void Erase(string folder)
{
if (!Directory.Exists(folder)) return;
foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", new EnumerationOptions { RecurseSubdirectories = true, AttributesToSkip = 0 }))
{
if ((file.Attributes & FileAttributes.ReadOnly) != 0) file.Attributes &= ~FileAttributes.ReadOnly;
}
Directory.Delete(folder, recursive: true);
}
}