feat(projects): workspace projects with linear versions, the local archive as their home

Owner review 2, phase 5a (R8): editing moves out of the library into a workspace on a fast disk, and a
sequence gets several projects, each with a linear version history pushed and pulled like git.

- Core: ProjectSettings keeps members a newer Chronos wrote (Extra) and reads a newer settings format
  read-only; ProjectContent is the portable form of a version (every frame position parked by photo,
  canonical text, SHA-256 content hash); ProjectBundle format 2 adds the workspace section, and a file
  without it is still written as format 1. JobKind.WorkspaceCopy = 20 (19 kept for Convert).
- Data: migration 0009 (projects, project_versions, the render's project columns); ProjectService on
  ArchiveService.Projects keeps projects as sidecars first (.chronos/projects/<id>/), then the index,
  under the sequence lease: create, rename, delete into the projects' trash, history, push with
  fast-forward, idempotent repeat, divergence and hash checks. Main is made from the sequence's settings
  and mirrored both ways, so every older code path keeps working; outside writes become "external"
  versions, a mirror a crash cut short is completed or merged. Full scans and rebuilds take the projects
  back from their sidecars.
- ProjectMerge moves from the App to Data/Projects, merges pending frames photo by photo and replays
  unpushed commits on a moved head.
- Workspaces: WorkspaceStore, WorkspaceSync (checkout, save, commit, push, pull with replay and merge,
  conflicts settled by keep mine / take server / save both, restore, status) and the WorkspaceCopy job
  (proxies copied hash-verified and resumable; originals refused until phase 5c).
- Renders of a project version place its positions on the frames and record the project and version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit c4c1802884e403db8759ed0501f770a67a047f20)
This commit is contained in:
Alby96 committed 2026-10-27 22:51:32 +01:00
1 parent e3cbe30b29
commit 03d32f18d3
51 files changed
+4917 -108

No files matched your search

