feat(app): workspace projects whose home is a server, pushed and pulled like this PC's archive

Owner review 2, R8, phase 5b (client part), ported onto the final phase 5a.
A Chronos Server with the "projects" capability is now the home of
workspace projects. A server sequence is edited in the workspace like a
local one, not inside the library, and its versions sync with the server
"like git".

- Data: ServerProjectHome is an IProjectHome over ChronosClient.
  - These are HomeUnavailableException, so the workspace shows Offline: a
    server out of reach, an expired sign-in, a 503 (lease, offline archive,
    projects_unreadable), a 409 folder_in_use, and a server without projects.
  - 404 sequence/project/version and refused names are ProjectException;
    other refusals keep their meaning.
  - A deleted project's head is 404 project, so final 5a's HeadAsync NotFound
    rule reads it as Gone. The original 5b's IsLiveAsync and
    WorkspaceStatus.Gone are dropped. IProjectHome gains rename and delete.
- Data: WorkspaceJobs.CopyFromServer downloads into the workspace, through
  the desktop's session, the proxies of one frames version (or the
  thumbnails standing in for them), with the aliases of the server's
  conversions. It is rebuilt on final 5a's copy handler:
  - the copy:frame:fv:folder checkpoint, EnsureSpace (from the server's proxy
    sizes), WritingMedia, and the cancelled-copy clean-up;
  - the editor's current file is never overwritten;
  - each file is hashed as it arrives and checked on disk, four at a time.
  It never writes this PC's archive. Originals are still refused until 5c.
- Data: SyncAgent passes on the server's projectChanged events, and after a
  lost event stream it reports that changes may have been missed.
- App: SyncHost gives the server home over one session client. The Server
  screen offers Open in workspace, disabled with its reason on older
  servers, whose sequences keep opening with proxies.
- App: Edit opens or checks out server projects with final 5a's refusals:
  unreadable copies, a disabled damaged or newer Main, a refused folder. The
  "sequence left the index" refusal now applies only to projects of this
  PC's archive.
- App: the picker and the chip follow projectChanged (Server newer, Not on
  server). Every state, conflict, delete, remove and failure text uses its
  ".Server" form when one exists (WorkspaceText.ForHome). That includes 5a's
  newer-format conflict, the save conflict, the taken-values toast, Gone and
  version-too-large.
- App: a render of a server project first offers to send what is not on the
  server, then renders the version the server holds. Offline, Gone, Damaged
  and missing media hold the render. Analyses and renders run as server jobs
  (ServerJobs, shared with RemoteSequenceSource).
- Pruning keeps final 5a's rule: a version is pruned only after HoldsAsync
  reads it back.
- Strings in en and it; ARCHITECTURE, DECISIONS and CHANGELOG.

Tests:
- ServerProjectHome error mapping, using a fake handler.
- Against the in-process server:
  - two workspaces on one project: fast-forward, replay and merge, keep mine,
    take server, save both, restore;
  - the copy job verifying, resuming and following new frames;
  - a project deleted on the server (Gone from its head; a push sends
    nothing);
  - an offline server.
- SyncAgent project events.
- App tests for the host, the project menu and renders of a server home.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-04 11:45:06 +01:00
1 parent e2ecc409a3
commit 26bab759fe
48 files changed
+3243 -409

No files matched your search

