feat: owner review 2 phase 5c: originals, local render, clean-up and the workspace settings (#18)
CI / Build and test (push) Successful in 9m26s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 8s
Release / Build, test and publish (push) Successful in 14m31s
CI / PostgreSQL 16 integration (push) Successful in 9m53s
CI / PostgreSQL 17 integration (push) Successful in 9m22s
CI / Docker image (push) Successful in 44s
Release / Server image (push) Successful in 1m36s
Originals in the workspace, local render and send home with provenance, the workspace clean-up, size limit and trash, moving the workspace folder, and the complete Settings › Workspace page (owner review 2, R8, phase 5c). One adversarial review round (35 findings, 32 fixed), a copy-cancel race fixed, 184 strings in all 38 languages. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
No files matched your search
@@ -91,6 +91,24 @@ public sealed class SequenceJobsTests
|
||||
Assert.Null(jobs.Active(JobKind.LightAnalyse));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheServerHeaderNeverShowsAWorkspaceRenderOrSendOfThisPc()
|
||||
{
|
||||
var jobs = new SequenceJobs(Sunset);
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var local = Job(JobKind.WorkspaceRender, JobState.Running) with { Started = now };
|
||||
var send = Job(JobKind.WorkspaceSend, JobState.Queued);
|
||||
jobs.Track(local);
|
||||
jobs.Track(send);
|
||||
Assert.Equal(local.Id, jobs.Shown!.Id, "the editor follows it");
|
||||
Assert.Null(jobs.ShownAtHome, "the server header and its Cancel do not");
|
||||
var atHome = Job(JobKind.DeepAnalyse, JobState.Queued) with { Created = now.AddMinutes(-3) };
|
||||
jobs.Track(atHome);
|
||||
Assert.Equal(atHome.Id, jobs.ShownAtHome!.Id, "a job at the home waits behind the local render, and is the one shown");
|
||||
Assert.True(SequenceJobs.IsLocalKind(JobKind.WorkspaceSend));
|
||||
Assert.False(SequenceJobs.IsLocalKind(JobKind.Render));
|
||||
}
|
||||
|
||||
private static Job Job(JobKind kind, JobState state, Guid? target = null) => new()
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
|
||||
@@ -37,7 +37,7 @@ public sealed class DesktopScheduleHostTests(TestContext context)
|
||||
await fx.StartAsync();
|
||||
var kept = Assert.NotNull(await fx.Db.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.ArchiveScan));
|
||||
Assert.Equal((scan.Id, "every:2h"), (kept.Id, kept.Recurrence));
|
||||
Assert.Count(3, (await fx.Db.Schedules.ListAsync()).Where(s => s.IsSystem));
|
||||
Assert.Count(4, (await fx.Db.Schedules.ListAsync()).Where(s => s.IsSystem));
|
||||
|
||||
// Reset goes back to what the host seeds with.
|
||||
Assert.Null((await fx.Scheduler!.ResetAsync(scan.Id)).Problem);
|
||||
@@ -109,9 +109,9 @@ public sealed class DesktopScheduleHostTests(TestContext context)
|
||||
Assert.Equal(fx.Clock.Now.AddDays(1), backup.NextRun);
|
||||
|
||||
// Chronos was closed for two days: the missed copy is made once at start (catch-up, as the housekeeping's run; the
|
||||
// scan has none and just moves on).
|
||||
// scan has none and just moves on; the workspace clean-up, with catch-up too, runs once as well).
|
||||
fx.Clock.Advance(TimeSpan.FromDays(2.5));
|
||||
Assert.Equal(2, await scheduler.RunDueAsync());
|
||||
Assert.Equal(3, await scheduler.RunDueAsync());
|
||||
var job = (await fx.Db.Jobs.ListByScheduleAsync(backup.Id)).Single();
|
||||
Assert.Equal((JobKind.Backup, JobPriority.Background, JobState.Queued), (job.Kind, job.Priority, job.State));
|
||||
Assert.Equal(0, await scheduler.RunDueAsync());
|
||||
@@ -168,6 +168,23 @@ public sealed class DesktopScheduleHostTests(TestContext context)
|
||||
Assert.Equal(ScheduleRecurrence.DailyAt(new TimeOnly(4, 0)).Next(fx.Clock.Now, TimeZoneInfo.Utc), housekeeping.NextRun);
|
||||
}
|
||||
|
||||
/// <summary>Phase 5c: the workspace's clean-up is a system schedule of its own, seeded once, daily at 04:30 with catch-up.</summary>
|
||||
[Test]
|
||||
public async Task TheWorkspaceCleanUpIsSeededOnceAsASystemSchedule()
|
||||
{
|
||||
await using var fx = await ScheduleFixture.CreateAsync(context);
|
||||
await fx.StartAsync();
|
||||
var cleanup = Assert.NotNull(await fx.Db.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.WorkspaceCleanup));
|
||||
Assert.Equal(("daily:04:30", true, ScheduleActions.Cleanup, true), (cleanup.Recurrence, cleanup.CatchUp, cleanup.Action, cleanup.Enabled));
|
||||
var parameters = ScheduleMapping.Parameters(cleanup);
|
||||
Assert.SequenceEqual([WorkspaceCleanStep.StepName, WorkspaceTrashStep.StepName], parameters.Steps!);
|
||||
Assert.Equal(0, parameters.OlderThanDays);
|
||||
Assert.Equal(("Workspace media", "Workspace trash"), (ScheduleText.Step(WorkspaceCleanStep.StepName), ScheduleText.Step(WorkspaceTrashStep.StepName)));
|
||||
|
||||
await fx.StartAsync();
|
||||
Assert.Count(1, (await fx.Db.Schedules.ListAsync()).Where(s => s.SystemKey == DesktopScheduleHost.WorkspaceCleanup));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SchedulesWorkOnTheArchiveAtTheFolderWhileItIsOnline()
|
||||
{
|
||||
|
||||
@@ -17,6 +17,9 @@ public sealed class JobNoticesTests
|
||||
[Case(JobKind.Move)]
|
||||
[Case(JobKind.Adopt)]
|
||||
[Case(JobKind.Convert)]
|
||||
[Case(JobKind.WorkspaceRender)]
|
||||
[Case(JobKind.WorkspaceSend)]
|
||||
[Case(JobKind.WorkspaceMove)]
|
||||
public void ALongOperationThatEndsSaysSo(JobKind kind)
|
||||
{
|
||||
Assert.Equal(JobNotice.Done, JobNotices.For(JobState.Running, Job(kind, JobState.Done)));
|
||||
|
||||
@@ -36,9 +36,9 @@ public sealed class ScheduledTabTests
|
||||
shell.Jobs.TabIndex = 1;
|
||||
await app.ExpectAsync<SchedulesView>("jobs-scheduled");
|
||||
|
||||
Assert.SequenceEqual(["Archive scan", "Index backup", "Housekeeping", "Weekly integrity check", "Monthly orphans report"], schedules.Rows.Select(r => r.Name));
|
||||
Assert.SequenceEqual(["Archive scan", "Index backup", "Housekeeping", "Workspace clean-up", "Weekly integrity check", "Monthly orphans report"], schedules.Rows.Select(r => r.Name));
|
||||
var items = app.FindAll<ListBoxItem>().Where(i => i.DataContext is ScheduleRowViewModel && i.IsVisible).ToList();
|
||||
Assert.Count(5, items);
|
||||
Assert.Count(6, items);
|
||||
foreach (var item in items)
|
||||
{
|
||||
var row = (ScheduleRowViewModel)item.DataContext;
|
||||
|
||||
@@ -30,9 +30,9 @@ public sealed class SchedulesViewModelTests
|
||||
using var vm = await fx.ViewModelAsync();
|
||||
|
||||
Assert.True(vm.IsRunning && vm.IsLoaded && vm.HasRows, "the schedules are listed");
|
||||
Assert.SequenceEqual(["Archive scan", "Index backup", "Housekeeping"], vm.Rows.Select(r => r.Name));
|
||||
Assert.SequenceEqual(["Every 10 minutes", "Every day", "Daily at " + ScheduleText.Time(new TimeOnly(4, 0))], vm.Rows.Select(r => r.WhenText));
|
||||
Assert.SequenceEqual(["Archive scan", "Index backup", "Clean-up"], vm.Rows.Select(r => r.ActionText));
|
||||
Assert.SequenceEqual(["Archive scan", "Index backup", "Housekeeping", "Workspace clean-up"], vm.Rows.Select(r => r.Name));
|
||||
Assert.SequenceEqual(["Every 10 minutes", "Every day", "Daily at " + ScheduleText.Time(new TimeOnly(4, 0)), "Daily at " + ScheduleText.Time(new TimeOnly(4, 30))], vm.Rows.Select(r => r.WhenText));
|
||||
Assert.SequenceEqual(["Archive scan", "Index backup", "Clean-up", "Clean-up"], vm.Rows.Select(r => r.ActionText));
|
||||
Assert.True(vm.Rows.All(r => r.IsSystem && r.IsEnabled && r.LastText == "never run" && r.LastKind == StatusKind.Offline), "nothing ran yet");
|
||||
// The scan's next run is ten minutes away, today.
|
||||
Assert.Equal(ScheduleText.Moment(fx.Clock.Now.AddMinutes(10)), vm.Rows[0].NextText);
|
||||
@@ -41,9 +41,9 @@ public sealed class SchedulesViewModelTests
|
||||
// A schedule the user creates joins the list after the system ones.
|
||||
var created = await fx.Scheduler!.CreateAsync(new CreateScheduleRequest("Weekly check", ScheduleActions.Verify, new RecurrenceDto("weekly", Time: "02:30", Days: ["mon", "thu"])), null);
|
||||
Assert.Null(created.Problem);
|
||||
Assert.Equal("Weekly check", vm.Rows[3].Name);
|
||||
Assert.Equal("Weekly check", vm.Rows[4].Name);
|
||||
Assert.Equal(ScheduleText.DayShort(DayOfWeek.Monday) + ", " + ScheduleText.DayShort(DayOfWeek.Thursday) + " at " + ScheduleText.Time(new TimeOnly(2, 30)),
|
||||
vm.Rows[3].WhenText);
|
||||
vm.Rows[4].WhenText);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -141,11 +141,11 @@ public sealed class SchedulesViewModelTests
|
||||
Assert.False(scan.DeleteCommand.CanExecute(null));
|
||||
Assert.False(mine.ResetCommand.CanExecute(null));
|
||||
await vm.DeleteAsync(mine);
|
||||
Assert.Count(4, vm.Rows);
|
||||
Assert.Count(5, vm.Rows);
|
||||
answer = true;
|
||||
vm.Selected = mine;
|
||||
await vm.DeleteAsync(mine);
|
||||
Assert.Count(3, vm.Rows);
|
||||
Assert.Count(4, vm.Rows);
|
||||
Assert.Null(vm.Selected);
|
||||
Assert.Null(await fx.Db.Schedules.GetAsync(mine.Id));
|
||||
|
||||
@@ -172,7 +172,7 @@ public sealed class SchedulesViewModelTests
|
||||
|
||||
await vm.DeleteAsync(mine);
|
||||
Assert.SequenceEqual([Loc.L("Jobs.Schedule.Failed")], toasts);
|
||||
Assert.Count(4, vm.Rows);
|
||||
Assert.Count(5, vm.Rows);
|
||||
Assert.Contains(mine, vm.Rows);
|
||||
Assert.NotNull(await fx.Db.Schedules.GetAsync(mine.Id));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
using Chronos.App.Server;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.App.Tests.Server;
|
||||
|
||||
/// <summary>
|
||||
/// Which jobs "Pause metered transfers" holds (Server.html, phase 5c): uploads, the sync's downloads, and the workspace's copies from and renders
|
||||
/// sent to a server; never a copy from or a send to this PC's archive.
|
||||
/// </summary>
|
||||
public sealed class UploadHoldTests
|
||||
{
|
||||
private const string Server = "https://nas.local:8443";
|
||||
private static readonly Guid SequenceId = Guid.CreateVersion7();
|
||||
private static readonly Guid ProjectId = Guid.CreateVersion7();
|
||||
private const string Root = @"C:\Users\me\Chronos\workspace";
|
||||
|
||||
private static Job Of(ArchiveJobRequest request) => new()
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Kind = request.Kind,
|
||||
TargetIds = request.Targets,
|
||||
TargetLabel = request.Label,
|
||||
ParametersJson = request.ParametersJson,
|
||||
State = JobState.Queued,
|
||||
Created = DateTimeOffset.UtcNow,
|
||||
};
|
||||
|
||||
private static Job Of(JobKind kind, string? parameters = null) => new()
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Kind = kind,
|
||||
TargetIds = [SequenceId],
|
||||
ParametersJson = parameters,
|
||||
State = JobState.Queued,
|
||||
Created = DateTimeOffset.UtcNow,
|
||||
};
|
||||
|
||||
[Test]
|
||||
public void TransfersWithAServerAreHeld()
|
||||
{
|
||||
Assert.True(UploadHold.Holds(Of(JobKind.UploadCommit)));
|
||||
// The sync's downloads too: the option's tooltip says "uploads and downloads".
|
||||
Assert.True(UploadHold.Holds(Of(JobKind.Download)));
|
||||
Assert.True(UploadHold.Holds(Of(WorkspaceJobs.CopyFromServer(SequenceId, "Harbour", Server, Root, ProjectId))));
|
||||
Assert.True(UploadHold.Holds(Of(WorkspaceJobs.Send(SequenceId, "Harbour", Root, ProjectId, [], Server))));
|
||||
Assert.SequenceEqual([JobKind.UploadCommit, JobKind.Download, JobKind.WorkspaceCopy, JobKind.WorkspaceSend], UploadHold.Kinds);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TransfersWithThisPcsLibraryAndOtherJobsAreNot()
|
||||
{
|
||||
var sequence = new Sequence { Id = SequenceId, ArchiveId = Guid.CreateVersion7(), Title = "Harbour", Folder = "2026/harbour" };
|
||||
Assert.False(UploadHold.Holds(Of(WorkspaceJobs.Copy(sequence, Root, ProjectId))));
|
||||
Assert.False(UploadHold.Holds(Of(WorkspaceJobs.Send(SequenceId, "Harbour", Root, ProjectId, []))));
|
||||
Assert.False(UploadHold.Holds(Of(JobKind.Render)));
|
||||
// Parameters that cannot be read are not held: the job fails with its reason.
|
||||
Assert.False(UploadHold.Holds(Of(JobKind.WorkspaceSend, "{not json")));
|
||||
Assert.False(UploadHold.Holds(Of(JobKind.WorkspaceCopy)));
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,26 @@
|
||||
using System.ComponentModel;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Settings;
|
||||
using Chronos.App.Workspace;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Naming;
|
||||
using Chronos.Core.Video;
|
||||
using Chronos.Core.Windows.Shell;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.App.Tests.Settings;
|
||||
|
||||
public sealed class SettingsLogicTests
|
||||
{
|
||||
public SettingsLogicTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
||||
private readonly TestContext _context;
|
||||
|
||||
public SettingsLogicTests(TestContext context)
|
||||
{
|
||||
_context = context;
|
||||
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DefaultTemplatesPreviewThreeNames()
|
||||
@@ -355,4 +364,453 @@ public sealed class SettingsLogicTests
|
||||
.ToHashSet(StringComparer.Ordinal);
|
||||
foreach (var key in keys) Assert.True(english.Contains(key), key);
|
||||
}
|
||||
|
||||
// ---------------- Settings › Workspace (phase 5c) ----------------
|
||||
|
||||
[Test]
|
||||
public void TheWorkspaceSizeLimitOffersItsPresetsThenNoLimit()
|
||||
{
|
||||
var (settings, rows, saves) = WorkspaceRows();
|
||||
Assert.SequenceEqual([25, 50, 100, 200, 500, 1000, 0], rows.SizeLimitChoices.Select(c => c.Value));
|
||||
Assert.Equal(("100 GB", "No limit"), (rows.SizeLimitChoices.Single(c => c.Value == 100).Label, rows.SizeLimitChoices[^1].Label));
|
||||
Assert.Equal(100, rows.SelectedSizeLimit.Value);
|
||||
Assert.Equal(Loc.L("Tooltips.Settings.Workspace.SizeLimit"), rows.SizeLimitToolTip);
|
||||
|
||||
rows.SelectedSizeLimit = rows.SizeLimitChoices.Single(c => c.Value == 500);
|
||||
Assert.Equal((500, 1), (settings.WorkspaceSizeLimitGb, saves()));
|
||||
rows.SelectedSizeLimit = rows.SizeLimitChoices.Single(c => c.Value == 500);
|
||||
rows.SelectedSizeLimit = null!;
|
||||
Assert.Equal(1, saves(), "nothing to store");
|
||||
rows.SelectedSizeLimit = rows.SizeLimitChoices[^1];
|
||||
Assert.Equal((0, 2), (settings.WorkspaceSizeLimitGb, saves()));
|
||||
Assert.Equal(Loc.L("Tooltips.Settings.Workspace.NoLimit"), rows.SizeLimitToolTip);
|
||||
|
||||
// A value set by hand is listed in order with the presets; one below 1 is no limit, as the clean-up applies it.
|
||||
settings.WorkspaceSizeLimitGb = 300;
|
||||
Assert.SequenceEqual([25, 50, 100, 200, 300, 500, 1000, 0], rows.SizeLimitChoices.Select(c => c.Value));
|
||||
Assert.Equal(300, rows.SelectedSizeLimit.Value);
|
||||
settings.WorkspaceSizeLimitGb = -5;
|
||||
Assert.Equal(0, rows.SelectedSizeLimit.Value);
|
||||
Assert.Count(7, rows.SizeLimitChoices);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheDefaultMediaAreTheProxiesUnlessTheOriginalsAreChosen()
|
||||
{
|
||||
var (settings, rows, saves) = WorkspaceRows();
|
||||
Assert.Equal((true, false), (rows.IsDefaultProxies, rows.IsDefaultOriginals));
|
||||
rows.IsDefaultOriginals = true;
|
||||
Assert.Equal((Chronos.Core.Project.BundleMedia.Originals, 1), (settings.WorkspaceDefaultMedia, saves()));
|
||||
Assert.Equal((false, true), (rows.IsDefaultProxies, rows.IsDefaultOriginals));
|
||||
// A radio button unchecked by its sibling stores nothing.
|
||||
rows.IsDefaultProxies = false;
|
||||
rows.IsDefaultOriginals = true;
|
||||
Assert.Equal(1, saves());
|
||||
rows.IsDefaultProxies = true;
|
||||
Assert.Equal((Chronos.Core.Project.BundleMedia.Proxies, 2), (settings.WorkspaceDefaultMedia, saves()));
|
||||
|
||||
// What the open dialog takes from a hand-edited file: originals in any case, anything else the proxies.
|
||||
settings.WorkspaceDefaultMedia = "ORIGINALS";
|
||||
Assert.True(rows.IsDefaultOriginals);
|
||||
settings.WorkspaceDefaultMedia = "everything";
|
||||
Assert.Equal((true, false), (rows.IsDefaultProxies, rows.IsDefaultOriginals));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void VersionOnRenderIsOnUntilTurnedOff()
|
||||
{
|
||||
var (settings, rows, saves) = WorkspaceRows();
|
||||
Assert.True(rows.VersionOnRender);
|
||||
rows.VersionOnRender = false;
|
||||
Assert.Equal((false, 1), (settings.WorkspaceVersionOnRender, saves()));
|
||||
rows.VersionOnRender = false;
|
||||
Assert.Equal(1, saves(), "nothing to store");
|
||||
rows.VersionOnRender = true;
|
||||
Assert.Equal((true, 2), (settings.WorkspaceVersionOnRender, saves()));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CleanAfterOffersItsDaysThenNever()
|
||||
{
|
||||
var (settings, rows, saves) = WorkspaceRows();
|
||||
Assert.SequenceEqual([7, 14, 30, 60, 90, 0], rows.CleanAfterChoices.Select(c => c.Value));
|
||||
Assert.Equal(("30 days", "Never"), (rows.CleanAfterChoices.Single(c => c.Value == 30).Label, rows.CleanAfterChoices[^1].Label));
|
||||
Assert.Equal(30, rows.SelectedCleanAfter.Value);
|
||||
Assert.Equal(Loc.L("Tooltips.Settings.Workspace.CleanAfter"), rows.CleanAfterToolTip);
|
||||
|
||||
rows.SelectedCleanAfter = rows.CleanAfterChoices.Single(c => c.Value == 7);
|
||||
Assert.Equal((7, 1), (settings.WorkspaceCleanAfterDays, saves()));
|
||||
rows.SelectedCleanAfter = rows.CleanAfterChoices[^1];
|
||||
Assert.Equal((0, 2), (settings.WorkspaceCleanAfterDays, saves()));
|
||||
Assert.Equal(Loc.L("Tooltips.Settings.Workspace.Never"), rows.CleanAfterToolTip);
|
||||
|
||||
settings.WorkspaceCleanAfterDays = 1;
|
||||
Assert.Equal("1 day", rows.SelectedCleanAfter.Label);
|
||||
Assert.SequenceEqual([1, 7, 14, 30, 60, 90, 0], rows.CleanAfterChoices.Select(c => c.Value));
|
||||
settings.WorkspaceCleanAfterDays = -1;
|
||||
Assert.Equal(0, rows.SelectedCleanAfter.Value);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void OpenProjectIsTheLastUsedUnlessMainOrAskIsChosen()
|
||||
{
|
||||
var (settings, rows, saves) = WorkspaceRows();
|
||||
Assert.Equal((true, false, false), (rows.IsOpenLastUsed, rows.IsOpenMain, rows.IsOpenAsk));
|
||||
rows.IsOpenMain = true;
|
||||
Assert.Equal((WorkspaceOpenPolicy.Main, 1), (settings.WorkspaceOpenProject, saves()));
|
||||
rows.IsOpenLastUsed = false;
|
||||
Assert.Equal(1, saves());
|
||||
rows.IsOpenAsk = true;
|
||||
Assert.Equal((WorkspaceOpenPolicy.Ask, 2), (settings.WorkspaceOpenProject, saves()));
|
||||
Assert.Equal((false, false, true), (rows.IsOpenLastUsed, rows.IsOpenMain, rows.IsOpenAsk));
|
||||
rows.IsOpenLastUsed = true;
|
||||
Assert.Equal((WorkspaceOpenPolicy.LastUsed, 3), (settings.WorkspaceOpenProject, saves()));
|
||||
|
||||
// A value the enum does not know reads as the default.
|
||||
settings.WorkspaceOpenProject = (WorkspaceOpenPolicy)99;
|
||||
Assert.Equal((true, false, false), (rows.IsOpenLastUsed, rows.IsOpenMain, rows.IsOpenAsk));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AWorkspaceListThatChangesIsRaisedBeforeItsSelection()
|
||||
{
|
||||
var (settings, rows, _) = WorkspaceRows();
|
||||
settings.WorkspaceSizeLimitGb = 300;
|
||||
var raised = new List<string?>();
|
||||
rows.PropertyChanged += (_, e) => raised.Add(e.PropertyName);
|
||||
rows.SelectedSizeLimit = rows.SizeLimitChoices.Single(c => c.Value == 50);
|
||||
Assert.SequenceEqual([nameof(rows.SizeLimitChoices), nameof(rows.SelectedSizeLimit), nameof(rows.SizeLimitToolTip)], raised);
|
||||
raised.Clear();
|
||||
rows.SelectedCleanAfter = rows.CleanAfterChoices.Single(c => c.Value == 90);
|
||||
Assert.SequenceEqual([nameof(rows.CleanAfterChoices), nameof(rows.SelectedCleanAfter), nameof(rows.CleanAfterToolTip)], raised);
|
||||
raised.Clear();
|
||||
rows.SelectedKept = rows.KeptChoices.Single(c => c.Value == 5);
|
||||
Assert.SequenceEqual([nameof(rows.KeptChoices), nameof(rows.SelectedKept)], raised);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ResetRestoresEveryWorkspaceRowButKeepsTheFolderAndWhatItRemembers()
|
||||
{
|
||||
var (settings, rows, _) = WorkspaceRows();
|
||||
var project = Guid.NewGuid();
|
||||
settings.WorkspaceFolder = @"E:\Fast\Chronos workspace";
|
||||
settings.WorkspaceRecent[Guid.NewGuid()] = project;
|
||||
settings.WorkspaceOpened[project] = DateTimeOffset.UnixEpoch;
|
||||
settings.WorkspaceSizeLimitGb = 0;
|
||||
settings.WorkspaceDefaultMedia = Chronos.Core.Project.BundleMedia.Originals;
|
||||
settings.WorkspaceAutoSync = false;
|
||||
settings.WorkspaceVersionOnRender = false;
|
||||
settings.WorkspaceKeptVersions = 5;
|
||||
settings.WorkspaceCleanAfterDays = 0;
|
||||
settings.WorkspaceOpenProject = WorkspaceOpenPolicy.Ask;
|
||||
var raised = new List<string?>();
|
||||
rows.PropertyChanged += (_, e) => raised.Add(e.PropertyName);
|
||||
|
||||
rows.Reset();
|
||||
var defaults = new AppSettings();
|
||||
Assert.Equal((defaults.WorkspaceSizeLimitGb, defaults.WorkspaceDefaultMedia, defaults.WorkspaceAutoSync, defaults.WorkspaceVersionOnRender),
|
||||
(settings.WorkspaceSizeLimitGb, settings.WorkspaceDefaultMedia, settings.WorkspaceAutoSync, settings.WorkspaceVersionOnRender));
|
||||
Assert.Equal((defaults.WorkspaceKeptVersions, defaults.WorkspaceCleanAfterDays, defaults.WorkspaceOpenProject),
|
||||
(settings.WorkspaceKeptVersions, settings.WorkspaceCleanAfterDays, settings.WorkspaceOpenProject));
|
||||
Assert.Equal((100, BundleMediaProxies, true, true, 20, 30, WorkspaceOpenPolicy.LastUsed),
|
||||
(rows.SelectedSizeLimit.Value, settings.WorkspaceDefaultMedia, rows.AutoSync, rows.VersionOnRender, rows.SelectedKept.Value, rows.SelectedCleanAfter.Value,
|
||||
settings.WorkspaceOpenProject));
|
||||
Assert.Equal(@"E:\Fast\Chronos workspace", settings.WorkspaceFolder);
|
||||
Assert.Count(1, settings.WorkspaceRecent);
|
||||
Assert.Equal(DateTimeOffset.UnixEpoch, settings.WorkspaceOpened[project]);
|
||||
Assert.Contains(raised, p => string.IsNullOrEmpty(p));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void MoveTakesTheFolderAlongAndWaitsWhileAMoveRuns()
|
||||
{
|
||||
var moving = false;
|
||||
var moves = 0;
|
||||
var (_, rows, _) = WorkspaceRows(new FakeWorkspace(), move: () =>
|
||||
{
|
||||
moves++;
|
||||
return Task.CompletedTask;
|
||||
}, isMoving: () => moving);
|
||||
Assert.True(rows.CanMove);
|
||||
Assert.True(rows.MoveCommand.CanExecute(null));
|
||||
Assert.Equal(Loc.L("Tooltips.Settings.Workspace.Move"), rows.MoveToolTip);
|
||||
rows.MoveCommand.Execute(null);
|
||||
Assert.Equal(1, moves);
|
||||
|
||||
moving = true;
|
||||
Assert.False(rows.MoveCommand.CanExecute(null));
|
||||
Assert.False(rows.ChangeCommand.CanExecute(null), "the folder changes only once the move ends");
|
||||
Assert.Equal(Loc.L("Errors.Workspace.Moving"), rows.MoveToolTip);
|
||||
|
||||
// Without the workspace's services (or a move), no Move… button.
|
||||
var (_, bare, _) = WorkspaceRows();
|
||||
Assert.False(bare.CanMove);
|
||||
Assert.False(bare.MoveCommand.CanExecute(null));
|
||||
Assert.Null(bare.UsageText);
|
||||
Assert.Null(bare.TrashText);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheWorkspaceIsMeasuredWithItsTrash()
|
||||
{
|
||||
var workspace = new FakeWorkspace();
|
||||
var pending = new TaskCompletionSource<WorkspaceUsage>();
|
||||
workspace.Measure = _ => pending.Task;
|
||||
var (_, rows, _) = WorkspaceRows(workspace);
|
||||
var measuring = rows.MeasureAsync();
|
||||
Assert.True(rows.IsMeasuring);
|
||||
Assert.Equal(("Measuring…", "Measuring…"), (rows.UsageText, rows.TrashText));
|
||||
Assert.False(rows.EmptyTrashCommand.CanExecute(null), "nothing to erase is known yet");
|
||||
|
||||
pending.SetResult(new WorkspaceUsage(MediaBytes: 9_000_000_000, TotalBytes: 12_400_000_000, TrashBytes: 1_200_000_000, TrashItems: 3));
|
||||
await measuring;
|
||||
Assert.False(rows.IsMeasuring);
|
||||
Assert.Equal(("12.4 GB used", "3 items, 1.2 GB"), (rows.UsageText, rows.TrashText));
|
||||
Assert.True(rows.HasUsageText);
|
||||
Assert.True(rows.HasTrash);
|
||||
Assert.True(rows.EmptyTrashCommand.CanExecute(null));
|
||||
Assert.Equal(Loc.L("Tooltips.Settings.Workspace.EmptyTrash"), rows.EmptyTrashToolTip);
|
||||
|
||||
workspace.Measure = _ => Task.FromResult(new WorkspaceUsage(0, 4_000, 0, 0));
|
||||
await rows.MeasureAsync();
|
||||
Assert.Equal(("4 KB used", "Nothing in trash"), (rows.UsageText, rows.TrashText));
|
||||
Assert.False(rows.HasTrash);
|
||||
Assert.False(rows.EmptyTrashCommand.CanExecute(null));
|
||||
Assert.Equal(Loc.L("Tooltips.Settings.Workspace.EmptyTrash.Disabled"), rows.EmptyTrashToolTip);
|
||||
workspace.Measure = _ => Task.FromResult(new WorkspaceUsage(0, 1_000, 2_000, 1));
|
||||
await rows.MeasureAsync();
|
||||
Assert.Equal("1 item, 2 KB", rows.TrashText);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ALaterMeasureReplacesOneStillRunningAndAFailureShowsNothing()
|
||||
{
|
||||
var workspace = new FakeWorkspace();
|
||||
var first = new TaskCompletionSource<WorkspaceUsage>();
|
||||
CancellationToken firstToken = default;
|
||||
workspace.Measure = token =>
|
||||
{
|
||||
firstToken = token;
|
||||
return first.Task;
|
||||
};
|
||||
var (_, rows, _) = WorkspaceRows(workspace);
|
||||
var older = rows.MeasureAsync();
|
||||
workspace.Measure = _ => Task.FromResult(new WorkspaceUsage(0, 2_000_000, 0, 0));
|
||||
await rows.MeasureAsync();
|
||||
Assert.True(firstToken.IsCancellationRequested, "the older measure is told to stop");
|
||||
first.SetResult(new WorkspaceUsage(0, 9_000_000_000, 0, 5));
|
||||
await older;
|
||||
Assert.Equal(("2 MB used", false, false), (rows.UsageText, rows.HasTrash, rows.IsMeasuring));
|
||||
|
||||
workspace.Measure = _ => Task.FromException<WorkspaceUsage>(new IOException("the drive went away"));
|
||||
await rows.MeasureAsync();
|
||||
Assert.Null(rows.UsageText);
|
||||
Assert.False(rows.HasUsageText);
|
||||
Assert.Null(rows.TrashText);
|
||||
Assert.False(rows.HasTrash);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task EmptyingTheWorkspaceTrashShowsItsPlanAndAsksForTheCountTyped()
|
||||
{
|
||||
var workspace = new FakeWorkspace { Confirmed = false };
|
||||
var items = Enumerable.Range(1, 8).Select(i => new WorkspaceTrashItem($"{Guid.Empty:N}-{i}", i * 1_000_000, i, DateTimeOffset.UnixEpoch.AddDays(i))).ToList();
|
||||
var plan = new WorkspaceTrashPlan(@"C:\workspace\.trash", items, items.Sum(i => i.Bytes), "fingerprint");
|
||||
workspace.Plan = plan;
|
||||
workspace.Measure = _ => Task.FromResult(new WorkspaceUsage(0, 50_000_000, plan.Bytes, items.Count));
|
||||
var (_, rows, _) = WorkspaceRows(workspace);
|
||||
await rows.MeasureAsync();
|
||||
|
||||
// Kept: the plan was shown, nothing erased.
|
||||
await rows.EmptyTrashAsync();
|
||||
var request = Assert.NotNull(workspace.Asked);
|
||||
Assert.Equal(0, workspace.Emptied.Count);
|
||||
Assert.Equal((Loc.L("Settings.Workspace.TrashPlan.Title"), "8", Loc.L("Settings.Workspace.TrashPlan.Type", "8")),
|
||||
(request.Heading, request.TypedConfirmation, request.TypedPrompt));
|
||||
Assert.True(request.IsDestructive);
|
||||
Assert.Equal((Loc.L("Settings.Workspace.TrashPlan.Action"), Loc.L("Tooltips.Settings.Workspace.TrashPlan.Action"), Loc.L("Tooltips.Settings.Workspace.TrashPlan.Keep")),
|
||||
(request.ActionText, request.ActionToolTip, request.SafeToolTip));
|
||||
var lines = request.Detail!.Split(Environment.NewLine);
|
||||
Assert.Equal(("Entries: 8", "Size: 36 MB"), (lines[0], lines[1]));
|
||||
// The newest entries are named, the rest counted.
|
||||
Assert.Equal(Loc.L("Settings.Workspace.TrashPlan.Item", items[7].Name, "8 MB", Formatting.Date(items[7].Trashed)), lines[2]);
|
||||
Assert.Equal(2 + DeletePlansListed + 1, lines.Length);
|
||||
Assert.Equal(Loc.Plural("Archive.Delete.More", 2), lines[^1]);
|
||||
|
||||
// Erased: exactly the plan shown, then told and measured again.
|
||||
workspace.Confirmed = true;
|
||||
workspace.Measure = _ => Task.FromResult(new WorkspaceUsage(0, 14_000_000, 0, 0));
|
||||
await rows.EmptyTrashAsync();
|
||||
Assert.Same(plan, Assert.Contains(workspace.Emptied, _ => true));
|
||||
Assert.Equal((Loc.L("Settings.Workspace.TrashEmptied"), "36 MB", false), Assert.Contains(workspace.Notices, _ => true));
|
||||
Assert.Equal("Nothing in trash", rows.TrashText);
|
||||
|
||||
// An empty trash asks nothing.
|
||||
workspace.Asked = null;
|
||||
workspace.Plan = new WorkspaceTrashPlan(@"C:\workspace\.trash", [], 0, string.Empty);
|
||||
await rows.EmptyTrashAsync();
|
||||
Assert.Null(workspace.Asked);
|
||||
Assert.Null(SettingsTrashRequest(workspace.Plan));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ATrashThatChangedSinceItsPlanIsNotEmptied()
|
||||
{
|
||||
var item = new WorkspaceTrashItem("copy", 1_000, 1, DateTimeOffset.UnixEpoch);
|
||||
var workspace = new FakeWorkspace
|
||||
{
|
||||
Plan = new WorkspaceTrashPlan(@"C:\workspace\.trash", [item], 1_000, "before"),
|
||||
Empty = _ => throw new WorkspaceException(Loc.L("Errors.Workspace.TrashChanged")),
|
||||
};
|
||||
workspace.Measure = _ => Task.FromResult(new WorkspaceUsage(0, 1_000, 1_000, 1));
|
||||
var (_, rows, _) = WorkspaceRows(workspace);
|
||||
await rows.EmptyTrashAsync();
|
||||
Assert.Equal((Loc.L("Settings.Workspace.TrashNotEmptied"), Loc.L("Errors.Workspace.TrashChanged"), true), Assert.Contains(workspace.Notices, _ => true));
|
||||
Assert.Equal("1 item, 1 KB", rows.TrashText);
|
||||
|
||||
workspace.Notices.Clear();
|
||||
workspace.Empty = _ => throw new UnauthorizedAccessException("denied");
|
||||
await rows.EmptyTrashAsync();
|
||||
var (title, _, isError) = Assert.Contains(workspace.Notices, _ => true);
|
||||
Assert.Equal((Loc.L("Settings.Workspace.TrashNotEmptied"), true), (title, isError));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheWorkspaceRowsReachTheWorkspaceHost()
|
||||
{
|
||||
var local = _context.CreateTempDirectory("local");
|
||||
var environment = AppEnvironment.From(AppPaths.Resolve(_context.CreateTempDirectory("app"), local, []));
|
||||
var settings = new AppSettings { WorkspaceFolder = _context.CreateTempDirectory("fast") };
|
||||
var host = new WorkspaceHost(environment, settings, () => { }, () => null, () => null, () => null);
|
||||
var notices = new List<string>();
|
||||
var services = WorkspaceSettingsServices.For(host, new NoDialogs(), (title, _, _) => notices.Add(title), () => Task.CompletedTask);
|
||||
Assert.False(services.IsMoving());
|
||||
var rows = new WorkspaceSettingsRows(settings, () => { }, () => host.Root, () => { }, () => Task.CompletedTask, services);
|
||||
await rows.MeasureAsync();
|
||||
Assert.Equal(("Nothing in trash", false), (rows.TrashText, rows.HasTrash));
|
||||
await rows.EmptyTrashAsync();
|
||||
Assert.Empty(notices);
|
||||
Assert.True(rows.CanMove);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AMoveStoppedBeforeItEndedIsOfferedAgainAndHoldsChangeAndMove()
|
||||
{
|
||||
var stopped = true;
|
||||
var resumed = 0;
|
||||
var (_, rows, _) = WorkspaceRows(new FakeWorkspace(), move: () => Task.CompletedTask, isMoving: () => stopped, unfinished: () => stopped, resume: () =>
|
||||
{
|
||||
resumed++;
|
||||
stopped = false;
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
await rows.MeasureAsync();
|
||||
|
||||
// Change and Move say why they wait; Resume takes the move up.
|
||||
Assert.True(rows.CanResumeMove);
|
||||
Assert.Equal((Loc.L("Tooltips.Settings.Workspace.MoveUnfinished"), Loc.L("Tooltips.Settings.Workspace.MoveUnfinished")), (rows.ChangeToolTip, rows.MoveToolTip));
|
||||
Assert.False(rows.ChangeCommand.CanExecute(null));
|
||||
Assert.False(rows.MoveCommand.CanExecute(null));
|
||||
Assert.True(rows.ResumeMoveCommand.CanExecute(null));
|
||||
|
||||
rows.ResumeMoveCommand.Execute(null);
|
||||
await Chronos.App.Tests.Workspace.WorkspaceTestBed.UntilAsync(() => !rows.ResumeMoveCommand.IsRunning, "the move taken up");
|
||||
Assert.Equal(1, resumed);
|
||||
Assert.False(rows.CanResumeMove);
|
||||
Assert.Equal((Loc.L("Tooltips.Settings.ChangeWorkspace"), Loc.L("Tooltips.Settings.Workspace.Move")), (rows.ChangeToolTip, rows.MoveToolTip));
|
||||
Assert.True(rows.ChangeCommand.CanExecute(null));
|
||||
Assert.True(rows.MoveCommand.CanExecute(null));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AMoveThatSwitchedHereAndLeftPartOfItsOldFolderStillHoldsChangeAndMove()
|
||||
{
|
||||
// The folder in use holds no journal (the move switched to it), but the old folder still does: Resume clears it,
|
||||
// and another folder chosen first would leave that part with no Resume.
|
||||
var (_, rows, _) = WorkspaceRows(new FakeWorkspace(), move: () => Task.CompletedTask, isMoving: () => false, unfinished: () => true,
|
||||
resume: () => Task.CompletedTask);
|
||||
await rows.MeasureAsync();
|
||||
|
||||
Assert.True(rows.CanResumeMove);
|
||||
Assert.Equal((Loc.L("Tooltips.Settings.Workspace.MoveUnfinished"), Loc.L("Tooltips.Settings.Workspace.MoveUnfinished")), (rows.ChangeToolTip, rows.MoveToolTip));
|
||||
Assert.False(rows.ChangeCommand.CanExecute(null));
|
||||
Assert.False(rows.MoveCommand.CanExecute(null));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ADefaultMediaOrOpenPolicySetElsewhereReadsAsEverythingAppliesIt()
|
||||
{
|
||||
var (settings, rows, _) = WorkspaceRows();
|
||||
settings.WorkspaceDefaultMedia = "ORIGINALS";
|
||||
Assert.Equal(Chronos.Core.Project.BundleMedia.Originals, settings.EffectiveDefaultMedia);
|
||||
Assert.True(rows.IsDefaultOriginals);
|
||||
settings.WorkspaceDefaultMedia = "raw files";
|
||||
Assert.Equal(BundleMediaProxies, settings.EffectiveDefaultMedia);
|
||||
Assert.True(rows.IsDefaultProxies);
|
||||
|
||||
settings.WorkspaceOpenProject = (WorkspaceOpenPolicy)42;
|
||||
Assert.Equal(WorkspaceOpenPolicy.LastUsed, settings.EffectiveOpenPolicy);
|
||||
Assert.True(rows.IsOpenLastUsed);
|
||||
settings.WorkspaceOpenProject = WorkspaceOpenPolicy.Ask;
|
||||
Assert.Equal(WorkspaceOpenPolicy.Ask, settings.EffectiveOpenPolicy);
|
||||
Assert.False(rows.IsOpenLastUsed);
|
||||
}
|
||||
|
||||
private const int DeletePlansListed = Chronos.App.Archiving.DeletePlans.ListedLines;
|
||||
private const string BundleMediaProxies = Chronos.Core.Project.BundleMedia.Proxies;
|
||||
|
||||
private static ConfirmRequest? SettingsTrashRequest(WorkspaceTrashPlan plan) => WorkspaceSettingsRows.TrashRequest(plan);
|
||||
|
||||
private static (AppSettings Settings, WorkspaceSettingsRows Rows, Func<int> Saves) WorkspaceRows(FakeWorkspace? workspace = null, Func<Task>? move = null,
|
||||
Func<bool>? isMoving = null, Func<bool>? unfinished = null, Func<Task>? resume = null)
|
||||
{
|
||||
var settings = new AppSettings();
|
||||
var saves = 0;
|
||||
WorkspaceSettingsServices? services = workspace is null ? null : new WorkspaceSettingsServices
|
||||
{
|
||||
Usage = token => workspace.Measure(token),
|
||||
PlanTrash = _ => Task.FromResult(workspace.Plan),
|
||||
EmptyTrash = (plan, _) =>
|
||||
{
|
||||
var result = workspace.Empty(plan);
|
||||
workspace.Emptied.Add(plan);
|
||||
return Task.FromResult(result);
|
||||
},
|
||||
Confirm = request =>
|
||||
{
|
||||
workspace.Asked = request;
|
||||
return workspace.Confirmed;
|
||||
},
|
||||
Notify = (title, message, isError) => workspace.Notices.Add((title, message, isError)),
|
||||
Move = move,
|
||||
IsMoving = isMoving ?? (() => false),
|
||||
HasUnfinishedMove = unfinished is null ? null : _ => Task.FromResult(unfinished()),
|
||||
ResumeMove = resume,
|
||||
};
|
||||
var rows = new WorkspaceSettingsRows(settings, () => saves++, () => @"C:\Users\me\AppData\Local\Chronos\workspace", () => { }, () => Task.CompletedTask, services);
|
||||
return (settings, rows, () => saves);
|
||||
}
|
||||
|
||||
/// <summary>The workspace as Settings › Workspace reaches it: its usage, its trash's plan and emptying, the questions and toasts.</summary>
|
||||
private sealed class FakeWorkspace
|
||||
{
|
||||
public Func<CancellationToken, Task<WorkspaceUsage>> Measure { get; set; } = _ => Task.FromResult(WorkspaceUsage.None);
|
||||
public WorkspaceTrashPlan Plan { get; set; } = new(@"C:\workspace\.trash", [], 0, string.Empty);
|
||||
public Func<WorkspaceTrashPlan, WorkspaceTrashResult> Empty { get; set; } = plan => new WorkspaceTrashResult(plan.Items.Count, plan.Bytes);
|
||||
public bool Confirmed { get; set; } = true;
|
||||
public ConfirmRequest? Asked { get; set; }
|
||||
public List<WorkspaceTrashPlan> Emptied { get; } = [];
|
||||
public List<(string Title, string? Message, bool IsError)> Notices { get; } = [];
|
||||
}
|
||||
|
||||
private sealed class NoDialogs : IAppDialogs
|
||||
{
|
||||
public string? PickFolder(string title, string? initialFolder = null) => null;
|
||||
|
||||
public string? PickJsonFile(string title) => null;
|
||||
|
||||
public bool Confirm(ConfirmRequest request) => throw new InvalidOperationException("nothing to confirm");
|
||||
|
||||
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
|
||||
}
|
||||
}
|
||||
@@ -137,7 +137,7 @@ public sealed class ServerHomeTests(TestContext context)
|
||||
public async Task TheEditorFollowsTheServerAndRendersOnlyWhatItHolds()
|
||||
{
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
|
||||
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
|
||||
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false, WorkspaceVersionOnRender = false });
|
||||
var server = new FakeServer(bed);
|
||||
Connect(host, server);
|
||||
var projectId = await CheckoutAsync(bed, host);
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using Chronos.App.Archiving;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Jobs;
|
||||
using Chronos.App.Settings;
|
||||
using Chronos.App.Workspace;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.App.Tests.Workspace;
|
||||
|
||||
/// <summary>
|
||||
/// The desktop's side of the workspace clean-up (phase 5c, P4): the <c>workspace-clean</c> and <c>workspace-trash</c> steps
|
||||
/// run by a Cleanup job with no archive, the project open in Edit kept, a removal refused (its renders queued to be sent)
|
||||
/// while renders wait, and the trash emptied only as planned, once its number of entries is typed.
|
||||
/// </summary>
|
||||
[Category("workspace")]
|
||||
public sealed class WorkspaceCleanupHostTests(TestContext context)
|
||||
{
|
||||
static WorkspaceCleanupHostTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
||||
|
||||
private static readonly TimeSpan Day = TimeSpan.FromDays(1);
|
||||
|
||||
[Test]
|
||||
public async Task TheScheduledCleanUpRunsWithoutAnArchiveAndKeepsTheProjectOpenInEdit()
|
||||
{
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
|
||||
var settings = new AppSettings { WorkspaceAutoSync = false, WorkspaceCleanAfterDays = 30 };
|
||||
var host = bed.Host(settings);
|
||||
var mainId = await bed.CheckoutAsync(host);
|
||||
settings.WorkspaceOpened[mainId] = DateTimeOffset.UtcNow - 40 * Day;
|
||||
var project = host.Store.Find(mainId)!;
|
||||
Assert.True(Directory.Exists(project.ProxiesDirectory), "copied");
|
||||
|
||||
// Open in Edit: kept, with why.
|
||||
Guid? open = mainId;
|
||||
host.OpenProject = () => open;
|
||||
var kept = Assert.NotNull(await host.CleanAsync(cleanAfter: true));
|
||||
Assert.Empty(kept.Cleaned);
|
||||
Assert.True(kept.Kept is [{ Reason: WorkspaceKeep.Open }], "kept while open");
|
||||
Assert.Equal("open in Edit", WorkspaceCleanStep.Reason(WorkspaceKeep.Open));
|
||||
Assert.True(Directory.Exists(project.ProxiesDirectory), "the media stay");
|
||||
|
||||
// The schedule's Cleanup job, with no archive: the media go, the trash is only reported.
|
||||
open = null;
|
||||
await using var jobs = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(bed.Directory, "jobs.db")), bed.Ct);
|
||||
var service = new ArchiveService(jobs, new ArchiveServiceOptions { CleanupSteps = [new WorkspaceCleanStep(() => host), new WorkspaceTrashStep(() => host)] });
|
||||
await using var engine = new JobEngine(jobs, service.CreateJobHandlers(), new JobEngineOptions { WorkerId = "cleanup", PollInterval = TimeSpan.FromMilliseconds(50) });
|
||||
await engine.StartAsync(bed.Ct);
|
||||
var job = await engine.EnqueueAsync(ArchiveJobs.Cleanup(null, [WorkspaceCleanStep.StepName, WorkspaceTrashStep.StepName], 0), cancellationToken: bed.Ct);
|
||||
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(60));
|
||||
while ((await jobs.Jobs.GetAsync(job.Id, bed.Ct))!.State is JobState.Queued or JobState.Running)
|
||||
{
|
||||
Assert.True(DateTime.UtcNow < deadline, "the clean-up job did not finish");
|
||||
await Task.Delay(50, bed.Ct);
|
||||
}
|
||||
var done = (await jobs.Jobs.GetAsync(job.Id, bed.Ct))!;
|
||||
Assert.Equal(JobState.Done, done.State, done.Error ?? done.LogTail);
|
||||
Assert.Contains("Workspace: projects cleaned: 1", done.LogTail);
|
||||
Assert.Contains(Loc.L("Jobs.Log.WorkspaceTrash", Formatting.Count(0), Formatting.Bytes(0)), done.LogTail);
|
||||
Assert.False(Directory.Exists(project.ProxiesDirectory), "the media went");
|
||||
Assert.True(host.Store.Find(mainId) is not null && File.Exists(project.BundlePath), "the copy and its work stay");
|
||||
Assert.False((await host.FindAsync(mainId))!.HasMedia, "opening it copies the media again");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task RendersNotSentBlockTheRemovalAndAreQueuedToBeSent()
|
||||
{
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
|
||||
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
|
||||
var mainId = await bed.CheckoutAsync(host);
|
||||
var project = host.Store.Find(mainId)!;
|
||||
Directory.CreateDirectory(project.ExportsDirectory);
|
||||
File.WriteAllText(project.ExportFile("clip.mp4"), "rendered");
|
||||
project.WriteRenders(WorkspaceRenders.Empty.With(new WorkspaceRenderEntry(Guid.CreateVersion7(), Guid.CreateVersion7(), "clip.mp4", new string('a', 64), 8,
|
||||
"preset", "h264", 1920, 1080, 25, 4, mainId, null, null, DateTimeOffset.UtcNow, WorkspaceRenderEntry.Pending, null)));
|
||||
|
||||
var plan = await host.PlanRemovalAsync(mainId);
|
||||
Assert.True(plan is { UnsentRenders: 1, IsSafe: false }, "a render waits");
|
||||
var dialog = new RemoveCopyDialogViewModel(plan, _ => Task.CompletedTask, () => Task.CompletedTask, () => true, _ => { });
|
||||
Assert.Contains(dialog.Facts, f => f.Label == Loc.L("Editor.RemoveCopy.UnsentRenders") && f.Value == Formatting.Count(1));
|
||||
Assert.False(dialog.RemoveCommand.CanExecute(null), "not while renders wait");
|
||||
|
||||
var refused = await Assert.ThrowsAsync<WorkspaceException>(() => host.RemoveLocalCopyAsync(mainId, discard: false));
|
||||
Assert.Equal(Loc.L("Errors.Workspace.UnsentRenders"), refused.Message);
|
||||
Assert.NotNull(host.Store.Find(mainId), "nothing was removed");
|
||||
var sends = (await bed.Db.Jobs.ListAsync(null, JobKind.WorkspaceSend, cancellationToken: bed.Ct)).Items;
|
||||
var send = Assert.Contains(sends, j => j.TargetIds.Contains(bed.SequenceId));
|
||||
Assert.Equal(mainId, WorkspaceJobs.SendParameters(send)!.ProjectId);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheTrashIsEmptiedAsPlannedOnceItsNumberIsTyped()
|
||||
{
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 2);
|
||||
var host = bed.Host();
|
||||
Assert.True((await host.PlanTrashAsync()).IsEmpty, "no trash yet");
|
||||
var folder = WorkspaceTrash.FolderOf(host.Root);
|
||||
foreach (var name in new[] { "a", "b" })
|
||||
{
|
||||
var entry = Directory.CreateDirectory(Path.Combine(folder, Guid.CreateVersion7().ToString("N") + "-" + DateTime.UtcNow.Ticks)).FullName;
|
||||
File.WriteAllText(Path.Combine(entry, name + ".txt"), "kept aside " + name);
|
||||
}
|
||||
var usage = await host.UsageAsync();
|
||||
Assert.Equal(2L * "kept aside a".Length, usage.TrashBytes);
|
||||
|
||||
var plan = await host.PlanTrashAsync();
|
||||
Assert.Equal((2, 2L * "kept aside a".Length), (plan.Items.Count, plan.Bytes));
|
||||
// The Empty… confirmation lists both entries and asks for their number typed.
|
||||
var request = Assert.NotNull(WorkspaceSettingsRows.TrashRequest(plan));
|
||||
Assert.Equal("2", request.TypedConfirmation);
|
||||
Assert.True(request.IsDestructive, "erasing for good is destructive");
|
||||
|
||||
// An entry added since the plan: refused, nothing erased.
|
||||
var late = Directory.CreateDirectory(Path.Combine(folder, Guid.CreateVersion7().ToString("N") + "-" + DateTime.UtcNow.Ticks)).FullName;
|
||||
File.WriteAllText(Path.Combine(late, "late.txt"), "late");
|
||||
var refused = await Assert.ThrowsAsync<WorkspaceException>(() => host.EmptyTrashAsync(plan));
|
||||
Assert.Equal(Loc.L("Errors.Workspace.TrashChanged"), refused.Message);
|
||||
Assert.Equal(3, (await host.PlanTrashAsync()).Items.Count);
|
||||
|
||||
// As planned again: erased for good.
|
||||
plan = await host.PlanTrashAsync();
|
||||
var emptied = await host.EmptyTrashAsync(plan);
|
||||
Assert.Equal(3, emptied.Items);
|
||||
Assert.True((await host.PlanTrashAsync()).IsEmpty, "the trash is empty");
|
||||
|
||||
// An empty trash offers nothing to erase.
|
||||
Assert.Null(WorkspaceSettingsRows.TrashRequest(await host.PlanTrashAsync()));
|
||||
}
|
||||
}
|
||||
@@ -266,7 +266,8 @@ public sealed class WorkspaceFallbackTests(TestContext context)
|
||||
Assert.False(facts.TooLittleSpace, "the test drive has room for four small proxies");
|
||||
|
||||
var dialog = new OpenInWorkspaceDialogViewModel("Synthetic", await host.HomeProjectsAsync(bed.SequenceId), _ => { }, copy: facts);
|
||||
Assert.SequenceEqual([Loc.L("Editor.OpenWorkspace.Size"), Loc.L("Editor.OpenWorkspace.Free")], dialog.CopyFacts.Select(f => f.Label));
|
||||
Assert.SequenceEqual([Loc.L("Editor.OpenWorkspace.Size"), Loc.L("Editor.OpenWorkspace.Free"), Loc.L("Editor.OpenWorkspace.Originals")], dialog.CopyFacts.Select(f => f.Label));
|
||||
Assert.Equal(Formatting.Bytes(facts.OriginalsBytes!.Value), dialog.CopyFacts[2].Value);
|
||||
Assert.Equal(Formatting.Bytes(facts.Bytes), dialog.CopyFacts[0].Value);
|
||||
Assert.False(dialog.IsShortOfSpace);
|
||||
|
||||
|
||||
@@ -75,6 +75,102 @@ public sealed class WorkspaceHostTests(TestContext context)
|
||||
Assert.Empty(older.WorkspaceRecent);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ThePhase5cWorkspaceSettingsHaveTheirDefaultsAndSurviveTheSettingsFile()
|
||||
{
|
||||
var fresh = new AppSettings();
|
||||
Assert.Equal((100, BundleMedia.Proxies, true, 30, WorkspaceOpenPolicy.LastUsed),
|
||||
(fresh.WorkspaceSizeLimitGb, fresh.WorkspaceDefaultMedia, fresh.WorkspaceVersionOnRender, fresh.WorkspaceCleanAfterDays, fresh.WorkspaceOpenProject));
|
||||
Assert.Empty(fresh.WorkspaceOpened);
|
||||
|
||||
// A settings file of phase 5b gets them too.
|
||||
var older = AppSettings.Parse("""{ "Theme": "Light", "WorkspaceKeptVersions": 50 }""")!;
|
||||
Assert.Equal((100, BundleMedia.Proxies, true, 30, WorkspaceOpenPolicy.LastUsed, 50),
|
||||
(older.WorkspaceSizeLimitGb, older.WorkspaceDefaultMedia, older.WorkspaceVersionOnRender, older.WorkspaceCleanAfterDays, older.WorkspaceOpenProject,
|
||||
older.WorkspaceKeptVersions));
|
||||
Assert.Empty(older.WorkspaceOpened);
|
||||
|
||||
var project = Guid.CreateVersion7();
|
||||
var at = new DateTimeOffset(2026, 11, 4, 9, 30, 0, TimeSpan.FromHours(1));
|
||||
var settings = new AppSettings
|
||||
{
|
||||
WorkspaceSizeLimitGb = 0,
|
||||
WorkspaceDefaultMedia = BundleMedia.Originals,
|
||||
WorkspaceVersionOnRender = false,
|
||||
WorkspaceCleanAfterDays = 0,
|
||||
WorkspaceOpenProject = WorkspaceOpenPolicy.Ask,
|
||||
};
|
||||
settings.WorkspaceOpened[project] = at;
|
||||
var copy = AppSettings.Parse(settings.ToJson())!;
|
||||
Assert.Equal((0, BundleMedia.Originals, false, 0, WorkspaceOpenPolicy.Ask),
|
||||
(copy.WorkspaceSizeLimitGb, copy.WorkspaceDefaultMedia, copy.WorkspaceVersionOnRender, copy.WorkspaceCleanAfterDays, copy.WorkspaceOpenProject));
|
||||
Assert.Equal(at, copy.WorkspaceOpened[project]);
|
||||
Assert.Contains("\"Ask\"", settings.ToJson());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void WhenEachProjectWasOpenedStaysOnThisPc()
|
||||
{
|
||||
var project = Guid.CreateVersion7();
|
||||
var sequence = Guid.CreateVersion7();
|
||||
var at = new DateTimeOffset(2026, 11, 4, 9, 30, 0, TimeSpan.Zero);
|
||||
var mine = new AppSettings { WorkspaceFolder = @"D:\Fast\Workspace", WorkspaceSizeLimitGb = 250, WorkspaceOpenProject = WorkspaceOpenPolicy.Main };
|
||||
mine.WorkspaceRecent[sequence] = project;
|
||||
mine.WorkspaceOpened[project] = at;
|
||||
|
||||
// Reset puts the preferences back and keeps what this PC knows of its projects.
|
||||
var reset = mine.ResetKeepingState();
|
||||
Assert.Equal((AppSettings.DefaultWorkspaceSizeLimitGb, WorkspaceOpenPolicy.LastUsed), (reset.WorkspaceSizeLimitGb, reset.WorkspaceOpenProject));
|
||||
Assert.Equal((@"D:\Fast\Workspace", project, at), (reset.WorkspaceFolder, reset.WorkspaceRecent[sequence], reset.WorkspaceOpened[project]));
|
||||
|
||||
// Export carries the preferences, not this PC's projects.
|
||||
var exported = AppSettings.Parse(mine.ForExport().ToJson())!;
|
||||
Assert.Equal((250, WorkspaceOpenPolicy.Main, (string?)null), (exported.WorkspaceSizeLimitGb, exported.WorkspaceOpenProject, exported.WorkspaceFolder));
|
||||
Assert.Empty(exported.WorkspaceOpened);
|
||||
Assert.Empty(exported.WorkspaceRecent);
|
||||
Assert.Equal(at, mine.WorkspaceOpened[project]);
|
||||
|
||||
// Import takes another PC's preferences and keeps this PC's projects.
|
||||
var theirs = new AppSettings { WorkspaceSizeLimitGb = 40, WorkspaceFolder = @"E:\Elsewhere" };
|
||||
theirs.WorkspaceOpened[Guid.CreateVersion7()] = at.AddDays(-3);
|
||||
var imported = mine.KeepLocalIn(AppSettings.Parse(theirs.ToJson())!);
|
||||
Assert.Equal((40, @"D:\Fast\Workspace"), (imported.WorkspaceSizeLimitGb, imported.WorkspaceFolder));
|
||||
Assert.Equal(at, imported.WorkspaceOpened.Values.Single());
|
||||
Assert.Count(1, imported.WorkspaceOpened);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void OpeningAProjectRecordsWhenAndSavesIt()
|
||||
{
|
||||
var local = context.CreateTempDirectory("local");
|
||||
var installed = AppEnvironment.From(AppPaths.Resolve(context.CreateTempDirectory("app"), local, []));
|
||||
var settings = new AppSettings();
|
||||
var saves = 0;
|
||||
var host = new WorkspaceHost(installed, settings, () => saves++, () => null, () => null, () => null);
|
||||
var project = Guid.CreateVersion7();
|
||||
var at = new DateTimeOffset(2026, 11, 4, 10, 0, 0, TimeSpan.Zero);
|
||||
host.RecordOpened(project, at);
|
||||
Assert.Equal((at, 1), (settings.WorkspaceOpened[project], saves));
|
||||
host.RecordOpened(project);
|
||||
Assert.True(settings.WorkspaceOpened[project] > at, "opened again later");
|
||||
Assert.Equal(2, saves);
|
||||
Assert.False(host.IsMoving);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AProjectWithRendersNotSentIsNotSafeToRemoveAndOriginalsNeedTheirRoom()
|
||||
{
|
||||
var plan = new WorkspaceRemovalPlan(Guid.CreateVersion7(), "Main", 12, 1_000, 0, false, false, false);
|
||||
Assert.True(plan.IsSafe);
|
||||
Assert.False((plan with { UnsentRenders = 1 }).IsSafe);
|
||||
Assert.True((plan with { LastOriginals = 3 }).IsSafe, "the last originals go to the trash, never deleted");
|
||||
|
||||
var facts = new WorkspaceCopyFacts(1_000, 1_000 + WorkspaceJobs.CopySpaceReserve + 500, 2_000);
|
||||
Assert.False(facts.TooLittleSpaceFor(BundleMedia.Proxies));
|
||||
Assert.True(facts.TooLittleSpaceFor(BundleMedia.Originals));
|
||||
Assert.False((facts with { Free = null }).TooLittleSpaceFor(BundleMedia.Originals), "a drive whose room is unknown is tried");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SettingsWorkspaceRowsStoreEachChoiceAtOnce()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using Chronos.App.Editor;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Workspace;
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Imaging.Decoders;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Protocol.Client;
|
||||
using Chronos.Testing;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Tests.Workspace;
|
||||
|
||||
/// <summary>
|
||||
/// Phase 5c in Edit: a workspace project that holds its originals renders on this PC (<see cref="JobKind.WorkspaceRender"/>),
|
||||
/// also when its home is a server, and Settings › Workspace › Version on render saves a changed project as a version first.
|
||||
/// </summary>
|
||||
[Category("workspace")]
|
||||
public sealed class WorkspaceLocalRenderTests(TestContext context)
|
||||
{
|
||||
private const string Server = "https://nas.test:8443";
|
||||
|
||||
private static readonly ExportSettings Mjpeg = new()
|
||||
{
|
||||
Preset = new Auto<string>().WithManual("mjpeg-avi"),
|
||||
Overrides = new ExportOverrides { Width = 96, Height = 64 },
|
||||
NameTemplate = "clip-{codec}",
|
||||
};
|
||||
|
||||
static WorkspaceLocalRenderTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
||||
|
||||
[Test]
|
||||
public async Task TheOriginalsRenderOnThisPcEvenForAServerHome()
|
||||
{
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
|
||||
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false, WorkspaceVersionOnRender = false });
|
||||
var checkout = await host.CheckoutAsync(bed.SequenceId, null, null, BundleMedia.Originals, cancellationToken: bed.Ct);
|
||||
await bed.WaitForJobAsync(checkout.Copy.Id);
|
||||
var projectId = checkout.Project.Id;
|
||||
// Named the server's, as a copy downloaded from the server leaves it.
|
||||
var folder = host.Store.Find(projectId)!;
|
||||
var bundle = folder.ReadBundle();
|
||||
var home = new BundleHome(BundleHome.ServerKind, bed.SequenceId, null, Server);
|
||||
folder.WriteBundle(bundle with { Workspace = bundle.Workspace! with { Home = home } });
|
||||
|
||||
// Not signed in to the server: a render from the originals runs here all the same.
|
||||
var source = new WorkspaceSequenceSource(host.Sync, projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
|
||||
new WorkspaceServerHome((IRemoteSequenceApi?)null));
|
||||
var content = await source.LoadAsync(bed.Ct);
|
||||
var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
|
||||
await using (session)
|
||||
{
|
||||
Assert.True(source is { IsServerHome: true, RendersLocally: true, UnsentRenders: 0 });
|
||||
var requests = session.RenderRequests(Mjpeg);
|
||||
var request = requests.Single();
|
||||
Assert.Equal(JobKind.WorkspaceRender, request.Kind);
|
||||
Assert.SequenceEqual([bed.SequenceId], request.Targets);
|
||||
var parameters = Assert.NotNull(WorkspaceJobs.RenderParameters(new Job { Id = Guid.CreateVersion7(), Kind = request.Kind, ParametersJson = request.ParametersJson }));
|
||||
Assert.Equal((projectId, host.Store.Root, Server), (parameters.ProjectId, parameters.WorkspaceRoot, parameters.Server));
|
||||
var (render, _) = ProcessingJobs.ReadRender(parameters.RenderJson);
|
||||
Assert.NotNull(render.SettingsJson, "the portable settings travel with the job");
|
||||
|
||||
// Queued on this PC's engine and listed beside the server's jobs (the render itself is the Data tests': this bed decodes nothing).
|
||||
var jobId = await source.SubmitAsync(request, bed.Ct);
|
||||
var queued = Assert.NotNull(await bed.Db.Jobs.GetAsync(jobId, bed.Ct));
|
||||
Assert.Equal(JobKind.WorkspaceRender, queued.Kind);
|
||||
Assert.Contains(await source.ListJobsAsync(bed.Ct), j => j.Id == jobId);
|
||||
await WorkspaceTestBed.UntilAsync(() => bed.Db.Jobs.GetAsync(jobId).GetAwaiter().GetResult()?.State is JobState.Done or JobState.Failed, "the render ends");
|
||||
|
||||
// A render the ledger holds and the home has not taken: listed with the others, not sent.
|
||||
var output = Path.Combine(folder.ExportsDirectory, "clip-MJPEG.avi");
|
||||
Directory.CreateDirectory(folder.ExportsDirectory);
|
||||
await File.WriteAllBytesAsync(output, [1, 2, 3], bed.Ct);
|
||||
var entry = new WorkspaceRenderEntry(Guid.CreateVersion7(), jobId, "clip-MJPEG.avi", new string('0', 64), 3, "Custom", "Mjpeg", 96, 64, 25, 0.16,
|
||||
projectId, null, null, DateTimeOffset.UtcNow);
|
||||
using (await folder.LockAsync(TimeSpan.FromSeconds(TestTiming.Budget(10)), bed.Ct)) folder.WriteRenders(WorkspaceRenders.Empty.With(entry));
|
||||
var reread = await source.LoadAsync(bed.Ct);
|
||||
Assert.Equal(1, source.UnsentRenders);
|
||||
Assert.Equal((entry.RenderId, output), (reread.Renders[0].Id, reread.Renders[0].OutputPath));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ProxiesOnlyAsksWithItsPlanAndRemovesNothingUntilConfirmed()
|
||||
{
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
|
||||
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
|
||||
var checkout = await host.CheckoutAsync(bed.SequenceId, null, null, BundleMedia.Originals, cancellationToken: bed.Ct);
|
||||
await bed.WaitForJobAsync(checkout.Copy.Id);
|
||||
var projectId = checkout.Project.Id;
|
||||
var folder = host.Store.Find(projectId)!;
|
||||
var (source, session) = await bed.OpenAsync(host, projectId);
|
||||
var ui = new RecordingUi { ConfirmAnswer = false };
|
||||
await using (session)
|
||||
using (var menu = new ProjectMenuViewModel(host, source, session, ui))
|
||||
{
|
||||
await menu.RefreshAsync();
|
||||
Assert.True(menu.HoldsOriginals);
|
||||
Assert.False(menu.CopyOriginalsCommand.CanExecute(null));
|
||||
Assert.Equal(Loc.L("Tooltips.Editor.Project.HasOriginals"), menu.CopyOriginalsToolTip, "says why it is disabled");
|
||||
Assert.Equal(Loc.L("Tooltips.Editor.Project.ProxiesOnly"), menu.ProxiesOnlyToolTip);
|
||||
var originals = Directory.GetFiles(folder.OriginalsDirectory).Length;
|
||||
Assert.Equal(4, originals);
|
||||
var plan = await host.PlanProxiesOnlyAsync(projectId, bed.Ct);
|
||||
Assert.Equal(4, plan.Originals + plan.ToTrash);
|
||||
|
||||
// Asked first, with the plan: kept on Keep.
|
||||
var command = (AsyncRelayCommand)menu.ProxiesOnlyCommand;
|
||||
command.Execute(null);
|
||||
await WorkspaceTestBed.UntilAsync(() => ui.Confirmations.Count == 1 && !command.IsRunning, "the question");
|
||||
var asked = ui.Confirmations[0];
|
||||
Assert.Equal(Loc.L("Editor.ProxiesOnly.Title", menu.Name), asked.Heading);
|
||||
Assert.True(asked.IsDestructive);
|
||||
Assert.Contains(Loc.L("Editor.ProxiesOnly.Originals", Formatting.Count(plan.Originals)), asked.Detail!);
|
||||
if (plan.ToTrash > 0) Assert.Contains(Loc.L("Editor.ProxiesOnly.ToTrash", Formatting.Count(plan.ToTrash)), asked.Detail!);
|
||||
Assert.Equal(originals, Directory.GetFiles(folder.OriginalsDirectory).Length, "nothing removed on Keep");
|
||||
Assert.True(menu.HoldsOriginals);
|
||||
|
||||
// Confirmed: every original the library holds goes, any other to the trash; the proxies stay.
|
||||
ui.ConfirmAnswer = true;
|
||||
command.Execute(null);
|
||||
await WorkspaceTestBed.UntilAsync(() => ui.Confirmations.Count == 2 && !command.IsRunning, "the removal");
|
||||
Assert.False(Directory.Exists(folder.OriginalsDirectory));
|
||||
Assert.Equal(Loc.L("Editor.Workspace.OriginalsRemoved"), ui.Toasts[^1].Title);
|
||||
Assert.False(menu.HoldsOriginals);
|
||||
Assert.False(menu.ProxiesOnlyCommand.CanExecute(null));
|
||||
Assert.Equal(Loc.L("Tooltips.Editor.Project.ProxiesAlready"), menu.ProxiesOnlyToolTip, "says why it is disabled");
|
||||
Assert.True(folder.ReadMedia()!.Frames.All(f => f.File is not null && File.Exists(folder.MediaFile(f.File))));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SendAgainQueuesTheRendersNotSentAndOnlyThose()
|
||||
{
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 2);
|
||||
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
|
||||
var projectId = await bed.CheckoutAsync(host);
|
||||
var folder = host.Store.Find(projectId)!;
|
||||
Assert.False(await host.SendRendersAsync(projectId, bed.Ct), "nothing waits to be sent");
|
||||
Assert.False(await host.RenderSendPendingAsync(projectId, bed.SequenceId, bed.Ct));
|
||||
|
||||
Directory.CreateDirectory(folder.ExportsDirectory);
|
||||
await File.WriteAllBytesAsync(Path.Combine(folder.ExportsDirectory, "clip.avi"), [1, 2, 3], bed.Ct);
|
||||
var entry = new WorkspaceRenderEntry(Guid.CreateVersion7(), Guid.CreateVersion7(), "clip.avi", new string('0', 64), 3, "Custom", "Mjpeg", 96, 64, 25, 0.16,
|
||||
projectId, null, null, DateTimeOffset.UtcNow);
|
||||
using (await folder.LockAsync(TimeSpan.FromSeconds(TestTiming.Budget(10)), bed.Ct)) folder.WriteRenders(WorkspaceRenders.Empty.With(entry.AsFailed("cut")));
|
||||
|
||||
// A send that failed leaves its render unsent: Send again queues one send of every such render.
|
||||
Assert.Equal(1, WorkspaceCleaner.UnsentRenders(folder));
|
||||
Assert.True(await host.SendRendersAsync(projectId, bed.Ct));
|
||||
var sends = (await bed.Db.Jobs.ListAsync(null, 50, null, bed.Ct)).Items.Where(j => j.Kind == JobKind.WorkspaceSend).ToList();
|
||||
Assert.Equal(1, sends.Count);
|
||||
var parameters = Assert.NotNull(WorkspaceJobs.SendParameters(sends[0]));
|
||||
Assert.Equal((projectId, host.Store.Root), (parameters.ProjectId, parameters.WorkspaceRoot));
|
||||
Assert.Empty(parameters.RenderIds);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task VersionOnRenderSavesAChangedProjectFirst()
|
||||
{
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
|
||||
var settings = new AppSettings();
|
||||
Assert.True(settings is { WorkspaceVersionOnRender: true, WorkspaceAutoSync: true }, "on by default");
|
||||
var host = bed.Host(settings);
|
||||
var projectId = await bed.CheckoutAsync(host);
|
||||
var (source, session) = await bed.OpenAsync(host, projectId);
|
||||
var ui = new RecordingUi();
|
||||
await using (session)
|
||||
using (var menu = new ProjectMenuViewModel(host, source, session, ui))
|
||||
{
|
||||
await menu.RefreshAsync();
|
||||
var folder = host.Store.Find(projectId)!;
|
||||
var before = folder.Versions().Count;
|
||||
|
||||
// Nothing changed: nothing saved.
|
||||
Assert.True(await menu.ReadyToRenderAsync());
|
||||
Assert.Equal(before, folder.Versions().Count);
|
||||
|
||||
// Changed: saved as a version noted Render and sent (Sync automatically); the render names it.
|
||||
Assert.True(session.SetHero(2));
|
||||
Assert.True(await session.FlushAsync());
|
||||
Assert.True(await menu.ReadyToRenderAsync());
|
||||
var saved = folder.Versions()[^1];
|
||||
Assert.Equal((before + 1, Loc.L("Editor.Workspace.RenderNote")), (folder.Versions().Count, saved.Note));
|
||||
Assert.Equal(WorkspaceState.InSync, menu.Status!.State);
|
||||
Assert.Equal(Loc.L("Editor.Workspace.SavedForRender", Formatting.Count(folder.ReadBundle().Workspace!.Base!.Number)), ui.Toasts[^1].Title);
|
||||
var (render, _) = ProcessingJobs.ReadRender(session.RenderRequests(session.Project.Export)[0].ParametersJson);
|
||||
Assert.Equal(folder.ReadBundle().Workspace!.Base!.VersionId, render.ProjectVersionId);
|
||||
|
||||
// Off: the project renders as it is, no version saved.
|
||||
settings.WorkspaceVersionOnRender = false;
|
||||
Assert.True(session.SetHero(3));
|
||||
Assert.True(await session.FlushAsync());
|
||||
Assert.True(await menu.ReadyToRenderAsync());
|
||||
Assert.Equal(before + 1, folder.Versions().Count);
|
||||
Assert.Empty(ui.Confirmations);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Workspace;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.App.Tests.Workspace;
|
||||
|
||||
/// <summary>
|
||||
/// Settings › Workspace › Move… (phase 5c, P6) as the desktop runs it: the plan and its confirmation, the open project
|
||||
/// closed first, the workspace held while the move waits or runs, the setting switched only once the move verified
|
||||
/// everything, a failed move that leaves both as they were, and a move stopped before it ended taken up again.
|
||||
/// </summary>
|
||||
[Category("workspace")]
|
||||
public sealed class WorkspaceMoveTests(TestContext context)
|
||||
{
|
||||
static WorkspaceMoveTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
||||
|
||||
[Test]
|
||||
public async Task TheWorkspaceWaitsForTheMoveAndFollowsTheFolderOnlyOnceItEnded()
|
||||
{
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
|
||||
var settings = new AppSettings();
|
||||
var mainId = await bed.CheckoutAsync(bed.Host(settings));
|
||||
await using var moves = await MovesAsync(bed, settings);
|
||||
var host = moves.Host;
|
||||
var from = host.Root;
|
||||
var target = Path.Combine(bed.Directory, "moved workspace");
|
||||
|
||||
var plan = await host.PlanMoveAsync(target);
|
||||
Assert.True(plan.CanMove, plan.Refusal);
|
||||
Assert.Equal((from, Path.GetFullPath(target), true), (plan.From, plan.To, plan.SameVolume));
|
||||
var project = Assert.NotNull(plan.Projects.SingleOrDefault());
|
||||
Assert.Equal(mainId, project.ProjectId);
|
||||
Assert.True(plan.Files >= project.Files && project.Files > 0 && plan.Bytes > 0);
|
||||
|
||||
var failures = new List<string>();
|
||||
var closes = 0;
|
||||
var close = true;
|
||||
Task<bool> CloseProject()
|
||||
{
|
||||
closes++;
|
||||
return Task.FromResult(close);
|
||||
}
|
||||
|
||||
// Declined, or the open project kept open: nothing is queued.
|
||||
var dialogs = new MoveDialogs { Folder = target, Answer = false };
|
||||
Assert.False(await WorkspaceFolderChange.MoveAsync(host, dialogs, CloseProject, failures.Add));
|
||||
var asked = Assert.NotNull(dialogs.Asked.SingleOrDefault());
|
||||
Assert.Equal(Loc.L("Settings.Workspace.MovePlan.Message", plan.From, plan.To), asked.Message);
|
||||
Assert.Contains(Loc.L("Settings.Workspace.MovePlan.Projects", Formatting.Count(1)), asked.Detail);
|
||||
Assert.Contains(Loc.L("Settings.Workspace.MovePlan.SameVolume"), asked.Detail);
|
||||
Assert.True(asked is { IsDestructive: false, ActionText.Length: > 0, ActionToolTip.Length: > 0, SafeToolTip.Length: > 0 });
|
||||
Assert.Equal(0, closes, "nothing closed before the plan is confirmed");
|
||||
dialogs.Answer = true;
|
||||
close = false;
|
||||
Assert.False(await WorkspaceFolderChange.MoveAsync(host, dialogs, CloseProject, failures.Add));
|
||||
Assert.False(host.IsMoving);
|
||||
|
||||
// Queued: until it ends the workspace opens, copies, syncs and changes folder no more, and is not moved twice.
|
||||
close = true;
|
||||
Assert.True(await WorkspaceFolderChange.MoveAsync(host, dialogs, CloseProject, failures.Add));
|
||||
Assert.Empty(failures);
|
||||
Assert.True(host.IsMoving);
|
||||
var moving = Loc.L("Errors.Workspace.Moving");
|
||||
Assert.Equal(moving, (await Assert.ThrowsAsync<WorkspaceException>(() => host.FindAsync(mainId))).Message);
|
||||
Assert.Equal(moving, (await Assert.ThrowsAsync<WorkspaceException>(() => host.ProjectsOfAsync(bed.SequenceId))).Message);
|
||||
Assert.Equal(moving, (await Assert.ThrowsAsync<WorkspaceException>(() => host.SyncAsync(mainId))).Message);
|
||||
Assert.Equal(moving, (await Assert.ThrowsAsync<WorkspaceException>(() => host.QueueCopyAsync(mainId))).Message);
|
||||
Assert.Equal(moving, (await Assert.ThrowsAsync<WorkspaceException>(() => host.CheckoutAsync(bed.SequenceId, mainId, null))).Message);
|
||||
Assert.Equal(moving, (await Assert.ThrowsAsync<WorkspaceException>(() => host.UseFolderAsync(Path.Combine(bed.Directory, "elsewhere")))).Message);
|
||||
Assert.False(await WorkspaceFolderChange.MoveAsync(host, dialogs, CloseProject, failures.Add));
|
||||
Assert.SequenceEqual([moving], failures);
|
||||
Assert.Equal(((string?)null, 0), (settings.WorkspaceFolder, moves.Saves), "the setting waits for the move");
|
||||
|
||||
await moves.Engine.StartAsync(context.Cancellation);
|
||||
var job = Assert.NotNull((await moves.Db.Jobs.ListAsync(null, JobKind.WorkspaceMove, 5, cancellationToken: context.Cancellation)).Items.SingleOrDefault());
|
||||
await moves.WaitAsync(job.Id, JobState.Done);
|
||||
await WorkspaceTestBed.UntilAsync(() => !host.IsMoving, "the workspace is let go");
|
||||
|
||||
Assert.Equal((Path.GetFullPath(target), 1), (settings.WorkspaceFolder, moves.Saves));
|
||||
Assert.Equal(Path.GetFullPath(target), host.Root);
|
||||
Assert.Equal(mainId, Assert.NotNull(await host.FindAsync(mainId)).ProjectId);
|
||||
Assert.Equal(mainId, (await host.ListAsync()).Single().ProjectId);
|
||||
Assert.False(Directory.Exists(Path.Combine(from, mainId.ToString("N"))), "the project left the folder");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AMoveThatFailsLeavesTheSettingAndTheWorkspaceWhereTheyWere()
|
||||
{
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
|
||||
var settings = new AppSettings();
|
||||
var mainId = await bed.CheckoutAsync(bed.Host(settings));
|
||||
await using var moves = await MovesAsync(bed, settings);
|
||||
var host = moves.Host;
|
||||
var from = host.Root;
|
||||
var target = Path.Combine(bed.Directory, "target");
|
||||
|
||||
// A workspace job waiting refuses the plan.
|
||||
var copy = await moves.Engine.EnqueueAsync(JobKind.WorkspaceCopy, [bed.SequenceId], "copy", null, cancellationToken: context.Cancellation);
|
||||
Assert.Equal(Loc.L("Errors.Workspace.JobsRunning"), (await host.PlanMoveAsync(target)).Refusal);
|
||||
await moves.Engine.CancelAsync(copy.Id, context.Cancellation);
|
||||
|
||||
var plan = await host.PlanMoveAsync(target);
|
||||
await host.QueueMoveAsync(plan);
|
||||
// Meanwhile the target became a workspace of its own: the job refuses it.
|
||||
_ = new WorkspaceStore(target);
|
||||
await moves.Engine.StartAsync(context.Cancellation);
|
||||
var job = Assert.NotNull((await moves.Db.Jobs.ListAsync(null, JobKind.WorkspaceMove, 5, cancellationToken: context.Cancellation)).Items.SingleOrDefault());
|
||||
var failed = await moves.WaitAsync(job.Id, JobState.Failed);
|
||||
Assert.Equal(Loc.L("Errors.Workspace.MoveTargetNotEmpty", Path.GetFullPath(target)), failed.Error);
|
||||
await WorkspaceTestBed.UntilAsync(() => !host.IsMoving, "the workspace is let go");
|
||||
|
||||
Assert.Equal(((string?)null, 0, from), (settings.WorkspaceFolder, moves.Saves, host.Root));
|
||||
Assert.Equal(mainId, Assert.NotNull(await host.FindAsync(mainId)).ProjectId);
|
||||
Assert.Empty(new WorkspaceStore(target).List());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AMoveStoppedBeforeItEndedIsOfferedAgainAndGoesOn()
|
||||
{
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
|
||||
var settings = new AppSettings();
|
||||
var mainId = await bed.CheckoutAsync(bed.Host(settings));
|
||||
await using var moves = await MovesAsync(bed, settings);
|
||||
var host = moves.Host;
|
||||
var from = host.Root;
|
||||
var target = Path.Combine(bed.Directory, "target");
|
||||
|
||||
// The program closed as the move began: its journal is in the folder, and no job waits for it.
|
||||
var plan = await host.PlanMoveAsync(target);
|
||||
using (var closed = new CancellationTokenSource())
|
||||
{
|
||||
await closed.CancelAsync();
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => new WorkspaceMover(from, target).MoveAsync(plan.Fingerprint, cancellationToken: closed.Token));
|
||||
}
|
||||
Assert.True(host.IsMoving, "a journal holds the workspace");
|
||||
Assert.Equal(Loc.L("Errors.Workspace.Moving"), (await Assert.ThrowsAsync<WorkspaceException>(() => host.FindAsync(mainId))).Message);
|
||||
var journal = Assert.NotNull(await host.UnfinishedMoveAsync());
|
||||
Assert.Equal((Path.GetFullPath(target), WorkspaceMoveStage.Moving), (journal.To, journal.Stage));
|
||||
|
||||
var job = await host.ResumeMoveAsync(journal);
|
||||
Assert.Null(await host.UnfinishedMoveAsync());
|
||||
await moves.Engine.StartAsync(context.Cancellation);
|
||||
var done = await moves.WaitAsync(job.Id, JobState.Done);
|
||||
Assert.Contains(Loc.L("Archive.Log.WorkspaceMoveResumed", Path.Combine(from, WorkspaceMover.JournalFile)), done.LogTail);
|
||||
await WorkspaceTestBed.UntilAsync(() => !host.IsMoving, "the workspace is let go");
|
||||
Assert.Equal(Path.GetFullPath(target), settings.WorkspaceFolder);
|
||||
Assert.Equal(mainId, Assert.NotNull(await host.FindAsync(mainId)).ProjectId);
|
||||
Assert.Null(await host.UnfinishedMoveAsync());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A workspace over the bed's folder whose move jobs run on an engine of their own (over an index of their own, so the
|
||||
/// bed's engine never takes them), which tells the workspace once a move ended; the engine is started by the test.
|
||||
/// </summary>
|
||||
private async Task<Moves> MovesAsync(WorkspaceTestBed bed, AppSettings settings)
|
||||
{
|
||||
var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory("moves"), "index.db")), context.Cancellation);
|
||||
var moves = new Moves(db);
|
||||
var options = new WorkspaceJobOptions(WorkspaceJobOptions.For(bed.Archives).Processing, () => false, (f, t) => moves.Host.MovedAsync(f, t));
|
||||
moves.Engine = new JobEngine(db, WorkspaceJobs.CreateHandlers(db, bed.Archives, null, options),
|
||||
new JobEngineOptions { Workers = 1, WorkerId = "moves", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
|
||||
moves.Host = new WorkspaceHost(bed.Environment, settings, () => moves.Saves++, () => db, () => bed.Archives, () => moves.Engine)
|
||||
{
|
||||
LockWait = TimeSpan.FromSeconds(TestTiming.Budget(10)),
|
||||
};
|
||||
return moves;
|
||||
}
|
||||
|
||||
private sealed class Moves(ChronosDatabase db) : IAsyncDisposable
|
||||
{
|
||||
public ChronosDatabase Db { get; } = db;
|
||||
public JobEngine Engine { get; set; } = null!;
|
||||
public WorkspaceHost Host { get; set; } = null!;
|
||||
public int Saves { get; set; }
|
||||
|
||||
public async Task<Job> WaitAsync(Guid jobId, JobState expected)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(60));
|
||||
while (true)
|
||||
{
|
||||
var job = await Db.Jobs.GetAsync(jobId);
|
||||
if (job is { State: JobState.Done or JobState.Failed or JobState.Cancelled })
|
||||
{
|
||||
Assert.Equal(expected, job.State, job.Error ?? job.LogTail);
|
||||
return job;
|
||||
}
|
||||
if (DateTime.UtcNow > deadline) Assert.Fail($"Job {jobId} still {job?.State} after its time budget");
|
||||
await Task.Delay(50);
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await Engine.DisposeAsync();
|
||||
await Db.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Dialogs that pick <see cref="Folder"/> and answer every confirmation with <see cref="Answer"/>, recording what they were asked.</summary>
|
||||
private sealed class MoveDialogs : IAppDialogs
|
||||
{
|
||||
public string? Folder { get; set; }
|
||||
public bool Answer { get; set; }
|
||||
public List<ConfirmRequest> Asked { get; } = [];
|
||||
public string? PickFolder(string title, string? initialFolder = null) => Folder;
|
||||
public string? PickJsonFile(string title) => null;
|
||||
|
||||
public bool Confirm(ConfirmRequest request)
|
||||
{
|
||||
Asked.Add(request);
|
||||
return Answer;
|
||||
}
|
||||
|
||||
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
using System.IO;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Shell;
|
||||
using Chronos.App.Tests.Editor;
|
||||
using Chronos.App.Tests.Windows;
|
||||
using Chronos.App.Workspace;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Codecs.Jpeg;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Metadata;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Windows.Shell;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.App.Tests.Workspace;
|
||||
|
||||
/// <summary>
|
||||
/// Phase 5c in Edit: "Open in workspace" offers the originals (Settings › Workspace › Media first, the proxies when the
|
||||
/// drive has no room), and Settings › Workspace › Open project picks the project a sequence with several opens.
|
||||
/// </summary>
|
||||
[WindowsOnly]
|
||||
[Serial]
|
||||
[Timeout(300_000)]
|
||||
[Category("workspace")]
|
||||
public sealed class WorkspaceOpenPolicyTests(TestContext context)
|
||||
{
|
||||
private static readonly SequenceProject Main = new() { Id = Guid.CreateVersion7(), SequenceId = Guid.CreateVersion7(), Name = ProjectService.MainName, IsMain = true };
|
||||
|
||||
[Test]
|
||||
public void TheOpenDialogStartsWithTheMediaOfTheSettingsWhenTheyFit()
|
||||
{
|
||||
UiLanguage.Apply("en");
|
||||
var room = new WorkspaceCopyFacts(10_000_000, 100_000_000_000, 4_000_000_000);
|
||||
using var proxies = new OpenInWorkspaceDialogViewModel("Harbour", [Main], _ => { }, copy: room);
|
||||
Assert.True(proxies is { IsProxies: true, IsOriginals: false, CanCopyOriginals: true });
|
||||
Assert.Equal(BundleMedia.Proxies, proxies.Media);
|
||||
Assert.Contains(proxies.CopyFacts, f => f.Label == Loc.L("Editor.OpenWorkspace.Originals"));
|
||||
|
||||
using var originals = new OpenInWorkspaceDialogViewModel("Harbour", [Main], _ => { }, copy: room, defaultMedia: BundleMedia.Originals);
|
||||
Assert.True(originals is { IsOriginals: true, IsProxies: false, IsShortOfSpace: false });
|
||||
Assert.Equal(Loc.L("Tooltips.Editor.OpenWorkspace.OriginalsReady"), originals.OriginalsToolTip);
|
||||
originals.OpenCommand.Execute(null);
|
||||
Assert.Equal(new OpenChoice(Main.Id, null, BundleMedia.Originals), originals.Choice.Result);
|
||||
|
||||
// The drive has room for the proxies, not the originals: they are offered disabled, why in the tooltip.
|
||||
var tight = new WorkspaceCopyFacts(10_000_000, WorkspaceJobs.CopySpaceReserve + 20_000_000, 4_000_000_000);
|
||||
using var refused = new OpenInWorkspaceDialogViewModel("Harbour", [Main], _ => { }, copy: tight, defaultMedia: BundleMedia.Originals);
|
||||
Assert.True(refused is { IsProxies: true, CanCopyOriginals: false, IsShortOfSpace: false });
|
||||
refused.IsOriginals = true;
|
||||
Assert.False(refused.IsOriginals, "never chosen without room");
|
||||
Assert.Equal(Loc.L("Tooltips.Editor.OpenWorkspace.NoRoomOriginals"), refused.OriginalsToolTip);
|
||||
refused.OpenCommand.Execute(null);
|
||||
Assert.Equal(BundleMedia.Proxies, refused.Choice.Result!.Media);
|
||||
|
||||
// Not measured (a server out of reach): offered, the copy measures again before it writes.
|
||||
using var unmeasured = new OpenInWorkspaceDialogViewModel("Harbour", [Main], _ => { }, server: true);
|
||||
Assert.True(unmeasured.CanCopyOriginals);
|
||||
Assert.Equal(Loc.L("Tooltips.Editor.OpenWorkspace.OriginalsReady.Server"), unmeasured.OriginalsToolTip);
|
||||
unmeasured.IsOriginals = true;
|
||||
Assert.Equal(BundleMedia.Originals, unmeasured.Media);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public Task TheOriginalsAreCopiedAndTheOpenProjectFollowsTheSettings() => ScreenHost.RunAsync(async () =>
|
||||
{
|
||||
var directory = context.CreateTempDirectory("workspace-open-policy");
|
||||
var environment = AppEnvironment.From(AppPaths.Resolve(Directory.CreateDirectory(Path.Combine(directory, "app")).FullName,
|
||||
Directory.CreateDirectory(Path.Combine(directory, "local")).FullName, []));
|
||||
UiLanguage.Apply("en");
|
||||
var settings = new AppSettings
|
||||
{
|
||||
Language = "en",
|
||||
FirstRunCompleted = true,
|
||||
CheckForUpdates = false,
|
||||
WorkspaceDefaultMedia = BundleMedia.Originals,
|
||||
};
|
||||
var services = new AppServices(environment, settings, () => { }, new NoDialogs());
|
||||
await services.AttachAsync(await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(environment.DatabasePath)), startEngine: true);
|
||||
var shell = new ShellViewModel(services);
|
||||
try
|
||||
{
|
||||
var sequenceId = await SequenceAsync(services, Path.Combine(directory, "archive"));
|
||||
var section = shell.Sequence;
|
||||
|
||||
// The originals, as the settings say: copied beside the proxies, and the project's menu offers Proxies only.
|
||||
shell.OpenSequence(sequenceId);
|
||||
await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenInWorkspaceDialogViewModel, "Open in workspace asks the first time");
|
||||
var ask = (OpenInWorkspaceDialogViewModel)section.Dialog!;
|
||||
Assert.True(ask.IsOriginals, "the settings' media first");
|
||||
ask.OpenCommand.Execute(null);
|
||||
await WorkspaceTestBed.UntilAsync(() => section.Editor is not null, "the project opens once its media are copied");
|
||||
var mainId = section.OpenProjectId!.Value;
|
||||
var menu = Assert.NotNull(section.Editor!.Project);
|
||||
Assert.True(menu.HoldsOriginals);
|
||||
var media = services.Workspace.Store.Find(mainId)!.ReadMedia()!;
|
||||
Assert.True(media.HoldsOriginals && media.Frames.All(f => f.HasOriginal), "every frame has its original");
|
||||
Assert.True(settings.WorkspaceOpened.ContainsKey(mainId), "the open is recorded for the clean-up");
|
||||
Assert.True(await section.ConfirmCloseAsync());
|
||||
await section.CloseAsync();
|
||||
shell.KeepSequence(null);
|
||||
|
||||
// A second project here, opened last.
|
||||
var vertical = (await services.Archives!.Projects.CreateAsync(sequenceId, "Vertical", cancellationToken: context.Cancellation)).Id;
|
||||
var checkout = await services.Workspace.CheckoutAsync(sequenceId, vertical, null);
|
||||
await WorkspaceTestBed.UntilAsync(() => services.Database!.Jobs.GetAsync(checkout.Copy.Id).GetAwaiter().GetResult()?.State == JobState.Done, "its media are copied");
|
||||
services.Workspace.Remember(sequenceId, vertical);
|
||||
|
||||
// Last used: Vertical.
|
||||
settings.WorkspaceOpenProject = WorkspaceOpenPolicy.LastUsed;
|
||||
Assert.Equal(vertical, await OpenAsync(shell, sequenceId));
|
||||
|
||||
// Main, whichever opened last.
|
||||
settings.WorkspaceOpenProject = WorkspaceOpenPolicy.Main;
|
||||
Assert.Equal(mainId, await OpenAsync(shell, sequenceId));
|
||||
|
||||
// Ask: the projects here are listed, the one opened last first; closing it opens nothing.
|
||||
settings.WorkspaceOpenProject = WorkspaceOpenPolicy.Ask;
|
||||
shell.OpenSequence(sequenceId);
|
||||
await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenProjectDialogViewModel, "Open which project? asks");
|
||||
var which = (OpenProjectDialogViewModel)section.Dialog!;
|
||||
Assert.Equal(2, which.Projects.Count);
|
||||
Assert.Equal(mainId, which.SelectedProject!.Entry.ProjectId);
|
||||
which.CloseCommand.Execute(null);
|
||||
await WorkspaceTestBed.UntilAsync(() => section.Dialog is null, "closed without a choice");
|
||||
Assert.Null(section.Editor);
|
||||
shell.KeepSequence(null);
|
||||
shell.OpenSequence(sequenceId);
|
||||
await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenProjectDialogViewModel, "Open which project? asks again");
|
||||
which = (OpenProjectDialogViewModel)section.Dialog!;
|
||||
which.SelectedProject = which.Projects.Single(p => p.Entry.ProjectId == vertical);
|
||||
which.OpenCommand.Execute(null);
|
||||
await WorkspaceTestBed.UntilAsync(() => section.Editor is not null, "the project chosen opens");
|
||||
Assert.Equal(vertical, section.OpenProjectId);
|
||||
}
|
||||
finally
|
||||
{
|
||||
await shell.Sequence.CloseAsync();
|
||||
shell.Dispose();
|
||||
await services.DisposeAsync();
|
||||
}
|
||||
});
|
||||
|
||||
/// <summary>Opens the sequence in Edit as the settings say and returns the project that opened, closed again.</summary>
|
||||
private static async Task<Guid> OpenAsync(ShellViewModel shell, Guid sequenceId)
|
||||
{
|
||||
var section = shell.Sequence;
|
||||
shell.OpenSequence(sequenceId);
|
||||
await WorkspaceTestBed.UntilAsync(() => section.Editor is not null, "the project opens");
|
||||
Assert.Null(section.Dialog);
|
||||
var opened = section.OpenProjectId!.Value;
|
||||
Assert.True(await section.ConfirmCloseAsync());
|
||||
await section.CloseAsync();
|
||||
shell.KeepSequence(null);
|
||||
return opened;
|
||||
}
|
||||
|
||||
/// <summary>An archive with one sequence of six synthetic photos, indexed.</summary>
|
||||
private async Task<Guid> SequenceAsync(AppServices services, string root)
|
||||
{
|
||||
var archives = services.Archives!;
|
||||
var archive = await archives.CreateAsync(root, "Test");
|
||||
var sequence = EditorFixture.Sequence(6);
|
||||
var folder = Path.Combine(root, "Synthetic");
|
||||
Directory.CreateDirectory(folder);
|
||||
for (var i = 0; i < sequence.Count; i++)
|
||||
{
|
||||
using var image = sequence.Render(i);
|
||||
var exif = ExifWriter.BuildJpegApp1(sequence.Metadata[i]);
|
||||
File.WriteAllBytes(Path.Combine(folder, $"IMG_{i + 1:0000}.JPG"), JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 90, App1Segments = [exif[4..]] }));
|
||||
}
|
||||
await archives.Indexer.ScanAsync(archive, ScanMode.Full, null, _ => ValueTask.CompletedTask, context.Cancellation);
|
||||
return (await services.Database!.Sequences.ListLocationsAsync(archive.Id, context.Cancellation)).Single().Id;
|
||||
}
|
||||
|
||||
/// <summary>Dialogs that pick nothing and decline every confirmation.</summary>
|
||||
private sealed class NoDialogs : IAppDialogs
|
||||
{
|
||||
public string? PickFolder(string title, string? initialFolder = null) => null;
|
||||
public string? PickJsonFile(string title) => null;
|
||||
public bool Confirm(ConfirmRequest request) => false;
|
||||
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
|
||||
}
|
||||
}
|
||||
@@ -53,7 +53,7 @@ public sealed class WorkspaceSectionTests(TestContext context)
|
||||
await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenInWorkspaceDialogViewModel, "Open in workspace asks the first time");
|
||||
var ask = (OpenInWorkspaceDialogViewModel)section.Dialog!;
|
||||
Assert.Equal(Loc.L("Editor.Project.Main"), ask.SelectedProject!.Label, "Main, made from the sequence's settings, is offered first");
|
||||
Assert.True(ask.IsProxies && !ask.CanCopyOriginals, "proxies; the originals come later");
|
||||
Assert.True(ask.IsProxies && ask.CanCopyOriginals, "the proxies first, the originals offered (Settings › Workspace › Media)");
|
||||
Assert.True(section.ShowsPicker && !section.IsLoading, "the picker shows behind the dialog, not the progress bar");
|
||||
ask.OpenCommand.Execute(null);
|
||||
Assert.Null(section.Dialog);
|
||||
@@ -143,7 +143,8 @@ public sealed class WorkspaceSectionTests(TestContext context)
|
||||
shell.OpenSequence(sequenceId);
|
||||
await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenInWorkspaceDialogViewModel, "Open in workspace asks the first time");
|
||||
var ask = (OpenInWorkspaceDialogViewModel)section.Dialog!;
|
||||
Assert.SequenceEqual([Loc.L("Editor.OpenWorkspace.Size"), Loc.L("Editor.OpenWorkspace.Free")], ask.CopyFacts.Select(f => f.Label), "the copy's facts reach the dialog");
|
||||
Assert.SequenceEqual([Loc.L("Editor.OpenWorkspace.Size"), Loc.L("Editor.OpenWorkspace.Free"), Loc.L("Editor.OpenWorkspace.Originals")], ask.CopyFacts.Select(f => f.Label),
|
||||
"the copy's facts reach the dialog");
|
||||
ask.OpenCommand.Execute(null);
|
||||
await WorkspaceTestBed.UntilAsync(() => toasts.Any(t => t.Title == Loc.L("Editor.Workspace.OpenFailed")), "the refusal is said");
|
||||
var refused = toasts.Single(t => t.Title == Loc.L("Editor.Workspace.OpenFailed"));
|
||||
|
||||
@@ -38,7 +38,7 @@ public sealed class ProjectBundleTests(TestContext context)
|
||||
// The archive's own meta files are JSON too, but not project files.
|
||||
Assert.Throws<InvalidDataException>(() => ProjectBundle.Parse("""{ "schemaVersion": 1, "id": "0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01" }"""));
|
||||
var json = Sample().ToJson();
|
||||
Assert.Throws<InvalidDataException>(() => ProjectBundle.Parse(json.Replace("\"formatVersion\": 1", "\"formatVersion\": 3", StringComparison.Ordinal)));
|
||||
Assert.Throws<InvalidDataException>(() => ProjectBundle.Parse(json.Replace("\"formatVersion\": 1", $"\"formatVersion\": {ProjectBundle.CurrentFormatVersion + 1}", StringComparison.Ordinal)));
|
||||
Assert.Throws<InvalidDataException>(() => ProjectBundle.Parse(json.Replace(SequenceId.ToString(), "not-a-guid", StringComparison.Ordinal)));
|
||||
Assert.Throws<InvalidDataException>(() => ProjectBundle.Parse(json.Replace("\"version\": 1", "\"version\": 99", StringComparison.Ordinal)));
|
||||
Assert.Throws<InvalidDataException>(() => ProjectBundle.Parse(json.Replace("\"folder\"", "\"place\"", StringComparison.Ordinal)));
|
||||
@@ -62,6 +62,12 @@ public sealed class ProjectBundleTests(TestContext context)
|
||||
Assert.Equal(bundle.Project.ToJson(), back.Project.ToJson());
|
||||
Assert.False(back.IsReadOnly);
|
||||
|
||||
// Holding the originals: format 3, which a Chronos before phase 5c refuses as newer rather than reading as proxies.
|
||||
var originals = bundle with { Workspace = workspace with { Media = new BundleMedia(BundleMedia.Originals, 12) } };
|
||||
Assert.Contains("\"formatVersion\": 3", originals.ToJson());
|
||||
Assert.Equal(BundleMedia.Originals, ProjectBundle.Parse(originals.ToJson()).Workspace!.Media.Kind);
|
||||
Assert.Equal(3, ProjectBundle.CurrentFormatVersion);
|
||||
|
||||
// A server home names its server; a project not pulled yet has no base.
|
||||
var remote = workspace with { Home = new BundleHome(BundleHome.ServerKind, SequenceId, Server: "https://nas:8443"), Base = null, IsMain = true };
|
||||
Assert.Equal(remote, ProjectBundle.Parse((bundle with { Workspace = remote }).ToJson()).Workspace);
|
||||
|
||||
@@ -30,6 +30,30 @@ public sealed class JobPriorityQueueTests
|
||||
Assert.Equal(JobKindPriority.Low, (queue with { Levels = new Dictionary<JobKind, JobKindPriority> { [JobKind.Render] = JobKindPriority.Low } }).LevelOf(JobKind.Render));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ALocalRenderAndAWorkspaceMoveGoFirstAndSendingARenderHomeWaitsItsTurn()
|
||||
{
|
||||
var queue = new JobPriorityQueue();
|
||||
// The user waits on a local render as on a render, and Edit is held while the workspace moves.
|
||||
Assert.Equal(JobKindPriority.High, queue.LevelOf(JobKind.WorkspaceRender));
|
||||
Assert.Equal(JobKindPriority.High, queue.LevelOf(JobKind.WorkspaceMove));
|
||||
Assert.Equal(JobKindPriority.Normal, queue.LevelOf(JobKind.WorkspaceSend));
|
||||
var on = queue with { Enabled = true };
|
||||
Assert.True(on.Interrupts(JobKind.WorkspaceRender, JobKind.WorkspaceSend));
|
||||
Assert.False(on.Interrupts(JobKind.WorkspaceSend, JobKind.Scan));
|
||||
// The defaults are no change: settings store none of them, and read back as they are.
|
||||
var defaults = new Dictionary<JobKind, JobKindPriority>
|
||||
{
|
||||
[JobKind.WorkspaceRender] = JobKindPriority.High,
|
||||
[JobKind.WorkspaceSend] = JobKindPriority.Normal,
|
||||
[JobKind.WorkspaceMove] = JobKindPriority.High,
|
||||
};
|
||||
Assert.Empty(JobPriorityQueue.Changed(defaults));
|
||||
var changed = JobPriorityQueue.Changed(new Dictionary<JobKind, JobKindPriority> { [JobKind.WorkspaceSend] = JobKindPriority.Low });
|
||||
Assert.Equal("low", changed["workspace-send"]);
|
||||
Assert.Equal(JobKindPriority.Low, JobPriorityQueue.From(true, changed).LevelOf(JobKind.WorkspaceSend));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void OnlyAHigherLevelInterruptsAndOnlyWhileTheQueueIsOn()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Jobs;
|
||||
|
||||
/// <summary>The names the jobs' kinds carry on the wire and in settings (BRIEF §14.6): stable once shipped.</summary>
|
||||
[Category("jobs")]
|
||||
public sealed class JobWireTests
|
||||
{
|
||||
[Theory]
|
||||
[Case(JobKind.WorkspaceCopy, 20, "workspace-copy")]
|
||||
[Case(JobKind.WorkspaceRender, 21, "workspace-render")]
|
||||
[Case(JobKind.WorkspaceSend, 22, "workspace-send")]
|
||||
[Case(JobKind.WorkspaceMove, 23, "workspace-move")]
|
||||
public void TheWorkspaceJobsKeepTheirValueAndName(JobKind kind, int value, string name)
|
||||
{
|
||||
Assert.Equal(value, (int)kind);
|
||||
Assert.Equal(name, JobWire.Kind(kind));
|
||||
Assert.True(JobWire.TryParseKind(name, out var parsed), name);
|
||||
Assert.Equal(kind, parsed);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EveryKindHasItsOwnName()
|
||||
{
|
||||
var names = Enum.GetValues<JobKind>().Select(JobWire.Kind).ToList();
|
||||
Assert.Equal(names.Count, names.Distinct(StringComparer.Ordinal).Count());
|
||||
Assert.False(JobWire.TryParseKind("workspace-teleport", out _));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Data.Tests.Archiving;
|
||||
using Chronos.Data.Tests.Infrastructure;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Workspaces;
|
||||
|
||||
/// <summary>
|
||||
/// The workspace's clean-up and trash (phase 5c, P4): media go only from projects whose home holds everything (each other case
|
||||
/// kept with its reason), an original the home lost goes to the trash, Size limit takes the least recently used first, Clean
|
||||
/// after counts from the last opening (else the save), and the trash is never touched by the clean-up and emptied only as
|
||||
/// planned.
|
||||
/// </summary>
|
||||
[Category("workspace")]
|
||||
public abstract class WorkspaceCleanupTests(TestContext context) : DatabaseTest(context)
|
||||
{
|
||||
private static readonly TimeSpan Day = TimeSpan.FromDays(1);
|
||||
|
||||
private async Task<WorkspaceFixture> FixtureAsync(int frames = 4)
|
||||
{
|
||||
var archive = Own(await ArchiveFixture.CreateAsync(Context, database: await NewOptionsAsync(multiConnection: true)));
|
||||
return Own(await WorkspaceFixture.CreateAsync(Context, archive, frames));
|
||||
}
|
||||
|
||||
private static WorkspaceCleaner Cleaner(WorkspaceFixture fx, WorkspaceSync sync, Func<BundleHome, IProjectHome?>? homes = null) =>
|
||||
new(sync, fx.Db, homes ?? (_ => fx.Home)) { LockWait = TimeSpan.FromSeconds(TestTiming.Budget(10)) };
|
||||
|
||||
private static T One<T>(IReadOnlyList<T> items, [System.Runtime.CompilerServices.CallerArgumentExpression(nameof(items))] string? expression = null)
|
||||
{
|
||||
Assert.Count(1, items, expression);
|
||||
return items[0];
|
||||
}
|
||||
|
||||
/// <summary>Clean after 30 days, the project last opened 40 days ago.</summary>
|
||||
private static WorkspaceCleanOptions Aged(Guid projectId, Func<Guid, bool>? isOpen = null, Guid? justCopied = null) => new()
|
||||
{
|
||||
CleanAfterDays = 30,
|
||||
Opened = new Dictionary<Guid, DateTimeOffset> { [projectId] = DateTimeOffset.UtcNow - 40 * Day },
|
||||
IsOpen = isOpen ?? (_ => false),
|
||||
JustCopied = justCopied,
|
||||
};
|
||||
|
||||
/// <summary>A render of the project's ledger with its file in <c>exports/</c>.</summary>
|
||||
private static WorkspaceRenderEntry Render(WorkspaceProject project, string name, string state)
|
||||
{
|
||||
Directory.CreateDirectory(project.ExportsDirectory);
|
||||
File.WriteAllText(project.ExportFile(name), "rendered " + name);
|
||||
return new WorkspaceRenderEntry(Guid.CreateVersion7(), Guid.CreateVersion7(), name, new string('a', 64), 12, "preset", "h264", 1920, 1080, 25, 4,
|
||||
project.ProjectId, null, null, DateTimeOffset.UtcNow, state, state == WorkspaceRenderEntry.SentState ? DateTimeOffset.UtcNow : null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AProjectInStepWithItsHomeLosesItsMediaAndKeepsItsWork()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var (store, sync) = fx.Workspace();
|
||||
var project = await fx.CheckoutAsync(sync);
|
||||
var id = project.ProjectId;
|
||||
var sent = Render(project, "sent.mp4", WorkspaceRenderEntry.SentState);
|
||||
project.WriteRenders(WorkspaceRenders.Empty.With(sent));
|
||||
var bundle = File.ReadAllBytes(project.BundlePath);
|
||||
var proxies = WorkspaceCleaner.Measure(project.ProxiesDirectory).Bytes;
|
||||
Assert.True(WorkspaceCleaner.HoldsMedia(project), "the copy brought the media");
|
||||
|
||||
var report = await Cleaner(fx, sync).CleanAsync(Aged(id), fx.Ct);
|
||||
|
||||
var cleaned = One(report.Cleaned);
|
||||
Assert.Equal((id, 0), (cleaned.ProjectId, cleaned.Trashed));
|
||||
Assert.Equal(proxies + "rendered sent.mp4".Length, cleaned.Freed);
|
||||
Assert.Empty(report.Kept);
|
||||
Assert.False(Directory.Exists(project.ProxiesDirectory), "the proxies went");
|
||||
Assert.FileMissing(project.ExportFile("sent.mp4"));
|
||||
Assert.Empty(project.ReadRenders().Entries);
|
||||
// The frames stay, naming no file; the working state, the deep report and the sync state are as they were.
|
||||
var media = Assert.NotNull(project.ReadMedia());
|
||||
Assert.True(media.IsCleaned, "the index says the clean-up emptied it");
|
||||
Assert.Equal(fx.Frames.Count, media.Frames.Count);
|
||||
Assert.True(media.Frames.All(f => f.File is null && f.Original is null && f.FileBytes == 0), "no frame names a file");
|
||||
Assert.BytesEqual(bundle, File.ReadAllBytes(project.BundlePath));
|
||||
Assert.False(WorkspaceCleaner.HoldsMedia(project), "nothing to edit until a copy");
|
||||
Assert.Equal(WorkspaceState.MediaRemoved, (await sync.StatusAsync(id, fx.Home, fx.Ct)).State);
|
||||
|
||||
// A second run finds nothing to do; a copy brings the media back, in step as before.
|
||||
Assert.Empty((await Cleaner(fx, sync).CleanAsync(Aged(id), fx.Ct)).Cleaned);
|
||||
await fx.CopyAsync(store, id);
|
||||
Assert.True(WorkspaceCleaner.HoldsMedia(project), "copied again");
|
||||
Assert.False(project.ReadMedia()!.IsCleaned, "a copy writes an index of its own");
|
||||
Assert.Equal(WorkspaceState.InSync, (await sync.StatusAsync(id, fx.Home, fx.Ct)).State);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task EachReasonToKeepAProjectKeepsItsMedia()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var (_, sync) = fx.Workspace();
|
||||
var project = await fx.CheckoutAsync(sync);
|
||||
var id = project.ProjectId;
|
||||
var cleaner = Cleaner(fx, sync);
|
||||
|
||||
async Task KeptAsync(WorkspaceKeep reason, WorkspaceCleanOptions options, WorkspaceCleaner? by = null)
|
||||
{
|
||||
var report = await (by ?? cleaner).CleanAsync(options, fx.Ct);
|
||||
Assert.Empty(report.Cleaned);
|
||||
Assert.Equal((id, reason), (One(report.Kept).ProjectId, report.Kept[0].Reason));
|
||||
Assert.True(Directory.Exists(project.ProxiesDirectory) && !project.ReadMedia()!.IsCleaned, $"kept ({reason})");
|
||||
}
|
||||
|
||||
await KeptAsync(WorkspaceKeep.JustCopied, Aged(id, justCopied: id));
|
||||
await KeptAsync(WorkspaceKeep.Open, Aged(id, isOpen: p => p == id));
|
||||
|
||||
// A copy of this project waiting (paused) in the queue; another project's does not count.
|
||||
var copy = TestData.Job(JobKind.WorkspaceCopy) with
|
||||
{
|
||||
TargetIds = [fx.Sequence.Id],
|
||||
State = JobState.Paused,
|
||||
ParametersJson = JsonSerializer.Serialize(new { workspaceRoot = sync.Store.Root, projectId = id, media = BundleMedia.Proxies }),
|
||||
};
|
||||
await fx.Db.Jobs.EnqueueAsync(copy, fx.Ct);
|
||||
await KeptAsync(WorkspaceKeep.Jobs, Aged(id));
|
||||
await fx.Db.Jobs.SetStateAsync(copy.Id, JobState.Cancelled, cancellationToken: fx.Ct);
|
||||
|
||||
var renders = WorkspaceRenders.Empty.With(Render(project, "pending.mp4", WorkspaceRenderEntry.Pending));
|
||||
project.WriteRenders(renders);
|
||||
await KeptAsync(WorkspaceKeep.UnsentRenders, Aged(id));
|
||||
project.WriteRenders(renders.With(renders.Entries[0] with { State = WorkspaceRenderEntry.Failed, Error = "refused" }));
|
||||
await KeptAsync(WorkspaceKeep.UnsentRenders, Aged(id));
|
||||
File.WriteAllText(project.RendersPath, "{ not a ledger");
|
||||
await KeptAsync(WorkspaceKeep.Unreadable, Aged(id));
|
||||
File.Delete(project.RendersPath);
|
||||
File.Delete(project.ExportFile("pending.mp4"));
|
||||
|
||||
await KeptAsync(WorkspaceKeep.Offline, Aged(id), Cleaner(fx, sync, _ => null));
|
||||
await KeptAsync(WorkspaceKeep.Offline, Aged(id), Cleaner(fx, sync, _ => new UnreachableHome(fx.Home)));
|
||||
|
||||
var session = await sync.OpenAsync(id, fx.Ct);
|
||||
await sync.SaveAsync(id, session.Working with { Exposure = session.Working.Exposure with { ExposureOffsetEv = 0.7 } }, fx.Ct);
|
||||
await KeptAsync(WorkspaceKeep.NotInSync, Aged(id));
|
||||
await sync.CommitAsync(id, null, null, fx.Ct);
|
||||
await KeptAsync(WorkspaceKeep.NotInSync, Aged(id));
|
||||
await sync.PushAsync(id, fx.Home, fx.Ct);
|
||||
|
||||
// In step again: it goes. Media whose files are gone already hold nothing to remove.
|
||||
var other = await fx.Archive.Service.Projects.CreateAsync(fx.Sequence.Id, "Second", cancellationToken: fx.Ct);
|
||||
var second = await fx.CheckoutAsync(sync, other.Id);
|
||||
Directory.Delete(second.ProxiesDirectory, recursive: true);
|
||||
var options = Aged(id) with { Opened = new Dictionary<Guid, DateTimeOffset> { [id] = DateTimeOffset.UtcNow - 40 * Day, [other.Id] = DateTimeOffset.UtcNow - 50 * Day } };
|
||||
var report = await cleaner.CleanAsync(options, fx.Ct);
|
||||
Assert.Equal(id, One(report.Cleaned).ProjectId);
|
||||
Assert.Equal((other.Id, WorkspaceKeep.NoMedia), (One(report.Kept).ProjectId, report.Kept[0].Reason));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnOriginalTheHomeNoLongerHoldsGoesToTheTrashNeverAway()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var (store, sync) = fx.Workspace();
|
||||
var project = await fx.CheckoutAsync(sync);
|
||||
// Originals of three frames: the first as the home holds it; the second of bytes the home no longer has; the third
|
||||
// recorded with the home's hash, its bytes changed since (the index is no proof). And a file the index never named.
|
||||
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");
|
||||
var changed = WorkspaceProject.OriginalName(media.Frames[2].Id, fx.Frames[2].Sha256!, ".jpg");
|
||||
Directory.CreateDirectory(project.OriginalsDirectory);
|
||||
var heldBytes = File.ReadAllBytes(fx.Archive.Paths.FromRelative(fx.Frames[0].RelativePath));
|
||||
File.WriteAllBytes(project.MediaFile(held), heldBytes);
|
||||
File.WriteAllText(project.MediaFile(lost), "last original");
|
||||
File.WriteAllText(project.MediaFile(changed), "edited since");
|
||||
File.WriteAllText(Path.Combine(project.OriginalsDirectory, "stray.jpg"), "named by no index");
|
||||
project.WriteMedia(media with
|
||||
{
|
||||
Kind = BundleMedia.Originals,
|
||||
Frames =
|
||||
[
|
||||
media.Frames[0] with { Original = held, OriginalSha256 = fx.Frames[0].Sha256, OriginalBytes = heldBytes.Length },
|
||||
media.Frames[1] with { Original = lost, OriginalSha256 = new string('f', 64), OriginalBytes = 13 },
|
||||
media.Frames[2] with { Original = changed, OriginalSha256 = fx.Frames[2].Sha256, OriginalBytes = 12 },
|
||||
.. media.Frames.Skip(3),
|
||||
],
|
||||
});
|
||||
// The index alone names only the second as the last one.
|
||||
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);
|
||||
|
||||
// Each file hashed now: only the one the home holds byte for byte went away.
|
||||
Assert.Equal(3, 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);
|
||||
var kept = Path.Combine(trash.Folder, entry.Name, WorkspaceProject.OriginalsFolder);
|
||||
Assert.Equal("last original", File.ReadAllText(Path.Combine(kept, Path.GetFileName(lost))));
|
||||
Assert.Equal("edited since", File.ReadAllText(Path.Combine(kept, Path.GetFileName(changed))));
|
||||
Assert.Equal("named by no index", File.ReadAllText(Path.Combine(kept, "stray.jpg")));
|
||||
Assert.False(File.Exists(Path.Combine(kept, Path.GetFileName(held))), "the home holds that one");
|
||||
Assert.Equal((3, (long)("last original".Length + "edited since".Length + "named by no index".Length)), (entry.Files, entry.Bytes));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheSizeLimitTakesTheLeastRecentlyUsedFirstAndNeverTheProjectJustCopied()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var (_, sync) = fx.Workspace();
|
||||
var main = await fx.CheckoutAsync(sync);
|
||||
var b = await fx.CheckoutAsync(sync, (await fx.Archive.Service.Projects.CreateAsync(fx.Sequence.Id, "B", cancellationToken: fx.Ct)).Id);
|
||||
var c = await fx.CheckoutAsync(sync, (await fx.Archive.Service.Projects.CreateAsync(fx.Sequence.Id, "C", cancellationToken: fx.Ct)).Id);
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var opened = new Dictionary<Guid, DateTimeOffset> { [main.ProjectId] = now - 3 * Day, [b.ProjectId] = now - Day, [c.ProjectId] = now - 2 * Day };
|
||||
var total = new[] { main, b, c }.Sum(p => WorkspaceCleaner.Measure(p.Folder).Bytes);
|
||||
var media = WorkspaceCleaner.Measure(main.ProxiesDirectory).Bytes;
|
||||
// Two projects' media must go to get under the limit (each holds the same proxies).
|
||||
var limit = total - media - 1;
|
||||
|
||||
// After a copy of Main, the oldest: Main stays, the next two oldest go while the folders stay above the limit.
|
||||
var report = await Cleaner(fx, sync).CleanAsync(new WorkspaceCleanOptions { SizeLimitBytes = limit, Opened = opened, JustCopied = main.ProjectId, Now = now }, fx.Ct);
|
||||
Assert.SequenceEqual([(main.ProjectId, WorkspaceKeep.JustCopied)], report.Kept.Select(k => (k.ProjectId, k.Reason)));
|
||||
Assert.SequenceEqual([c.ProjectId, b.ProjectId], report.Cleaned.Select(p => p.ProjectId));
|
||||
Assert.Equal(total, report.UsedBefore);
|
||||
Assert.Equal(total - report.Freed, report.UsedAfter);
|
||||
|
||||
// Once copied again: the oldest goes first, and one is enough this time.
|
||||
await fx.CopyAsync(sync.Store, b.ProjectId);
|
||||
await fx.CopyAsync(sync.Store, c.ProjectId);
|
||||
// Measured again: a copy's timestamps may be a byte shorter or longer than the first copy's.
|
||||
var again = new[] { main, b, c }.Sum(p => WorkspaceCleaner.Measure(p.Folder).Bytes);
|
||||
report = await Cleaner(fx, sync).CleanAsync(new WorkspaceCleanOptions { SizeLimitBytes = again - 1, Opened = opened, Now = now }, fx.Ct);
|
||||
Assert.SequenceEqual([main.ProjectId], report.Cleaned.Select(p => p.ProjectId));
|
||||
Assert.Empty(report.Kept);
|
||||
Assert.True(Directory.Exists(b.ProxiesDirectory) && Directory.Exists(c.ProxiesDirectory), "the others stay");
|
||||
|
||||
// Under the limit, or with none: nothing goes.
|
||||
Assert.Empty((await Cleaner(fx, sync).CleanAsync(new WorkspaceCleanOptions { SizeLimitBytes = total * 2, Opened = opened, Now = now }, fx.Ct)).Cleaned);
|
||||
Assert.Empty((await Cleaner(fx, sync).CleanAsync(new WorkspaceCleanOptions { Opened = opened, Now = now }, fx.Ct)).Cleaned);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CleanAfterCountsFromTheLastOpeningElseFromTheSave()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var (_, sync) = fx.Workspace();
|
||||
var main = await fx.CheckoutAsync(sync);
|
||||
var other = await fx.CheckoutAsync(sync, (await fx.Archive.Service.Projects.CreateAsync(fx.Sequence.Id, "Other", cancellationToken: fx.Ct)).Id);
|
||||
var saved = main.ReadBundle().Saved;
|
||||
// Main was opened yesterday; the other never here (its save counts), a year after the save past Clean after.
|
||||
var opened = new Dictionary<Guid, DateTimeOffset> { [main.ProjectId] = saved + 364 * Day };
|
||||
var options = new WorkspaceCleanOptions { CleanAfterDays = 30, Opened = opened, Now = saved + 365 * Day };
|
||||
|
||||
var report = await Cleaner(fx, sync).CleanAsync(options, fx.Ct);
|
||||
Assert.SequenceEqual([other.ProjectId], report.Cleaned.Select(p => p.ProjectId));
|
||||
Assert.Empty(report.Kept);
|
||||
Assert.True(Directory.Exists(main.ProxiesDirectory), "opened yesterday");
|
||||
|
||||
// Within Clean after of the save, or with Clean after off: kept.
|
||||
await fx.CopyAsync(sync.Store, other.ProjectId);
|
||||
Assert.Empty((await Cleaner(fx, sync).CleanAsync(options with { Now = saved + 29 * Day, Opened = new Dictionary<Guid, DateTimeOffset>() }, fx.Ct)).Cleaned);
|
||||
Assert.Empty((await Cleaner(fx, sync).CleanAsync(options with { CleanAfterDays = 0 }, fx.Ct)).Cleaned);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheCleanUpNeverTouchesTheTrashWhichEmptiesOnlyAsPlanned()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var (store, sync) = fx.Workspace();
|
||||
var project = await fx.CheckoutAsync(sync);
|
||||
var folder = WorkspaceTrash.FolderOf(store.Root);
|
||||
var kept = Directory.CreateDirectory(Path.Combine(folder, Guid.CreateVersion7().ToString("N") + "-" + DateTime.UtcNow.AddDays(-90).Ticks)).FullName;
|
||||
File.WriteAllText(Path.Combine(kept, "project.chronos"), "a removed copy's work");
|
||||
var before = WorkspaceTrash.List(store.Root, fx.Ct);
|
||||
Assert.Equal((1, 1, (long)"a removed copy's work".Length), (before.Entries.Count, before.Entries[0].Files, before.Bytes));
|
||||
Assert.InRange((before.Entries[0].Trashed - DateTimeOffset.UtcNow.AddDays(-90)).TotalMinutes, -1, 1);
|
||||
|
||||
// Even a size limit of one byte leaves the trash as it was.
|
||||
await Cleaner(fx, sync).CleanAsync(new WorkspaceCleanOptions { CleanAfterDays = 1, SizeLimitBytes = 1, Now = DateTimeOffset.UtcNow + 10 * Day }, fx.Ct);
|
||||
Assert.False(Directory.Exists(project.ProxiesDirectory), "the media went");
|
||||
Assert.Equal(before.Fingerprint, WorkspaceTrash.List(store.Root, fx.Ct).Fingerprint);
|
||||
|
||||
// An entry added after the plan: nothing is erased.
|
||||
var added = Directory.CreateDirectory(Path.Combine(folder, Guid.CreateVersion7().ToString("N") + "-" + DateTime.UtcNow.Ticks)).FullName;
|
||||
File.WriteAllText(Path.Combine(added, "late.txt"), "late");
|
||||
Assert.Throws<WorkspaceTrashChangedException>(() => WorkspaceTrash.Empty(store.Root, before, fx.Ct));
|
||||
Assert.True(Directory.Exists(kept) && Directory.Exists(added), "nothing was erased");
|
||||
// A file changed inside an entry changes the fingerprint too.
|
||||
var plan = WorkspaceTrash.List(store.Root, fx.Ct);
|
||||
File.AppendAllText(Path.Combine(added, "late.txt"), " and longer");
|
||||
Assert.Throws<WorkspaceTrashChangedException>(() => WorkspaceTrash.Empty(store.Root, plan, fx.Ct));
|
||||
|
||||
plan = WorkspaceTrash.List(store.Root, fx.Ct);
|
||||
File.SetAttributes(Path.Combine(kept, "project.chronos"), FileAttributes.ReadOnly);
|
||||
Assert.Equal((2, plan.Bytes), WorkspaceTrash.Empty(store.Root, plan, fx.Ct));
|
||||
Assert.True(WorkspaceTrash.List(store.Root, fx.Ct).IsEmpty, "the trash is empty");
|
||||
Assert.True(Directory.Exists(folder), "the trash folder itself stays");
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SqliteWorkspaceCleanupTests(TestContext context) : WorkspaceCleanupTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.SqliteFile;
|
||||
}
|
||||
|
||||
[RequiresEnvironment(PgTestServer.Variable)]
|
||||
public sealed class PostgresWorkspaceCleanupTests(TestContext context) : WorkspaceCleanupTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.Postgres;
|
||||
}
|
||||
@@ -84,10 +84,10 @@ internal sealed class WorkspaceFixture : IAsyncDisposable
|
||||
}
|
||||
|
||||
/// <summary>Queues a workspace copy job and returns at once, while it runs.</summary>
|
||||
public async Task<Job> StartCopyAsync(WorkspaceStore store, Guid projectId)
|
||||
public async Task<Job> StartCopyAsync(WorkspaceStore store, Guid projectId, string media = "proxies")
|
||||
{
|
||||
var engine = await EngineAsync();
|
||||
return await engine.EnqueueAsync(WorkspaceJobs.Copy(Sequence, store.Root, projectId), cancellationToken: Ct);
|
||||
return await engine.EnqueueAsync(WorkspaceJobs.Copy(Sequence, store.Root, projectId, media), cancellationToken: Ct);
|
||||
}
|
||||
|
||||
/// <summary>Cancels a job, as the user does from the jobs list.</summary>
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
using System.Text.Json.Nodes;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Tests.Archiving;
|
||||
using Chronos.Data.Tests.Infrastructure;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Workspaces;
|
||||
|
||||
/// <summary>
|
||||
/// The shared types of phase 5c (owner review 2, R8): originals in the media index, the ledger of local renders, the names
|
||||
/// of the workspace's files, and the jobs of the workspace with their parameters.
|
||||
/// </summary>
|
||||
[Category("workspace")]
|
||||
public sealed class WorkspaceFoundationTests(TestContext context)
|
||||
{
|
||||
private static readonly DateTimeOffset T0 = new(2026, 11, 4, 9, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private static WorkspaceMedia Media(Guid sequenceId, string kind, params WorkspaceFrame[] frames) =>
|
||||
new(WorkspaceMedia.FormatName, WorkspaceMedia.CurrentFormatVersion, kind, sequenceId, 3, frames, T0);
|
||||
|
||||
private static WorkspaceFrame Frame(Guid sequenceId, int index) =>
|
||||
WorkspaceFrame.Of(TestData.Frame(sequenceId, index), $"proxies/{Guid.NewGuid():N}.jpg", new string('a', 64), 1_500_000);
|
||||
|
||||
[Test]
|
||||
public void AMediaIndexOfPhase5bReadsAsProxiesWithoutOriginals()
|
||||
{
|
||||
var store = new WorkspaceStore(Path.Combine(context.CreateTempDirectory("ws"), "workspace"));
|
||||
var project = store.Project(Guid.CreateVersion7());
|
||||
var sequenceId = Guid.CreateVersion7();
|
||||
project.WriteMedia(Media(sequenceId, BundleMedia.Proxies, Frame(sequenceId, 0), Frame(sequenceId, 1)));
|
||||
|
||||
// As phase 5b wrote it: no original fields at all.
|
||||
var json = JsonNode.Parse(File.ReadAllText(project.MediaIndexPath))!.AsObject();
|
||||
foreach (var frame in json["frames"]!.AsArray())
|
||||
{
|
||||
var fields = frame!.AsObject();
|
||||
foreach (var name in new[] { "original", "originalSha256", "originalBytes" }) fields.Remove(name);
|
||||
}
|
||||
File.WriteAllText(project.MediaIndexPath, json.ToJsonString());
|
||||
Assert.False(File.ReadAllText(project.MediaIndexPath).Contains("\"original\"", StringComparison.Ordinal), "no original field is left");
|
||||
|
||||
var media = Assert.NotNull(project.ReadMedia());
|
||||
Assert.Equal(BundleMedia.Proxies, media.Kind);
|
||||
Assert.False(media.HoldsOriginals);
|
||||
foreach (var frame in media.Frames)
|
||||
{
|
||||
Assert.Equal(((string?)null, (string?)null, 0L, false), (frame.Original, frame.OriginalSha256, frame.OriginalBytes, frame.HasOriginal));
|
||||
// A render from originals finds none: every frame is missing there, while the editor reads its proxy.
|
||||
Assert.True(frame.ToOriginalFrame(sequenceId).Flags.HasFlag(FrameFlags.Missing));
|
||||
Assert.False(frame.ToFrame(sequenceId).Flags.HasFlag(FrameFlags.Missing));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void OriginalsInTheMediaIndexAreReadBackAndRenderedFrom()
|
||||
{
|
||||
var store = new WorkspaceStore(Path.Combine(context.CreateTempDirectory("ws"), "workspace"));
|
||||
var project = store.Project(Guid.CreateVersion7());
|
||||
var sequenceId = Guid.CreateVersion7();
|
||||
var held = Frame(sequenceId, 0);
|
||||
var sha = new string('c', 64);
|
||||
var original = WorkspaceProject.OriginalName(held.Id, sha, Path.GetExtension(held.FileName));
|
||||
held = held with { Original = original, OriginalSha256 = sha, OriginalBytes = held.Size };
|
||||
var proxied = Frame(sequenceId, 1);
|
||||
project.WriteMedia(Media(sequenceId, BundleMedia.Originals, held, proxied));
|
||||
|
||||
var media = Assert.NotNull(project.ReadMedia());
|
||||
Assert.True(media.HoldsOriginals);
|
||||
Assert.Equal((original, sha, held.Size), (media.Frames[0].Original, media.Frames[0].OriginalSha256, media.Frames[0].OriginalBytes));
|
||||
var frames = media.ToOriginalFrames();
|
||||
Assert.Equal(original, frames[0].RelativePath);
|
||||
Assert.False(frames[0].Flags.HasFlag(FrameFlags.Missing));
|
||||
// A frame whose original the home lacked stays a proxy for the editor and is missing for a local render.
|
||||
Assert.True(frames[1].Flags.HasFlag(FrameFlags.Missing));
|
||||
Assert.Equal(proxied.File, media.ToFrames()[1].RelativePath);
|
||||
Assert.Equal(Path.Combine(project.OriginalsDirectory, Path.GetFileName(original)), project.MediaFile(original));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void OriginalsKeepTheirExtensionAndAShortHashInTheirName()
|
||||
{
|
||||
var id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
|
||||
var sha = "ABCDEF0123456789" + new string('0', 48);
|
||||
Assert.Equal("originals/0192a4c17b3e7cc08a512f9d0e6b1a01-abcdef01.cr3", WorkspaceProject.OriginalName(id, sha, ".CR3"));
|
||||
Assert.Equal("originals/0192a4c17b3e7cc08a512f9d0e6b1a01-abcdef01.dng", WorkspaceProject.OriginalName(id, sha, "dng"));
|
||||
Assert.Equal("originals/0192a4c17b3e7cc08a512f9d0e6b1a01-abcdef01", WorkspaceProject.OriginalName(id, sha, null));
|
||||
Assert.Equal("originals/0192a4c17b3e7cc08a512f9d0e6b1a01-abcdef01", WorkspaceProject.OriginalName(id, sha, "a/b"));
|
||||
Assert.Throws<ArgumentException>(() => WorkspaceProject.OriginalName(id, string.Empty, ".jpg"));
|
||||
|
||||
var store = new WorkspaceStore(Path.Combine(context.CreateTempDirectory("ws"), "workspace"));
|
||||
var project = store.Project(id);
|
||||
Assert.Equal("exports/renders.json", WorkspaceProject.RendersFile);
|
||||
Assert.Equal(Path.Combine(project.Folder, "exports", "renders.json"), project.RendersPath);
|
||||
Assert.Equal(Path.Combine(project.ExportsDirectory, "Roof 4K.mp4"), project.ExportFile("Roof 4K.mp4"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AMediaIndexHoldingOriginalsIsWrittenInAFormatAPhase5bChronosRefuses()
|
||||
{
|
||||
var store = new WorkspaceStore(Path.Combine(context.CreateTempDirectory("ws"), "workspace"));
|
||||
var project = store.Project(Guid.CreateVersion7());
|
||||
var sequenceId = Guid.CreateVersion7();
|
||||
int Written() => JsonNode.Parse(File.ReadAllText(project.MediaIndexPath))!["formatVersion"]!.GetValue<int>();
|
||||
|
||||
// Proxies only: as phase 5b wrote it, which it reads.
|
||||
project.WriteMedia(Media(sequenceId, BundleMedia.Proxies, Frame(sequenceId, 0)));
|
||||
Assert.Equal(WorkspaceMedia.ProxiesFormatVersion, Written());
|
||||
// Originals, or a frame holding one, or media the clean-up removed: format 2, which phase 5b refuses as newer
|
||||
// rather than reading the frames' files as its proxies.
|
||||
project.WriteMedia(Media(sequenceId, BundleMedia.Originals, Frame(sequenceId, 0)));
|
||||
Assert.Equal(WorkspaceMedia.CurrentFormatVersion, Written());
|
||||
var held = Frame(sequenceId, 0);
|
||||
held = held with { Original = WorkspaceProject.OriginalName(held.Id, new string('c', 64), ".jpg"), OriginalSha256 = new string('c', 64), OriginalBytes = 9 };
|
||||
project.WriteMedia(Media(sequenceId, BundleMedia.Proxies, held));
|
||||
Assert.Equal(WorkspaceMedia.CurrentFormatVersion, Written());
|
||||
project.WriteMedia(Media(sequenceId, BundleMedia.Proxies, Frame(sequenceId, 0)) with { Cleaned = T0 });
|
||||
Assert.Equal(WorkspaceMedia.CurrentFormatVersion, Written());
|
||||
Assert.True(Assert.NotNull(project.ReadMedia()).IsCleaned, "this Chronos reads its own format back");
|
||||
Assert.Equal(2, WorkspaceMedia.CurrentFormatVersion);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ALedgerNamesOnlyFilesInsideTheExports()
|
||||
{
|
||||
var store = new WorkspaceStore(Path.Combine(context.CreateTempDirectory("ws"), "workspace"));
|
||||
var project = store.Project(Guid.CreateVersion7());
|
||||
Assert.Equal(Path.GetFullPath(project.ExportFile("Roof 4K.mp4")), project.ContainedExportFile("Roof 4K.mp4"));
|
||||
Assert.Equal(Path.GetFullPath(project.ExportFile(Path.Combine("Roof frames", "0001.tif"))), project.ContainedExportFile("Roof frames/0001.tif"));
|
||||
foreach (var refused in new[]
|
||||
{
|
||||
null, "", " ", ".", "..", "../project.chronos", @"..\media.json", "a/../../x.mp4", "a//b.mp4", "./a.mp4", "/etc/passwd",
|
||||
@"C:\Windows\win.ini", "C:x.mp4", @"\\server\share\x.mp4", WorkspaceProject.RendersFileName,
|
||||
})
|
||||
Assert.Null(project.ContainedExportFile(refused), refused ?? "null");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ATrashEntryBeingFilledIsNeverListedAndTakesItsNameWhenWhole()
|
||||
{
|
||||
var root = Path.Combine(context.CreateTempDirectory("ws"), "workspace");
|
||||
var projectId = Guid.CreateVersion7();
|
||||
string staging;
|
||||
using (var trash = WorkspaceTrash.Begin(root, projectId, T0.UtcDateTime))
|
||||
{
|
||||
staging = trash.Path;
|
||||
Assert.True(Directory.Exists(staging));
|
||||
File.WriteAllText(Path.Combine(staging, "half.jpg"), "half");
|
||||
// Listed while it is being filled, an Empty… could erase what a removal is still moving there.
|
||||
var listing = WorkspaceTrash.List(root);
|
||||
Assert.True(listing.IsEmpty, string.Join(", ", listing.Entries.Select(e => e.Name)));
|
||||
Assert.Equal((0, 0L), WorkspaceTrash.Empty(root, listing));
|
||||
Assert.FileExists(Path.Combine(staging, "half.jpg"));
|
||||
}
|
||||
Assert.False(Directory.Exists(staging));
|
||||
var entries = WorkspaceTrash.List(root).Entries;
|
||||
Assert.Equal(1, entries.Count);
|
||||
var entry = entries[0];
|
||||
Assert.True(entry.Name.StartsWith(projectId.ToString("N") + "-", StringComparison.Ordinal), entry.Name);
|
||||
Assert.Equal((1, 4L), (entry.Files, entry.Bytes));
|
||||
|
||||
// One that nothing came into leaves no entry.
|
||||
using (var empty = WorkspaceTrash.Begin(root, projectId, T0.UtcDateTime))
|
||||
Assert.True(Directory.Exists(empty.Path));
|
||||
Assert.Equal(1, WorkspaceTrash.List(root).Entries.Count);
|
||||
}
|
||||
|
||||
private static WorkspaceRenderEntry Entry(Guid projectId, string file) =>
|
||||
new(Guid.CreateVersion7(), Guid.CreateVersion7(), file, new string('b', 64), 12_345, "4K HEVC", "hevc", 3840, 2160, 30, 10, projectId,
|
||||
Guid.CreateVersion7(), "hash", T0);
|
||||
|
||||
[Test]
|
||||
public void TheLedgerOfLocalRendersIsWrittenWholeAndReadBack()
|
||||
{
|
||||
var store = new WorkspaceStore(Path.Combine(context.CreateTempDirectory("ws"), "workspace"));
|
||||
var project = store.Project(Guid.CreateVersion7());
|
||||
// No ledger yet: no renders.
|
||||
Assert.Empty(project.ReadRenders().Entries);
|
||||
Assert.Same(WorkspaceRenders.Empty, project.ReadRenders());
|
||||
|
||||
var first = Entry(project.ProjectId, "Roof 4K.mp4");
|
||||
var second = Entry(project.ProjectId, "Roof 1080p.mp4") with { ProjectVersionId = null, SettingsHash = null };
|
||||
var ledger = WorkspaceRenders.Empty.With(first).With(second);
|
||||
project.WriteRenders(ledger);
|
||||
Assert.FileExists(project.RendersPath);
|
||||
Assert.Empty(Directory.GetFiles(project.ExportsDirectory, "*.tmp"));
|
||||
|
||||
var read = project.ReadRenders();
|
||||
Assert.Equal((WorkspaceRenders.FormatName, 1, 2), (read.Format, read.FormatVersion, read.Entries.Count));
|
||||
Assert.Equal(first, read.Entries[0]);
|
||||
Assert.Equal(second, read.Entries[1]);
|
||||
Assert.Equal(WorkspaceRenderEntry.Pending, read.Entries[0].State);
|
||||
Assert.Count(2, read.Unsent);
|
||||
Assert.Contains("\"state\": \"pending\"", File.ReadAllText(project.RendersPath));
|
||||
|
||||
// One entry per render id: a send that went home replaces it, a second time changes nothing.
|
||||
var sent = read.With(first.AsSent(T0.AddMinutes(5)));
|
||||
Assert.Count(2, sent.Entries);
|
||||
Assert.True(Assert.NotNull(sent.Find(first.RenderId)).IsSent);
|
||||
Assert.True(sent.Entries.SequenceEqual(sent.With(first.AsSent(T0.AddMinutes(5))).Entries), "the same send twice changes nothing");
|
||||
Assert.True(sent.Unsent.Select(e => e.RenderId).SequenceEqual([second.RenderId]), "only the render not sent is unsent");
|
||||
var failed = sent.With(second.AsFailed("The library cannot be reached now."));
|
||||
Assert.Equal((WorkspaceRenderEntry.Failed, "The library cannot be reached now."), (failed.Find(second.RenderId)!.State, failed.Find(second.RenderId)!.Error));
|
||||
Assert.True(failed.Find(second.RenderId)!.IsUnsent, "a failed send is sent again");
|
||||
Assert.Count(1, failed.Without(first.RenderId).Entries);
|
||||
Assert.Null(failed.Find(Guid.NewGuid()));
|
||||
|
||||
project.WriteRenders(failed);
|
||||
Assert.True(failed.Entries.SequenceEqual(project.ReadRenders().Entries), "the ledger reads back as written");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ALedgerDamagedOrOfANewerChronosIsRefused()
|
||||
{
|
||||
var store = new WorkspaceStore(Path.Combine(context.CreateTempDirectory("ws"), "workspace"));
|
||||
var project = store.Project(Guid.CreateVersion7());
|
||||
Directory.CreateDirectory(project.ExportsDirectory);
|
||||
File.WriteAllText(project.RendersPath, "{ \"format\": \"chronos-workspace-renders\", \"formatVersion\": 1, \"entries\": [ { \"renderId\": ");
|
||||
Assert.Throws<InvalidDataException>(() => project.ReadRenders());
|
||||
File.WriteAllText(project.RendersPath, """{ "format": "something-else", "formatVersion": 1, "entries": [] }""");
|
||||
Assert.Throws<InvalidDataException>(() => project.ReadRenders());
|
||||
File.WriteAllText(project.RendersPath, """{ "format": "chronos-workspace-renders", "formatVersion": 2, "entries": [] }""");
|
||||
Assert.Throws<InvalidDataException>(() => project.ReadRenders());
|
||||
// A state a later Chronos wrote counts as not sent: its file is never cleaned up.
|
||||
var entry = Entry(project.ProjectId, "Roof.mp4") with { State = "queued-elsewhere" };
|
||||
project.WriteRenders(WorkspaceRenders.Empty.With(entry));
|
||||
Assert.True(project.ReadRenders().Entries.Single().IsUnsent);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheWorkspaceJobsCarryTheirParameters()
|
||||
{
|
||||
var sequenceId = Guid.CreateVersion7();
|
||||
var projectId = Guid.CreateVersion7();
|
||||
var versionId = Guid.CreateVersion7();
|
||||
var root = Path.Combine(context.CreateTempDirectory("ws"), "workspace");
|
||||
|
||||
var render = WorkspaceJobs.Render(sequenceId, "Roof", root, projectId, versionId, """{ "presetName": "4K HEVC" }""", "https://studio:8443");
|
||||
Assert.Equal((JobKind.WorkspaceRender, "Roof", JobPriority.User), (render.Kind, render.Label, render.Priority));
|
||||
Assert.True(render.Targets.SequenceEqual([sequenceId]), "the render targets its sequence");
|
||||
var rendered = Assert.NotNull(WorkspaceJobs.RenderParameters(Job(render)));
|
||||
Assert.Equal(new WorkspaceRenderParameters(root, projectId, versionId, """{ "presetName": "4K HEVC" }""", "https://studio:8443"), rendered);
|
||||
|
||||
var ids = new[] { Guid.CreateVersion7(), Guid.CreateVersion7() };
|
||||
var send = WorkspaceJobs.Send(sequenceId, "Roof", root, projectId, ids);
|
||||
Assert.Equal((JobKind.WorkspaceSend, JobPriority.User), (send.Kind, send.Priority));
|
||||
var sending = Assert.NotNull(WorkspaceJobs.SendParameters(Job(send)));
|
||||
Assert.Equal((root, projectId, (string?)null), (sending.WorkspaceRoot, sending.ProjectId, sending.Server));
|
||||
Assert.True(sending.RenderIds.SequenceEqual(ids), "the send names its renders");
|
||||
|
||||
var target = Path.Combine(context.CreateTempDirectory("fast"), "workspace");
|
||||
var move = WorkspaceJobs.Move(root, target, "fingerprint");
|
||||
Assert.Equal((JobKind.WorkspaceMove, target, 0), (move.Kind, move.Label, move.Targets.Count));
|
||||
Assert.Equal(new WorkspaceMoveParameters(root, target, "fingerprint"), WorkspaceJobs.MoveParameters(Job(move)));
|
||||
|
||||
// Parameters of another kind, or none that read, are none.
|
||||
Assert.Null(WorkspaceJobs.RenderParameters(Job(send)));
|
||||
Assert.Null(WorkspaceJobs.MoveParameters(Job(move) with { ParametersJson = "{" }));
|
||||
Assert.Equal(BundleMedia.Originals, WorkspaceJobs.CopyParameters(Job(WorkspaceJobs.CopyFromServer(sequenceId, "Roof", "https://studio:8443", root,
|
||||
projectId, BundleMedia.Originals)))!.Media);
|
||||
Assert.Throws<ArgumentException>(() => WorkspaceJobs.Move(root, target, " "));
|
||||
|
||||
static Job Job(ArchiveJobRequest request) => TestData.Job(request.Kind) with { TargetIds = request.Targets, ParametersJson = request.ParametersJson };
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheWorkspaceRegistersAHandlerForEachOfItsJobs()
|
||||
{
|
||||
await using var archive = await ArchiveFixture.CreateAsync(context);
|
||||
var kinds = new[] { JobKind.WorkspaceCopy, JobKind.WorkspaceRender, JobKind.WorkspaceSend, JobKind.WorkspaceMove };
|
||||
var handlers = WorkspaceJobs.CreateHandlers(archive.Db, archive.Service, null, WorkspaceJobOptionsFor());
|
||||
Assert.True(handlers.Select(h => h.Kind).SequenceEqual(kinds), string.Join(", ", handlers.Select(h => h.Kind)));
|
||||
// The overloads of phase 5b register them all too.
|
||||
Assert.True(WorkspaceJobs.CreateHandlers(archive.Db, archive.Service).Select(h => h.Kind).SequenceEqual(kinds), "the earlier overload");
|
||||
|
||||
static WorkspaceJobOptions WorkspaceJobOptionsFor() => new(new Chronos.Data.Processing.ProcessingOptions(), () => false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,561 @@
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Workspaces;
|
||||
|
||||
/// <summary>
|
||||
/// Moving the workspace folder with its projects (phase 5c, P6): renamed on one volume, copied and hash-verified across
|
||||
/// volumes (one disk told it is two), a damaged copy that never costs the source, a move stopped and taken up from its
|
||||
/// journal, the refusals of the plan, a failure undone, and the job that carries it out.
|
||||
/// </summary>
|
||||
[Category("workspace")]
|
||||
public sealed class WorkspaceMoveTests(TestContext context)
|
||||
{
|
||||
static WorkspaceMoveTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
|
||||
|
||||
[Test]
|
||||
public async Task OnOneVolumeEveryProjectIsRenamedAndTheDesktopToldOnce()
|
||||
{
|
||||
var (from, ids) = Workspace(projects: 2);
|
||||
File.WriteAllText(Path.Combine(from, "notes.txt"), "the user's own");
|
||||
var before = Contents(from);
|
||||
var to = Path.Combine(context.CreateTempDirectory("target"), "moved");
|
||||
var mover = new WorkspaceMover(from, to);
|
||||
var survey = mover.Survey();
|
||||
Assert.True(survey.CanMove, survey.RefusalText);
|
||||
Assert.True(survey.SameVolume, "both folders lie in the test's own temporary folder");
|
||||
Assert.SequenceEqual([.. ids.Select(i => i.ToString("N")).Order(StringComparer.Ordinal), WorkspaceStore.ManifestFile, ".trash"], survey.Entries);
|
||||
Assert.Equal(before.Keys.Count(k => k != "notes.txt" && !IsLease(k)), survey.Files, "the leases and the user's file are not counted");
|
||||
Assert.True(survey.Projects.All(p => p.IsProject));
|
||||
|
||||
var told = new List<(string, string)>();
|
||||
var log = new List<string>();
|
||||
var (_, resumed) = await mover.MoveAsync(survey.Fingerprint, (f, t) =>
|
||||
{
|
||||
told.Add((f, t));
|
||||
return Task.CompletedTask;
|
||||
}, log: log.Add, cancellationToken: context.Cancellation);
|
||||
|
||||
Assert.False(resumed);
|
||||
Assert.SequenceEqual([(mover.From, mover.To)], told);
|
||||
// Everything of the workspace is at the target as it was, the lease with its project; the user's file stays.
|
||||
var after = Contents(to);
|
||||
foreach (var (name, sha) in before.Where(b => b.Key != "notes.txt")) Assert.Equal(sha, after.GetValueOrDefault(name), name);
|
||||
Assert.SequenceEqual(["notes.txt"], Directory.EnumerateFileSystemEntries(from).Select(Path.GetFileName).ToList());
|
||||
Assert.False(WorkspaceMover.HasJournal(from));
|
||||
Assert.Contains(Loc.L("Archive.Log.WorkspaceMoved", mover.To, 2, survey.Files), log);
|
||||
Assert.Equal(ids.Count, new WorkspaceStore(to).List().Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AcrossVolumesEveryFileIsCopiedAndCheckedBeforeTheSourceGoes()
|
||||
{
|
||||
var (from, ids) = Workspace(projects: 3);
|
||||
var before = Contents(from);
|
||||
var times = File.GetLastWriteTimeUtc(Path.Combine(from, ids[0].ToString("N"), WorkspaceProject.BundleFile));
|
||||
var to = Path.Combine(context.CreateTempDirectory("target"), "moved");
|
||||
var atSwitch = (Source: new Dictionary<string, string>(), Target: new Dictionary<string, string>());
|
||||
var mover = new WorkspaceMover(from, to)
|
||||
{
|
||||
SameVolume = false,
|
||||
Cut = (step, _) =>
|
||||
{
|
||||
if (step != "switched") return;
|
||||
atSwitch = (Contents(from), Contents(to));
|
||||
},
|
||||
};
|
||||
var survey = mover.Survey();
|
||||
Assert.False(survey.SameVolume);
|
||||
var told = 0;
|
||||
await mover.MoveAsync(survey.Fingerprint, (_, _) =>
|
||||
{
|
||||
told++;
|
||||
// Told only once everything is at the target: the source is still whole.
|
||||
Assert.Equal(before.Count, Contents(from).Count);
|
||||
return Task.CompletedTask;
|
||||
}, cancellationToken: context.Cancellation);
|
||||
|
||||
Assert.Equal(1, told);
|
||||
// At the switch both sides held everything (the lease is the project holder's: not copied).
|
||||
Assert.Equal(before.Count, atSwitch.Source.Count);
|
||||
foreach (var (name, sha) in before.Where(b => !IsLease(b.Key))) Assert.Equal(sha, atSwitch.Target.GetValueOrDefault(name), name);
|
||||
// Then the source went, the journal last, and the folder with them.
|
||||
Assert.False(Directory.Exists(from));
|
||||
Assert.Equal(times, File.GetLastWriteTimeUtc(Path.Combine(to, ids[0].ToString("N"), WorkspaceProject.BundleFile)), "the copy keeps the file's time");
|
||||
Assert.Empty(Directory.EnumerateFiles(to, "*" + WorkspaceMover.PartSuffix, SearchOption.AllDirectories));
|
||||
Assert.True(Directory.Exists(Path.Combine(to, ids[0].ToString("N"), "media", "empty")), "an empty folder comes along");
|
||||
Assert.Equal(ids.Count, new WorkspaceStore(to).List().Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ACopyThatDoesNotMatchItsSourceNeverCostsTheSource()
|
||||
{
|
||||
var (from, _) = Workspace(projects: 2);
|
||||
var before = Contents(from);
|
||||
var to = Path.Combine(context.CreateTempDirectory("target"), "moved");
|
||||
var copies = 0;
|
||||
var mover = new WorkspaceMover(from, to)
|
||||
{
|
||||
SameVolume = false,
|
||||
Cut = (step, path) =>
|
||||
{
|
||||
// The fourth file is damaged on its way to the target disk.
|
||||
if (step != "verify" || ++copies != 4) return;
|
||||
var bytes = File.ReadAllBytes(path);
|
||||
bytes[0] ^= 0xFF;
|
||||
File.WriteAllBytes(path, bytes);
|
||||
},
|
||||
};
|
||||
var told = 0;
|
||||
var failed = await Assert.ThrowsAsync<InvalidOperationException>(() => mover.MoveAsync(mover.Survey().Fingerprint, (_, _) =>
|
||||
{
|
||||
told++;
|
||||
return Task.CompletedTask;
|
||||
}, cancellationToken: context.Cancellation));
|
||||
|
||||
Assert.True(failed.Message.StartsWith(Loc.L("Errors.Workspace.MoveVerify", "§").Split('§')[0], StringComparison.Ordinal), failed.Message);
|
||||
Assert.Equal(0, told);
|
||||
Same(before, Contents(from));
|
||||
Assert.False(WorkspaceMover.HasJournal(from), "the move was undone");
|
||||
Assert.False(Directory.Exists(to) && Directory.EnumerateFileSystemEntries(to).Any(), "no copy is left at the target");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AMoveStoppedAcrossVolumesGoesOnFromItsJournalWithoutCopyingTwice()
|
||||
{
|
||||
var (from, _) = Workspace(projects: 3);
|
||||
var before = Contents(from);
|
||||
var to = Path.Combine(context.CreateTempDirectory("target"), "moved");
|
||||
using var stop = CancellationTokenSource.CreateLinkedTokenSource(context.Cancellation);
|
||||
var copied = 0;
|
||||
var first = new WorkspaceMover(from, to)
|
||||
{
|
||||
SameVolume = false,
|
||||
Cut = (step, _) =>
|
||||
{
|
||||
// The program closes after the fifth file reached the target.
|
||||
if (step == "copied" && ++copied == 5) stop.Cancel();
|
||||
},
|
||||
};
|
||||
var fingerprint = first.Survey().Fingerprint;
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => first.MoveAsync(fingerprint, cancellationToken: stop.Token));
|
||||
Assert.True(WorkspaceMover.HasJournal(from), "the journal stays for the next run");
|
||||
Same(before, Contents(from));
|
||||
Assert.Equal(WorkspaceMoveStage.Moving, WorkspaceMover.ReadJournal(from)!.Stage);
|
||||
|
||||
// The workspace changed since (a lease taken and let go does not count): the move taken up does not ask the plan again.
|
||||
var again = 0;
|
||||
var second = new WorkspaceMover(from, to)
|
||||
{
|
||||
SameVolume = false,
|
||||
Cut = (step, _) =>
|
||||
{
|
||||
if (step == "copied") again++;
|
||||
},
|
||||
};
|
||||
var told = 0;
|
||||
var log = new List<string>();
|
||||
var (_, resumed) = await second.MoveAsync("another plan", (_, _) =>
|
||||
{
|
||||
told++;
|
||||
return Task.CompletedTask;
|
||||
}, log: log.Add, cancellationToken: context.Cancellation);
|
||||
|
||||
Assert.True(resumed);
|
||||
Assert.Equal(1, told);
|
||||
var copiedFiles = before.Keys.Count(k => !IsLease(k));
|
||||
Assert.Equal(copiedFiles - 5, again, "the files verified before the stop are not copied again");
|
||||
Assert.True(log.Any(l => l.StartsWith(Loc.L("Archive.Log.WorkspaceMoveResumed", "§").Split('§')[0], StringComparison.Ordinal)), string.Join("; ", log));
|
||||
var after = Contents(to);
|
||||
foreach (var (name, sha) in before.Where(b => !IsLease(b.Key))) Assert.Equal(sha, after.GetValueOrDefault(name), name);
|
||||
Assert.False(Directory.Exists(from));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AMoveStoppedOnOneVolumeGoesOnFromItsJournal()
|
||||
{
|
||||
var (from, ids) = Workspace(projects: 3);
|
||||
var before = Contents(from);
|
||||
var to = Path.Combine(context.CreateTempDirectory("target"), "moved");
|
||||
using var stop = CancellationTokenSource.CreateLinkedTokenSource(context.Cancellation);
|
||||
var first = new WorkspaceMover(from, to)
|
||||
{
|
||||
SameVolume = true,
|
||||
Cut = (step, _) =>
|
||||
{
|
||||
if (step == "moved") stop.Cancel();
|
||||
},
|
||||
};
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => first.MoveAsync(first.Survey().Fingerprint, cancellationToken: stop.Token));
|
||||
Assert.True(WorkspaceMover.HasJournal(from));
|
||||
Assert.True(Directory.Exists(Path.Combine(to, ids.Select(i => i.ToString("N")).Order(StringComparer.Ordinal).First())), "the first project went");
|
||||
|
||||
var (_, resumed) = await new WorkspaceMover(from, to) { SameVolume = true }.MoveAsync("whatever", cancellationToken: context.Cancellation);
|
||||
Assert.True(resumed);
|
||||
Same(before, Contents(to));
|
||||
Assert.False(Directory.Exists(from));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AMoveThatFailsOnOneVolumeIsUndone()
|
||||
{
|
||||
var (from, _) = Workspace(projects: 3);
|
||||
var before = Contents(from);
|
||||
var to = Path.Combine(context.CreateTempDirectory("target"), "moved");
|
||||
var moved = 0;
|
||||
var mover = new WorkspaceMover(from, to)
|
||||
{
|
||||
SameVolume = true,
|
||||
Cut = (step, _) =>
|
||||
{
|
||||
// The second project's rename meets a file someone holds open.
|
||||
if (step == "moved" && ++moved == 2) throw new IOException("The file is in use.");
|
||||
},
|
||||
};
|
||||
await Assert.ThrowsAsync<IOException>(() => mover.MoveAsync(mover.Survey().Fingerprint, cancellationToken: context.Cancellation));
|
||||
|
||||
Same(before, Contents(from));
|
||||
Assert.False(WorkspaceMover.HasJournal(from));
|
||||
Assert.False(Directory.Exists(to), "the target made for the move went with it");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task APlanIsRefusedForTheFolderItselfAFullTargetNoRoomAndAChangedWorkspace()
|
||||
{
|
||||
var (from, ids) = Workspace(projects: 1);
|
||||
Assert.Equal(WorkspaceMoveRefusal.SameFolder, new WorkspaceMover(from, from + Path.DirectorySeparatorChar).Survey().Refusal);
|
||||
var inside = Path.Combine(from, "inner");
|
||||
var refused = new WorkspaceMover(from, inside).Survey();
|
||||
Assert.Equal(WorkspaceMoveRefusal.SameFolder, refused.Refusal);
|
||||
Assert.Equal(Loc.L("Errors.Workspace.MoveSameFolder", refused.To), refused.RefusalText);
|
||||
|
||||
// A target that is a workspace already, or holds a project of this one.
|
||||
var other = context.CreateTempDirectory("other");
|
||||
_ = new WorkspaceStore(other);
|
||||
Assert.Equal(WorkspaceMoveRefusal.TargetNotEmpty, new WorkspaceMover(from, other).Survey().Refusal);
|
||||
var holding = context.CreateTempDirectory("holding");
|
||||
Directory.CreateDirectory(Path.Combine(holding, ids[0].ToString("N")));
|
||||
var full = new WorkspaceMover(from, holding).Survey();
|
||||
Assert.Equal(Loc.L("Errors.Workspace.MoveTargetNotEmpty", full.To), full.RefusalText);
|
||||
// Unrelated files do not refuse it.
|
||||
var used = context.CreateTempDirectory("used");
|
||||
File.WriteAllText(Path.Combine(used, "readme.txt"), "x");
|
||||
Assert.True(new WorkspaceMover(from, used).Survey().CanMove);
|
||||
|
||||
// Across volumes the target's drive must hold the workspace and the reserve; a rename needs no room.
|
||||
var small = new WorkspaceMover(from, Path.Combine(used, "w")) { SameVolume = false, FreeSpace = _ => 1000, Reserve = 0 }.Survey();
|
||||
Assert.Equal((WorkspaceMoveRefusal?)WorkspaceMoveRefusal.NoRoom, small.Refusal);
|
||||
Assert.Equal(small.Bytes - 1000, small.Missing);
|
||||
Assert.True(new WorkspaceMover(from, Path.Combine(used, "w")) { SameVolume = true, FreeSpace = _ => 1000 }.Survey().CanMove);
|
||||
|
||||
// A file written after the plan: the move refuses it and touches nothing.
|
||||
var to = Path.Combine(used, "moved");
|
||||
var mover = new WorkspaceMover(from, to);
|
||||
var fingerprint = mover.Survey().Fingerprint;
|
||||
Assert.Equal(fingerprint, mover.Survey().Fingerprint, "the plan reads the same twice");
|
||||
File.WriteAllText(Path.Combine(from, ids[0].ToString("N"), "versions", "late.json"), "{}");
|
||||
var changed = await Assert.ThrowsAsync<InvalidOperationException>(() => mover.MoveAsync(fingerprint, cancellationToken: context.Cancellation));
|
||||
Assert.Equal(Loc.L("Errors.Workspace.MoveChanged"), changed.Message);
|
||||
Assert.False(Directory.Exists(to));
|
||||
Assert.False(WorkspaceMover.HasJournal(from));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheJobMovesTheWorkspaceAndTellsTheDesktop()
|
||||
{
|
||||
var (from, ids) = Workspace(projects: 2);
|
||||
var before = Contents(from);
|
||||
var to = Path.Combine(context.CreateTempDirectory("target"), "moved");
|
||||
await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory("db"), "chronos.db")), context.Cancellation);
|
||||
var told = new List<(string, string)>();
|
||||
var options = new WorkspaceJobOptions(new ProcessingOptions(), () => false, (f, t) =>
|
||||
{
|
||||
told.Add((f, t));
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
var handler = new WorkspaceMoveJobHandler(db, options) { Movers = p => new WorkspaceMover(p.From, p.To) { SameVolume = false } };
|
||||
await using var engine = new JobEngine(db, [handler],
|
||||
new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
|
||||
|
||||
// Another job of the workspace waits (nothing here runs it): the move is refused.
|
||||
var copy = await engine.EnqueueAsync(JobKind.WorkspaceCopy, [Guid.CreateVersion7()], "copy", null, cancellationToken: context.Cancellation);
|
||||
var survey = new WorkspaceMover(from, to).Survey();
|
||||
await engine.StartAsync(context.Cancellation);
|
||||
var refused = await engine.EnqueueAsync(WorkspaceJobs.Move(from, to, survey.Fingerprint), cancellationToken: context.Cancellation);
|
||||
var failed = await WaitAsync(db, refused.Id);
|
||||
Assert.Equal(JobState.Failed, failed.State);
|
||||
Assert.Equal(Loc.L("Errors.Workspace.JobsRunning"), failed.Error);
|
||||
Same(before, Contents(from));
|
||||
|
||||
await engine.CancelAsync(copy.Id, context.Cancellation);
|
||||
var job = await engine.EnqueueAsync(WorkspaceJobs.Move(from, to, survey.Fingerprint), cancellationToken: context.Cancellation);
|
||||
var done = await WaitAsync(db, job.Id);
|
||||
Assert.Equal(JobState.Done, done.State, done.Error ?? done.LogTail);
|
||||
Assert.SequenceEqual([(survey.From, survey.To)], told);
|
||||
Assert.Equal(ids.Count, new WorkspaceStore(to).List().Count);
|
||||
Assert.False(Directory.Exists(from));
|
||||
Assert.Contains(Loc.L("Archive.Log.WorkspaceMoved", survey.To, 2, survey.Files), done.LogTail);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AMoveCancelledWhilePausedIsUndone()
|
||||
{
|
||||
var (from, _) = Workspace(projects: 2);
|
||||
var before = Contents(from);
|
||||
var to = Path.Combine(context.CreateTempDirectory("target"), "moved");
|
||||
// A move stopped half way, as a pause leaves it.
|
||||
using var stop = CancellationTokenSource.CreateLinkedTokenSource(context.Cancellation);
|
||||
var mover = new WorkspaceMover(from, to) { SameVolume = true, Cut = (step, _) => stop.Cancel() };
|
||||
var fingerprint = mover.Survey().Fingerprint;
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => mover.MoveAsync(fingerprint, cancellationToken: stop.Token));
|
||||
Assert.NotEqual(before.Count, Contents(from).Count);
|
||||
|
||||
await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory("db"), "chronos.db")), context.Cancellation);
|
||||
var handler = new WorkspaceMoveJobHandler(db, new WorkspaceJobOptions(new ProcessingOptions(), () => false))
|
||||
{
|
||||
Movers = p => new WorkspaceMover(p.From, p.To) { SameVolume = true },
|
||||
};
|
||||
var request = WorkspaceJobs.Move(from, to, fingerprint);
|
||||
await using var engine = new JobEngine(db, [handler]);
|
||||
var job = await engine.EnqueueAsync(request, cancellationToken: context.Cancellation) with { State = JobState.Cancelled };
|
||||
await handler.CancelledAsync(job, context.Cancellation);
|
||||
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(20));
|
||||
while (WorkspaceMover.HasJournal(from) && DateTime.UtcNow < deadline) await Task.Delay(20, context.Cancellation);
|
||||
|
||||
Assert.False(WorkspaceMover.HasJournal(from));
|
||||
Same(before, Contents(from));
|
||||
Assert.False(Directory.Exists(to));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TwoVolumesUnderOneFolderAreCopiedWhenTheFirstRenameIsRefused()
|
||||
{
|
||||
var (from, _) = Workspace(projects: 2);
|
||||
var before = Contents(from);
|
||||
var to = Path.Combine(context.CreateTempDirectory("target"), "moved");
|
||||
var renames = 0;
|
||||
var copied = 0;
|
||||
var mover = new WorkspaceMover(from, to)
|
||||
{
|
||||
// Both under one drive letter, the target a volume mounted in a folder: the system refuses the rename.
|
||||
SameVolume = true,
|
||||
Cut = (step, _) =>
|
||||
{
|
||||
if (step == "rename" && ++renames == 1)
|
||||
throw new IOException("The system cannot move the file to a different disk drive.", OperatingSystem.IsWindows() ? unchecked((int)0x80070011) : 18);
|
||||
if (step == "copied") copied++;
|
||||
},
|
||||
};
|
||||
var (survey, resumed) = await mover.MoveAsync(mover.Survey().Fingerprint, cancellationToken: context.Cancellation);
|
||||
|
||||
Assert.False(resumed);
|
||||
Assert.True(survey.SameVolume, "planned as one volume");
|
||||
Assert.Equal(1, renames);
|
||||
Assert.Equal(before.Keys.Count(k => !IsLease(k)), copied, "every file copied and verified instead");
|
||||
var after = Contents(to);
|
||||
foreach (var (name, sha) in before.Where(b => !IsLease(b.Key))) Assert.Equal(sha, after.GetValueOrDefault(name), name);
|
||||
Assert.False(Directory.Exists(from));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnEntryThatChangedAfterItsCopyIsKeptAndTheMoveEndsWell()
|
||||
{
|
||||
var (from, ids) = Workspace(projects: 2);
|
||||
var to = Path.Combine(context.CreateTempDirectory("target"), "moved");
|
||||
var changed = Path.Combine(from, ids[0].ToString("N"), "versions", "0001.json");
|
||||
var mover = new WorkspaceMover(from, to)
|
||||
{
|
||||
SameVolume = false,
|
||||
Cut = (step, _) =>
|
||||
{
|
||||
// Written after its copy was verified, before the source is cleared.
|
||||
if (step == "switched") File.AppendAllText(changed, " ");
|
||||
},
|
||||
};
|
||||
var log = new List<string>();
|
||||
var survey = mover.Survey();
|
||||
await mover.MoveAsync(survey.Fingerprint, log: log.Add, cancellationToken: context.Cancellation);
|
||||
|
||||
Assert.Equal("{} ", File.ReadAllText(changed), "never deleted");
|
||||
Assert.False(Directory.Exists(Path.Combine(from, ids[1].ToString("N"))), "the other project went");
|
||||
Assert.Contains(Loc.L("Archive.Log.WorkspaceMoveLeft", mover.From, 1), log);
|
||||
Assert.Contains(Loc.L("Archive.Log.WorkspaceMoved", mover.To, 2, survey.Files), log);
|
||||
Assert.Equal(2, new WorkspaceStore(to).List().Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public async Task AnEntryHeldOpenAfterTheSwitchStaysInTheJournalAndIsClearedWhenTakenUp()
|
||||
{
|
||||
var (from, ids) = Workspace(projects: 2);
|
||||
var to = Path.Combine(context.CreateTempDirectory("target"), "moved");
|
||||
var heldFile = Path.Combine(from, ids[1].ToString("N"), WorkspaceProject.BundleFile);
|
||||
FileStream? held = null;
|
||||
var mover = new WorkspaceMover(from, to)
|
||||
{
|
||||
SameVolume = false,
|
||||
Cut = (step, _) =>
|
||||
{
|
||||
// An editor elsewhere holds a file of the old folder open: it cannot be deleted.
|
||||
if (step == "switched") held = new FileStream(heldFile, FileMode.Open, FileAccess.Read, FileShare.Read);
|
||||
},
|
||||
};
|
||||
var log = new List<string>();
|
||||
try
|
||||
{
|
||||
// The move ends well: the target is the workspace, the left entry is a notice.
|
||||
await mover.MoveAsync(mover.Survey().Fingerprint, log: log.Add, cancellationToken: context.Cancellation);
|
||||
}
|
||||
finally
|
||||
{
|
||||
held?.Dispose();
|
||||
}
|
||||
Assert.Contains(Loc.L("Archive.Log.WorkspaceMoveLeft", mover.From, 1), log);
|
||||
var journal = Assert.NotNull(WorkspaceMover.ReadJournal(from));
|
||||
Assert.Equal(WorkspaceMoveStage.Switched, journal.Stage);
|
||||
Assert.SequenceEqual([ids[1].ToString("N")], journal.Entries);
|
||||
Assert.Equal(2, new WorkspaceStore(to).List().Count);
|
||||
|
||||
// Taken up once let go: told again, the entry cleared, the journal and the old folder gone.
|
||||
var told = 0;
|
||||
var (_, resumed) = await new WorkspaceMover(from, to) { SameVolume = false }.MoveAsync("whatever", (_, _) =>
|
||||
{
|
||||
told++;
|
||||
return Task.CompletedTask;
|
||||
}, cancellationToken: context.Cancellation);
|
||||
Assert.True(resumed);
|
||||
Assert.Equal(1, told);
|
||||
Assert.False(Directory.Exists(from));
|
||||
Assert.Equal(2, new WorkspaceStore(to).List().Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AMoveCutInsideAnEntryLeavingAPartFinishesWithEveryFileWhole()
|
||||
{
|
||||
var (from, ids) = Workspace(projects: 2);
|
||||
var before = Contents(from);
|
||||
var to = Path.Combine(context.CreateTempDirectory("target"), "moved");
|
||||
using var stop = CancellationTokenSource.CreateLinkedTokenSource(context.Cancellation);
|
||||
var copied = 0;
|
||||
var first = new WorkspaceMover(from, to)
|
||||
{
|
||||
SameVolume = false,
|
||||
Cut = (step, _) =>
|
||||
{
|
||||
// The second file of an entry reached the target: the entry is not verified yet.
|
||||
if (step == "copied" && ++copied == 2) stop.Cancel();
|
||||
},
|
||||
};
|
||||
var fingerprint = first.Survey().Fingerprint;
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => first.MoveAsync(fingerprint, cancellationToken: stop.Token));
|
||||
Assert.Empty(WorkspaceMover.ReadJournal(from)!.Verified);
|
||||
// The program was killed while it wrote the next file: half of it is left as a part beside its name.
|
||||
var proxies = Path.Combine(to, ids.Select(i => i.ToString("N")).Order(StringComparer.Ordinal).First(), "media", "proxies");
|
||||
Directory.CreateDirectory(proxies);
|
||||
File.WriteAllBytes(Path.Combine(proxies, "2.jpg" + WorkspaceMover.PartSuffix), new byte[100]);
|
||||
|
||||
var (_, resumed) = await new WorkspaceMover(from, to) { SameVolume = false }.MoveAsync("whatever", cancellationToken: context.Cancellation);
|
||||
|
||||
Assert.True(resumed);
|
||||
var after = Contents(to);
|
||||
foreach (var (name, sha) in before.Where(b => !IsLease(b.Key))) Assert.Equal(sha, after.GetValueOrDefault(name), name);
|
||||
Assert.Empty(Directory.EnumerateFiles(to, "*" + WorkspaceMover.PartSuffix, SearchOption.AllDirectories));
|
||||
Assert.False(Directory.Exists(from));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AJobFindsItsProjectWhereTheWorkspaceIsNowAndWaitsWhileItIsMoved()
|
||||
{
|
||||
var (from, ids) = Workspace(projects: 1);
|
||||
var id = ids[0];
|
||||
const string missing = "Errors.Workspace.NotCheckedOut";
|
||||
Assert.Equal(WorkspaceStore.FullRoot(from), WorkspaceJobRoots.Resolve(from, id, null, missing));
|
||||
var other = Assert.Throws<InvalidOperationException>(() => WorkspaceJobRoots.Resolve(from, Guid.CreateVersion7(), null, missing));
|
||||
Assert.Equal(Loc.L(missing), other.Message);
|
||||
|
||||
// A move under way (before its switch): every job of either folder waits for it.
|
||||
var to = Path.Combine(context.CreateTempDirectory("target"), "moved");
|
||||
using (var stop = CancellationTokenSource.CreateLinkedTokenSource(context.Cancellation))
|
||||
{
|
||||
var moving = new WorkspaceMover(from, to) { SameVolume = false, Cut = (step, _) => { if (step == "copied") stop.Cancel(); } };
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => moving.MoveAsync(moving.Survey().Fingerprint, cancellationToken: stop.Token));
|
||||
}
|
||||
Assert.Equal(Loc.L("Errors.Workspace.Moving"), Assert.Throws<InvalidOperationException>(() => WorkspaceJobRoots.Resolve(from, id, null, missing)).Message);
|
||||
Assert.Equal(Loc.L("Errors.Workspace.Moving"), Assert.Throws<InvalidOperationException>(() => WorkspaceJobRoots.Resolve(to, id, () => from, missing)).Message);
|
||||
|
||||
// Past its switch, the source not cleared yet: a job queued for the old folder works in the new one.
|
||||
var switched = new WorkspaceMover(from, to) { SameVolume = false, Cut = (step, _) => { if (step == "switched") throw new IOException("closed at the switch"); } };
|
||||
await Assert.ThrowsAsync<IOException>(() => switched.MoveAsync("whatever", cancellationToken: context.Cancellation));
|
||||
Assert.Equal(WorkspaceMoveStage.Switched, WorkspaceMover.ReadJournal(from)!.Stage);
|
||||
Assert.Equal(WorkspaceStore.FullRoot(to), WorkspaceJobRoots.Resolve(from, id, null, missing));
|
||||
|
||||
// Once ended: the old folder holds nothing; the folder in use does.
|
||||
await new WorkspaceMover(from, to) { SameVolume = false }.MoveAsync("whatever", cancellationToken: context.Cancellation);
|
||||
Assert.False(Directory.Exists(from));
|
||||
Assert.Equal(WorkspaceStore.FullRoot(to), WorkspaceJobRoots.Resolve(from, id, () => to, missing));
|
||||
Assert.Equal(Loc.L(missing), Assert.Throws<InvalidOperationException>(() => WorkspaceJobRoots.Resolve(from, id, null, missing)).Message);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A workspace with <paramref name="projects"/> projects (a working state, media with an empty folder, versions, the
|
||||
/// lease), its manifest and a trash entry.
|
||||
/// </summary>
|
||||
private (string Root, List<Guid> Ids) Workspace(int projects)
|
||||
{
|
||||
var root = Path.Combine(context.CreateTempDirectory("ws"), "workspace");
|
||||
_ = new WorkspaceStore(root);
|
||||
var ids = new List<Guid>();
|
||||
for (var i = 0; i < projects; i++)
|
||||
{
|
||||
var id = Guid.CreateVersion7();
|
||||
ids.Add(id);
|
||||
var folder = Path.Combine(root, id.ToString("N"));
|
||||
Directory.CreateDirectory(Path.Combine(folder, "media", "proxies"));
|
||||
Directory.CreateDirectory(Path.Combine(folder, "media", "empty"));
|
||||
Directory.CreateDirectory(Path.Combine(folder, "versions"));
|
||||
File.WriteAllText(Path.Combine(folder, WorkspaceProject.BundleFile), "{\"project\": " + i + "}");
|
||||
for (var f = 0; f < 3; f++) File.WriteAllBytes(Path.Combine(folder, "media", "proxies", $"{f}.jpg"), RandomNumberGenerator.GetBytes(4096 + f * 1000));
|
||||
File.WriteAllText(Path.Combine(folder, "versions", "0001.json"), "{}");
|
||||
File.WriteAllText(Path.Combine(folder, ".lock.lease"), "held by nobody");
|
||||
}
|
||||
var trash = Path.Combine(root, ".trash", "removed-1");
|
||||
Directory.CreateDirectory(trash);
|
||||
File.WriteAllText(Path.Combine(trash, "kept.json"), "{}");
|
||||
return (root, ids);
|
||||
}
|
||||
|
||||
/// <summary>Every file under <paramref name="root"/> by its relative name, with its SHA-256; a move's journal is not counted.</summary>
|
||||
private static Dictionary<string, string> Contents(string root) =>
|
||||
Directory.Exists(root)
|
||||
? Directory.EnumerateFiles(root, "*", SearchOption.AllDirectories).Where(f => Path.GetFileName(f) != WorkspaceMover.JournalFile)
|
||||
.ToDictionary(f => Path.GetRelativePath(root, f).Replace('\\', '/'), f => Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(f))))
|
||||
: [];
|
||||
|
||||
/// <summary>Both hold the same files with the same contents.</summary>
|
||||
private static void Same(Dictionary<string, string> expected, Dictionary<string, string> actual)
|
||||
{
|
||||
Assert.SequenceEqual(expected.Keys.Order(StringComparer.Ordinal), actual.Keys.Order(StringComparer.Ordinal));
|
||||
foreach (var (name, sha) in expected) Assert.Equal(sha, actual[name], name);
|
||||
}
|
||||
|
||||
private static bool IsLease(string name) => name.EndsWith(".lease", StringComparison.Ordinal);
|
||||
|
||||
private async Task<Job> WaitAsync(ChronosDatabase db, Guid jobId)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(60));
|
||||
while (true)
|
||||
{
|
||||
var job = await db.Jobs.GetAsync(jobId, context.Cancellation);
|
||||
if (job is { State: JobState.Done or JobState.Failed or JobState.Cancelled }) return job;
|
||||
if (DateTime.UtcNow > deadline) Assert.Fail($"Job {jobId} still {job?.State}");
|
||||
await Task.Delay(20, context.Cancellation);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
using System.Security.Cryptography;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Tests.Archiving;
|
||||
using Chronos.Data.Tests.Infrastructure;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Workspaces;
|
||||
|
||||
/// <summary>A workspace project's originals (phase 5c): their copy from the archive, checked and resumable, and "Proxies only".</summary>
|
||||
[Category("workspace")]
|
||||
public abstract class WorkspaceOriginalsTests(TestContext context) : DatabaseTest(context)
|
||||
{
|
||||
private async Task<WorkspaceFixture> FixtureAsync(int frames = 3, Func<ArchiveServiceOptions, ArchiveServiceOptions>? configure = null)
|
||||
{
|
||||
var archive = Own(await ArchiveFixture.CreateAsync(Context, database: await NewOptionsAsync(multiConnection: true), configure: configure));
|
||||
var fx = Own(await WorkspaceFixture.CreateAsync(Context, archive, frames));
|
||||
// The archive's own proxies: the copy takes those, so a damaged original never changes a proxy.
|
||||
await archive.Service.Images.BuildProxiesAsync(archive.Archive, fx.Sequence, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
|
||||
return fx;
|
||||
}
|
||||
|
||||
private static string Sha(string path) => Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(path)));
|
||||
|
||||
private static async Task<(WorkspaceStore Store, WorkspaceProject Project)> CheckoutOriginalsAsync(WorkspaceFixture fx)
|
||||
{
|
||||
var (store, sync) = fx.Workspace();
|
||||
var main = await fx.Archive.Service.Projects.MainAsync(fx.Sequence.Id, fx.Ct);
|
||||
var project = await sync.CheckoutAsync(fx.Home, main.Id, BundleMedia.Originals, fx.Ct);
|
||||
return (store, project);
|
||||
}
|
||||
|
||||
private string Source(WorkspaceFixture fx, int index) => fx.Archive.Paths.FromRelative(fx.Frames.Single(f => f.Index == index).RelativePath);
|
||||
|
||||
[Test]
|
||||
public async Task ACopyOfTheOriginalsHoldsEachPhotoCheckedAgainstTheHome()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var (store, project) = await CheckoutOriginalsAsync(fx);
|
||||
Assert.Equal(fx.Frames.Sum(f => f.Size), await WorkspaceOriginals.ArchiveOriginalsBytesAsync(fx.Db, fx.Archive.Service, fx.Sequence.Id, cancellationToken: fx.Ct));
|
||||
|
||||
await fx.CopyAsync(store, project.ProjectId, media: BundleMedia.Originals);
|
||||
var media = project.ReadMedia()!;
|
||||
Assert.True(media.HoldsOriginals);
|
||||
Assert.Equal(BundleMedia.Originals, project.ReadBundle().Workspace!.Media.Kind);
|
||||
foreach (var frame in fx.Frames)
|
||||
{
|
||||
var entry = media.Frames.Single(f => f.Id == frame.Id);
|
||||
Assert.NotNull(entry.File);
|
||||
var original = project.MediaFile(Assert.NotNull(entry.Original));
|
||||
Assert.Equal(frame.Sha256!.ToLowerInvariant(), entry.OriginalSha256);
|
||||
Assert.Equal(entry.OriginalSha256, Sha(original));
|
||||
Assert.Equal(frame.Size, entry.OriginalBytes);
|
||||
Assert.Equal(WorkspaceProject.OriginalName(frame.Id, frame.Sha256, Path.GetExtension(frame.RelativePath)), entry.Original);
|
||||
}
|
||||
Assert.Empty(Directory.GetFiles(project.OriginalsDirectory, "*.part"));
|
||||
Assert.Equal(0L, await WorkspaceOriginals.ArchiveOriginalsBytesAsync(fx.Db, fx.Archive.Service, fx.Sequence.Id, project, fx.Ct));
|
||||
|
||||
// The frames read by a local render are the originals.
|
||||
Assert.SequenceEqual(media.Frames.Select(f => f.Original), media.ToOriginalFrames().Select(f => f.RelativePath));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnOriginalThatIsGoneOrDamagedAtTheHomeLeavesItsFrameProxied()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var (store, project) = await CheckoutOriginalsAsync(fx);
|
||||
File.Delete(Source(fx, 0));
|
||||
var damaged = Source(fx, 1);
|
||||
var bytes = File.ReadAllBytes(damaged);
|
||||
bytes[^3] ^= 0x5A;
|
||||
File.WriteAllBytes(damaged, bytes);
|
||||
|
||||
await fx.CopyAsync(store, project.ProjectId, media: BundleMedia.Originals);
|
||||
var media = project.ReadMedia()!;
|
||||
Assert.True(media.HoldsOriginals);
|
||||
var gone = media.Frames.Single(f => f.Index == 0);
|
||||
var mismatched = media.Frames.Single(f => f.Index == 1);
|
||||
Assert.Null(gone.Original);
|
||||
Assert.Null(mismatched.Original);
|
||||
Assert.NotNull(mismatched.File);
|
||||
Assert.NotNull(media.Frames.Single(f => f.Index == 2).Original);
|
||||
Assert.Equal(1, Directory.GetFiles(project.OriginalsDirectory).Length);
|
||||
Assert.True(media.ToOriginalFrames().Count(f => (f.Flags & FrameFlags.Missing) != 0) == 2, "a render counts the two frames without an original");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ACopyStoppedAmongTheOriginalsResumesWithWhatItHad()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var (store, project) = await CheckoutOriginalsAsync(fx);
|
||||
await fx.CopyAsync(store, project.ProjectId, media: BundleMedia.Originals);
|
||||
var media = project.ReadMedia()!;
|
||||
var kept = project.MediaFile(media.Frames[0].Original!);
|
||||
var written = File.GetLastWriteTimeUtc(kept);
|
||||
var lost = project.MediaFile(media.Frames[2].Original!);
|
||||
File.Delete(lost);
|
||||
File.WriteAllBytes(Path.Combine(project.OriginalsDirectory, media.Frames[2].Id.ToString("N") + ".part"), [1, 2, 3]);
|
||||
|
||||
var row = (await fx.Db.Sequences.GetAsync(fx.Sequence.Id))!;
|
||||
await fx.CopyAsync(store, project.ProjectId, checkpoint: $"originals:2:{row.FramesVersion}:{row.Folder}", media: BundleMedia.Originals);
|
||||
Assert.Equal(written, File.GetLastWriteTimeUtc(kept));
|
||||
Assert.Equal(media.Frames[2].OriginalSha256, Sha(lost));
|
||||
Assert.Empty(Directory.GetFiles(project.OriginalsDirectory, "*.part"));
|
||||
Assert.Equal(3, project.ReadMedia()!.Frames.Count(f => f.HasOriginal));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheOriginalsAreNotCopiedWhenTheDriveLacksTheirRoom()
|
||||
{
|
||||
long? free = null;
|
||||
var fx = await FixtureAsync(configure: options => options with { FreeSpace = _ => free });
|
||||
var (store, project) = await CheckoutOriginalsAsync(fx);
|
||||
await fx.CopyAsync(store, project.ProjectId);
|
||||
free = WorkspaceJobs.CopySpaceReserve + fx.Frames.Sum(f => f.Size) - 1;
|
||||
|
||||
var job = await fx.CopyAsync(store, project.ProjectId, JobState.Failed, media: BundleMedia.Originals);
|
||||
var parts = Loc.L("Errors.Workspace.DiskFull", "\u0001").Split('\u0001');
|
||||
Assert.True(job.Error!.StartsWith(parts[0], StringComparison.Ordinal), job.Error);
|
||||
Assert.False(project.ReadMedia()!.HoldsOriginals);
|
||||
Assert.False(Directory.Exists(project.OriginalsDirectory) && Directory.EnumerateFiles(project.OriginalsDirectory).Any());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ProxiesOnlyDeletesWhatTheHomeHoldsAndTrashesTheRest()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var (store, project) = await CheckoutOriginalsAsync(fx);
|
||||
await fx.CopyAsync(store, project.ProjectId, media: BundleMedia.Originals);
|
||||
var media = project.ReadMedia()!;
|
||||
// The home lost frame 1's photo: its only copy is the workspace's, which goes to the trash, not away.
|
||||
var lostAtHome = project.MediaFile(media.Frames[1].Original!);
|
||||
var home = await fx.Home.FramesAsync(fx.Ct);
|
||||
home = home with { Frames = [.. home.Frames.Select(f => f.Index == 1 ? f with { Flags = f.Flags | FrameFlags.Missing } : f)] };
|
||||
|
||||
var plan = WorkspaceOriginals.PlanProxiesOnly(project, home);
|
||||
Assert.Equal((2, 1), (plan.Originals, plan.ToTrash));
|
||||
Assert.Equal(fx.Frames.Where(f => f.Index != 1).Sum(f => f.Size), plan.Bytes);
|
||||
var trashed = await WorkspaceOriginals.ApplyProxiesOnlyAsync(project, plan, home, TimeSpan.FromSeconds(10), fx.Ct);
|
||||
Assert.Equal(1, trashed);
|
||||
Assert.False(Directory.Exists(project.OriginalsDirectory));
|
||||
var after = project.ReadMedia()!;
|
||||
Assert.False(after.HoldsOriginals);
|
||||
Assert.True(after.Frames.All(f => f.Original is null && f.File is not null));
|
||||
Assert.Equal(BundleMedia.Proxies, project.ReadBundle().Workspace!.Media.Kind);
|
||||
var inTrash = Directory.GetFiles(Path.Combine(store.Root, WorkspaceOriginals.TrashFolder), Path.GetFileName(lostAtHome), SearchOption.AllDirectories);
|
||||
Assert.Equal(1, inTrash.Length);
|
||||
Assert.Equal(media.Frames[1].OriginalSha256, Sha(inTrash[0]));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ACancelledCopyOfTheOriginalsRemovesWhatItWroteAndTrashesWhatTheHomeLacks()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var (store, sync) = fx.Workspace();
|
||||
var project = await fx.CheckoutAsync(sync);
|
||||
Assert.False(project.ReadMedia()!.HoldsOriginals);
|
||||
var until = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(30));
|
||||
|
||||
// Held so that the copy writes its originals and waits to record them; cancelled there.
|
||||
var lease = await project.LockAsync(TimeSpan.FromSeconds(10), fx.Ct);
|
||||
Job job;
|
||||
try
|
||||
{
|
||||
job = await fx.StartCopyAsync(store, project.ProjectId, BundleMedia.Originals);
|
||||
while (!(Directory.Exists(project.OriginalsDirectory)
|
||||
&& Directory.GetFiles(project.OriginalsDirectory).Count(f => !f.EndsWith(".part", StringComparison.Ordinal)) == fx.Frames.Count))
|
||||
{
|
||||
if (DateTime.UtcNow > until) Assert.Fail("the copy's originals were not written");
|
||||
await Task.Delay(20, fx.Ct);
|
||||
}
|
||||
// A file of bytes the home does not hold, and a download cut short.
|
||||
File.WriteAllText(Path.Combine(project.OriginalsDirectory, "edited.jpg"), "not the home's photo");
|
||||
File.WriteAllText(Path.Combine(project.OriginalsDirectory, Guid.NewGuid().ToString("N") + ".part"), "half");
|
||||
await fx.CancelAsync(job.Id);
|
||||
}
|
||||
finally
|
||||
{
|
||||
lease.Dispose();
|
||||
}
|
||||
await fx.Archive.WaitForAsync(job.Id, JobState.Cancelled, (int)TestTiming.Budget(30));
|
||||
while (Directory.Exists(project.OriginalsDirectory))
|
||||
{
|
||||
if (DateTime.UtcNow > until) Assert.Fail("the cancelled copy's originals stayed: " + string.Join(", ", Directory.GetFiles(project.OriginalsDirectory).Select(Path.GetFileName)));
|
||||
await Task.Delay(20, fx.Ct);
|
||||
}
|
||||
|
||||
// The media a copy finished before stay; the one file the home lacks is in the trash, never away.
|
||||
var media = project.ReadMedia()!;
|
||||
Assert.False(media.HoldsOriginals);
|
||||
foreach (var frame in media.Frames) Assert.FileExists(project.MediaFile(frame.File!));
|
||||
var inTrash = Directory.GetFiles(Path.Combine(store.Root, WorkspaceOriginals.TrashFolder), "*", SearchOption.AllDirectories);
|
||||
Assert.SequenceEqual(["edited.jpg"], inTrash.Select(Path.GetFileName));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ProxiesOnlyRefusesAPlanTheFilesChangedSince()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var (store, project) = await CheckoutOriginalsAsync(fx);
|
||||
await fx.CopyAsync(store, project.ProjectId, media: BundleMedia.Originals);
|
||||
var home = await fx.Home.FramesAsync(fx.Ct);
|
||||
var plan = WorkspaceOriginals.PlanProxiesOnly(project, home);
|
||||
Assert.Equal((3, 0), (plan.Originals, plan.ToTrash));
|
||||
|
||||
var changed = project.MediaFile(project.ReadMedia()!.Frames[0].Original!);
|
||||
File.AppendAllText(changed, "x");
|
||||
var error = await Assert.ThrowsAsync<InvalidOperationException>(() => WorkspaceOriginals.ApplyProxiesOnlyAsync(project, plan, home, TimeSpan.FromSeconds(10), fx.Ct));
|
||||
Assert.Equal(Loc.L("Errors.Workspace.MediaChanged"), error.Message);
|
||||
Assert.True(project.ReadMedia()!.HoldsOriginals);
|
||||
Assert.Equal(3, Directory.GetFiles(project.OriginalsDirectory).Length);
|
||||
|
||||
// Planned again, the changed file is no photo the home holds: it goes to the trash.
|
||||
var again = WorkspaceOriginals.PlanProxiesOnly(project, home);
|
||||
Assert.Equal((2, 1), (again.Originals, again.ToTrash));
|
||||
Assert.Equal(1, await WorkspaceOriginals.ApplyProxiesOnlyAsync(project, again, home, TimeSpan.FromSeconds(10), fx.Ct));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SqliteWorkspaceOriginalsTests(TestContext context) : WorkspaceOriginalsTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.SqliteFile;
|
||||
}
|
||||
|
||||
[RequiresEnvironment(PgTestServer.Variable)]
|
||||
public sealed class PostgresWorkspaceOriginalsTests(TestContext context) : WorkspaceOriginalsTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.Postgres;
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
using Chronos.Core.Diagnostics.Synthetic;
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Data.Processing.Jobs;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Data.Tests.Processing;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Workspaces;
|
||||
|
||||
/// <summary>
|
||||
/// A workspace project rendered on this PC from the originals its media hold (phase 5c, <see cref="JobKind.WorkspaceRender"/>):
|
||||
/// into its exports, recorded in its ledger and sent home after; refused without the originals; a cancel leaves nothing half written.
|
||||
/// </summary>
|
||||
[Category("workspace")]
|
||||
public sealed class WorkspaceRenderTests(TestContext context)
|
||||
{
|
||||
private const int Frames = 24;
|
||||
|
||||
private static readonly ExportSettings Mjpeg = new()
|
||||
{
|
||||
Preset = new Auto<string>().WithManual("mjpeg-avi"),
|
||||
Overrides = new ExportOverrides { Width = 96, Height = 64 },
|
||||
NameTemplate = "clip-{codec}",
|
||||
};
|
||||
|
||||
private static SyntheticSequence Scene() => SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = Frames, StartEv = 0.5, EndEv = -0.5 });
|
||||
|
||||
private sealed record Bed(ProcessingFixture Fx, Sequence Sequence, WorkspaceStore Store, WorkspaceProject Project, JobEngine Engine) : IAsyncDisposable
|
||||
{
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await Engine.DisposeAsync();
|
||||
await Fx.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A sequence of the archive, Main checked out into a workspace with <paramref name="media"/> copied, and an engine running every handler.</summary>
|
||||
private async Task<Bed> BedAsync(string media = BundleMedia.Originals, Action<ProcessingFixture, Sequence>? beforeCopy = null)
|
||||
{
|
||||
var fx = await ProcessingFixture.CreateAsync(context);
|
||||
var sequence = await fx.AddAsync(Scene());
|
||||
var engine = new JobEngine(fx.Db,
|
||||
[
|
||||
.. fx.Archive.Service.CreateJobHandlers(), .. fx.Processing.CreateJobHandlers(),
|
||||
.. WorkspaceJobs.CreateHandlers(fx.Db, fx.Archive.Service, null, new WorkspaceJobOptions(fx.Processing.Options, () => false)),
|
||||
],
|
||||
new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
|
||||
await engine.StartAsync(fx.Ct);
|
||||
var store = new WorkspaceStore(Path.Combine(context.CreateTempDirectory("render-ws"), "workspace"));
|
||||
var sync = new WorkspaceSync(store, "test") { LockWait = TimeSpan.FromSeconds(TestTiming.Budget(10)) };
|
||||
var home = new ArchiveProjectHome(fx.Db, fx.Archive.Service.Projects, sequence.Id);
|
||||
var main = await fx.Archive.Service.Projects.MainAsync(sequence.Id, fx.Ct);
|
||||
var project = await sync.CheckoutAsync(home, main.Id, media, fx.Ct);
|
||||
beforeCopy?.Invoke(fx, sequence);
|
||||
var copy = await engine.EnqueueAsync(WorkspaceJobs.Copy(sequence, store.Root, main.Id, media), cancellationToken: fx.Ct);
|
||||
await fx.WaitForAsync(copy.Id, JobState.Done);
|
||||
return new Bed(fx, sequence, store, project, engine);
|
||||
}
|
||||
|
||||
private static ArchiveJobRequest RenderRequest(Bed bed, Guid? versionId = null)
|
||||
{
|
||||
var json = ProcessingJobs.Render(bed.Sequence, Mjpeg, 96, 64, new ProjectSettings()).ParametersJson!;
|
||||
return WorkspaceJobs.Render(bed.Sequence.Id, bed.Sequence.DisplayTitle, bed.Store.Root, bed.Project.ProjectId, versionId, json);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ARenderFromTheOriginalsIsWrittenToExportsRecordedAndSentAfter()
|
||||
{
|
||||
await using var bed = await BedAsync();
|
||||
var fx = bed.Fx;
|
||||
var job = await bed.Engine.EnqueueAsync(RenderRequest(bed), cancellationToken: fx.Ct);
|
||||
await fx.WaitForAsync(job.Id, JobState.Done);
|
||||
|
||||
var output = Path.Combine(bed.Project.ExportsDirectory, "clip-MJPEG.avi");
|
||||
Assert.FileExists(output);
|
||||
Assert.Empty(Directory.EnumerateFileSystemEntries(bed.Project.ExportsDirectory, ".*"));
|
||||
var entry = bed.Project.ReadRenders().Entries.Single();
|
||||
Assert.Equal(RenderJobHandler.RenderId(job.Id, 0), entry.RenderId);
|
||||
Assert.Equal((job.Id, "clip-MJPEG.avi", new FileInfo(output).Length, WorkspaceRenderEntry.Pending, bed.Project.ProjectId),
|
||||
(entry.JobId, entry.File, entry.Size, entry.State, entry.ProjectId));
|
||||
Assert.Equal(await Chronos.Core.Archiving.ContentHash.Sha256Async(output), entry.Sha256);
|
||||
Assert.Equal(("Mjpeg", 96, 64), (entry.Codec, entry.Width, entry.Height));
|
||||
Assert.Null(entry.ProjectVersionId, "the working state the job embeds is no version this workspace holds");
|
||||
|
||||
// The send home follows with the new render, and files it in the archive with its project.
|
||||
var send = (await fx.Db.Jobs.ListAsync(null, 50, null, fx.Ct)).Items.Single(j => j.Kind == JobKind.WorkspaceSend);
|
||||
var sent = Assert.NotNull(WorkspaceJobs.SendParameters(send));
|
||||
// Every render not sent yet, this one among them: one a send failed earlier goes with it.
|
||||
Assert.Empty(sent.RenderIds);
|
||||
Assert.Equal((bed.Project.ProjectId, bed.Store.Root), (sent.ProjectId, sent.WorkspaceRoot));
|
||||
await fx.WaitForAsync(send.Id, JobState.Done);
|
||||
var filed = Assert.NotNull(await fx.Db.Renders.GetAsync(entry.RenderId, fx.Ct));
|
||||
Assert.Equal((bed.Sequence.Id, (Guid?)bed.Project.ProjectId, (Guid?)null), (filed.SequenceId, filed.ProjectId, filed.ProjectVersionId));
|
||||
entry = Assert.NotNull(bed.Project.ReadRenders().Find(entry.RenderId));
|
||||
Assert.True(entry.IsSent, "the ledger says it went home");
|
||||
|
||||
// The same render of the archive's own sequence: the same pictures, at the same size and length.
|
||||
var archive = await bed.Engine.EnqueueAsync(ProcessingJobs.Render(bed.Sequence, Mjpeg, 96, 64), cancellationToken: fx.Ct);
|
||||
await fx.WaitForAsync(archive.Id, JobState.Done);
|
||||
var row = Assert.NotNull(await fx.Db.Renders.GetAsync(RenderJobHandler.RenderId(archive.Id, 0), fx.Ct));
|
||||
Assert.Equal((row.Width, row.Height, row.Fps, row.DurationSeconds), (entry.Width, entry.Height, entry.Fps, entry.DurationSeconds));
|
||||
|
||||
// Again: another name, the first output and its entry kept.
|
||||
var again = await bed.Engine.EnqueueAsync(RenderRequest(bed), cancellationToken: fx.Ct);
|
||||
await fx.WaitForAsync(again.Id, JobState.Done);
|
||||
var entries = bed.Project.ReadRenders().Entries;
|
||||
Assert.Equal(2, entries.Count);
|
||||
Assert.True(entries[1].File != entries[0].File, entries[1].File);
|
||||
Assert.Equal(entry, entries[0]);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AVersionHeldInTheWorkspaceIsRecordedWithTheRender()
|
||||
{
|
||||
await using var bed = await BedAsync();
|
||||
var fx = bed.Fx;
|
||||
var (_, sync) = (bed.Store, new WorkspaceSync(bed.Store, "test"));
|
||||
var session = await sync.OpenAsync(bed.Project.ProjectId, fx.Ct);
|
||||
await sync.SaveAsync(bed.Project.ProjectId, session.Working with { ExcludedFrames = [2] }, fx.Ct);
|
||||
var version = Assert.NotNull(await sync.CommitAsync(bed.Project.ProjectId, "Render", cancellationToken: fx.Ct));
|
||||
var json = ProcessingJobs.Render(bed.Sequence, Mjpeg, 96, 64).ParametersJson!;
|
||||
// The job names the version alone: the settings come from versions/.
|
||||
var stripped = System.Text.Json.Nodes.JsonNode.Parse(json)!.AsObject();
|
||||
stripped.Remove("settingsJson");
|
||||
var job = await bed.Engine.EnqueueAsync(
|
||||
WorkspaceJobs.Render(bed.Sequence.Id, bed.Sequence.DisplayTitle, bed.Store.Root, bed.Project.ProjectId, version.Id, stripped.ToJsonString()), cancellationToken: fx.Ct);
|
||||
await fx.WaitForAsync(job.Id, JobState.Done);
|
||||
var entry = bed.Project.ReadRenders().Entries.Single();
|
||||
Assert.Equal(version.Id, entry.ProjectVersionId);
|
||||
Assert.Equal(version.ContentHash, entry.SettingsHash);
|
||||
|
||||
// A version the workspace does not hold: refused, saying so.
|
||||
var unknown = await bed.Engine.EnqueueAsync(
|
||||
WorkspaceJobs.Render(bed.Sequence.Id, bed.Sequence.DisplayTitle, bed.Store.Root, bed.Project.ProjectId, Guid.CreateVersion7(), stripped.ToJsonString()),
|
||||
cancellationToken: fx.Ct);
|
||||
Assert.Equal(Loc.L("Errors.Workspace.RenderVersion"), (await fx.WaitForAsync(unknown.Id, JobState.Failed)).Error);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The whole way of a local render to an archive home: originals copied, a version saved for the render, the render on this
|
||||
/// PC, the send that pushes the version first and files the render with its project and version, then the clean-up that
|
||||
/// removes the media and the sent file of the project, now in step with its home.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public async Task ALocalRenderGoesHomeWithItsVersionAndTheCleanUpThenFreesTheProject()
|
||||
{
|
||||
await using var bed = await BedAsync();
|
||||
var fx = bed.Fx;
|
||||
var id = bed.Project.ProjectId;
|
||||
var sync = new WorkspaceSync(bed.Store, "test") { LockWait = TimeSpan.FromSeconds(TestTiming.Budget(10)) };
|
||||
var home = new ArchiveProjectHome(fx.Db, fx.Archive.Service.Projects, bed.Sequence.Id);
|
||||
Assert.True(bed.Project.ReadMedia() is { HoldsOriginals: true }, "the copy brought the originals");
|
||||
// The archive's photos hashed (a Verify), so the home can say it holds each original as it is here.
|
||||
var verify = await bed.Engine.EnqueueAsync(ArchiveJobs.Verify(fx.Archive.Archive, [bed.Sequence.Id]), cancellationToken: fx.Ct);
|
||||
await fx.WaitForAsync(verify.Id, JobState.Done);
|
||||
|
||||
// Version on render: the working state saved as a version here, not sent yet.
|
||||
var session = await sync.OpenAsync(id, fx.Ct);
|
||||
await sync.SaveAsync(id, session.Working with { ExcludedFrames = [4] }, fx.Ct);
|
||||
var version = Assert.NotNull(await sync.CommitAsync(id, "Render", cancellationToken: fx.Ct));
|
||||
Assert.Null(await home.GetVersionAsync(id, version.Id, fx.Ct), "the home does not have the version yet");
|
||||
|
||||
var json = System.Text.Json.Nodes.JsonNode.Parse(ProcessingJobs.Render(bed.Sequence, Mjpeg, 96, 64).ParametersJson!)!.AsObject();
|
||||
json.Remove("settingsJson");
|
||||
var render = await bed.Engine.EnqueueAsync(
|
||||
WorkspaceJobs.Render(bed.Sequence.Id, bed.Sequence.DisplayTitle, bed.Store.Root, id, version.Id, json.ToJsonString()), cancellationToken: fx.Ct);
|
||||
await fx.WaitForAsync(render.Id, JobState.Done);
|
||||
var entry = bed.Project.ReadRenders().Entries.Single();
|
||||
Assert.Equal((version.Id, WorkspaceRenderEntry.Pending), (entry.ProjectVersionId, entry.State));
|
||||
|
||||
// The send pushes the version, then files the render with its project and version.
|
||||
var send = (await fx.Db.Jobs.ListAsync(null, 50, null, fx.Ct)).Items.Single(j => j.Kind == JobKind.WorkspaceSend);
|
||||
send = await fx.WaitForAsync(send.Id, JobState.Done);
|
||||
Assert.Contains(Loc.L("Archive.Log.WorkspaceVersionPushed", bed.Project.ReadBundle().Workspace!.Name, version.Number), send.LogTail);
|
||||
Assert.NotNull(await home.GetVersionAsync(id, version.Id, fx.Ct));
|
||||
var row = Assert.NotNull(await fx.Db.Renders.GetAsync(entry.RenderId, fx.Ct));
|
||||
Assert.Equal((bed.Sequence.Id, (Guid?)id, (Guid?)version.Id, entry.Size), (row.SequenceId, row.ProjectId, row.ProjectVersionId, row.Bytes));
|
||||
Assert.Equal(entry.Sha256, await Chronos.Core.Archiving.ContentHash.Sha256Async(Path.Combine(fx.Archive.Paths.Root, row.OutputPath)));
|
||||
Assert.True(bed.Project.ReadRenders().Find(entry.RenderId)!.IsSent, "the ledger says it went home");
|
||||
Assert.Equal(WorkspaceState.InSync, (await sync.StatusAsync(id, home, fx.Ct)).State);
|
||||
|
||||
// The clean-up (here the size limit) frees the project: its proxies, originals and the sent render go; the originals
|
||||
// are the home's own, so none is set aside in the trash.
|
||||
var exported = bed.Project.ExportFile(entry.File);
|
||||
var report = await new WorkspaceCleaner(sync, fx.Db, _ => home) { LockWait = TimeSpan.FromSeconds(TestTiming.Budget(10)) }
|
||||
.CleanAsync(new WorkspaceCleanOptions { SizeLimitBytes = 1 }, fx.Ct);
|
||||
var cleaned = Assert.NotNull(report.Cleaned.SingleOrDefault());
|
||||
Assert.Equal((id, 0), (cleaned.ProjectId, cleaned.Trashed));
|
||||
Assert.Empty(report.Kept);
|
||||
Assert.FileMissing(exported);
|
||||
Assert.Empty(bed.Project.ReadRenders().Entries);
|
||||
Assert.False(Directory.Exists(bed.Project.OriginalsDirectory), "the originals went");
|
||||
Assert.False(Directory.Exists(bed.Project.ProxiesDirectory), "the proxies went");
|
||||
Assert.True(bed.Project.ReadMedia() is { IsCleaned: true }, "the media index says it was cleaned");
|
||||
Assert.Equal(WorkspaceState.MediaRemoved, (await sync.StatusAsync(id, home, fx.Ct)).State);
|
||||
// The home keeps the render and the version.
|
||||
Assert.FileExists(Path.Combine(fx.Archive.Paths.Root, row.OutputPath));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WithoutTheOriginalsTheRenderIsRefusedSayingHowManyLack()
|
||||
{
|
||||
await using var bed = await BedAsync(beforeCopy: (fx, sequence) =>
|
||||
{
|
||||
File.Delete(Path.Combine(fx.Archive.Paths.Root, "Synthetic", ProcessingFixture.FileName(3)));
|
||||
File.Delete(Path.Combine(fx.Archive.Paths.Root, "Synthetic", ProcessingFixture.FileName(7)));
|
||||
});
|
||||
var fx = bed.Fx;
|
||||
Assert.Equal(Frames - 2, bed.Project.ReadMedia()!.Frames.Count(f => f.HasOriginal));
|
||||
var job = await bed.Engine.EnqueueAsync(RenderRequest(bed), cancellationToken: fx.Ct);
|
||||
Assert.Equal(Loc.L("Errors.Workspace.RenderNoOriginals", 2), (await fx.WaitForAsync(job.Id, JobState.Failed)).Error);
|
||||
Assert.Empty(bed.Project.ReadRenders().Entries);
|
||||
Assert.False(Directory.Exists(bed.Project.ExportsDirectory) && Directory.EnumerateFileSystemEntries(bed.Project.ExportsDirectory).Any());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ProxiesAloneAreRefused()
|
||||
{
|
||||
await using var bed = await BedAsync(BundleMedia.Proxies);
|
||||
var job = await bed.Engine.EnqueueAsync(RenderRequest(bed), cancellationToken: bed.Fx.Ct);
|
||||
Assert.Equal(Loc.L("Errors.Workspace.OriginalsMissing"), (await bed.Fx.WaitForAsync(job.Id, JobState.Failed)).Error);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ACancelledRenderLeavesNoPartialOutput()
|
||||
{
|
||||
await using var bed = await BedAsync();
|
||||
var fx = bed.Fx;
|
||||
fx.Decoder.HoldPurpose = DecodePurpose.Render;
|
||||
fx.Decoder.Hold = Path.GetFileName(bed.Project.ReadMedia()!.Frames[12].Original);
|
||||
var job = await bed.Engine.EnqueueAsync(RenderRequest(bed), cancellationToken: fx.Ct);
|
||||
await fx.Decoder.Holding.Task.WaitAsync(TimeSpan.FromSeconds(60), fx.Ct);
|
||||
await bed.Engine.CancelAsync(job.Id, fx.Ct);
|
||||
await fx.WaitForAsync(job.Id, JobState.Cancelled);
|
||||
var until = DateTime.UtcNow.AddSeconds(30);
|
||||
while (bed.Engine.RunningJobIds.Contains(job.Id))
|
||||
{
|
||||
Assert.True(DateTime.UtcNow < until, "the render did not stop");
|
||||
await Task.Delay(20, fx.Ct);
|
||||
}
|
||||
var left = Directory.Exists(bed.Project.ExportsDirectory) ? Directory.GetFileSystemEntries(bed.Project.ExportsDirectory) : [];
|
||||
Assert.Empty(left);
|
||||
Assert.Empty(bed.Project.ReadRenders().Entries);
|
||||
Assert.False((await fx.Db.Jobs.ListAsync(null, 50, null, fx.Ct)).Items.Any(j => j.Kind == JobKind.WorkspaceSend), "nothing to send");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
using System.Security.Cryptography;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Tests.Archiving;
|
||||
using Chronos.Data.Tests.Infrastructure;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Workspaces;
|
||||
|
||||
/// <summary>
|
||||
/// A workspace's local renders sent home (phase 5c, <see cref="JobKind.WorkspaceSend"/>) to this PC's archive: filed with
|
||||
/// their project and version, the version pushed first when the home lacks it, a changed or missing file refused and left in
|
||||
/// the workspace, a send repeated after a cut harmless, and never held on a metered connection.
|
||||
/// </summary>
|
||||
[Category("workspace")]
|
||||
public abstract class WorkspaceSendTests(TestContext context) : DatabaseTest(context)
|
||||
{
|
||||
private static readonly DateTimeOffset Rendered = new(2026, 11, 4, 9, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private async Task<WorkspaceFixture> FixtureAsync()
|
||||
{
|
||||
var archive = Own(await ArchiveFixture.CreateAsync(Context, database: await NewOptionsAsync(multiConnection: true)));
|
||||
return Own(await WorkspaceFixture.CreateAsync(Context, archive, 3));
|
||||
}
|
||||
|
||||
/// <summary>An engine with the workspace's handlers; <paramref name="hold"/> stands for a metered connection.</summary>
|
||||
private async Task<JobEngine> EngineAsync(WorkspaceFixture fx, Func<bool>? hold = null)
|
||||
{
|
||||
var options = WorkspaceJobOptions.For(fx.Archive.Service) with { HoldTransfers = hold ?? (() => false) };
|
||||
var engine = new JobEngine(fx.Db, WorkspaceJobs.CreateHandlers(fx.Db, fx.Archive.Service, null, options),
|
||||
new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
|
||||
await engine.StartAsync(Ct);
|
||||
Own(engine);
|
||||
return engine;
|
||||
}
|
||||
|
||||
/// <summary>Main checked out into a workspace of its own (its media are not needed to send).</summary>
|
||||
private static async Task<(WorkspaceStore Store, WorkspaceSync Sync, WorkspaceProject Project)> CheckoutAsync(WorkspaceFixture fx)
|
||||
{
|
||||
var (store, sync) = fx.Workspace();
|
||||
var main = await fx.Archive.Service.Projects.MainAsync(fx.Sequence.Id, fx.Ct);
|
||||
return (store, sync, await sync.CheckoutAsync(fx.Home, main.Id, cancellationToken: fx.Ct));
|
||||
}
|
||||
|
||||
/// <summary>An output in the project's exports with its ledger entry, as a local render leaves them.</summary>
|
||||
private static WorkspaceRenderEntry Render(WorkspaceProject project, Guid? versionId, string name, int seed, string? settingsHash = null)
|
||||
{
|
||||
Directory.CreateDirectory(project.ExportsDirectory);
|
||||
var bytes = new byte[150_000 + seed];
|
||||
new Random(seed).NextBytes(bytes);
|
||||
File.WriteAllBytes(Path.Combine(project.ExportsDirectory, name), bytes);
|
||||
var entry = new WorkspaceRenderEntry(Guid.CreateVersion7(), Guid.CreateVersion7(), name, Convert.ToHexStringLower(SHA256.HashData(bytes)), bytes.Length,
|
||||
"1080p H.264", "h264", 1920, 1080, 24, 2.5, project.ProjectId, versionId, settingsHash, Rendered);
|
||||
project.WriteRenders(project.ReadRenders().With(entry));
|
||||
return entry;
|
||||
}
|
||||
|
||||
private static string Sha(string path) => Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(path)));
|
||||
|
||||
private static async Task<Job> SendAsync(WorkspaceFixture fx, JobEngine engine, WorkspaceStore store, Guid projectId, JobState expected,
|
||||
params Guid[] renderIds)
|
||||
{
|
||||
var job = await engine.EnqueueAsync(WorkspaceJobs.Send(fx.Sequence.Id, fx.Sequence.DisplayTitle, store.Root, projectId, renderIds), cancellationToken: fx.Ct);
|
||||
return await fx.Archive.WaitForAsync(job.Id, expected, (int)TestTiming.Budget(60));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheSendFilesTheRenderInTheLibraryWithItsProjectAndVersion()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var engine = await EngineAsync(fx);
|
||||
var (store, _, project) = await CheckoutAsync(fx);
|
||||
var head = project.ReadBundle().Workspace!.Base!.VersionId;
|
||||
var entry = Render(project, head, "Main 1080p.mp4", 1);
|
||||
|
||||
await SendAsync(fx, engine, store, project.ProjectId, JobState.Done);
|
||||
|
||||
var row = Assert.NotNull(await fx.Db.Renders.GetAsync(entry.RenderId, fx.Ct));
|
||||
Assert.Equal((fx.Sequence.Id, (Guid?)project.ProjectId, (Guid?)head, "1080p H.264", entry.Size, 1920),
|
||||
(row.SequenceId, row.ProjectId, row.ProjectVersionId, row.PresetName, row.Bytes, row.Width));
|
||||
var filed = Path.Combine(fx.Archive.Archive.RootPath, row.OutputPath);
|
||||
Assert.Equal(entry.Sha256, Sha(filed));
|
||||
Assert.Equal("Main 1080p.mp4", Path.GetFileName(filed));
|
||||
// The workspace keeps its file until a clean-up; the ledger says it went home.
|
||||
Assert.Equal(entry.Sha256, Sha(project.ExportFile(entry.File)));
|
||||
var sent = Assert.NotNull(project.ReadRenders().Find(entry.RenderId));
|
||||
Assert.True(sent.IsSent);
|
||||
Assert.NotNull(sent.Sent);
|
||||
Assert.Empty(Directory.GetFiles(fx.Archive.Paths.StagingDirectory, "workspace-render-*"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ASendRepeatedAfterACutFilesNothingTwice()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var engine = await EngineAsync(fx);
|
||||
var (store, _, project) = await CheckoutAsync(fx);
|
||||
var entry = Render(project, project.ReadBundle().Workspace!.Base!.VersionId, "Main.mp4", 2);
|
||||
await SendAsync(fx, engine, store, project.ProjectId, JobState.Done, entry.RenderId);
|
||||
|
||||
// Cut after the home filed it, before the ledger said so: the next send finds it there and only marks it sent.
|
||||
project.WriteRenders(project.ReadRenders().With(entry));
|
||||
Assert.True(project.ReadRenders().Find(entry.RenderId)!.IsUnsent);
|
||||
var again = await SendAsync(fx, engine, store, project.ProjectId, JobState.Done);
|
||||
Assert.Contains(Loc.L("Archive.Log.WorkspaceSent", project.ReadBundle().Workspace!.Name, 0, 1), again.LogTail);
|
||||
Assert.True(project.ReadRenders().Find(entry.RenderId)!.IsSent);
|
||||
Assert.Equal(1, (await fx.Db.Renders.ListBySequenceAsync(fx.Sequence.Id, fx.Ct)).Count);
|
||||
var exports = Path.GetDirectoryName(Path.Combine(fx.Archive.Archive.RootPath, (await fx.Db.Renders.GetAsync(entry.RenderId, fx.Ct))!.OutputPath))!;
|
||||
Assert.Equal(1, Directory.GetFiles(exports).Length);
|
||||
|
||||
// A send with nothing unsent is done at once.
|
||||
var nothing = await SendAsync(fx, engine, store, project.ProjectId, JobState.Done);
|
||||
Assert.Contains(Loc.L("Archive.Log.WorkspaceSent", project.ReadBundle().Workspace!.Name, 0, 0), nothing.LogTail);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnImageSequenceIsFiledWholeAndCheckedByItsListing()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var engine = await EngineAsync(fx);
|
||||
var (store, _, project) = await CheckoutAsync(fx);
|
||||
var folder = Path.Combine(project.ExportsDirectory, "Main frames");
|
||||
Directory.CreateDirectory(folder);
|
||||
for (var i = 0; i < 3; i++) File.WriteAllText(Path.Combine(folder, $"frame-{i:D4}.png"), "frame " + i);
|
||||
var size = Directory.GetFiles(folder).Sum(f => new FileInfo(f).Length);
|
||||
var entry = new WorkspaceRenderEntry(Guid.CreateVersion7(), Guid.CreateVersion7(), "Main frames", await WorkspaceRenderJobHandler.HashAsync(folder), size,
|
||||
"PNG frames", "png", 96, 64, 24, 0.125, project.ProjectId, null, null, Rendered);
|
||||
project.WriteRenders(project.ReadRenders().With(entry));
|
||||
|
||||
await SendAsync(fx, engine, store, project.ProjectId, JobState.Done);
|
||||
|
||||
var row = Assert.NotNull(await fx.Db.Renders.GetAsync(entry.RenderId, fx.Ct));
|
||||
Assert.Equal((size, (Guid?)project.ProjectId), (row.Bytes, row.ProjectId));
|
||||
var filed = Path.Combine(fx.Archive.Archive.RootPath, row.OutputPath);
|
||||
Assert.True(Directory.Exists(filed), filed);
|
||||
Assert.Equal(entry.Sha256, await WorkspaceRenderJobHandler.HashAsync(filed));
|
||||
Assert.True(project.ReadRenders().Find(entry.RenderId)!.IsSent);
|
||||
Assert.Empty(Directory.GetFileSystemEntries(fx.Archive.Paths.StagingDirectory, "workspace-render-*"));
|
||||
|
||||
// A frame changed after the render: refused, the folder left where it is.
|
||||
var changed = entry with { RenderId = Guid.CreateVersion7(), File = "Changed frames" };
|
||||
Directory.CreateDirectory(project.ExportFile(changed.File));
|
||||
foreach (var file in Directory.GetFiles(folder)) File.Copy(file, Path.Combine(project.ExportFile(changed.File), Path.GetFileName(file)));
|
||||
File.WriteAllText(Path.Combine(project.ExportFile(changed.File), "frame-0001.png"), "frame X");
|
||||
project.WriteRenders(project.ReadRenders().With(changed with { State = WorkspaceRenderEntry.Pending, Sent = null }));
|
||||
var failed = await SendAsync(fx, engine, store, project.ProjectId, JobState.Failed);
|
||||
Assert.Contains(Loc.L("Errors.Workspace.SendHashMismatch", "Changed frames"), failed.LogTail);
|
||||
Assert.Null(await fx.Db.Renders.GetAsync(changed.RenderId, fx.Ct));
|
||||
Assert.True(Directory.Exists(project.ExportFile(changed.File)), "the folder stays in the workspace");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AVersionTheHomeLacksIsSentFirst()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var engine = await EngineAsync(fx);
|
||||
// With its media: a version is saved only of frames the workspace holds.
|
||||
var (store, sync) = fx.Workspace();
|
||||
var project = await fx.CheckoutAsync(sync);
|
||||
var session = await sync.OpenAsync(project.ProjectId, fx.Ct);
|
||||
await sync.SaveAsync(project.ProjectId, session.Working with { HeroFrame = 2 }, fx.Ct);
|
||||
var local = Assert.NotNull(await sync.CommitAsync(project.ProjectId, "Render", cancellationToken: fx.Ct));
|
||||
Assert.Null(await fx.Home.GetVersionAsync(project.ProjectId, local.Id, fx.Ct));
|
||||
var entry = Render(project, local.Id, "Hero.mp4", 3);
|
||||
|
||||
var job = await SendAsync(fx, engine, store, project.ProjectId, JobState.Done);
|
||||
|
||||
var pushed = Assert.NotNull(await fx.Home.GetVersionAsync(project.ProjectId, local.Id, fx.Ct));
|
||||
Assert.Contains(Loc.L("Archive.Log.WorkspaceVersionPushed", project.ReadBundle().Workspace!.Name, pushed.Number), job.LogTail);
|
||||
Assert.Equal((Guid?)local.Id, (await fx.Db.Renders.GetAsync(entry.RenderId, fx.Ct))!.ProjectVersionId);
|
||||
Assert.Equal(WorkspaceState.InSync, (await sync.StatusAsync(project.ProjectId, fx.Home, fx.Ct)).State);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AChangedOrMissingRenderIsRefusedAndTheOthersGoOn()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var engine = await EngineAsync(fx);
|
||||
var (store, _, project) = await CheckoutAsync(fx);
|
||||
var head = project.ReadBundle().Workspace!.Base!.VersionId;
|
||||
var changed = Render(project, head, "Changed.mp4", 4);
|
||||
var gone = Render(project, head, "Gone.mp4", 5);
|
||||
var good = Render(project, head, "Good.mp4", 6);
|
||||
var original = File.ReadAllBytes(project.ExportFile(changed.File));
|
||||
File.AppendAllText(project.ExportFile(changed.File), "edited");
|
||||
File.Delete(project.ExportFile(gone.File));
|
||||
|
||||
var failed = await SendAsync(fx, engine, store, project.ProjectId, JobState.Failed);
|
||||
|
||||
Assert.Equal(Loc.L("Errors.Workspace.SendFailed", 2, 3), failed.Error);
|
||||
var ledger = project.ReadRenders();
|
||||
Assert.True(ledger.Find(good.RenderId)!.IsSent);
|
||||
Assert.Equal((WorkspaceRenderEntry.Failed, Loc.L("Errors.Workspace.SendHashMismatch", "Changed.mp4")),
|
||||
(ledger.Find(changed.RenderId)!.State, ledger.Find(changed.RenderId)!.Error));
|
||||
Assert.Equal((WorkspaceRenderEntry.Failed, Loc.L("Errors.Workspace.SendMissing", "Gone.mp4")),
|
||||
(ledger.Find(gone.RenderId)!.State, ledger.Find(gone.RenderId)!.Error));
|
||||
Assert.Null(await fx.Db.Renders.GetAsync(changed.RenderId, fx.Ct));
|
||||
Assert.Null(await fx.Db.Renders.GetAsync(gone.RenderId, fx.Ct));
|
||||
// The changed file stays in the workspace as it is.
|
||||
Assert.FileExists(project.ExportFile(changed.File));
|
||||
|
||||
// Put back as rendered (and the missing one discarded), the next send takes it.
|
||||
File.WriteAllBytes(project.ExportFile(changed.File), original);
|
||||
project.WriteRenders(project.ReadRenders().Without(gone.RenderId));
|
||||
await SendAsync(fx, engine, store, project.ProjectId, JobState.Done);
|
||||
Assert.True(project.ReadRenders().Find(changed.RenderId)!.IsSent);
|
||||
Assert.Equal(2, (await fx.Db.Renders.ListBySequenceAsync(fx.Sequence.Id, fx.Ct)).Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AVersionOfAnotherProjectIsNeverFiledWithTheRender()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var engine = await EngineAsync(fx);
|
||||
var (store, _, project) = await CheckoutAsync(fx);
|
||||
var other = await fx.Home.CreateAsync("Vertical", null, null, fx.Ct);
|
||||
var foreign = (await fx.Home.HeadAsync(other.Id, fx.Ct)).Id;
|
||||
var entry = Render(project, foreign, "Foreign.mp4", 7);
|
||||
|
||||
var job = await SendAsync(fx, engine, store, project.ProjectId, JobState.Done);
|
||||
|
||||
// The project's home holds no such version of this project: the render goes with its project alone.
|
||||
Assert.Contains(Loc.L("Archive.Log.WorkspaceVersionNotHome", project.ReadBundle().Workspace!.Name), job.LogTail!);
|
||||
var row = Assert.NotNull(await fx.Db.Renders.GetAsync(entry.RenderId, fx.Ct));
|
||||
Assert.Equal(((Guid?)project.ProjectId, (Guid?)null), (row.ProjectId, row.ProjectVersionId));
|
||||
Assert.True(project.ReadRenders().Find(entry.RenderId)!.IsSent);
|
||||
Assert.Null(project.ReadRenders().Find(entry.RenderId)!.ProjectVersionId);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AVersionTheHomeHoldsByAnotherIdIsFiledByThatId()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var engine = await EngineAsync(fx);
|
||||
var (store, _, project) = await CheckoutAsync(fx);
|
||||
// A version a push replayed on a home that moved on: the home holds its content under another id.
|
||||
var head = await fx.Home.HeadAsync(project.ProjectId, fx.Ct);
|
||||
var entry = Render(project, Guid.CreateVersion7(), "Replayed.mp4", 11, head.ContentHash);
|
||||
|
||||
var job = await SendAsync(fx, engine, store, project.ProjectId, JobState.Done);
|
||||
|
||||
Assert.Contains(Loc.L("Archive.Log.WorkspaceVersionReplayed", project.ReadBundle().Workspace!.Name, head.Number), job.LogTail!);
|
||||
var row = Assert.NotNull(await fx.Db.Renders.GetAsync(entry.RenderId, fx.Ct));
|
||||
Assert.Equal(((Guid?)project.ProjectId, (Guid?)head.Id), (row.ProjectId, row.ProjectVersionId));
|
||||
// The ledger names the home's id from now on.
|
||||
var sent = Assert.NotNull(project.ReadRenders().Find(entry.RenderId));
|
||||
Assert.Equal(((Guid?)head.Id, true), (sent.ProjectVersionId, sent.IsSent));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ALedgerNamingAFileOutsideTheExportsIsRefused()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var engine = await EngineAsync(fx);
|
||||
var (store, _, project) = await CheckoutAsync(fx);
|
||||
// A ledger edited by hand (or a newer Chronos's) naming the working state: never read, never sent.
|
||||
var entry = Render(project, null, "Outside.mp4", 12) with { File = Path.Combine("..", WorkspaceProject.BundleFile) };
|
||||
project.WriteRenders(project.ReadRenders().Without(entry.RenderId).With(entry));
|
||||
|
||||
var failed = await SendAsync(fx, engine, store, project.ProjectId, JobState.Failed);
|
||||
|
||||
Assert.Equal(Loc.L("Errors.Workspace.SendFailed", 1, 1), failed.Error);
|
||||
Assert.Null(await fx.Db.Renders.GetAsync(entry.RenderId, fx.Ct));
|
||||
Assert.Equal((WorkspaceRenderEntry.Failed, Loc.L("Errors.Workspace.SendMissing", WorkspaceProject.BundleFile)),
|
||||
(project.ReadRenders().Find(entry.RenderId)!.State, project.ReadRenders().Find(entry.RenderId)!.Error));
|
||||
Assert.FileExists(project.BundlePath);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ASendToThisPcsLibraryIsNeverHeldOnAMeteredConnection()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var engine = await EngineAsync(fx, hold: () => true);
|
||||
var (store, _, project) = await CheckoutAsync(fx);
|
||||
var entry = Render(project, null, "Working.mp4", 8);
|
||||
|
||||
var job = await SendAsync(fx, engine, store, project.ProjectId, JobState.Done);
|
||||
|
||||
Assert.False(job.LogTail?.Contains(Loc.L("Archive.Log.WorkspaceSendHeld"), StringComparison.Ordinal) ?? false);
|
||||
var row = Assert.NotNull(await fx.Db.Renders.GetAsync(entry.RenderId, fx.Ct));
|
||||
Assert.Equal(((Guid?)project.ProjectId, (Guid?)null), (row.ProjectId, row.ProjectVersionId));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SqliteWorkspaceSendTests(TestContext context) : WorkspaceSendTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.SqliteFile;
|
||||
}
|
||||
|
||||
[RequiresEnvironment(PgTestServer.Variable)]
|
||||
public sealed class PostgresWorkspaceSendTests(TestContext context) : WorkspaceSendTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.Postgres;
|
||||
}
|
||||
@@ -192,14 +192,17 @@ public abstract class WorkspaceTests(TestContext context) : DatabaseTest(context
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CopyingTheOriginalsIsRefusedForNowWithItsReason()
|
||||
public async Task CopyingTheOriginalsCopiesTheProxiesToo()
|
||||
{
|
||||
var fx = await FixtureAsync(2);
|
||||
var (store, sync) = fx.Workspace();
|
||||
var main = await fx.Archive.Service.Projects.MainAsync(fx.Sequence.Id, fx.Ct);
|
||||
await sync.CheckoutAsync(fx.Home, main.Id, BundleMedia.Originals, fx.Ct);
|
||||
var job = await fx.CopyAsync(store, main.Id, JobState.Failed, media: BundleMedia.Originals);
|
||||
Assert.Equal(Loc.L("Errors.Workspace.OriginalsLater"), job.Error);
|
||||
var project = await sync.CheckoutAsync(fx.Home, main.Id, BundleMedia.Originals, fx.Ct);
|
||||
await fx.CopyAsync(store, main.Id, media: BundleMedia.Originals);
|
||||
var media = project.ReadMedia()!;
|
||||
Assert.True(media.HoldsOriginals);
|
||||
Assert.True(media.Frames.All(f => f.HasOriginal), "every frame has its original");
|
||||
Assert.Equal(media.Frames.Count, (await sync.OpenAsync(main.Id, fx.Ct)).Media!.Frames.Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
|
||||
@@ -341,6 +341,25 @@ public sealed class UploadTests(TestContext context)
|
||||
Assert.Equal("cancelled", (await state.ReadAsync(ProtocolJson.Default.UploadState)).State);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ARenderOfferOfAnEarlierClientReadsWithoutItsProjectAndAWorkspaceOneKeepsIt()
|
||||
{
|
||||
// As a client of phase 5b sends it: no project, no version.
|
||||
var earlier = System.Text.Json.JsonSerializer.Deserialize("""
|
||||
{ "renderId": "0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01", "fileName": "Roof.mp4", "size": 10, "sha256": "ab", "presetName": "4K HEVC",
|
||||
"codec": "hevc", "width": 3840, "height": 2160, "fps": 30, "durationSeconds": 10 }
|
||||
""", ProtocolJson.Default.RenderUploadRequest);
|
||||
Assert.NotNull(earlier);
|
||||
Assert.Equal(("Roof.mp4", (Guid?)null, (Guid?)null), (earlier.FileName, earlier.ProjectId, earlier.ProjectVersionId));
|
||||
var omitted = System.Text.Json.JsonSerializer.Serialize(earlier, ProtocolJson.Default.RenderUploadRequest);
|
||||
Assert.False(omitted.Contains("projectId", StringComparison.Ordinal), "an offer without a project names none");
|
||||
|
||||
var workspace = earlier with { ProjectId = Guid.CreateVersion7(), ProjectVersionId = Guid.CreateVersion7() };
|
||||
var json = System.Text.Json.JsonSerializer.Serialize(workspace, ProtocolJson.Default.RenderUploadRequest);
|
||||
Assert.Contains("\"projectVersionId\"", json);
|
||||
Assert.Equal(workspace, System.Text.Json.JsonSerializer.Deserialize(json, ProtocolJson.Default.RenderUploadRequest));
|
||||
}
|
||||
|
||||
/// <summary>Reports synchronously (Progress<T> posts to the thread pool and may arrive late).</summary>
|
||||
private sealed class SyncProgress<T>(Action<T> report) : IProgress<T>
|
||||
{
|
||||
|
||||
@@ -184,6 +184,36 @@ public sealed class ServerWorkspaceTests(TestContext context)
|
||||
static int Downloaded(WorkspaceMedia media, Range frames) => media.Frames.Take(frames).Count(f => f.FileKind == "proxy");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ACopyFromTheServerWaitsWhileTheConnectionIsMetered()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (_, _, token) = await server.UserAsync("alberto", "editor");
|
||||
var sid = await SequenceAsync(server, token, 2);
|
||||
var metered = true;
|
||||
var asked = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
await using var a = await WorkspaceClient.StartAsync(context, server, token, "PC-A", hold: () =>
|
||||
{
|
||||
var held = Volatile.Read(ref metered);
|
||||
if (held) asked.TrySetResult();
|
||||
return held;
|
||||
});
|
||||
var home = a.Home(sid);
|
||||
var main = (await home.ListAsync(context.Cancellation)).Single();
|
||||
var project = await a.Sync.CheckoutAsync(home, main.Id, cancellationToken: context.Cancellation);
|
||||
|
||||
// Held before anything is downloaded.
|
||||
var job = await a.EnqueueAsync(WorkspaceJobs.CopyFromServer(sid, Title, a.Server, a.Store.Root, main.Id));
|
||||
await asked.Task.WaitAsync(Wait, context.Cancellation);
|
||||
Assert.Equal(JobState.Running, (await a.Db.Jobs.GetAsync(job.Id, context.Cancellation))!.State);
|
||||
Assert.False(Directory.Exists(project.ProxiesDirectory) && Directory.EnumerateFiles(project.ProxiesDirectory).Any(), "nothing downloaded while metered");
|
||||
|
||||
Volatile.Write(ref metered, false);
|
||||
var done = await a.WaitAsync(job.Id, JobState.Done);
|
||||
Assert.Contains(Loc.L("Archive.Log.WorkspaceCopyHeld"), done.LogTail!);
|
||||
Assert.Equal(2, Assert.NotNull(project.ReadMedia()).Frames.Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ACopyIsRefusedForAnotherHomeOrWithoutTheServer()
|
||||
{
|
||||
@@ -197,14 +227,45 @@ public sealed class ServerWorkspaceTests(TestContext context)
|
||||
// Another server's job for this project, or this server's for another sequence: refused, nothing downloaded.
|
||||
var other = await a.EnqueueAsync(WorkspaceJobs.CopyFromServer(sid, Title, "https://elsewhere:8443", a.Store.Root, main.Id));
|
||||
Assert.Equal(Loc.L("Errors.Workspace.OtherHome"), (await a.WaitAsync(other.Id, JobState.Failed)).Error);
|
||||
var originals = await a.EnqueueAsync(WorkspaceJobs.CopyFromServer(sid, Title, a.Server, a.Store.Root, main.Id, BundleMedia.Originals));
|
||||
Assert.Equal(Loc.L("Errors.Workspace.OriginalsLater"), (await a.WaitAsync(originals.Id, JobState.Failed)).Error);
|
||||
a.Connected = false;
|
||||
var signedOut = await a.EnqueueAsync(WorkspaceJobs.CopyFromServer(sid, Title, a.Server, a.Store.Root, main.Id));
|
||||
Assert.Equal(Loc.L("Errors.Sync.NotConnected"), (await a.WaitAsync(signedOut.Id, JobState.Failed)).Error);
|
||||
Assert.Null(a.Store.Find(main.Id)!.ReadMedia());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheOriginalsAreDownloadedCheckedAndKeptBesideTheProxies()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (_, _, token) = await server.UserAsync("alberto", "editor");
|
||||
var sid = await SequenceAsync(server, token, 3);
|
||||
await using var a = await WorkspaceClient.StartAsync(context, server, token, "PC-A");
|
||||
var home = a.Home(sid);
|
||||
var main = (await home.ListAsync(context.Cancellation)).Single();
|
||||
var project = await a.Sync.CheckoutAsync(home, main.Id, BundleMedia.Originals, context.Cancellation);
|
||||
var library = Listing(a.Archive.RootPath);
|
||||
|
||||
var job = await a.EnqueueAsync(WorkspaceJobs.CopyFromServer(sid, Title, a.Server, a.Store.Root, main.Id, BundleMedia.Originals));
|
||||
job = await a.WaitAsync(job.Id, JobState.Done);
|
||||
Assert.Contains(Loc.L("Archive.Log.WorkspaceOriginalsDownloaded", Title, 3, 0, 0), job.LogTail!);
|
||||
var media = Assert.NotNull(project.ReadMedia());
|
||||
Assert.True(media.HoldsOriginals);
|
||||
Assert.Equal(BundleMedia.Originals, project.ReadBundle().Workspace!.Media.Kind);
|
||||
var manifest = await a.Client.GetManifestAsync(sid, context.Cancellation);
|
||||
foreach (var (frame, entry) in manifest.Frames.OrderBy(f => f.Index).Zip(media.Frames))
|
||||
{
|
||||
Assert.Equal(frame.Sha256.ToLowerInvariant(), entry.OriginalSha256);
|
||||
Assert.Equal(entry.OriginalSha256, Sha(project.MediaFile(Assert.NotNull(entry.Original))));
|
||||
Assert.NotNull(entry.File);
|
||||
}
|
||||
Assert.False(Directory.Exists(Path.Combine(project.OriginalsDirectory, ".staging")));
|
||||
Assert.SequenceEqual(library, Listing(a.Archive.RootPath), "this PC's library is as it was");
|
||||
|
||||
// Again: every original held is kept, hashed again.
|
||||
job = await a.WaitAsync((await a.EnqueueAsync(WorkspaceJobs.CopyFromServer(sid, Title, a.Server, a.Store.Root, main.Id, BundleMedia.Originals))).Id, JobState.Done);
|
||||
Assert.Contains(Loc.L("Archive.Log.WorkspaceOriginalsDownloaded", Title, 0, 3, 0), job.LogTail!);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AProjectDeletedOnTheServerIsGoneAndItsCopyStays()
|
||||
{
|
||||
@@ -498,7 +559,8 @@ public sealed class ServerWorkspaceTests(TestContext context)
|
||||
/// <summary>Whether the copy job finds this PC signed in to the server.</summary>
|
||||
public bool Connected { get; set; } = true;
|
||||
|
||||
public static async Task<WorkspaceClient> StartAsync(TestContext context, TestServer server, string token, string name, HttpMessageHandler? handler = null)
|
||||
public static async Task<WorkspaceClient> StartAsync(TestContext context, TestServer server, string token, string name, HttpMessageHandler? handler = null,
|
||||
Func<bool>? hold = null)
|
||||
{
|
||||
var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory(name + "-db"), "chronos.db")), context.Cancellation);
|
||||
var archives = new ArchiveService(db, new ArchiveServiceOptions { Owner = name });
|
||||
@@ -506,7 +568,8 @@ public sealed class ServerWorkspaceTests(TestContext context)
|
||||
var archive = await archives.CreateAsync(context.CreateTempDirectory(name + "-archive"), "Local", cancellationToken: context.Cancellation);
|
||||
var client = new ChronosClient(server.HttpBase, new CertificatePinning([]), name, handler) { Token = token };
|
||||
WorkspaceClient? created = null;
|
||||
var engine = new JobEngine(db, WorkspaceJobs.CreateHandlers(db, archives, new Connector(client, () => created?.Connected ?? true)),
|
||||
var options = hold is null ? WorkspaceJobOptions.For(archives) : WorkspaceJobOptions.For(archives) with { HoldTransfers = hold };
|
||||
var engine = new JobEngine(db, WorkspaceJobs.CreateHandlers(db, archives, new Connector(client, () => created?.Connected ?? true), options),
|
||||
new JobEngineOptions { Workers = 1, WorkerId = name, PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
|
||||
await engine.StartAsync(context.Cancellation);
|
||||
var store = new WorkspaceStore(Path.Combine(context.CreateTempDirectory(name + "-ws"), "workspace"));
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
using System.Net;
|
||||
using System.Security.Cryptography;
|
||||
using Chronos.Core.Codecs.Jpeg;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Protocol.Client;
|
||||
using Chronos.Server.Storage;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Workspaces;
|
||||
|
||||
/// <summary>
|
||||
/// A render made in a workspace and sent to its server (phase 5c): the server checks the project and version it names
|
||||
/// against the sequence (422 <c>project_mismatch</c>) and records them with the render; one naming neither is filed as
|
||||
/// before. The desktop's <see cref="JobKind.WorkspaceSend"/> uploads it with them, and waits while a metered connection holds
|
||||
/// transfers with the server.
|
||||
/// </summary>
|
||||
[Category("server")]
|
||||
[Category("workspace")]
|
||||
public sealed class WorkspaceSendServerTests(TestContext context)
|
||||
{
|
||||
private const string Title = "Rooftop";
|
||||
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(TestTiming.Budget(60));
|
||||
|
||||
[Test]
|
||||
public async Task TheServerFilesAWorkspaceRenderWithItsProjectAndVersion()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (http, _, token) = await server.UserAsync("alberto", "editor");
|
||||
var sid = (await Uploads.UploadAsync(http, Photo(1), "IMG_0001.JPG", sessionKey: "roof")).SequenceId;
|
||||
using var client = new ChronosClient(server.HttpBase, new CertificatePinning([]), "PC-A") { Token = token };
|
||||
var home = new ServerProjectHome(client, sid, "Test server");
|
||||
var main = (await home.ListAsync(context.Cancellation)).Single();
|
||||
var head = await home.HeadAsync(main.Id, context.Cancellation);
|
||||
|
||||
var (path, request) = Output(1);
|
||||
var dto = Assert.NotNull(await client.UploadRenderAsync(sid, path, request with { ProjectId = main.Id, ProjectVersionId = head.Id }, ct: context.Cancellation));
|
||||
Assert.Equal(((Guid?)main.Id, (Guid?)head.Id), (dto.ProjectId, dto.ProjectVersionId));
|
||||
var row = Assert.NotNull(await server.Database.Renders.GetAsync(request.RenderId));
|
||||
Assert.Equal((sid, (Guid?)main.Id, (Guid?)head.Id), (row.SequenceId, row.ProjectId, row.ProjectVersionId));
|
||||
Assert.Contains((await client.GetManifestAsync(sid, context.Cancellation)).Renders, r => r.Id == request.RenderId && r.ProjectVersionId == head.Id);
|
||||
|
||||
// A version alone names its project.
|
||||
var (alone, versionOnly) = Output(2);
|
||||
var named = Assert.NotNull(await client.UploadRenderAsync(sid, alone, versionOnly with { ProjectVersionId = head.Id }, ct: context.Cancellation));
|
||||
Assert.Equal(((Guid?)main.Id, (Guid?)head.Id), (named.ProjectId, named.ProjectVersionId));
|
||||
|
||||
// Sent again: the server holds it already, and nothing is filed twice.
|
||||
Assert.Null(await client.UploadRenderAsync(sid, path, request with { ProjectId = main.Id, ProjectVersionId = head.Id }, ct: context.Cancellation));
|
||||
Assert.Equal(2, (await server.Database.Renders.ListBySequenceAsync(sid)).Count);
|
||||
|
||||
// Without them, as from an earlier client: filed naming neither.
|
||||
var (plain, earlier) = Output(3);
|
||||
var before = Assert.NotNull(await client.UploadRenderAsync(sid, plain, earlier, ct: context.Cancellation));
|
||||
Assert.Equal(((Guid?)null, (Guid?)null), (before.ProjectId, before.ProjectVersionId));
|
||||
Assert.Null((await server.Database.Renders.GetAsync(earlier.RenderId))!.ProjectVersionId);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AProjectOrVersionOfAnotherSequenceIsRefused()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (http, _, token) = await server.UserAsync("alberto", "editor");
|
||||
var sid = (await Uploads.UploadAsync(http, Photo(1), "IMG_0001.JPG", sessionKey: "roof")).SequenceId;
|
||||
var other = (await Uploads.UploadAsync(http, Photo(2), "IMG_0002.JPG", sessionKey: "lake", capturedAt: new DateTime(2026, 10, 3, 9, 0, 0))).SequenceId;
|
||||
Assert.NotEqual(sid, other);
|
||||
using var client = new ChronosClient(server.HttpBase, new CertificatePinning([]), "PC-A") { Token = token };
|
||||
var main = (await new ServerProjectHome(client, sid).ListAsync(context.Cancellation)).Single();
|
||||
var foreignHome = new ServerProjectHome(client, other);
|
||||
var foreign = (await foreignHome.ListAsync(context.Cancellation)).Single();
|
||||
var foreignHead = await foreignHome.HeadAsync(foreign.Id, context.Cancellation);
|
||||
|
||||
var (path, request) = Output(4);
|
||||
foreach (var named in new[]
|
||||
{
|
||||
request with { ProjectId = main.Id, ProjectVersionId = foreignHead.Id },
|
||||
request with { ProjectId = foreign.Id },
|
||||
request with { ProjectVersionId = foreignHead.Id },
|
||||
request with { ProjectId = Guid.CreateVersion7() },
|
||||
})
|
||||
{
|
||||
var refused = await Assert.ThrowsAsync<ChronosApiException>(() => client.UploadRenderAsync(sid, path, named, ct: context.Cancellation));
|
||||
Assert.Equal((HttpStatusCode.UnprocessableEntity, "project_mismatch"), (refused.Status, refused.Error.Code));
|
||||
}
|
||||
Assert.Null(await server.Database.Renders.GetAsync(request.RenderId));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheSendUploadsTheRenderWithItsVersionOnceTheConnectionIsNoLongerMetered()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (http, _, token) = await server.UserAsync("alberto", "editor");
|
||||
var sid = (await Uploads.UploadAsync(http, Photo(1), "IMG_0001.JPG", sessionKey: "roof")).SequenceId;
|
||||
using var client = new ChronosClient(server.HttpBase, new CertificatePinning([]), "PC-A") { Token = token };
|
||||
var serverKey = SyncService.ServerKey(client.BaseAddress);
|
||||
await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory("pc-db"), "chronos.db")), context.Cancellation);
|
||||
var archives = new ArchiveService(db, new ArchiveServiceOptions { Owner = "PC-A" });
|
||||
var metered = true;
|
||||
// Signalled once the send asks: from then on it waits, and nothing it holds went out.
|
||||
var asked = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var options = WorkspaceJobOptions.For(archives) with
|
||||
{
|
||||
HoldTransfers = () =>
|
||||
{
|
||||
var held = Volatile.Read(ref metered);
|
||||
if (held) asked.TrySetResult();
|
||||
return held;
|
||||
},
|
||||
};
|
||||
await using var engine = new JobEngine(db, WorkspaceJobs.CreateHandlers(db, archives, new Connector(client), options),
|
||||
new JobEngineOptions { Workers = 1, WorkerId = "PC-A", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
|
||||
await engine.StartAsync(context.Cancellation);
|
||||
var store = new WorkspaceStore(Path.Combine(context.CreateTempDirectory("pc-ws"), "workspace"));
|
||||
var sync = new WorkspaceSync(store, "Chronos on PC-A") { LockWait = TimeSpan.FromSeconds(TestTiming.Budget(10)) };
|
||||
var home = new ServerProjectHome(client, sid, "Test server");
|
||||
var main = (await home.ListAsync(context.Cancellation)).Single();
|
||||
var project = await sync.CheckoutAsync(home, main.Id, cancellationToken: context.Cancellation);
|
||||
var head = project.ReadBundle().Workspace!.Base!.VersionId;
|
||||
|
||||
Directory.CreateDirectory(project.ExportsDirectory);
|
||||
var bytes = RandomNumberGenerator.GetBytes(120_000);
|
||||
File.WriteAllBytes(Path.Combine(project.ExportsDirectory, "Roof 1080p.mp4"), bytes);
|
||||
var entry = new WorkspaceRenderEntry(Guid.CreateVersion7(), Guid.CreateVersion7(), "Roof 1080p.mp4", Convert.ToHexStringLower(SHA256.HashData(bytes)),
|
||||
bytes.Length, "1080p H.264", "h264", 1920, 1080, 24, 2.5, main.Id, head, null, DateTimeOffset.UtcNow);
|
||||
project.WriteRenders(WorkspaceRenders.Empty.With(entry));
|
||||
|
||||
// Held while the connection is metered: nothing goes out.
|
||||
var job = await engine.EnqueueAsync(WorkspaceJobs.Send(sid, Title, store.Root, main.Id, [entry.RenderId], serverKey), cancellationToken: context.Cancellation);
|
||||
await asked.Task.WaitAsync(Wait, context.Cancellation);
|
||||
Assert.Equal(JobState.Running, (await db.Jobs.GetAsync(job.Id, context.Cancellation))!.State);
|
||||
Assert.Null(await server.Database.Renders.GetAsync(entry.RenderId));
|
||||
Assert.True(project.ReadRenders().Find(entry.RenderId)!.IsUnsent);
|
||||
|
||||
Volatile.Write(ref metered, false);
|
||||
var done = await WaitAsync(db, job.Id, JobState.Done);
|
||||
Assert.Contains(Loc.L("Archive.Log.WorkspaceSendHeld"), done.LogTail!);
|
||||
Assert.Contains(Loc.L("Archive.Log.WorkspaceSent", main.Name, 1, 0), done.LogTail!);
|
||||
var row = Assert.NotNull(await server.Database.Renders.GetAsync(entry.RenderId));
|
||||
Assert.Equal((sid, (Guid?)main.Id, (Guid?)head, entry.Size), (row.SequenceId, row.ProjectId, row.ProjectVersionId, row.Bytes));
|
||||
Assert.True(project.ReadRenders().Find(entry.RenderId)!.IsSent);
|
||||
Assert.FileExists(project.ExportFile(entry.File));
|
||||
// This PC's library is never written: the server is the home.
|
||||
Assert.Empty(await db.Renders.ListBySequenceAsync(sid, context.Cancellation));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnImageSequenceRenderedHereStaysInTheWorkspaceForAServerHome()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (http, _, token) = await server.UserAsync("alberto", "editor");
|
||||
var sid = (await Uploads.UploadAsync(http, Photo(1), "IMG_0001.JPG", sessionKey: "roof")).SequenceId;
|
||||
using var client = new ChronosClient(server.HttpBase, new CertificatePinning([]), "PC-A") { Token = token };
|
||||
await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory("pc-db"), "chronos.db")), context.Cancellation);
|
||||
var archives = new ArchiveService(db, new ArchiveServiceOptions { Owner = "PC-A" });
|
||||
await using var engine = new JobEngine(db, WorkspaceJobs.CreateHandlers(db, archives, new Connector(client), WorkspaceJobOptions.For(archives)),
|
||||
new JobEngineOptions { Workers = 1, WorkerId = "PC-A", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
|
||||
await engine.StartAsync(context.Cancellation);
|
||||
var store = new WorkspaceStore(Path.Combine(context.CreateTempDirectory("pc-ws"), "workspace"));
|
||||
var sync = new WorkspaceSync(store, "Chronos on PC-A") { LockWait = TimeSpan.FromSeconds(TestTiming.Budget(10)) };
|
||||
var home = new ServerProjectHome(client, sid, "Test server");
|
||||
var main = (await home.ListAsync(context.Cancellation)).Single();
|
||||
var project = await sync.CheckoutAsync(home, main.Id, cancellationToken: context.Cancellation);
|
||||
|
||||
// A TIFF sequence: a folder of frames, which a server's render (one file each) cannot take.
|
||||
var folder = Path.Combine(project.ExportsDirectory, "Roof frames");
|
||||
Directory.CreateDirectory(folder);
|
||||
for (var i = 1; i <= 3; i++) File.WriteAllBytes(Path.Combine(folder, $"{i:0000}.tif"), RandomNumberGenerator.GetBytes(4000));
|
||||
var entry = new WorkspaceRenderEntry(Guid.CreateVersion7(), Guid.CreateVersion7(), "Roof frames", new string('a', 64), 12_000, "TIFF sequence", "tiff",
|
||||
1920, 1080, 24, 0.125, main.Id, null, null, DateTimeOffset.UtcNow);
|
||||
project.WriteRenders(WorkspaceRenders.Empty.With(entry));
|
||||
|
||||
var job = await engine.EnqueueAsync(WorkspaceJobs.Send(sid, Title, store.Root, main.Id, [], SyncService.ServerKey(client.BaseAddress)),
|
||||
cancellationToken: context.Cancellation);
|
||||
var failed = await WaitAsync(db, job.Id, JobState.Failed);
|
||||
|
||||
Assert.Equal(Loc.L("Errors.Workspace.SendFailed", 1, 1), failed.Error);
|
||||
var kept = Assert.NotNull(project.ReadRenders().Find(entry.RenderId));
|
||||
Assert.Equal((WorkspaceRenderEntry.Failed, Loc.L("Errors.Workspace.SendSequence", "Roof frames")), (kept.State, kept.Error));
|
||||
Assert.Null(await server.Database.Renders.GetAsync(entry.RenderId));
|
||||
Assert.Equal(3, Directory.GetFiles(folder).Length);
|
||||
}
|
||||
|
||||
/// <summary>A render's file on this PC and the offer of it, naming no project.</summary>
|
||||
private (string Path, RenderUploadRequest Request) Output(int seed)
|
||||
{
|
||||
var data = Uploads.Photo(4000 + seed, seed);
|
||||
var path = System.IO.Path.Combine(context.CreateTempDirectory("render"), $"Roof {seed}.mp4");
|
||||
File.WriteAllBytes(path, data);
|
||||
return (path, new RenderUploadRequest(Guid.CreateVersion7(), System.IO.Path.GetFileName(path), data.Length, Uploads.Sha(data), "1080p H.264", "h264", 1920, 1080,
|
||||
24, 2.5, "PC-A"));
|
||||
}
|
||||
|
||||
private static async Task<Job> WaitAsync(ChronosDatabase db, Guid jobId, JobState state)
|
||||
{
|
||||
var until = DateTime.UtcNow + Wait;
|
||||
while (true)
|
||||
{
|
||||
var job = await db.Jobs.GetAsync(jobId);
|
||||
if (job?.State == state) return job;
|
||||
if (job?.State is JobState.Failed or JobState.Done or JobState.Cancelled) Assert.Fail($"Job ended {job.State}: {job.Error}\n{job.LogTail}");
|
||||
if (DateTime.UtcNow > until) Assert.Fail($"Job {jobId} did not reach {state} (now {job?.State})");
|
||||
await Task.Delay(25);
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] Photo(int seed)
|
||||
{
|
||||
const int width = 96, height = 64;
|
||||
var pixels = new byte[width * height * 3];
|
||||
for (var i = 0; i < pixels.Length; i++) pixels[i] = (byte)((i * 7 + seed * 31) % 251);
|
||||
return JpegEncoder.Encode(pixels, width, height, 3, new JpegEncodeOptions { Quality = 90 });
|
||||
}
|
||||
|
||||
/// <summary>The desktop's session with the test server: a remote and the project home over the signed-in client.</summary>
|
||||
private sealed class Connector(ChronosClient client) : ISyncConnector
|
||||
{
|
||||
public ValueTask<ISyncRemote?> ConnectAsync(string server, CancellationToken cancellationToken)
|
||||
{
|
||||
ISyncRemote remote = new ChronosSyncRemote(client, ownsClient: false);
|
||||
return ValueTask.FromResult<ISyncRemote?>(remote.Server == server ? remote : null);
|
||||
}
|
||||
|
||||
public IProjectHome? ProjectHome(BundleHome home) => new ServerProjectHome(client, home.SequenceId, "Test server");
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 77 KiB After Width: | Height: | Size: 81 KiB |
|
Before Width: | Height: | Size: 75 KiB After Width: | Height: | Size: 78 KiB |
|
Before Width: | Height: | Size: 61 KiB After Width: | Height: | Size: 67 KiB |
|
Before Width: | Height: | Size: 56 KiB After Width: | Height: | Size: 61 KiB |
|
Before Width: | Height: | Size: 73 KiB After Width: | Height: | Size: 74 KiB |
|
Before Width: | Height: | Size: 66 KiB After Width: | Height: | Size: 67 KiB |
|
Before Width: | Height: | Size: 45 KiB After Width: | Height: | Size: 60 KiB |
|
Before Width: | Height: | Size: 42 KiB After Width: | Height: | Size: 54 KiB |