Files
Chronos/tests/Chronos.App.Tests/Workspace/ServerHomeTests.cs
T
Alby96andClaude Opus 5.5 9ad8c6f7a9 feat: wire separate homes into the desktop (owner review 5 P3.2)
The desktop now uses the per-home layout from P3.1: each home keeps its
own projects, proxies and originals, and a server is known by its id
whichever address reaches it.

- Settings keep the known servers (id, name, last address, certificate,
  aliases, originals archive). Reset and Import keep them; Export leaves
  them out.
- SyncHost records each server the first time it signs in with an id. It
  names the cache and workspace folders by that id, and re-keys the
  folders a server had under its addresses at sign-in. The re-key waits
  while transfer or workspace jobs are pending.
- Download originals goes to the server's own archive. It is created
  beside this PC's archive at the first download, and a toast says
  where. A sequence that already has a local copy keeps receiving into
  that copy's archive. A server without an id keeps the 1.0 behaviour.
- At start, after the index opens and before any job runs, the folders
  are sorted into their homes. A toast reports the result: sorted,
  pending or failed.
- The workspace host gives each home's store its own sync. Find, List,
  usage, clean-up and the trash plan and empty cover every home. Server
  comparisons go through the identity, so a project stays Online when
  its server is reached by another address.
- The render-node downloads and the server import staging move into the
  server's folder of the cache. The cache trim keeps `servers`, and the
  scheduled scan also scans the originals archives.
- Settings shows the Home folders rows (Workspace) and the Known servers
  table (Server). The diagnostics bundle lists the homes.
- The dead `AppPaths.CreateDirectories` and `ThumbnailsDirectory` are
  removed.

Refs #66

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

422 lines
26 KiB
C#

