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

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

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

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

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

No files matched your search

@@ -159,34 +159,46 @@ public abstract class WorkspaceCleanupTests(TestContext context) : DatabaseTest(
var fx = await FixtureAsync();
var (store, sync) = fx.Workspace();
var project = await fx.CheckoutAsync(sync);
// Originals of two frames: the first as the home holds it, the second of bytes the home no longer has.
// Originals of three frames: the first as the home holds it; the second of bytes the home no longer has; the third
// recorded with the home's hash, its bytes changed since (the index is no proof). And a file the index never named.
var media = project.ReadMedia()!;
var held = WorkspaceProject.OriginalName(media.Frames[0].Id, fx.Frames[0].Sha256!, ".jpg");
var lost = WorkspaceProject.OriginalName(media.Frames[1].Id, new string('f', 64), ".jpg");
var changed = WorkspaceProject.OriginalName(media.Frames[2].Id, fx.Frames[2].Sha256!, ".jpg");
Directory.CreateDirectory(project.OriginalsDirectory);
File.WriteAllText(project.MediaFile(held), "held original");
var heldBytes = File.ReadAllBytes(fx.Archive.Paths.FromRelative(fx.Frames[0].RelativePath));
File.WriteAllBytes(project.MediaFile(held), heldBytes);
File.WriteAllText(project.MediaFile(lost), "last original");
File.WriteAllText(project.MediaFile(changed), "edited since");
File.WriteAllText(Path.Combine(project.OriginalsDirectory, "stray.jpg"), "named by no index");
project.WriteMedia(media with
{
Kind = BundleMedia.Originals,
Frames =
[
media.Frames[0] with { Original = held, OriginalSha256 = fx.Frames[0].Sha256, OriginalBytes = 13 },
media.Frames[0] with { Original = held, OriginalSha256 = fx.Frames[0].Sha256, OriginalBytes = heldBytes.Length },
media.Frames[1] with { Original = lost, OriginalSha256 = new string('f', 64), OriginalBytes = 13 },
.. media.Frames.Skip(2),
media.Frames[2] with { Original = changed, OriginalSha256 = fx.Frames[2].Sha256, OriginalBytes = 12 },
.. media.Frames.Skip(3),
],
});
// The index alone names only the second as the last one.
Assert.SequenceEqual([media.Frames[1].Id], WorkspaceCleaner.LastOriginals(project.ReadMedia(), await fx.Home.FramesAsync(fx.Ct)).Select(f => f.Id));
var report = await Cleaner(fx, sync).CleanAsync(Aged(project.ProjectId), fx.Ct);
Assert.Equal(1, One(report.Cleaned).Trashed);
// Each file hashed now: only the one the home holds byte for byte went away.
Assert.Equal(3, One(report.Cleaned).Trashed);
Assert.False(Directory.Exists(project.OriginalsDirectory), "the originals folder went");
var trash = WorkspaceTrash.List(store.Root, fx.Ct);
var entry = One(trash.Entries);
Assert.True(entry.Name.StartsWith(project.ProjectId.ToString("N") + "-", StringComparison.Ordinal), entry.Name);
Assert.Equal("last original", File.ReadAllText(Path.Combine(trash.Folder, entry.Name, WorkspaceProject.OriginalsFolder, Path.GetFileName(lost))));
Assert.Equal((1, "last original".Length), (entry.Files, entry.Bytes));
var kept = Path.Combine(trash.Folder, entry.Name, WorkspaceProject.OriginalsFolder);
Assert.Equal("last original", File.ReadAllText(Path.Combine(kept, Path.GetFileName(lost))));
Assert.Equal("edited since", File.ReadAllText(Path.Combine(kept, Path.GetFileName(changed))));
Assert.Equal("named by no index", File.ReadAllText(Path.Combine(kept, "stray.jpg")));
Assert.False(File.Exists(Path.Combine(kept, Path.GetFileName(held))), "the home holds that one");
Assert.Equal((3, (long)("last original".Length + "edited since".Length + "named by no index".Length)), (entry.Files, entry.Bytes));
}
[Test]
@@ -214,7 +226,9 @@ public abstract class WorkspaceCleanupTests(TestContext context) : DatabaseTest(
// Once copied again: the oldest goes first, and one is enough this time.
await fx.CopyAsync(sync.Store, b.ProjectId);
await fx.CopyAsync(sync.Store, c.ProjectId);
report = await Cleaner(fx, sync).CleanAsync(new WorkspaceCleanOptions { SizeLimitBytes = total - 1, Opened = opened, Now = now }, fx.Ct);
// Measured again: a copy's timestamps may be a byte shorter or longer than the first copy's.
var again = new[] { main, b, c }.Sum(p => WorkspaceCleaner.Measure(p.Folder).Bytes);
report = await Cleaner(fx, sync).CleanAsync(new WorkspaceCleanOptions { SizeLimitBytes = again - 1, Opened = opened, Now = now }, fx.Ct);
Assert.SequenceEqual([main.ProjectId], report.Cleaned.Select(p => p.ProjectId));
Assert.Empty(report.Kept);
Assert.True(Directory.Exists(b.ProxiesDirectory) && Directory.Exists(c.ProxiesDirectory), "the others stay");
@@ -84,10 +84,10 @@ internal sealed class WorkspaceFixture : IAsyncDisposable
}
/// <summary>Queues a workspace copy job and returns at once, while it runs.</summary>
public async Task<Job> StartCopyAsync(WorkspaceStore store, Guid projectId)
public async Task<Job> StartCopyAsync(WorkspaceStore store, Guid projectId, string media = "proxies")
{
var engine = await EngineAsync();
return await engine.EnqueueAsync(WorkspaceJobs.Copy(Sequence, store.Root, projectId), cancellationToken: Ct);
return await engine.EnqueueAsync(WorkspaceJobs.Copy(Sequence, store.Root, projectId, media), cancellationToken: Ct);
}
/// <summary>Cancels a job, as the user does from the jobs list.</summary>
@@ -98,6 +98,76 @@ public sealed class WorkspaceFoundationTests(TestContext context)
Assert.Equal(Path.Combine(project.ExportsDirectory, "Roof 4K.mp4"), project.ExportFile("Roof 4K.mp4"));
}
[Test]
public void AMediaIndexHoldingOriginalsIsWrittenInAFormatAPhase5bChronosRefuses()
{
var store = new WorkspaceStore(Path.Combine(context.CreateTempDirectory("ws"), "workspace"));
var project = store.Project(Guid.CreateVersion7());
var sequenceId = Guid.CreateVersion7();
int Written() => JsonNode.Parse(File.ReadAllText(project.MediaIndexPath))!["formatVersion"]!.GetValue<int>();
// Proxies only: as phase 5b wrote it, which it reads.
project.WriteMedia(Media(sequenceId, BundleMedia.Proxies, Frame(sequenceId, 0)));
Assert.Equal(WorkspaceMedia.ProxiesFormatVersion, Written());
// Originals, or a frame holding one, or media the clean-up removed: format 2, which phase 5b refuses as newer
// rather than reading the frames' files as its proxies.
project.WriteMedia(Media(sequenceId, BundleMedia.Originals, Frame(sequenceId, 0)));
Assert.Equal(WorkspaceMedia.CurrentFormatVersion, Written());
var held = Frame(sequenceId, 0);
held = held with { Original = WorkspaceProject.OriginalName(held.Id, new string('c', 64), ".jpg"), OriginalSha256 = new string('c', 64), OriginalBytes = 9 };
project.WriteMedia(Media(sequenceId, BundleMedia.Proxies, held));
Assert.Equal(WorkspaceMedia.CurrentFormatVersion, Written());
project.WriteMedia(Media(sequenceId, BundleMedia.Proxies, Frame(sequenceId, 0)) with { Cleaned = T0 });
Assert.Equal(WorkspaceMedia.CurrentFormatVersion, Written());
Assert.True(Assert.NotNull(project.ReadMedia()).IsCleaned, "this Chronos reads its own format back");
Assert.Equal(2, WorkspaceMedia.CurrentFormatVersion);
}
[Test]
public void ALedgerNamesOnlyFilesInsideTheExports()
{
var store = new WorkspaceStore(Path.Combine(context.CreateTempDirectory("ws"), "workspace"));
var project = store.Project(Guid.CreateVersion7());
Assert.Equal(Path.GetFullPath(project.ExportFile("Roof 4K.mp4")), project.ContainedExportFile("Roof 4K.mp4"));
Assert.Equal(Path.GetFullPath(project.ExportFile(Path.Combine("Roof frames", "0001.tif"))), project.ContainedExportFile("Roof frames/0001.tif"));
foreach (var refused in new[]
{
null, "", " ", ".", "..", "../project.chronos", @"..\media.json", "a/../../x.mp4", "a//b.mp4", "./a.mp4", "/etc/passwd",
@"C:\Windows\win.ini", "C:x.mp4", @"\\server\share\x.mp4", WorkspaceProject.RendersFileName,
})
Assert.Null(project.ContainedExportFile(refused), refused ?? "null");
}
[Test]
public void ATrashEntryBeingFilledIsNeverListedAndTakesItsNameWhenWhole()
{
var root = Path.Combine(context.CreateTempDirectory("ws"), "workspace");
var projectId = Guid.CreateVersion7();
string staging;
using (var trash = WorkspaceTrash.Begin(root, projectId, T0.UtcDateTime))
{
staging = trash.Path;
Assert.True(Directory.Exists(staging));
File.WriteAllText(Path.Combine(staging, "half.jpg"), "half");
// Listed while it is being filled, an Empty… could erase what a removal is still moving there.
var listing = WorkspaceTrash.List(root);
Assert.True(listing.IsEmpty, string.Join(", ", listing.Entries.Select(e => e.Name)));
Assert.Equal((0, 0L), WorkspaceTrash.Empty(root, listing));
Assert.FileExists(Path.Combine(staging, "half.jpg"));
}
Assert.False(Directory.Exists(staging));
var entries = WorkspaceTrash.List(root).Entries;
Assert.Equal(1, entries.Count);
var entry = entries[0];
Assert.True(entry.Name.StartsWith(projectId.ToString("N") + "-", StringComparison.Ordinal), entry.Name);
Assert.Equal((1, 4L), (entry.Files, entry.Bytes));
// One that nothing came into leaves no entry.
using (var empty = WorkspaceTrash.Begin(root, projectId, T0.UtcDateTime))
Assert.True(Directory.Exists(empty.Path));
Assert.Equal(1, WorkspaceTrash.List(root).Entries.Count);
}
private static WorkspaceRenderEntry Entry(Guid projectId, string file) =>
new(Guid.CreateVersion7(), Guid.CreateVersion7(), file, new string('b', 64), 12_345, "4K HEVC", "hevc", 3840, 2160, 30, 10, projectId,
Guid.CreateVersion7(), "hash", T0);
@@ -334,6 +334,175 @@ public sealed class WorkspaceMoveTests(TestContext context)
Assert.False(Directory.Exists(to));
}
[Test]
public async Task TwoVolumesUnderOneFolderAreCopiedWhenTheFirstRenameIsRefused()
{
var (from, _) = Workspace(projects: 2);
var before = Contents(from);
var to = Path.Combine(context.CreateTempDirectory("target"), "moved");
var renames = 0;
var copied = 0;
var mover = new WorkspaceMover(from, to)
{
// Both under one drive letter, the target a volume mounted in a folder: the system refuses the rename.
SameVolume = true,
Cut = (step, _) =>
{
if (step == "rename" && ++renames == 1)
throw new IOException("The system cannot move the file to a different disk drive.", OperatingSystem.IsWindows() ? unchecked((int)0x80070011) : 18);
if (step == "copied") copied++;
},
};
var (survey, resumed) = await mover.MoveAsync(mover.Survey().Fingerprint, cancellationToken: context.Cancellation);
Assert.False(resumed);
Assert.True(survey.SameVolume, "planned as one volume");
Assert.Equal(1, renames);
Assert.Equal(before.Keys.Count(k => !IsLease(k)), copied, "every file copied and verified instead");
var after = Contents(to);
foreach (var (name, sha) in before.Where(b => !IsLease(b.Key))) Assert.Equal(sha, after.GetValueOrDefault(name), name);
Assert.False(Directory.Exists(from));
}
[Test]
public async Task AnEntryThatChangedAfterItsCopyIsKeptAndTheMoveEndsWell()
{
var (from, ids) = Workspace(projects: 2);
var to = Path.Combine(context.CreateTempDirectory("target"), "moved");
var changed = Path.Combine(from, ids[0].ToString("N"), "versions", "0001.json");
var mover = new WorkspaceMover(from, to)
{
SameVolume = false,
Cut = (step, _) =>
{
// Written after its copy was verified, before the source is cleared.
if (step == "switched") File.AppendAllText(changed, " ");
},
};
var log = new List<string>();
var survey = mover.Survey();
await mover.MoveAsync(survey.Fingerprint, log: log.Add, cancellationToken: context.Cancellation);
Assert.Equal("{} ", File.ReadAllText(changed), "never deleted");
Assert.False(Directory.Exists(Path.Combine(from, ids[1].ToString("N"))), "the other project went");
Assert.Contains(Loc.L("Archive.Log.WorkspaceMoveLeft", mover.From, 1), log);
Assert.Contains(Loc.L("Archive.Log.WorkspaceMoved", mover.To, 2, survey.Files), log);
Assert.Equal(2, new WorkspaceStore(to).List().Count);
}
[Test]
[WindowsOnly]
public async Task AnEntryHeldOpenAfterTheSwitchStaysInTheJournalAndIsClearedWhenTakenUp()
{
var (from, ids) = Workspace(projects: 2);
var to = Path.Combine(context.CreateTempDirectory("target"), "moved");
var heldFile = Path.Combine(from, ids[1].ToString("N"), WorkspaceProject.BundleFile);
FileStream? held = null;
var mover = new WorkspaceMover(from, to)
{
SameVolume = false,
Cut = (step, _) =>
{
// An editor elsewhere holds a file of the old folder open: it cannot be deleted.
if (step == "switched") held = new FileStream(heldFile, FileMode.Open, FileAccess.Read, FileShare.Read);
},
};
var log = new List<string>();
try
{
// The move ends well: the target is the workspace, the left entry is a notice.
await mover.MoveAsync(mover.Survey().Fingerprint, log: log.Add, cancellationToken: context.Cancellation);
}
finally
{
held?.Dispose();
}
Assert.Contains(Loc.L("Archive.Log.WorkspaceMoveLeft", mover.From, 1), log);
var journal = Assert.NotNull(WorkspaceMover.ReadJournal(from));
Assert.Equal(WorkspaceMoveStage.Switched, journal.Stage);
Assert.SequenceEqual([ids[1].ToString("N")], journal.Entries);
Assert.Equal(2, new WorkspaceStore(to).List().Count);
// Taken up once let go: told again, the entry cleared, the journal and the old folder gone.
var told = 0;
var (_, resumed) = await new WorkspaceMover(from, to) { SameVolume = false }.MoveAsync("whatever", (_, _) =>
{
told++;
return Task.CompletedTask;
}, cancellationToken: context.Cancellation);
Assert.True(resumed);
Assert.Equal(1, told);
Assert.False(Directory.Exists(from));
Assert.Equal(2, new WorkspaceStore(to).List().Count);
}
[Test]
public async Task AMoveCutInsideAnEntryLeavingAPartFinishesWithEveryFileWhole()
{
var (from, ids) = Workspace(projects: 2);
var before = Contents(from);
var to = Path.Combine(context.CreateTempDirectory("target"), "moved");
using var stop = CancellationTokenSource.CreateLinkedTokenSource(context.Cancellation);
var copied = 0;
var first = new WorkspaceMover(from, to)
{
SameVolume = false,
Cut = (step, _) =>
{
// The second file of an entry reached the target: the entry is not verified yet.
if (step == "copied" && ++copied == 2) stop.Cancel();
},
};
var fingerprint = first.Survey().Fingerprint;
await Assert.ThrowsAsync<OperationCanceledException>(() => first.MoveAsync(fingerprint, cancellationToken: stop.Token));
Assert.Empty(WorkspaceMover.ReadJournal(from)!.Verified);
// The program was killed while it wrote the next file: half of it is left as a part beside its name.
var proxies = Path.Combine(to, ids.Select(i => i.ToString("N")).Order(StringComparer.Ordinal).First(), "media", "proxies");
Directory.CreateDirectory(proxies);
File.WriteAllBytes(Path.Combine(proxies, "2.jpg" + WorkspaceMover.PartSuffix), new byte[100]);
var (_, resumed) = await new WorkspaceMover(from, to) { SameVolume = false }.MoveAsync("whatever", cancellationToken: context.Cancellation);
Assert.True(resumed);
var after = Contents(to);
foreach (var (name, sha) in before.Where(b => !IsLease(b.Key))) Assert.Equal(sha, after.GetValueOrDefault(name), name);
Assert.Empty(Directory.EnumerateFiles(to, "*" + WorkspaceMover.PartSuffix, SearchOption.AllDirectories));
Assert.False(Directory.Exists(from));
}
[Test]
public async Task AJobFindsItsProjectWhereTheWorkspaceIsNowAndWaitsWhileItIsMoved()
{
var (from, ids) = Workspace(projects: 1);
var id = ids[0];
const string missing = "Errors.Workspace.NotCheckedOut";
Assert.Equal(WorkspaceStore.FullRoot(from), WorkspaceJobRoots.Resolve(from, id, null, missing));
var other = Assert.Throws<InvalidOperationException>(() => WorkspaceJobRoots.Resolve(from, Guid.CreateVersion7(), null, missing));
Assert.Equal(Loc.L(missing), other.Message);
// A move under way (before its switch): every job of either folder waits for it.
var to = Path.Combine(context.CreateTempDirectory("target"), "moved");
using (var stop = CancellationTokenSource.CreateLinkedTokenSource(context.Cancellation))
{
var moving = new WorkspaceMover(from, to) { SameVolume = false, Cut = (step, _) => { if (step == "copied") stop.Cancel(); } };
await Assert.ThrowsAsync<OperationCanceledException>(() => moving.MoveAsync(moving.Survey().Fingerprint, cancellationToken: stop.Token));
}
Assert.Equal(Loc.L("Errors.Workspace.Moving"), Assert.Throws<InvalidOperationException>(() => WorkspaceJobRoots.Resolve(from, id, null, missing)).Message);
Assert.Equal(Loc.L("Errors.Workspace.Moving"), Assert.Throws<InvalidOperationException>(() => WorkspaceJobRoots.Resolve(to, id, () => from, missing)).Message);
// Past its switch, the source not cleared yet: a job queued for the old folder works in the new one.
var switched = new WorkspaceMover(from, to) { SameVolume = false, Cut = (step, _) => { if (step == "switched") throw new IOException("closed at the switch"); } };
await Assert.ThrowsAsync<IOException>(() => switched.MoveAsync("whatever", cancellationToken: context.Cancellation));
Assert.Equal(WorkspaceMoveStage.Switched, WorkspaceMover.ReadJournal(from)!.Stage);
Assert.Equal(WorkspaceStore.FullRoot(to), WorkspaceJobRoots.Resolve(from, id, null, missing));
// Once ended: the old folder holds nothing; the folder in use does.
await new WorkspaceMover(from, to) { SameVolume = false }.MoveAsync("whatever", cancellationToken: context.Cancellation);
Assert.False(Directory.Exists(from));
Assert.Equal(WorkspaceStore.FullRoot(to), WorkspaceJobRoots.Resolve(from, id, () => to, missing));
Assert.Equal(Loc.L(missing), Assert.Throws<InvalidOperationException>(() => WorkspaceJobRoots.Resolve(from, id, null, missing)).Message);
}
/// <summary>
/// A workspace with <paramref name="projects"/> projects (a working state, media with an empty folder, versions, the
/// lease), its manifest and a trash entry.
@@ -151,6 +151,51 @@ public abstract class WorkspaceOriginalsTests(TestContext context) : DatabaseTes
Assert.Equal(media.Frames[1].OriginalSha256, Sha(inTrash[0]));
}
[Test]
public async Task ACancelledCopyOfTheOriginalsRemovesWhatItWroteAndTrashesWhatTheHomeLacks()
{
var fx = await FixtureAsync();
var (store, sync) = fx.Workspace();
var project = await fx.CheckoutAsync(sync);
Assert.False(project.ReadMedia()!.HoldsOriginals);
var until = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(30));
// Held so that the copy writes its originals and waits to record them; cancelled there.
var lease = await project.LockAsync(TimeSpan.FromSeconds(10), fx.Ct);
Job job;
try
{
job = await fx.StartCopyAsync(store, project.ProjectId, BundleMedia.Originals);
while (!(Directory.Exists(project.OriginalsDirectory)
&& Directory.GetFiles(project.OriginalsDirectory).Count(f => !f.EndsWith(".part", StringComparison.Ordinal)) == fx.Frames.Count))
{
if (DateTime.UtcNow > until) Assert.Fail("the copy's originals were not written");
await Task.Delay(20, fx.Ct);
}
// A file of bytes the home does not hold, and a download cut short.
File.WriteAllText(Path.Combine(project.OriginalsDirectory, "edited.jpg"), "not the home's photo");
File.WriteAllText(Path.Combine(project.OriginalsDirectory, Guid.NewGuid().ToString("N") + ".part"), "half");
await fx.CancelAsync(job.Id);
}
finally
{
lease.Dispose();
}
await fx.Archive.WaitForAsync(job.Id, JobState.Cancelled, (int)TestTiming.Budget(30));
while (Directory.Exists(project.OriginalsDirectory))
{
if (DateTime.UtcNow > until) Assert.Fail("the cancelled copy's originals stayed: " + string.Join(", ", Directory.GetFiles(project.OriginalsDirectory).Select(Path.GetFileName)));
await Task.Delay(20, fx.Ct);
}
// The media a copy finished before stay; the one file the home lacks is in the trash, never away.
var media = project.ReadMedia()!;
Assert.False(media.HoldsOriginals);
foreach (var frame in media.Frames) Assert.FileExists(project.MediaFile(frame.File!));
var inTrash = Directory.GetFiles(Path.Combine(store.Root, WorkspaceOriginals.TrashFolder), "*", SearchOption.AllDirectories);
Assert.SequenceEqual(["edited.jpg"], inTrash.Select(Path.GetFileName));
}
[Test]
public async Task ProxiesOnlyRefusesAPlanTheFilesChangedSince()
{
@@ -94,7 +94,8 @@ public sealed class WorkspaceRenderTests(TestContext context)
// The send home follows with the new render, and files it in the archive with its project.
var send = (await fx.Db.Jobs.ListAsync(null, 50, null, fx.Ct)).Items.Single(j => j.Kind == JobKind.WorkspaceSend);
var sent = Assert.NotNull(WorkspaceJobs.SendParameters(send));
Assert.SequenceEqual([entry.RenderId], sent.RenderIds);
// Every render not sent yet, this one among them: one a send failed earlier goes with it.
Assert.Empty(sent.RenderIds);
Assert.Equal((bed.Project.ProjectId, bed.Store.Root), (sent.ProjectId, sent.WorkspaceRoot));
await fx.WaitForAsync(send.Id, JobState.Done);
var filed = Assert.NotNull(await fx.Db.Renders.GetAsync(entry.RenderId, fx.Ct));
@@ -47,14 +47,14 @@ public abstract class WorkspaceSendTests(TestContext context) : DatabaseTest(con
}
/// <summary>An output in the project's exports with its ledger entry, as a local render leaves them.</summary>
private static WorkspaceRenderEntry Render(WorkspaceProject project, Guid? versionId, string name, int seed)
private static WorkspaceRenderEntry Render(WorkspaceProject project, Guid? versionId, string name, int seed, string? settingsHash = null)
{
Directory.CreateDirectory(project.ExportsDirectory);
var bytes = new byte[150_000 + seed];
new Random(seed).NextBytes(bytes);
File.WriteAllBytes(Path.Combine(project.ExportsDirectory, name), bytes);
var entry = new WorkspaceRenderEntry(Guid.CreateVersion7(), Guid.CreateVersion7(), name, Convert.ToHexStringLower(SHA256.HashData(bytes)), bytes.Length,
"1080p H.264", "h264", 1920, 1080, 24, 2.5, project.ProjectId, versionId, null, Rendered);
"1080p H.264", "h264", 1920, 1080, 24, 2.5, project.ProjectId, versionId, settingsHash, Rendered);
project.WriteRenders(project.ReadRenders().With(entry));
return entry;
}
@@ -221,12 +221,53 @@ public abstract class WorkspaceSendTests(TestContext context) : DatabaseTest(con
var foreign = (await fx.Home.HeadAsync(other.Id, fx.Ct)).Id;
var entry = Render(project, foreign, "Foreign.mp4", 7);
var job = await SendAsync(fx, engine, store, project.ProjectId, JobState.Done);
// The project's home holds no such version of this project: the render goes with its project alone.
Assert.Contains(Loc.L("Archive.Log.WorkspaceVersionNotHome", project.ReadBundle().Workspace!.Name), job.LogTail!);
var row = Assert.NotNull(await fx.Db.Renders.GetAsync(entry.RenderId, fx.Ct));
Assert.Equal(((Guid?)project.ProjectId, (Guid?)null), (row.ProjectId, row.ProjectVersionId));
Assert.True(project.ReadRenders().Find(entry.RenderId)!.IsSent);
Assert.Null(project.ReadRenders().Find(entry.RenderId)!.ProjectVersionId);
}
[Test]
public async Task AVersionTheHomeHoldsByAnotherIdIsFiledByThatId()
{
var fx = await FixtureAsync();
var engine = await EngineAsync(fx);
var (store, _, project) = await CheckoutAsync(fx);
// A version a push replayed on a home that moved on: the home holds its content under another id.
var head = await fx.Home.HeadAsync(project.ProjectId, fx.Ct);
var entry = Render(project, Guid.CreateVersion7(), "Replayed.mp4", 11, head.ContentHash);
var job = await SendAsync(fx, engine, store, project.ProjectId, JobState.Done);
Assert.Contains(Loc.L("Archive.Log.WorkspaceVersionReplayed", project.ReadBundle().Workspace!.Name, head.Number), job.LogTail!);
var row = Assert.NotNull(await fx.Db.Renders.GetAsync(entry.RenderId, fx.Ct));
Assert.Equal(((Guid?)project.ProjectId, (Guid?)head.Id), (row.ProjectId, row.ProjectVersionId));
// The ledger names the home's id from now on.
var sent = Assert.NotNull(project.ReadRenders().Find(entry.RenderId));
Assert.Equal(((Guid?)head.Id, true), (sent.ProjectVersionId, sent.IsSent));
}
[Test]
public async Task ALedgerNamingAFileOutsideTheExportsIsRefused()
{
var fx = await FixtureAsync();
var engine = await EngineAsync(fx);
var (store, _, project) = await CheckoutAsync(fx);
// A ledger edited by hand (or a newer Chronos's) naming the working state: never read, never sent.
var entry = Render(project, null, "Outside.mp4", 12) with { File = Path.Combine("..", WorkspaceProject.BundleFile) };
project.WriteRenders(project.ReadRenders().Without(entry.RenderId).With(entry));
var failed = await SendAsync(fx, engine, store, project.ProjectId, JobState.Failed);
Assert.Equal(Loc.L("Errors.Workspace.SendVersion"), failed.Error);
Assert.Equal(Loc.L("Errors.Workspace.SendFailed", 1, 1), failed.Error);
Assert.Null(await fx.Db.Renders.GetAsync(entry.RenderId, fx.Ct));
// Not the render's fault: it waits, unsent, for the next send.
Assert.Equal(WorkspaceRenderEntry.Pending, project.ReadRenders().Find(entry.RenderId)!.State);
Assert.Equal((WorkspaceRenderEntry.Failed, Loc.L("Errors.Workspace.SendMissing", WorkspaceProject.BundleFile)),
(project.ReadRenders().Find(entry.RenderId)!.State, project.ReadRenders().Find(entry.RenderId)!.Error));
Assert.FileExists(project.BundlePath);
}
[Test]