feat: owner review 2 phase 3: Library on the web panel, photo trash and web upload (#11)
CI / Build and test (push) Successful in 7m25s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 10s
CI / PostgreSQL 16 integration (push) Successful in 5m20s
CI / PostgreSQL 17 integration (push) Successful in 5m22s
CI / Docker image (push) Successful in 50s
Release / Build, test and publish (push) Successful in 12m1s
Release / Server image (push) Successful in 1m26s
CI / Build and test (push) Successful in 7m25s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 10s
CI / PostgreSQL 16 integration (push) Successful in 5m20s
CI / PostgreSQL 17 integration (push) Successful in 5m22s
CI / Docker image (push) Successful in 50s
Release / Build, test and publish (push) Successful in 12m1s
Release / Server image (push) Successful in 1m26s
- Web panel Library: browse, view, delete sequences and photos, mass operations (analyse, proxies, thumbnails, verify, retag, delete, CSV). It never edits the video. - Photo trash with tombstones (migration 0008): crash-safe delete and restore, hash-checked restore with reasons, and emptying only by an explicit fingerprinted job. Sync and uploads keep deleted photos deleted; an explicit "Upload again" brings one back. - Upload from the web panel: in-house SHA-256 in a worker with a fail-closed self-test, capture time from EXIF, chunked, resumable; no folders. - Desktop trash dialog with photo entries and Empty. - Admin files are revalidated (no-cache + ETag). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #11.
This commit is contained in:
1 parent
af9eeaab9b
commit
9aa818ed47
283 files changed
+24922
-293
No files matched your search
@@ -0,0 +1,227 @@
|
||||
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 (a replacement that no longer matches, an entry changed since the plan).</summary>
|
||||
public sealed record TrashEmptyResult(int Erased, long Bytes, IReadOnlyList<string> Refused);
|
||||
|
||||
/// <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, 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)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
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);
|
||||
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, and when it was deleted.</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}");
|
||||
}
|
||||
|
||||
/// <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 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.
|
||||
/// </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 async Task<TrashEmptyResult> EmptyAsync(Archive archive, EmptyTrashParameters parameters, int start, Func<int, int, ValueTask> progress,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
ArgumentNullException.ThrowIfNull(parameters);
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
SweepErasing(paths);
|
||||
var items = parameters.Entries;
|
||||
var current = await PlanEmptyAsync(archive, [.. items.Skip(start).Select(i => i.Name)], cancellationToken).ConfigureAwait(false);
|
||||
if (start == 0 && (current.Fingerprint != parameters.Fingerprint || current.Unknown.Count > 0)) throw new StaleTrashPlanException();
|
||||
var refused = new List<string>();
|
||||
int erased = 0;
|
||||
long bytes = 0;
|
||||
for (var i = start; i < items.Count; i++)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var item = items[i];
|
||||
if (current.Entries.FirstOrDefault(e => e.Name == item.Name) is { } entry)
|
||||
{
|
||||
if (EntryFingerprint(entry) != item.Fingerprint)
|
||||
{
|
||||
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))
|
||||
{
|
||||
erased++;
|
||||
bytes += entry.Bytes;
|
||||
}
|
||||
else
|
||||
{
|
||||
refused.Add(entry.Title);
|
||||
}
|
||||
}
|
||||
await progress(i + 1, items.Count).ConfigureAwait(false);
|
||||
}
|
||||
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); 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)
|
||||
{
|
||||
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)
|
||||
{
|
||||
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))
|
||||
{
|
||||
Log.Warning("archive", $"Trash entry {entry.Name} is kept: a replacement of its originals no longer matches");
|
||||
return false;
|
||||
}
|
||||
var aside = Path.Combine(TrashDirectory(paths), ErasingFolder, Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(aside)!);
|
||||
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");
|
||||
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).
|
||||
/// </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)
|
||||
{
|
||||
var (folder, recordPath) = Location(paths, entry);
|
||||
var now = FrameTrash.IsPhotoEntry(entry.Name)
|
||||
? FrameTrash.ReadListed(paths, entry.ArchiveId, entry.Name)
|
||||
: 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 };
|
||||
}
|
||||
|
||||
/// <summary>The folder and record of an entry of either kind.</summary>
|
||||
private static (string Folder, string Record) Location(ArchivePaths paths, TrashEntry entry)
|
||||
{
|
||||
if (FrameTrash.IsPhotoEntry(entry.Name)) return FrameTrash.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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user