@@ -1,3 +1,4 @@
using Chronos.Core.Model;
using Chronos.Data.Migrations;
using Chronos.Data.Tests.Infrastructure;
using Chronos.Testing;
@@ -9,7 +10,7 @@ public abstract class MigrationTests(TestContext context) : RepositoryTest(conte
private static readonly string[] Tables =
[
"archives", "sequences", "frames", "renders", "jobs", "media_cards", "import_history", "users", "tokens",
"render_nodes", "settings", "tags", "sequence_tags", "audit_log", "uploads", "schedules", "frame_removals",
"render_nodes", "settings", "tags", "sequence_tags", "audit_log", "uploads", "schedules", "frame_removals", "projects", "project_versions",
];
[Test]
@@ -41,6 +42,67 @@ public abstract class MigrationTests(TestContext context) : RepositoryTest(conte
Assert.True(recorded[0].GetDateTimeOffset(2) > DateTimeOffset.UtcNow.AddMinutes(-5));
}
[Test]
public async Task ProjectsKeepOneMainAndOneLiveNamePerSequence()
{
var chronos = await OpenChronosAsync();
var archive = TestData.Archive("Main");
await chronos.Archives.UpsertAsync(archive, Ct);
var sequence = TestData.Sequence(archive.Id);
await chronos.Sequences.UpsertAsync(sequence, Ct);
var now = DateTimeOffset.UtcNow;
SequenceProject Project(string name, bool main) => new() { Id = Guid.CreateVersion7(), SequenceId = sequence.Id, Name = name, IsMain = main, CreatedAt = now, UpdatedAt = now };
var main = Project("Main", true);
await chronos.Projects.InsertAsync(main, Ct);
await Assert.ThrowsAsync<DatabaseException>(() => chronos.Projects.InsertAsync(Project("Other main", true), Ct));
var vertical = Project("Vertical", false);
await chronos.Projects.InsertAsync(vertical, Ct);
await Assert.ThrowsAsync<DatabaseException>(() => chronos.Projects.InsertAsync(Project("Vertical", false), Ct));
// A deleted project gives its name back.
await chronos.Projects.UpdateAsync(vertical with { DeletedAt = now }, Ct);
await chronos.Projects.InsertAsync(Project("Vertical", false), Ct);
// Versions: one number each, settings kept byte for byte, and they go with the sequence.
const string settings = "{\n \"version\": 1,\n \"exposure\": {}\n}";
var version = new ProjectVersion
{
Id = Guid.CreateVersion7(),
ProjectId = main.Id,
Number = 1,
Kind = ProjectVersionKind.Imported,
SettingsJson = settings,
ContentHash = new string('0', 64),
FramesVersion = 3,
CreatedAt = now,
StoredAt = now,
};
await chronos.Projects.InsertVersionAsync(version, Ct);
await Assert.ThrowsAsync<DatabaseException>(() => chronos.Projects.InsertVersionAsync(version with { Id = Guid.CreateVersion7() }, Ct));
var stored = Assert.NotNull(await chronos.Projects.GetVersionAsync(version.Id, Ct));
Assert.Equal(settings, stored.SettingsJson);
Assert.Equal((ProjectVersionKind.Imported, 3), (stored.Kind, stored.FramesVersion));
Assert.True(await chronos.Projects.AdvanceHeadAsync(main.Id, 0, version.Id, 1, now, Ct));
Assert.False(await chronos.Projects.AdvanceHeadAsync(main.Id, 0, version.Id, 1, now, Ct), "the head moved already");
var render = new Render
{
Id = Guid.CreateVersion7(),
SequenceId = sequence.Id,
PresetName = "MJPEG",
OutputPath = "x/exports/a.avi",
Created = now,
ProjectId = main.Id,
ProjectVersionId = version.Id,
};
await chronos.Renders.InsertAsync(render, Ct);
Assert.Equal((main.Id, version.Id), ((await chronos.Renders.GetAsync(render.Id, Ct))!.ProjectId, (await chronos.Renders.GetAsync(render.Id, Ct))!.ProjectVersionId));
await chronos.Sequences.DeleteAsync(sequence.Id, Ct);
Assert.Empty(await chronos.Projects.ListBySequenceAsync(sequence.Id, includeDeleted: true, Ct));
Assert.Null(await chronos.Projects.GetVersionAsync(version.Id, Ct));
}
[Test]
public async Task AppliesOnlyPendingMigrations()
{
@@ -64,6 +64,52 @@ public sealed class RenderJobTests(TestContext context)
Assert.Equal(3, (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!.RenderedCount);
}
[Test]
public async Task AProjectVersionRendersWithItsPositionsPlacedOnTheFramesAndIsRecordedWithIt()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Scene());
var frames = await fx.Db.Frames.ListBySequenceAsync(sequence.Id, cancellationToken: fx.Ct);
var photos = new FramePhotos(frames.Select(f => (f.Index, new FramePhoto(f.Sha256, f.Size, f.CapturedAt))));
var projects = fx.Archive.Service.Projects;
var vertical = await projects.CreateAsync(sequence.Id, "Vertical", cancellationToken: fx.Ct);
var head = await projects.HeadAsync(vertical.Id, fx.Ct);
// The version holds its positions parked by photo (the adopted frames are not hashed: size and capture time name them).
var settings = new ProjectSettings { ExcludedFrames = [3, 5], Timing = new TimingSettings { Mode = new Auto<TimingMode>().WithManual(TimingMode.Constant) } };
var portable = ProjectContent.ToPortable(settings, photos);
Assert.Empty(ProjectSettings.FromJson(portable).ExcludedFrames);
var draft = head with
{
Id = Guid.CreateVersion7(),
ParentId = head.Id,
Number = 2,
Kind = ProjectVersionKind.Commit,
SettingsJson = portable,
ContentHash = ProjectContent.Hash(portable),
StoredAt = null,
};
var version = (await projects.PushAsync(vertical.Id, draft, fx.Ct)).Version!;
await fx.StartEngineAsync();
var requests = ProcessingJobs.RenderVersion(sequence, version, Mjpeg with { Preset = new Auto<string>().WithManual("png-sequence") }, 96, 64);
var job = await fx.EnqueueAsync(requests.Single());
await fx.Archive.WaitForAsync(job.Id, JobState.Done, (int)TestTiming.Budget(60));
Assert.Equal(Frames - 2, Directory.GetFiles(Path.Combine(fx.Folder(sequence).Exports, "clip-PNG")).Length);
var render = (await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct)).Single();
Assert.Equal((vertical.Id, version.Id), (render.ProjectId, render.ProjectVersionId));
Assert.SequenceEqual([3, 5], ProjectSettings.FromJson(render.SettingsJson!).ExcludedFrames);
// A render of another project leaves the sequence's own settings alone.
Assert.Empty(ProjectSettings.FromJson((await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!.SettingsJson ?? "{}").ExcludedFrames);
// A job naming the version without its settings renders them too.
var named = Chronos.Protocol.ProtocolJson.Default.RenderJobParameters;
var parameters = System.Text.Json.JsonSerializer.Deserialize(requests[0].ParametersJson!, named)! with { SettingsJson = null };
var second = await fx.EnqueueAsync(requests[0] with { ParametersJson = System.Text.Json.JsonSerializer.Serialize(parameters, named) });
await fx.Archive.WaitForAsync(second.Id, JobState.Done, (int)TestTiming.Budget(60));
Assert.True((await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct)).All(r => r.ProjectVersionId == version.Id));
}
[Test]
public async Task FramesThisHostCannotDecodeRenderFromTheirProxies()
{
@@ -0,0 +1,350 @@
using Chronos.Core.Archiving;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Archiving;
using Chronos.Data.Projects;
using Chronos.Data.Repositories;
using Chronos.Data.Tests.Archiving;
using Chronos.Data.Tests.Infrastructure;
using Chronos.Testing;
using static Chronos.Data.Tests.Archiving.ArchiveFixture;
namespace Chronos.Data.Tests.Projects;
/// <summary>Projects of a sequence with this PC's archive as their home (owner review 2, R8): sidecars, index, Main mirror, push.</summary>
[Category("projects")]
public abstract class ProjectServiceTests(TestContext context) : DatabaseTest(context)
{
internal async Task<ArchiveFixture> FixtureAsync() => Own(await CreateAsync(Context, database: await NewOptionsAsync(multiConnection: true)));
/// <summary>A sequence of <paramref name="count"/> uploaded photos (hashed), ten seconds apart.</summary>
internal static async Task<(Sequence Sequence, List<Frame> Frames)> UploadedAsync(ArchiveFixture fx, int count, int seed = 100)
{
Guid? id = null;
for (var i = 0; i < count; i++)
{
var (path, size, sha) = fx.Stage(Start.AddSeconds(10 * i), seed + i);
var result = await fx.Service.Ingest.CommitAsync(new IngestRequest(fx.Archive.Id, id, null, id is null ? $"upload-{seed}" : null, path,
$"IMG_{i + 1:0000}.JPG", size, sha, null, null), fx.Ct);
id = result.SequenceId;
}
return ((await fx.Db.Sequences.GetAsync(id!.Value))!, [.. await fx.Db.Frames.ListBySequenceAsync(id.Value)]);
}
internal static FramePhotos Photos(IEnumerable<Frame> frames) => new(frames.Select(f => (f.Index, new FramePhoto(f.Sha256, f.Size, f.CapturedAt))));
/// <summary>The sequence's settings written as an older code path writes them (the editor, an analysis): index first, with its version check.</summary>
internal static async Task<Sequence> WriteSettingsAsync(ArchiveFixture fx, Guid sequenceId, ProjectSettings settings)
{
var row = (await fx.Db.Sequences.GetAsync(sequenceId))!;
var result = await fx.Db.Sequences.EditAsync(sequenceId, new SequenceEdit { SettingsJson = settings.ToJson() }, row.SettingsVersion, fx.Ct);
Assert.Equal(SequenceEditOutcome.Updated, result.Outcome);
return result.Sequence!;
}
/// <summary>A version made from <paramref name="parent"/> with <paramref name="settings"/> (positions on <paramref name="frames"/>), as a workspace sends it.</summary>
internal static ProjectVersion Draft(ProjectVersion parent, ProjectSettings settings, IEnumerable<Frame> frames, string? note = null)
{
var portable = ProjectContent.ToPortable(settings, Photos(frames));
return new ProjectVersion
{
Id = Guid.CreateVersion7(),
ProjectId = parent.ProjectId,
ParentId = parent.Id,
Number = parent.Number + 1,
Kind = ProjectVersionKind.Commit,
Author = "alberto",
ClientName = "test",
Note = note,
SettingsJson = portable,
ContentHash = ProjectContent.Hash(portable),
FramesVersion = parent.FramesVersion,
CreatedAt = DateTimeOffset.UtcNow,
};
}
[Test]
public async Task MainIsMadeFromTheSequenceSettingsWithItsPositionsParkedByPhoto()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 5);
await WriteSettingsAsync(fx, sequence.Id, new ProjectSettings { ExcludedFrames = [1], HeroFrame = 3 });
var projects = fx.Service.Projects;
var main = await projects.MainAsync(sequence.Id, fx.Ct);
Assert.True(main.IsMain);
Assert.Equal((ProjectService.MainName, 1), (main.Name, main.HeadNumber));
var head = await projects.HeadAsync(main.Id, fx.Ct);
Assert.Equal(ProjectVersionKind.Imported, head.Kind);
Assert.True(ProjectContent.Verifies(head.SettingsJson, head.ContentHash));
var portable = ProjectSettings.FromJson(head.SettingsJson);
Assert.Empty(portable.ExcludedFrames);
Assert.Null(portable.HeroFrame);
Assert.Equal(2, portable.PendingFrames!.Count);
var placed = ProjectSettings.FromJson(ProjectContent.Place(head.SettingsJson, Photos(frames)));
Assert.SequenceEqual([1], placed.ExcludedFrames);
Assert.Equal(3, placed.HeroFrame);
// The sidecars hold it: the record and an immutable version file.
var folder = fx.Paths.Sequence(sequence.Folder);
var record = ProjectSidecars.ReadRecord(folder.ProjectRecordPath(main.Id));
Assert.Equal((main.Id, sequence.Id, true, head.Id, 1), (record.Id, record.SequenceId, record.IsMain, record.Head!.Id, record.Head.Number));
Assert.Equal(head.SettingsJson, ProjectSidecars.ReadVersion(folder.VersionPath(main.Id, 1, head.Id)).SettingsJson);
// Asking again makes nothing new.
Assert.Equal(main.Id, (await projects.MainAsync(sequence.Id, fx.Ct)).Id);
Assert.Count(1, await projects.ListAsync(sequence.Id, fx.Ct));
Assert.Count(1, await projects.HistoryAsync(main.Id, cancellationToken: fx.Ct));
}
[Test]
public async Task APushFastForwardsAndMirrorsMainIntoTheSequence()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 5);
var projects = fx.Service.Projects;
var main = await projects.MainAsync(sequence.Id, fx.Ct);
var head = await projects.HeadAsync(main.Id, fx.Ct);
var before = (await fx.Db.Sequences.GetAsync(sequence.Id))!;
var draft = Draft(head, new ProjectSettings { ExcludedFrames = [0, 4], HeroFrame = 2, Exposure = new ExposureSettings { ExposureOffsetEv = 0.7 } }, frames,
"first look");
var result = await projects.PushAsync(main.Id, draft, fx.Ct);
Assert.Equal(PushOutcome.Stored, result.Outcome);
var stored = Assert.NotNull(result.Version);
Assert.Equal((draft.Id, 2, "first look"), (stored.Id, stored.Number, stored.Note));
Assert.NotNull(stored.StoredAt);
Assert.Equal(stored.Id, (await projects.HeadAsync(main.Id, fx.Ct)).Id);
Assert.SequenceEqual([2, 1], (await projects.HistoryAsync(main.Id, cancellationToken: fx.Ct)).Select(v => v.Number));
Assert.FileExists(fx.Paths.Sequence(sequence.Folder).VersionPath(main.Id, 2, draft.Id));
// Main's head is the sequence's settings, positions on its frames, through the settings version check.
var after = (await fx.Db.Sequences.GetAsync(sequence.Id))!;
Assert.Greater(after.SettingsVersion, before.SettingsVersion);
var mirrored = ProjectSettings.FromJson(after.SettingsJson!);
Assert.SequenceEqual([0, 4], mirrored.ExcludedFrames);
Assert.Equal(0.7, mirrored.Exposure.ExposureOffsetEv);
Assert.Equal(frames[2].Id, after.HeroFrameId);
Assert.Equal(after.SettingsJson, File.ReadAllText(fx.Paths.Sequence(sequence.Folder).ProjectPath));
var row = (await fx.Db.Projects.GetAsync(main.Id))!;
Assert.Equal((stored.Id, after.SettingsVersion), (row.MirroredVersionId, row.MirroredSettingsVersion));
// The mirror is no outside change: no version is added for it.
Assert.Equal(2, (await projects.HeadAsync(main.Id, fx.Ct)).Number);
}
[Test]
public async Task APushIsIdempotentDivergesFromAnOldParentAndChecksItsHash()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 3);
var projects = fx.Service.Projects;
var main = await projects.MainAsync(sequence.Id, fx.Ct);
var first = await projects.HeadAsync(main.Id, fx.Ct);
var draft = Draft(first, new ProjectSettings { Stack = new StackSettings { Mode = StackSetting.Median } }, frames);
Assert.Equal(PushOutcome.Stored, (await projects.PushAsync(main.Id, draft, fx.Ct)).Outcome);
var again = await projects.PushAsync(main.Id, draft, fx.Ct);
Assert.Equal((PushOutcome.AlreadyStored, 2), (again.Outcome, again.Version!.Number));
Assert.Equal(2, (await projects.HistoryAsync(main.Id, cancellationToken: fx.Ct)).Count);
var late = Draft(first, new ProjectSettings { Stack = new StackSettings { Mode = StackSetting.Mean } }, frames);
var diverged = await projects.PushAsync(main.Id, late, fx.Ct);
Assert.Equal(PushOutcome.Diverged, diverged.Outcome);
Assert.Equal(draft.Id, diverged.Head!.Id);
var head = diverged.Head;
var damaged = Draft(head, new ProjectSettings(), frames) with { ContentHash = new string('f', 64) };
Assert.Equal(PushOutcome.HashMismatch, (await projects.PushAsync(main.Id, damaged, fx.Ct)).Outcome);
var positional = new ProjectSettings { ExcludedFrames = [1] }.ToJson();
var notPortable = Draft(head, new ProjectSettings(), frames) with { SettingsJson = positional, ContentHash = ProjectContent.Hash(positional) };
Assert.Equal(PushOutcome.Invalid, (await projects.PushAsync(main.Id, notPortable, fx.Ct)).Outcome);
var newer = """{ "version": 9 }""";
Assert.Equal(PushOutcome.NewerFormat,
(await projects.PushAsync(main.Id, Draft(head, new ProjectSettings(), frames) with { SettingsJson = newer, ContentHash = ProjectContent.Hash(newer) }, fx.Ct)).Outcome);
Assert.Equal(2, (await projects.HeadAsync(main.Id, fx.Ct)).Number);
}
[Test]
public async Task SettingsAnotherPathWritesBecomeAnExternalVersionOfMain()
{
var fx = await FixtureAsync();
var (sequence, _) = await UploadedAsync(fx, 3);
var projects = fx.Service.Projects;
var main = await projects.MainAsync(sequence.Id, fx.Ct);
// The editor's old path (or an analysis, or the server's API) writes the settings.
await WriteSettingsAsync(fx, sequence.Id, new ProjectSettings { ExcludedFrames = [2], Exposure = new ExposureSettings { ExposureOffsetEv = -0.3 } });
var history = await projects.HistoryAsync(main.Id, cancellationToken: fx.Ct);
Assert.Equal((2, ProjectVersionKind.External), (history[0].Number, history[0].Kind));
Assert.Equal(history[1].Id, history[0].ParentId);
Assert.Equal(-0.3, ProjectSettings.FromJson(history[0].SettingsJson).Exposure.ExposureOffsetEv);
// A title or tags edit moves the settings version too, but not the settings: nothing is added.
await fx.Db.Sequences.SetTagsAsync(sequence.Id, ["harbour"], fx.Ct);
Assert.Equal(2, (await projects.HistoryAsync(main.Id, cancellationToken: fx.Ct)).Count);
}
[Test]
public async Task AMirrorACrashCutShortIsCompletedAndOneRacedByAnEditIsMerged()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 4);
var projects = fx.Service.Projects;
var main = await projects.MainAsync(sequence.Id, fx.Ct);
var first = await projects.HeadAsync(main.Id, fx.Ct);
var pushed = (await projects.PushAsync(main.Id, Draft(first, new ProjectSettings { Stack = new StackSettings { Mode = StackSetting.Median } }, frames),
fx.Ct)).Version!;
// As if the push had stopped before its mirror: the sequence still holds version 1, mirrored at its settings version.
var reverted = await WriteSettingsAsync(fx, sequence.Id, new ProjectSettings());
await fx.Db.Projects.SetMirroredAsync(main.Id, first.Id, reverted.SettingsVersion, fx.Ct);
Assert.Equal(pushed.Id, (await projects.HeadAsync(main.Id, fx.Ct)).Id);
var completed = (await fx.Db.Sequences.GetAsync(sequence.Id))!;
Assert.Equal(StackSetting.Median, ProjectSettings.FromJson(completed.SettingsJson!).Stack.Mode);
// Again, but someone wrote other settings meanwhile: both changes are kept in a merge version.
await WriteSettingsAsync(fx, sequence.Id, new ProjectSettings());
await fx.Db.Projects.SetMirroredAsync(main.Id, first.Id, completed.SettingsVersion, fx.Ct);
await WriteSettingsAsync(fx, sequence.Id, new ProjectSettings { Exposure = new ExposureSettings { ExposureOffsetEv = 1.25 } });
var merge = await projects.HeadAsync(main.Id, fx.Ct);
Assert.Equal((ProjectVersionKind.Merge, pushed.Id), (merge.Kind, merge.ParentId));
var merged = ProjectSettings.FromJson((await fx.Db.Sequences.GetAsync(sequence.Id))!.SettingsJson!);
Assert.Equal((StackSetting.Median, 1.25), (merged.Stack.Mode, merged.Exposure.ExposureOffsetEv));
}
[Test]
public async Task ProjectsAreNamedOnceDeletedIntoTheirTrashAndMainStays()
{
var fx = await FixtureAsync();
var (sequence, _) = await UploadedAsync(fx, 3);
var projects = fx.Service.Projects;
var main = await projects.MainAsync(sequence.Id, fx.Ct);
var mainHead = await projects.HeadAsync(main.Id, fx.Ct);
var vertical = await projects.CreateAsync(sequence.Id, " Vertical social ", author: "alberto", cancellationToken: fx.Ct);
Assert.Equal(("Vertical social", false, 1), (vertical.Name, vertical.IsMain, vertical.HeadNumber));
var copy = await projects.HeadAsync(vertical.Id, fx.Ct);
Assert.Equal((ProjectVersionKind.Imported, mainHead.ContentHash), (copy.Kind, copy.ContentHash));
Assert.Equal(ProjectError.NameTaken,
(await Assert.ThrowsAsync<ProjectException>(() => projects.CreateAsync(sequence.Id, "VERTICAL SOCIAL", cancellationToken: fx.Ct))).Reason);
Assert.Equal(ProjectError.InvalidName, (await Assert.ThrowsAsync<ProjectException>(() => projects.CreateAsync(sequence.Id, " ", cancellationToken: fx.Ct))).Reason);
var landscape = await projects.CreateAsync(sequence.Id, "4K landscape", copy.Id, cancellationToken: fx.Ct);
Assert.Equal(ProjectError.NameTaken, (await Assert.ThrowsAsync<ProjectException>(() => projects.RenameAsync(landscape.Id, "Main", fx.Ct))).Reason);
landscape = await projects.RenameAsync(landscape.Id, "4K wide", fx.Ct);
Assert.Equal("4K wide", ProjectSidecars.ReadRecord(fx.Paths.Sequence(sequence.Folder).ProjectRecordPath(landscape.Id)).Name);
Assert.SequenceEqual(["Main", "Vertical social", "4K wide"], (await projects.ListAsync(sequence.Id, fx.Ct)).Select(p => p.Name));
Assert.Equal(ProjectError.MainCannotBeDeleted, (await Assert.ThrowsAsync<ProjectException>(() => projects.DeleteAsync(main.Id, fx.Ct))).Reason);
await projects.DeleteAsync(vertical.Id, fx.Ct);
var folder = fx.Paths.Sequence(sequence.Folder);
Assert.False(Directory.Exists(folder.ProjectDirectory(vertical.Id)));
var trashed = Directory.GetDirectories(folder.ProjectsTrashDirectory).Single();
Assert.True(Path.GetFileName(trashed).StartsWith(vertical.Id.ToString("N"), StringComparison.Ordinal));
Assert.NotNull(ProjectSidecars.ReadRecord(Path.Combine(trashed, "project.json")).Deleted);
Assert.SequenceEqual(["Main", "4K wide"], (await projects.ListAsync(sequence.Id, fx.Ct)).Select(p => p.Name));
// Its name is free again.
await projects.CreateAsync(sequence.Id, "Vertical social", cancellationToken: fx.Ct);
}
[Test]
public async Task AnIndexRebuiltFromTheSidecarsHasEveryProjectAndVersionBack()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 4);
var projects = fx.Service.Projects;
var main = await projects.MainAsync(sequence.Id, fx.Ct);
var mainPush = (await projects.PushAsync(main.Id, Draft(await projects.HeadAsync(main.Id, fx.Ct), new ProjectSettings { ExcludedFrames = [3] }, frames),
fx.Ct)).Version!;
var vertical = await projects.CreateAsync(sequence.Id, "Vertical", cancellationToken: fx.Ct);
var verticalPush = (await projects.PushAsync(vertical.Id,
Draft(await projects.HeadAsync(vertical.Id, fx.Ct), new ProjectSettings { Camera = new CameraSettings { Aspect = new Auto<string>().WithManual("9:16") } }, frames),
fx.Ct)).Version!;
var gone = await projects.CreateAsync(sequence.Id, "Old", cancellationToken: fx.Ct);
await projects.DeleteAsync(gone.Id, fx.Ct);
await fx.ReopenWithEmptyIndexAsync();
await fx.ScanAsync(ScanMode.Rebuild);
var rebuilt = fx.Service.Projects;
var listed = await rebuilt.ListAsync(sequence.Id, fx.Ct);
Assert.SequenceEqual([main.Id, vertical.Id], listed.Select(p => p.Id));
Assert.Equal((mainPush.Id, 2), (listed[0].HeadVersionId, listed[0].HeadNumber));
Assert.Equal((verticalPush.Id, 2), (listed[1].HeadVersionId, listed[1].HeadNumber));
Assert.Equal(verticalPush.SettingsJson, (await rebuilt.GetVersionAsync(verticalPush.Id, fx.Ct))!.SettingsJson);
Assert.NotNull((await fx.Db.Projects.GetAsync(gone.Id))!.DeletedAt);
// The sequence's settings are Main's head: the rebuilt index recognises the mirror and adds no version.
Assert.SequenceEqual([2, 1], (await rebuilt.HistoryAsync(main.Id, cancellationToken: fx.Ct)).Select(v => v.Number));
Assert.Equal(mainPush.Id, (await fx.Db.Projects.GetAsync(main.Id))!.MirroredVersionId);
}
[Test]
public async Task AVersionFileAPushLeftBehindItsRecordIsAdoptedAndAStrayOneSetAside()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 3);
var projects = fx.Service.Projects;
var vertical = await projects.CreateAsync(sequence.Id, "Vertical", cancellationToken: fx.Ct);
var head = await projects.HeadAsync(vertical.Id, fx.Ct);
var folder = fx.Paths.Sequence(sequence.Folder);
// A push that wrote its version file and stopped before the record: the file follows the head.
var follower = Draft(head, new ProjectSettings { Stack = new StackSettings { Mode = StackSetting.StarTrails } }, frames) with { StoredAt = DateTimeOffset.UtcNow };
ProjectSidecars.WriteVersion(folder.VersionPath(vertical.Id, 2, follower.Id), follower);
// And a file past the head that follows nothing.
var stray = Draft(head, new ProjectSettings(), frames) with { Number = 5, ParentId = Guid.CreateVersion7(), StoredAt = DateTimeOffset.UtcNow };
ProjectSidecars.WriteVersion(folder.VersionPath(vertical.Id, 5, stray.Id), stray);
Assert.Equal(follower.Id, (await projects.HeadAsync(vertical.Id, fx.Ct)).Id);
Assert.Equal(follower.Id, ProjectSidecars.ReadRecord(folder.ProjectRecordPath(vertical.Id)).Head!.Id);
Assert.False(File.Exists(folder.VersionPath(vertical.Id, 5, stray.Id)));
Assert.Count(1, Directory.GetFiles(Path.Combine(folder.ProjectVersionsDirectory(vertical.Id), ".stray")));
// A version file is immutable: another version at its name is refused.
Assert.Throws<IOException>(() => ProjectSidecars.WriteVersion(folder.VersionPath(vertical.Id, 2, follower.Id), follower with { ContentHash = stray.ContentHash }));
}
[Test]
public async Task AReadWhileAnotherWriterHoldsTheSequenceAnswersFromTheIndex()
{
var fx = await FixtureAsync();
var (sequence, _) = await UploadedAsync(fx, 2);
var projects = fx.Service.Projects;
var main = await projects.MainAsync(sequence.Id, fx.Ct);
using (Assert.NotNull(LeaseFile.TryAcquire(fx.Paths.LocksDirectory, $"seq-{sequence.Id:N}", "another process")))
{
var watch = System.Diagnostics.Stopwatch.StartNew();
Assert.Equal(main.Id, (await projects.ListAsync(sequence.Id, fx.Ct)).Single().Id);
Assert.Equal(main.HeadVersionId, (await projects.HeadAsync(main.Id, fx.Ct)).Id);
// Each read waits a moment for the lease, never the writers' whole wait.
Assert.Less(watch.Elapsed.TotalSeconds, TestTiming.Budget(15));
}
}
[Test]
public async Task AReorganizedSequenceKeepsItsProjects()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 3);
var projects = fx.Service.Projects;
var main = await projects.MainAsync(sequence.Id, fx.Ct);
var moved = "2026/Moved " + Guid.NewGuid().ToString("N")[..6];
Directory.CreateDirectory(Path.GetDirectoryName(fx.Paths.Sequence(moved).Folder)!);
Directory.Move(fx.Paths.Sequence(sequence.Folder).Folder, fx.Paths.Sequence(moved).Folder);
await fx.Db.Sequences.RelocateAsync(sequence.Id, moved, sequence.Title, fx.Ct);
var pushed = await projects.PushAsync(main.Id, Draft(await projects.HeadAsync(main.Id, fx.Ct), new ProjectSettings { ExcludedFrames = [1] }, frames), fx.Ct);
Assert.Equal(PushOutcome.Stored, pushed.Outcome);
Assert.FileExists(fx.Paths.Sequence(moved).VersionPath(main.Id, 2, pushed.Version!.Id));
}
}
public sealed class SqliteProjectServiceTests(TestContext context) : ProjectServiceTests(context)
{
protected override Backend Backend => Backend.SqliteFile;
}
[RequiresEnvironment(PgTestServer.Variable)]
public sealed class PostgresProjectServiceTests(TestContext context) : ProjectServiceTests(context)
{
protected override Backend Backend => Backend.Postgres;
}
@@ -0,0 +1,108 @@
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Data.Projects;
using Chronos.Data.Tests.Archiving;
using Chronos.Data.Tests.Projects;
using Chronos.Data.Workspaces;
using Chronos.Testing;
namespace Chronos.Data.Tests.Workspaces;
/// <summary>An archive with an uploaded sequence as the projects' home, and workspaces that edit it (owner review 2, R8).</summary>
internal sealed class WorkspaceFixture : IAsyncDisposable
{
private readonly TestContext _context;
private JobEngine? _engine;
private WorkspaceFixture(TestContext context, ArchiveFixture archive, Sequence sequence, List<Frame> frames)
{
_context = context;
Archive = archive;
Sequence = sequence;
Frames = frames;
Home = new ArchiveProjectHome(archive.Db, archive.Service.Projects, sequence.Id);
}
public ArchiveFixture Archive { get; }
public Sequence Sequence { get; set; }
public List<Frame> Frames { get; }
public ArchiveProjectHome Home { get; }
public ChronosDatabase Db => Archive.Db;
public CancellationToken Ct => Archive.Ct;
public static async Task<WorkspaceFixture> CreateAsync(TestContext context, ArchiveFixture archive, int frames = 5)
{
var (sequence, list) = await ProjectServiceTests.UploadedAsync(archive, frames);
return new WorkspaceFixture(context, archive, sequence, list);
}
/// <summary>A workspace of its own (another PC, or another folder of this one) and its sync.</summary>
public (WorkspaceStore Store, WorkspaceSync Sync) Workspace(string name = "workspace")
{
var store = new WorkspaceStore(Path.Combine(_context.CreateTempDirectory(name), "workspace"));
return (store, new WorkspaceSync(store, "Chronos on " + name) { LockWait = TimeSpan.FromSeconds(TestTiming.Budget(10)) });
}
/// <summary>Main of the sequence checked out into <paramref name="sync"/>'s workspace, its media copied.</summary>
public async Task<WorkspaceProject> CheckoutAsync(WorkspaceSync sync, Guid? projectId = null)
{
var id = projectId ?? (await Archive.Service.Projects.MainAsync(Sequence.Id, Ct)).Id;
var project = await sync.CheckoutAsync(Home, id, cancellationToken: Ct);
await CopyAsync(sync.Store, id);
return project;
}
/// <summary>Runs a workspace copy job to its end.</summary>
public async Task<Job> CopyAsync(WorkspaceStore store, Guid projectId, JobState expected = JobState.Done, string? checkpoint = null, string media = "proxies")
{
var engine = await EngineAsync();
var request = WorkspaceJobs.Copy(Sequence, store.Root, projectId, media);
var job = checkpoint is null ? await engine.EnqueueAsync(request, cancellationToken: Ct) : await Archive.EnqueueWithCheckpointAsync(engine, request, checkpoint);
return await Archive.WaitForAsync(job.Id, expected, (int)TestTiming.Budget(60));
}
private async Task<JobEngine> EngineAsync()
{
if (_engine is not null) return _engine;
_engine = new JobEngine(Db, [.. Archive.Service.CreateJobHandlers(), .. WorkspaceJobs.CreateHandlers(Db, Archive.Service)],
new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
await _engine.StartAsync(Ct);
return _engine;
}
public async ValueTask DisposeAsync()
{
if (_engine is not null) await _engine.DisposeAsync();
}
}
/// <summary>A home that cannot be reached, standing for a server out of reach or an archive offline.</summary>
internal sealed class UnreachableHome(IProjectHome home) : IProjectHome
{
public bool Reachable { get; set; }
private T Reach<T>(Func<T> call) => Reachable ? call() : throw new HomeUnavailableException("The home cannot be reached.");
public Task<HomeSequence> SequenceAsync(CancellationToken cancellationToken) => Reach(() => home.SequenceAsync(cancellationToken));
public Task<IReadOnlyList<SequenceProject>> ListAsync(CancellationToken cancellationToken) => Reach(() => home.ListAsync(cancellationToken));
public Task<SequenceProject> CreateAsync(string name, Guid? fromVersionId, string? author, CancellationToken cancellationToken) =>
Reach(() => home.CreateAsync(name, fromVersionId, author, cancellationToken));
public Task<ProjectVersion> HeadAsync(Guid projectId, CancellationToken cancellationToken) => Reach(() => home.HeadAsync(projectId, cancellationToken));
public Task<ProjectVersion?> GetVersionAsync(Guid projectId, Guid versionId, CancellationToken cancellationToken) =>
Reach(() => home.GetVersionAsync(projectId, versionId, cancellationToken));
public Task<IReadOnlyList<ProjectVersion>> VersionsAfterAsync(Guid projectId, int afterNumber, int limit, CancellationToken cancellationToken) =>
Reach(() => home.VersionsAfterAsync(projectId, afterNumber, limit, cancellationToken));
public Task<IReadOnlyList<ProjectVersion>> HistoryAsync(Guid projectId, int? beforeNumber, int limit, CancellationToken cancellationToken) =>
Reach(() => home.HistoryAsync(projectId, beforeNumber, limit, cancellationToken));
public Task<PushResult> PushAsync(Guid projectId, ProjectVersion version, CancellationToken cancellationToken) =>
Reach(() => home.PushAsync(projectId, version, cancellationToken));
public Task<HomeFrames> FramesAsync(CancellationToken cancellationToken) => Reach(() => home.FramesAsync(cancellationToken));
}
@@ -0,0 +1,389 @@
using Chronos.Data.Tests.Projects;
using System.Security.Cryptography;
using Chronos.Core.Archiving;
using Chronos.Core.Localization;
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 (owner review 2, R8): its folder, the copy of a sequence's proxies, and sync with the archive as home.</summary>
[Category("workspace")]
public abstract class WorkspaceTests(TestContext context) : DatabaseTest(context)
{
private async Task<WorkspaceFixture> FixtureAsync(int frames = 5)
{
var archive = Own(await ArchiveFixture.CreateAsync(Context, database: await NewOptionsAsync(multiConnection: true)));
return Own(await WorkspaceFixture.CreateAsync(Context, archive, frames));
}
private static string Sha(string path) => Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(path)));
/// <summary>The working state edited as the editor does: read, changed, stored.</summary>
private static async Task<ProjectSettings> EditAsync(WorkspaceSync sync, Guid projectId, Func<ProjectSettings, ProjectSettings> edit, CancellationToken ct)
{
var session = await sync.OpenAsync(projectId, ct);
var edited = edit(session.Working);
await sync.SaveAsync(projectId, edited, ct);
return edited;
}
[Test]
public void TheWorkspaceFolderHasItsManifestAndProjectFolders()
{
var root = Path.Combine(Context.CreateTempDirectory("ws"), "workspace");
var store = new WorkspaceStore(root);
Assert.FileExists(Path.Combine(root, WorkspaceStore.ManifestFile));
Assert.Equal((WorkspaceStore.FormatName, 1), (store.Manifest.Format, store.Manifest.FormatVersion));
Assert.Equal(store.Id, new WorkspaceStore(root).Id);
Assert.Empty(store.List());
// Only folders named by a project id that hold a working state are projects.
Directory.CreateDirectory(Path.Combine(root, "notes"));
var empty = Guid.CreateVersion7();
Directory.CreateDirectory(Path.Combine(root, empty.ToString("N")));
Assert.Empty(store.List());
Assert.Null(store.Find(empty));
var project = store.Project(empty);
Assert.Equal(Path.Combine(root, empty.ToString("N"), "media", "proxies"), project.ProxiesDirectory);
Assert.Equal("proxies/" + empty.ToString("N") + ".jpg", WorkspaceProject.ProxyName(empty));
File.WriteAllText(Path.Combine(root, WorkspaceStore.ManifestFile), """{ "format": "chronos-workspace", "formatVersion": 7, "id": "0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01" }""");
Assert.Throws<InvalidDataException>(() => new WorkspaceStore(root));
}
[Test]
public async Task AProjectIsHeldByOneWriterAtATime()
{
var store = new WorkspaceStore(Path.Combine(Context.CreateTempDirectory("ws"), "workspace"));
var project = store.Project(Guid.CreateVersion7());
using (await project.LockAsync(TimeSpan.FromSeconds(1), Ct))
await Assert.ThrowsAsync<LeaseUnavailableException>(() => project.LockAsync(TimeSpan.FromMilliseconds(200), Ct));
using (await project.LockAsync(TimeSpan.FromSeconds(TestTiming.Budget(5)), Ct))
{
}
}
[Test]
public async Task TheCopyBringsVerifiedProxiesAndTheWorkingStateFollowsItsFrames()
{
var fx = await FixtureAsync();
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, cancellationToken: fx.Ct);
Assert.Equal(WorkspaceState.MediaRemoved, (await sync.StatusAsync(main.Id, fx.Home, fx.Ct)).State);
Assert.Null((await sync.OpenAsync(main.Id, fx.Ct)).Sequence);
var job = await fx.CopyAsync(store, main.Id);
Assert.Contains(Loc.L("Archive.Log.WorkspaceCopied", fx.Sequence.DisplayTitle, 5, 0, 0, 0), job.LogTail!);
var media = Assert.NotNull(project.ReadMedia());
Assert.Equal((BundleMedia.Proxies, fx.Sequence.Id, fx.Frames.Count), (media.Kind, media.SequenceId, media.Frames.Count));
foreach (var (frame, entry) in fx.Frames.Zip(media.Frames))
{
Assert.Equal((frame.Id, frame.Sha256), (entry.Id, entry.Sha256));
var file = project.MediaFile(entry.File!);
Assert.Equal(entry.FileSha256, Sha(file));
// The archive's own proxy, copied byte for byte.
Assert.Equal(Sha(fx.Archive.Paths.Sequence(fx.Sequence.Folder).Proxy(frame.Index)), entry.FileSha256);
}
var session = await sync.OpenAsync(main.Id, fx.Ct);
var opened = Assert.NotNull(session.Sequence);
Assert.Equal(5, opened.Files.Count(f => f is not null));
Assert.Equal((WorkspaceState.InSync, 0), ((await sync.StatusAsync(main.Id, fx.Home, fx.Ct)).State, (await sync.StatusAsync(main.Id, fx.Home, fx.Ct)).Ahead));
// Positions on the copied frames follow their photos when the home's frames change and the copy runs again.
await EditAsync(sync, main.Id, s => s with { ExcludedFrames = [2] }, fx.Ct);
var (path, size, sha) = fx.Archive.Stage(ArchiveFixture.Start.AddSeconds(-30), 999);
await fx.Archive.Service.Ingest.CommitAsync(new Chronos.Data.Archiving.IngestRequest(fx.Archive.Archive.Id, fx.Sequence.Id, null, null, path, "IMG_0000.JPG",
size, sha, null, null), fx.Ct);
fx.Sequence = (await fx.Db.Sequences.GetAsync(fx.Sequence.Id))!;
await fx.CopyAsync(store, main.Id);
var moved = await sync.OpenAsync(main.Id, fx.Ct);
Assert.Equal(6, moved.Media!.Frames.Count);
Assert.SequenceEqual([3], moved.Working.ExcludedFrames);
Assert.Equal(fx.Frames[2].Id, moved.Media.Frames[3].Id);
}
[Test]
public async Task ACopyResumesFromItsCheckpointAndRewritesWhatDoesNotMatch()
{
var fx = await FixtureAsync();
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, cancellationToken: fx.Ct);
await fx.CopyAsync(store, main.Id);
var copied = project.ReadMedia()!;
// An earlier run copied the first two before it stopped; a later file was left damaged.
File.WriteAllText(project.MediaFile(copied.Frames[3].File!), "not a photo");
File.Delete(project.MediaIndexPath);
var job = await fx.CopyAsync(store, main.Id, checkpoint: "copy:2");
Assert.Contains(Loc.L("Archive.Log.WorkspaceCopied", fx.Sequence.DisplayTitle, 1, 0, 4, 0), job.LogTail!);
var media = Assert.NotNull(project.ReadMedia());
Assert.SequenceEqual(copied.Frames.Select(f => f.FileSha256), media.Frames.Select(f => f.FileSha256));
Assert.Equal(copied.Frames[3].FileSha256, Sha(project.MediaFile(media.Frames[3].File!)));
}
[Test]
public async Task CopyingTheOriginalsIsRefusedForNowWithItsReason()
{
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);
}
[Test]
public async Task AVersionSavedHereIsPushedAndBecomesTheSequenceSettings()
{
var fx = await FixtureAsync();
var (_, sync) = fx.Workspace();
var project = await fx.CheckoutAsync(sync);
var id = project.ProjectId;
Assert.Null(await sync.CommitAsync(id, cancellationToken: fx.Ct));
await EditAsync(sync, id, s => s with { ExcludedFrames = [1, 4], Exposure = s.Exposure with { ExposureOffsetEv = 0.4 } }, fx.Ct);
Assert.Equal(WorkspaceState.Modified, (await sync.StatusAsync(id, fx.Home, fx.Ct)).State);
var version = Assert.NotNull(await sync.CommitAsync(id, "warmer", "alberto", fx.Ct));
Assert.Equal((ProjectVersionKind.Commit, 2, "warmer", (DateTimeOffset?)null), (version.Kind, version.Number, version.Note, version.StoredAt));
var status = await sync.StatusAsync(id, fx.Home, fx.Ct);
Assert.Equal((WorkspaceState.Ahead, 1, false), (status.State, status.Ahead, status.Modified));
var pushed = await sync.PushAsync(id, fx.Home, fx.Ct);
Assert.Equal(version.Id, pushed.Pushed.Single().Id);
Assert.Equal(WorkspaceState.InSync, pushed.Status.State);
Assert.NotNull(project.Versions().Single(v => v.Id == version.Id).StoredAt);
var sequence = (await fx.Db.Sequences.GetAsync(fx.Sequence.Id))!;
var settings = ProjectSettings.FromJson(sequence.SettingsJson!);
Assert.SequenceEqual([1, 4], settings.ExcludedFrames);
Assert.Equal(0.4, settings.Exposure.ExposureOffsetEv);
// Nothing else to push; the home's head is ours.
Assert.Empty((await sync.PushAsync(id, fx.Home, fx.Ct)).Pushed);
Assert.Equal(version.Id, (await fx.Home.HeadAsync(id, fx.Ct)).Id);
}
[Test]
public async Task AnotherWorkspacesPushIsPulledIntoTheWorkingState()
{
var fx = await FixtureAsync();
var (_, one) = fx.Workspace("one");
var (_, two) = fx.Workspace("two");
var id = (await fx.CheckoutAsync(one)).ProjectId;
await fx.CheckoutAsync(two, id);
await EditAsync(one, id, s => s with { Stack = new StackSettings { Mode = StackSetting.Median, Length = 5 } }, fx.Ct);
await one.CommitAsync(id, cancellationToken: fx.Ct);
await one.PushAsync(id, fx.Home, fx.Ct);
// Two has a change of its own not saved as a version yet: it stays, on top of what one pushed.
await EditAsync(two, id, s => s with { ExcludedFrames = [0] }, fx.Ct);
Assert.Equal((WorkspaceState.Behind, 1), ((await two.StatusAsync(id, fx.Home, fx.Ct)).State, (await two.StatusAsync(id, fx.Home, fx.Ct)).Behind));
var pulled = await two.PullAsync(id, fx.Home, fx.Ct);
Assert.Equal(1, pulled.Pulled.Count);
Assert.Equal(WorkspaceState.Modified, pulled.Status.State);
var working = (await two.OpenAsync(id, fx.Ct)).Working;
Assert.Equal((StackSetting.Median, 5), (working.Stack.Mode, working.Stack.Length));
Assert.SequenceEqual([0], working.ExcludedFrames);
}
[Test]
public async Task SeveralLocalVersionsAreReplayedOnTopOfTheHomesWhenItMovedMeanwhile()
{
var fx = await FixtureAsync();
var (_, one) = fx.Workspace("one");
var (_, two) = fx.Workspace("two");
var project = await fx.CheckoutAsync(one);
var id = project.ProjectId;
await fx.CheckoutAsync(two, id);
await EditAsync(two, id, s => s with { Exposure = s.Exposure with { DeflickerStrength = new Auto<double>().WithManual(0.6) } }, fx.Ct);
await two.CommitAsync(id, cancellationToken: fx.Ct);
await two.PushAsync(id, fx.Home, fx.Ct);
// One saved two versions meanwhile, excluding another photo than two would have and changing other settings.
await EditAsync(one, id, s => s with { Exposure = s.Exposure with { ExposureOffsetEv = 0.3 } }, fx.Ct);
var first = (await one.CommitAsync(id, "offset", cancellationToken: fx.Ct))!;
await EditAsync(one, id, s => s with { ExcludedFrames = [3], Stack = new StackSettings { Mode = StackSetting.Mean } }, fx.Ct);
var second = (await one.CommitAsync(id, "stack", cancellationToken: fx.Ct))!;
Assert.Equal(2, (await one.StatusAsync(id, cancellationToken: fx.Ct)).Ahead);
var pushed = await one.PushAsync(id, fx.Home, fx.Ct);
Assert.Equal(1, pushed.Pulled.Count);
Assert.SequenceEqual([3, 4], pushed.Pushed.Select(v => v.Number));
Assert.SequenceEqual(["offset", "stack"], pushed.Pushed.Select(v => v.Note));
Assert.False(pushed.Pushed.Any(v => v.Id == first.Id || v.Id == second.Id), "replayed versions are new versions");
Assert.Equal(WorkspaceState.InSync, pushed.Status.State);
var head = await fx.Home.HeadAsync(id, fx.Ct);
var settings = ProjectSettings.FromJson(ProjectContent.Place(head.SettingsJson, ProjectServiceTests.Photos(fx.Frames)));
Assert.Equal((0.6, 0.3, StackSetting.Mean), (settings.Exposure.DeflickerStrength.Resolve(1), settings.Exposure.ExposureOffsetEv, settings.Stack.Mode));
Assert.SequenceEqual([3], settings.ExcludedFrames);
// The first replayed version holds one's first change on top of two's, without the later ones.
var replayed = ProjectSettings.FromJson(pushed.Pushed[0].SettingsJson);
Assert.Equal((0.6, 0.3, StackSetting.None), (replayed.Exposure.DeflickerStrength.Resolve(1), replayed.Exposure.ExposureOffsetEv, replayed.Stack.Mode));
// The versions as they were saved are kept.
Assert.Equal(2, Directory.GetFiles(Path.Combine(project.VersionsDirectory, WorkspaceProject.ReplacedFolder)).Length);
}
[Test]
public async Task ExcludingDifferentPhotosOnEachSideMergesWithoutAConflict()
{
var fx = await FixtureAsync();
var (_, one) = fx.Workspace("one");
var (_, two) = fx.Workspace("two");
var id = (await fx.CheckoutAsync(one)).ProjectId;
await fx.CheckoutAsync(two, id);
await EditAsync(one, id, s => s with { ExcludedFrames = [1] }, fx.Ct);
await one.CommitAsync(id, cancellationToken: fx.Ct);
await one.PushAsync(id, fx.Home, fx.Ct);
await EditAsync(two, id, s => s with { ExcludedFrames = [3] }, fx.Ct);
await two.CommitAsync(id, cancellationToken: fx.Ct);
var pushed = await two.PushAsync(id, fx.Home, fx.Ct);
Assert.Equal(WorkspaceState.InSync, pushed.Status.State);
Assert.SequenceEqual([1, 3], ProjectSettings.FromJson((await fx.Db.Sequences.GetAsync(fx.Sequence.Id))!.SettingsJson!).ExcludedFrames);
}
[Test]
public async Task TheSameSettingChangedOnBothSidesIsAConflictToSettle()
{
var fx = await FixtureAsync();
var (_, one) = fx.Workspace("one");
var (_, two) = fx.Workspace("two");
var id = (await fx.CheckoutAsync(one)).ProjectId;
await fx.CheckoutAsync(two, id);
await EditAsync(one, id, s => s with { Exposure = s.Exposure with { ExposureOffsetEv = 0.5 } }, fx.Ct);
await one.CommitAsync(id, cancellationToken: fx.Ct);
await one.PushAsync(id, fx.Home, fx.Ct);
await EditAsync(two, id, s => s with { Exposure = s.Exposure with { ExposureOffsetEv = 1.0 }, Stack = new StackSettings { Mode = StackSetting.Median } }, fx.Ct);
await two.CommitAsync(id, cancellationToken: fx.Ct);
var stopped = await two.PushAsync(id, fx.Home, fx.Ct);
Assert.Empty(stopped.Pushed);
Assert.Equal(WorkspaceState.Conflict, stopped.Status.State);
var difference = stopped.Status.Conflict!.Differences.Single();
Assert.Equal(("exposure.exposureOffsetEv", "1", "0.5"), (difference.Path, difference.Mine, difference.Theirs));
await Assert.ThrowsAsync<InvalidOperationException>(() => two.CommitAsync(id, cancellationToken: fx.Ct));
// Take the server's value there: the other change of this workspace stays, and is pushed.
var settled = await two.ResolveAsync(id, fx.Home, ConflictChoice.TakeServer, cancellationToken: fx.Ct);
Assert.Equal(WorkspaceState.Ahead, settled.Status.State);
Assert.Equal(ProjectVersionKind.Merge, two.Unpushed(id).Single().Kind);
await two.PushAsync(id, fx.Home, fx.Ct);
var head = ProjectSettings.FromJson((await fx.Home.HeadAsync(id, fx.Ct)).SettingsJson);
Assert.Equal((0.5, StackSetting.Median), (head.Exposure.ExposureOffsetEv, head.Stack.Mode));
}
[Test]
public async Task KeepMineWinsWhereBothChangedAndSaveBothKeepsEachSide()
{
var fx = await FixtureAsync();
var (_, one) = fx.Workspace("one");
var (_, two) = fx.Workspace("two");
var (_, three) = fx.Workspace("three");
var id = (await fx.CheckoutAsync(one)).ProjectId;
await fx.CheckoutAsync(two, id);
await fx.CheckoutAsync(three, id);
await EditAsync(one, id, s => s with { Exposure = s.Exposure with { ExposureOffsetEv = 0.5 } }, fx.Ct);
await one.CommitAsync(id, cancellationToken: fx.Ct);
await one.PushAsync(id, fx.Home, fx.Ct);
await EditAsync(two, id, s => s with { Exposure = s.Exposure with { ExposureOffsetEv = -1 } }, fx.Ct);
await two.CommitAsync(id, cancellationToken: fx.Ct);
Assert.Equal(WorkspaceState.Conflict, (await two.PullAsync(id, fx.Home, fx.Ct)).Status.State);
await two.ResolveAsync(id, fx.Home, ConflictChoice.KeepMine, cancellationToken: fx.Ct);
await two.PushAsync(id, fx.Home, fx.Ct);
Assert.Equal(-1, ProjectSettings.FromJson((await fx.Home.HeadAsync(id, fx.Ct)).SettingsJson).Exposure.ExposureOffsetEv);
await EditAsync(three, id, s => s with { Exposure = s.Exposure with { ExposureOffsetEv = 2 } }, fx.Ct);
await three.CommitAsync(id, "bright", cancellationToken: fx.Ct);
await EditAsync(three, id, s => s with { Stack = new StackSettings { Mode = StackSetting.StarTrails } }, fx.Ct);
Assert.Equal(WorkspaceState.Conflict, (await three.PushAsync(id, fx.Home, fx.Ct)).Status.State);
var both = await three.ResolveAsync(id, fx.Home, ConflictChoice.SaveBoth, cancellationToken: fx.Ct);
// Three's versions (its unsaved change saved first) live on in a new project; this project is the home's again.
var copy = Assert.NotNull(both.SavedAs);
Assert.Equal("Main (2)", copy.Name);
Assert.Equal(2, both.Pushed.Count);
var kept = ProjectSettings.FromJson((await fx.Home.HeadAsync(copy.Id, fx.Ct)).SettingsJson);
Assert.Equal((2, StackSetting.StarTrails), (kept.Exposure.ExposureOffsetEv, kept.Stack.Mode));
Assert.Equal(WorkspaceState.InSync, both.Status.State);
Assert.Equal(-1, (await three.OpenAsync(id, fx.Ct)).Working.Exposure.ExposureOffsetEv);
Assert.Equal(2, (await fx.Home.ListAsync(fx.Ct)).Count);
}
[Test]
public async Task ARestoredVersionIsTheWorkingStateAndTheNextVersionSaysSo()
{
var fx = await FixtureAsync();
var (_, sync) = fx.Workspace();
var id = (await fx.CheckoutAsync(sync)).ProjectId;
var original = await fx.Home.HeadAsync(id, fx.Ct);
await EditAsync(sync, id, s => s with { ExcludedFrames = [2] }, fx.Ct);
await sync.CommitAsync(id, cancellationToken: fx.Ct);
// An unsaved change before the restore is saved as a version first.
await EditAsync(sync, id, s => s with { Stack = new StackSettings { Mode = StackSetting.Mean } }, fx.Ct);
var restored = await sync.RestoreAsync(id, original.Id, fx.Home, fx.Ct);
Assert.Empty(restored.ExcludedFrames);
Assert.Equal(2, sync.Unpushed(id).Count);
await EditAsync(sync, id, s => s with { Exposure = s.Exposure with { ExposureOffsetEv = 0.1 } }, fx.Ct);
var version = Assert.NotNull(await sync.CommitAsync(id, cancellationToken: fx.Ct));
Assert.Equal((ProjectVersionKind.Restore, original.Id), (version.Kind, version.RestoredFrom));
await EditAsync(sync, id, s => s with { Exposure = s.Exposure with { ExposureOffsetEv = 0.2 } }, fx.Ct);
var next = Assert.NotNull(await sync.CommitAsync(id, cancellationToken: fx.Ct));
Assert.Equal((ProjectVersionKind.Commit, (Guid?)null), (next.Kind, next.RestoredFrom));
}
[Test]
public async Task AHomeOutOfReachIsOfflineAndTheWorkWaits()
{
var fx = await FixtureAsync();
var (_, sync) = fx.Workspace();
var id = (await fx.CheckoutAsync(sync)).ProjectId;
var away = new UnreachableHome(fx.Home);
await EditAsync(sync, id, s => s with { ExcludedFrames = [0] }, fx.Ct);
await sync.CommitAsync(id, cancellationToken: fx.Ct);
var status = await sync.StatusAsync(id, away, fx.Ct);
Assert.Equal((WorkspaceState.Offline, 1, true), (status.State, status.Ahead, status.Offline));
await Assert.ThrowsAsync<HomeUnavailableException>(() => sync.PushAsync(id, away, fx.Ct));
away.Reachable = true;
Assert.Equal(WorkspaceState.InSync, (await sync.PushAsync(id, away, fx.Ct)).Status.State);
}
[Test]
public async Task SettingsOfANewerChronosOpenReadOnly()
{
var fx = await FixtureAsync(2);
var (_, sync) = fx.Workspace();
var project = await fx.CheckoutAsync(sync);
var bundle = project.ReadBundle();
File.WriteAllText(project.BundlePath, bundle.ToJson().Replace("\"version\": 1", "\"version\": 2", StringComparison.Ordinal));
var session = await sync.OpenAsync(project.ProjectId, fx.Ct);
Assert.True(session.IsReadOnly);
await Assert.ThrowsAsync<InvalidOperationException>(() => sync.SaveAsync(project.ProjectId, new ProjectSettings(), fx.Ct));
await Assert.ThrowsAsync<InvalidOperationException>(() => sync.CommitAsync(project.ProjectId, cancellationToken: fx.Ct));
Assert.True((await sync.StatusAsync(project.ProjectId, cancellationToken: fx.Ct)).ReadOnly);
}
}
public sealed class SqliteWorkspaceTests(TestContext context) : WorkspaceTests(context)
{
protected override Backend Backend => Backend.SqliteFile;
}
[RequiresEnvironment(PgTestServer.Variable)]
public sealed class PostgresWorkspaceTests(TestContext context) : WorkspaceTests(context)
{
protected override Backend Backend => Backend.Postgres;
}