diff --git a/src/Chronos.App/Infrastructure/AppServices.cs b/src/Chronos.App/Infrastructure/AppServices.cs
index b60cbaea..82084c27 100644
--- a/src/Chronos.App/Infrastructure/AppServices.cs
+++ b/src/Chronos.App/Infrastructure/AppServices.cs
@@ -481,7 +481,9 @@ public sealed class AppServices : IAsyncDisposable
Parallelism = () => Parallelism,
MemoryBudget = () => ProcessingTuning.MemoryBudget(Settings, GC.GetGCMemoryInfo().TotalAvailableMemoryBytes),
// The housekeeping schedule trims the cache to Settings › Storage › Cache limit (owner review 2, R10).
- CleanupSteps = [new CacheTrimStep(() => CacheStore.Folder(Environment, Settings), () => Settings.CacheLimitGb * (1L << 30))],
+ // The workspace-cleanup schedule removes the media past Settings › Workspace's Clean after and Size limit, and reports its trash (phase 5c).
+ CleanupSteps = [new CacheTrimStep(() => CacheStore.Folder(Environment, Settings), () => Settings.CacheLimitGb * (1L << 30)),
+ new WorkspaceCleanStep(() => Workspace), new WorkspaceTrashStep(() => Workspace)],
BackupDirectory = Environment.BackupDirectory,
// Told after each step of a Reorganize, and each sequence a conversion replaced or made, while the rest of the job runs.
SequenceChanged = (id, _, _) =>
@@ -497,6 +499,8 @@ public sealed class AppServices : IAsyncDisposable
var kinds = handlers.Select(h => h.Kind).Distinct().ToArray();
// One job at a time (owner review 1): the parallelism works inside it, the priority queue decides which runs.
Engine = new JobEngine(database, handlers, new JobEngineOptions { WorkerId = WorkerId, Kinds = kinds, PriorityQueue = () => PriorityQueue });
+ // The workspace's size limit runs after each copy of media into it (phase 5c).
+ Engine.JobChanged += Workspace.OnJobChanged;
// Sync follows the engine's jobs before it runs any: a render resumed at start that finishes at once is still sent (Export "Sync").
Sync.Update();
// With no handler the engine must not run: an empty kind list would let workers claim (and fail) every job.
diff --git a/src/Chronos.App/Jobs/DesktopScheduleHost.cs b/src/Chronos.App/Jobs/DesktopScheduleHost.cs
index b7eafeaf..cf29b2f5 100644
--- a/src/Chronos.App/Jobs/DesktopScheduleHost.cs
+++ b/src/Chronos.App/Jobs/DesktopScheduleHost.cs
@@ -20,8 +20,8 @@ namespace Chronos.App.Jobs;
/// wrote into its archive.json, as the rescans before it did, and counts as none while it is offline (an unplugged
/// drive). The system schedules stand for the timers the desktop used to run out of sight: the archive scan (its interval
/// carried over from the former Settings › Archive › Rescan every, , once:
-/// a row that exists keeps the user's edits), the daily index backup, and the housekeeping clean-up at 04:00 (job history,
-/// cache trim). Scans give what they find a deep analysis as Settings › Analysis › After a scan says at each run
+/// a row that exists keeps the user's edits), the daily index backup, the housekeeping clean-up at 04:00 (job history,
+/// cache trim), and the workspace's clean-up at 04:30 (phase 5c: its media, a report of its trash). Scans give what they find a deep analysis as Settings › Analysis › After a scan says at each run
/// (), like the scans started by hand. Thread-safe: the scheduler calls it from its loop.
///
public sealed class DesktopScheduleHost(AppSettings settings, Func database, Func archives) : IScheduleHost
@@ -41,6 +41,16 @@ public sealed class DesktopScheduleHost(AppSettings settings, FuncWhen the housekeeping runs.
public static readonly TimeOnly HousekeepingTime = new(4, 0);
+ ///
+ /// Clean-up of the workspace (phase 5c), daily at 04:30, with catch-up: the media of projects past Settings › Workspace ›
+ /// Clean after or Size limit (), and a report of its trash (),
+ /// which it never empties. It runs whether an archive is open or not.
+ ///
+ public const string WorkspaceCleanup = "workspace-cleanup";
+
+ /// When the workspace clean-up runs: after the housekeeping.
+ public static readonly TimeOnly WorkspaceCleanupTime = new(4, 30);
+
/// The PC's zone; tests set another.
public TimeZoneInfo TimeZone { get; init; } = TimeZoneInfo.Local;
@@ -54,6 +64,9 @@ public sealed class DesktopScheduleHost(AppSettings settings, Func CleanupSteps => archives()?.CleanupSteps.Select(s => s.Name).ToList() ?? [];
diff --git a/src/Chronos.App/Jobs/ScheduleText.cs b/src/Chronos.App/Jobs/ScheduleText.cs
index b3064aae..e9a8b16c 100644
--- a/src/Chronos.App/Jobs/ScheduleText.cs
+++ b/src/Chronos.App/Jobs/ScheduleText.cs
@@ -166,6 +166,7 @@ public static class ScheduleText
DesktopScheduleHost.ArchiveScan => "Jobs.Schedule.System.ArchiveScan",
DesktopScheduleHost.IndexBackup => "Jobs.Schedule.System.IndexBackup",
DesktopScheduleHost.Housekeeping => "Jobs.Schedule.System.Housekeeping",
+ DesktopScheduleHost.WorkspaceCleanup => "Jobs.Schedule.System.WorkspaceCleanup",
_ => null,
};
@@ -175,6 +176,8 @@ public static class ScheduleText
CleanupSteps.Audit => "Audit",
CleanupSteps.TrashReport => "TrashReport",
CacheTrimStep.StepName => "CacheTrim",
+ WorkspaceCleanStep.StepName => "WorkspaceClean",
+ WorkspaceTrashStep.StepName => "WorkspaceTrash",
_ => null,
};
diff --git a/src/Chronos.App/Jobs/WorkspaceCleanStep.cs b/src/Chronos.App/Jobs/WorkspaceCleanStep.cs
new file mode 100644
index 00000000..99003947
--- /dev/null
+++ b/src/Chronos.App/Jobs/WorkspaceCleanStep.cs
@@ -0,0 +1,63 @@
+using Chronos.App.Infrastructure;
+using Chronos.App.Workspace;
+using Chronos.Core.Localization;
+using Chronos.Data.Archiving.Jobs;
+using Chronos.Data.Housekeeping;
+using Chronos.Data.Workspaces;
+
+namespace Chronos.App.Jobs;
+
+///
+/// The desktop's clean-up step workspace-clean (phase 5c): removes the media of workspace projects in step with their
+/// home, those not opened for Settings › Workspace › Clean after, then the least recently used while the projects take more
+/// than Size limit (). Each project kept is logged with why. It needs no archive: the
+/// workspace-cleanup schedule runs it whether one is open or not. The trash is never emptied here.
+///
+public sealed class WorkspaceCleanStep(Func workspace) : ICleanupStep
+{
+ public const string StepName = "workspace-clean";
+
+ public string Name => StepName;
+
+ public async Task RunAsync(CleanupContext context, CleanupParameters parameters)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+ if (workspace() is not { } host || await host.CleanAsync(cleanAfter: true, cancellationToken: context.Cancellation).ConfigureAwait(false) is not { } report)
+ return Loc.L("Jobs.Log.WorkspaceUnavailable");
+ foreach (var kept in report.Kept)
+ context.Job.Log(Loc.L("Jobs.Log.WorkspaceKept", Named(kept.SequenceTitle, kept.Name, kept.IsMain), Reason(kept.Reason)));
+ if (report.Cleaned.Count == 0 && report.Kept.Count == 0) return Loc.L("Jobs.Log.WorkspaceNothing", Formatting.Bytes(report.UsedBefore));
+ foreach (var cleaned in report.Cleaned.Where(c => c.Trashed > 0))
+ context.Job.Log(Loc.L("Archive.Log.WorkspaceOriginalsTrashed", Named(cleaned.SequenceTitle, cleaned.Name, cleaned.IsMain), Formatting.Count(cleaned.Trashed)));
+ return Loc.L("Jobs.Log.WorkspaceCleaned", Formatting.Count(report.Cleaned.Count), Formatting.Bytes(report.Freed), Formatting.Count(report.Kept.Count));
+ }
+
+ /// "open in Edit", "renders not sent", …: why a project was kept, for the job log.
+ public static string Reason(WorkspaceKeep reason) => Loc.L("Jobs.Log.WorkspaceSkip." + reason);
+
+ /// "Harbour sunset · Main": a project as the job log names it (its sequence, then its name).
+ public static string Named(string sequenceTitle, string name, bool isMain)
+ {
+ var project = WorkspaceText.ProjectName(name, isMain);
+ return sequenceTitle is { Length: > 0 } title ? title + Loc.Separator + project : project;
+ }
+}
+
+///
+/// The desktop's clean-up step workspace-trash (phase 5c): reports what the workspace's trash holds (entries and
+/// size); it never deletes, emptying it stays the user's Settings › Workspace › Trash › Empty….
+///
+public sealed class WorkspaceTrashStep(Func workspace) : ICleanupStep
+{
+ public const string StepName = "workspace-trash";
+
+ public string Name => StepName;
+
+ public async Task RunAsync(CleanupContext context, CleanupParameters parameters)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+ if (workspace() is not { IsEnabled: true } host) return Loc.L("Jobs.Log.WorkspaceUnavailable");
+ var plan = await host.PlanTrashAsync(context.Cancellation).ConfigureAwait(false);
+ return Loc.L("Jobs.Log.WorkspaceTrash", Formatting.Count(plan.Items.Count), Formatting.Bytes(plan.Bytes));
+ }
+}
diff --git a/src/Chronos.App/Shell/ShellViewModel.cs b/src/Chronos.App/Shell/ShellViewModel.cs
index d0fc0999..e01d5b53 100644
--- a/src/Chronos.App/Shell/ShellViewModel.cs
+++ b/src/Chronos.App/Shell/ShellViewModel.cs
@@ -41,6 +41,8 @@ public sealed class ShellViewModel : LocalizedViewModel
Library = new LibraryViewModel(this);
Import = new ImportViewModel(this);
Sequence = new SequenceViewModel(this);
+ // The workspace's clean-up never takes the project open in Edit (phase 5c).
+ services.Workspace.OpenProject = () => Sequence.OpenProjectId;
Archive = new ArchiveViewModel(this);
Jobs = new JobsViewModel(this);
Server = new ServerViewModel(this);
diff --git a/src/Chronos.App/Workspace/WorkspaceDialogs.cs b/src/Chronos.App/Workspace/WorkspaceDialogs.cs
index 60467b4f..66290463 100644
--- a/src/Chronos.App/Workspace/WorkspaceDialogs.cs
+++ b/src/Chronos.App/Workspace/WorkspaceDialogs.cs
@@ -648,6 +648,15 @@ public sealed class RemoveCopyDialogViewModel : ArchiveDialogViewModel
new DialogFact(Loc.L("Editor.RemoveCopy.Size"), Formatting.Bytes(plan.Bytes)),
new DialogFact(Loc.L("Editor.RemoveCopy.Unsent"), Formatting.Count(plan.Unsent)),
new DialogFact(Loc.L("Editor.RemoveCopy.Changed"), Loc.L(plan.Modified ? "Editor.RemoveCopy.Yes" : "Editor.RemoveCopy.No")),
+ // Phase 5c: renders made here not sent yet, and originals the home lost (they go to the trash): shown only when there are some.
+ .. plan.UnsentRenders > 0
+ ? [new DialogFact(Loc.L("Editor.RemoveCopy.UnsentRenders"), Formatting.Count(plan.UnsentRenders),
+ Reason: WorkspaceText.ForHome("Tooltips.Editor.RemoveCopy.UnsentRenders", server))]
+ : Array.Empty(),
+ .. plan.LastOriginals > 0
+ ? [new DialogFact(Loc.L("Editor.RemoveCopy.LastOriginals"), Formatting.Count(plan.LastOriginals),
+ Reason: WorkspaceText.ForHome("Tooltips.Editor.RemoveCopy.LastOriginals", server))]
+ : Array.Empty(),
];
RemoveCommand = new AsyncRelayCommand(() => RunAsync(() => _remove(false)), () => !IsBusy && plan.IsSafe && !plan.Offline && !plan.Gone);
SendFirstCommand = new AsyncRelayCommand(() => RunAsync(_sendFirst), () => !IsBusy && !plan.IsSafe && !plan.Conflict && !plan.Offline && !plan.Gone && !plan.Damaged);
diff --git a/src/Chronos.App/Workspace/WorkspaceHost.Cleanup.cs b/src/Chronos.App/Workspace/WorkspaceHost.Cleanup.cs
index 2a1e1f88..c1cb9ffb 100644
--- a/src/Chronos.App/Workspace/WorkspaceHost.Cleanup.cs
+++ b/src/Chronos.App/Workspace/WorkspaceHost.Cleanup.cs
@@ -1,5 +1,11 @@
using System.IO;
+using Chronos.Core.Diagnostics;
+using Chronos.Core.Localization;
+using Chronos.Core.Model;
using Chronos.Core.Project;
+using Chronos.Data;
+using Chronos.Data.Archiving;
+using Chronos.Data.Projects;
using Chronos.Data.Workspaces;
namespace Chronos.App.Workspace;
@@ -36,67 +42,246 @@ public sealed record WorkspaceTrashPlan(string Folder, IReadOnlyList
-/// The workspace's clean-up side (phase 5c, P4): its usage, the plan and emptying of its trash, and what a local copy's removal
-/// keeps of renders not sent and originals the home lost. Stubs until the clean-up lands: usage and the trash read as empty,
-/// and a removal finds nothing more to keep.
+/// The workspace's clean-up side (phase 5c, P4): its usage, the clean-up of media (: Settings ›
+/// Workspace › Clean after and Size limit, run by the workspace-cleanup schedule and, for the size limit, after each
+/// copy of media), the plan and emptying of its trash, and what a local copy's removal keeps of renders not sent and
+/// originals the home lost.
///
public sealed partial class WorkspaceHost
{
- /// What the workspace takes of its drive (), measured off the UI thread.
- public Task UsageAsync(CancellationToken cancellationToken = default)
+ private readonly SemaphoreSlim _cleaning = new(1, 1);
+
+ ///
+ /// The workspace project open in Edit now (any thread may ask); null when none is. The clean-up never removes the media of
+ /// that one. Unset (as in a test without the shell), no project counts as open.
+ ///
+ public Func? OpenProject { get; set; }
+
+ /// What the workspace takes of its drive (), measured off the UI thread; none while its folder is not made.
+ public Task UsageAsync(CancellationToken cancellationToken = default) => Task.Run(() =>
{
- cancellationToken.ThrowIfCancellationRequested();
- return Task.FromResult(WorkspaceUsage.None);
- }
+ var root = Root;
+ if (!Directory.Exists(root)) return WorkspaceUsage.None;
+ var media = 0L;
+ foreach (var folder in Directory.EnumerateDirectories(root).Where(d => Guid.TryParseExact(Path.GetFileName(d), "N", out _)))
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ media += WorkspaceCleaner.Measure(Path.Combine(folder, WorkspaceProject.MediaFolder)).Bytes;
+ }
+ var trash = WorkspaceTrash.List(root, cancellationToken);
+ return new WorkspaceUsage(media, WorkspaceCleaner.Measure(root).Bytes, trash.Bytes, trash.Entries.Count);
+ }, cancellationToken);
/// The plan of emptying the workspace's trash (); nothing is erased.
- public Task PlanTrashAsync(CancellationToken cancellationToken = default)
+ public Task PlanTrashAsync(CancellationToken cancellationToken = default) => Task.Run(() =>
{
- cancellationToken.ThrowIfCancellationRequested();
- return Task.FromResult(new WorkspaceTrashPlan(Path.Combine(Root, TrashFolder), [], 0, string.Empty));
- }
+ var listing = WorkspaceTrash.List(Root, cancellationToken);
+ return new WorkspaceTrashPlan(listing.Folder, [.. listing.Entries.Select(e => new WorkspaceTrashItem(e.Name, e.Bytes, e.Files, e.Trashed))], listing.Bytes,
+ listing.Fingerprint);
+ }, cancellationToken);
///
/// Erases the entries of from the workspace's trash for good, after the user typed their number;
/// refused when the trash changed since the plan (Errors.Workspace.TrashChanged).
///
/// The trash changed since the plan; nothing was erased.
+ /// An entry could not be erased (a file held open); the others were.
public Task EmptyTrashAsync(WorkspaceTrashPlan plan, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(plan);
- throw new NotImplementedException("Emptying the workspace's trash comes with phase 5c (P4).");
+ return Task.Run(() =>
+ {
+ EnsureNotMoving();
+ var listing = new WorkspaceTrashListing(plan.Folder, [.. plan.Items.Select(i => new WorkspaceTrashEntry(i.Name, i.Bytes, i.Files, i.Trashed))], plan.Bytes,
+ plan.Fingerprint);
+ try
+ {
+ var (items, bytes) = WorkspaceTrash.Empty(Root, listing, cancellationToken);
+ return new WorkspaceTrashResult(items, bytes);
+ }
+ catch (WorkspaceTrashChangedException ex)
+ {
+ Log.Info("workspace", $"The workspace's trash was not emptied: {ex.Message}");
+ throw new WorkspaceException(Loc.L("Errors.Workspace.TrashChanged"), ex);
+ }
+ }, cancellationToken);
+ }
+
+ ///
+ /// One run of the workspace's clean-up (): with , Settings ›
+ /// Workspace › Clean after, then Size limit (the workspace-clean step of the schedule); without, the size limit
+ /// alone, never taking (after a copy of its media). Null when the workspace cannot be
+ /// cleaned now (the index not open, the folder being moved); a folder not made yet has nothing to clean. One run at a time.
+ ///
+ public async Task CleanAsync(bool cleanAfter, Guid? justCopied = null, CancellationToken cancellationToken = default)
+ {
+ if (_db() is not { } db || IsMoving || !IsEnabled) return null;
+ var root = Root;
+ if (!Directory.Exists(root)) return WorkspaceCleanReport.Nothing;
+ var options = new WorkspaceCleanOptions
+ {
+ CleanAfterDays = cleanAfter ? Math.Max(0, _settings.WorkspaceCleanAfterDays) : 0,
+ SizeLimitBytes = Math.Max(0, _settings.WorkspaceSizeLimitGb) * (1L << 30),
+ Opened = OpenedSnapshot(),
+ IsOpen = id => OpenProject?.Invoke() == id,
+ JustCopied = justCopied,
+ };
+ if (options is { CleanAfterDays: 0, SizeLimitBytes: 0 }) return WorkspaceCleanReport.Nothing;
+ await _cleaning.WaitAsync(cancellationToken).ConfigureAwait(false);
+ try
+ {
+ var cleaner = new WorkspaceCleaner(Sync, db, HomeOf) { LockWait = LockWait };
+ return await Task.Run(() => cleaner.CleanAsync(options, cancellationToken), cancellationToken).ConfigureAwait(false);
+ }
+ finally
+ {
+ _cleaning.Release();
+ }
+ }
+
+ ///
+ /// A job of the engine changed (any thread): once a copy of media into this workspace is done, the size limit runs, never
+ /// taking the project just copied. Nothing else follows from a job here.
+ ///
+ public void OnJobChanged(Job job)
+ {
+ ArgumentNullException.ThrowIfNull(job);
+ if (job is not { Kind: JobKind.WorkspaceCopy, State: JobState.Done } || _settings.WorkspaceSizeLimitGb <= 0) return;
+ if (WorkspaceJobs.CopyParameters(job) is not { } copied
+ || !string.Equals(Path.TrimEndingDirectorySeparator(Path.GetFullPath(copied.WorkspaceRoot)), Path.TrimEndingDirectorySeparator(Path.GetFullPath(Root)),
+ StringComparison.OrdinalIgnoreCase))
+ return;
+ _ = Task.Run(async () =>
+ {
+ try
+ {
+ if (await CleanAsync(cleanAfter: false, copied.ProjectId).ConfigureAwait(false) is { Cleaned.Count: > 0 } report)
+ Log.Info("workspace", $"Size limit after the copy of project {copied.ProjectId}: {report.Cleaned.Count} project(s) cleaned, {report.Freed} bytes freed");
+ }
+ catch (Exception ex) when (ex is not OutOfMemoryException)
+ {
+ Log.Warning("workspace", $"The size limit after the copy of project {copied.ProjectId} did not run", ex);
+ }
+ });
+ }
+
+ /// When each project was opened last, as Settings hold it now (written on the UI thread: copied until a copy reads whole).
+ private IReadOnlyDictionary OpenedSnapshot()
+ {
+ for (var attempt = 0; ; attempt++)
+ {
+ try
+ {
+ return new Dictionary(_settings.WorkspaceOpened);
+ }
+ catch (InvalidOperationException) when (attempt < 5)
+ {
+ // Written while it was copied: copied again.
+ }
+ }
}
///
/// What a local copy's removal plan counts besides its versions (,
- /// ): renders of its ledger not sent, and originals the home no longer holds.
+ /// ): renders of its ledger not sent, and originals the home no longer
+ /// holds (all of them while the home cannot be asked: they go to the trash then, never deleted).
///
- private Task<(int UnsentRenders, int LastOriginals)> RemovalMediaAsync(WorkspaceProject project, CancellationToken cancellationToken)
+ private async Task<(int UnsentRenders, int LastOriginals)> RemovalMediaAsync(WorkspaceProject project, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(project);
- cancellationToken.ThrowIfCancellationRequested();
- return Task.FromResult((0, 0));
+ var unsent = WorkspaceCleaner.UnsentRenders(project);
+ var last = (await LastOriginalsOfAsync(project, cancellationToken).ConfigureAwait(false)).Count;
+ return (unsent, last);
}
- /// A removal without Discard is refused while the project's ledger holds renders not sent (Send first sends them).
+ ///
+ /// A removal without Discard is refused while the project's ledger holds renders not sent: Send first queues their
+ /// sending home (unless one is queued or running already), and the copy goes once they are there.
+ ///
/// Renders wait to be sent.
- private Task EnsureRendersSentAsync(WorkspaceProject project, BundleWorkspace workspace, CancellationToken cancellationToken)
+ private async Task EnsureRendersSentAsync(WorkspaceProject project, BundleWorkspace workspace, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(project);
ArgumentNullException.ThrowIfNull(workspace);
- cancellationToken.ThrowIfCancellationRequested();
- return Task.CompletedTask;
+ if (WorkspaceCleaner.UnsentRenders(project) == 0) return;
+ try
+ {
+ await QueueRenderSendAsync(project, workspace, cancellationToken).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (ex is DatabaseException or InvalidOperationException or IOException or InvalidDataException)
+ {
+ Log.Warning("workspace", $"The renders of project {project.ProjectId} could not be queued to be sent", ex);
+ }
+ throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.UnsentRenders", !workspace.Home.IsArchive));
}
///
/// Before a removed copy's media are deleted, under the project's lease: the originals the home no longer holds with the
/// same SHA-256 moved into (the copy's trash entry), never deleted.
///
- private Task KeepLastOriginalsAsync(WorkspaceProject project, string aside, CancellationToken cancellationToken)
+ private async Task KeepLastOriginalsAsync(WorkspaceProject project, string aside, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(project);
ArgumentException.ThrowIfNullOrEmpty(aside);
- cancellationToken.ThrowIfCancellationRequested();
- return Task.CompletedTask;
+ // The working state went into the entry first: the home is read from there.
+ BundleHome? home = null;
+ try
+ {
+ home = ProjectBundle.Load(Path.Combine(aside, WorkspaceProject.BundleFile)).Workspace?.Home;
+ }
+ catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
+ {
+ Log.Info("workspace", $"The home of removed project {project.ProjectId} is not known: every original it holds is kept ({ex.Message})");
+ }
+ var last = await LastOriginalsOfAsync(project, cancellationToken, home, known: true).ConfigureAwait(false);
+ if (last.Count == 0) return;
+ var moved = WorkspaceCleaner.SetOriginalsAside(project, last, aside);
+ Log.Info("workspace", $"{moved} original(s) of project {project.ProjectId} its home no longer holds kept in {aside}");
+ }
+
+ ///
+ /// The frames whose original the workspace holds and the home no longer holds as it is (every one while the home cannot
+ /// be asked); the home is the working state's, else () .
+ ///
+ private async Task> LastOriginalsOfAsync(WorkspaceProject project, CancellationToken cancellationToken, BundleHome? named = null,
+ bool known = false)
+ {
+ WorkspaceMedia? media;
+ try
+ {
+ media = project.ReadMedia();
+ }
+ catch (InvalidDataException ex)
+ {
+ Log.Info("workspace", $"The media index of project {project.ProjectId} cannot be read: no original is counted from it ({ex.Message})");
+ return [];
+ }
+ if (media is null || !media.Frames.Any(f => f.HasOriginal)) return [];
+ HomeFrames? held = null;
+ try
+ {
+ var homeOf = known ? named : project.ReadBundle().Workspace!.Home;
+ if (homeOf is not null && HomeOf(homeOf) is { } home) held = await home.FramesAsync(cancellationToken).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (ex is HomeUnavailableException or ProjectException or DatabaseException or IOException or InvalidDataException)
+ {
+ // Not known: every original counts as the last one, and goes to the trash.
+ Log.Info("workspace", $"The home of project {project.ProjectId} could not be asked for its frames: {ex.Message}");
+ }
+ return WorkspaceCleaner.LastOriginals(media, held);
+ }
+
+ /// Queues the sending of the project's renders not sent yet (), unless one is queued or running.
+ private async Task QueueRenderSendAsync(WorkspaceProject project, BundleWorkspace workspace, CancellationToken cancellationToken)
+ {
+ if (_engine() is not { } engine || _db() is not { } db) return;
+ foreach (var pending in await db.Jobs.ListPendingAsync(JobKind.WorkspaceSend, workspace.Home.SequenceId, cancellationToken).ConfigureAwait(false))
+ {
+ if (WorkspaceJobs.SendParameters(pending)?.ProjectId == project.ProjectId) return;
+ }
+ var title = project.ReadBundle().Sequence.Title ?? string.Empty;
+ var job = await engine.EnqueueAsync(WorkspaceJobs.Send(workspace.Home.SequenceId, title, Store.Root, project.ProjectId, [], workspace.Home.Server),
+ cancellationToken: cancellationToken).ConfigureAwait(false);
+ Log.Info("workspace", $"The renders of project {project.ProjectId} not sent yet are queued to be sent (job {job.Id})");
}
}
diff --git a/src/Chronos.App/Workspace/WorkspaceHost.cs b/src/Chronos.App/Workspace/WorkspaceHost.cs
index 61d5a5a5..3352ef2e 100644
--- a/src/Chronos.App/Workspace/WorkspaceHost.cs
+++ b/src/Chronos.App/Workspace/WorkspaceHost.cs
@@ -1087,7 +1087,7 @@ public sealed partial class WorkspaceHost
{
var workspace = bundle.Workspace!;
return new WorkspaceEntry(project.ProjectId, workspace.Home.SequenceId, workspace.Name, workspace.IsMain, workspace.Home,
- bundle.Sequence.Title is { Length: > 0 } title ? title : bundle.Sequence.Folder, File.Exists(project.MediaIndexPath), bundle.Saved);
+ bundle.Sequence.Title is { Length: > 0 } title ? title : bundle.Sequence.Folder, WorkspaceCleaner.HoldsMedia(project), bundle.Saved);
}
///
diff --git a/src/Chronos.App/Workspace/WorkspaceTrashDialog.cs b/src/Chronos.App/Workspace/WorkspaceTrashDialog.cs
new file mode 100644
index 00000000..ab30a89c
--- /dev/null
+++ b/src/Chronos.App/Workspace/WorkspaceTrashDialog.cs
@@ -0,0 +1,109 @@
+using System.Globalization;
+using System.Windows.Input;
+using Chronos.App.Archiving;
+using Chronos.App.Infrastructure;
+using Chronos.Core.Diagnostics;
+using Chronos.Core.Localization;
+using Chronos.Ui.Mvvm;
+
+namespace Chronos.App.Workspace;
+
+/// One entry of the workspace's trash as Empty… lists it: "name · 1.2 GB · 04/11/2026".
+public sealed class WorkspaceTrashRowViewModel(WorkspaceTrashItem item)
+{
+ public WorkspaceTrashItem Item { get; } = item;
+
+ public string Text => Loc.L("Settings.Workspace.TrashPlan.Item", Item.Name, Formatting.Bytes(Item.Bytes),
+ Formatting.Date(Item.Trashed) + " " + Formatting.TimeOfDay(Item.Trashed));
+}
+
+///
+/// Settings › Workspace › Trash › Empty… (phase 5c): the plan (every entry of the workspace's trash, their number and size,
+/// ), then Erase for good, which enables only once the user typed the number of entries; the
+/// emptying erases exactly the entries listed, and is refused when the trash changed since (the plan is shown again then).
+/// Keep closes it, erasing nothing.
+///
+public sealed class WorkspaceTrashDialogViewModel : ArchiveDialogViewModel
+{
+ private readonly Func> _empty;
+ private readonly Action? _emptied;
+ private string _typed = string.Empty;
+
+ /// Erases the plan's entries ().
+ /// Told what was erased, once the dialog closes on it (the page measures the workspace again).
+ public WorkspaceTrashDialogViewModel(WorkspaceTrashPlan plan, Func> empty, Action? emptied,
+ Action close)
+ : base(close)
+ {
+ ArgumentNullException.ThrowIfNull(plan);
+ ArgumentNullException.ThrowIfNull(empty);
+ Plan = plan;
+ _empty = empty;
+ _emptied = emptied;
+ Rows = [.. plan.Items.Select(i => new WorkspaceTrashRowViewModel(i))];
+ EraseCommand = new AsyncRelayCommand(EraseAsync, () => CanErase);
+ }
+
+ public WorkspaceTrashPlan Plan { get; }
+
+ public IReadOnlyList Rows { get; }
+
+ public string Heading => Loc.L("Settings.Workspace.TrashPlan.Title");
+
+ public string Message => Loc.L("Settings.Workspace.TrashPlan.Message");
+
+ /// "Entries: 3".
+ public string ItemsText => Loc.L("Settings.Workspace.TrashPlan.Items", Formatting.Count(Plan.Items.Count));
+
+ /// "Size: 1.2 GB".
+ public string SizeText => Loc.L("Settings.Workspace.TrashPlan.Size", Formatting.Bytes(Plan.Bytes));
+
+ /// What the user types to confirm: the number of entries, in plain digits.
+ public string Confirmation => Plan.Items.Count.ToString(CultureInfo.InvariantCulture);
+
+ /// "Type the number of entries, 3, to confirm".
+ public string TypedPrompt => Loc.L("Settings.Workspace.TrashPlan.Type", Confirmation);
+
+ /// What the user typed; Erase for good enables once it is .
+ public string Typed
+ {
+ get => _typed;
+ set
+ {
+ if (!Set(ref _typed, value ?? string.Empty)) return;
+ OnPropertyChanged(nameof(CanErase));
+ CommandManager.InvalidateRequerySuggested();
+ }
+ }
+
+ /// The trash holds something, the number typed matches, and nothing runs.
+ public bool CanErase => !IsBusy && !Plan.IsEmpty && string.Equals(_typed.Trim(), Confirmation, StringComparison.Ordinal);
+
+ public ICommand EraseCommand { get; }
+
+ public string EraseToolTip => Plan.IsEmpty ? Loc.L("Tooltips.Settings.Workspace.EmptyTrash.Disabled") : Loc.L("Tooltips.Settings.Workspace.TrashPlan.Action");
+
+ public string KeepToolTip => Loc.L("Tooltips.Settings.Workspace.TrashPlan.Keep");
+
+ private async Task EraseAsync()
+ {
+ if (!CanErase) return;
+ ClearError();
+ IsBusy = true;
+ OnPropertyChanged(nameof(CanErase));
+ try
+ {
+ var result = await _empty(Plan);
+ IsBusy = false;
+ Close();
+ _emptied?.Invoke(result);
+ }
+ catch (Exception ex) when (ex is not OutOfMemoryException)
+ {
+ Log.Warning("workspace", "The workspace's trash was not emptied", ex);
+ ShowMessage(WorkspaceText.Failure(ex), ex.Message);
+ IsBusy = false;
+ OnPropertyChanged(nameof(CanErase));
+ }
+ }
+}
diff --git a/src/Chronos.App/Workspace/WorkspaceTrashDialog.xaml b/src/Chronos.App/Workspace/WorkspaceTrashDialog.xaml
new file mode 100644
index 00000000..081ba296
--- /dev/null
+++ b/src/Chronos.App/Workspace/WorkspaceTrashDialog.xaml
@@ -0,0 +1,58 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Chronos.Data/Workspaces/WorkspaceCleaner.cs b/src/Chronos.Data/Workspaces/WorkspaceCleaner.cs
new file mode 100644
index 00000000..b3e560bb
--- /dev/null
+++ b/src/Chronos.Data/Workspaces/WorkspaceCleaner.cs
@@ -0,0 +1,471 @@
+using Chronos.Core.Archiving;
+using Chronos.Core.Diagnostics;
+using Chronos.Core.Model;
+using Chronos.Core.Project;
+using Chronos.Data.Projects;
+
+namespace Chronos.Data.Workspaces;
+
+/// Why the workspace's clean-up kept the media of a project it would have cleaned (each reason is logged with the project).
+public enum WorkspaceKeep
+{
+ /// The project is open in Edit.
+ Open,
+
+ /// The project is not in step with its home: changes not saved, versions not sent or not taken, a conflict, a damaged version.
+ NotInSync,
+
+ /// The project's home cannot be asked now: whether it holds everything is not known.
+ Offline,
+
+ /// A copy, render or send of the project, or a move of the workspace, is queued, running or paused.
+ Jobs,
+
+ /// The project's ledger holds renders made here that its home does not have yet.
+ UnsentRenders,
+
+ /// The project's working state, media index or render ledger cannot be read.
+ Unreadable,
+
+ /// The project holds no media files to remove.
+ NoMedia,
+
+ /// The project's media were copied just now (the size limit after a copy never takes that one).
+ JustCopied,
+}
+
+///
+/// What a run of the workspace's clean-up applies (phase 5c, Settings › Workspace): Clean after (projects not opened for that
+/// many days) and Size limit (the projects' folders above it, the least recently used first); 0 turns either off.
+///
+public sealed record WorkspaceCleanOptions
+{
+ /// Days a project may go unopened before its media are removed; 0 never removes them for their age.
+ public int CleanAfterDays { get; init; }
+
+ /// Bytes the projects' folders may take (the trash is not counted: only the user empties it); 0 sets no limit.
+ public long SizeLimitBytes { get; init; }
+
+ /// When each project was opened last (Settings' WorkspaceOpened); a project not listed counts from when its working state was saved.
+ public IReadOnlyDictionary Opened { get; init; } = new Dictionary();
+
+ /// Whether a project is open in Edit now (asked again under the project's lease, just before anything goes).
+ public Func IsOpen { get; init; } = _ => false;
+
+ /// The project whose media a copy just brought (the size limit after a copy): never cleaned by this run.
+ public Guid? JustCopied { get; init; }
+
+ /// The time the ages count from.
+ public DateTimeOffset Now { get; init; } = DateTimeOffset.UtcNow;
+}
+
+/// A project whose media the clean-up removed: the bytes freed and the originals set aside in the workspace's trash.
+public sealed record WorkspaceCleanedProject(Guid ProjectId, string Name, bool IsMain, string SequenceTitle, long Freed, int Trashed);
+
+/// A project the clean-up would have cleaned and kept, with why.
+public sealed record WorkspaceKeptProject(Guid ProjectId, string Name, bool IsMain, string SequenceTitle, WorkspaceKeep Reason);
+
+/// What a run of the workspace's clean-up did: the projects cleaned, those kept with why, and the projects' bytes before and after.
+public sealed record WorkspaceCleanReport(IReadOnlyList Cleaned, IReadOnlyList Kept, long UsedBefore, long UsedAfter)
+{
+ /// A run over a workspace with nothing in it.
+ public static WorkspaceCleanReport Nothing { get; } = new([], [], 0, 0);
+
+ /// The bytes the run freed.
+ public long Freed => Cleaned.Sum(c => c.Freed);
+
+ /// The originals the run set aside in the workspace's trash (their home no longer holds them).
+ public int Trashed => Cleaned.Sum(c => c.Trashed);
+}
+
+///
+/// The workspace's clean-up (phase 5c, P4): removes the media of projects whose home holds everything they hold, so they are
+/// copied again when next opened. A project is cleaned only when it is in step with its home, asked now (never while the
+/// home is out of reach), not open in Edit, with no copy, render or send of it queued or running (nor a move of the
+/// workspace), and no local render waiting to be sent. Cleaning removes media/proxies and media/originals
+/// (the media index stays, its frames naming no file: ) and the renders of
+/// exports/ the home took; never the working state, the versions, the sync state, the deep report or a render not
+/// sent. An original is deleted only when the home still holds the same frame with the same SHA-256; otherwise it is moved
+/// to the workspace's trash (.trash/<id>-<ticks>/originals). The trash itself is never emptied here.
+///
+public sealed class WorkspaceCleaner
+{
+ private static readonly JobKind[] ProjectJobs = [JobKind.WorkspaceCopy, JobKind.WorkspaceRender, JobKind.WorkspaceSend];
+
+ private readonly WorkspaceSync _sync;
+ private readonly ChronosDatabase _db;
+ private readonly Func _homes;
+
+ /// The home of a workspace project; null for one this PC cannot reach now.
+ public WorkspaceCleaner(WorkspaceSync sync, ChronosDatabase db, Func homes)
+ {
+ ArgumentNullException.ThrowIfNull(sync);
+ ArgumentNullException.ThrowIfNull(db);
+ ArgumentNullException.ThrowIfNull(homes);
+ _sync = sync;
+ _db = db;
+ _homes = homes;
+ }
+
+ /// How long a project another writer holds is waited for; past it the project is kept ().
+ public TimeSpan LockWait { get; init; } = TimeSpan.FromSeconds(30);
+
+ ///
+ /// One run: the projects not opened for , oldest first, then, while the
+ /// projects' folders take more than , the least recently used others.
+ /// Each project the policies name is cleaned or kept with its reason.
+ ///
+ public async Task CleanAsync(WorkspaceCleanOptions options, CancellationToken cancellationToken = default)
+ {
+ ArgumentNullException.ThrowIfNull(options);
+ var candidates = new List();
+ var used = 0L;
+ foreach (var project in _sync.Store.List())
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var candidate = Candidate.Of(project, options);
+ used += candidate.FolderBytes;
+ candidates.Add(candidate);
+ }
+ var before = used;
+ var cleaned = new List();
+ var kept = new List();
+ var named = new HashSet();
+ var moving = await _db.Jobs.HasPendingAsync([JobKind.WorkspaceMove], null, cancellationToken).ConfigureAwait(false);
+
+ async Task CleanOneAsync(Candidate candidate)
+ {
+ named.Add(candidate.Project.ProjectId);
+ var (reason, freed, trashed) = await TryCleanAsync(candidate, options, moving, cancellationToken).ConfigureAwait(false);
+ if (reason is { } why)
+ {
+ kept.Add(new WorkspaceKeptProject(candidate.Project.ProjectId, candidate.Name, candidate.IsMain, candidate.Title, why));
+ return;
+ }
+ cleaned.Add(new WorkspaceCleanedProject(candidate.Project.ProjectId, candidate.Name, candidate.IsMain, candidate.Title, freed, trashed));
+ used -= freed;
+ }
+
+ if (options.CleanAfterDays > 0)
+ {
+ var cutoff = options.Now - TimeSpan.FromDays(options.CleanAfterDays);
+ foreach (var candidate in candidates.Where(c => c.Targeted && c.LastUsed < cutoff).OrderBy(c => c.LastUsed).ToList())
+ await CleanOneAsync(candidate).ConfigureAwait(false);
+ }
+ if (options.SizeLimitBytes > 0)
+ {
+ foreach (var candidate in candidates.Where(c => c.Targeted && !named.Contains(c.Project.ProjectId)).OrderBy(c => c.LastUsed).ToList())
+ {
+ if (used <= options.SizeLimitBytes) break;
+ await CleanOneAsync(candidate).ConfigureAwait(false);
+ }
+ }
+ foreach (var project in cleaned)
+ Log.Info("workspace", $"Media of project {project.ProjectId} ('{project.Name}') removed by the clean-up: {project.Freed} bytes freed, {project.Trashed} original(s) kept in the trash");
+ foreach (var project in kept) Log.Info("workspace", $"Media of project {project.ProjectId} ('{project.Name}') kept by the clean-up: {project.Reason}");
+ return new WorkspaceCleanReport(cleaned, kept, before, Math.Max(0, used));
+ }
+
+ /// The frames of whose original the home no longer holds as it is here (all of them when the home's frames are not known).
+ public static IReadOnlyList LastOriginals(WorkspaceMedia? media, HomeFrames? home)
+ {
+ if (media is null) return [];
+ var held = home?.Frames.ToDictionary(f => f.Id);
+ return [.. media.Frames.Where(f => f.HasOriginal && (held is null || !Holds(held, f)))];
+
+ static bool Holds(Dictionary held, WorkspaceFrame frame) =>
+ frame.OriginalSha256 is { Length: > 0 } sha && held.TryGetValue(frame.Id, out var there) && (there.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) == 0
+ && string.Equals(there.Sha256, sha, StringComparison.OrdinalIgnoreCase);
+ }
+
+ ///
+ /// Moves the originals of the project holds into 's originals
+ /// folder (a workspace trash entry, made when needed); the caller holds the project's lease. Returns how many moved.
+ ///
+ /// An original could not be moved; those moved before it stay in the trash.
+ public static int SetOriginalsAside(WorkspaceProject project, IEnumerable frames, string aside)
+ {
+ ArgumentNullException.ThrowIfNull(project);
+ ArgumentNullException.ThrowIfNull(frames);
+ ArgumentException.ThrowIfNullOrEmpty(aside);
+ var moved = 0;
+ foreach (var frame in frames)
+ {
+ if (frame.Original is not { } relative) continue;
+ var source = project.MediaFile(relative);
+ if (!File.Exists(source)) continue;
+ var folder = Path.Combine(aside, WorkspaceProject.OriginalsFolder);
+ Directory.CreateDirectory(folder);
+ File.Move(source, Path.Combine(folder, Path.GetFileName(source)));
+ moved++;
+ }
+ return moved;
+ }
+
+ ///
+ /// The local renders of the project its home does not have yet (its ledger's unsent entries); a ledger that cannot be
+ /// read counts the files of exports/ besides it, at least one: whether they went home is not known.
+ ///
+ public static int UnsentRenders(WorkspaceProject project)
+ {
+ ArgumentNullException.ThrowIfNull(project);
+ try
+ {
+ return project.ReadRenders().Unsent.Count;
+ }
+ catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
+ {
+ Log.Warning("workspace", $"The render ledger of project {project.ProjectId} cannot be read: its renders count as not sent", ex);
+ var files = Directory.Exists(project.ExportsDirectory)
+ ? Directory.EnumerateFiles(project.ExportsDirectory, "*", SearchOption.AllDirectories)
+ .Count(f => !string.Equals(Path.GetFileName(f), WorkspaceProject.RendersFileName, StringComparison.OrdinalIgnoreCase))
+ : 0;
+ return Math.Max(1, files);
+ }
+ }
+
+ ///
+ /// The workspace holds the project's media to edit: a media index whose files the clean-up did not remove (the folders of
+ /// proxies or originals there say so at once; otherwise the index is read).
+ ///
+ public static bool HoldsMedia(WorkspaceProject project)
+ {
+ ArgumentNullException.ThrowIfNull(project);
+ if (!File.Exists(project.MediaIndexPath)) return false;
+ if (Directory.Exists(project.ProxiesDirectory) || Directory.Exists(project.OriginalsDirectory)) return true;
+ try
+ {
+ return project.ReadMedia() is { IsCleaned: false };
+ }
+ catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
+ {
+ // The index is there: whatever it holds, opening it says so.
+ return true;
+ }
+ }
+
+ /// Files and bytes under , leases left out; nothing when it is not there.
+ public static (int Files, long Bytes) Measure(string folder)
+ {
+ var (files, bytes) = (0, 0L);
+ if (!Directory.Exists(folder)) return (files, bytes);
+ foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", SearchOption.AllDirectories))
+ {
+ if (WorkspaceProject.IsLeaseFile(file.Name)) continue;
+ files++;
+ bytes += file.Length;
+ }
+ return (files, bytes);
+ }
+
+ /// The project cleaned, or why it is kept.
+ private async Task<(WorkspaceKeep? Kept, long Freed, int Trashed)> TryCleanAsync(Candidate candidate, WorkspaceCleanOptions options, bool moving,
+ CancellationToken cancellationToken)
+ {
+ var project = candidate.Project;
+ var id = project.ProjectId;
+ if (candidate.Unreadable || candidate.Bundle is not { Workspace: { } workspace }) return (WorkspaceKeep.Unreadable, 0, 0);
+ if (options.JustCopied == id) return (WorkspaceKeep.JustCopied, 0, 0);
+ if (options.IsOpen(id)) return (WorkspaceKeep.Open, 0, 0);
+ if (moving || await BusyAsync(id, workspace.Home.SequenceId, cancellationToken).ConfigureAwait(false)) return (WorkspaceKeep.Jobs, 0, 0);
+ if (candidate.CleanableBytes == 0) return (WorkspaceKeep.NoMedia, 0, 0);
+ if (ReadLedger(project) is not { } ledger) return (WorkspaceKeep.Unreadable, 0, 0);
+ if (ledger.Unsent.Count > 0) return (WorkspaceKeep.UnsentRenders, 0, 0);
+ if (_homes(workspace.Home) is not { } home) return (WorkspaceKeep.Offline, 0, 0);
+ WorkspaceStatus status;
+ try
+ {
+ status = await _sync.StatusAsync(id, home, cancellationToken).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (ex is ProjectException or DatabaseException or IOException or InvalidDataException or LeaseUnavailableException)
+ {
+ Log.Info("workspace", $"The home of project {id} could not be asked for the clean-up: {ex.Message}");
+ return (WorkspaceKeep.Offline, 0, 0);
+ }
+ if (status.Offline && status.State != WorkspaceState.Gone) return (WorkspaceKeep.Offline, 0, 0);
+ if (status.State != WorkspaceState.InSync) return (WorkspaceKeep.NotInSync, 0, 0);
+ // The home's frames, asked now: an original goes only when the home holds the same one.
+ HomeFrames? held = null;
+ if (candidate.Media!.Frames.Any(f => f.HasOriginal))
+ {
+ try
+ {
+ held = await home.FramesAsync(cancellationToken).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (ex is HomeUnavailableException or ProjectException or DatabaseException or IOException)
+ {
+ Log.Info("workspace", $"The frames of project {id}'s home could not be read for the clean-up: {ex.Message}");
+ return (WorkspaceKeep.Offline, 0, 0);
+ }
+ }
+ IDisposable lease;
+ try
+ {
+ lease = await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false);
+ }
+ catch (LeaseUnavailableException)
+ {
+ return (WorkspaceKeep.Jobs, 0, 0);
+ }
+ using (lease)
+ {
+ // Asked again under the lease: the editor may have opened it, a save or a render may have come meanwhile.
+ if (options.IsOpen(id)) return (WorkspaceKeep.Open, 0, 0);
+ var local = await _sync.StatusAsync(id, null, cancellationToken).ConfigureAwait(false);
+ if (local.State != WorkspaceState.InSync) return (WorkspaceKeep.NotInSync, 0, 0);
+ if (ReadLedger(project) is not { } renders) return (WorkspaceKeep.Unreadable, 0, 0);
+ if (renders.Unsent.Count > 0) return (WorkspaceKeep.UnsentRenders, 0, 0);
+ WorkspaceMedia? media;
+ try
+ {
+ media = project.ReadMedia();
+ }
+ catch (InvalidDataException)
+ {
+ return (WorkspaceKeep.Unreadable, 0, 0);
+ }
+ if (media is null || media.IsCleaned) return (WorkspaceKeep.NoMedia, 0, 0);
+ var (freed, trashed) = Clear(project, media, renders, held, options.Now);
+ return (null, freed, trashed);
+ }
+ }
+
+ ///
+ /// Removes the project's media and its sent renders, under its lease: the originals the home lost into the trash first,
+ /// then the media index rewritten with no file (so nothing ever names a file that is gone), then the sent renders, then
+ /// the folders of proxies and originals. A file that cannot be deleted (held open) stays, and is logged.
+ ///
+ private static (long Freed, int Trashed) Clear(WorkspaceProject project, WorkspaceMedia media, WorkspaceRenders renders, HomeFrames? held, DateTimeOffset now)
+ {
+ var before = Cleanable(project, renders);
+ var lost = LastOriginals(media, held);
+ var trashed = 0;
+ var trashedBytes = 0L;
+ if (lost.Count > 0)
+ {
+ trashedBytes = lost.Where(f => File.Exists(project.MediaFile(f.Original!))).Sum(f => new FileInfo(project.MediaFile(f.Original!)).Length);
+ var aside = WorkspaceTrash.NewEntry(project.Store.Root, project.ProjectId, now.UtcDateTime);
+ trashed = SetOriginalsAside(project, lost, aside);
+ Log.Info("workspace", $"{trashed} original(s) of project {project.ProjectId} its home no longer holds kept in {aside}");
+ }
+ project.WriteMedia(media with
+ {
+ Frames = [.. media.Frames.Select(f => f with { File = null, FileSha256 = null, FileBytes = 0, FileKind = null, Original = null, OriginalSha256 = null, OriginalBytes = 0 })],
+ Cleaned = now,
+ });
+ var ledger = renders;
+ foreach (var entry in renders.Entries.Where(e => e.IsSent))
+ {
+ var path = project.ExportFile(entry.File);
+ try
+ {
+ if (File.Exists(path)) File.Delete(path);
+ ledger = ledger.Without(entry.RenderId);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Log.Warning("workspace", $"The sent render {path} could not be removed; it stays", ex);
+ }
+ }
+ if (!ReferenceEquals(ledger, renders)) project.WriteRenders(ledger);
+ foreach (var folder in new[] { project.ProxiesDirectory, project.OriginalsDirectory })
+ {
+ try
+ {
+ if (Directory.Exists(folder)) Directory.Delete(folder, recursive: true);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Log.Warning("workspace", $"{folder} could not be removed whole; what is left stays", ex);
+ }
+ }
+ var after = Cleanable(project, ledger);
+ return (Math.Max(0, before - after - trashedBytes), trashed);
+ }
+
+ /// What a clean-up may remove of the project: its proxies, its originals and the renders its home took.
+ private static long Cleanable(WorkspaceProject project, WorkspaceRenders renders) =>
+ Measure(project.ProxiesDirectory).Bytes + Measure(project.OriginalsDirectory).Bytes
+ + renders.Entries.Where(e => e.IsSent).Select(e => new FileInfo(project.ExportFile(e.File))).Where(f => f.Exists).Sum(f => f.Length);
+
+ /// The project's ledger; null (logged) when it cannot be read.
+ private static WorkspaceRenders? ReadLedger(WorkspaceProject project)
+ {
+ try
+ {
+ return project.ReadRenders();
+ }
+ catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
+ {
+ Log.Warning("workspace", $"The render ledger of project {project.ProjectId} cannot be read: the clean-up keeps the project", ex);
+ return null;
+ }
+ }
+
+ /// A copy, render or send of the project is queued, running or paused (one whose parameters do not read counts too).
+ private async Task BusyAsync(Guid projectId, Guid sequenceId, CancellationToken cancellationToken)
+ {
+ foreach (var kind in ProjectJobs)
+ {
+ foreach (var job in await _db.Jobs.ListPendingAsync(kind, sequenceId, cancellationToken).ConfigureAwait(false))
+ {
+ var named = kind switch
+ {
+ JobKind.WorkspaceCopy => WorkspaceJobs.CopyParameters(job)?.ProjectId,
+ JobKind.WorkspaceRender => WorkspaceJobs.RenderParameters(job)?.ProjectId,
+ _ => WorkspaceJobs.SendParameters(job)?.ProjectId,
+ };
+ if (named is null || named == projectId) return true;
+ }
+ }
+ return false;
+ }
+
+ /// A project of the workspace as the clean-up weighs it.
+ private sealed record Candidate(WorkspaceProject Project, ProjectBundle? Bundle, WorkspaceMedia? Media, bool Unreadable, string Name, bool IsMain, string Title,
+ DateTimeOffset LastUsed, long FolderBytes, long CleanableBytes)
+ {
+ /// The policies may name it: media a copy wrote (cleaned ones are done), or a copy that cannot be read holding media files.
+ public bool Targeted => Media is { IsCleaned: false } || (Unreadable && CleanableBytes > 0);
+
+ public static Candidate Of(WorkspaceProject project, WorkspaceCleanOptions options)
+ {
+ var folder = Measure(project.Folder).Bytes;
+ var media = Measure(project.ProxiesDirectory).Bytes + Measure(project.OriginalsDirectory).Bytes;
+ var saved = File.Exists(project.BundlePath) ? new DateTimeOffset(File.GetLastWriteTimeUtc(project.BundlePath), TimeSpan.Zero) : DateTimeOffset.MinValue;
+ ProjectBundle bundle;
+ try
+ {
+ bundle = project.ReadBundle();
+ }
+ catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
+ {
+ return new Candidate(project, null, null, true, project.ProjectId.ToString("N"), false, string.Empty, Used(saved), folder, media);
+ }
+ var workspace = bundle.Workspace!;
+ var title = bundle.Sequence.Title is { Length: > 0 } t ? t : bundle.Sequence.Folder;
+ WorkspaceMedia? index;
+ var unreadable = false;
+ try
+ {
+ index = project.ReadMedia();
+ }
+ catch (InvalidDataException)
+ {
+ (index, unreadable) = (null, true);
+ }
+ var sent = 0L;
+ try
+ {
+ sent = project.ReadRenders().Entries.Where(e => e.IsSent).Select(e => new FileInfo(project.ExportFile(e.File))).Where(f => f.Exists).Sum(f => f.Length);
+ }
+ catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
+ {
+ // Weighed by its media alone: cleaning it is refused while its ledger cannot be read.
+ }
+ return new Candidate(project, bundle, index, unreadable, workspace.Name, workspace.IsMain, title, Used(bundle.Saved), folder, media + sent);
+
+ DateTimeOffset Used(DateTimeOffset fallback) => options.Opened.TryGetValue(project.ProjectId, out var opened) ? opened : fallback;
+ }
+ }
+}
diff --git a/src/Chronos.Data/Workspaces/WorkspaceMedia.cs b/src/Chronos.Data/Workspaces/WorkspaceMedia.cs
index 59079d8e..850b4ded 100644
--- a/src/Chronos.Data/Workspaces/WorkspaceMedia.cs
+++ b/src/Chronos.Data/Workspaces/WorkspaceMedia.cs
@@ -132,8 +132,13 @@ public sealed record WorkspaceFrame(
///
/// The encodings of the sequence's photos a conversion joined at the home (R7, its tombstones of reason
/// "replaced") when the media were copied: a version parked on a photo before its file was converted still finds its frame.
+///
+/// When the workspace's clean-up removed the files of these media (phase 5c, ): the frames stay,
+/// none names a file, and the project reads as until a copy brings them again (a
+/// copy writes a new index, without it). Null for media a copy wrote.
+///
public sealed record WorkspaceMedia(string Format, int FormatVersion, string Kind, Guid SequenceId, int FramesVersion, IReadOnlyList Frames,
- DateTimeOffset Copied, string? AnalysisSha256 = null, IReadOnlyList? Aliases = null)
+ DateTimeOffset Copied, string? AnalysisSha256 = null, IReadOnlyList? Aliases = null, DateTimeOffset? Cleaned = null)
{
public const string FormatName = "chronos-workspace-media";
public const int CurrentFormatVersion = 1;
@@ -148,6 +153,10 @@ public sealed record WorkspaceMedia(string Format, int FormatVersion, string Kin
/// The frames over the originals the workspace holds (), as a local render reads them.
public IReadOnlyList ToOriginalFrames() => [.. Frames.Select(f => f.ToOriginalFrame(SequenceId))];
+ /// The clean-up removed the files of these media (): nothing to edit until they are copied again.
+ [JsonIgnore]
+ public bool IsCleaned => Cleaned is not null;
+
/// Media of kind : the proxies plus the originals the frames name.
[JsonIgnore]
public bool HoldsOriginals => Kind == BundleMedia.Originals;
diff --git a/src/Chronos.Data/Workspaces/WorkspaceSync.cs b/src/Chronos.Data/Workspaces/WorkspaceSync.cs
index 593da3ac..26486b29 100644
--- a/src/Chronos.Data/Workspaces/WorkspaceSync.cs
+++ b/src/Chronos.Data/Workspaces/WorkspaceSync.cs
@@ -1200,7 +1200,7 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
// A local commit the home stored although its answer was lost reads as behind by the commits it holds: they are ours.
if (head is not null && locals.Any(v => v.Id == head.Id)) behind = 0;
var state = gone ? WorkspaceState.Gone
- : media is null ? WorkspaceState.MediaRemoved
+ : media is null || media.IsCleaned ? WorkspaceState.MediaRemoved
: damaged > 0 ? WorkspaceState.Damaged
: conflict is not null ? WorkspaceState.Conflict
: offline ? WorkspaceState.Offline
@@ -1210,7 +1210,9 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
: WorkspaceState.InSync;
// A project the home no longer has holds no conflict to answer (nothing can be merged with it): the one recorded stays
// in sync.json, for the record and for a project the home holds again.
- return new WorkspaceStatus(state, modified, locals.Count, behind, offline, media is null, bundle.IsReadOnly, gone ? null : conflict, workspace.Base, head)
+ // Media the clean-up emptied hold no file to edit: removed, as media never copied, until a copy brings them again.
+ return new WorkspaceStatus(state, modified, locals.Count, behind, offline, media is null || media.IsCleaned, bundle.IsReadOnly, gone ? null : conflict,
+ workspace.Base, head)
{
MediaOutdated = outdated,
Damaged = damaged,
diff --git a/src/Chronos.Data/Workspaces/WorkspaceTrash.cs b/src/Chronos.Data/Workspaces/WorkspaceTrash.cs
new file mode 100644
index 00000000..86c383fa
--- /dev/null
+++ b/src/Chronos.Data/Workspaces/WorkspaceTrash.cs
@@ -0,0 +1,164 @@
+using System.Globalization;
+using System.Security.Cryptography;
+using System.Text;
+using Chronos.Core.Diagnostics;
+
+namespace Chronos.Data.Workspaces;
+
+/// One entry of a workspace's trash: its name in the trash folder, its bytes and files, and when it was put there.
+public sealed record WorkspaceTrashEntry(string Name, long Bytes, int Files, DateTimeOffset Trashed);
+
+///
+/// What a workspace's trash holds now (): its entries, oldest first, their bytes, and a
+/// fingerprint over the name, size and time of every file in them, which an emptying checks first.
+///
+public sealed record WorkspaceTrashListing(string Folder, IReadOnlyList Entries, long Bytes, string Fingerprint)
+{
+ /// The trash holds nothing.
+ public bool IsEmpty => Entries.Count == 0;
+}
+
+/// The workspace's trash changed after it was listed: nothing was erased.
+public sealed class WorkspaceTrashChangedException(string message) : IOException(message);
+
+///
+/// The trash of a workspace (<workspace>/.trash, phase 5c): what a removed local copy kept of its work
+/// (<project id>-<ticks>), and the originals a clean-up found the home no longer holds
+/// (<project id>-<ticks>/originals). Nothing in Chronos writes into an entry once it is made, and only the
+/// user's Empty… erases them: the plan lists them (), and erases exactly those, only
+/// while the fingerprint of the plan still matches. Schedules and the size limit never empty it.
+///
+public static class WorkspaceTrash
+{
+ /// The trash's folder name in the workspace (the store lists only folders named by a project id).
+ public const string FolderName = ".trash";
+
+ /// The trash folder of the workspace at .
+ public static string FolderOf(string workspaceRoot)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(workspaceRoot);
+ return Path.Combine(workspaceRoot, FolderName);
+ }
+
+ ///
+ /// The path of a new entry of the trash for (<id>-<ticks>, the ticks of
+ /// moved on while an entry of that name exists); not made.
+ ///
+ public static string NewEntry(string workspaceRoot, Guid projectId, DateTime nowUtc)
+ {
+ var folder = FolderOf(workspaceRoot);
+ for (var ticks = nowUtc.Ticks; ; ticks++)
+ {
+ var path = Path.Combine(folder, projectId.ToString("N") + "-" + ticks.ToString(CultureInfo.InvariantCulture));
+ if (!Directory.Exists(path) && !File.Exists(path)) return path;
+ }
+ }
+
+ /// The entries of the workspace's trash at , with their fingerprint; empty when there is no trash.
+ /// The trash cannot be read.
+ public static WorkspaceTrashListing List(string workspaceRoot, CancellationToken cancellationToken = default)
+ {
+ var folder = FolderOf(workspaceRoot);
+ var entries = new List();
+ var lines = new List();
+ if (Directory.Exists(folder))
+ {
+ foreach (var entry in new DirectoryInfo(folder).EnumerateFileSystemInfos())
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var (files, bytes) = (0, 0L);
+ if (entry is DirectoryInfo directory)
+ {
+ // A folder counts by its name only: NTFS updates a folder's time in its parent's index lazily, so the
+ // enumeration may report a stale one; its files (read from their own records) cover what it holds.
+ lines.Add(entry.Name + "/");
+ foreach (var file in directory.EnumerateFiles("*", SearchOption.AllDirectories))
+ {
+ file.Refresh();
+ files++;
+ bytes += file.Length;
+ lines.Add(Line(Path.GetRelativePath(folder, file.FullName).Replace('\\', '/'), file.Length, file.LastWriteTimeUtc));
+ }
+ }
+ else if (entry is FileInfo single)
+ {
+ single.Refresh();
+ (files, bytes) = (1, single.Length);
+ lines.Add(Line(entry.Name, single.Length, single.LastWriteTimeUtc));
+ }
+ entries.Add(new WorkspaceTrashEntry(entry.Name, bytes, files, TrashedAt(entry)));
+ }
+ }
+ lines.Sort(StringComparer.Ordinal);
+ var fingerprint = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(string.Join('\n', lines))));
+ IReadOnlyList ordered = [.. entries.OrderBy(e => e.Trashed).ThenBy(e => e.Name, StringComparer.Ordinal)];
+ return new WorkspaceTrashListing(folder, ordered, ordered.Sum(e => e.Bytes), fingerprint);
+
+ static string Line(string name, long size, DateTime written) =>
+ string.Create(CultureInfo.InvariantCulture, $"{name}|{size}|{written.Ticks}");
+ }
+
+ ///
+ /// Erases the entries of from the workspace's trash for good, the user having confirmed it; refused,
+ /// erasing nothing, when the trash is not as the plan listed it (an entry added, removed or changed since).
+ ///
+ /// The entries and bytes erased.
+ /// The trash changed since the plan; nothing was erased.
+ /// An entry could not be erased (a file held open); the others were, and it stays.
+ public static (int Entries, long Bytes) Empty(string workspaceRoot, WorkspaceTrashListing plan, CancellationToken cancellationToken = default)
+ {
+ ArgumentNullException.ThrowIfNull(plan);
+ var now = List(workspaceRoot, cancellationToken);
+ if (!string.Equals(Path.GetFullPath(now.Folder), Path.GetFullPath(plan.Folder), StringComparison.OrdinalIgnoreCase)
+ || !string.Equals(now.Fingerprint, plan.Fingerprint, StringComparison.Ordinal))
+ throw new WorkspaceTrashChangedException($"The trash {now.Folder} changed after it was listed.");
+ var (erased, bytes) = (0, 0L);
+ var failed = new List();
+ foreach (var entry in plan.Entries)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var path = Path.Combine(now.Folder, entry.Name);
+ try
+ {
+ Erase(path);
+ erased++;
+ bytes += entry.Bytes;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Log.Warning("workspace", $"The trash entry {path} could not be erased", ex);
+ failed.Add(entry.Name);
+ }
+ }
+ Log.Info("workspace", $"The workspace's trash {now.Folder} emptied: {erased} entr(ies), {bytes} bytes erased");
+ if (failed.Count > 0) throw new IOException($"Trash entries not erased: {string.Join(", ", failed)}.");
+ return (erased, bytes);
+ }
+
+ /// When an entry was put in the trash: the ticks of its name (<id>-<ticks>), else when it was written last.
+ private static DateTimeOffset TrashedAt(FileSystemInfo entry)
+ {
+ var dash = entry.Name.LastIndexOf('-');
+ if (dash > 0 && long.TryParse(entry.Name.AsSpan(dash + 1), NumberStyles.None, CultureInfo.InvariantCulture, out var ticks)
+ && ticks >= DateTime.MinValue.Ticks && ticks <= DateTime.MaxValue.Ticks)
+ return new DateTimeOffset(ticks, TimeSpan.Zero);
+ return new DateTimeOffset(entry.LastWriteTimeUtc, TimeSpan.Zero);
+ }
+
+ /// A trash entry erased, files marked read-only included.
+ private static void Erase(string path)
+ {
+ if (File.Exists(path))
+ {
+ File.SetAttributes(path, FileAttributes.Normal);
+ File.Delete(path);
+ return;
+ }
+ if (!Directory.Exists(path)) return;
+ foreach (var file in new DirectoryInfo(path).EnumerateFiles("*", SearchOption.AllDirectories))
+ {
+ if ((file.Attributes & FileAttributes.ReadOnly) != 0) file.Attributes &= ~FileAttributes.ReadOnly;
+ }
+ Directory.Delete(path, recursive: true);
+ }
+}
diff --git a/tests/Chronos.App.Tests/Jobs/DesktopScheduleHostTests.cs b/tests/Chronos.App.Tests/Jobs/DesktopScheduleHostTests.cs
index 6d4c592d..768569fc 100644
--- a/tests/Chronos.App.Tests/Jobs/DesktopScheduleHostTests.cs
+++ b/tests/Chronos.App.Tests/Jobs/DesktopScheduleHostTests.cs
@@ -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);
}
+ /// Phase 5c: the workspace's clean-up is a system schedule of its own, seeded once, daily at 04:30 with catch-up.
+ [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()
{
diff --git a/tests/Chronos.App.Tests/Jobs/ScheduledTabTests.cs b/tests/Chronos.App.Tests/Jobs/ScheduledTabTests.cs
index ef08d3e8..05c204ef 100644
--- a/tests/Chronos.App.Tests/Jobs/ScheduledTabTests.cs
+++ b/tests/Chronos.App.Tests/Jobs/ScheduledTabTests.cs
@@ -36,9 +36,9 @@ public sealed class ScheduledTabTests
shell.Jobs.TabIndex = 1;
await app.ExpectAsync("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().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;
diff --git a/tests/Chronos.App.Tests/Jobs/SchedulesViewModelTests.cs b/tests/Chronos.App.Tests/Jobs/SchedulesViewModelTests.cs
index 495aeb9c..1ce6cbb2 100644
--- a/tests/Chronos.App.Tests/Jobs/SchedulesViewModelTests.cs
+++ b/tests/Chronos.App.Tests/Jobs/SchedulesViewModelTests.cs
@@ -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));
}
diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceCleanupHostTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceCleanupHostTests.cs
new file mode 100644
index 00000000..45e8b97c
--- /dev/null
+++ b/tests/Chronos.App.Tests/Workspace/WorkspaceCleanupHostTests.cs
@@ -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;
+
+///
+/// The desktop's side of the workspace clean-up (phase 5c, P4): the workspace-clean and workspace-trash 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.
+///
+[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(() => 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);
+ }
+}
diff --git a/tests/Chronos.Data.Tests/Workspaces/WorkspaceCleanupTests.cs b/tests/Chronos.Data.Tests/Workspaces/WorkspaceCleanupTests.cs
new file mode 100644
index 00000000..422e5a71
--- /dev/null
+++ b/tests/Chronos.Data.Tests/Workspaces/WorkspaceCleanupTests.cs
@@ -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;
+
+///
+/// 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.
+///
+[Category("workspace")]
+public abstract class WorkspaceCleanupTests(TestContext context) : DatabaseTest(context)
+{
+ private static readonly TimeSpan Day = TimeSpan.FromDays(1);
+
+ private async Task 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? homes = null) =>
+ new(sync, fx.Db, homes ?? (_ => fx.Home)) { LockWait = TimeSpan.FromSeconds(TestTiming.Budget(10)) };
+
+ private static T One(IReadOnlyList items, [System.Runtime.CompilerServices.CallerArgumentExpression(nameof(items))] string? expression = null)
+ {
+ Assert.Count(1, items, expression);
+ return items[0];
+ }
+
+ /// Clean after 30 days, the project last opened 40 days ago.
+ private static WorkspaceCleanOptions Aged(Guid projectId, Func? isOpen = null, Guid? justCopied = null) => new()
+ {
+ CleanAfterDays = 30,
+ Opened = new Dictionary { [projectId] = DateTimeOffset.UtcNow - 40 * Day },
+ IsOpen = isOpen ?? (_ => false),
+ JustCopied = justCopied,
+ };
+
+ /// A render of the project's ledger with its file in exports/.
+ 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 { [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 { [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 { [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() }, 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(() => 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(() => 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;
+}