Files
Chronos/tests/Chronos.Data.Tests/Workspaces/WorkspaceFoundationTests.cs
T
Alby96andClaude Opus 5.5 2e1c67f531 feat(workspace): lay the phase 5c foundation
Phase 5c (owner review 2, R8) is built by six packages in parallel. This
commit settles everything they share, so each one touches its own files:

- job kinds WorkspaceRender (21), WorkspaceSend (22) and WorkspaceMove (23)
  with their wire names, default priorities, notices and parameter records;
  their handlers are registered as skeletons that throw until their
  package lands
- WorkspaceJobOptions and a new CreateHandlers overload; the earlier ones
  stay and default the options
- originals in the media index (an index of phase 5b reads as proxies
  only), their file names, and the exports/renders.json ledger of local
  renders, written atomically
- the optional project and version of an uploaded render
- the workspace settings (size limit, default media, version on render,
  clean-up age, project to open) and when each project was opened, which
  Reset and Import keep and Export leaves out
- WorkspaceHost split into partial files, with stubs for usage, trash and
  the folder move, removal hooks for unsent renders and last originals,
  and a guard that holds work while the workspace moves
- every new string of the phase in English and Italian, with tooltips

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 15:05:09 +01:00

212 lines
13 KiB
C#

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"));
}
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);
}
}