using System.Globalization;
using System.IO;
using System.Text.Json;
using Chronos.App.Editor;
using Chronos.App.Infrastructure;
using Chronos.App.Tests.Editor;
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.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.SyncOf(projectId).OpenAsync(projectId, bed.Ct);
await other.SyncOf(projectId).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.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 async Task EachHomeChecksOutIntoItsOwnFolderAndTheServerIsOneByItsId()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 3);
var serverId = Guid.CreateVersion7();
var idKey = Chronos.Core.IO.HomeFolders.IdKey(serverId);
var host = bed.Host();
host.Identity = () => new Chronos.Data.Sync.ServerIdentity([new Chronos.Data.Sync.KnownServerKey(serverId, [Server])]);
var server = new FakeServer(bed);
host.ServerHomes = home => host.SameServer(home.Server, idKey) && home.SequenceId == server.Inner.SequenceId ? server : null;
// A server project goes into the server's folder, named by its id even though the project names its address.
var checkout = await host.CheckoutAsync(ServerHome(bed), null, null, cancellationToken: bed.Ct);
var folder = host.Find(checkout.Project.Id)!;
Assert.Equal(Path.Combine(host.Root, "servers", serverId.ToString("N")), folder.Store.Root);
Assert.Equal(Server, folder.ReadBundle().Workspace!.Home.Server);
Assert.True(host.SameServer(Server, idKey), "the address is an alias of the id");
Assert.False(host.SameServer("https://elsewhere:8443", idKey));
// The server told by its id reaches the project that names its address.
var told = new List<WorkspaceHomeChange>();
host.HomeChanged += told.Add;
host.OnServerProjectChanged(idKey, new ProjectChangedEvent(bed.SequenceId, checkout.Project.Id, ProjectChanges.Pushed, 2, Guid.CreateVersion7()));
Assert.Equal(checkout.Project.Id, told.Single().ProjectId);
// A project of this PC's archive goes into local\, and the picker lists both.
var other = bed.Host(name: "second");
var localId = await bed.CheckoutAsync(other);
Assert.Equal(Path.Combine(other.Root, "local"), other.Find(localId)!.Store.Root);
Assert.SequenceEqual([checkout.Project.Id], host.Homes.List().Select(p => p.ProjectId).ToArray());
Assert.Count(1, (await host.ListAsync(bed.Ct)).Where(e => e.ProjectId == checkout.Project.Id));
}
[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, WorkspaceVersionOnRender = false });
var server = new FakeServer(bed);
Connect(host, server);
var projectId = await CheckoutAsync(bed, host);
var told = new List<WorkspaceHomeChange>();
host.HomeChanged += told.Add;
// Opened signed out; the sign-in made later is the one the source connects with.
FakeRemoteSequenceApi? signedIn = null;
var source = new WorkspaceSequenceSource(host.SyncOf(projectId), projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
new WorkspaceServerHome(() => signedIn, () => signedIn));
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);
// Signed in since: the render goes to the server on that sign-in's connection; signed in anew, on the new one's.
var first = new FakeRemoteSequenceApi(await bed.RowAsync(), []);
signedIn = first;
await source.SubmitAsync(session.RenderRequests(session.Project.Export)[0], bed.Ct);
Assert.Equal(1, first.Posted.Count);
var second = new FakeRemoteSequenceApi(await bed.RowAsync(), []);
signedIn = second;
await source.SubmitAsync(session.RenderRequests(session.Project.Export)[0], bed.Ct);
Assert.Equal((1, 1), (first.Posted.Count, second.Posted.Count));
var until = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(10));
while (!first.Disposed && DateTime.UtcNow < until) await Task.Delay(20, bed.Ct);
Assert.True(first.Disposed, "the old sign-in's connection closes");
signedIn = null;
// 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.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.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.SyncOf(projectId).OpenAsync(projectId, bed.Ct);
await other.SyncOf(projectId).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.Find(projectId)?.ReadMedia());
}
}
[Test]
public async Task AServerThatReadsAnOlderFormatIsNotSentSettingsItCannotRead()
{
Assert.Null(ServerJobs.NeedsNewerServer(ProjectSettings.BaseVersion, ProjectSettings.BaseVersion));
Assert.Equal(Loc.L("Tooltips.Server.NeedsNewerServer"), ServerJobs.NeedsNewerServer(2, ProjectSettings.BaseVersion));
// A server that says no format reads the base one; a session-less home too.
Assert.Equal(ProjectSettings.BaseVersion, Chronos.App.Server.SyncHost.SettingsFormatOf(new ServerInfo("Studio NAS", "1.3.0", 1, [], null, [], new ServerLimits(0, 0))));
Assert.Equal(ProjectSettings.BaseVersion, Chronos.App.Server.SyncHost.SettingsFormatOf(null));
Assert.Equal(ProjectSettings.CurrentVersion, Chronos.App.Server.SyncHost.SettingsFormatOf(
new ServerInfo("Studio NAS", "1.4.0", 1, [], null, [], new ServerLimits(0, 0), SettingsFormat: ProjectSettings.CurrentVersion)));
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false, WorkspaceVersionOnRender = false });
var server = new FakeServer(bed) { SettingsFormat = ProjectSettings.BaseVersion };
Connect(host, server);
var projectId = await CheckoutAsync(bed, host);
var source = new WorkspaceSequenceSource(host.SyncOf(projectId), projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
new WorkspaceServerHome(() => null, () => 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();
// A change of the base format goes to the older server as before.
Assert.True(session.SetHero(2));
Assert.Null(menu.PushBlockedReason);
Assert.True(menu.SyncCommand.CanExecute(null));
// A turn needs format 2: Sync is disabled saying why, and a render of it is held.
Assert.True(session.Edit(p => p with { Camera = p.Camera with { Rotate = 90 } }));
Assert.True(await session.FlushAsync());
Assert.Equal(Loc.L("Tooltips.Server.NeedsNewerServer"), menu.PushBlockedReason);
Assert.Equal(menu.PushBlockedReason, menu.SyncToolTip);
Assert.False(menu.SyncCommand.CanExecute(null));
Assert.False(await menu.ReadyToRenderAsync(), "the server cannot read it");
Assert.Equal((Loc.L("Editor.Workspace.RenderHeld"), true), (ui.Toasts[^1].Title, ui.Toasts[^1].IsError));
var before = host.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId;
await menu.SyncAsync();
Assert.Equal(before, host.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId, "nothing was sent");
// Saved as a version with the turn, then turned back: the working state is of the base format, but the version
// waiting to be sent is not. Sync stays disabled, and the workspace itself never sends it (Send first, Delete,
// Resolve reach the host without the menu's gate), saying why.
await host.SaveVersionAsync(projectId, null, bed.Ct);
Assert.True(session.Edit(p => p with { Camera = p.Camera with { Rotate = 0 } }));
Assert.True(await session.FlushAsync());
await menu.RefreshAsync();
Assert.Equal(ProjectSettings.BaseVersion, session.Project.WrittenFormat);
Assert.Equal(2, menu.Status!.UnpushedFormat);
Assert.Equal(Loc.L("Tooltips.Server.NeedsNewerServer"), menu.PushBlockedReason);
Assert.False(menu.SyncCommand.CanExecute(null));
var refused = await Assert.ThrowsAsync<WorkspaceSyncException>(() => host.SyncAsync(projectId, bed.Ct));
Assert.True(refused.HomeReadsOlderFormat);
Assert.Equal(Loc.L("Tooltips.Server.NeedsNewerServer"), WorkspaceText.Failure(refused, server: true));
Assert.Equal(before, host.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId, "nothing was sent");
// A server of this format takes it.
server.SettingsFormat = ProjectSettings.CurrentVersion;
Assert.Null(menu.PushBlockedReason);
Assert.True(menu.SyncCommand.CanExecute(null));
}
}
/// <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.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; } = [];
/// <summary>The settings format the server reads, as its info says.</summary>
public int SettingsFormat { get; set; } = ProjectSettings.CurrentVersion;
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();
}
}
}