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>
232 lines
16 KiB
C#
232 lines
16 KiB
C#
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);
|
||
}
|
||
}
|
||
}
|