fix(workspace): close the phase 5c review findings

Originals are now judged by their bytes, never by the media index: a removal
or clean-up hashes every file under media/originals and deletes it only when
the home holds that SHA-256; every other file, named or not, goes to the
workspace trash. Trash entries are filled under a staging name that Empty
never lists. A ledger can only name files inside exports/.

Jobs follow the workspace: a copy, render or send resolves the folder that
holds its project now (a moved workspace, a retry after a move) and waits
while a move has not switched yet. A clean-up failure after the switch is a
warning that keeps the journal for a later resume; entries that changed
since they were copied are kept, and a same-volume rename refused across
volumes falls back to copy and verify.

Sends map a replayed version by content hash, or go with the project only,
and note an old server that drops provenance. The media index (format 2) and
project file (format 3) refuse older readers while they hold originals.
Metered connections also hold sync downloads and server copies. The editor
gains Send again, the Settings page can resume a stopped move, the disabled
tooltips say why, and unused strings are pruned.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-04 17:32:48 +01:00
1 parent 09fcff4eb2
commit 2654683a12
125 files changed
+1618 -401

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(),
@@ -7,7 +7,7 @@ using Chronos.Testing;
namespace Chronos.App.Tests.Server;
/// <summary>
/// Which jobs "Pause metered transfers" holds (Server.html, phase 5c): uploads, and the workspace's copies from and renders
/// 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
@@ -42,9 +42,11 @@ public sealed class UploadHoldTests
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.WorkspaceCopy, JobKind.WorkspaceSend], UploadHold.Kinds);
Assert.SequenceEqual([JobKind.UploadCommit, JobKind.Download, JobKind.WorkspaceCopy, JobKind.WorkspaceSend], UploadHold.Kinds);
}
[Test]
@@ -53,7 +55,6 @@ public sealed class UploadHoldTests
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.Download)));
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")));
@@ -693,13 +693,61 @@ public sealed class SettingsLogicTests
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 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>? isMoving = null, Func<bool>? unfinished = null, Func<Task>? resume = null)
{
var settings = new AppSettings();
var saves = 0;
@@ -721,6 +769,8 @@ public sealed class SettingsLogicTests
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);
@@ -12,6 +12,7 @@ using Chronos.Data.Processing;
using Chronos.Data.Workspaces;
using Chronos.Protocol.Client;
using Chronos.Testing;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Tests.Workspace;
@@ -84,6 +85,81 @@ public sealed class WorkspaceLocalRenderTests(TestContext context)
}
}
[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()
{
@@ -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);
@@ -159,34 +159,46 @@ public abstract class WorkspaceCleanupTests(TestContext context) : DatabaseTest(
var fx = await FixtureAsync();
var (store, sync) = fx.Workspace();
var project = await fx.CheckoutAsync(sync);
// Originals of two frames: the first as the home holds it, the second of bytes the home no longer has.
// 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);
File.WriteAllText(project.MediaFile(held), "held original");
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 = 13 },
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.Skip(2),
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);
Assert.Equal(1, One(report.Cleaned).Trashed);
// 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);
Assert.Equal("last original", File.ReadAllText(Path.Combine(trash.Folder, entry.Name, WorkspaceProject.OriginalsFolder, Path.GetFileName(lost))));
Assert.Equal((1, "last original".Length), (entry.Files, entry.Bytes));
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]
@@ -214,7 +226,9 @@ public abstract class WorkspaceCleanupTests(TestContext context) : DatabaseTest(
// Once copied again: the oldest goes first, and one is enough this time.
await fx.CopyAsync(sync.Store, b.ProjectId);
await fx.CopyAsync(sync.Store, c.ProjectId);
report = await Cleaner(fx, sync).CleanAsync(new WorkspaceCleanOptions { SizeLimitBytes = total - 1, Opened = opened, Now = now }, fx.Ct);
// 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");
@@ -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>
@@ -98,6 +98,76 @@ public sealed class WorkspaceFoundationTests(TestContext context)
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);
@@ -334,6 +334,175 @@ public sealed class WorkspaceMoveTests(TestContext context)
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.
@@ -151,6 +151,51 @@ public abstract class WorkspaceOriginalsTests(TestContext context) : DatabaseTes
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()
{
@@ -94,7 +94,8 @@ public sealed class WorkspaceRenderTests(TestContext context)
// 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));
Assert.SequenceEqual([entry.RenderId], sent.RenderIds);
// 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));
@@ -47,14 +47,14 @@ public abstract class WorkspaceSendTests(TestContext context) : DatabaseTest(con
}
/// <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)
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, null, Rendered);
"1080p H.264", "h264", 1920, 1080, 24, 2.5, project.ProjectId, versionId, settingsHash, Rendered);
project.WriteRenders(project.ReadRenders().With(entry));
return entry;
}
@@ -221,12 +221,53 @@ public abstract class WorkspaceSendTests(TestContext context) : DatabaseTest(con
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.SendVersion"), failed.Error);
Assert.Equal(Loc.L("Errors.Workspace.SendFailed", 1, 1), failed.Error);
Assert.Null(await fx.Db.Renders.GetAsync(entry.RenderId, fx.Ct));
// Not the render's fault: it waits, unsent, for the next send.
Assert.Equal(WorkspaceRenderEntry.Pending, project.ReadRenders().Find(entry.RenderId)!.State);
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]
@@ -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()
{
@@ -529,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 });
@@ -537,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"));
@@ -104,7 +104,17 @@ public sealed class WorkspaceSendServerTests(TestContext context)
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;
var options = WorkspaceJobOptions.For(archives) with { HoldTransfers = () => Volatile.Read(ref metered) };
// 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);
@@ -124,7 +134,7 @@ public sealed class WorkspaceSendServerTests(TestContext context)
// 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 Task.Delay(TimeSpan.FromSeconds(1), 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);
@@ -141,6 +151,43 @@ public sealed class WorkspaceSendServerTests(TestContext context)
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)
{