@@ -48,8 +48,10 @@ public sealed class SyncTextTests
{
Assert.SequenceEqual([SyncAction.Upload], SyncText.Actions(Entry(SyncStatus.LocalOnly, link: null), Editor));
Assert.Empty(SyncText.Actions(Entry(SyncStatus.LocalOnly, link: null), Viewer));
Assert.SequenceEqual([SyncAction.OpenWithProxies, SyncAction.DownloadOriginals], SyncText.Actions(Entry(SyncStatus.RemoteOnly, local: null), Editor));
Assert.SequenceEqual([SyncAction.OpenWithProxies], SyncText.Actions(Entry(SyncStatus.ProxiesOnly, local: null), Viewer));
// A server that keeps no projects opens its sequences with proxies; the workspace is offered disabled (owner review 2, R8).
Assert.SequenceEqual([SyncAction.OpenWithProxies, SyncAction.DownloadOriginals, SyncAction.OpenInWorkspace],
SyncText.Actions(Entry(SyncStatus.RemoteOnly, local: null), Editor));
Assert.SequenceEqual([SyncAction.OpenWithProxies, SyncAction.OpenInWorkspace], SyncText.Actions(Entry(SyncStatus.ProxiesOnly, local: null), Viewer));
Assert.SequenceEqual([SyncAction.Upload], SyncText.Actions(Entry(SyncStatus.LocalAhead, Link with { MissingRemote = 4 }), Editor));
Assert.SequenceEqual([SyncAction.DownloadOriginals], SyncText.Actions(Entry(SyncStatus.ServerAhead, Link with { MissingLocal = 2 }), Editor));
Assert.SequenceEqual([SyncAction.SyncSettings], SyncText.Actions(Entry(SyncStatus.ServerAhead), Editor));
@@ -74,6 +76,37 @@ public sealed class SyncTextTests
Assert.SequenceEqual([SyncAction.Resume], SyncText.Actions(Entry(SyncStatus.Transferring, transfer: Upload(JobState.Paused)), Editor));
}
[Test]
public async Task AServerThatKeepsProjectsOpensItsSequencesInTheWorkspace()
{
// Owner review 2, R8, phase 5b: the workspace replaces Open with proxies, and the originals can still come down.
var projects = Editor with { KeepsProjects = true };
Assert.SequenceEqual([SyncAction.OpenInWorkspace, SyncAction.DownloadOriginals], SyncText.Actions(Entry(SyncStatus.RemoteOnly, local: null), projects));
Assert.SequenceEqual([SyncAction.OpenInWorkspace], SyncText.Actions(Entry(SyncStatus.ProxiesOnly, local: null), Viewer with { KeepsProjects = true }));
Assert.True(SyncText.IsEnabled(SyncAction.OpenInWorkspace, projects), "a server that keeps projects opens them");
Assert.Equal(Loc.L("Tooltips.Server.Sync.OpenInWorkspace"), SyncText.ToolTip(Entry(SyncStatus.RemoteOnly, local: null), SyncAction.OpenInWorkspace, projects));
// An older server's row says why its workspace action is disabled; the other actions are not.
Assert.False(SyncText.IsEnabled(SyncAction.OpenInWorkspace, Editor), "an older server keeps no projects");
Assert.True(SyncText.IsEnabled(SyncAction.OpenWithProxies, Editor), "proxies open as before");
Assert.Equal(Loc.L("Tooltips.Server.Sync.OpenInWorkspace.NoProjects"), SyncText.ToolTip(Entry(SyncStatus.RemoteOnly, local: null), SyncAction.OpenInWorkspace, Editor));
// The row's button is disabled with its reason, and enabled once the server keeps projects.
var acted = new List<SyncAction>();
var row = new SyncRow(Entry(SyncStatus.RemoteOnly, local: null), Editor, (_, action) =>
{
acted.Add(action);
return Task.CompletedTask;
});
var workspace = row.Actions.Single(a => a.Action == SyncAction.OpenInWorkspace);
Assert.Equal((false, Loc.L("Tooltips.Server.Sync.OpenInWorkspace.NoProjects")), (workspace.Command.CanExecute(null), workspace.ToolTip));
row.Update(Entry(SyncStatus.RemoteOnly, local: null), projects);
workspace = row.Actions.First();
Assert.Equal((SyncAction.OpenInWorkspace, true), (workspace.Action, workspace.Command.CanExecute(null)));
workspace.Command.Execute(null);
await Task.Yield();
Assert.SequenceEqual([SyncAction.OpenInWorkspace], acted);
}
[Test]
public void ColumnsSayWhatEachSideHolds()
{
@@ -0,0 +1,302 @@
using System.Globalization;
using System.Text.Json;
using Chronos.App.Editor;
using Chronos.App.Infrastructure;
using Chronos.App.Workspace;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Windows.Shell;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Projects;
using Chronos.Data.Workspaces;
using Chronos.Protocol;
using Chronos.Testing;
using Chronos.Ui.Controls;
namespace Chronos.App.Tests.Workspace;
/// <summary>
/// Workspace projects whose home is a server (owner review 2, R8, phase 5b), as the desktop handles them: the home asked
/// through the signed-in session (offline without it), the copy downloaded from the server, the states the server's
/// changes and deletions lead to, its texts, and renders of what the server holds only. The server here is this PC's
/// archive seen through a home that names a server, so its versions, pushes and merges are the engine's own.
/// </summary>
[Category("workspace")]
public sealed class ServerHomeTests(TestContext context)
{
private const string Server = "https://nas.test:8443";
static ServerHomeTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
[Test]
public async Task TheServerIsTheHomeWhileThisPcIsSignedInToIt()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host();
var named = ServerHome(bed);
Assert.Null(host.HomeOf(named), "no session: the server cannot be asked");
await Assert.ThrowsAsync<HomeUnavailableException>(() => host.HomeProjectsAsync(named, bed.Ct));
Assert.Equal(Loc.L("Errors.Workspace.Offline.Server"), WorkspaceText.Failure(new HomeUnavailableException("down"), server: true));
var server = new FakeServer(bed);
Connect(host, server);
Assert.Same(server, host.HomeOf(named));
Assert.Null(host.HomeOf(named with { Server = "https://elsewhere:8443" }), "another server than the session's");
Assert.Equal("Main", (await host.HomeProjectsAsync(named, bed.Ct)).Single().Name);
// Checked out from the server: its media are downloaded by a copy job that names the server, never this PC's archive.
var checkout = await host.CheckoutAsync(named, null, null, cancellationToken: bed.Ct);
var bundle = host.Store.Find(checkout.Project.Id)!.ReadBundle();
Assert.Equal((BundleHome.ServerKind, Server, bed.SequenceId), (bundle.Workspace!.Home.Kind, bundle.Workspace.Home.Server, bundle.Workspace.Home.SequenceId));
using (var parameters = JsonDocument.Parse(checkout.Copy.ParametersJson!))
{
var root = parameters.RootElement;
Assert.Equal((Server, checkout.Project.Id.ToString(), BundleMedia.Proxies),
(root.GetProperty("server").GetString(), root.GetProperty("projectId").GetString(), root.GetProperty("media").GetString()));
}
Assert.SequenceEqual([bed.SequenceId], checkout.Copy.TargetIds);
// This test bed's engine has no session to download through: the job says to connect.
var failed = await bed.WaitForJobAsync(checkout.Copy.Id, JobState.Failed);
Assert.Equal(Loc.L("Errors.Sync.NotConnected"), failed.Error);
var entry = Assert.NotNull(await host.FindAsync(checkout.Project.Id));
Assert.True(entry.IsServerHome && !entry.HasMedia, "listed as the server's, without media yet");
}
[Test]
public async Task AServerProjectsStateFollowsWhatTheServerSays()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var server = new FakeServer(bed);
Connect(host, server);
var projectId = await CheckoutAsync(bed, host);
var status = await host.StatusAsync(projectId, cancellationToken: bed.Ct);
Assert.Equal(WorkspaceState.InSync, status.State);
Assert.Equal(Loc.L("Tooltips.Editor.Workspace.State.InSync.Server"), WorkspaceText.StateToolTip(status, server: true));
// Another PC sends a version: this one reads as Server newer.
var other = bed.Host(name: "other-pc");
var otherId = await bed.CheckoutAsync(other);
Assert.Equal(projectId, otherId);
var session = await other.Sync.OpenAsync(projectId, bed.Ct);
await other.Sync.SaveAsync(projectId, session.Working with { HeroFrame = 2 }, bed.Ct);
await other.SaveVersionAsync(projectId, null, bed.Ct);
status = await host.StatusAsync(projectId, cancellationToken: bed.Ct);
Assert.Equal((WorkspaceState.Behind, 1), (status.State, status.Behind));
Assert.Equal(Loc.L("Editor.Workspace.State.Behind.Server"), WorkspaceText.State(status, server: true));
Assert.Equal(Loc.L("Editor.Workspace.State.Behind"), WorkspaceText.State(status));
Assert.Equal(Loc.L("Tooltips.Editor.Workspace.State.Behind.Server", "1"), WorkspaceText.StateToolTip(status, server: true));
// Signed out, or the server out of reach: offline, its work kept.
server.Reachable = false;
Assert.Equal(WorkspaceState.Offline, (await host.StatusAsync(projectId, cancellationToken: bed.Ct)).State);
server.Reachable = true;
host.ServerHomes = null;
status = await host.StatusAsync(projectId, cancellationToken: bed.Ct);
Assert.Equal((WorkspaceState.Offline, true), (status.State, status.Offline));
Assert.Equal(Loc.L("Tooltips.Editor.Workspace.State.Offline.Server"), WorkspaceText.StateToolTip(status, server: true));
Connect(host, server);
// Deleted on the server (its head answers 404 project): not on the server, with its copy kept here as it was.
server.Deleted.Add(projectId);
status = await host.StatusAsync(projectId, cancellationToken: bed.Ct);
Assert.Equal((WorkspaceState.Gone, 0), (status.State, status.Behind));
Assert.Equal(Loc.L("Editor.Workspace.State.Gone.Server"), WorkspaceText.State(status, server: true));
Assert.Equal(Loc.L("Tooltips.Editor.Workspace.State.Gone.Server"), WorkspaceText.StateToolTip(status, server: true));
Assert.Equal(StatusKind.Warning, WorkspaceText.Kind(status));
Assert.NotNull(host.Store.Find(projectId)?.ReadMedia());
// A server that answers 404 for the project itself (deleted with its sequence) is gone too.
server.Deleted.Clear();
server.Missing = true;
Assert.Equal(WorkspaceState.Gone, (await host.StatusAsync(projectId, cancellationToken: bed.Ct)).State);
}
[Test]
public void TheServersProjectChangesReachOnlyTheProjectsItIsHomeOf()
{
var local = context.CreateTempDirectory("local");
var environment = AppEnvironment.From(AppPaths.Resolve(context.CreateTempDirectory("app"), local, []));
var host = new WorkspaceHost(environment, new AppSettings(), () => { }, () => null, () => null, () => null);
var told = new List<WorkspaceHomeChange>();
host.HomeChanged += told.Add;
// Missed changes (the event stream came back) are told for every project of that server.
host.OnServerProjectChanged(Server, null);
Assert.Equal(new WorkspaceHomeChange(Server, null, null), told.Single());
// A project this workspace does not hold is not told (and the workspace without an index holds none).
host.OnServerProjectChanged(Server, new ProjectChangedEvent(Guid.CreateVersion7(), Guid.CreateVersion7(), ProjectChanges.Pushed, 2, Guid.CreateVersion7()));
Assert.Count(1, told);
}
[Test]
public async Task TheEditorFollowsTheServerAndRendersOnlyWhatItHolds()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var server = new FakeServer(bed);
Connect(host, server);
var projectId = await CheckoutAsync(bed, host);
var told = new List<WorkspaceHomeChange>();
host.HomeChanged += told.Add;
var source = new WorkspaceSequenceSource(host.Sync, projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine, new WorkspaceServerHome(null));
var content = await source.LoadAsync(bed.Ct);
var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
var ui = new RecordingUi();
await using (session)
using (var menu = new ProjectMenuViewModel(host, source, session, ui))
{
await menu.RefreshAsync();
Assert.True(source.IsServerHome && source.IsRemote && menu.IsServerHome, "analyses and renders run on the server");
Assert.Equal(Loc.L("Errors.Workspace.MainKept"), menu.DeleteToolTip);
Assert.Equal(Loc.L("Tooltips.Editor.Project.Rename.Server"), menu.RenameToolTip);
Assert.Equal(Loc.L("Tooltips.Editor.Project.RemoveCopy.Server"), menu.RemoveCopyToolTip);
Assert.Equal(Loc.L("Tooltips.Editor.Workspace.UpdateMedia.Server"), menu.UpdateMediaToolTip);
// Not signed in to the server: the project opens, its jobs are refused saying so.
Assert.Empty(await source.ListJobsAsync(bed.Ct));
var refused = await Assert.ThrowsAsync<EditorException>(() => source.SubmitAsync(session.RenderRequests(session.Project.Export)[0], bed.Ct));
Assert.Equal(Loc.L("Editor.Error.SignedOut"), refused.Message);
// In step with the server: the render names the version it holds, whose settings the server renders.
Assert.True(await menu.ReadyToRenderAsync(), "nothing to send");
Assert.Empty(ui.Confirmations);
var basis = host.Store.Find(projectId)!.ReadBundle().Workspace!.Base!;
var (held, _) = ProcessingJobs.ReadRender(session.RenderRequests(session.Project.Export)[0].ParametersJson);
Assert.Equal<(Guid?, Guid?, string?)>((projectId, basis.VersionId, null), (held.ProjectId, held.ProjectVersionId, held.SettingsJson));
// A change not sent: the render of the working state names the project alone, and is offered to be sent first.
Assert.True(session.SetHero(3));
Assert.True(await session.FlushAsync());
var (unsent, _) = ProcessingJobs.ReadRender(session.RenderRequests(session.Project.Export)[0].ParametersJson);
Assert.Equal<(Guid?, Guid?)>((projectId, null), (unsent.ProjectId, unsent.ProjectVersionId));
Assert.NotNull(unsent.SettingsJson);
ui.ConfirmAnswer = false;
Assert.False(await menu.ReadyToRenderAsync(), "kept here: nothing renders");
Assert.Equal(Loc.L("Editor.Workspace.SendFirst.Title"), ui.Confirmations.Single().Heading);
Assert.Equal(WorkspaceState.Modified, menu.Status!.State);
ui.ConfirmAnswer = true;
Assert.True(await menu.ReadyToRenderAsync(), "saved and sent: the server holds it");
Assert.Equal(WorkspaceState.InSync, menu.Status!.State);
var sent = host.Store.Find(projectId)!.ReadBundle().Workspace!.Base!;
Assert.NotEqual(basis.VersionId, sent.VersionId);
var (version, _) = ProcessingJobs.ReadRender(session.RenderRequests(session.Project.Export)[0].ParametersJson);
Assert.Equal<(Guid?, string?)>((sent.VersionId, null), (version.ProjectVersionId, version.SettingsJson));
Assert.Equal(3, ProjectSettings.FromJson(Assert.NotNull((await bed.RowAsync()).SettingsJson)).HeroFrame, "the server holds the version");
// The server out of reach: the render waits, said in a toast.
server.Reachable = false;
Assert.True(session.SetHero(1));
Assert.True(await session.FlushAsync());
Assert.False(await menu.ReadyToRenderAsync());
Assert.Equal(Loc.L("Editor.Workspace.RenderHeld"), ui.Toasts[^1].Title);
Assert.False(ui.Toasts[^1].IsError, "out of reach is no error");
server.Reachable = true;
await menu.SaveVersionAsync(null);
await menu.SyncAsync();
Assert.Equal(WorkspaceState.InSync, menu.Status!.State);
// Another PC sends a version and the server says so: the chip reads Server newer at once.
var other = bed.Host(name: "other-pc");
await bed.CheckoutAsync(other);
var theirs = await other.Sync.OpenAsync(projectId, bed.Ct);
await other.Sync.SaveAsync(projectId, theirs.Working with { Exposure = theirs.Working.Exposure with { ExposureOffsetEv = 0.7 } }, bed.Ct);
var stored = (await other.SaveVersionAsync(projectId, null, bed.Ct)).Version!;
host.OnServerProjectChanged(Server, new ProjectChangedEvent(bed.SequenceId, projectId, ProjectChanges.Pushed, stored.Number, stored.Id));
Assert.Equal(projectId, told.Single().ProjectId);
await WorkspaceTestBed.UntilAsync(() => menu.Status?.State == WorkspaceState.Behind, "the chip follows the server's change");
Assert.Equal(Loc.L("Editor.Workspace.State.Behind.Server"), menu.StateText);
// A change of another server, or of a project this workspace does not hold, is not told.
host.OnServerProjectChanged("https://elsewhere:8443", new ProjectChangedEvent(bed.SequenceId, projectId, ProjectChanges.Pushed, 9, Guid.CreateVersion7()));
host.OnServerProjectChanged(Server, new ProjectChangedEvent(Guid.CreateVersion7(), projectId, ProjectChanges.Pushed, 9, Guid.CreateVersion7()));
Assert.Count(1, told);
await menu.SyncAsync();
Assert.Equal(0.7, session.Project.Exposure.ExposureOffsetEv);
// Deleted on the server: the chip says so, the copy and the editor stay.
server.Deleted.Add(projectId);
host.OnServerProjectChanged(Server, new ProjectChangedEvent(bed.SequenceId, projectId, ProjectChanges.Deleted, stored.Number, stored.Id));
await WorkspaceTestBed.UntilAsync(() => menu.Status?.State == WorkspaceState.Gone, "the chip says the project is gone");
Assert.Equal(Loc.L("Editor.Workspace.State.Gone.Server"), menu.StateText);
Assert.False(await menu.ReadyToRenderAsync(), "nothing to render it from");
Assert.True(ui.Toasts[^1].IsError);
Assert.NotNull(host.Store.Find(projectId)?.ReadMedia());
}
}
/// <summary>The home a workspace project of the test sequence names on <see cref="Server"/>.</summary>
private static BundleHome ServerHome(WorkspaceTestBed bed) => new(BundleHome.ServerKind, bed.SequenceId, null, Server);
/// <summary>The host signed in to <paramref name="server"/>, as the desktop's SyncHost gives it.</summary>
private static void Connect(WorkspaceHost host, FakeServer server) =>
host.ServerHomes = home => string.Equals(home.Server, Server, StringComparison.OrdinalIgnoreCase) && home.SequenceId == server.Inner.SequenceId ? server : null;
/// <summary>
/// Main checked out with its media copied from the archive, then named the server's: as a copy downloaded from the
/// server leaves it (that download is the server tests' own).
/// </summary>
private static async Task<Guid> CheckoutAsync(WorkspaceTestBed bed, WorkspaceHost host)
{
var projectId = await bed.CheckoutAsync(host);
var folder = host.Store.Find(projectId)!;
var bundle = folder.ReadBundle();
folder.WriteBundle(bundle with { Workspace = bundle.Workspace! with { Home = ServerHome(bed) } });
return projectId;
}
/// <summary>A server that keeps the archive's projects: reachable or not, with projects deleted there, or none of the sequence's.</summary>
private sealed class FakeServer(WorkspaceTestBed bed) : IProjectHome
{
public ArchiveProjectHome Inner { get; } = new(bed.Db, bed.Archives.Projects, bed.SequenceId);
public bool Reachable { get; set; } = true;
/// <summary>The server answers 404 for the sequence's projects (deleted with their sequence).</summary>
public bool Missing { get; set; }
public HashSet<Guid> Deleted { get; } = [];
public async Task<HomeSequence> SequenceAsync(CancellationToken cancellationToken)
{
var sequence = await Reach(() => Inner.SequenceAsync(cancellationToken));
return sequence with { Home = ServerHome(bed), Archive = sequence.Archive with { Id = ServerProjectHome.ArchiveIdOf(Server), Path = null } };
}
public Task<IReadOnlyList<SequenceProject>> ListAsync(CancellationToken cancellationToken) => Reach(() => Inner.ListAsync(cancellationToken));
public Task<SequenceProject> CreateAsync(string name, Guid? fromVersionId, string? author, CancellationToken cancellationToken) =>
Reach(() => Inner.CreateAsync(name, fromVersionId, author, cancellationToken));
/// <remarks>A project deleted there has no head (404 <c>project</c>), as the server answers.</remarks>
public Task<ProjectVersion> HeadAsync(Guid projectId, CancellationToken cancellationToken) =>
Deleted.Contains(projectId)
? throw new ProjectException(ProjectError.NotFound, "deleted on the server")
: Reach(() => Inner.HeadAsync(projectId, cancellationToken));
public Task<ProjectVersion?> GetVersionAsync(Guid projectId, Guid versionId, CancellationToken cancellationToken) =>
Reach(() => Inner.GetVersionAsync(projectId, versionId, cancellationToken));
public Task<IReadOnlyList<ProjectVersion>> VersionsAfterAsync(Guid projectId, int afterNumber, int limit, CancellationToken cancellationToken) =>
Reach(() => Inner.VersionsAfterAsync(projectId, afterNumber, limit, cancellationToken));
public Task<IReadOnlyList<ProjectVersion>> HistoryAsync(Guid projectId, int? beforeNumber, int limit, CancellationToken cancellationToken) =>
Reach(() => Inner.HistoryAsync(projectId, beforeNumber, limit, cancellationToken));
public Task<PushResult> PushAsync(Guid projectId, ProjectVersion version, CancellationToken cancellationToken) =>
Deleted.Contains(projectId)
? throw new ProjectException(ProjectError.NotFound, "deleted on the server")
: Reach(() => Inner.PushAsync(projectId, version, cancellationToken));
public Task<HomeFrames> FramesAsync(CancellationToken cancellationToken) => Reach(() => Inner.FramesAsync(cancellationToken));
private Task<T> Reach<T>(Func<Task<T>> call)
{
if (!Reachable) throw new HomeUnavailableException("The server cannot be reached.");
if (Missing) throw new ProjectException(ProjectError.NotFound, "not on the server");
return call();
}
}
}
@@ -0,0 +1,231 @@
using System.Net;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Projects;
using Chronos.Data.Workspaces;
using Chronos.Protocol;
using Chronos.Protocol.Client;
using Chronos.Testing;
namespace Chronos.Data.Tests.Projects;
/// <summary>
/// A server as the home of workspace projects (owner review 2, R8, phase 5b): the calls <see cref="ServerProjectHome"/> makes
/// and how it reads the server's answers, a server out of reach, an expired sign-in, a busy sequence or a server without
/// projects being a home out of reach, and its refusals the archive's own.
/// </summary>
[Category("workspace")]
public sealed class ServerProjectHomeTests(TestContext context)
{
private static readonly Uri Address = new("https://nas.local:8443/");
private static readonly Guid SequenceId = Guid.CreateVersion7();
private static readonly Guid ProjectId = Guid.CreateVersion7();
[Test]
public async Task ItAsksTheServersProjectsAndReadsThemAsTheArchiveGivesThem()
{
var head = Version(3);
var handler = new FakeHandler(request => (request.Method.Method, request.RequestUri!.PathAndQuery) switch
{
("GET", var path) when path == $"/api/v1/sequences/{SequenceId}" => Json(Sequence()),
("GET", var path) when path == $"/api/v1/sequences/{SequenceId}/projects" => Json(new List<ProjectDto> { Project() }),
("POST", var path) when path == $"/api/v1/sequences/{SequenceId}/projects" => Json(Project() with { Name = "Vertical", IsMain = false }, HttpStatusCode.Created),
("GET", var path) when path == $"/api/v1/sequences/{SequenceId}/projects/{ProjectId}/head" => Json(head),
("GET", var path) when path.StartsWith($"/api/v1/sequences/{SequenceId}/projects/{ProjectId}/versions?", StringComparison.Ordinal) =>
Json(new ProjectVersionPageDto([Version(2), Version(1)], 3, false)),
("GET", var path) when path == $"/api/v1/sequences/{SequenceId}/projects/{ProjectId}/versions/{head.Id}" => Json(head),
("GET", var path) when path.StartsWith($"/api/v1/sequences/{SequenceId}/projects/{ProjectId}/versions/", StringComparison.Ordinal) =>
Error(HttpStatusCode.NotFound, "not_found", "version"),
("PATCH", var path) when path == $"/api/v1/sequences/{SequenceId}/projects/{ProjectId}" => Json(Project() with { Name = "Main renamed" }),
("GET", var path) when path == $"/api/v1/sequences/{SequenceId}/projects/{ProjectId}" => Json(Project()),
("DELETE", _) => new HttpResponseMessage(HttpStatusCode.NoContent),
_ => Error(HttpStatusCode.NotFound, "not_found", null),
});
using var client = Client(handler);
var home = new ServerProjectHome(client, SequenceId, "Studio NAS");
// The sequence as a workspace's project file names it: the server's key (as sync links name it) and its name.
var sequence = await home.SequenceAsync(context.Cancellation);
Assert.Equal((BundleHome.ServerKind, SequenceId, (Guid?)null, "https://nas.local:8443"), (sequence.Home.Kind, sequence.Home.SequenceId, sequence.Home.ArchiveId, sequence.Home.Server));
Assert.Equal(("Studio NAS", "Harbour sunset", "2026/harbour", 3), (sequence.Archive.Name, sequence.Sequence.Title, sequence.Sequence.Folder, sequence.Sequence.Frames));
// A project file names an archive: the server's sequences carry one made from its key, the same each time.
Assert.Equal(ServerProjectHome.ArchiveIdOf("https://nas.local:8443"), sequence.Archive.Id);
Assert.NotEqual(Guid.Empty, sequence.Archive.Id);
Assert.NotEqual(ServerProjectHome.ArchiveIdOf("https://other:8443"), sequence.Archive.Id);
var main = (await home.ListAsync(context.Cancellation)).Single();
Assert.Equal((ProjectId, true, "Main", 3), (main.Id, main.IsMain, main.Name, main.HeadNumber));
Assert.Equal("Vertical", (await home.CreateAsync("Vertical", head.Id, "ignored", context.Cancellation)).Name);
var read = await home.HeadAsync(ProjectId, context.Cancellation);
Assert.Equal((head.Id, 3, ProjectVersionKind.Commit, head.ContentHash), (read.Id, read.Number, read.Kind, read.ContentHash));
Assert.SequenceEqual([2, 1], (await home.HistoryAsync(ProjectId, 3, 500, context.Cancellation)).Select(v => v.Number));
Assert.SequenceEqual([2, 1], (await home.VersionsAfterAsync(ProjectId, 0, 100, context.Cancellation)).Select(v => v.Number));
Assert.Equal(head.Id, (await home.GetVersionAsync(ProjectId, head.Id, context.Cancellation))?.Id);
// A version the server does not have is none, as on this PC's archive.
Assert.Null(await home.GetVersionAsync(ProjectId, Guid.CreateVersion7(), context.Cancellation));
Assert.Equal("Main renamed", (await home.RenameAsync(ProjectId, "Main renamed", context.Cancellation)).Name);
await home.DeleteAsync(ProjectId, context.Cancellation);
// Pages are asked within the server's 1–200, oldest first above a number or newest first below one.
Assert.Contains(handler.Requests, r => r.EndsWith("/versions?before=3&limit=200", StringComparison.Ordinal));
Assert.Contains(handler.Requests, r => r.EndsWith("/versions?after=0&limit=100", StringComparison.Ordinal));
// The server makes the project from that version, its maker the account: no author travels.
Assert.Equal($"{{\"name\":\"Vertical\",\"fromVersionId\":\"{head.Id}\"}}", handler.Bodies.Single(b => b.Contains("Vertical", StringComparison.Ordinal)));
}
[Test]
public async Task APushAnswersItsOutcomeAsTheArchiveDoes()
{
var head = Version(4);
var outcomes = new Queue<HttpResponseMessage>(
[
Json(new ProjectPushResultDto(ProjectPushOutcomes.Stored, Version(5), Version(5)), HttpStatusCode.Created),
Json(new ProjectPushResultDto(ProjectPushOutcomes.AlreadyStored, Version(5), Version(5))),
Json(new ProjectPushResultDto(ProjectPushOutcomes.Diverged, null, head, ProjectErrors.Diverged, "moved"), HttpStatusCode.Conflict),
Json(new ProjectPushResultDto(ProjectPushOutcomes.HashMismatch, null, head, ProjectErrors.HashMismatch, "damaged"), HttpStatusCode.UnprocessableEntity),
Json(new ProjectPushResultDto("from_a_newer_server", null, head, "something", "new"), HttpStatusCode.UnprocessableEntity),
]);
using var client = Client(new FakeHandler(_ => outcomes.Dequeue()));
var home = new ServerProjectHome(client, SequenceId);
var local = ProjectWire.ToVersion(Version(5) with { StoredAt = null });
Assert.Equal((PushOutcome.Stored, 5), Outcome(await home.PushAsync(ProjectId, local, context.Cancellation)));
Assert.Equal((PushOutcome.AlreadyStored, 5), Outcome(await home.PushAsync(ProjectId, local, context.Cancellation)));
var diverged = await home.PushAsync(ProjectId, local, context.Cancellation);
Assert.Equal((PushOutcome.Diverged, (ProjectVersion?)null, (Guid?)head.Id), (diverged.Outcome, diverged.Version, diverged.Head?.Id));
Assert.Equal(PushOutcome.HashMismatch, (await home.PushAsync(ProjectId, local, context.Cancellation)).Outcome);
// An outcome this build does not know is a refusal, never a stored version.
Assert.Equal(PushOutcome.Invalid, (await home.PushAsync(ProjectId, local, context.Cancellation)).Outcome);
static (PushOutcome, int?) Outcome(PushResult result) => (result.Outcome, result.Version?.Number);
}
[Test]
public async Task AServerOutOfReachBusyOrSignedOutIsAHomeOutOfReach()
{
foreach (var (what, answer) in new (string, Func<HttpResponseMessage>)[]
{
("no answer", () => throw new HttpRequestException("refused")),
("the sign-in expired", () => Error(HttpStatusCode.Unauthorized, "unauthorized", null)),
("the sequence busy", () => Error(HttpStatusCode.ServiceUnavailable, "sequence_busy", null)),
("the archive offline", () => Error(HttpStatusCode.ServiceUnavailable, "archive_offline", null)),
("a gateway", () => new HttpResponseMessage(HttpStatusCode.BadGateway) { Content = new StringContent("<html>502</html>") }),
("a project file in use", () => Error(HttpStatusCode.Conflict, "folder_in_use", null)),
("a server without projects", () => Error(HttpStatusCode.NotFound, "not_found", null)),
("an answer that is not the API's", () => new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("<html>portal</html>", Encoding.UTF8, "text/html") }),
})
{
using var client = Client(new FakeHandler(_ => answer()));
var home = new ServerProjectHome(client, SequenceId);
var unavailable = await Assert.ThrowsAsync<HomeUnavailableException>(() => home.HeadAsync(ProjectId, context.Cancellation));
Assert.True(unavailable.InnerException is not null, what);
await Assert.ThrowsAsync<HomeUnavailableException>(() => home.ListAsync(context.Cancellation));
await Assert.ThrowsAsync<HomeUnavailableException>(() => home.PushAsync(ProjectId, ProjectWire.ToVersion(Version(2)), context.Cancellation));
}
// A client disposed meanwhile (the session ended) is a server out of reach too.
var gone = Client(new FakeHandler(_ => Json(Version(1))));
gone.Dispose();
await Assert.ThrowsAsync<HomeUnavailableException>(() => new ServerProjectHome(gone, SequenceId).HeadAsync(ProjectId, context.Cancellation));
// The caller's own cancellation stays a cancellation.
using var cancelled = new CancellationTokenSource();
await cancelled.CancelAsync();
using var slow = Client(new FakeHandler(_ => Json(Version(1))));
await Assert.ThrowsAsync<OperationCanceledException>(() => new ServerProjectHome(slow, SequenceId).HeadAsync(ProjectId, cancelled.Token));
}
[Test]
public async Task RefusalsReadAsTheArchivesAndTheOthersKeepTheirMeaning()
{
async Task<ProjectException> RefusedAsync(HttpResponseMessage answer, Func<ServerProjectHome, Task> call)
{
using var client = Client(new FakeHandler(_ => answer));
return await Assert.ThrowsAsync<ProjectException>(() => call(new ServerProjectHome(client, SequenceId)));
}
Assert.Equal(ProjectError.SequenceNotFound, (await RefusedAsync(Error(HttpStatusCode.NotFound, "not_found", "sequence"), h => h.ListAsync(default))).Reason);
Assert.Equal(ProjectError.NotFound, (await RefusedAsync(Error(HttpStatusCode.NotFound, "not_found", "project"), h => h.HeadAsync(ProjectId, default))).Reason);
Assert.Equal(ProjectError.NotFound, (await RefusedAsync(Error(HttpStatusCode.NotFound, "not_found", "version"), h => h.CreateAsync("Copy", Guid.CreateVersion7(), null, default))).Reason);
Assert.Equal(ProjectError.InvalidName, (await RefusedAsync(Error(HttpStatusCode.BadRequest, ProjectErrors.InvalidName, null), h => h.CreateAsync(" ", null, null, default))).Reason);
Assert.Equal(ProjectError.NameTaken, (await RefusedAsync(Error(HttpStatusCode.Conflict, ProjectErrors.NameTaken, null), h => h.RenameAsync(ProjectId, "Main", default))).Reason);
Assert.Equal(ProjectError.MainCannotBeDeleted,
(await RefusedAsync(Error(HttpStatusCode.Conflict, ProjectErrors.MainCannotBeDeleted, null), h => h.DeleteAsync(ProjectId, default))).Reason);
// An account that may not change projects there: the server's own refusal, not a home out of reach.
using var viewer = Client(new FakeHandler(_ => Error(HttpStatusCode.Forbidden, "forbidden", null)));
var forbidden = await Assert.ThrowsAsync<ChronosApiException>(() => new ServerProjectHome(viewer, SequenceId).CreateAsync("Mine", null, null, default));
Assert.Equal(HttpStatusCode.Forbidden, forbidden.Status);
}
[Test]
public async Task AWorkspaceOfAServerOutOfReachIsOfflineAndItsWorkWaits()
{
var head = Version(1);
var reachable = true;
var handler = new FakeHandler(request =>
{
if (!reachable) throw new HttpRequestException("refused");
var path = request.RequestUri!.AbsolutePath;
if (path == $"/api/v1/sequences/{SequenceId}") return Json(Sequence());
if (path.EndsWith("/projects", StringComparison.Ordinal)) return Json(new List<ProjectDto> { Project() with { HeadNumber = 1, HeadVersionId = head.Id } });
if (path.EndsWith("/head", StringComparison.Ordinal)) return Json(head);
return Json(Project() with { HeadNumber = 1, HeadVersionId = head.Id });
});
using var client = Client(handler);
var home = new ServerProjectHome(client, SequenceId);
var store = new WorkspaceStore(Path.Combine(context.CreateTempDirectory("ws"), "workspace"));
var sync = new WorkspaceSync(store, "Chronos on PC-A");
var project = await sync.CheckoutAsync(home, ProjectId, cancellationToken: context.Cancellation);
Assert.Equal((BundleHome.ServerKind, "https://nas.local:8443"), (project.ReadBundle().Workspace!.Home.Kind, project.ReadBundle().Workspace!.Home.Server));
// No media yet (the copy job brings them): its settings name no frame, so a version can still be saved.
await sync.SaveAsync(ProjectId, new ProjectSettings { Exposure = new ExposureSettings { ExposureOffsetEv = 0.4 } }, context.Cancellation);
Assert.NotNull(await sync.CommitAsync(ProjectId, "warmer", cancellationToken: context.Cancellation));
reachable = false;
var status = await sync.StatusAsync(ProjectId, home, context.Cancellation);
Assert.Equal((WorkspaceState.MediaRemoved, true, 1), (status.State, status.Offline, status.Ahead));
await Assert.ThrowsAsync<HomeUnavailableException>(() => sync.PushAsync(ProjectId, home, context.Cancellation));
// Nothing was lost: the version still waits here.
Assert.Equal(1, sync.Unpushed(ProjectId).Count);
}
private static ChronosClient Client(HttpMessageHandler handler) => new(Address, new CertificatePinning([]), "tests", handler) { Token = "token" };
private static SequenceDto Sequence() => new(SequenceId, "Harbour sunset", "Harbour sunset", "2026/harbour", "Canon", "Canon EOS R5", null, null, null, 3, 60, 0,
0, 0, null, [], 0, null, 2, 1, 0, null, DateTimeOffset.UtcNow);
private static ProjectDto Project() => new(ProjectId, SequenceId, "Main", true, Guid.CreateVersion7(), 3, null, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, "commit",
"alberto", "Chronos on PC-A", DateTimeOffset.UtcNow);
private static ProjectVersionDto Version(int number)
{
var portable = ProjectContent.ToPortable(new ProjectSettings { Exposure = new ExposureSettings { ExposureOffsetEv = number / 10.0 } }, new FramePhotos([]));
return new ProjectVersionDto(Guid.CreateVersion7(), ProjectId, null, number, "commit", "alberto", "Chronos on PC-A", null, portable, ProjectContent.Hash(portable),
ProjectContent.FormatOf(portable), 1, null, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow);
}
private static HttpResponseMessage Json<T>(T body, HttpStatusCode status = HttpStatusCode.OK) =>
new(status) { Content = JsonContent.Create(body, (System.Text.Json.Serialization.Metadata.JsonTypeInfo<T>)ProtocolJson.Default.GetTypeInfo(typeof(T))!) };
private static HttpResponseMessage Error(HttpStatusCode status, string code, string? details) => Json(new ApiError(code, "refused", details), status);
/// <summary>The server as the test answers it, with the requests it was sent.</summary>
private sealed class FakeHandler(Func<HttpRequestMessage, HttpResponseMessage> answer) : HttpMessageHandler
{
public List<string> Requests { get; } = [];
public List<string> Bodies { get; } = [];
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
Requests.Add(request.Method.Method + " " + request.RequestUri!.PathAndQuery);
if (request.Content is not null) Bodies.Add(await request.Content.ReadAsStringAsync(cancellationToken));
return answer(request);
}
}
}
@@ -27,6 +27,9 @@ internal sealed class FakeSyncRemote : ISyncRemote
/// <summary>Listings still to fail with a network error.</summary>
public int FailingListings { get; set; }
/// <summary>Event streams still to be lost right after they opened.</summary>
public int FailingEvents { get; set; }
/// <summary>The next original download of this frame returns damaged bytes.</summary>
public Guid? CorruptOnce { get; set; }
@@ -251,6 +254,14 @@ internal sealed class FakeSyncRemote : ISyncRemote
public async IAsyncEnumerable<ServerEvent> EventsAsync([EnumeratorCancellation] CancellationToken cancellationToken)
{
lock (_gate)
{
if (FailingEvents > 0)
{
FailingEvents--;
throw new HttpRequestException("socket closed");
}
}
while (await _events.Reader.WaitToReadAsync(cancellationToken))
{
while (_events.Reader.TryRead(out var e)) yield return e;
@@ -51,6 +51,35 @@ public sealed class SyncAgentTests(TestContext context)
Assert.Same(first, agent.Snapshot);
}
[Test]
public async Task ProjectChangesAreToldAndALostStreamSaysSomeWereMissed()
{
// Owner review 2, R8, phase 5b: the server's projectChanged reaches the workspace through the agent.
await using var f = await SyncFixture.CreateAsync(context);
f.Remote.Add("Harbour", f.NewPhotos(1));
f.Remote.FailingEvents = 1;
var told = new List<ProjectChangedEvent?>();
var missed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var changed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using var agent = new SyncAgent(f.Sync, f.Remote, () => new SyncPolicy(), null, EventsOnly);
agent.ProjectChanged += e =>
{
lock (told) told.Add(e);
(e is null ? missed : changed).TrySetResult();
// What a listener throws never ends the event loop.
throw new InvalidOperationException("a listener that fails");
};
agent.Start();
// The stream was lost once: the comparison after it says changes may have been missed.
await SignalAsync(missed.Task, "the missed changes told");
var change = new ProjectChangedEvent(Guid.CreateVersion7(), Guid.CreateVersion7(), ProjectChanges.Pushed, 3, Guid.CreateVersion7());
f.Remote.Publish(change);
await SignalAsync(changed.Task, "the project change told");
lock (told) Assert.Equal(change, told.Single(e => e is not null));
Assert.Equal(1, agent.Snapshot!.ServerSequences);
}
[Test]
public async Task FailedComparisonsAreRetriedWithBackoff()
{
@@ -0,0 +1,450 @@
using System.Security.Cryptography;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
using Chronos.Data.Workspaces;
using Chronos.Protocol;
using Chronos.Protocol.Client;
using Chronos.Server.Storage;
using Chronos.Testing;
namespace Chronos.Server.Tests.Workspaces;
/// <summary>
/// A server as the home of desktop workspaces (owner review 2, R8, phase 5b), end to end through the protocol client:
/// two workspaces of two accounts on one server project (checkout, the copy of its media, commit, push, the other's
/// fast-forward pull, replays and merges, a real conflict settled by keep mine, take server and save both, restore), the
/// copy job resuming after an interruption and keeping what it holds, and a server out of reach.
/// </summary>
[Category("server")]
[Category("workspace")]
public sealed class ServerWorkspaceTests(TestContext context)
{
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(TestTiming.Budget(60));
[Test]
public async Task TwoWorkspacesShareAProjectOfTheServerLikeGit()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (_, _, albertoToken) = await server.UserAsync("alberto", "editor");
var (_, _, giuliaToken) = await server.UserAsync("giulia", "editor");
var sid = await SequenceAsync(server, albertoToken, 3);
await using var a = await WorkspaceClient.StartAsync(context, server, albertoToken, "PC-A");
await using var b = await WorkspaceClient.StartAsync(context, server, giuliaToken, "PC-B");
var homeA = a.Home(sid);
var homeB = b.Home(sid);
var main = (await homeA.ListAsync(context.Cancellation)).Single(p => p.IsMain);
// Each workspace takes the server's Main and downloads its media.
await a.CheckoutAsync(homeA, main.Id);
await b.CheckoutAsync(homeB, main.Id);
Assert.Equal((BundleHome.ServerKind, a.Server, sid), (a.Bundle(main.Id).Workspace!.Home.Kind, a.Bundle(main.Id).Workspace!.Home.Server, a.Bundle(main.Id).Workspace!.Home.SequenceId));
Assert.Equal(WorkspaceState.InSync, (await a.Sync.StatusAsync(main.Id, homeA, context.Cancellation)).State);
// A saves a version and sends it: a fast-forward, numbered and signed by the server.
await a.EditAsync(main.Id, s => s with { Exposure = s.Exposure with { ExposureOffsetEv = 0.3 } });
Assert.NotNull(await a.Sync.CommitAsync(main.Id, "warmer", cancellationToken: context.Cancellation));
var pushed = await a.Sync.PushAsync(main.Id, homeA, context.Cancellation);
var v2 = pushed.Pushed.Single();
Assert.Equal((2, "alberto", "warmer", WorkspaceState.InSync), (v2.Number, v2.Author, v2.Note, pushed.Status.State));
// B is behind and takes it.
Assert.Equal((WorkspaceState.Behind, 1), ((await b.Sync.StatusAsync(main.Id, homeB, context.Cancellation)).State, (await b.Sync.StatusAsync(main.Id, homeB, context.Cancellation)).Behind));
var pulled = await b.Sync.PullAsync(main.Id, homeB, context.Cancellation);
Assert.Equal((v2.Id, WorkspaceState.InSync), (pulled.Pulled.Single().Id, pulled.Status.State));
Assert.Equal(0.3, (await b.Sync.OpenAsync(main.Id, context.Cancellation)).Working.Exposure.ExposureOffsetEv);
// Both change different settings: B's push meets A's, replays on it and merges, no question asked.
await a.EditAsync(main.Id, s => s with { ExcludedFrames = [1] });
await a.CommitAndPushAsync(homeA, main.Id);
await b.EditAsync(main.Id, s => s with { HeroFrame = 2 });
Assert.NotNull(await b.Sync.CommitAsync(main.Id, cancellationToken: context.Cancellation));
var replayed = await b.Sync.PushAsync(main.Id, homeB, context.Cancellation);
Assert.Equal((1, 1, WorkspaceState.InSync), (replayed.Pulled.Count, replayed.Pushed.Count, replayed.Status.State));
var both = await a.PlacedHeadAsync(homeA, main.Id);
Assert.SequenceEqual([1], both.ExcludedFrames);
Assert.Equal((2, 0.3), (both.HeroFrame, both.Exposure.ExposureOffsetEv));
await a.Sync.PullAsync(main.Id, homeA, context.Cancellation);
Assert.Equal(2, (await a.Sync.OpenAsync(main.Id, context.Cancellation)).Working.HeroFrame);
// The same setting changed on both sides: a real conflict, settled by keeping mine.
Assert.Equal(0.9, (await ConflictAsync(a, b, homeA, homeB, main.Id, 0.5, 0.9, ConflictChoice.KeepMine)).Exposure.ExposureOffsetEv);
// Taking the server's.
Assert.Equal(0.1, (await ConflictAsync(a, b, homeA, homeB, main.Id, 0.1, 0.2, ConflictChoice.TakeServer)).Exposure.ExposureOffsetEv);
// Saving both: B's versions go to a new project of the server, its Main takes A's.
var savedBoth = await ConflictAsync(a, b, homeA, homeB, main.Id, 0.6, 0.7, ConflictChoice.SaveBoth, "Main (PC-B)");
Assert.Equal(0.6, savedBoth.Exposure.ExposureOffsetEv);
var sibling = Assert.NotNull((await homeA.ListAsync(context.Cancellation)).SingleOrDefault(p => p.Name == "Main (PC-B)"));
Assert.Equal(0.7, (await a.PlacedHeadAsync(homeA, sibling.Id)).Exposure.ExposureOffsetEv);
Assert.Equal("giulia", sibling.CreatedBy);
// A restores the first version it sent: the next version says so, and the server keeps it as a restore.
await a.Sync.PullAsync(main.Id, homeA, context.Cancellation);
var restored = await a.Sync.RestoreAsync(main.Id, v2.Id, homeA, context.Cancellation);
Assert.Equal(0.3, restored.Exposure.ExposureOffsetEv);
var restore = Assert.NotNull(await a.Sync.CommitAsync(main.Id, cancellationToken: context.Cancellation));
Assert.Equal((ProjectVersionKind.Restore, (Guid?)v2.Id), (restore.Kind, restore.RestoredFrom));
await a.Sync.PushAsync(main.Id, homeA, context.Cancellation);
var head = await homeB.HeadAsync(main.Id, context.Cancellation);
Assert.Equal((ProjectVersionKind.Restore, (Guid?)v2.Id, "alberto"), (head.Kind, head.RestoredFrom, head.Author));
// Main's head is the sequence's own settings, for older clients and the panel.
var sequence = ProjectSettings.FromJson(Assert.NotNull((await server.Database.Sequences.GetAsync(sid))!.SettingsJson));
Assert.Equal(0.3, sequence.Exposure.ExposureOffsetEv);
}
/// <summary>
/// A and B change one setting from the same version, A first: B's push stops at a conflict, which B settles as
/// <paramref name="choice"/>; returns Main's head at the server as placed on its frames.
/// </summary>
private async Task<ProjectSettings> ConflictAsync(WorkspaceClient a, WorkspaceClient b, ServerProjectHome homeA, ServerProjectHome homeB, Guid projectId,
double theirs, double mine, ConflictChoice choice, string? saveBothName = null)
{
await a.Sync.PullAsync(projectId, homeA, context.Cancellation);
await b.Sync.PullAsync(projectId, homeB, context.Cancellation);
await a.EditAsync(projectId, s => s with { Exposure = s.Exposure with { ExposureOffsetEv = theirs } });
await a.CommitAndPushAsync(homeA, projectId);
await b.EditAsync(projectId, s => s with { Exposure = s.Exposure with { ExposureOffsetEv = mine } });
Assert.NotNull(await b.Sync.CommitAsync(projectId, cancellationToken: context.Cancellation));
var met = await b.Sync.PushAsync(projectId, homeB, context.Cancellation);
var conflict = Assert.NotNull(met.Status.Conflict, "both changed the exposure offset");
Assert.Equal(WorkspaceState.Conflict, met.Status.State);
Assert.Contains(conflict.Differences, d => d.Path.StartsWith("exposure.exposureOffsetEv", StringComparison.Ordinal));
var settled = await b.Sync.ResolveAsync(projectId, homeB, choice, saveBothName: saveBothName, cancellationToken: context.Cancellation);
Assert.Null(settled.Status.Conflict);
if (choice == ConflictChoice.SaveBoth) Assert.Equal(saveBothName, settled.SavedAs?.Name);
var sent = await b.Sync.PushAsync(projectId, homeB, context.Cancellation);
Assert.Equal(WorkspaceState.InSync, sent.Status.State, $"after {choice}");
return await b.PlacedHeadAsync(homeB, projectId);
}
[Test]
public async Task TheCopyDownloadsVerifiedProxiesResumesAndKeepsWhatItHolds()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (_, _, token) = await server.UserAsync("alberto", "editor");
var sid = await SequenceAsync(server, token, 4);
await using var a = await WorkspaceClient.StartAsync(context, server, token, "PC-A");
var home = a.Home(sid);
var main = (await home.ListAsync(context.Cancellation)).Single();
var project = await a.Sync.CheckoutAsync(home, main.Id, cancellationToken: context.Cancellation);
Assert.Equal(WorkspaceState.MediaRemoved, (await a.Sync.StatusAsync(main.Id, home, context.Cancellation)).State);
var library = Listing(a.Archive.RootPath);
// The frames as the server holds them, each file hashed as it arrived and checked on the disk; this PC's library never written.
var job = await a.CopyAsync(sid, main.Id);
var media = Assert.NotNull(project.ReadMedia());
var manifest = await a.Client.GetManifestAsync(sid, context.Cancellation);
Assert.Equal((BundleMedia.Proxies, sid, manifest.FramesVersion, 4), (media.Kind, media.SequenceId, media.FramesVersion, media.Frames.Count));
foreach (var (frame, entry) in manifest.Frames.OrderBy(f => f.Index).Zip(media.Frames))
{
Assert.Equal((frame.Id, frame.Sha256), (entry.Id, entry.Sha256));
Assert.Equal(entry.FileSha256, Sha(project.MediaFile(Assert.NotNull(entry.File))));
Assert.Equal(frame.HasProxy ? "proxy" : "thumb", entry.FileKind);
}
var downloaded = media.Frames.Count(f => f.FileKind == "proxy");
Assert.Contains(Loc.L("Archive.Log.WorkspaceDownloaded", Title, downloaded, 4 - downloaded, 0, 0), job.LogTail!);
Assert.SequenceEqual(library, Listing(a.Archive.RootPath), "this PC's library is as it was");
var session = await a.Sync.OpenAsync(main.Id, context.Cancellation);
Assert.Equal(4, Assert.NotNull(session.Sequence).Files.Count(f => f is not null));
// A run stopped after two frames, a later file left damaged and the media index gone: the two are kept as they are,
// the others downloaded again.
File.WriteAllText(project.MediaFile(media.Frames[3].File!), "not a photo");
File.Delete(project.MediaIndexPath);
job = await a.CopyAsync(sid, main.Id, $"copy:2:{manifest.FramesVersion}");
Assert.Contains(Loc.L("Archive.Log.WorkspaceDownloaded", Title, Downloaded(media, 2..), media.Frames.Count - 2 - Downloaded(media, 2..), 2, 0), job.LogTail!);
var again = Assert.NotNull(project.ReadMedia());
Assert.SequenceEqual(media.Frames.Select(f => f.FileSha256), again.Frames.Select(f => f.FileSha256));
// Update media while nothing changed keeps every file it holds of the same photo, hashed again; one damaged since is fetched anew.
job = await a.CopyAsync(sid, main.Id);
Assert.Contains(Loc.L("Archive.Log.WorkspaceDownloaded", Title, 0, 0, 4, 0), job.LogTail!);
File.WriteAllText(project.MediaFile(media.Frames[0].File!), "damaged");
job = await a.CopyAsync(sid, main.Id);
Assert.Contains(Loc.L("Archive.Log.WorkspaceDownloaded", Title, Downloaded(media, ..1), 1 - Downloaded(media, ..1), 3, 0), job.LogTail!);
Assert.Equal(media.Frames[0].FileSha256, Sha(project.MediaFile(media.Frames[0].File!)));
// Positions follow their photos when the server's frames change and the copy runs again.
await a.EditAsync(main.Id, s => s with { ExcludedFrames = [2] });
var uploader = server.NewClient(token);
await Uploads.UploadAsync(uploader, Photo(99), "IMG_0000.JPG", sid, capturedAt: new DateTime(2026, 9, 28, 17, 59, 11));
await JobsDoneAsync(server);
await a.CopyAsync(sid, main.Id);
var moved = await a.Sync.OpenAsync(main.Id, context.Cancellation);
Assert.Equal(5, moved.Media!.Frames.Count);
Assert.SequenceEqual([3], moved.Working.ExcludedFrames);
Assert.Equal(media.Frames[2].Id, moved.Media.Frames[3].Id);
static int Downloaded(WorkspaceMedia media, Range frames) => media.Frames.Take(frames).Count(f => f.FileKind == "proxy");
}
[Test]
public async Task ACopyIsRefusedForAnotherHomeOrWithoutTheServer()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (_, _, token) = await server.UserAsync("alberto", "editor");
var sid = await SequenceAsync(server, token, 1);
await using var a = await WorkspaceClient.StartAsync(context, server, token, "PC-A");
var main = (await a.Home(sid).ListAsync(context.Cancellation)).Single();
await a.Sync.CheckoutAsync(a.Home(sid), main.Id, cancellationToken: context.Cancellation);
// Another server's job for this project, or this server's for another sequence: refused, nothing downloaded.
var other = await a.EnqueueAsync(WorkspaceJobs.CopyFromServer(sid, Title, "https://elsewhere:8443", a.Store.Root, main.Id));
Assert.Equal(Loc.L("Errors.Workspace.OtherHome"), (await a.WaitAsync(other.Id, JobState.Failed)).Error);
var originals = await a.EnqueueAsync(WorkspaceJobs.CopyFromServer(sid, Title, a.Server, a.Store.Root, main.Id, BundleMedia.Originals));
Assert.Equal(Loc.L("Errors.Workspace.OriginalsLater"), (await a.WaitAsync(originals.Id, JobState.Failed)).Error);
a.Connected = false;
var signedOut = await a.EnqueueAsync(WorkspaceJobs.CopyFromServer(sid, Title, a.Server, a.Store.Root, main.Id));
Assert.Equal(Loc.L("Errors.Sync.NotConnected"), (await a.WaitAsync(signedOut.Id, JobState.Failed)).Error);
Assert.Null(a.Store.Find(main.Id)!.ReadMedia());
}
[Test]
public async Task AProjectDeletedOnTheServerIsGoneAndItsCopyStays()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (_, _, token) = await server.UserAsync("alberto", "editor");
var sid = await SequenceAsync(server, token, 2);
await using var a = await WorkspaceClient.StartAsync(context, server, token, "PC-A");
var home = a.Home(sid);
var vertical = await home.CreateAsync("Vertical", null, null, context.Cancellation);
Assert.Equal("alberto", vertical.CreatedBy);
await a.CheckoutAsync(home, vertical.Id);
await a.EditAsync(vertical.Id, s => s with { HeroFrame = 1 });
Assert.NotNull(await a.Sync.CommitAsync(vertical.Id, cancellationToken: context.Cancellation));
// Deleted on the server (by its maker, from another program): the copy here reads as gone, with its unsent version.
using (var deleted = await server.NewClient(token).DeleteAsync($"/api/v1/sequences/{sid}/projects/{vertical.Id}"))
Assert.Equal(System.Net.HttpStatusCode.NoContent, deleted.StatusCode);
// The server has no head for it any more (404 project): the copy here reads as gone, never as in step.
Assert.Equal(ProjectError.NotFound, (await Assert.ThrowsAsync<ProjectException>(() => home.HeadAsync(vertical.Id, context.Cancellation))).Reason);
var status = await a.Sync.StatusAsync(vertical.Id, home, context.Cancellation);
Assert.Equal((WorkspaceState.Gone, 0, 1), (status.State, status.Behind, status.Ahead));
// A push sends nothing to it: the copy keeps reading as gone, its version kept here.
var pushed = await a.Sync.PushAsync(vertical.Id, home, context.Cancellation);
Assert.Equal((WorkspaceState.Gone, 0), (pushed.Status.State, pushed.Pushed.Count));
Assert.Equal(1, a.Sync.Unpushed(vertical.Id).Count);
Assert.Equal(1, (await a.Sync.OpenAsync(vertical.Id, context.Cancellation)).Working.HeroFrame);
// Its versions stay readable on the server, as in its project trash.
Assert.SequenceEqual([1], (await home.HistoryAsync(vertical.Id, null, 10, context.Cancellation)).Select(v => v.Number));
}
[Test]
public async Task AServerOutOfReachLeavesTheProjectOfflineAndItsWorkWaits()
{
var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var running = true;
WorkspaceClient? a = null;
try
{
var (_, _, token) = await server.UserAsync("alberto", "editor");
var sid = await SequenceAsync(server, token, 2);
a = await WorkspaceClient.StartAsync(context, server, token, "PC-A");
var home = a.Home(sid);
var main = (await home.ListAsync(context.Cancellation)).Single();
await a.CheckoutAsync(home, main.Id);
await a.EditAsync(main.Id, s => s with { HeroFrame = 1 });
Assert.NotNull(await a.Sync.CommitAsync(main.Id, cancellationToken: context.Cancellation));
running = false;
await server.DisposeAsync();
var status = await a.Sync.StatusAsync(main.Id, home, context.Cancellation);
Assert.Equal((WorkspaceState.Offline, true, 1), (status.State, status.Offline, status.Ahead));
await Assert.ThrowsAsync<HomeUnavailableException>(() => a.Sync.PushAsync(main.Id, home, context.Cancellation));
await Assert.ThrowsAsync<HomeUnavailableException>(() => a.Sync.PullAsync(main.Id, home, context.Cancellation));
// Nothing was lost: the version still waits, and the project still opens from the workspace.
Assert.Equal(1, a.Sync.Unpushed(main.Id).Count);
Assert.Equal(1, (await a.Sync.OpenAsync(main.Id, context.Cancellation)).Working.HeroFrame);
}
finally
{
if (a is not null) await a.DisposeAsync();
if (running) await server.DisposeAsync();
}
}
private const string Title = "harbour";
private static string Sha(string path) => Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(path)));
/// <summary>Every file and folder under <paramref name="root"/> with its size, in order.</summary>
private static List<string> Listing(string root) =>
[.. new DirectoryInfo(root).EnumerateFileSystemInfos("*", SearchOption.AllDirectories).Select(e => $"{Path.GetRelativePath(root, e.FullName)} {(e as FileInfo)?.Length}")
.Order(StringComparer.Ordinal)];
/// <summary>A sequence of <paramref name="photos"/> JPEG photos a minute apart, filed by the archive engine, once its jobs are done.</summary>
private static async Task<Guid> SequenceAsync(TestServer server, string token, int photos)
{
var uploader = server.NewClient(token);
Guid id = default;
for (var i = 0; i < photos; i++)
id = (await Uploads.UploadAsync(uploader, Photo(i), $"IMG_{i + 1:0000}.JPG", sessionKey: Title, capturedAt: new DateTime(2026, 9, 28, 18, i, 11))).SequenceId;
await JobsDoneAsync(server);
var admin = await server.AdminAsync();
using var titled = await admin.PatchAsync($"/api/v1/sequences/{id}",
System.Net.Http.Json.JsonContent.Create(new UpdateSequenceRequest(Title, null, null, null, null, null), ProtocolJson.Default.UpdateSequenceRequest));
titled.EnsureSuccessStatusCode();
return id;
}
/// <summary>Waits until the server's jobs (thumbnails, proxies, analyses) are done.</summary>
private static async Task JobsDoneAsync(TestServer server)
{
var until = DateTime.UtcNow + Wait;
foreach (var state in new[] { JobState.Queued, JobState.Running, JobState.Queued, JobState.Running })
{
while ((await server.Database.Jobs.ListAsync(state)).Items.Any(j => j.Kind != JobKind.Render))
{
Assert.True(DateTime.UtcNow < until, $"jobs still {state}");
await Task.Delay(50);
}
}
}
private static byte[] Photo(int seed)
{
const int width = 96, height = 64;
var pixels = new byte[width * height * 3];
for (var i = 0; i < pixels.Length; i++) pixels[i] = (byte)((i * 7 + seed * 31) % 251);
return JpegEncoder.Encode(pixels, width, height, 3, new JpegEncodeOptions { Quality = 90 });
}
/// <summary>A desktop's side: its own index (for the job engine), the workspace copy job connected to the test server, a workspace and its sync.</summary>
private sealed class WorkspaceClient : IAsyncDisposable
{
private readonly TestContext _context;
private WorkspaceClient(TestContext context, ChronosDatabase db, Archive archive, ChronosClient client, JobEngine engine, WorkspaceStore store, string name)
{
_context = context;
Db = db;
Archive = archive;
Client = client;
Engine = engine;
Store = store;
Sync = new WorkspaceSync(store, "Chronos on " + name) { LockWait = TimeSpan.FromSeconds(TestTiming.Budget(10)) };
}
public ChronosDatabase Db { get; }
public Archive Archive { get; }
public ChronosClient Client { get; }
public JobEngine Engine { get; }
public WorkspaceStore Store { get; }
public WorkspaceSync Sync { get; }
public string Server => SyncService.ServerKey(Client.BaseAddress);
/// <summary>Whether the copy job finds this PC signed in to the server.</summary>
public bool Connected { get; set; } = true;
public static async Task<WorkspaceClient> StartAsync(TestContext context, TestServer server, string token, string name)
{
var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory(name + "-db"), "chronos.db")), context.Cancellation);
var archives = new ArchiveService(db, new ArchiveServiceOptions { Owner = name });
// This PC's own library: the copy of a server project never writes into it.
var archive = await archives.CreateAsync(context.CreateTempDirectory(name + "-archive"), "Local", cancellationToken: context.Cancellation);
var client = new ChronosClient(server.HttpBase, new CertificatePinning([]), name) { Token = token };
WorkspaceClient? created = null;
var engine = new JobEngine(db, WorkspaceJobs.CreateHandlers(db, archives, new Connector(client, () => created?.Connected ?? true)),
new JobEngineOptions { Workers = 1, WorkerId = name, PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
await engine.StartAsync(context.Cancellation);
var store = new WorkspaceStore(Path.Combine(context.CreateTempDirectory(name + "-ws"), "workspace"));
created = new WorkspaceClient(context, db, archive, client, engine, store, name);
return created;
}
public ServerProjectHome Home(Guid sequenceId) => new(Client, sequenceId, "Test server");
public ProjectBundle Bundle(Guid projectId) => Store.Find(projectId)!.ReadBundle();
/// <summary>The project checked out and its media downloaded.</summary>
public async Task CheckoutAsync(ServerProjectHome home, Guid projectId)
{
await Sync.CheckoutAsync(home, projectId, cancellationToken: _context.Cancellation);
await CopyAsync(home.SequenceId, projectId);
}
/// <summary>A copy job of the project's media from the server to its end (from <paramref name="checkpoint"/> when given).</summary>
public async Task<Job> CopyAsync(Guid sequenceId, Guid projectId, string? checkpoint = null)
{
var request = WorkspaceJobs.CopyFromServer(sequenceId, Title, Server, Store.Root, projectId);
var job = await EnqueueAsync(request, checkpoint);
return await WaitAsync(job.Id, JobState.Done);
}
public async Task<Job> EnqueueAsync(Data.Archiving.Jobs.ArchiveJobRequest request, string? checkpoint = null)
{
if (checkpoint is null) return await Engine.EnqueueAsync(request, cancellationToken: _context.Cancellation);
var job = new Job
{
Id = Guid.CreateVersion7(),
Kind = request.Kind,
TargetIds = request.Targets,
TargetLabel = request.Label,
ParametersJson = request.ParametersJson,
State = JobState.Queued,
Checkpoint = checkpoint,
Created = DateTimeOffset.UtcNow,
};
await Db.Jobs.EnqueueAsync(job, _context.Cancellation);
Engine.Wake();
return job;
}
public async Task<Job> WaitAsync(Guid jobId, JobState state)
{
var until = DateTime.UtcNow + Wait;
while (true)
{
var job = await Db.Jobs.GetAsync(jobId, _context.Cancellation);
if (job?.State == state) return job;
if (job?.State is JobState.Failed or JobState.Done or JobState.Cancelled) Assert.Fail($"Job ended {job.State}: {job.Error}\n{job.LogTail}");
if (DateTime.UtcNow > until) Assert.Fail($"Job {jobId} did not reach {state} (now {job?.State})");
await Task.Delay(25, _context.Cancellation);
}
}
/// <summary>The working state edited as the editor does: read, changed, stored.</summary>
public async Task EditAsync(Guid projectId, Func<ProjectSettings, ProjectSettings> edit)
{
var session = await Sync.OpenAsync(projectId, _context.Cancellation);
await Sync.SaveAsync(projectId, edit(session.Working), _context.Cancellation);
}
public async Task CommitAndPushAsync(ServerProjectHome home, Guid projectId)
{
Assert.NotNull(await Sync.CommitAsync(projectId, cancellationToken: _context.Cancellation));
Assert.Equal(1, (await Sync.PushAsync(projectId, home, _context.Cancellation)).Pushed.Count);
}
/// <summary>The project's head at the server, its positions placed on the server's frames.</summary>
public async Task<ProjectSettings> PlacedHeadAsync(ServerProjectHome home, Guid projectId)
{
var head = await home.HeadAsync(projectId, _context.Cancellation);
var frames = await home.FramesAsync(_context.Cancellation);
return ProjectSettings.FromJson(ProjectContent.Place(head.SettingsJson, frames.Photos));
}
public async ValueTask DisposeAsync()
{
await Engine.DisposeAsync();
Client.Dispose();
await Db.DisposeAsync();
}
/// <summary>The copy job's connection: a remote over the signed-in client while <c>connected</c> says so.</summary>
private sealed class Connector(ChronosClient client, Func<bool> connected) : ISyncConnector
{
public ValueTask<ISyncRemote?> ConnectAsync(string server, CancellationToken cancellationToken)
{
ISyncRemote remote = new ChronosSyncRemote(client, ownsClient: false);
return ValueTask.FromResult<ISyncRemote?>(connected() && remote.Server == server ? remote : null);
}
}
}
}