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>
This commit was merged in pull request #18.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-11-04 20:03:52 +01:00
1 parent 81c303f484
commit db389a54f2
364 files changed
+17417 -595

No files matched your search

@@ -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]