feat(data): delete sequences into the archive's trash and restore them
SequenceTrash plans (files, bytes, trash folder, blocked reasons) and moves
each sequence folder whole into .titano/trash/<id> under its leases, next to a
record of its index row and renders, then drops the index rows; restore moves
it back (to a free folder when the old one is taken) and indexes it again from
its sidecar with the same ids. The server's DELETE /sequences/{id} now uses it
and refuses a sequence a job is working on (409 sequence_busy).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
10 files changed
+700
-20
No files matched your search
@@ -10,7 +10,8 @@ namespace Titano.Data.Archiving;
|
||||
|
||||
/// <summary>
|
||||
/// What the desktop client and the server call to work with archives (BRIEF §7, §12.4, §12.5, §14.4): open, create
|
||||
/// or adopt an archive, plan and apply mass renames, plan imports and card erases, query duplicates and orphans, and
|
||||
/// or adopt an archive, plan and apply mass renames, plan imports and card erases, delete sequences into the trash and
|
||||
/// restore them, query duplicates and orphans, and
|
||||
/// the job handlers for the long operations (enqueue them with <see cref="ArchiveJobs"/>).
|
||||
/// </summary>
|
||||
public sealed class ArchiveService : IJobHandlerProvider
|
||||
@@ -29,6 +30,7 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
Renamer = new MassRenamer(db, _writer, Indexer);
|
||||
Images = new ArchiveImages(db, _writer, Indexer);
|
||||
Imports = new ImportService(db, Ingest);
|
||||
Trash = new SequenceTrash(db, _writer, Indexer);
|
||||
}
|
||||
|
||||
public ArchiveIndexer Indexer { get; }
|
||||
@@ -42,6 +44,9 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
public ArchiveImages Images { get; }
|
||||
public ImportService Imports { get; }
|
||||
|
||||
/// <summary>Deletes sequences into the archive's trash and restores them.</summary>
|
||||
public SequenceTrash Trash { get; }
|
||||
|
||||
/// <summary>Handlers for scan, rebuild, verify, import, thumbs, proxies and maintenance jobs; register them on the <see cref="JobEngine"/>.</summary>
|
||||
public IReadOnlyList<IJobHandler> CreateJobHandlers() =>
|
||||
[
|
||||
@@ -160,6 +165,23 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
await Renamer.ApplyAsync(await LoadArchiveAsync(plan.ArchiveId, cancellationToken).ConfigureAwait(false), plan, progress, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
/// <summary>Dry run of moving sequences to their archive's trash.</summary>
|
||||
public Task<DeletePlan> PlanDeleteAsync(IReadOnlyList<Guid> sequenceIds, CancellationToken cancellationToken = default) =>
|
||||
Trash.PlanAsync(sequenceIds, cancellationToken);
|
||||
|
||||
/// <summary>Moves exactly the planned sequences to the trash; returns the trash entries made.</summary>
|
||||
public Task<IReadOnlyList<TrashEntry>> DeleteAsync(DeletePlan plan, string? deletedBy = null, IProgress<int>? progress = null,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
Trash.DeleteAsync(plan, deletedBy, progress, cancellationToken);
|
||||
|
||||
/// <summary>The sequences in an archive's trash, newest first.</summary>
|
||||
public async Task<IReadOnlyList<TrashEntry>> ListTrashAsync(Guid archiveId, CancellationToken cancellationToken = default) =>
|
||||
await Trash.ListAsync(await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
/// <summary>Moves a sequence back from the trash and indexes it again; null when its folder has no sidecar (a scan adopts it).</summary>
|
||||
public async Task<Sequence?> RestoreAsync(Guid archiveId, string entryName, CancellationToken cancellationToken = default) =>
|
||||
await Trash.RestoreAsync(await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false), entryName, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
/// <summary>Plans a card or folder import into an archive (nothing is copied).</summary>
|
||||
public async Task<ImportPlan> PlanImportAsync(Guid archiveId, string sourceRoot, ImportOptions options, Guid? cardId = null, IProgress<int>? progress = null,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
|
||||
@@ -0,0 +1,381 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Titano.Core.Archiving;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.IO;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
|
||||
namespace Titano.Data.Archiving;
|
||||
|
||||
/// <summary>Why a sequence cannot go to the trash; nothing of it is touched.</summary>
|
||||
public enum DeleteBlock
|
||||
{
|
||||
/// <summary>The archive is offline or read-only.</summary>
|
||||
Offline,
|
||||
|
||||
/// <summary>The photos lie in the archive root itself (a folder adopted in place): the root never moves.</summary>
|
||||
ArchiveRoot,
|
||||
|
||||
/// <summary>Other sequences live in folders below this one; moving it would take them along.</summary>
|
||||
ContainsSequences,
|
||||
|
||||
/// <summary>A job is running on the sequence, or paused in the middle of it.</summary>
|
||||
Busy,
|
||||
|
||||
/// <summary>The folder's sidecar names another sequence: the index is out of date (a scan fixes it).</summary>
|
||||
ForeignSidecar,
|
||||
}
|
||||
|
||||
/// <summary>One sequence of a delete plan: its folder moves to <see cref="TrashFolder"/> and its index rows go.</summary>
|
||||
/// <param name="TrashFolder">Archive-relative folder the sequence folder moves to; null when it has no folder on disk (only its rows go).</param>
|
||||
/// <param name="Files">Files under the folder (originals, proxies, exports, sidecars).</param>
|
||||
/// <param name="Bytes">Their size on disk.</param>
|
||||
public sealed record DeleteStep(Sequence Sequence, string? TrashFolder, int Files, long Bytes);
|
||||
|
||||
public sealed record BlockedDelete(Sequence Sequence, DeleteBlock Reason);
|
||||
|
||||
/// <summary>The dry run of moving sequences to their archive's trash (BRIEF §0.2 rule 8): what moves, and what cannot.</summary>
|
||||
public sealed record DeletePlan(IReadOnlyList<DeleteStep> Steps, IReadOnlyList<BlockedDelete> 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);
|
||||
}
|
||||
|
||||
/// <summary>A deleted sequence kept in an archive's trash, as <see cref="SequenceTrash.ListAsync"/> lists it.</summary>
|
||||
/// <param name="Name">Folder name inside the trash; pass it to <see cref="SequenceTrash.RestoreAsync"/>.</param>
|
||||
/// <param name="Folder">Archive-relative folder the sequence came from (and returns to when it is free).</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);
|
||||
|
||||
/// <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"))
|
||||
{
|
||||
public Guid SequenceId { get; } = sequenceId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deleting sequences without erasing anything (BRIEF §0.2 rule 8, §12.2, §12.5): <see cref="PlanAsync"/> is the dry
|
||||
/// run; <see cref="DeleteAsync"/> moves each sequence folder whole — originals, proxies, exports and its sidecars — into
|
||||
/// <c>.titano/trash/<id></c> of its archive under the sequence's leases, next to a record of its index row and
|
||||
/// renders, then removes the index rows. <see cref="RestoreAsync"/> 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.
|
||||
/// </summary>
|
||||
public sealed class SequenceTrash
|
||||
{
|
||||
/// <summary>Folder of the trash inside the archive's <c>.titano</c>.</summary>
|
||||
public const string FolderName = "trash";
|
||||
|
||||
private const string RecordExtension = ".json";
|
||||
private const int JobPage = 200;
|
||||
|
||||
private readonly TitanoDatabase _db;
|
||||
private readonly SequenceWriter _writer;
|
||||
private readonly ArchiveIndexer _indexer;
|
||||
|
||||
/// <summary>A trash of its own (hosts without an <see cref="ArchiveService"/>); lease files keep it in step with other writers.</summary>
|
||||
public SequenceTrash(TitanoDatabase db, ArchiveServiceOptions? options = null)
|
||||
: this(db, new SequenceWriter(options ?? new ArchiveServiceOptions()), null)
|
||||
{
|
||||
}
|
||||
|
||||
internal SequenceTrash(TitanoDatabase db, SequenceWriter writer, ArchiveIndexer? indexer)
|
||||
{
|
||||
_db = db;
|
||||
_writer = writer;
|
||||
_indexer = indexer ?? new ArchiveIndexer(db, writer);
|
||||
}
|
||||
|
||||
/// <summary>The trash folder of an archive.</summary>
|
||||
public static string TrashDirectory(ArchivePaths archive) => Path.Combine(archive.MetaDirectory, FolderName);
|
||||
|
||||
/// <summary>The dry run: for each sequence, where its folder goes and how many files and bytes it holds, or why it cannot go.</summary>
|
||||
/// <exception cref="ArgumentException">A sequence is not in the index.</exception>
|
||||
public async Task<DeletePlan> PlanAsync(IReadOnlyList<Guid> sequenceIds, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var busy = await BusySequencesAsync(cancellationToken).ConfigureAwait(false);
|
||||
var archives = new Dictionary<Guid, (Archive Archive, ArchivePaths Paths, bool Online, IReadOnlyList<Repositories.SequenceLocation> Locations)>();
|
||||
var steps = new List<DeleteStep>();
|
||||
var blocked = new List<BlockedDelete>();
|
||||
var claimed = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
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));
|
||||
if (!archives.TryGetValue(sequence.ArchiveId, out var context))
|
||||
{
|
||||
var archive = await _db.Archives.GetAsync(sequence.ArchiveId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ArgumentException($"Unknown archive {sequence.ArchiveId}.", nameof(sequenceIds));
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
context = (archive, paths, ArchiveVolume.Probe(paths) == ArchiveAvailability.Online,
|
||||
await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false));
|
||||
archives[sequence.ArchiveId] = context;
|
||||
}
|
||||
if (Block(sequence, context.Paths, context.Online, context.Locations, busy) is { } reason)
|
||||
{
|
||||
blocked.Add(new BlockedDelete(sequence, reason));
|
||||
continue;
|
||||
}
|
||||
var folder = sequence.Folder.Length == 0 ? null : context.Paths.Sequence(sequence.Folder).Folder;
|
||||
if (folder is null || !Directory.Exists(folder))
|
||||
{
|
||||
steps.Add(new DeleteStep(sequence, null, 0, 0));
|
||||
continue;
|
||||
}
|
||||
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));
|
||||
}
|
||||
return new DeletePlan(steps, blocked);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="deletedBy">Who asked (user name or client), kept in the trash record.</param>
|
||||
/// <exception cref="StaleDeletePlanException">A sequence moved, vanished or got busy since the plan; nothing was deleted.</exception>
|
||||
/// <exception cref="ArchiveOfflineException">An archive went offline; sequences before it are in the trash.</exception>
|
||||
public async Task<IReadOnlyList<TrashEntry>> DeleteAsync(DeletePlan plan, string? deletedBy = null, IProgress<int>? progress = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
// A plan made before another change is refused before anything moves.
|
||||
var fresh = await PlanAsync([.. plan.Steps.Select(s => s.Sequence.Id)], cancellationToken).ConfigureAwait(false);
|
||||
if (fresh.Blocked is [var block, ..]) throw new StaleDeletePlanException(block.Sequence.Id);
|
||||
foreach (var step in plan.Steps)
|
||||
{
|
||||
if (fresh.Steps.First(s => s.Sequence.Id == step.Sequence.Id).Sequence.Folder != step.Sequence.Folder)
|
||||
throw new StaleDeletePlanException(step.Sequence.Id);
|
||||
}
|
||||
|
||||
var entries = new List<TrashEntry>(plan.Steps.Count);
|
||||
for (var i = 0; i < fresh.Steps.Count; i++)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
if (await DeleteOneAsync(fresh.Steps[i], deletedBy, cancellationToken).ConfigureAwait(false) is { } entry) entries.Add(entry);
|
||||
progress?.Report(i + 1);
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
/// <summary>The sequences in an archive's trash, newest first; records whose folder is gone are left out.</summary>
|
||||
public async Task<IReadOnlyList<TrashEntry>> 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<TrashEntry>)[];
|
||||
var entries = new List<TrashEntry>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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. Returns the restored row; null when the folder has
|
||||
/// no sidecar (the next scan adopts it).
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidOperationException">The index already holds that sequence.</exception>
|
||||
/// <exception cref="DirectoryNotFoundException">The entry is not in the trash.</exception>
|
||||
public async Task<Sequence?> 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 InvalidOperationException(Loc.L("Archive.Error.InLibrary", 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))
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(sequence.Folder)!);
|
||||
Directory.Move(source, sequence.Folder);
|
||||
Log.Info("archive", $"{record.Sequence.DisplayTitle} restored from the trash to {folder}");
|
||||
if (!File.Exists(sequence.ManifestPath))
|
||||
{
|
||||
File.Delete(recordPath);
|
||||
return null;
|
||||
}
|
||||
var manifest = SequenceWriter.ReadLocked(sequence, id);
|
||||
var kept = record.Sequence with { ArchiveId = archive.Id, Folder = folder, RenderedCount = 0 };
|
||||
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(id, SequenceMapping.ToFrames(manifest, sequence), cancellationToken).ConfigureAwait(false);
|
||||
foreach (var key in manifest.SessionKeys) await tx.Sequences.MapSessionKeyAsync(archive.Id, key, id, cancellationToken).ConfigureAwait(false);
|
||||
foreach (var render in record.Renders)
|
||||
await tx.Renders.InsertAsync(render with { OutputPath = Rebase(render.OutputPath, record.Sequence.Folder, folder) }, cancellationToken).ConfigureAwait(false);
|
||||
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
await _indexer.RecordStampsAsync(archive, sequence, id, cancellationToken).ConfigureAwait(false);
|
||||
File.Delete(recordPath);
|
||||
}
|
||||
return await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task<TrashEntry?> 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);
|
||||
TrashEntry? entry = null;
|
||||
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 not null && sequence.Folder.Length > 0 && Directory.Exists(paths.Sequence(sequence.Folder).Folder))
|
||||
{
|
||||
var folder = paths.Sequence(sequence.Folder);
|
||||
if (File.Exists(folder.ManifestPath) && ManifestStore.ReadSequence(folder.ManifestPath).Id != sequence.Id)
|
||||
throw new StaleDeletePlanException(sequence.Id);
|
||||
var trash = TrashDirectory(paths);
|
||||
Directory.CreateDirectory(trash);
|
||||
var name = EntryName(paths, sequence.Id, new HashSet<string>());
|
||||
var record = new TrashRecord(row, await _db.Renders.ListBySequenceAsync(sequence.Id, cancellationToken).ConfigureAwait(false), step.Files,
|
||||
step.Bytes, DateTimeOffset.UtcNow, deletedBy);
|
||||
// The record first: a crash before the move leaves a record without a folder, which the listing ignores.
|
||||
AtomicFile.WriteAllText(Path.Combine(trash, name + RecordExtension), JsonSerializer.Serialize(record, TrashJson.Default.TrashRecord));
|
||||
Directory.Move(folder.Folder, Path.Combine(trash, name));
|
||||
entry = Entry(archive.Id, name, record);
|
||||
}
|
||||
await using (var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await tx.Sequences.DeleteAsync(sequence.Id, cancellationToken).ConfigureAwait(false);
|
||||
await tx.Archives.DeleteFolderStateAsync(archive.Id, sequence.Folder, cancellationToken).ConfigureAwait(false);
|
||||
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
Log.Info("archive", entry is null
|
||||
? $"{sequence.DisplayTitle} removed from the index (no folder on disk)"
|
||||
: $"{sequence.DisplayTitle} moved to the trash: {sequence.Folder} → {entry.Name} ({step.Files} files, {step.Bytes} bytes)");
|
||||
return entry;
|
||||
}
|
||||
|
||||
private static DeleteBlock? Block(Sequence sequence, ArchivePaths paths, bool online, IReadOnlyList<Repositories.SequenceLocation> locations,
|
||||
IReadOnlySet<Guid> busy)
|
||||
{
|
||||
if (!online) return DeleteBlock.Offline;
|
||||
if (busy.Contains(sequence.Id)) 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 prefix = sequence.Folder + "/";
|
||||
if (locations.Any(l => l.Id != sequence.Id && l.Folder.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))) return DeleteBlock.ContainsSequences;
|
||||
var sidecar = paths.Sequence(sequence.Folder).ManifestPath;
|
||||
try
|
||||
{
|
||||
if (File.Exists(sidecar) && ManifestStore.ReadSequence(sidecar).Id != sequence.Id) return DeleteBlock.ForeignSidecar;
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
return DeleteBlock.ForeignSidecar;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Sequences a running or paused job works on (an import, a render, a transfer, a proxy pass).</summary>
|
||||
private async Task<IReadOnlySet<Guid>> BusySequencesAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var busy = new HashSet<Guid>();
|
||||
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(job.TargetIds);
|
||||
cursor = page.NextCursor;
|
||||
}
|
||||
while (cursor is not null);
|
||||
}
|
||||
return busy;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>The sequence id, or the id with a time stamp when an earlier deletion of the same sequence is still in the trash.</summary>
|
||||
private static string EntryName(ArchivePaths paths, Guid sequenceId, IReadOnlySet<string> 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;
|
||||
}
|
||||
|
||||
/// <summary>The original folder when it is free on disk and in the index, else "folder (2)", "folder (3)", …</summary>
|
||||
private static string FreeFolder(ArchivePaths paths, string folder, IReadOnlySet<string> 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;
|
||||
}
|
||||
|
||||
/// <summary>A render stored inside the old folder points into the folder it was restored to.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What the trash keeps next to a deleted folder: the index row and renders the sidecar does not carry.</summary>
|
||||
internal sealed record TrashRecord(Sequence Sequence, IReadOnlyList<Render> 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;
|
||||
@@ -3,7 +3,9 @@ using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Titano.Core.Model;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Titano.Data;
|
||||
using Titano.Data.Archiving;
|
||||
using Titano.Data.Repositories;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Configuration;
|
||||
@@ -141,30 +143,35 @@ public static class SequenceEndpoints
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a sequence from the index and moves its folder into the archive's trash (BRIEF §0.2 rule 8: nothing is
|
||||
/// erased). <c>?dryRun=true</c> only reports what would happen. Owners and admins only.
|
||||
/// Moves a sequence's folder into the archive's trash and removes it from the index through the archive engine's
|
||||
/// <see cref="SequenceTrash"/> (BRIEF §0.2 rule 8: nothing is erased, the trash keeps it restorable).
|
||||
/// <c>?dryRun=true</c> only reports what would happen. Owners and admins only; a sequence a job is working on is refused (409).
|
||||
/// </summary>
|
||||
private static async Task<IResult> DeleteAsync(HttpContext context, Caller caller, Guid id, bool? dryRun, TitanoDatabase db, ServerArchive archive,
|
||||
ServerOptions options, AuditLog audit, EventHub events)
|
||||
private static async Task<IResult> DeleteAsync(HttpContext context, Caller caller, Guid id, bool? dryRun, TitanoDatabase db,
|
||||
[FromServices] ArchiveService? archives, AuditLog audit, EventHub events)
|
||||
{
|
||||
if (await db.Sequences.GetAsync(id, context.RequestAborted) is not { } sequence) return ApiErrors.NotFound(context, "sequence");
|
||||
var ct = context.RequestAborted;
|
||||
if (await db.Sequences.GetAsync(id, ct) is not { } sequence) return ApiErrors.NotFound(context, "sequence");
|
||||
if (!caller.IsAdmin && sequence.OwnerUserId != caller.Id) return ApiErrors.Forbidden(context);
|
||||
var folder = string.IsNullOrEmpty(sequence.Folder) ? null : ArchivePathGuard.Resolve(archive.Root, sequence.Folder);
|
||||
var trash = Path.Combine(options.TrashPath, id.ToString("N"));
|
||||
var hasFolder = folder is not null && Directory.Exists(folder);
|
||||
var plan = new SequenceDeletePlan(id, sequence.Folder, hasFolder ? Path.GetRelativePath(archive.Root, trash).Replace('\\', '/') : null,
|
||||
sequence.FrameCount, sequence.TotalBytes, sequence.RenderedCount, dryRun == true);
|
||||
if (dryRun == true) return Results.Json(plan, ProtocolJson.Default.SequenceDeletePlan);
|
||||
|
||||
if (hasFolder)
|
||||
var trash = archives?.Trash ?? new SequenceTrash(db, new ArchiveServiceOptions { Owner = ArchiveModule.Owner });
|
||||
DeletePlan plan;
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(options.TrashPath);
|
||||
Directory.Move(folder!, trash);
|
||||
plan = await trash.PlanAsync([id], ct);
|
||||
if (plan.Blocked is [{ } blocked]) return ApiErrors.Conflict(context, "sequence_busy", blocked.Reason.ToString());
|
||||
if (dryRun != true) await trash.DeleteAsync(plan, caller.User.Username, null, ct);
|
||||
}
|
||||
await db.Sequences.DeleteAsync(id, context.RequestAborted);
|
||||
catch (StaleDeletePlanException)
|
||||
{
|
||||
return ApiErrors.Conflict(context, "sequence_busy");
|
||||
}
|
||||
var step = plan.Steps[0];
|
||||
var result = new SequenceDeletePlan(id, sequence.Folder, step.TrashFolder, sequence.FrameCount, sequence.TotalBytes, sequence.RenderedCount, dryRun == true);
|
||||
if (dryRun == true) return Results.Json(result, ProtocolJson.Default.SequenceDeletePlan);
|
||||
|
||||
await audit.WriteAsync(caller, context, "sequence_deleted", "sequence", id.ToString(), sequence.DisplayTitle);
|
||||
events.Publish(new SequenceChangedEvent(id, "deleted", sequence.FramesVersion, sequence.SettingsVersion));
|
||||
return Results.Json(plan, ProtocolJson.Default.SequenceDeletePlan);
|
||||
return Results.Json(result, ProtocolJson.Default.SequenceDeletePlan);
|
||||
}
|
||||
|
||||
/// <summary>Everything a client needs to mirror a sequence and detect changes (BRIEF §14.5); ETag over the version counters.</summary>
|
||||
|
||||
Reference in new issue
Block a user