feat(workspace): clean-up of media, size limit and workspace trash
Phase 5c P4. The workspace no longer grows without bound: a daily workspace-cleanup system schedule (04:30, catch-up) removes the media of projects in step with their home that were not opened for Clean after, and the size limit removes the least recently used after each copy. Each project kept is logged with its reason (open in Edit, not in step, home offline, jobs pending, renders not sent, unreadable, just copied). - WorkspaceCleaner: cleans under the project's lease, re-checking every condition; the originals the home no longer holds go to the workspace trash, never away. The media index is marked Cleaned, so the project reads as MediaRemoved and opening it copies the media again. - WorkspaceTrash: lists entries with a fingerprint, and empties only the plan the user confirmed (refused when the trash changed since). - Trash dialog view model and view: Erase is enabled only after the user types the number of entries. - Removing a copy counts the unsent renders and the last originals. Send first queues the renders' sending and refuses the removal until they are sent. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2e1c67f531
commit
f86630c77a
19 files changed
+1595
-44
No files matched your search
@@ -37,7 +37,7 @@ public sealed class DesktopScheduleHostTests(TestContext context)
|
||||
await fx.StartAsync();
|
||||
var kept = Assert.NotNull(await fx.Db.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.ArchiveScan));
|
||||
Assert.Equal((scan.Id, "every:2h"), (kept.Id, kept.Recurrence));
|
||||
Assert.Count(3, (await fx.Db.Schedules.ListAsync()).Where(s => s.IsSystem));
|
||||
Assert.Count(4, (await fx.Db.Schedules.ListAsync()).Where(s => s.IsSystem));
|
||||
|
||||
// Reset goes back to what the host seeds with.
|
||||
Assert.Null((await fx.Scheduler!.ResetAsync(scan.Id)).Problem);
|
||||
@@ -109,9 +109,9 @@ public sealed class DesktopScheduleHostTests(TestContext context)
|
||||
Assert.Equal(fx.Clock.Now.AddDays(1), backup.NextRun);
|
||||
|
||||
// Chronos was closed for two days: the missed copy is made once at start (catch-up, as the housekeeping's run; the
|
||||
// scan has none and just moves on).
|
||||
// scan has none and just moves on; the workspace clean-up, with catch-up too, runs once as well).
|
||||
fx.Clock.Advance(TimeSpan.FromDays(2.5));
|
||||
Assert.Equal(2, await scheduler.RunDueAsync());
|
||||
Assert.Equal(3,await scheduler.RunDueAsync());
|
||||
var job = (await fx.Db.Jobs.ListByScheduleAsync(backup.Id)).Single();
|
||||
Assert.Equal((JobKind.Backup, JobPriority.Background, JobState.Queued), (job.Kind, job.Priority, job.State));
|
||||
Assert.Equal(0, await scheduler.RunDueAsync());
|
||||
@@ -168,6 +168,23 @@ public sealed class DesktopScheduleHostTests(TestContext context)
|
||||
Assert.Equal(ScheduleRecurrence.DailyAt(new TimeOnly(4, 0)).Next(fx.Clock.Now, TimeZoneInfo.Utc), housekeeping.NextRun);
|
||||
}
|
||||
|
||||
/// <summary>Phase 5c: the workspace's clean-up is a system schedule of its own, seeded once, daily at 04:30 with catch-up.</summary>
|
||||
[Test]
|
||||
public async Task TheWorkspaceCleanUpIsSeededOnceAsASystemSchedule()
|
||||
{
|
||||
await using var fx = await ScheduleFixture.CreateAsync(context);
|
||||
await fx.StartAsync();
|
||||
var cleanup = Assert.NotNull(await fx.Db.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.WorkspaceCleanup));
|
||||
Assert.Equal(("daily:04:30", true, ScheduleActions.Cleanup, true), (cleanup.Recurrence, cleanup.CatchUp, cleanup.Action, cleanup.Enabled));
|
||||
var parameters = ScheduleMapping.Parameters(cleanup);
|
||||
Assert.SequenceEqual([WorkspaceCleanStep.StepName, WorkspaceTrashStep.StepName], parameters.Steps!);
|
||||
Assert.Equal(0, parameters.OlderThanDays);
|
||||
Assert.Equal(("Workspace media", "Workspace trash"), (ScheduleText.Step(WorkspaceCleanStep.StepName), ScheduleText.Step(WorkspaceTrashStep.StepName)));
|
||||
|
||||
await fx.StartAsync();
|
||||
Assert.Count(1, (await fx.Db.Schedules.ListAsync()).Where(s => s.SystemKey == DesktopScheduleHost.WorkspaceCleanup));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SchedulesWorkOnTheArchiveAtTheFolderWhileItIsOnline()
|
||||
{
|
||||
|
||||
@@ -36,9 +36,9 @@ public sealed class ScheduledTabTests
|
||||
shell.Jobs.TabIndex = 1;
|
||||
await app.ExpectAsync<SchedulesView>("jobs-scheduled");
|
||||
|
||||
Assert.SequenceEqual(["Archive scan", "Index backup", "Housekeeping", "Weekly integrity check", "Monthly orphans report"], schedules.Rows.Select(r => r.Name));
|
||||
Assert.SequenceEqual(["Archive scan", "Index backup", "Housekeeping", "Workspace clean-up", "Weekly integrity check", "Monthly orphans report"], schedules.Rows.Select(r => r.Name));
|
||||
var items = app.FindAll<ListBoxItem>().Where(i => i.DataContext is ScheduleRowViewModel && i.IsVisible).ToList();
|
||||
Assert.Count(5, items);
|
||||
Assert.Count(6, items);
|
||||
foreach (var item in items)
|
||||
{
|
||||
var row = (ScheduleRowViewModel)item.DataContext;
|
||||
|
||||
@@ -30,9 +30,9 @@ public sealed class SchedulesViewModelTests
|
||||
using var vm = await fx.ViewModelAsync();
|
||||
|
||||
Assert.True(vm.IsRunning && vm.IsLoaded && vm.HasRows, "the schedules are listed");
|
||||
Assert.SequenceEqual(["Archive scan", "Index backup", "Housekeeping"], vm.Rows.Select(r => r.Name));
|
||||
Assert.SequenceEqual(["Every 10 minutes", "Every day", "Daily at " + ScheduleText.Time(new TimeOnly(4, 0))], vm.Rows.Select(r => r.WhenText));
|
||||
Assert.SequenceEqual(["Archive scan", "Index backup", "Clean-up"], vm.Rows.Select(r => r.ActionText));
|
||||
Assert.SequenceEqual(["Archive scan", "Index backup", "Housekeeping", "Workspace clean-up"], vm.Rows.Select(r => r.Name));
|
||||
Assert.SequenceEqual(["Every 10 minutes", "Every day", "Daily at " + ScheduleText.Time(new TimeOnly(4, 0)), "Daily at " + ScheduleText.Time(new TimeOnly(4, 30))], vm.Rows.Select(r => r.WhenText));
|
||||
Assert.SequenceEqual(["Archive scan", "Index backup", "Clean-up", "Clean-up"], vm.Rows.Select(r => r.ActionText));
|
||||
Assert.True(vm.Rows.All(r => r.IsSystem && r.IsEnabled && r.LastText == "never run" && r.LastKind == StatusKind.Offline), "nothing ran yet");
|
||||
// The scan's next run is ten minutes away, today.
|
||||
Assert.Equal(ScheduleText.Moment(fx.Clock.Now.AddMinutes(10)), vm.Rows[0].NextText);
|
||||
@@ -41,9 +41,9 @@ public sealed class SchedulesViewModelTests
|
||||
// A schedule the user creates joins the list after the system ones.
|
||||
var created = await fx.Scheduler!.CreateAsync(new CreateScheduleRequest("Weekly check", ScheduleActions.Verify, new RecurrenceDto("weekly", Time: "02:30", Days: ["mon", "thu"])), null);
|
||||
Assert.Null(created.Problem);
|
||||
Assert.Equal("Weekly check", vm.Rows[3].Name);
|
||||
Assert.Equal("Weekly check", vm.Rows[4].Name);
|
||||
Assert.Equal(ScheduleText.DayShort(DayOfWeek.Monday) + ", " + ScheduleText.DayShort(DayOfWeek.Thursday) + " at " + ScheduleText.Time(new TimeOnly(2, 30)),
|
||||
vm.Rows[3].WhenText);
|
||||
vm.Rows[4].WhenText);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -141,11 +141,11 @@ public sealed class SchedulesViewModelTests
|
||||
Assert.False(scan.DeleteCommand.CanExecute(null));
|
||||
Assert.False(mine.ResetCommand.CanExecute(null));
|
||||
await vm.DeleteAsync(mine);
|
||||
Assert.Count(4, vm.Rows);
|
||||
Assert.Count(5, vm.Rows);
|
||||
answer = true;
|
||||
vm.Selected = mine;
|
||||
await vm.DeleteAsync(mine);
|
||||
Assert.Count(3, vm.Rows);
|
||||
Assert.Count(4, vm.Rows);
|
||||
Assert.Null(vm.Selected);
|
||||
Assert.Null(await fx.Db.Schedules.GetAsync(mine.Id));
|
||||
|
||||
@@ -172,7 +172,7 @@ public sealed class SchedulesViewModelTests
|
||||
|
||||
await vm.DeleteAsync(mine);
|
||||
Assert.SequenceEqual([Loc.L("Jobs.Schedule.Failed")], toasts);
|
||||
Assert.Count(4, vm.Rows);
|
||||
Assert.Count(5, vm.Rows);
|
||||
Assert.Contains(mine, vm.Rows);
|
||||
Assert.NotNull(await fx.Db.Schedules.GetAsync(mine.Id));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using Chronos.App.Archiving;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Jobs;
|
||||
using Chronos.App.Workspace;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.App.Tests.Workspace;
|
||||
|
||||
/// <summary>
|
||||
/// The desktop's side of the workspace clean-up (phase 5c, P4): the <c>workspace-clean</c> and <c>workspace-trash</c> steps
|
||||
/// run by a Cleanup job with no archive, the project open in Edit kept, a removal refused (its renders queued to be sent)
|
||||
/// while renders wait, and the trash emptied only as planned, once its number of entries is typed.
|
||||
/// </summary>
|
||||
[Category("workspace")]
|
||||
public sealed class WorkspaceCleanupHostTests(TestContext context)
|
||||
{
|
||||
static WorkspaceCleanupHostTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
||||
|
||||
private static readonly TimeSpan Day = TimeSpan.FromDays(1);
|
||||
|
||||
[Test]
|
||||
public async Task TheScheduledCleanUpRunsWithoutAnArchiveAndKeepsTheProjectOpenInEdit()
|
||||
{
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
|
||||
var settings = new AppSettings { WorkspaceAutoSync = false, WorkspaceCleanAfterDays = 30 };
|
||||
var host = bed.Host(settings);
|
||||
var mainId = await bed.CheckoutAsync(host);
|
||||
settings.WorkspaceOpened[mainId] = DateTimeOffset.UtcNow - 40 * Day;
|
||||
var project = host.Store.Find(mainId)!;
|
||||
Assert.True(Directory.Exists(project.ProxiesDirectory), "copied");
|
||||
|
||||
// Open in Edit: kept, with why.
|
||||
Guid? open = mainId;
|
||||
host.OpenProject = () => open;
|
||||
var kept = Assert.NotNull(await host.CleanAsync(cleanAfter: true));
|
||||
Assert.Empty(kept.Cleaned);
|
||||
Assert.True(kept.Kept is [{ Reason: WorkspaceKeep.Open }], "kept while open");
|
||||
Assert.Equal("open in Edit", WorkspaceCleanStep.Reason(WorkspaceKeep.Open));
|
||||
Assert.True(Directory.Exists(project.ProxiesDirectory), "the media stay");
|
||||
|
||||
// The schedule's Cleanup job, with no archive: the media go, the trash is only reported.
|
||||
open = null;
|
||||
await using var jobs = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(bed.Directory, "jobs.db")), bed.Ct);
|
||||
var service = new ArchiveService(jobs, new ArchiveServiceOptions { CleanupSteps = [new WorkspaceCleanStep(() => host), new WorkspaceTrashStep(() => host)] });
|
||||
await using var engine = new JobEngine(jobs, service.CreateJobHandlers(), new JobEngineOptions { WorkerId = "cleanup", PollInterval = TimeSpan.FromMilliseconds(50) });
|
||||
await engine.StartAsync(bed.Ct);
|
||||
var job = await engine.EnqueueAsync(ArchiveJobs.Cleanup(null, [WorkspaceCleanStep.StepName, WorkspaceTrashStep.StepName], 0), cancellationToken: bed.Ct);
|
||||
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(60));
|
||||
while ((await jobs.Jobs.GetAsync(job.Id, bed.Ct))!.State is JobState.Queued or JobState.Running)
|
||||
{
|
||||
Assert.True(DateTime.UtcNow < deadline, "the clean-up job did not finish");
|
||||
await Task.Delay(50, bed.Ct);
|
||||
}
|
||||
var done = (await jobs.Jobs.GetAsync(job.Id, bed.Ct))!;
|
||||
Assert.Equal(JobState.Done, done.State, done.Error ?? done.LogTail);
|
||||
Assert.Contains("Workspace: projects cleaned: 1", done.LogTail);
|
||||
Assert.Contains(Loc.L("Jobs.Log.WorkspaceTrash", Formatting.Count(0), Formatting.Bytes(0)), done.LogTail);
|
||||
Assert.False(Directory.Exists(project.ProxiesDirectory), "the media went");
|
||||
Assert.True(host.Store.Find(mainId) is not null && File.Exists(project.BundlePath), "the copy and its work stay");
|
||||
Assert.False((await host.FindAsync(mainId))!.HasMedia, "opening it copies the media again");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task RendersNotSentBlockTheRemovalAndAreQueuedToBeSent()
|
||||
{
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
|
||||
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
|
||||
var mainId = await bed.CheckoutAsync(host);
|
||||
var project = host.Store.Find(mainId)!;
|
||||
Directory.CreateDirectory(project.ExportsDirectory);
|
||||
File.WriteAllText(project.ExportFile("clip.mp4"), "rendered");
|
||||
project.WriteRenders(WorkspaceRenders.Empty.With(new WorkspaceRenderEntry(Guid.CreateVersion7(), Guid.CreateVersion7(), "clip.mp4", new string('a', 64), 8,
|
||||
"preset", "h264", 1920, 1080, 25, 4, mainId, null, null, DateTimeOffset.UtcNow, WorkspaceRenderEntry.Pending, null)));
|
||||
|
||||
var plan = await host.PlanRemovalAsync(mainId);
|
||||
Assert.True(plan is { UnsentRenders: 1, IsSafe: false }, "a render waits");
|
||||
var dialog = new RemoveCopyDialogViewModel(plan, _ => Task.CompletedTask, () => Task.CompletedTask, () => true, _ => { });
|
||||
Assert.Contains(dialog.Facts, f => f.Label == Loc.L("Editor.RemoveCopy.UnsentRenders") && f.Value == Formatting.Count(1));
|
||||
Assert.False(dialog.RemoveCommand.CanExecute(null), "not while renders wait");
|
||||
|
||||
var refused = await Assert.ThrowsAsync<WorkspaceException>(() => host.RemoveLocalCopyAsync(mainId, discard: false));
|
||||
Assert.Equal(Loc.L("Errors.Workspace.UnsentRenders"), refused.Message);
|
||||
Assert.NotNull(host.Store.Find(mainId), "nothing was removed");
|
||||
var sends = (await bed.Db.Jobs.ListAsync(null, JobKind.WorkspaceSend, cancellationToken: bed.Ct)).Items;
|
||||
var send = Assert.Contains(sends, j => j.TargetIds.Contains(bed.SequenceId));
|
||||
Assert.Equal(mainId, WorkspaceJobs.SendParameters(send)!.ProjectId);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheTrashIsEmptiedAsPlannedOnceItsNumberIsTyped()
|
||||
{
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 2);
|
||||
var host = bed.Host();
|
||||
Assert.True((await host.PlanTrashAsync()).IsEmpty, "no trash yet");
|
||||
var folder = WorkspaceTrash.FolderOf(host.Root);
|
||||
foreach (var name in new[] { "a", "b" })
|
||||
{
|
||||
var entry = Directory.CreateDirectory(Path.Combine(folder, Guid.CreateVersion7().ToString("N") + "-" + DateTime.UtcNow.Ticks)).FullName;
|
||||
File.WriteAllText(Path.Combine(entry, name + ".txt"), "kept aside " + name);
|
||||
}
|
||||
var usage = await host.UsageAsync();
|
||||
Assert.Equal(2L * "kept aside a".Length, usage.TrashBytes);
|
||||
|
||||
var plan = await host.PlanTrashAsync();
|
||||
Assert.Equal((2, 2L * "kept aside a".Length), (plan.Items.Count, plan.Bytes));
|
||||
var closed = 0;
|
||||
WorkspaceTrashResult? emptied = null;
|
||||
var dialog = new WorkspaceTrashDialogViewModel(plan, p => host.EmptyTrashAsync(p), r => emptied = r, _ => closed++);
|
||||
Assert.Equal(2, dialog.Rows.Count);
|
||||
Assert.Equal("2", dialog.Confirmation);
|
||||
Assert.False(dialog.EraseCommand.CanExecute(null), "nothing typed");
|
||||
dialog.Typed = "3";
|
||||
Assert.False(dialog.CanErase, "the wrong number");
|
||||
dialog.Typed = " 2 ";
|
||||
Assert.True(dialog.CanErase && dialog.EraseCommand.CanExecute(null), "the number of entries");
|
||||
|
||||
// An entry added since the plan: refused, nothing erased, the dialog stays open with why.
|
||||
var late = Directory.CreateDirectory(Path.Combine(folder, Guid.CreateVersion7().ToString("N") + "-" + DateTime.UtcNow.Ticks)).FullName;
|
||||
File.WriteAllText(Path.Combine(late, "late.txt"), "late");
|
||||
dialog.EraseCommand.Execute(null);
|
||||
await WorkspaceTestBed.UntilAsync(() => dialog.ErrorText is { Length: > 0 }, "the emptying is refused");
|
||||
Assert.Equal(0, closed);
|
||||
Assert.Equal(3, (await host.PlanTrashAsync()).Items.Count);
|
||||
|
||||
// As planned again: erased for good, the dialog closed.
|
||||
plan = await host.PlanTrashAsync();
|
||||
dialog = new WorkspaceTrashDialogViewModel(plan, p => host.EmptyTrashAsync(p), r => emptied = r, _ => closed++) { Typed = "3" };
|
||||
dialog.EraseCommand.Execute(null);
|
||||
await WorkspaceTestBed.UntilAsync(() => closed == 1, "the dialog closes");
|
||||
Assert.True(emptied is { Items: 3 }, "three entries erased");
|
||||
Assert.True((await host.PlanTrashAsync()).IsEmpty, "the trash is empty");
|
||||
|
||||
// An empty trash offers nothing to erase.
|
||||
var none = new WorkspaceTrashDialogViewModel(await host.PlanTrashAsync(), p => host.EmptyTrashAsync(p), null, _ => { }) { Typed = "0" };
|
||||
Assert.False(none.CanErase);
|
||||
Assert.Equal(Loc.L("Tooltips.Settings.Workspace.EmptyTrash.Disabled"), none.EraseToolTip);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Data.Tests.Archiving;
|
||||
using Chronos.Data.Tests.Infrastructure;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Workspaces;
|
||||
|
||||
/// <summary>
|
||||
/// The workspace's clean-up and trash (phase 5c, P4): media go only from projects whose home holds everything (each other case
|
||||
/// kept with its reason), an original the home lost goes to the trash, Size limit takes the least recently used first, Clean
|
||||
/// after counts from the last opening (else the save), and the trash is never touched by the clean-up and emptied only as
|
||||
/// planned.
|
||||
/// </summary>
|
||||
[Category("workspace")]
|
||||
public abstract class WorkspaceCleanupTests(TestContext context) : DatabaseTest(context)
|
||||
{
|
||||
private static readonly TimeSpan Day = TimeSpan.FromDays(1);
|
||||
|
||||
private async Task<WorkspaceFixture> FixtureAsync(int frames = 4)
|
||||
{
|
||||
var archive = Own(await ArchiveFixture.CreateAsync(Context, database: await NewOptionsAsync(multiConnection: true)));
|
||||
return Own(await WorkspaceFixture.CreateAsync(Context, archive, frames));
|
||||
}
|
||||
|
||||
private static WorkspaceCleaner Cleaner(WorkspaceFixture fx, WorkspaceSync sync, Func<BundleHome, IProjectHome?>? homes = null) =>
|
||||
new(sync, fx.Db, homes ?? (_ => fx.Home)) { LockWait = TimeSpan.FromSeconds(TestTiming.Budget(10)) };
|
||||
|
||||
private static T One<T>(IReadOnlyList<T> items, [System.Runtime.CompilerServices.CallerArgumentExpression(nameof(items))] string? expression = null)
|
||||
{
|
||||
Assert.Count(1, items, expression);
|
||||
return items[0];
|
||||
}
|
||||
|
||||
/// <summary>Clean after 30 days, the project last opened 40 days ago.</summary>
|
||||
private static WorkspaceCleanOptions Aged(Guid projectId, Func<Guid, bool>? isOpen = null, Guid? justCopied = null) => new()
|
||||
{
|
||||
CleanAfterDays = 30,
|
||||
Opened = new Dictionary<Guid, DateTimeOffset> { [projectId] = DateTimeOffset.UtcNow - 40 * Day },
|
||||
IsOpen = isOpen ?? (_ => false),
|
||||
JustCopied = justCopied,
|
||||
};
|
||||
|
||||
/// <summary>A render of the project's ledger with its file in <c>exports/</c>.</summary>
|
||||
private static WorkspaceRenderEntry Render(WorkspaceProject project, string name, string state)
|
||||
{
|
||||
Directory.CreateDirectory(project.ExportsDirectory);
|
||||
File.WriteAllText(project.ExportFile(name), "rendered " + name);
|
||||
return new WorkspaceRenderEntry(Guid.CreateVersion7(), Guid.CreateVersion7(), name, new string('a', 64), 12, "preset", "h264", 1920, 1080, 25, 4,
|
||||
project.ProjectId, null, null, DateTimeOffset.UtcNow, state, state == WorkspaceRenderEntry.SentState ? DateTimeOffset.UtcNow : null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AProjectInStepWithItsHomeLosesItsMediaAndKeepsItsWork()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var (store, sync) = fx.Workspace();
|
||||
var project = await fx.CheckoutAsync(sync);
|
||||
var id = project.ProjectId;
|
||||
var sent = Render(project, "sent.mp4", WorkspaceRenderEntry.SentState);
|
||||
project.WriteRenders(WorkspaceRenders.Empty.With(sent));
|
||||
var bundle = File.ReadAllBytes(project.BundlePath);
|
||||
var proxies = WorkspaceCleaner.Measure(project.ProxiesDirectory).Bytes;
|
||||
Assert.True(WorkspaceCleaner.HoldsMedia(project), "the copy brought the media");
|
||||
|
||||
var report = await Cleaner(fx, sync).CleanAsync(Aged(id), fx.Ct);
|
||||
|
||||
var cleaned = One(report.Cleaned);
|
||||
Assert.Equal((id, 0), (cleaned.ProjectId, cleaned.Trashed));
|
||||
Assert.Equal(proxies + "rendered sent.mp4".Length, cleaned.Freed);
|
||||
Assert.Empty(report.Kept);
|
||||
Assert.False(Directory.Exists(project.ProxiesDirectory), "the proxies went");
|
||||
Assert.FileMissing(project.ExportFile("sent.mp4"));
|
||||
Assert.Empty(project.ReadRenders().Entries);
|
||||
// The frames stay, naming no file; the working state, the deep report and the sync state are as they were.
|
||||
var media = Assert.NotNull(project.ReadMedia());
|
||||
Assert.True(media.IsCleaned, "the index says the clean-up emptied it");
|
||||
Assert.Equal(fx.Frames.Count, media.Frames.Count);
|
||||
Assert.True(media.Frames.All(f => f.File is null && f.Original is null && f.FileBytes == 0), "no frame names a file");
|
||||
Assert.BytesEqual(bundle, File.ReadAllBytes(project.BundlePath));
|
||||
Assert.False(WorkspaceCleaner.HoldsMedia(project), "nothing to edit until a copy");
|
||||
Assert.Equal(WorkspaceState.MediaRemoved, (await sync.StatusAsync(id, fx.Home, fx.Ct)).State);
|
||||
|
||||
// A second run finds nothing to do; a copy brings the media back, in step as before.
|
||||
Assert.Empty((await Cleaner(fx, sync).CleanAsync(Aged(id), fx.Ct)).Cleaned);
|
||||
await fx.CopyAsync(store, id);
|
||||
Assert.True(WorkspaceCleaner.HoldsMedia(project), "copied again");
|
||||
Assert.False(project.ReadMedia()!.IsCleaned, "a copy writes an index of its own");
|
||||
Assert.Equal(WorkspaceState.InSync, (await sync.StatusAsync(id, fx.Home, fx.Ct)).State);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task EachReasonToKeepAProjectKeepsItsMedia()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var (_, sync) = fx.Workspace();
|
||||
var project = await fx.CheckoutAsync(sync);
|
||||
var id = project.ProjectId;
|
||||
var cleaner = Cleaner(fx, sync);
|
||||
|
||||
async Task KeptAsync(WorkspaceKeep reason, WorkspaceCleanOptions options, WorkspaceCleaner? by = null)
|
||||
{
|
||||
var report = await (by ?? cleaner).CleanAsync(options, fx.Ct);
|
||||
Assert.Empty(report.Cleaned);
|
||||
Assert.Equal((id, reason), (One(report.Kept).ProjectId, report.Kept[0].Reason));
|
||||
Assert.True(Directory.Exists(project.ProxiesDirectory) && !project.ReadMedia()!.IsCleaned, $"kept ({reason})");
|
||||
}
|
||||
|
||||
await KeptAsync(WorkspaceKeep.JustCopied, Aged(id, justCopied: id));
|
||||
await KeptAsync(WorkspaceKeep.Open, Aged(id, isOpen: p => p == id));
|
||||
|
||||
// A copy of this project waiting (paused) in the queue; another project's does not count.
|
||||
var copy = TestData.Job(JobKind.WorkspaceCopy) with
|
||||
{
|
||||
TargetIds = [fx.Sequence.Id],
|
||||
State = JobState.Paused,
|
||||
ParametersJson = JsonSerializer.Serialize(new { workspaceRoot = sync.Store.Root, projectId = id, media = BundleMedia.Proxies }),
|
||||
};
|
||||
await fx.Db.Jobs.EnqueueAsync(copy, fx.Ct);
|
||||
await KeptAsync(WorkspaceKeep.Jobs, Aged(id));
|
||||
await fx.Db.Jobs.SetStateAsync(copy.Id, JobState.Cancelled, cancellationToken: fx.Ct);
|
||||
|
||||
var renders = WorkspaceRenders.Empty.With(Render(project, "pending.mp4", WorkspaceRenderEntry.Pending));
|
||||
project.WriteRenders(renders);
|
||||
await KeptAsync(WorkspaceKeep.UnsentRenders, Aged(id));
|
||||
project.WriteRenders(renders.With(renders.Entries[0] with { State = WorkspaceRenderEntry.Failed, Error = "refused" }));
|
||||
await KeptAsync(WorkspaceKeep.UnsentRenders, Aged(id));
|
||||
File.WriteAllText(project.RendersPath, "{ not a ledger");
|
||||
await KeptAsync(WorkspaceKeep.Unreadable, Aged(id));
|
||||
File.Delete(project.RendersPath);
|
||||
File.Delete(project.ExportFile("pending.mp4"));
|
||||
|
||||
await KeptAsync(WorkspaceKeep.Offline, Aged(id), Cleaner(fx, sync, _ => null));
|
||||
await KeptAsync(WorkspaceKeep.Offline, Aged(id), Cleaner(fx, sync, _ => new UnreachableHome(fx.Home)));
|
||||
|
||||
var session = await sync.OpenAsync(id, fx.Ct);
|
||||
await sync.SaveAsync(id, session.Working with { Exposure = session.Working.Exposure with { ExposureOffsetEv = 0.7 } }, fx.Ct);
|
||||
await KeptAsync(WorkspaceKeep.NotInSync, Aged(id));
|
||||
await sync.CommitAsync(id, null, null, fx.Ct);
|
||||
await KeptAsync(WorkspaceKeep.NotInSync, Aged(id));
|
||||
await sync.PushAsync(id, fx.Home, fx.Ct);
|
||||
|
||||
// In step again: it goes. Media whose files are gone already hold nothing to remove.
|
||||
var other = await fx.Archive.Service.Projects.CreateAsync(fx.Sequence.Id, "Second", cancellationToken: fx.Ct);
|
||||
var second = await fx.CheckoutAsync(sync, other.Id);
|
||||
Directory.Delete(second.ProxiesDirectory, recursive: true);
|
||||
var options = Aged(id) with { Opened = new Dictionary<Guid, DateTimeOffset> { [id] = DateTimeOffset.UtcNow - 40 * Day, [other.Id] = DateTimeOffset.UtcNow - 50 * Day } };
|
||||
var report = await cleaner.CleanAsync(options, fx.Ct);
|
||||
Assert.Equal(id, One(report.Cleaned).ProjectId);
|
||||
Assert.Equal((other.Id, WorkspaceKeep.NoMedia), (One(report.Kept).ProjectId, report.Kept[0].Reason));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnOriginalTheHomeNoLongerHoldsGoesToTheTrashNeverAway()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var (store, sync) = fx.Workspace();
|
||||
var project = await fx.CheckoutAsync(sync);
|
||||
// Originals of two frames: the first as the home holds it, the second of bytes the home no longer has.
|
||||
var media = project.ReadMedia()!;
|
||||
var held = WorkspaceProject.OriginalName(media.Frames[0].Id, fx.Frames[0].Sha256!, ".jpg");
|
||||
var lost = WorkspaceProject.OriginalName(media.Frames[1].Id, new string('f', 64), ".jpg");
|
||||
Directory.CreateDirectory(project.OriginalsDirectory);
|
||||
File.WriteAllText(project.MediaFile(held), "held original");
|
||||
File.WriteAllText(project.MediaFile(lost), "last original");
|
||||
project.WriteMedia(media with
|
||||
{
|
||||
Kind = BundleMedia.Originals,
|
||||
Frames =
|
||||
[
|
||||
media.Frames[0] with { Original = held, OriginalSha256 = fx.Frames[0].Sha256, OriginalBytes = 13 },
|
||||
media.Frames[1] with { Original = lost, OriginalSha256 = new string('f', 64), OriginalBytes = 13 },
|
||||
.. media.Frames.Skip(2),
|
||||
],
|
||||
});
|
||||
Assert.SequenceEqual([media.Frames[1].Id], WorkspaceCleaner.LastOriginals(project.ReadMedia(), await fx.Home.FramesAsync(fx.Ct)).Select(f => f.Id));
|
||||
|
||||
var report = await Cleaner(fx, sync).CleanAsync(Aged(project.ProjectId), fx.Ct);
|
||||
|
||||
Assert.Equal(1, One(report.Cleaned).Trashed);
|
||||
Assert.False(Directory.Exists(project.OriginalsDirectory), "the originals folder went");
|
||||
var trash = WorkspaceTrash.List(store.Root, fx.Ct);
|
||||
var entry = One(trash.Entries);
|
||||
Assert.True(entry.Name.StartsWith(project.ProjectId.ToString("N") + "-", StringComparison.Ordinal), entry.Name);
|
||||
Assert.Equal("last original", File.ReadAllText(Path.Combine(trash.Folder, entry.Name, WorkspaceProject.OriginalsFolder, Path.GetFileName(lost))));
|
||||
Assert.Equal((1, "last original".Length), (entry.Files, entry.Bytes));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheSizeLimitTakesTheLeastRecentlyUsedFirstAndNeverTheProjectJustCopied()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var (_, sync) = fx.Workspace();
|
||||
var main = await fx.CheckoutAsync(sync);
|
||||
var b = await fx.CheckoutAsync(sync, (await fx.Archive.Service.Projects.CreateAsync(fx.Sequence.Id, "B", cancellationToken: fx.Ct)).Id);
|
||||
var c = await fx.CheckoutAsync(sync, (await fx.Archive.Service.Projects.CreateAsync(fx.Sequence.Id, "C", cancellationToken: fx.Ct)).Id);
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var opened = new Dictionary<Guid, DateTimeOffset> { [main.ProjectId] = now - 3 * Day, [b.ProjectId] = now - Day, [c.ProjectId] = now - 2 * Day };
|
||||
var total = new[] { main, b, c }.Sum(p => WorkspaceCleaner.Measure(p.Folder).Bytes);
|
||||
var media = WorkspaceCleaner.Measure(main.ProxiesDirectory).Bytes;
|
||||
// Two projects' media must go to get under the limit (each holds the same proxies).
|
||||
var limit = total - media - 1;
|
||||
|
||||
// After a copy of Main, the oldest: Main stays, the next two oldest go while the folders stay above the limit.
|
||||
var report = await Cleaner(fx, sync).CleanAsync(new WorkspaceCleanOptions { SizeLimitBytes = limit, Opened = opened, JustCopied = main.ProjectId, Now = now }, fx.Ct);
|
||||
Assert.SequenceEqual([(main.ProjectId, WorkspaceKeep.JustCopied)], report.Kept.Select(k => (k.ProjectId, k.Reason)));
|
||||
Assert.SequenceEqual([c.ProjectId, b.ProjectId], report.Cleaned.Select(p => p.ProjectId));
|
||||
Assert.Equal(total, report.UsedBefore);
|
||||
Assert.Equal(total - report.Freed, report.UsedAfter);
|
||||
|
||||
// Once copied again: the oldest goes first, and one is enough this time.
|
||||
await fx.CopyAsync(sync.Store, b.ProjectId);
|
||||
await fx.CopyAsync(sync.Store, c.ProjectId);
|
||||
report = await Cleaner(fx, sync).CleanAsync(new WorkspaceCleanOptions { SizeLimitBytes = total - 1, Opened = opened, Now = now }, fx.Ct);
|
||||
Assert.SequenceEqual([main.ProjectId], report.Cleaned.Select(p => p.ProjectId));
|
||||
Assert.Empty(report.Kept);
|
||||
Assert.True(Directory.Exists(b.ProxiesDirectory) && Directory.Exists(c.ProxiesDirectory), "the others stay");
|
||||
|
||||
// Under the limit, or with none: nothing goes.
|
||||
Assert.Empty((await Cleaner(fx, sync).CleanAsync(new WorkspaceCleanOptions { SizeLimitBytes = total * 2, Opened = opened, Now = now }, fx.Ct)).Cleaned);
|
||||
Assert.Empty((await Cleaner(fx, sync).CleanAsync(new WorkspaceCleanOptions { Opened = opened, Now = now }, fx.Ct)).Cleaned);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CleanAfterCountsFromTheLastOpeningElseFromTheSave()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var (_, sync) = fx.Workspace();
|
||||
var main = await fx.CheckoutAsync(sync);
|
||||
var other = await fx.CheckoutAsync(sync, (await fx.Archive.Service.Projects.CreateAsync(fx.Sequence.Id, "Other", cancellationToken: fx.Ct)).Id);
|
||||
var saved = main.ReadBundle().Saved;
|
||||
// Main was opened yesterday; the other never here (its save counts), a year after the save past Clean after.
|
||||
var opened = new Dictionary<Guid, DateTimeOffset> { [main.ProjectId] = saved + 364 * Day };
|
||||
var options = new WorkspaceCleanOptions { CleanAfterDays = 30, Opened = opened, Now = saved + 365 * Day };
|
||||
|
||||
var report = await Cleaner(fx, sync).CleanAsync(options, fx.Ct);
|
||||
Assert.SequenceEqual([other.ProjectId], report.Cleaned.Select(p => p.ProjectId));
|
||||
Assert.Empty(report.Kept);
|
||||
Assert.True(Directory.Exists(main.ProxiesDirectory), "opened yesterday");
|
||||
|
||||
// Within Clean after of the save, or with Clean after off: kept.
|
||||
await fx.CopyAsync(sync.Store, other.ProjectId);
|
||||
Assert.Empty((await Cleaner(fx, sync).CleanAsync(options with { Now = saved + 29 * Day, Opened = new Dictionary<Guid, DateTimeOffset>() }, fx.Ct)).Cleaned);
|
||||
Assert.Empty((await Cleaner(fx, sync).CleanAsync(options with { CleanAfterDays = 0 }, fx.Ct)).Cleaned);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheCleanUpNeverTouchesTheTrashWhichEmptiesOnlyAsPlanned()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var (store, sync) = fx.Workspace();
|
||||
var project = await fx.CheckoutAsync(sync);
|
||||
var folder = WorkspaceTrash.FolderOf(store.Root);
|
||||
var kept = Directory.CreateDirectory(Path.Combine(folder, Guid.CreateVersion7().ToString("N") + "-" + DateTime.UtcNow.AddDays(-90).Ticks)).FullName;
|
||||
File.WriteAllText(Path.Combine(kept, "project.chronos"), "a removed copy's work");
|
||||
var before = WorkspaceTrash.List(store.Root, fx.Ct);
|
||||
Assert.Equal((1, 1, (long)"a removed copy's work".Length), (before.Entries.Count, before.Entries[0].Files, before.Bytes));
|
||||
Assert.InRange((before.Entries[0].Trashed - DateTimeOffset.UtcNow.AddDays(-90)).TotalMinutes, -1, 1);
|
||||
|
||||
// Even a size limit of one byte leaves the trash as it was.
|
||||
await Cleaner(fx, sync).CleanAsync(new WorkspaceCleanOptions { CleanAfterDays = 1, SizeLimitBytes = 1, Now = DateTimeOffset.UtcNow + 10 * Day }, fx.Ct);
|
||||
Assert.False(Directory.Exists(project.ProxiesDirectory), "the media went");
|
||||
Assert.Equal(before.Fingerprint, WorkspaceTrash.List(store.Root, fx.Ct).Fingerprint);
|
||||
|
||||
// An entry added after the plan: nothing is erased.
|
||||
var added = Directory.CreateDirectory(Path.Combine(folder, Guid.CreateVersion7().ToString("N") + "-" + DateTime.UtcNow.Ticks)).FullName;
|
||||
File.WriteAllText(Path.Combine(added, "late.txt"), "late");
|
||||
Assert.Throws<WorkspaceTrashChangedException>(() => WorkspaceTrash.Empty(store.Root, before, fx.Ct));
|
||||
Assert.True(Directory.Exists(kept) && Directory.Exists(added), "nothing was erased");
|
||||
// A file changed inside an entry changes the fingerprint too.
|
||||
var plan = WorkspaceTrash.List(store.Root, fx.Ct);
|
||||
File.AppendAllText(Path.Combine(added, "late.txt"), " and longer");
|
||||
Assert.Throws<WorkspaceTrashChangedException>(() => WorkspaceTrash.Empty(store.Root, plan, fx.Ct));
|
||||
|
||||
plan = WorkspaceTrash.List(store.Root, fx.Ct);
|
||||
File.SetAttributes(Path.Combine(kept, "project.chronos"), FileAttributes.ReadOnly);
|
||||
Assert.Equal((2, plan.Bytes), WorkspaceTrash.Empty(store.Root, plan, fx.Ct));
|
||||
Assert.True(WorkspaceTrash.List(store.Root, fx.Ct).IsEmpty, "the trash is empty");
|
||||
Assert.True(Directory.Exists(folder), "the trash folder itself stays");
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SqliteWorkspaceCleanupTests(TestContext context) : WorkspaceCleanupTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.SqliteFile;
|
||||
}
|
||||
|
||||
[RequiresEnvironment(PgTestServer.Variable)]
|
||||
public sealed class PostgresWorkspaceCleanupTests(TestContext context) : WorkspaceCleanupTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.Postgres;
|
||||
}
|
||||
Reference in new issue
Block a user