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; /// /// 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 /// () refuses a plan whose fingerprint no longer matches the trash. /// /// Names asked for that the trash does not hold. public sealed record TrashEmptyPlan(Guid ArchiveId, IReadOnlyList Entries, long Bytes, string Fingerprint, IReadOnlyList Unknown) { public int Files => Entries.Sum(e => e.Files); public int Photos => Entries.Sum(e => e.Frames); } /// What an emptying erased, and the entries it kept, each with why (). public sealed record TrashEmptyResult(int Erased, long Bytes, IReadOnlyList Refused); /// An entry an emptying kept in the trash: its title and why. public sealed record TrashKept(string Title, TrashKeptReason Reason) { /// /// "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. /// 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); } /// /// Why an emptying kept an entry in the trash. For an entry of replaced originals (owner review 2, R7), all but /// and 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. /// public enum TrashKeptReason { /// The entry changed since the emptying was planned (restored, or deleted again, meanwhile), or is gone. Changed, /// /// 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). /// Mismatch, /// /// 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. /// Unknown, /// Its sequence is busy: another writer holds it, or a change to it is not settled yet. Busy, /// A frame of its sequence that may hold a conversion of its originals was never hashed: a verify of the sequence settles it. Unhashed, /// /// 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). /// Unreadable, /// /// 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). /// StaleIndex, } /// The trash changed after the emptying was planned (an entry came, went or changed); nothing was erased. public sealed class StaleTrashPlanException() : InvalidOperationException(Loc.L("Archive.Error.TrashChanged")); public sealed partial class SequenceTrash { /// Folder inside the trash that entries move into before they are erased, so a listing never sees half an entry. private const string ErasingFolder = ".erasing"; /// The lease that keeps a restore and an erasing of one entry apart. internal static string EntryLease(string name) => "trash-" + name; /// /// The dry run of emptying the trash: of the entries to erase (null: every entry), each /// measured on disk, each replaced entry whose conversion was deleted since said so (), /// and the plan's fingerprint (). Reads only. /// public Task PlanEmptyAsync(Archive archive, IReadOnlyList? names = null, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(archive); var paths = new ArchivePaths(archive.RootPath); return PlanEmptyAsync(archive, paths, names, new SidecarWalk(paths), cancellationToken); } /// The dry run, finding the sequences of replaced entries that moved through (made at most once). private async Task PlanEmptyAsync(Archive archive, ArchivePaths paths, IReadOnlyList? 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(); 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); } /// /// Fingerprint of a set of entries: SHA-256 of each one's in name order. The same /// entries with the same files on disk give the same fingerprint whatever order they were listed in. /// public static string Fingerprint(IEnumerable 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()))); } /// /// 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 (), which the dry run says. /// 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; } /// /// Erases the entries of from 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 (), 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 /// entry is weighed under its sequence's lease as well, against the archive as it is then /// (): 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 /// (), and the records of erased sequences no replaced entry needs any more go at the end /// (). /// /// Entries done so far (the resume point) and their number. /// The trash no longer holds exactly the planned entries; nothing was erased. internal Task EmptyAsync(Archive archive, EmptyTrashParameters parameters, int start, Func progress, CancellationToken cancellationToken) => EmptyAsync(archive, parameters, start, progress, null, cancellationToken); /// /// /// Told before each entry with the entries done, their number and the entry's title (null when the trash no longer holds it). /// internal async Task EmptyAsync(Archive archive, EmptyTrashParameters parameters, int start, Func progress, Func? 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(); 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); } /// /// Erases one entry under its lease, once its record read and its folder measured again under it still give the /// planned (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 (). Returns null once erased, /// else why the entry is kept (logged). /// private async Task 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; } } } /// /// 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 (, which says whether the /// conversion of one of its photos was deleted, ); a null entry when its record /// cannot be read or its folder is gone. /// 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); } /// /// as an emptying plans it: a replaced entry is when the /// archive shows the conversion of one of its photos deleted (), so the dry run says so. Its sequence /// is found once per plan (, through when it moved). Reads sidecars and /// records; hashes nothing. /// private async Task PlannedAsync(Archive archive, ArchivePaths paths, TrashEntry entry, Dictionary 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; } /// The folder and record of an entry of any kind (a sequence, photos, or a video: owner review 1, R9). 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); } /// Deletes what an interrupted erase left aside: those entries were confirmed and had left the listing already. 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); } /// Deletes a folder and everything in it, read-only files included; one that is gone already is fine. 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); } }