using System.Text.Json;
using System.Text.Json.Serialization;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.IO;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Archiving.Jobs;
namespace Chronos.Data.Archiving;
/// Why a sequence cannot go to the trash; nothing of it is touched.
public enum DeleteBlock
{
/// The archive is offline or read-only.
Offline,
/// The photos lie in the archive root itself (a folder adopted in place): the root never moves.
ArchiveRoot,
/// Other sequences live in folders below this one; moving it would take them along.
ContainsSequences,
/// A running or paused job works on the sequence, or on its whole archive (a scan, a rebuild, an import, a verify, maintenance).
Busy,
/// The folder's sidecar names another sequence: the index is out of date (a scan fixes it).
ForeignSidecar,
/// The index names a folder that is not on disk: there is nothing to keep in the trash, so the Orphans check removes the row.
FolderMissing,
}
/// One sequence of a delete plan: its folder moves to and its index rows go.
/// Archive-relative folder the sequence folder moves to; null for a sequence that has no folder yet (created on the server, no photo received), of which only the rows go.
/// Files under the folder (originals, proxies, exports, sidecars).
/// Their size on disk.
public sealed record DeleteStep(Sequence Sequence, string? TrashFolder, int Files, long Bytes);
public sealed record BlockedDelete(Sequence Sequence, DeleteBlock Reason);
/// The dry run of moving sequences to their archive's trash (BRIEF §0.2 rule 8): what moves, and what cannot.
public sealed record DeletePlan(IReadOnlyList Steps, IReadOnlyList Blocked)
{
public int Frames => Steps.Sum(s => s.Sequence.FrameCount);
public int Files => Steps.Sum(s => s.Files);
public long Bytes => Steps.Sum(s => s.Bytes);
public int Renders => Steps.Sum(s => s.Sequence.RenderedCount);
}
/// A deleted sequence kept in an archive's trash, as lists it.
/// Folder name inside the trash; pass it to .
/// Archive-relative folder the sequence came from (and returns to when it is free).
public sealed record TrashEntry(Guid ArchiveId, string Name, Guid SequenceId, string Title, string Folder, int Frames, int Files, long Bytes,
DateTimeOffset DeletedAt, string? DeletedBy);
/// The plan no longer matches the index or the jobs (a sequence moved, vanished or got busy since it was made); nothing was deleted.
public sealed class StaleDeletePlanException(Guid sequenceId) : InvalidOperationException(Loc.L("Archive.Error.StalePlan"))
{
public Guid SequenceId { get; } = sequenceId;
}
/// A trash entry cannot come back: the index already holds its sequence (restored before, or scanned again); nothing moved.
public sealed class SequenceInLibraryException(Guid sequenceId, string title) : InvalidOperationException(Loc.L("Archive.Error.InLibrary", title))
{
public Guid SequenceId { get; } = sequenceId;
}
///
/// Deleting sequences without erasing anything (BRIEF §0.2 rule 8, §12.2, §12.5): is the dry
/// run; moves each sequence folder whole — originals, proxies, exports and its sidecars — into
/// .chronos/trash/<id> of its archive under the sequence's leases, next to a record of its index row and
/// renders, then removes the index rows. moves a folder back and indexes it again from its
/// sidecar with the same ids. The trash is a hidden folder of the archive, so scans never index it. Once a folder has
/// moved, its index step runs to the end whatever the caller cancels; when that step fails, the folder moves back, so
/// the trash and the index never disagree.
///
public sealed class SequenceTrash
{
/// Folder of the trash inside the archive's .chronos.
public const string FolderName = "trash";
private const string RecordExtension = ".json";
private const int JobPage = 200;
/// Bytes of a sidecar read to find its id (written second, after the schema version).
private const int SidecarHead = 4096;
private readonly ChronosDatabase _db;
private readonly SequenceWriter _writer;
private readonly ArchiveIndexer _indexer;
/// A trash of its own (hosts without an ); lease files keep it in step with other writers.
public SequenceTrash(ChronosDatabase db, ArchiveServiceOptions? options = null)
: this(db, new SequenceWriter(options ?? new ArchiveServiceOptions()), null)
{
}
internal SequenceTrash(ChronosDatabase db, SequenceWriter writer, ArchiveIndexer? indexer)
{
_db = db;
_writer = writer;
_indexer = indexer ?? new ArchiveIndexer(db, writer);
}
/// The trash folder of an archive.
public static string TrashDirectory(ArchivePaths archive) => Path.Combine(archive.MetaDirectory, FolderName);
/// The dry run: for each sequence, where its folder goes and how many files and bytes it holds, or why it cannot go.
/// Sequences checked so far.
/// A sequence is not in the index.
public async Task PlanAsync(IReadOnlyList sequenceIds, IProgress? progress = null, CancellationToken cancellationToken = default)
{
var busy = await BusyAsync(cancellationToken).ConfigureAwait(false);
var archives = new Dictionary();
var steps = new List();
var blocked = new List();
var claimed = new HashSet(StringComparer.OrdinalIgnoreCase);
var checkedCount = 0;
foreach (var id in sequenceIds.Distinct())
{
cancellationToken.ThrowIfCancellationRequested();
var sequence = await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false)
?? throw new ArgumentException($"Unknown sequence {id}.", nameof(sequenceIds));
var context = await ContextAsync(archives, sequence.ArchiveId, cancellationToken).ConfigureAwait(false)
?? throw new ArgumentException($"Unknown archive {sequence.ArchiveId}.", nameof(sequenceIds));
if (Block(sequence, context, busy) is { } reason)
{
blocked.Add(new BlockedDelete(sequence, reason));
}
else if (sequence.Folder.Length == 0)
{
steps.Add(new DeleteStep(sequence, null, 0, 0));
}
else
{
var folder = context.Paths.Sequence(sequence.Folder).Folder;
var (files, bytes) = await Task.Run(() => Measure(folder, cancellationToken), cancellationToken).ConfigureAwait(false);
var name = EntryName(context.Paths, sequence.Id, claimed);
claimed.Add(name);
steps.Add(new DeleteStep(sequence, context.Paths.ToRelative(Path.Combine(TrashDirectory(context.Paths), name)), files, bytes));
}
progress?.Report(++checkedCount);
}
return new DeletePlan(steps, blocked);
}
///
/// Moves the planned sequences to the trash, one at a time, each completely (folder, then index rows) before the
/// next; cancelling stops between two sequences. Returns the trash entries made.
///
/// Who asked (user name or client), kept in the trash record.
/// Sequences moved so far.
/// A sequence moved, vanished or got busy since the plan; nothing was deleted.
/// An archive is offline; sequences before it are in the trash.
public async Task> DeleteAsync(DeletePlan plan, string? deletedBy = null, IProgress? progress = null,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(plan);
await RevalidateAsync(plan, cancellationToken).ConfigureAwait(false);
var entries = new List(plan.Steps.Count);
for (var i = 0; i < plan.Steps.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
if (await DeleteOneAsync(plan.Steps[i], deletedBy, cancellationToken).ConfigureAwait(false) is { } entry) entries.Add(entry);
progress?.Report(i + 1);
}
return entries;
}
/// The sequences in an archive's trash, newest first; records whose folder is gone are left out.
public async Task> ListAsync(Archive archive, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(archive);
var trash = TrashDirectory(new ArchivePaths(archive.RootPath));
return await Task.Run(() =>
{
if (!Directory.Exists(trash)) return (IReadOnlyList)[];
var entries = new List();
foreach (var path in Directory.EnumerateFiles(trash, "*" + RecordExtension))
{
cancellationToken.ThrowIfCancellationRequested();
var name = Path.GetFileNameWithoutExtension(path);
if (!Directory.Exists(Path.Combine(trash, name)) || ReadRecord(path) is not { } record) continue;
entries.Add(Entry(archive.Id, name, record));
}
return entries.OrderByDescending(e => e.DeletedAt).ToList();
}, cancellationToken).ConfigureAwait(false);
}
///
/// Moves a sequence back from the trash into its folder (or, when that is taken, a free one next to it) and indexes
/// it again from its sidecar with its ids, settings and renders. A folder without a sidecar is adopted under the
/// sequence's id, as a scan would adopt it, with the title, tags, rating and notes the record kept. Returns the
/// restored row. When it cannot be indexed, the folder goes back into the trash with its record.
///
/// The index already holds that sequence.
/// The entry is not in the trash.
public async Task RestoreAsync(Archive archive, string name, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(archive);
ArgumentException.ThrowIfNullOrWhiteSpace(name);
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
var trash = TrashDirectory(paths);
var source = Path.Combine(trash, Path.GetFileName(name));
var recordPath = source + RecordExtension;
if (!Directory.Exists(source) || ReadRecord(recordPath) is not { } record)
throw new DirectoryNotFoundException($"{name} is not in the trash of {archive.Name}.");
var id = record.Sequence.Id;
if (await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false) is not null)
throw new SequenceInLibraryException(id, record.Sequence.DisplayTitle);
var locations = (await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false)).Select(l => l.Folder)
.ToHashSet(StringComparer.OrdinalIgnoreCase);
var folder = FreeFolder(paths, record.Sequence.Folder, locations);
var sequence = paths.Sequence(folder);
await using (await _writer.LockAsync(paths, id, cancellationToken).ConfigureAwait(false))
{
cancellationToken.ThrowIfCancellationRequested();
Directory.CreateDirectory(Path.GetDirectoryName(sequence.Folder)!);
Directory.Move(source, sequence.Folder);
try
{
var manifest = File.Exists(sequence.ManifestPath) ? SequenceWriter.ReadLocked(sequence, id) : Adopt(sequence, record.Sequence, cancellationToken);
// The index step runs to the end once it starts: a cancel cannot leave half the rows written.
await IndexAsync(archive, sequence, manifest, record, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
Log.Warning("archive", $"{record.Sequence.DisplayTitle} could not be restored; its folder goes back into the trash", ex);
MoveBack(sequence.Folder, source);
throw;
}
Log.Info("archive", $"{record.Sequence.DisplayTitle} restored from the trash to {folder}");
await RecordStampsAsync(archive, sequence, id).ConfigureAwait(false);
File.Delete(recordPath);
}
return await _db.Sequences.GetAsync(id, CancellationToken.None).ConfigureAwait(false)
?? throw new InvalidOperationException($"{record.Sequence.DisplayTitle} was restored but is not in the index.");
}
///
/// A sidecar for a restored folder that lost its own, built as a scan adopts a folder: its frames get new ids, the
/// sequence keeps its id, and the title, tags, rating and notes of the record go into it so sidecar and index agree.
///
private SequenceManifest Adopt(SequencePaths sequence, Sequence kept, CancellationToken cancellationToken)
{
var built = SequenceAdopter.Build(kept.Id, sequence, _writer.Options.Owner, cancellationToken);
var manifest = built with
{
Title = kept.Title,
Tags = kept.Tags,
Rating = kept.Rating,
Notes = kept.Notes,
Versions = built.Versions with { Settings = System.Math.Max(built.Versions.Settings, kept.SettingsVersion) },
};
Directory.CreateDirectory(sequence.MetaDirectory);
ManifestStore.WriteSequence(sequence.ManifestPath, manifest);
return manifest;
}
/// The restored sequence's rows: the sidecar's frames, the record's row and renders; a hero frame the sidecar no longer has is dropped.
private async Task IndexAsync(Archive archive, SequencePaths sequence, SequenceManifest manifest, TrashRecord record, CancellationToken cancellationToken)
{
var deleted = record.Sequence;
var hero = deleted.HeroFrameId is { } frame && manifest.Frames.Any(f => f.Id == frame) ? frame : (Guid?)null;
var kept = deleted with { ArchiveId = archive.Id, Folder = sequence.RelativeFolder, RenderedCount = 0, HeroFrameId = hero };
await using var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false);
await tx.Sequences.UpsertAsync(SequenceMapping.ToSequence(manifest, archive.Id, sequence, kept), cancellationToken).ConfigureAwait(false);
await tx.Frames.SyncSequenceAsync(deleted.Id, SequenceMapping.ToFrames(manifest, sequence), cancellationToken).ConfigureAwait(false);
foreach (var key in manifest.SessionKeys) await tx.Sequences.MapSessionKeyAsync(archive.Id, key, deleted.Id, cancellationToken).ConfigureAwait(false);
foreach (var render in record.Renders)
{
var moved = render with { OutputPath = Rebase(render.OutputPath, deleted.Folder, sequence.RelativeFolder) };
await tx.Renders.InsertAsync(moved, cancellationToken).ConfigureAwait(false);
}
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// The next incremental scan skips the restored folder; when the stamps cannot be written it only reads the folder again.
private async Task RecordStampsAsync(Archive archive, SequencePaths sequence, Guid id)
{
try
{
await _indexer.RecordStampsAsync(archive, sequence, id, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
{
Log.Warning("archive", $"Scan stamps of {sequence.RelativeFolder} not recorded; the next scan reads it again", ex);
}
}
/// Checks the plan again just before anything moves, without measuring the folders again; any change refuses it whole.
private async Task RevalidateAsync(DeletePlan plan, CancellationToken cancellationToken)
{
var busy = await BusyAsync(cancellationToken).ConfigureAwait(false);
var archives = new Dictionary();
foreach (var step in plan.Steps)
{
cancellationToken.ThrowIfCancellationRequested();
var row = await _db.Sequences.GetAsync(step.Sequence.Id, cancellationToken).ConfigureAwait(false);
if (row is null || row.ArchiveId != step.Sequence.ArchiveId || row.Folder != step.Sequence.Folder) throw new StaleDeletePlanException(step.Sequence.Id);
if (await ContextAsync(archives, row.ArchiveId, cancellationToken).ConfigureAwait(false) is not { } context) throw new StaleDeletePlanException(row.Id);
switch (Block(row, context, busy))
{
case DeleteBlock.Offline:
throw new ArchiveOfflineException(context.Paths.Root, context.Availability);
case not null:
throw new StaleDeletePlanException(row.Id);
}
}
}
private async Task DeleteOneAsync(DeleteStep step, string? deletedBy, CancellationToken cancellationToken)
{
var sequence = step.Sequence;
var archive = await _db.Archives.GetAsync(sequence.ArchiveId, cancellationToken).ConfigureAwait(false)
?? throw new StaleDeletePlanException(sequence.Id);
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
await using (await _writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, $"thumbs-{sequence.Id:N}", _writer.Options.Owner, _writer.Options.LeaseWait,
_writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
{
var row = await _db.Sequences.GetAsync(sequence.Id, cancellationToken).ConfigureAwait(false);
if (row is null || row.Folder != sequence.Folder) throw new StaleDeletePlanException(sequence.Id);
if (step.TrashFolder is null)
{
await RemoveRowsAsync(archive.Id, row, cancellationToken).ConfigureAwait(false);
Log.Info("archive", $"{row.DisplayTitle} removed from the index (no folder yet)");
return null;
}
var folder = paths.Sequence(sequence.Folder);
if (!Directory.Exists(folder.Folder) || (File.Exists(folder.ManifestPath) && SidecarId(folder.ManifestPath) != sequence.Id))
throw new StaleDeletePlanException(sequence.Id);
var trash = TrashDirectory(paths);
Directory.CreateDirectory(trash);
var name = EntryName(paths, sequence.Id, new HashSet());
var target = Path.Combine(trash, name);
var record = new TrashRecord(row, await _db.Renders.ListBySequenceAsync(sequence.Id, cancellationToken).ConfigureAwait(false), step.Files,
step.Bytes, DateTimeOffset.UtcNow, deletedBy);
cancellationToken.ThrowIfCancellationRequested();
// The record first: a crash before the move leaves a record without a folder, which the listing ignores.
var recordPath = target + RecordExtension;
AtomicFile.WriteAllText(recordPath, JsonSerializer.Serialize(record, TrashJson.Default.TrashRecord));
try
{
Directory.Move(folder.Folder, target);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// A file of the folder is open elsewhere: nothing moved, so the record goes and the rows stay.
File.Delete(recordPath);
throw;
}
try
{
// The folder has moved: its rows go too, to the end, whatever the caller cancels meanwhile.
await RemoveRowsAsync(archive.Id, row, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
Log.Warning("archive", $"{row.DisplayTitle} could not leave the index; its folder goes back", ex);
if (MoveBack(target, folder.Folder)) File.Delete(recordPath);
throw;
}
Log.Info("archive", $"{row.DisplayTitle} moved to the trash: {row.Folder} → {name} ({step.Files} files, {step.Bytes} bytes)");
return Entry(archive.Id, name, record);
}
}
private async Task RemoveRowsAsync(Guid archiveId, Sequence sequence, CancellationToken cancellationToken)
{
await using var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false);
await tx.Sequences.DeleteAsync(sequence.Id, cancellationToken).ConfigureAwait(false);
// A sequence without a folder has no scan state; the root's belongs to a folder adopted in place.
if (sequence.Folder.Length > 0) await tx.Archives.DeleteFolderStateAsync(archiveId, sequence.Folder, cancellationToken).ConfigureAwait(false);
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// Undoes a folder move after a failed index step; false (logged) when the folder cannot move back either.
private static bool MoveBack(string from, string to)
{
try
{
Directory.Move(from, to);
return true;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Error("archive", $"{from} could not move back to {to}; it stays where it is", ex);
return false;
}
}
private async Task ContextAsync(Dictionary known, Guid archiveId, CancellationToken cancellationToken)
{
if (known.TryGetValue(archiveId, out var context)) return context;
if (await _db.Archives.GetAsync(archiveId, cancellationToken).ConfigureAwait(false) is { } archive)
{
var paths = new ArchivePaths(archive.RootPath);
context = new ArchiveContext(paths, ArchiveVolume.Probe(paths),
await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false));
}
known[archiveId] = context;
return context;
}
private static DeleteBlock? Block(Sequence sequence, ArchiveContext context, IReadOnlySet busy)
{
if (context.Availability != ArchiveAvailability.Online) return DeleteBlock.Offline;
if (busy.Contains(sequence.Id) || busy.Contains(sequence.ArchiveId)) return DeleteBlock.Busy;
// An empty folder is the archive root of a folder adopted in place, or a server sequence still waiting for its first frame.
if (sequence.Folder.Length == 0) return sequence.FrameCount > 0 ? DeleteBlock.ArchiveRoot : null;
var folder = context.Paths.Sequence(sequence.Folder);
if (!Directory.Exists(folder.Folder)) return DeleteBlock.FolderMissing;
var prefix = sequence.Folder + "/";
if (context.Locations.Any(l => l.Id != sequence.Id && l.Folder.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))) return DeleteBlock.ContainsSequences;
return File.Exists(folder.ManifestPath) && SidecarId(folder.ManifestPath) != sequence.Id ? DeleteBlock.ForeignSidecar : null;
}
///
/// What running and paused jobs hold: the sequences they target (renders, analyses, proxies, transfers) and the
/// archives of archive-wide ones (scan, rebuild, import, maintenance, a verify of everything). An import's folders
/// are known only to its plan, so it holds its whole archive; a verify of named sequences holds only those.
///
private async Task> BusyAsync(CancellationToken cancellationToken)
{
var busy = new HashSet();
foreach (var state in new[] { JobState.Running, JobState.Paused })
{
string? cursor = null;
do
{
var page = await _db.Jobs.ListAsync(state, JobPage, cursor, cancellationToken).ConfigureAwait(false);
foreach (var job in page.Items) busy.UnionWith(Holds(job));
cursor = page.NextCursor;
}
while (cursor is not null);
}
return busy;
}
private static IReadOnlyList Holds(Job job)
{
if (job.Kind != JobKind.Verify) return job.TargetIds;
try
{
return ArchiveJobJson.Read(job, ArchiveJobJson.Default.VerifyParameters, new VerifyParameters(null)).SequenceIds ?? job.TargetIds;
}
catch (JsonException)
{
return job.TargetIds;
}
}
///
/// The id a sidecar names, from its head (the id is written second), so checking a 35 MB sidecar does not parse it;
/// the whole file is read only when the head does not hold the id. Null when the file is unreadable.
///
private static Guid? SidecarId(string path)
{
try
{
var head = new byte[SidecarHead];
int length;
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
length = stream.ReadAtLeast(head, head.Length, throwOnEndOfStream: false);
var reader = new Utf8JsonReader(head.AsSpan(0, length), isFinalBlock: length < head.Length, state: default);
while (reader.Read())
{
if (reader.TokenType != JsonTokenType.PropertyName || reader.CurrentDepth != 1) continue;
if (reader.ValueTextEquals("id"u8))
{
if (!reader.Read()) break;
return reader.TokenType == JsonTokenType.String && reader.TryGetGuid(out var id) ? id : null;
}
if (!reader.TrySkip()) break;
}
return ManifestStore.ReadSequence(path).Id;
}
catch (Exception ex) when (ex is JsonException or InvalidDataException or IOException or UnauthorizedAccessException)
{
return null;
}
}
private static (int Files, long Bytes) Measure(string folder, CancellationToken cancellationToken)
{
int files = 0;
long bytes = 0;
foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", new EnumerationOptions { RecurseSubdirectories = true, AttributesToSkip = 0 }))
{
cancellationToken.ThrowIfCancellationRequested();
files++;
bytes += file.Length;
}
return (files, bytes);
}
/// The sequence id, or the id with a time stamp when an earlier deletion of the same sequence is still in the trash.
private static string EntryName(ArchivePaths paths, Guid sequenceId, IReadOnlySet claimed)
{
var trash = TrashDirectory(paths);
var name = sequenceId.ToString("N");
var stamp = DateTime.UtcNow.ToString("yyyyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture);
for (var n = 1; claimed.Contains(name) || Directory.Exists(Path.Combine(trash, name)); n++)
name = $"{sequenceId:N}-{stamp}" + (n > 1 ? "-" + n.ToString(System.Globalization.CultureInfo.InvariantCulture) : string.Empty);
return name;
}
/// The original folder when it is free on disk and in the index, else "folder (2)", "folder (3)", …
private static string FreeFolder(ArchivePaths paths, string folder, IReadOnlySet indexed)
{
var candidate = folder;
for (var n = 2; indexed.Contains(candidate) || Directory.Exists(paths.Sequence(candidate).Folder); n++)
candidate = string.Create(System.Globalization.CultureInfo.InvariantCulture, $"{folder} ({n})");
return candidate;
}
/// A render stored inside the old folder points into the folder it was restored to.
private static string Rebase(string outputPath, string from, string to) =>
from != to && outputPath.StartsWith(from + "/", StringComparison.Ordinal) ? to + outputPath[from.Length..] : outputPath;
private static TrashEntry Entry(Guid archiveId, string name, TrashRecord record) =>
new(archiveId, name, record.Sequence.Id, record.Sequence.DisplayTitle, record.Sequence.Folder, record.Sequence.FrameCount, record.Files,
record.Bytes, record.DeletedAt, record.DeletedBy);
private static TrashRecord? ReadRecord(string path)
{
try
{
return JsonSerializer.Deserialize(File.ReadAllText(path), TrashJson.Default.TrashRecord);
}
catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
{
Log.Warning("archive", $"Trash record {path} is unreadable", ex);
return null;
}
}
/// An archive as the plan sees it: where it is, whether it can be written, and where its sequences are.
private sealed record ArchiveContext(ArchivePaths Paths, ArchiveAvailability Availability, IReadOnlyList Locations);
}
/// What the trash keeps next to a deleted folder: the index row and renders the sidecar does not carry.
internal sealed record TrashRecord(Sequence Sequence, IReadOnlyList Renders, int Files, long Bytes, DateTimeOffset DeletedAt, string? DeletedBy);
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
UseStringEnumConverter = true, IgnoreReadOnlyProperties = true)]
[JsonSerializable(typeof(TrashRecord))]
internal sealed partial class TrashJson : JsonSerializerContext;