using System.Globalization; 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; /// /// 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. /// [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(() => 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(); 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(); 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.Sync, 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(() => 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.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()); } } /// The home a workspace project of the test sequence names on . private static BundleHome ServerHome(WorkspaceTestBed bed) => new(BundleHome.ServerKind, bed.SequenceId, null, Server); /// The host signed in to , as the desktop's SyncHost gives it. 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; /// /// 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). /// private static async Task 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; } /// A server that keeps the archive's projects: reachable or not, with projects deleted there, or none of the sequence's. 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; /// The server answers 404 for the sequence's projects (deleted with their sequence). public bool Missing { get; set; } public HashSet Deleted { get; } = []; public async Task 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> ListAsync(CancellationToken cancellationToken) => Reach(() => Inner.ListAsync(cancellationToken)); public Task CreateAsync(string name, Guid? fromVersionId, string? author, CancellationToken cancellationToken) => Reach(() => Inner.CreateAsync(name, fromVersionId, author, cancellationToken)); /// A project deleted there has no head (404 project), as the server answers. public Task HeadAsync(Guid projectId, CancellationToken cancellationToken) => Deleted.Contains(projectId) ? throw new ProjectException(ProjectError.NotFound, "deleted on the server") : Reach(() => Inner.HeadAsync(projectId, cancellationToken)); public Task GetVersionAsync(Guid projectId, Guid versionId, CancellationToken cancellationToken) => Reach(() => Inner.GetVersionAsync(projectId, versionId, cancellationToken)); public Task> VersionsAfterAsync(Guid projectId, int afterNumber, int limit, CancellationToken cancellationToken) => Reach(() => Inner.VersionsAfterAsync(projectId, afterNumber, limit, cancellationToken)); public Task> HistoryAsync(Guid projectId, int? beforeNumber, int limit, CancellationToken cancellationToken) => Reach(() => Inner.HistoryAsync(projectId, beforeNumber, limit, cancellationToken)); public Task 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 FramesAsync(CancellationToken cancellationToken) => Reach(() => Inner.FramesAsync(cancellationToken)); private Task Reach(Func> call) { if (!Reachable) throw new HomeUnavailableException("The server cannot be reached."); if (Missing) throw new ProjectException(ProjectError.NotFound, "not on the server"); return call(); } } }