merge: or5 parcel p4
# Conflicts: # src/Chronos.App/Sections/ServerView.xaml # src/Chronos.App/Sections/ServerViewModel.cs # src/Chronos.Server/Jobs/JobEngineHost.cs
This commit is contained in:
commit
e367f03c80
127 files changed
+6822
-1117
No files matched your search
@@ -41,6 +41,27 @@ public sealed class ConnectFlowTests
|
||||
Assert.Contains(Fingerprint, server.Created[^1]);
|
||||
}
|
||||
|
||||
/// <summary>Owner review 5, #67: this PC's own shared library is refused before the trust question, and once trusted.</summary>
|
||||
[Test]
|
||||
public async Task ThisPcsOwnSharedLibraryIsRefused()
|
||||
{
|
||||
var server = new FakeServer { SelfSigned = true };
|
||||
var trust = new MemoryTrust();
|
||||
using var flow = new ConnectFlow(server, trust) { IsOwnLibrary = (fingerprint, _) => fingerprint == Fingerprint };
|
||||
Assert.Equal(ConnectStep.Failed, await flow.ProbeAsync("localhost:8443"));
|
||||
Assert.Equal(ConnectError.OwnLibrary, flow.Error);
|
||||
Assert.Null(flow.PendingFingerprint);
|
||||
Assert.Empty(trust.Fingerprints);
|
||||
|
||||
trust.Trust("https://localhost:8443", Fingerprint);
|
||||
Assert.Equal(ConnectStep.Failed, await flow.ProbeAsync("localhost:8443"));
|
||||
Assert.Equal(ConnectError.OwnLibrary, flow.Error);
|
||||
Assert.Equal(0, server.Logins);
|
||||
|
||||
flow.IsOwnLibrary = (_, _) => false;
|
||||
Assert.Equal(ConnectStep.AwaitingCredentials, await flow.ProbeAsync("localhost:8443"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task RejectingTheCertificateSendsNothing()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Sockets;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Jobs;
|
||||
using Chronos.App.Server;
|
||||
using Chronos.App.Tests.Uploader;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Server.Jobs;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.App.Tests.Server;
|
||||
|
||||
/// <summary>Settings › Server › Share this library (owner review 5, #67): the server Chronos hosts over its own index and engines.</summary>
|
||||
[WindowsOnly]
|
||||
[Serial] // the hosted server's logging and Kestrel share the process with the other tests' Log sink
|
||||
[Timeout(180_000)]
|
||||
public sealed class LibraryShareTests
|
||||
{
|
||||
private sealed class NoDialogs : IAppDialogs
|
||||
{
|
||||
public string? PickFolder(string title, string? initialFolder = null) => null;
|
||||
public string? PickJsonFile(string title) => null;
|
||||
public bool Confirm(ConfirmRequest request) => false;
|
||||
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void A10SettingsFileSharesNothingOnDockersPortsAndResetTurnsSharingOff()
|
||||
{
|
||||
var settings = Assert.NotNull(AppSettings.Parse("""{ "Language": "en" }"""));
|
||||
Assert.False(settings.Share.Enabled);
|
||||
Assert.Equal((8443, 8080, true), (settings.Share.HttpsPort, settings.Share.HttpPort, settings.Share.Discovery));
|
||||
Assert.Null(settings.Share.PublicHttpsPort);
|
||||
|
||||
settings.Share.Enabled = true;
|
||||
settings.Share.HttpsPort = 9443;
|
||||
var copy = Assert.NotNull(AppSettings.Parse(settings.ToJson()));
|
||||
Assert.True(copy.Share.Enabled);
|
||||
Assert.Equal(9443, copy.Share.HttpsPort);
|
||||
Assert.False(settings.ResetKeepingState().Share.Enabled);
|
||||
Assert.Equal(8443, settings.ResetKeepingState().Share.HttpsPort);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheSharedLibrarysCleanUpsAreScheduledOnlyWhileSharing()
|
||||
{
|
||||
var settings = new AppSettings();
|
||||
var host = new DesktopScheduleHost(settings, () => null, () => null);
|
||||
Assert.False(host.SystemSchedules.Any(s => s.SystemKey == ServerScheduleHost.UploadCleanup));
|
||||
settings.Share.Enabled = true;
|
||||
var keys = host.SystemSchedules.Select(s => s.SystemKey).ToList();
|
||||
Assert.Contains(ServerScheduleHost.UploadCleanup, keys);
|
||||
Assert.Contains(ServerScheduleHost.AuditCleanup, keys);
|
||||
Assert.Contains(DesktopScheduleHost.ArchiveScan, keys);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SharingStartsAfterTheSchedulesOnTheDesktopsEngineAndStopsFirst()
|
||||
{
|
||||
var environment = AppEnvironment.ForCapture();
|
||||
try
|
||||
{
|
||||
SingleThreadedContext.Run(async () =>
|
||||
{
|
||||
var root = await ArchiveAsync(environment);
|
||||
var (https, http) = (FreePort(), FreePort());
|
||||
var settings = Settings(root, https, http);
|
||||
var services = new AppServices(environment, settings, () => { }, new NoDialogs());
|
||||
try
|
||||
{
|
||||
await services.OpenAsync(environment.DatabasePath);
|
||||
Assert.True(await services.SchedulerReady, "the schedules started");
|
||||
await WaitAsync(services.Share, ShareState.On);
|
||||
|
||||
var share = services.Share;
|
||||
Assert.Equal((https, http), (share.HttpsPort, share.HttpPort));
|
||||
Assert.True(share.Addresses.Count > 0, "addresses");
|
||||
Assert.True(share.Addresses.All(a => a.StartsWith("https://", StringComparison.Ordinal) && a.EndsWith($":{https}", StringComparison.Ordinal)),
|
||||
string.Join(", ", share.Addresses));
|
||||
var fingerprint = Assert.NotNull(share.Fingerprint);
|
||||
Assert.True(share.IsOwn(fingerprint, null), "own by fingerprint");
|
||||
Assert.True(share.IsOwn(null, share.Server!.ServerId), "own by id");
|
||||
Assert.False(share.IsOwn("00:11", Guid.NewGuid()), "another server");
|
||||
Assert.NotNull(share.AdminPassword);
|
||||
Assert.Same(services.Engine, share.Server.Services.GetService(typeof(JobEngineHost)) is JobEngineHost jobs ? jobs.Engine : null);
|
||||
using (var client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) })
|
||||
{
|
||||
using var health = await client.GetAsync($"http://127.0.0.1:{http}/health");
|
||||
Assert.Equal(HttpStatusCode.OK, health.StatusCode);
|
||||
}
|
||||
Assert.NotNull(await services.Database!.Schedules.GetBySystemKeyAsync(ServerScheduleHost.UploadCleanup));
|
||||
Assert.True(Directory.Exists(environment.ShareDirectory), "the share's folder");
|
||||
|
||||
// Stopped, the engine and the index run on; started again, the same certificate.
|
||||
await share.StopAsync();
|
||||
Assert.Equal(ShareState.Off, share.State);
|
||||
Assert.Null(share.Server);
|
||||
Assert.NotNull(await services.Database.Archives.ListAsync());
|
||||
await share.RestartAsync();
|
||||
Assert.Equal(ShareState.On, share.State);
|
||||
Assert.Equal(fingerprint, share.Fingerprint);
|
||||
|
||||
// Sharing turned off in Settings stops it.
|
||||
settings.Share.Enabled = false;
|
||||
share.Apply();
|
||||
await WaitAsync(share, ShareState.Off);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Assert.True(services.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(20)), "services stopped");
|
||||
}
|
||||
Assert.Null(services.Share.Server);
|
||||
});
|
||||
}
|
||||
finally
|
||||
{
|
||||
environment.DeleteCaptureData();
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void APortInUseLeavesSharingNotStartedNamingThePort()
|
||||
{
|
||||
var environment = AppEnvironment.ForCapture();
|
||||
try
|
||||
{
|
||||
SingleThreadedContext.Run(async () =>
|
||||
{
|
||||
var root = await ArchiveAsync(environment);
|
||||
// Held as another server would (both address families, exclusively): Windows lets a second program share a port otherwise.
|
||||
using var taken = new TcpListener(IPAddress.IPv6Any, 0) { ExclusiveAddressUse = true };
|
||||
taken.Server.DualMode = true;
|
||||
taken.Start();
|
||||
var https = ((IPEndPoint)taken.LocalEndpoint).Port;
|
||||
var services = new AppServices(environment, Settings(root, https, FreePort()), () => { }, new NoDialogs());
|
||||
try
|
||||
{
|
||||
await services.OpenAsync(environment.DatabasePath);
|
||||
Assert.True(await services.SchedulerReady, "the schedules started");
|
||||
await WaitAsync(services.Share, ShareState.Failed);
|
||||
Assert.Equal(Loc.L("Errors.Share.PortInUse", https), services.Share.Reason);
|
||||
Assert.Null(services.Share.Server);
|
||||
Assert.False(services.Share.IsOwn(null, null), "nothing shared");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Assert.True(services.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(20)), "services stopped");
|
||||
}
|
||||
});
|
||||
}
|
||||
finally
|
||||
{
|
||||
environment.DeleteCaptureData();
|
||||
}
|
||||
}
|
||||
|
||||
private static AppSettings Settings(string root, int https, int http) => new()
|
||||
{
|
||||
Language = "en",
|
||||
LastArchivePath = root,
|
||||
Share = new ShareSettings { Enabled = true, HttpsPort = https, HttpPort = http, Discovery = false },
|
||||
};
|
||||
|
||||
private static async Task<string> ArchiveAsync(AppEnvironment environment)
|
||||
{
|
||||
var root = Path.Combine(environment.DataDirectory, "archive");
|
||||
await using var setup = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(environment.DataDirectory, "setup.db")));
|
||||
await new ArchiveService(setup).CreateAsync(root, "Shared");
|
||||
return root;
|
||||
}
|
||||
|
||||
private static int FreePort()
|
||||
{
|
||||
using var listener = new TcpListener(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
return ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||
}
|
||||
|
||||
private static async Task WaitAsync(LibraryShare share, ShareState state)
|
||||
{
|
||||
var until = DateTime.UtcNow + TimeSpan.FromSeconds(60);
|
||||
while (share.State != state)
|
||||
{
|
||||
Assert.True(DateTime.UtcNow < until, $"sharing is {share.State} ({share.Reason}), not {state}");
|
||||
await Task.Delay(50);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using Chronos.App.Editor;
|
||||
using Chronos.App.Infrastructure;
|
||||
@@ -50,7 +51,7 @@ public sealed class ServerHomeTests(TestContext context)
|
||||
|
||||
// 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();
|
||||
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!))
|
||||
{
|
||||
@@ -83,8 +84,8 @@ public sealed class ServerHomeTests(TestContext context)
|
||||
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);
|
||||
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));
|
||||
@@ -109,13 +110,46 @@ public sealed class ServerHomeTests(TestContext context)
|
||||
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());
|
||||
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()
|
||||
{
|
||||
@@ -146,7 +180,7 @@ public sealed class ServerHomeTests(TestContext context)
|
||||
|
||||
// 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,
|
||||
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));
|
||||
@@ -181,7 +215,7 @@ public sealed class ServerHomeTests(TestContext context)
|
||||
// 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 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));
|
||||
|
||||
@@ -198,7 +232,7 @@ public sealed class ServerHomeTests(TestContext context)
|
||||
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!;
|
||||
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));
|
||||
@@ -219,8 +253,8 @@ public sealed class ServerHomeTests(TestContext context)
|
||||
// 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 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);
|
||||
@@ -240,7 +274,7 @@ public sealed class ServerHomeTests(TestContext context)
|
||||
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());
|
||||
Assert.NotNull(host.Find(projectId)?.ReadMedia());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -260,7 +294,7 @@ public sealed class ServerHomeTests(TestContext context)
|
||||
var server = new FakeServer(bed) { SettingsFormat = ProjectSettings.BaseVersion };
|
||||
Connect(host, server);
|
||||
var projectId = await CheckoutAsync(bed, host);
|
||||
var source = new WorkspaceSequenceSource(host.Sync, projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
|
||||
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));
|
||||
@@ -282,9 +316,9 @@ public sealed class ServerHomeTests(TestContext context)
|
||||
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.Store.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId;
|
||||
var before = host.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId;
|
||||
await menu.SyncAsync();
|
||||
Assert.Equal(before, host.Store.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId, "nothing was sent");
|
||||
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,
|
||||
@@ -300,7 +334,7 @@ public sealed class ServerHomeTests(TestContext context)
|
||||
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.Store.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId, "nothing was sent");
|
||||
Assert.Equal(before, host.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId, "nothing was sent");
|
||||
|
||||
// A server of this format takes it.
|
||||
server.SettingsFormat = ProjectSettings.CurrentVersion;
|
||||
@@ -323,7 +357,7 @@ public sealed class ServerHomeTests(TestContext context)
|
||||
private static async Task<Guid> CheckoutAsync(WorkspaceTestBed bed, WorkspaceHost host)
|
||||
{
|
||||
var projectId = await bed.CheckoutAsync(host);
|
||||
var folder = host.Store.Find(projectId)!;
|
||||
var folder = host.Find(projectId)!;
|
||||
var bundle = folder.ReadBundle();
|
||||
folder.WriteBundle(bundle with { Workspace = bundle.Workspace! with { Home = ServerHome(bed) } });
|
||||
return projectId;
|
||||
|
||||
@@ -36,7 +36,7 @@ public sealed class WorkspaceCleanupHostTests(TestContext context)
|
||||
var host = bed.Host(settings);
|
||||
var mainId = await bed.CheckoutAsync(host);
|
||||
settings.WorkspaceOpened[mainId] = DateTimeOffset.UtcNow - 40 * Day;
|
||||
var project = host.Store.Find(mainId)!;
|
||||
var project = host.Find(mainId)!;
|
||||
Assert.True(Directory.Exists(project.ProxiesDirectory), "copied");
|
||||
|
||||
// Open in Edit: kept, with why.
|
||||
@@ -66,7 +66,7 @@ public sealed class WorkspaceCleanupHostTests(TestContext context)
|
||||
Assert.Contains("Workspace: projects cleaned: 1", done.LogTail);
|
||||
Assert.Contains(Loc.L("Jobs.Log.WorkspaceTrash", Formatting.Count(0), Formatting.Bytes(0)), done.LogTail);
|
||||
Assert.False(Directory.Exists(project.ProxiesDirectory), "the media went");
|
||||
Assert.True(host.Store.Find(mainId) is not null && File.Exists(project.BundlePath), "the copy and its work stay");
|
||||
Assert.True(host.Find(mainId) is not null && File.Exists(project.BundlePath), "the copy and its work stay");
|
||||
Assert.False((await host.FindAsync(mainId))!.HasMedia, "opening it copies the media again");
|
||||
}
|
||||
|
||||
@@ -76,7 +76,7 @@ public sealed class WorkspaceCleanupHostTests(TestContext context)
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
|
||||
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
|
||||
var mainId = await bed.CheckoutAsync(host);
|
||||
var project = host.Store.Find(mainId)!;
|
||||
var project = host.Find(mainId)!;
|
||||
Directory.CreateDirectory(project.ExportsDirectory);
|
||||
File.WriteAllText(project.ExportFile("clip.mp4"), "rendered");
|
||||
project.WriteRenders(WorkspaceRenders.Empty.With(new WorkspaceRenderEntry(Guid.CreateVersion7(), Guid.CreateVersion7(), "clip.mp4", new string('a', 64), 8,
|
||||
@@ -90,7 +90,7 @@ public sealed class WorkspaceCleanupHostTests(TestContext context)
|
||||
|
||||
var refused = await Assert.ThrowsAsync<WorkspaceException>(() => host.RemoveLocalCopyAsync(mainId, discard: false));
|
||||
Assert.Equal(Loc.L("Errors.Workspace.UnsentRenders"), refused.Message);
|
||||
Assert.NotNull(host.Store.Find(mainId), "nothing was removed");
|
||||
Assert.NotNull(host.Find(mainId), "nothing was removed");
|
||||
var sends = (await bed.Db.Jobs.ListAsync(null, JobKind.WorkspaceSend, cancellationToken: bed.Ct)).Items;
|
||||
var send = Assert.Contains(sends, j => j.TargetIds.Contains(bed.SequenceId));
|
||||
Assert.Equal(mainId, WorkspaceJobs.SendParameters(send)!.ProjectId);
|
||||
@@ -102,7 +102,7 @@ public sealed class WorkspaceCleanupHostTests(TestContext context)
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 2);
|
||||
var host = bed.Host();
|
||||
Assert.True((await host.PlanTrashAsync()).IsEmpty, "no trash yet");
|
||||
var folder = WorkspaceTrash.FolderOf(host.Root);
|
||||
var folder = WorkspaceTrash.FolderOf(host.Homes.Local.Root);
|
||||
foreach (var name in new[] { "a", "b" })
|
||||
{
|
||||
var entry = Directory.CreateDirectory(Path.Combine(folder, Guid.CreateVersion7().ToString("N") + "-" + DateTime.UtcNow.Ticks)).FullName;
|
||||
|
||||
@@ -50,7 +50,7 @@ public sealed class WorkspaceEditorTests(TestContext context)
|
||||
|
||||
Assert.True(session.Edit(p => Exposure(p, 0.4)));
|
||||
Assert.True(await session.FlushAsync());
|
||||
var folder = host.Store.Find(projectId)!;
|
||||
var folder = host.Find(projectId)!;
|
||||
Assert.Equal(0.4, folder.ReadBundle().Project.Exposure.ExposureOffsetEv);
|
||||
Assert.Equal(libraryBefore, (await bed.RowAsync()).SettingsJson, "editing never writes the library");
|
||||
Assert.Equal(WorkspaceState.Modified, (await host.StatusAsync(projectId)).State);
|
||||
@@ -72,12 +72,12 @@ public sealed class WorkspaceEditorTests(TestContext context)
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 3);
|
||||
var host = bed.Host();
|
||||
var projectId = await bed.CheckoutAsync(host);
|
||||
var impatient = new WorkspaceSync(host.Store, "Chronos test") { LockWait = TimeSpan.FromMilliseconds(200) };
|
||||
var impatient = new WorkspaceSync(host.Find(projectId)!.Store, "Chronos test") { LockWait = TimeSpan.FromMilliseconds(200) };
|
||||
var source = new WorkspaceSequenceSource(impatient, projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine);
|
||||
await using (source)
|
||||
{
|
||||
// A long sync or copy holds the project: the editor says so in words, and nothing was read.
|
||||
using (await host.Store.Find(projectId)!.LockAsync(TimeSpan.FromSeconds(TestTiming.Budget(5)), bed.Ct))
|
||||
using (await host.Find(projectId)!.LockAsync(TimeSpan.FromSeconds(TestTiming.Budget(5)), bed.Ct))
|
||||
{
|
||||
var busy = await Assert.ThrowsAsync<EditorException>(() => source.LoadAsync(bed.Ct));
|
||||
Assert.Equal(Loc.L("Errors.Workspace.Busy"), busy.Message);
|
||||
@@ -328,7 +328,7 @@ public sealed class WorkspaceEditorTests(TestContext context)
|
||||
Assert.Equal(excluded, session.Content.Frames[3].Id);
|
||||
Assert.True(session.Edit(p => Exposure(p, 0.2)));
|
||||
Assert.True(await session.FlushAsync(), "saves go on over the new frames");
|
||||
Assert.SequenceEqual([3], host.Store.Find(projectId)!.ReadBundle().Project.ExcludedFrames);
|
||||
Assert.SequenceEqual([3], host.Find(projectId)!.ReadBundle().Project.ExcludedFrames);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -62,7 +62,7 @@ public sealed class WorkspaceFallbackTests(TestContext context)
|
||||
Assert.Equal((Path.GetFullPath(other), before + 1), (settings.WorkspaceFolder, saves));
|
||||
Assert.Equal(Path.GetFullPath(other), host.Root);
|
||||
Assert.Empty(await host.ListAsync());
|
||||
Assert.FileExists(Path.Combine(first, mainId.ToString("N"), WorkspaceProject.BundleFile));
|
||||
Assert.FileExists(Path.Combine(first, "local", mainId.ToString("N"), WorkspaceProject.BundleFile));
|
||||
|
||||
// Chosen back, the default is named by no setting and its project is listed again.
|
||||
Assert.Equal(new WorkspaceFolderPlan(Path.GetFullPath(other), first, 0, 1, false), await host.PlanFolderAsync(first));
|
||||
@@ -155,7 +155,7 @@ public sealed class WorkspaceFallbackTests(TestContext context)
|
||||
Assert.True(await session.FlushAsync());
|
||||
}
|
||||
var unsent = (await host.SaveVersionAsync(mainId, "Not sent")).Version!;
|
||||
var project = host.Store.Find(mainId)!;
|
||||
var project = host.Find(mainId)!;
|
||||
await File.WriteAllTextAsync(project.BundlePath, "{ this is not a project", bed.Ct);
|
||||
// A file this Chronos does not know (a newer one's, the user's own): Discard keeps it too.
|
||||
await File.WriteAllTextAsync(Path.Combine(project.Folder, "notes.txt"), "kept", bed.Ct);
|
||||
@@ -195,11 +195,11 @@ public sealed class WorkspaceFallbackTests(TestContext context)
|
||||
|
||||
var refused = await Assert.ThrowsAsync<WorkspaceException>(() => host.RemoveLocalCopyAsync(mainId, discard: false));
|
||||
Assert.Equal(Loc.L("Errors.Workspace.Damaged"), refused.Message);
|
||||
Assert.NotNull(host.Store.Find(mainId), "nothing was removed");
|
||||
Assert.NotNull(host.Find(mainId), "nothing was removed");
|
||||
|
||||
await host.RemoveLocalCopyAsync(mainId, discard: true);
|
||||
Assert.Null(host.Store.Find(mainId));
|
||||
var aside = Assert.Contains(Directory.EnumerateDirectories(Path.Combine(host.Root, WorkspaceHost.TrashFolder)),
|
||||
Assert.Null(host.Find(mainId));
|
||||
var aside = Assert.Contains(Directory.EnumerateDirectories(Path.Combine(host.Homes.LocalRoot, WorkspaceHost.TrashFolder)),
|
||||
d => Path.GetFileName(d).StartsWith(mainId.ToString("N"), StringComparison.Ordinal));
|
||||
Assert.Equal("{ this is not a project", await File.ReadAllTextAsync(Path.Combine(aside, WorkspaceProject.BundleFile), bed.Ct), "kept as it was");
|
||||
Assert.Equal("kept", await File.ReadAllTextAsync(Path.Combine(aside, "notes.txt"), bed.Ct), "every file of the folder is kept, not only the known ones");
|
||||
@@ -215,7 +215,7 @@ public sealed class WorkspaceFallbackTests(TestContext context)
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
|
||||
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
|
||||
var mainId = await bed.CheckoutAsync(host);
|
||||
var project = host.Store.Find(mainId)!;
|
||||
var project = host.Find(mainId)!;
|
||||
// A newer Chronos on this PC rewrote the working state in a format this one does not know (a downgrade since).
|
||||
var json = System.Text.Json.Nodes.JsonNode.Parse(await File.ReadAllTextAsync(project.BundlePath, bed.Ct))!.AsObject();
|
||||
json["formatVersion"] = ProjectBundle.CurrentFormatVersion + 1;
|
||||
@@ -330,7 +330,7 @@ public sealed class WorkspaceFallbackTests(TestContext context)
|
||||
await host.SaveVersionAsync(mainId, $"Step {i}");
|
||||
}
|
||||
}
|
||||
var project = host.Store.Find(mainId)!;
|
||||
var project = host.Find(mainId)!;
|
||||
Assert.SequenceEqual([1, 2, 3, 4, 5, 6], project.Versions().Where(v => v.StoredAt is not null).Select(v => v.Number).Order());
|
||||
|
||||
// The library's file of version 2 is damaged: the workspace's copy is the only good one left, so it stays.
|
||||
|
||||
@@ -43,7 +43,7 @@ public sealed class WorkspaceHostTests(TestContext context)
|
||||
var elsewhere = Path.Combine(context.CreateTempDirectory("fast-disk"), "Chronos workspace");
|
||||
settings.WorkspaceFolder = elsewhere;
|
||||
Assert.Equal(elsewhere, host.Root);
|
||||
Assert.Equal(elsewhere, host.Store.Root, "the store follows the folder");
|
||||
Assert.Equal(elsewhere, host.Homes.Root, "the homes follow the folder");
|
||||
Assert.FileExists(Path.Combine(elsewhere, WorkspaceStore.ManifestFile));
|
||||
|
||||
// A capture (sample data without an engine) edits its library as before.
|
||||
@@ -142,6 +142,60 @@ public sealed class WorkspaceHostTests(TestContext context)
|
||||
Assert.Count(1, imported.WorkspaceOpened);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheKnownServersStayOnThisPc()
|
||||
{
|
||||
var id = Guid.CreateVersion7();
|
||||
var originals = Guid.CreateVersion7();
|
||||
var mine = new AppSettings
|
||||
{
|
||||
KnownServers = [new KnownServer { Id = id, Name = "Studio NAS", LastAddress = "https://nas.local:8443", Aliases = ["https://nas.local:8443"], OriginalsArchiveId = originals }],
|
||||
};
|
||||
var copy = AppSettings.Parse(mine.ToJson())!;
|
||||
Assert.Equal(("Studio NAS", originals, "https://nas.local:8443"), (copy.KnownServers.Single().Name, copy.KnownServers.Single().OriginalsArchiveId, copy.KnownServers.Single().Aliases.Single()));
|
||||
Assert.Equal(id, copy.FindKnownServer(id)?.Id);
|
||||
Assert.True(copy.KnownIdentity().Same("https://nas.local:8443", Chronos.Core.IO.HomeFolders.IdKey(id)), "an alias names the server by its id");
|
||||
|
||||
// Reset and Import keep what this PC knows of its servers; Export leaves it out.
|
||||
Assert.Equal(id, mine.ResetKeepingState().KnownServers.Single().Id);
|
||||
Assert.Empty(AppSettings.Parse(mine.ForExport().ToJson())!.KnownServers);
|
||||
Assert.Equal(id, mine.KeepLocalIn(AppSettings.Parse(new AppSettings().ToJson())!).KnownServers.Single().Id);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheTrashOfEveryHomeIsPlannedAndEmptiedTogether()
|
||||
{
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 2);
|
||||
var host = bed.Host(name: "homes");
|
||||
var homes = host.Homes;
|
||||
Assert.True(homes.IsSplit, "a new workspace is split into homes");
|
||||
var server = homes.StoreFor(new BundleHome(BundleHome.ServerKind, Guid.CreateVersion7(), null, "https://nas.test:8443")).Root;
|
||||
foreach (var (root, name) in new[] { (homes.Local.Root, "a"), (server, "b") })
|
||||
{
|
||||
var entry = Directory.CreateDirectory(Path.Combine(WorkspaceTrash.FolderOf(root), $"{Guid.CreateVersion7():N}-{name}"));
|
||||
File.WriteAllBytes(Path.Combine(entry.FullName, "file.bin"), new byte[100]);
|
||||
}
|
||||
|
||||
// Settings › Workspace › Home folders: this PC first, then the server by what its folder records.
|
||||
var rows = HomeFolderRow.Of(homes, [], _ => { });
|
||||
Assert.SequenceEqual([Loc.L("Settings.Workspace.ThisPc"), "https://nas.test:8443"], rows.Select(r => r.Name).ToArray());
|
||||
Assert.Equal(server, rows[1].Path);
|
||||
|
||||
var usage = await host.UsageAsync(bed.Ct);
|
||||
Assert.Equal((2, 200L), (usage.TrashItems, usage.TrashBytes));
|
||||
var plan = await host.PlanTrashAsync(bed.Ct);
|
||||
Assert.Equal((2, 200L, 2), (plan.Items.Count, plan.Bytes, plan.Listings.Count));
|
||||
|
||||
// One home's trash changed since the plan: nothing is erased, in either.
|
||||
File.WriteAllBytes(Path.Combine(WorkspaceTrash.FolderOf(server), "late.bin"), new byte[5]);
|
||||
await Assert.ThrowsAsync<WorkspaceException>(() => host.EmptyTrashAsync(plan, bed.Ct));
|
||||
Assert.Equal(3, (await host.UsageAsync(bed.Ct)).TrashItems, "nothing was erased");
|
||||
|
||||
var again = await host.PlanTrashAsync(bed.Ct);
|
||||
Assert.Equal(new WorkspaceTrashResult(3, 205), await host.EmptyTrashAsync(again, bed.Ct));
|
||||
Assert.Equal(0, (await host.UsageAsync(bed.Ct)).TrashItems);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void OpeningAProjectRecordsWhenAndSavesIt()
|
||||
{
|
||||
@@ -309,7 +363,7 @@ public sealed class WorkspaceHostTests(TestContext context)
|
||||
var verticalId2 = (await host.HomeProjectsAsync(bed.SequenceId)).Single(p => !p.IsMain).Id;
|
||||
await bed.CheckoutAsync(host, verticalId2);
|
||||
Assert.Equal("Vertical", await host.RenameAsync(verticalId2, " Vertical "));
|
||||
Assert.Equal("Vertical", host.Store.Find(verticalId2)!.ReadBundle().Workspace!.Name);
|
||||
Assert.Equal("Vertical", host.Find(verticalId2)!.ReadBundle().Workspace!.Name);
|
||||
Assert.Contains((await host.HomeProjectsAsync(bed.SequenceId)), p => p.Name == "Vertical");
|
||||
|
||||
// Delete project…: confirmed, sent first, then gone from the library's list and from the workspace (kept in the library's trash).
|
||||
@@ -329,7 +383,7 @@ public sealed class WorkspaceHostTests(TestContext context)
|
||||
Assert.Equal(1, deleting.Closed);
|
||||
}
|
||||
Assert.DoesNotContain(verticalId2, (await host.HomeProjectsAsync(bed.SequenceId)).Select(p => p.Id));
|
||||
Assert.Null(host.Store.Find(verticalId2));
|
||||
Assert.Null(host.Find(verticalId2));
|
||||
var row = await bed.RowAsync();
|
||||
var trash = Path.Combine(new Chronos.Core.Archiving.ArchivePaths((await bed.Db.Archives.GetAsync(row.ArchiveId))!.RootPath).Sequence(row.Folder).ProjectsTrashDirectory);
|
||||
Assert.True(Directory.EnumerateDirectories(trash).Any(d => Path.GetFileName(d).StartsWith(verticalId2.ToString("N"), StringComparison.Ordinal)),
|
||||
@@ -375,15 +429,15 @@ public sealed class WorkspaceHostTests(TestContext context)
|
||||
Assert.True(request is { IsDestructive: true, TypedConfirmation: "Main" } && request.TypedPrompt is { Length: > 0 });
|
||||
var refused = await Assert.ThrowsAsync<WorkspaceException>(() => host.RemoveLocalCopyAsync(mainId, discard: false));
|
||||
Assert.Equal(Loc.L("Errors.Workspace.Unsent"), refused.Message);
|
||||
Assert.NotNull(host.Store.Find(mainId), "nothing was removed");
|
||||
Assert.NotNull(host.Find(mainId), "nothing was removed");
|
||||
|
||||
// Send first: saved and sent, then the library's copy is read back and checked before the local one goes.
|
||||
await host.SaveVersionAsync(mainId, "Before removal");
|
||||
await host.SyncAsync(mainId);
|
||||
Assert.True((await host.PlanRemovalAsync(mainId)).IsSafe);
|
||||
var folder = host.Store.Find(mainId)!.Folder;
|
||||
var folder = host.Find(mainId)!.Folder;
|
||||
await host.RemoveLocalCopyAsync(mainId, discard: false);
|
||||
Assert.Null(host.Store.Find(mainId));
|
||||
Assert.Null(host.Find(mainId));
|
||||
Assert.False(Directory.Exists(Path.Combine(folder, WorkspaceProject.MediaFolder)), "the copied photos are gone");
|
||||
Assert.Equal(0.3, ProjectSettings.FromJson((await bed.RowAsync()).SettingsJson!).Exposure.ExposureOffsetEv, "the work is in the library");
|
||||
|
||||
@@ -397,14 +451,14 @@ public sealed class WorkspaceHostTests(TestContext context)
|
||||
}
|
||||
var unsent = (await host.SaveVersionAsync(vertical, "Not sent")).Version!;
|
||||
await host.RemoveLocalCopyAsync(vertical, discard: true);
|
||||
Assert.Null(host.Store.Find(vertical));
|
||||
var aside = Assert.Contains(Directory.EnumerateDirectories(Path.Combine(host.Root, WorkspaceHost.TrashFolder)),
|
||||
Assert.Null(host.Find(vertical));
|
||||
var aside = Assert.Contains(Directory.EnumerateDirectories(Path.Combine(host.Homes.LocalRoot, WorkspaceHost.TrashFolder)),
|
||||
d => Path.GetFileName(d).StartsWith(vertical.ToString("N"), StringComparison.Ordinal));
|
||||
Assert.FileExists(Path.Combine(aside, WorkspaceProject.BundleFile));
|
||||
Assert.True(Directory.EnumerateFiles(Path.Combine(aside, WorkspaceProject.VersionsFolder)).Any(f => f.Contains(unsent.Id.ToString("N"), StringComparison.OrdinalIgnoreCase)
|
||||
|| f.Contains(unsent.Id.ToString(), StringComparison.OrdinalIgnoreCase)), "the version never sent is kept");
|
||||
Assert.False(Directory.Exists(Path.Combine(aside, WorkspaceProject.MediaFolder)), "the photos, copies the library can make again, are not");
|
||||
Assert.Empty(host.Store.List());
|
||||
Assert.Empty(host.Homes.List());
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -413,7 +467,7 @@ public sealed class WorkspaceHostTests(TestContext context)
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
|
||||
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
|
||||
var mainId = await bed.CheckoutAsync(host);
|
||||
var project = host.Store.Find(mainId)!;
|
||||
var project = host.Find(mainId)!;
|
||||
var basis = project.ReadBundle().Workspace!.Base!;
|
||||
var conflict = $$"""
|
||||
"conflict": { "theirsVersionId": "{{basis.VersionId}}", "theirsNumber": {{basis.Number}}, "baseVersionId": "{{Guid.CreateVersion7()}}",
|
||||
@@ -449,9 +503,9 @@ public sealed class WorkspaceHostTests(TestContext context)
|
||||
Assert.True((await host.PlanRemovalAsync(vertical)).Gone);
|
||||
var refused = await Assert.ThrowsAsync<WorkspaceException>(() => host.RemoveLocalCopyAsync(vertical, discard: false));
|
||||
Assert.Equal(Loc.L("Errors.Workspace.DeletedAtHome"), refused.Message);
|
||||
Assert.NotNull(host.Store.Find(vertical), "nothing was removed");
|
||||
Assert.NotNull(host.Find(vertical), "nothing was removed");
|
||||
await host.RemoveLocalCopyAsync(vertical, discard: true);
|
||||
Assert.Null(host.Store.Find(vertical));
|
||||
Assert.Null(host.Find(vertical));
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -460,7 +514,7 @@ public sealed class WorkspaceHostTests(TestContext context)
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
|
||||
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
|
||||
var vertical = await bed.CheckoutAsync(host, newName: "Vertical");
|
||||
var project = host.Store.Find(vertical)!;
|
||||
var project = host.Find(vertical)!;
|
||||
var bundle = File.ReadAllBytes(project.BundlePath);
|
||||
var held = Path.Combine(project.Folder, "notes.txt");
|
||||
File.WriteAllText(held, "mine");
|
||||
@@ -471,13 +525,13 @@ public sealed class WorkspaceHostTests(TestContext context)
|
||||
Assert.SequenceEqual(bundle, File.ReadAllBytes(project.BundlePath), "the working state is back");
|
||||
Assert.Contains(await host.ListAsync(), e => e.ProjectId == vertical && e.IsReadable);
|
||||
Assert.True(Directory.Exists(project.MediaDirectory) && Directory.Exists(project.VersionsDirectory), "the copy is whole");
|
||||
var trash = Path.Combine(host.Root, WorkspaceHost.TrashFolder);
|
||||
var trash = Path.Combine(host.Homes.LocalRoot, WorkspaceHost.TrashFolder);
|
||||
Assert.False(Directory.Exists(trash) && Directory.EnumerateDirectories(trash).Any(d => Path.GetFileName(d).StartsWith(vertical.ToString("N"), StringComparison.Ordinal)),
|
||||
"nothing is left aside");
|
||||
|
||||
// The file let go: removed.
|
||||
await host.RemoveLocalCopyAsync(vertical, discard: true);
|
||||
Assert.Null(host.Store.Find(vertical));
|
||||
Assert.Null(host.Find(vertical));
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -496,7 +550,7 @@ public sealed class WorkspaceHostTests(TestContext context)
|
||||
await host.SaveVersionAsync(mainId, $"Step {i}");
|
||||
}
|
||||
}
|
||||
var project = host.Store.Find(mainId)!;
|
||||
var project = host.Find(mainId)!;
|
||||
var kept = project.Versions().Where(v => v.StoredAt is not null).Select(v => v.Number).Order().ToList();
|
||||
Assert.SequenceEqual([5, 6], kept, "the base and the one before it");
|
||||
var history = await host.HistoryAsync(mainId);
|
||||
|
||||
@@ -44,13 +44,13 @@ public sealed class WorkspaceLocalRenderTests(TestContext context)
|
||||
await bed.WaitForJobAsync(checkout.Copy.Id);
|
||||
var projectId = checkout.Project.Id;
|
||||
// Named the server's, as a copy downloaded from the server leaves it.
|
||||
var folder = host.Store.Find(projectId)!;
|
||||
var folder = host.Find(projectId)!;
|
||||
var bundle = folder.ReadBundle();
|
||||
var home = new BundleHome(BundleHome.ServerKind, bed.SequenceId, null, Server);
|
||||
folder.WriteBundle(bundle with { Workspace = bundle.Workspace! with { Home = home } });
|
||||
|
||||
// Not signed in to the server: a render from the originals runs here all the same.
|
||||
var source = new WorkspaceSequenceSource(host.Sync, projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
|
||||
var source = new WorkspaceSequenceSource(host.SyncOf(projectId), projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
|
||||
new WorkspaceServerHome((IRemoteSequenceApi?)null));
|
||||
var content = await source.LoadAsync(bed.Ct);
|
||||
var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
|
||||
@@ -62,7 +62,7 @@ public sealed class WorkspaceLocalRenderTests(TestContext context)
|
||||
Assert.Equal(JobKind.WorkspaceRender, request.Kind);
|
||||
Assert.SequenceEqual([bed.SequenceId], request.Targets);
|
||||
var parameters = Assert.NotNull(WorkspaceJobs.RenderParameters(new Job { Id = Guid.CreateVersion7(), Kind = request.Kind, ParametersJson = request.ParametersJson }));
|
||||
Assert.Equal((projectId, host.Store.Root, Server), (parameters.ProjectId, parameters.WorkspaceRoot, parameters.Server));
|
||||
Assert.Equal((projectId, host.Find(projectId)!.Store.Root, Server), (parameters.ProjectId, parameters.WorkspaceRoot, parameters.Server));
|
||||
var (render, _) = ProcessingJobs.ReadRender(parameters.RenderJson);
|
||||
Assert.NotNull(render.SettingsJson, "the portable settings travel with the job");
|
||||
|
||||
@@ -108,7 +108,7 @@ public sealed class WorkspaceLocalRenderTests(TestContext context)
|
||||
var checkout = await host.CheckoutAsync(bed.SequenceId, null, null, BundleMedia.Originals, cancellationToken: bed.Ct);
|
||||
await bed.WaitForJobAsync(checkout.Copy.Id);
|
||||
var projectId = checkout.Project.Id;
|
||||
var folder = host.Store.Find(projectId)!;
|
||||
var folder = host.Find(projectId)!;
|
||||
var (source, session) = await bed.OpenAsync(host, projectId);
|
||||
var ui = new RecordingUi { ConfirmAnswer = false };
|
||||
await using (session)
|
||||
@@ -155,7 +155,7 @@ public sealed class WorkspaceLocalRenderTests(TestContext context)
|
||||
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 2);
|
||||
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
|
||||
var projectId = await bed.CheckoutAsync(host);
|
||||
var folder = host.Store.Find(projectId)!;
|
||||
var folder = host.Find(projectId)!;
|
||||
Assert.False(await host.SendRendersAsync(projectId, bed.Ct), "nothing waits to be sent");
|
||||
Assert.False(await host.RenderSendPendingAsync(projectId, bed.SequenceId, bed.Ct));
|
||||
|
||||
@@ -171,7 +171,7 @@ public sealed class WorkspaceLocalRenderTests(TestContext context)
|
||||
var sends = (await bed.Db.Jobs.ListAsync(null, 50, null, bed.Ct)).Items.Where(j => j.Kind == JobKind.WorkspaceSend).ToList();
|
||||
Assert.Equal(1, sends.Count);
|
||||
var parameters = Assert.NotNull(WorkspaceJobs.SendParameters(sends[0]));
|
||||
Assert.Equal((projectId, host.Store.Root), (parameters.ProjectId, parameters.WorkspaceRoot));
|
||||
Assert.Equal((projectId, host.Find(projectId)!.Store.Root), (parameters.ProjectId, parameters.WorkspaceRoot));
|
||||
Assert.Empty(parameters.RenderIds);
|
||||
}
|
||||
|
||||
@@ -189,7 +189,7 @@ public sealed class WorkspaceLocalRenderTests(TestContext context)
|
||||
using (var menu = new ProjectMenuViewModel(host, source, session, ui))
|
||||
{
|
||||
await menu.RefreshAsync();
|
||||
var folder = host.Store.Find(projectId)!;
|
||||
var folder = host.Find(projectId)!;
|
||||
var before = folder.Versions().Count;
|
||||
|
||||
// Nothing changed: nothing saved.
|
||||
|
||||
@@ -35,7 +35,7 @@ public sealed class WorkspaceMenuTests(TestContext context)
|
||||
session.ConflictFound += conflicts.Add;
|
||||
await using (session)
|
||||
{
|
||||
var folder = host.Store.Find(projectId)!;
|
||||
var folder = host.Find(projectId)!;
|
||||
// A sync wrote another PC's exclusion of frame 5 while the editor's exclusion of frame 2 waited for its save.
|
||||
var stored = folder.ReadBundle();
|
||||
folder.WriteBundle(stored with { Project = stored.Project with { ExcludedFrames = [5] } });
|
||||
@@ -102,7 +102,7 @@ public sealed class WorkspaceMenuTests(TestContext context)
|
||||
Assert.True(sessionB.Undo());
|
||||
Assert.Equal((0.7, 0.2), (sessionB.Project.Exposure.ExposureOffsetEv, sessionB.Project.Camera.OffsetY));
|
||||
Assert.True(await sessionB.FlushAsync());
|
||||
var working = here.Store.Find(mainId)!.ReadBundle().Project;
|
||||
var working = here.Find(mainId)!.ReadBundle().Project;
|
||||
Assert.Equal((0.7, 0.2), (working.Exposure.ExposureOffsetEv, working.Camera.OffsetY), "the values brought back are stored");
|
||||
}
|
||||
}
|
||||
@@ -172,7 +172,7 @@ public sealed class WorkspaceMenuTests(TestContext context)
|
||||
removing.SendFirstCommand.Execute(null);
|
||||
await WorkspaceTestBed.UntilAsync(() => uiB.Open is ConflictDialogViewModel, "the conflict is asked, not hidden behind Discard");
|
||||
Assert.Equal(0, uiB.Closed, "the editor stays open");
|
||||
Assert.NotNull(here.Store.Find(mainId), "nothing was removed");
|
||||
Assert.NotNull(here.Find(mainId), "nothing was removed");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -211,7 +211,7 @@ public sealed class WorkspaceMenuTests(TestContext context)
|
||||
Assert.Equal(b.Name, copy.Message, "the copy Save both made is offered");
|
||||
Assert.False(b.SaveVersionCommand.CanExecute(null), "nothing can be sent to it");
|
||||
Assert.Equal(0.7, sessionB.Project.Exposure.ExposureOffsetEv, "the work stays in the editor");
|
||||
Assert.Equal(0.7, here.Store.Find(sideId)!.ReadBundle().Project.Exposure.ExposureOffsetEv);
|
||||
Assert.Equal(0.7, here.Find(sideId)!.ReadBundle().Project.Exposure.ExposureOffsetEv);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -254,7 +254,7 @@ public sealed class WorkspaceMenuTests(TestContext context)
|
||||
await using (session)
|
||||
{
|
||||
Assert.False(session.IsReadOnly);
|
||||
var folder = host.Store.Find(projectId)!;
|
||||
var folder = host.Find(projectId)!;
|
||||
var stored = folder.ReadBundle();
|
||||
folder.WriteBundle(stored with { Project = stored.Project with { Version = ProjectSettings.CurrentVersion + 1 } });
|
||||
await session.ReloadAsync();
|
||||
|
||||
@@ -32,7 +32,7 @@ public sealed class WorkspaceNewerFormatTests(TestContext context)
|
||||
Assert.True(session.History.CanUndo);
|
||||
|
||||
// A pull with nothing of this PC's waiting moved the working state onto a newer Chronos's settings.
|
||||
var folder = host.Store.Find(projectId)!;
|
||||
var folder = host.Find(projectId)!;
|
||||
var stored = folder.ReadBundle();
|
||||
folder.WriteBundle(stored with { Project = Exposure(stored.Project, 1.5) with { Version = ProjectSettings.CurrentVersion + 1 } });
|
||||
await session.ReloadAsync();
|
||||
@@ -64,7 +64,7 @@ public sealed class WorkspaceNewerFormatTests(TestContext context)
|
||||
Assert.True(session.Edit(p => Exposure(p, 0.4)));
|
||||
Assert.True(await session.FlushAsync());
|
||||
Assert.NotNull(await host.CommitAsync(projectId, bed.Ct));
|
||||
var folder = host.Store.Find(projectId)!;
|
||||
var folder = host.Find(projectId)!;
|
||||
var stored = folder.ReadBundle();
|
||||
// A sync took a newer Chronos's settings while one more edit waited for its save (made during the sync).
|
||||
folder.WriteBundle(stored with { Project = Exposure(stored.Project, 1.5) with { Version = ProjectSettings.CurrentVersion + 1 } });
|
||||
@@ -86,7 +86,7 @@ public sealed class WorkspaceNewerFormatTests(TestContext context)
|
||||
Assert.Equal(0.4, placed.Exposure.ExposureOffsetEv);
|
||||
Assert.SequenceEqual([2], placed.ExcludedFrames, "the edit as it was, by photo");
|
||||
Assert.False(folder.Versions().Any(v => v.Id == aside.Id), "outside the chain: never sent");
|
||||
Assert.Empty(host.Sync.Unpushed(projectId).Where(v => v.Id == aside.Id));
|
||||
Assert.Empty(host.SyncOf(projectId).Unpushed(projectId).Where(v => v.Id == aside.Id));
|
||||
|
||||
// Read again: no throw, nothing more kept aside, the editor as it is.
|
||||
await session.ReloadAsync();
|
||||
|
||||
@@ -97,7 +97,7 @@ public sealed class WorkspaceOpenPolicyTests(TestContext context)
|
||||
var mainId = section.OpenProjectId!.Value;
|
||||
var menu = Assert.NotNull(section.Editor!.Project);
|
||||
Assert.True(menu.HoldsOriginals);
|
||||
var media = services.Workspace.Store.Find(mainId)!.ReadMedia()!;
|
||||
var media = services.Workspace.Find(mainId)!.ReadMedia()!;
|
||||
Assert.True(media.HoldsOriginals && media.Frames.All(f => f.HasOriginal), "every frame has its original");
|
||||
Assert.True(settings.WorkspaceOpened.ContainsKey(mainId), "the open is recorded for the clean-up");
|
||||
Assert.True(await section.ConfirmCloseAsync());
|
||||
|
||||
@@ -65,7 +65,7 @@ public sealed class WorkspaceSectionTests(TestContext context)
|
||||
await WorkspaceTestBed.UntilAsync(() => project.Status is not null, "its state is read");
|
||||
Assert.Equal(WorkspaceState.InSync, project.Status!.State);
|
||||
Assert.Equal(section.OpenProjectId!.Value, settings.WorkspaceRecent[sequenceId]);
|
||||
Assert.True(File.Exists(Path.Combine(WorkspaceHost.DefaultRoot(environment), section.OpenProjectId.Value.ToString("N"), WorkspaceProject.BundleFile)),
|
||||
Assert.True(File.Exists(Path.Combine(WorkspaceHost.DefaultRoot(environment), "local", section.OpenProjectId.Value.ToString("N"), WorkspaceProject.BundleFile)),
|
||||
"the project lives in the workspace beside the index");
|
||||
|
||||
// Edited in the workspace; the library takes it with the version saved.
|
||||
@@ -231,7 +231,7 @@ public sealed class WorkspaceSectionTests(TestContext context)
|
||||
Assert.True(await section.ConfirmCloseAsync());
|
||||
await section.CloseAsync();
|
||||
shell.KeepSequence(null);
|
||||
var folder = Path.Combine(services.Workspace.Root, mainId.ToString("N"));
|
||||
var folder = Path.Combine(services.Workspace.Homes.LocalRoot, mainId.ToString("N"));
|
||||
var bundle = Path.Combine(folder, WorkspaceProject.BundleFile);
|
||||
|
||||
// Saved by a newer Chronos: said at once, nothing offered over it, nothing asked.
|
||||
@@ -298,7 +298,7 @@ public sealed class WorkspaceSectionTests(TestContext context)
|
||||
await section.CloseAsync();
|
||||
shell.KeepSequence(null);
|
||||
var vertical = (await services.Archives!.Projects.CreateAsync(sequenceId, "Vertical", cancellationToken: context.Cancellation)).Id;
|
||||
var bundle = Path.Combine(services.Workspace.Root, mainId.ToString("N"), WorkspaceProject.BundleFile);
|
||||
var bundle = Path.Combine(services.Workspace.Homes.LocalRoot, mainId.ToString("N"), WorkspaceProject.BundleFile);
|
||||
|
||||
// Damaged: the sequence has another project, so it is asked which; Main is listed, disabled, why in its tooltip.
|
||||
await WriteWhenFreeAsync(bundle, "{ not a project");
|
||||
|
||||
@@ -120,7 +120,7 @@ internal sealed class WorkspaceTestBed : IAsyncDisposable
|
||||
/// <summary>The project open in an editor session over the workspace (saves 20 ms after each edit).</summary>
|
||||
public async Task<(WorkspaceSequenceSource Source, EditorSession Session)> OpenAsync(WorkspaceHost host, Guid projectId)
|
||||
{
|
||||
var source = new WorkspaceSequenceSource(host.Sync, projectId, Db, DecoderFactory.CreateClient(null), Engine);
|
||||
var source = new WorkspaceSequenceSource(host.SyncOf(projectId), projectId, Db, DecoderFactory.CreateClient(null), Engine);
|
||||
var content = await source.LoadAsync(Ct);
|
||||
return (source, new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20)));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Core.Tests.Foundation;
|
||||
|
||||
/// <summary>The folders of the homes (owner review 5, #66): this PC's, a server's by id, a server's by address hash.</summary>
|
||||
public sealed class HomeFoldersTests(TestContext context)
|
||||
{
|
||||
private static readonly Guid ServerId = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
|
||||
|
||||
[Test]
|
||||
public void AnIdKeyNamesItsFolderByTheId()
|
||||
{
|
||||
var key = HomeFolders.IdKey(ServerId);
|
||||
Assert.Equal("id:0192a4c17b3e7cc08a512f9d0e6b1a01", key);
|
||||
Assert.Equal("0192a4c17b3e7cc08a512f9d0e6b1a01", HomeFolders.ServerFolder(key));
|
||||
Assert.Equal(ServerId, HomeFolders.IdOfKey(key));
|
||||
Assert.Equal(ServerId, HomeFolders.IdOfKey("ID:0192A4C17B3E7CC08A512F9D0E6B1A01"));
|
||||
Assert.Equal(ServerId, HomeFolders.IdOfFolder(HomeFolders.ServerFolder(key)));
|
||||
Assert.Throws<ArgumentException>(() => HomeFolders.IdKey(Guid.Empty));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AnAddressKeyNamesItsFolderAsTheProxyCacheOf10Did()
|
||||
{
|
||||
const string key = "https://nas.local:8443";
|
||||
// ProxyCache 1.0: Convert.ToHexStringLower(SHA256(UTF-8 key))[..16].
|
||||
var hash = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(key)))[..16];
|
||||
Assert.Equal(hash, HomeFolders.AddressHash(key));
|
||||
Assert.Equal("addr-" + hash, HomeFolders.ServerFolder(key));
|
||||
Assert.Null(HomeFolders.IdOfKey(key));
|
||||
Assert.True(HomeFolders.IsAddressFolder("addr-" + hash));
|
||||
Assert.True(HomeFolders.IsServerFolder("addr-" + hash));
|
||||
Assert.Null(HomeFolders.IdOfFolder("addr-" + hash));
|
||||
// "id:" with no id after it is an address key like any other.
|
||||
Assert.Equal("addr-" + HomeFolders.AddressHash("id:nothing"), HomeFolders.ServerFolder("id:nothing"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void OnlyAHomeFolderNameIsAServerHome()
|
||||
{
|
||||
Assert.True(HomeFolders.IsServerFolder(ServerId.ToString("N")));
|
||||
foreach (var name in new[] { null, "", "local", "servers", ".trash", ServerId.ToString("N").ToUpperInvariant(), ServerId.ToString("D"), "addr-", "addr-0123",
|
||||
"addr-0123456789ABCDEF", "addr-0123456789abcdefa", "xaddr-0123456789abcdef", Guid.Empty.ToString("N") })
|
||||
Assert.False(HomeFolders.IsServerFolder(name), name ?? "null");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HomePathsLieUnderTheirRoot()
|
||||
{
|
||||
var root = context.CreateTempDirectory("homes");
|
||||
Assert.Equal(Path.Combine(root, "local"), HomeFolders.LocalPath(root));
|
||||
Assert.Equal(Path.Combine(root, "servers", ServerId.ToString("N")), HomeFolders.ServerPath(root, HomeFolders.IdKey(ServerId)));
|
||||
Assert.Equal(Path.Combine(root, "servers", "addr-" + HomeFolders.AddressHash("https://x")), HomeFolders.ServerPath(root, "https://x"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheOriginalsOfAServerGetAnArchiveBesideThisPcs()
|
||||
{
|
||||
var parent = context.CreateTempDirectory("originals");
|
||||
var archive = Path.Combine(parent, "ChronosArchive");
|
||||
Directory.CreateDirectory(archive);
|
||||
Assert.Equal(Path.Combine(parent, "ChronosArchive - Studio NAS"), HomeFolders.OriginalsArchiveRoot(archive, "Studio NAS", Path.Combine(parent, "fallback")));
|
||||
|
||||
// Taken: " (2)"; a name Windows refuses is made safe.
|
||||
Directory.CreateDirectory(Path.Combine(parent, "ChronosArchive - Studio NAS"));
|
||||
Assert.Equal(Path.Combine(parent, "ChronosArchive - Studio NAS (2)"), HomeFolders.OriginalsArchiveRoot(archive + Path.DirectorySeparatorChar, "Studio NAS", "unused"));
|
||||
Assert.Equal(Path.Combine(parent, "ChronosArchive - A B C"), HomeFolders.OriginalsArchiveRoot(archive, "A:B/C", "unused"));
|
||||
Assert.Equal(Path.Combine(parent, "ChronosArchive - Taken (3)"),
|
||||
HomeFolders.OriginalsArchiveRoot(archive, "Taken", "unused", path => !path.EndsWith("(3)", StringComparison.Ordinal)));
|
||||
|
||||
// No archive of this PC's: beside where its first one would go.
|
||||
var fallback = Path.Combine(parent, "Pictures", "ChronosArchive");
|
||||
Assert.Equal(Path.Combine(parent, "Pictures", "ChronosArchive - NAS"), HomeFolders.OriginalsArchiveRoot(null, "NAS", fallback));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ASafeNameIsAFolderNameEveryDriveTakes()
|
||||
{
|
||||
Assert.Equal("Studio NAS", HomeFolders.SafeName(" Studio \t NAS. "));
|
||||
Assert.Equal("a b", HomeFolders.SafeName("a<>:\"|?*b"));
|
||||
Assert.Equal("CON_", HomeFolders.SafeName("con".ToUpperInvariant()));
|
||||
Assert.Equal("nul.box_", HomeFolders.SafeName("nul.box"));
|
||||
Assert.Equal("Server", HomeFolders.SafeName("..."));
|
||||
Assert.Equal("Server", HomeFolders.SafeName(null));
|
||||
Assert.Equal(HomeFolders.MaxNameLength, HomeFolders.SafeName(new string('x', 200)).Length);
|
||||
}
|
||||
}
|
||||
@@ -18,11 +18,8 @@ public sealed class AppPathsTests(TestContext context)
|
||||
Assert.Equal(Path.Combine(app, "data", "chronos.db"), paths.DatabasePath);
|
||||
Assert.False(paths.IsInSyncedFolder);
|
||||
Assert.Null(paths.PortableSyncRoot);
|
||||
|
||||
paths.CreateDirectories();
|
||||
Assert.True(Directory.Exists(paths.LogsDirectory));
|
||||
Assert.True(Directory.Exists(paths.CacheDirectory));
|
||||
Assert.True(Directory.Exists(paths.ThumbnailsDirectory));
|
||||
Assert.Equal(Path.Combine(app, "data", "logs"), paths.LogsDirectory);
|
||||
Assert.Equal(Path.Combine(app, "data", "cache"), paths.CacheDirectory);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -50,22 +47,19 @@ public sealed class AppPathsTests(TestContext context)
|
||||
Assert.Equal(Path.Combine(local, "Chronos"), paths.DataRoot);
|
||||
Assert.Equal<string?>(oneDrive, paths.PortableSyncRoot);
|
||||
Assert.False(paths.IsInSyncedFolder);
|
||||
paths.CreateDirectories();
|
||||
Assert.True(Directory.Exists(paths.LogsDirectory));
|
||||
Assert.False(Directory.Exists(Path.Combine(app, "data")), "nothing is written into the synchronised folder");
|
||||
Assert.Equal(Path.Combine(local, "Chronos", "logs"), paths.LogsDirectory);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DataInsideOneDriveIsReportedAndRefused()
|
||||
public void DataInsideOneDriveIsReported()
|
||||
{
|
||||
// Local application data inside a sync root: nowhere is safe, so nothing is created.
|
||||
// Local application data inside a sync root: nowhere is safe, and the app tells the user.
|
||||
var oneDrive = context.CreateTempDirectory("onedrive");
|
||||
var local = Directory.CreateDirectory(Path.Combine(oneDrive, "AppData", "Local")).FullName;
|
||||
|
||||
var paths = AppPaths.Resolve(context.CreateTempDirectory("app"), local, [oneDrive]);
|
||||
Assert.True(paths.IsInSyncedFolder);
|
||||
Assert.Equal<string?>(oneDrive, paths.SyncedFolder);
|
||||
Assert.Throws<InvalidOperationException>(paths.CreateDirectories);
|
||||
Assert.False(Directory.Exists(paths.DataRoot));
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Workspaces;
|
||||
|
||||
namespace Chronos.Data.Tests.Homes;
|
||||
|
||||
/// <summary>Workspaces and caches laid out as 1.0 left them, for the sorting into homes (owner review 5, #66).</summary>
|
||||
internal static class HomeFixtures
|
||||
{
|
||||
public const string Nas = "https://nas.local:8443";
|
||||
public const string NasByIp = "https://192.168.1.5:8443";
|
||||
public const string Other = "https://other.example:8443";
|
||||
|
||||
/// <summary>A working state of <paramref name="home"/> written into <c><root>/<id></c> with some media, versions and a render.</summary>
|
||||
public static Guid Project(string root, BundleHome home, string name = "Main", DateTimeOffset? saved = null, Guid? id = null, int proxies = 3)
|
||||
{
|
||||
var projectId = id ?? Guid.CreateVersion7();
|
||||
var folder = Path.Combine(root, projectId.ToString("N"));
|
||||
Directory.CreateDirectory(folder);
|
||||
var archive = home.IsArchive
|
||||
? new BundleArchive(home.ArchiveId ?? Guid.CreateVersion7(), "This PC", @"D:\ChronosArchive")
|
||||
: new BundleArchive(Data.Projects.ServerProjectHome.ArchiveIdOf(home.Server!), "Studio NAS", null);
|
||||
var bundle = new ProjectBundle(archive, new BundleSequence(home.SequenceId, "2026/2026-11-15 Harbour", "Harbour", proxies), new ProjectSettings(),
|
||||
saved ?? DateTimeOffset.UtcNow)
|
||||
{
|
||||
Workspace = new BundleWorkspace(projectId, name, true, home, null, new BundleMedia(BundleMedia.Proxies, 1)),
|
||||
};
|
||||
bundle.Save(Path.Combine(folder, WorkspaceProject.BundleFile));
|
||||
var media = Path.Combine(folder, WorkspaceProject.MediaFolder, WorkspaceProject.ProxiesFolder);
|
||||
Directory.CreateDirectory(media);
|
||||
for (var i = 0; i < proxies; i++) File.WriteAllBytes(Path.Combine(media, Guid.CreateVersion7().ToString("N") + ".jpg"), Bytes(projectId, i, 500 + i));
|
||||
Directory.CreateDirectory(Path.Combine(folder, WorkspaceProject.VersionsFolder));
|
||||
File.WriteAllText(Path.Combine(folder, WorkspaceProject.VersionsFolder, "1-" + Guid.CreateVersion7().ToString("N") + ".json"), "{}");
|
||||
Directory.CreateDirectory(Path.Combine(folder, WorkspaceProject.ExportsFolder));
|
||||
File.WriteAllBytes(Path.Combine(folder, WorkspaceProject.ExportsFolder, "render.mp4"), Bytes(projectId, 99, 2048));
|
||||
return projectId;
|
||||
}
|
||||
|
||||
public static BundleHome Local() => new(BundleHome.ArchiveKind, Guid.CreateVersion7(), Guid.CreateVersion7());
|
||||
|
||||
public static BundleHome Server(string key) => new(BundleHome.ServerKind, Guid.CreateVersion7(), null, key);
|
||||
|
||||
/// <summary>A 1.0 workspace: its manifest (format 1) and the folder.</summary>
|
||||
public static string LegacyWorkspace(string parent)
|
||||
{
|
||||
var root = Path.Combine(parent, "workspace");
|
||||
_ = new WorkspaceStore(root);
|
||||
return root;
|
||||
}
|
||||
|
||||
/// <summary>A trash entry of <paramref name="projectId"/> holding a working state, as a removal leaves it.</summary>
|
||||
public static string TrashEntry(string root, Guid projectId, BundleHome home)
|
||||
{
|
||||
var trash = Path.Combine(root, WorkspaceTrash.FolderName);
|
||||
var staging = Path.Combine(trash, "staging");
|
||||
Directory.CreateDirectory(staging);
|
||||
Project(staging, home, id: projectId, proxies: 1);
|
||||
var entry = Path.Combine(trash, projectId.ToString("N") + "-638000000000000000");
|
||||
Directory.Move(Path.Combine(staging, projectId.ToString("N")), entry);
|
||||
Directory.Delete(staging);
|
||||
return entry;
|
||||
}
|
||||
|
||||
/// <summary>The 1.0 proxy cache of <paramref name="key"/>'s sequence <paramref name="remoteId"/>.</summary>
|
||||
public static string LegacyProxies(string cache, string key, Guid remoteId, int frames = 2)
|
||||
{
|
||||
var folder = Data.Sync.ProxyCache.LegacyFolder(Path.Combine(cache, "proxies"), key, remoteId);
|
||||
Directory.CreateDirectory(folder);
|
||||
File.WriteAllText(Path.Combine(folder, "remote.json"), "{}");
|
||||
for (var i = 0; i < frames; i++) File.WriteAllBytes(Path.Combine(folder, Guid.CreateVersion7().ToString("N") + ".jpg"), Bytes(remoteId, i, 300));
|
||||
return folder;
|
||||
}
|
||||
|
||||
/// <summary>A live lease on a project folder, as another Chronos working on the same workspace holds it.</summary>
|
||||
public static LeaseFile Hold(string projectFolder) =>
|
||||
LeaseFile.TryAcquire(projectFolder, ".lock", "workspace@other", TimeSpan.FromMinutes(5)) ?? throw new InvalidOperationException("The lease is held.");
|
||||
|
||||
/// <summary>
|
||||
/// The SHA-256 of every file under <paramref name="root"/> by its name relative to the project or entry it belongs to,
|
||||
/// whatever home folder holds it: the same before and after a sorting that only renames (the test-only proof).
|
||||
/// </summary>
|
||||
public static SortedDictionary<string, string> Manifest(string root)
|
||||
{
|
||||
var manifest = new SortedDictionary<string, string>(StringComparer.Ordinal);
|
||||
if (!Directory.Exists(root)) return manifest;
|
||||
foreach (var file in Directory.EnumerateFiles(root, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
var relative = Path.GetRelativePath(root, file).Replace('\\', '/');
|
||||
var name = Path.GetFileName(file);
|
||||
if (name is WorkspaceStore.ManifestFile or "server.json" && !relative.Contains('/', StringComparison.Ordinal)) continue;
|
||||
if (name is WorkspaceStore.ManifestFile or "server.json" && IsHomeLevel(relative)) continue;
|
||||
manifest[Strip(relative)] = Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(file))) + "|" + new FileInfo(file).Length;
|
||||
}
|
||||
return manifest;
|
||||
}
|
||||
|
||||
/// <summary>A path without the home folders it lies in (<c>local/</c>, <c>servers/<folder>/</c>).</summary>
|
||||
private static string Strip(string relative)
|
||||
{
|
||||
if (relative.StartsWith("local/", StringComparison.Ordinal)) return relative["local/".Length..];
|
||||
if (relative.StartsWith("servers/", StringComparison.Ordinal))
|
||||
{
|
||||
var rest = relative["servers/".Length..];
|
||||
var slash = rest.IndexOf('/', StringComparison.Ordinal);
|
||||
return slash < 0 ? rest : rest[(slash + 1)..];
|
||||
}
|
||||
return relative;
|
||||
}
|
||||
|
||||
private static bool IsHomeLevel(string relative) =>
|
||||
relative.Split('/') is { Length: 2 } parts && parts[0] == "local" || relative.Split('/') is { Length: 3 } more && more[0] == "servers";
|
||||
|
||||
private static byte[] Bytes(Guid seed, int index, int length)
|
||||
{
|
||||
var bytes = new byte[length];
|
||||
var hash = SHA256.HashData(Encoding.UTF8.GetBytes(seed.ToString("N") + index));
|
||||
for (var i = 0; i < length; i++) bytes[i] = hash[i % hash.Length];
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Homes;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Homes;
|
||||
|
||||
/// <summary>The one-time sorting of a 1.0 workspace and cache into homes (owner review 5, #66).</summary>
|
||||
[Category("homes")]
|
||||
public sealed class HomeLayoutMigrationTests(TestContext context)
|
||||
{
|
||||
private static readonly Guid Id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
|
||||
|
||||
/// <summary>A 1.0 data folder: a workspace with local, server and damaged projects and a trash, and a cache with proxies, render-node files and a staged import.</summary>
|
||||
private sealed class Legacy
|
||||
{
|
||||
public required string Data { get; init; }
|
||||
public required string Workspace { get; init; }
|
||||
public required string Cache { get; init; }
|
||||
public required Guid Local { get; init; }
|
||||
public required Guid OnNas { get; init; }
|
||||
public required Guid OnOther { get; init; }
|
||||
public required Guid Damaged { get; init; }
|
||||
public required Guid NasRemote { get; init; }
|
||||
|
||||
public HomeLayoutMigration Migration(ServerIdentity? identity = null, Action<string, string>? cut = null) =>
|
||||
new(new HomeLayoutOptions
|
||||
{
|
||||
DataDirectory = Data,
|
||||
WorkspaceRoot = Workspace,
|
||||
CacheRoot = Cache,
|
||||
Identity = identity ?? ServerIdentity.None,
|
||||
CurrentServer = HomeFixtures.Nas,
|
||||
})
|
||||
{ Cut = cut };
|
||||
}
|
||||
|
||||
private Legacy Make()
|
||||
{
|
||||
var data = context.CreateTempDirectory("data");
|
||||
var workspace = HomeFixtures.LegacyWorkspace(data);
|
||||
var local = HomeFixtures.Project(workspace, HomeFixtures.Local());
|
||||
var onNas = HomeFixtures.Project(workspace, HomeFixtures.Server(HomeFixtures.Nas));
|
||||
var onOther = HomeFixtures.Project(workspace, HomeFixtures.Server(HomeFixtures.Other));
|
||||
var damaged = Guid.CreateVersion7();
|
||||
Directory.CreateDirectory(Path.Combine(workspace, damaged.ToString("N")));
|
||||
File.WriteAllText(Path.Combine(workspace, damaged.ToString("N"), WorkspaceProject.BundleFile), "{ not json");
|
||||
HomeFixtures.TrashEntry(workspace, onNas, HomeFixtures.Server(HomeFixtures.Nas));
|
||||
File.WriteAllText(Path.Combine(workspace, WorkspaceTrash.FolderName, "loose.txt"), "kept");
|
||||
var cache = Path.Combine(data, "cache");
|
||||
var nasRemote = Guid.CreateVersion7();
|
||||
HomeFixtures.LegacyProxies(cache, HomeFixtures.Nas, nasRemote);
|
||||
HomeFixtures.LegacyProxies(cache, HomeFixtures.Other, Guid.CreateVersion7());
|
||||
Directory.CreateDirectory(Path.Combine(cache, "render-node", "job1"));
|
||||
File.WriteAllText(Path.Combine(cache, "render-node", "job1", "frame.jpg"), "rn");
|
||||
Directory.CreateDirectory(Path.Combine(cache, "server-import"));
|
||||
File.WriteAllText(Path.Combine(cache, "server-import", "card.part"), "import");
|
||||
return new Legacy
|
||||
{
|
||||
Data = data,
|
||||
Workspace = workspace,
|
||||
Cache = cache,
|
||||
Local = local,
|
||||
OnNas = onNas,
|
||||
OnOther = onOther,
|
||||
Damaged = damaged,
|
||||
NasRemote = nasRemote,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Every file and folder under <paramref name="root"/> with its size and time: what a dry run must leave as it was.</summary>
|
||||
private static List<string> Snapshot(string root) =>
|
||||
[.. new DirectoryInfo(root).EnumerateFileSystemInfos("*", SearchOption.AllDirectories)
|
||||
.Select(e => Path.GetRelativePath(root, e.FullName) + "|" + (e is FileInfo f ? f.Length + "|" + f.LastWriteTimeUtc.Ticks : "dir"))
|
||||
.Order(StringComparer.Ordinal)];
|
||||
|
||||
private static string Home(string workspace, string key) => Path.Combine(workspace, "servers", HomeFolders.ServerFolder(key));
|
||||
|
||||
private static void AssertSorted(Legacy legacy, string nasFolder)
|
||||
{
|
||||
var ws = legacy.Workspace;
|
||||
Assert.True(WorkspaceHomes.IsSplitRoot(ws));
|
||||
Assert.FileExists(Path.Combine(ws, "local", legacy.Local.ToString("N"), WorkspaceProject.BundleFile));
|
||||
Assert.FileExists(Path.Combine(ws, "local", legacy.Damaged.ToString("N"), WorkspaceProject.BundleFile));
|
||||
Assert.FileExists(Path.Combine(ws, "servers", nasFolder, legacy.OnNas.ToString("N"), WorkspaceProject.BundleFile));
|
||||
Assert.FileExists(Path.Combine(Home(ws, HomeFixtures.Other), legacy.OnOther.ToString("N"), WorkspaceProject.BundleFile));
|
||||
Assert.FileExists(Path.Combine(ws, "local", WorkspaceTrash.FolderName, "loose.txt"));
|
||||
Assert.Count(1, Directory.EnumerateDirectories(Path.Combine(ws, "servers", nasFolder, WorkspaceTrash.FolderName)));
|
||||
Assert.False(Directory.EnumerateDirectories(ws).Any(d => Guid.TryParseExact(Path.GetFileName(d), "N", out _)), "no project is left in the parent");
|
||||
Assert.False(Directory.Exists(Path.Combine(ws, WorkspaceTrash.FolderName)), "the parent's emptied trash went");
|
||||
Assert.Equal("Studio NAS", Assert.NotNull(ServerHomeRecord.Read(Path.Combine(ws, "servers", nasFolder))).Name);
|
||||
Assert.FileExists(Path.Combine(legacy.Cache, "servers", nasFolder, "proxies", legacy.NasRemote.ToString("N"), "remote.json"));
|
||||
Assert.True(Directory.Exists(Path.Combine(legacy.Cache, "servers", HomeFolders.ServerFolder(HomeFixtures.Other), "proxies")));
|
||||
Assert.FileExists(Path.Combine(legacy.Cache, "servers", nasFolder, "render-node", "job1", "frame.jpg"));
|
||||
Assert.FileExists(Path.Combine(legacy.Cache, "servers", nasFolder, "import", "card.part"));
|
||||
Assert.False(Directory.Exists(Path.Combine(legacy.Cache, "render-node")));
|
||||
Assert.FileMissing(Path.Combine(legacy.Data, HomeLayoutMigration.JournalFile));
|
||||
var homes = new WorkspaceHomes(ws);
|
||||
Assert.True(homes.IsSplit);
|
||||
Assert.Equal(4, homes.List().Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ThePlanWritesNothing()
|
||||
{
|
||||
var legacy = Make();
|
||||
var before = Snapshot(legacy.Data);
|
||||
var plan = await legacy.Migration().PlanAsync(context.Cancellation);
|
||||
Assert.SequenceEqual(before, Snapshot(legacy.Data));
|
||||
Assert.True(plan.SplitsWorkspace);
|
||||
Assert.Null(plan.Deferred);
|
||||
Assert.Equal(4, plan.Projects);
|
||||
Assert.Equal(2, plan.Entries.Count(e => e.Kind == HomeEntryKind.Trash));
|
||||
Assert.Equal(2, plan.Entries.Count(e => e.Kind == HomeEntryKind.Proxies));
|
||||
Assert.Equal(1, plan.Entries.Count(e => e.Kind == HomeEntryKind.RenderNode));
|
||||
Assert.Equal(1, plan.Entries.Count(e => e.Kind == HomeEntryKind.Import));
|
||||
var damaged = plan.Entries.Single(e => e.Source.EndsWith(legacy.Damaged.ToString("N"), StringComparison.Ordinal));
|
||||
Assert.Equal(Path.Combine(legacy.Workspace, "local", legacy.Damaged.ToString("N")), damaged.Target);
|
||||
Assert.Equal(plan.Fingerprint, (await legacy.Migration().PlanAsync(context.Cancellation)).Fingerprint);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SortingMovesEveryHomeAndRenamesOnly()
|
||||
{
|
||||
var legacy = Make();
|
||||
var before = HomeFixtures.Manifest(legacy.Workspace);
|
||||
var cacheBefore = HomeFixtures.Manifest(legacy.Cache);
|
||||
var result = await legacy.Migration().ApplyAsync(context.Cancellation);
|
||||
Assert.Equal((4, 0, false, true), (result.ProjectsMoved, result.InUse, result.Resumed, result.Split));
|
||||
AssertSorted(legacy, HomeFolders.ServerFolder(HomeFixtures.Nas));
|
||||
// Every file is there with the same name relative to its project and the same bytes: the sorting only renamed.
|
||||
Assert.SequenceEqual(before, HomeFixtures.Manifest(legacy.Workspace));
|
||||
Assert.SequenceEqual(cacheBefore.Values.Order(), HomeFixtures.Manifest(legacy.Cache).Values.Order());
|
||||
|
||||
// A second run does nothing.
|
||||
var again = await legacy.Migration().ApplyAsync(context.Cancellation);
|
||||
Assert.Equal(HomeLayoutResult.Nothing, again);
|
||||
Assert.True((await legacy.Migration().PlanAsync(context.Cancellation)).IsEmpty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AServerKnownByIdGetsItsIdHome()
|
||||
{
|
||||
var legacy = Make();
|
||||
await legacy.Migration(new ServerIdentity([new KnownServerKey(Id, [HomeFixtures.Nas])])).ApplyAsync(context.Cancellation);
|
||||
AssertSorted(legacy, Id.ToString("N"));
|
||||
Assert.Equal(ServerIdentity.IdKey(Id), Assert.NotNull(ServerHomeRecord.Read(Path.Combine(legacy.Workspace, "servers", Id.ToString("N")))).Key);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ACrashAtAnyStepIsTakenUpToTheSameEnd()
|
||||
{
|
||||
var entries = (await Make().Migration().PlanAsync(context.Cancellation)).Entries.Count;
|
||||
var cuts = new List<(string Step, int Occurrence)> { ("journal", 1), ("commit", 1) };
|
||||
for (var i = 1; i <= entries; i++) cuts.AddRange([("rename", i), ("renamed", i)]);
|
||||
foreach (var (step, occurrence) in cuts)
|
||||
{
|
||||
var legacy = Make();
|
||||
var before = HomeFixtures.Manifest(legacy.Workspace);
|
||||
var seen = 0;
|
||||
var crashing = legacy.Migration(cut: (name, _) =>
|
||||
{
|
||||
if (name == step && ++seen == occurrence) throw new IOException("cut at " + step);
|
||||
});
|
||||
await Assert.ThrowsAsync<IOException>(() => crashing.ApplyAsync(context.Cancellation));
|
||||
Assert.FileExists(Path.Combine(legacy.Data, HomeLayoutMigration.JournalFile));
|
||||
var resumed = await legacy.Migration().ApplyAsync(context.Cancellation);
|
||||
Assert.True(resumed.Resumed, $"{step} #{occurrence}");
|
||||
AssertSorted(legacy, HomeFolders.ServerFolder(HomeFixtures.Nas));
|
||||
Assert.SequenceEqual(before, HomeFixtures.Manifest(legacy.Workspace), $"{step} #{occurrence}");
|
||||
Assert.Equal(HomeLayoutResult.Nothing, await legacy.Migration().ApplyAsync(context.Cancellation));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AProjectInUseIsLeftAndMovedAtALaterStart()
|
||||
{
|
||||
var legacy = Make();
|
||||
var held = HomeFixtures.Hold(Path.Combine(legacy.Workspace, legacy.Local.ToString("N")));
|
||||
HomeLayoutResult result;
|
||||
using (held)
|
||||
{
|
||||
var plan = await legacy.Migration().PlanAsync(context.Cancellation);
|
||||
Assert.SequenceEqual(new[] { legacy.Local }, plan.InUse);
|
||||
result = await legacy.Migration().ApplyAsync(context.Cancellation);
|
||||
Assert.Equal((3, 1, true), (result.ProjectsMoved, result.InUse, result.Split));
|
||||
Assert.True(WorkspaceHomes.IsSplitRoot(legacy.Workspace));
|
||||
var homes = new WorkspaceHomes(legacy.Workspace);
|
||||
Assert.Equal(homes.Root, Path.GetDirectoryName(Assert.NotNull(homes.Find(legacy.Local)).Folder));
|
||||
Assert.Equal(4, homes.List().Count);
|
||||
}
|
||||
result = await legacy.Migration().ApplyAsync(context.Cancellation);
|
||||
Assert.Equal((1, 0), (result.ProjectsMoved, result.InUse));
|
||||
Assert.FileExists(Path.Combine(legacy.Workspace, "local", legacy.Local.ToString("N"), WorkspaceProject.BundleFile));
|
||||
Assert.Null(new WorkspaceHomes(legacy.Workspace).Homes().FirstOrDefault(h => h.IsLegacy));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnUnfinishedMoveDefersTheWorkspaceWhileTheCacheIsSorted()
|
||||
{
|
||||
var legacy = Make();
|
||||
File.WriteAllText(Path.Combine(legacy.Workspace, WorkspaceMover.JournalFile), "{}");
|
||||
var before = Snapshot(legacy.Workspace);
|
||||
var result = await legacy.Migration().ApplyAsync(context.Cancellation);
|
||||
Assert.Equal((HomeLayoutDeferral?)HomeLayoutDeferral.Moving, result.Deferred);
|
||||
Assert.False(result.Split);
|
||||
Assert.SequenceEqual(before, Snapshot(legacy.Workspace));
|
||||
Assert.FileExists(Path.Combine(legacy.Cache, "servers", HomeFolders.ServerFolder(HomeFixtures.Nas), "proxies", legacy.NasRemote.ToString("N"), "remote.json"));
|
||||
|
||||
File.Delete(Path.Combine(legacy.Workspace, WorkspaceMover.JournalFile));
|
||||
await legacy.Migration().ApplyAsync(context.Cancellation);
|
||||
AssertSorted(legacy, HomeFolders.ServerFolder(HomeFixtures.Nas));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AWorkspaceThatWentOfflineWaitsWithItsJournal()
|
||||
{
|
||||
var legacy = Make();
|
||||
var before = HomeFixtures.Manifest(legacy.Workspace);
|
||||
await Assert.ThrowsAsync<IOException>(() => legacy.Migration(cut: (name, _) =>
|
||||
{
|
||||
if (name == "journal") throw new IOException("cut");
|
||||
}).ApplyAsync(context.Cancellation));
|
||||
// The drive goes before the next start.
|
||||
var away = legacy.Workspace + "-unplugged";
|
||||
Directory.Move(legacy.Workspace, away);
|
||||
var waiting = await legacy.Migration().ApplyAsync(context.Cancellation);
|
||||
Assert.Equal((HomeLayoutDeferral?)HomeLayoutDeferral.Offline, waiting.Deferred);
|
||||
Assert.FileExists(Path.Combine(legacy.Data, HomeLayoutMigration.JournalFile));
|
||||
Assert.FileExists(Path.Combine(legacy.Cache, "servers", HomeFolders.ServerFolder(HomeFixtures.Nas), "import", "card.part"));
|
||||
// Back: the workspace is sorted, the cache left as it is now.
|
||||
Directory.Move(away, legacy.Workspace);
|
||||
await legacy.Migration().ApplyAsync(context.Cancellation);
|
||||
AssertSorted(legacy, HomeFolders.ServerFolder(HomeFixtures.Nas));
|
||||
Assert.SequenceEqual(before, HomeFixtures.Manifest(legacy.Workspace));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AProjectInBothPlacesKeepsTheCopySavedLastAndTrashesTheOther()
|
||||
{
|
||||
var data = context.CreateTempDirectory("data");
|
||||
var workspace = HomeFixtures.LegacyWorkspace(data);
|
||||
var id = Guid.CreateVersion7();
|
||||
var home = HomeFixtures.Local();
|
||||
HomeFixtures.Project(workspace, home, "newer", DateTimeOffset.UtcNow, id);
|
||||
HomeFixtures.Project(Path.Combine(workspace, "local"), home, "older", DateTimeOffset.UtcNow.AddDays(-1), id);
|
||||
var files = Directory.EnumerateFiles(workspace, "*", SearchOption.AllDirectories).Count(f => Path.GetFileName(f) != WorkspaceStore.ManifestFile);
|
||||
var result = await new HomeLayoutMigration(new HomeLayoutOptions { DataDirectory = data, WorkspaceRoot = workspace }).ApplyAsync(context.Cancellation);
|
||||
Assert.Equal(1, result.Clashes);
|
||||
var kept = ProjectBundle.Load(Path.Combine(workspace, "local", id.ToString("N"), WorkspaceProject.BundleFile));
|
||||
Assert.Equal("newer", kept.Workspace!.Name);
|
||||
var trashed = Assert.NotNull(Directory.EnumerateDirectories(Path.Combine(workspace, "local", WorkspaceTrash.FolderName)).SingleOrDefault());
|
||||
Assert.Equal("older", ProjectBundle.Load(Path.Combine(trashed, WorkspaceProject.BundleFile)).Workspace!.Name);
|
||||
Assert.Equal(files, Directory.EnumerateFiles(workspace, "*", SearchOption.AllDirectories)
|
||||
.Count(f => Path.GetFileName(f) is not (WorkspaceStore.ManifestFile or "server.json")), "nothing was deleted");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ARenameThatDoesNotCheckStopsWithItsJournal()
|
||||
{
|
||||
var legacy = Make();
|
||||
var tampered = false;
|
||||
var migration = legacy.Migration(cut: (name, path) =>
|
||||
{
|
||||
if (name != "renamed" || tampered || !Directory.Exists(path)) return;
|
||||
tampered = true;
|
||||
File.WriteAllText(Path.Combine(path, "stray.txt"), "written meanwhile");
|
||||
});
|
||||
await Assert.ThrowsAsync<HomeLayoutException>(() => migration.ApplyAsync(context.Cancellation));
|
||||
Assert.FileExists(Path.Combine(legacy.Data, HomeLayoutMigration.JournalFile));
|
||||
// The next start takes it up; the entry found renamed is taken as moved.
|
||||
await legacy.Migration().ApplyAsync(context.Cancellation);
|
||||
AssertSorted(legacy, HomeFolders.ServerFolder(HomeFixtures.Nas));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AWorkspaceNeverMadeOrAlreadySortedHasNothingToDo()
|
||||
{
|
||||
var data = context.CreateTempDirectory("data");
|
||||
var options = new HomeLayoutOptions { DataDirectory = data, WorkspaceRoot = Path.Combine(data, "workspace"), CacheRoot = Path.Combine(data, "cache") };
|
||||
Assert.True((await new HomeLayoutMigration(options).PlanAsync(context.Cancellation)).IsEmpty);
|
||||
Assert.Equal(HomeLayoutResult.Nothing, await new HomeLayoutMigration(options).ApplyAsync(context.Cancellation));
|
||||
Assert.False(Directory.Exists(options.WorkspaceRoot));
|
||||
|
||||
_ = new WorkspaceHomes(options.WorkspaceRoot);
|
||||
Assert.True((await new HomeLayoutMigration(options).PlanAsync(context.Cancellation)).IsEmpty);
|
||||
|
||||
// An empty 1.0 workspace is split by its manifest alone.
|
||||
var empty = HomeFixtures.LegacyWorkspace(context.CreateTempDirectory("empty"));
|
||||
var split = await new HomeLayoutMigration(options with { WorkspaceRoot = empty }).ApplyAsync(context.Cancellation);
|
||||
Assert.True(split.Split);
|
||||
Assert.True(WorkspaceHomes.IsSplitRoot(empty));
|
||||
Assert.Equal(WorkspaceStore.FormatVersion, new WorkspaceStore(Path.Combine(empty, "local")).Manifest.FormatVersion);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Homes;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Data.Tests.Infrastructure;
|
||||
using Chronos.Data.Tests.Repositories;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Homes;
|
||||
|
||||
/// <summary>A server's home moves from its address to its id when it first announces one (owner review 5, #66).</summary>
|
||||
[Category("homes")]
|
||||
public sealed class HomeRekeyTests(TestContext context)
|
||||
{
|
||||
private static readonly Guid Id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
|
||||
private static string IdFolder => Id.ToString("N");
|
||||
|
||||
private (string Data, WorkspaceHomes Homes, string Cache) Make()
|
||||
{
|
||||
var data = context.CreateTempDirectory("data");
|
||||
return (data, new WorkspaceHomes(Path.Combine(data, "workspace")), Path.Combine(data, "cache"));
|
||||
}
|
||||
|
||||
private static HomeLayoutMigration Migration(string data, WorkspaceHomes homes, string cache) =>
|
||||
new(new HomeLayoutOptions { DataDirectory = data, WorkspaceRoot = homes.Root, CacheRoot = cache });
|
||||
|
||||
private static string AddressHome(string root, string key) => Path.Combine(root, "servers", HomeFolders.ServerFolder(key));
|
||||
|
||||
private static ProjectBundle Bundle(string home, Guid id) => ProjectBundle.Load(Path.Combine(home, id.ToString("N"), WorkspaceProject.BundleFile));
|
||||
|
||||
[Test]
|
||||
public async Task TheHomeOfTheAddressBecomesTheHomeOfTheId()
|
||||
{
|
||||
var (data, homes, cache) = Make();
|
||||
var home = HomeFixtures.Server(HomeFixtures.Nas);
|
||||
var store = homes.StoreFor(home);
|
||||
var (a, b) = (HomeFixtures.Project(store.Root, home), HomeFixtures.Project(store.Root, HomeFixtures.Server(HomeFixtures.Nas)));
|
||||
HomeFixtures.TrashEntry(store.Root, a, home);
|
||||
var before = HomeFixtures.Manifest(homes.Root);
|
||||
var (sorted, old) = (Guid.CreateVersion7(), Guid.CreateVersion7());
|
||||
var cached = Path.Combine(AddressHome(cache, HomeFixtures.Nas), "proxies", sorted.ToString("N"));
|
||||
Directory.CreateDirectory(cached);
|
||||
File.WriteAllText(Path.Combine(cached, "remote.json"), "{}");
|
||||
HomeFixtures.LegacyProxies(cache, HomeFixtures.Nas, old);
|
||||
|
||||
var result = await Migration(data, homes, cache).RekeyAsync(Id, [HomeFixtures.Nas], context.Cancellation);
|
||||
Assert.Equal(new HomeRekeyResult(2, 0, 0, 2, 0, 0, 0), result);
|
||||
var idHome = Path.Combine(homes.Root, "servers", IdFolder);
|
||||
Assert.False(Directory.Exists(AddressHome(homes.Root, HomeFixtures.Nas)));
|
||||
var idKey = ServerIdentity.IdKey(Id);
|
||||
foreach (var id in new[] { a, b })
|
||||
{
|
||||
var bundle = Bundle(idHome, id);
|
||||
Assert.Equal(idKey, bundle.Workspace!.Home!.Server);
|
||||
Assert.Equal(ServerProjectHome.ArchiveIdOf(idKey), bundle.Archive.Id);
|
||||
}
|
||||
var record = Assert.NotNull(ServerHomeRecord.Read(idHome));
|
||||
Assert.Equal((idKey, (Guid?)Id, HomeFixtures.Nas), (record.Key, record.Id, record.Address));
|
||||
Assert.Count(1, Directory.EnumerateDirectories(Path.Combine(idHome, WorkspaceTrash.FolderName)));
|
||||
// Only the working states were rewritten: every other file is as it was.
|
||||
var after = HomeFixtures.Manifest(homes.Root);
|
||||
Assert.SequenceEqual(before.Keys, after.Keys);
|
||||
Assert.SequenceEqual(before.Where(f => !f.Key.EndsWith(WorkspaceProject.BundleFile, StringComparison.Ordinal)),
|
||||
after.Where(f => !f.Key.EndsWith(WorkspaceProject.BundleFile, StringComparison.Ordinal)));
|
||||
|
||||
Assert.FileExists(Path.Combine(cache, "servers", IdFolder, "proxies", sorted.ToString("N"), "remote.json"));
|
||||
Assert.FileExists(Path.Combine(cache, "servers", IdFolder, "proxies", old.ToString("N"), "remote.json"));
|
||||
Assert.False(Directory.Exists(AddressHome(cache, HomeFixtures.Nas)));
|
||||
// The store now finds the id home by either key.
|
||||
var identity = new ServerIdentity([new KnownServerKey(Id, [HomeFixtures.Nas])]);
|
||||
Assert.Equal(idHome, new WorkspaceHomes(homes.Root, identity).ServerRoot(HomeFixtures.Nas));
|
||||
|
||||
// Again: nothing left to do.
|
||||
Assert.Equal(new HomeRekeyResult(0, 0, 0, 0, 0, 0, 0), await Migration(data, homes, cache).RekeyAsync(Id, [HomeFixtures.Nas], context.Cancellation));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TwoAddressesOfOneServerMergeAndTheOlderCopyGoesToTheTrash()
|
||||
{
|
||||
var (data, homes, cache) = Make();
|
||||
var byName = HomeFixtures.Server(HomeFixtures.Nas);
|
||||
var byIp = HomeFixtures.Server(HomeFixtures.NasByIp);
|
||||
var first = homes.StoreFor(byName).Root;
|
||||
var second = homes.StoreFor(byIp).Root;
|
||||
var both = Guid.CreateVersion7();
|
||||
HomeFixtures.Project(first, byName, "older", DateTimeOffset.UtcNow.AddDays(-1), both);
|
||||
HomeFixtures.Project(second, byIp, "newer", DateTimeOffset.UtcNow, both);
|
||||
var onlyFirst = HomeFixtures.Project(first, byName);
|
||||
var onlySecond = HomeFixtures.Project(second, byIp);
|
||||
HomeFixtures.TrashEntry(first, onlyFirst, byName);
|
||||
HomeFixtures.TrashEntry(second, onlyFirst, byIp);
|
||||
var files = Directory.EnumerateFiles(homes.Root, "*", SearchOption.AllDirectories).Count(IsProjectFile);
|
||||
// Each address had a proxy cache too.
|
||||
Directory.CreateDirectory(Path.Combine(AddressHome(cache, HomeFixtures.Nas), "proxies", "a"));
|
||||
Directory.CreateDirectory(Path.Combine(AddressHome(cache, HomeFixtures.NasByIp), "proxies", "a"));
|
||||
Directory.CreateDirectory(Path.Combine(AddressHome(cache, HomeFixtures.NasByIp), "proxies", "b"));
|
||||
|
||||
var result = await Migration(data, homes, cache).RekeyAsync(Id, [HomeFixtures.Nas, HomeFixtures.NasByIp], context.Cancellation);
|
||||
Assert.Equal((2, 2, 1, 3), (result.HomesMoved, result.ProjectsMoved, result.ProjectsTrashed, result.BundlesRewritten));
|
||||
var idHome = Path.Combine(homes.Root, "servers", IdFolder);
|
||||
Assert.Equal("newer", Bundle(idHome, both).Workspace!.Name);
|
||||
foreach (var id in new[] { onlyFirst, onlySecond }) Assert.FileExists(Path.Combine(idHome, id.ToString("N"), WorkspaceProject.BundleFile));
|
||||
var trash = Directory.EnumerateDirectories(Path.Combine(idHome, WorkspaceTrash.FolderName)).ToList();
|
||||
Assert.Equal(3, trash.Count);
|
||||
Assert.Contains(trash, t => ProjectBundle.Load(Path.Combine(t, WorkspaceProject.BundleFile)).Workspace!.Name == "older");
|
||||
// The second address's home held only its manifest and record afterwards: it went. Nothing else was deleted.
|
||||
Assert.False(Directory.Exists(second));
|
||||
Assert.Equal(files, Directory.EnumerateFiles(homes.Root, "*", SearchOption.AllDirectories).Count(IsProjectFile));
|
||||
Assert.Count(1, Directory.EnumerateDirectories(Path.Combine(homes.Root, "servers")));
|
||||
Assert.True(Directory.Exists(Path.Combine(cache, "servers", IdFolder, "proxies", "b")));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AProjectInUseStaysAndKeepsItsAliasWhichStillMatches()
|
||||
{
|
||||
var (data, homes, cache) = Make();
|
||||
var home = HomeFixtures.Server(HomeFixtures.Nas);
|
||||
var root = homes.StoreFor(home).Root;
|
||||
var (held, free) = (HomeFixtures.Project(root, home), HomeFixtures.Project(root, HomeFixtures.Server(HomeFixtures.Nas)));
|
||||
HomeRekeyResult result;
|
||||
using (HomeFixtures.Hold(Path.Combine(root, held.ToString("N"))))
|
||||
{
|
||||
// A project in use keeps the whole home where it is until a later re-key; the id home is made beside it.
|
||||
_ = new WorkspaceStore(Path.Combine(homes.Root, "servers", IdFolder));
|
||||
result = await Migration(data, homes, cache).RekeyAsync(Id, [HomeFixtures.Nas], context.Cancellation);
|
||||
}
|
||||
Assert.Equal((0, 1, 1), (result.HomesMoved, result.ProjectsMoved, result.BundlesRewritten));
|
||||
Assert.FileExists(Path.Combine(root, held.ToString("N"), WorkspaceProject.BundleFile));
|
||||
Assert.Equal(HomeFixtures.Nas, Bundle(root, held).Workspace!.Home!.Server);
|
||||
var idHome = Path.Combine(homes.Root, "servers", IdFolder);
|
||||
Assert.Equal(ServerIdentity.IdKey(Id), Bundle(idHome, free).Workspace!.Home!.Server);
|
||||
Assert.True(ServerProjectHome.IsArchiveIdOf(Bundle(root, held).Archive.Id, [ServerIdentity.IdKey(Id), HomeFixtures.Nas]));
|
||||
Assert.NotNull(homes.Find(held));
|
||||
|
||||
result = await Migration(data, homes, cache).RekeyAsync(Id, [HomeFixtures.Nas], context.Cancellation);
|
||||
Assert.Equal((1, 1), (result.ProjectsMoved, result.BundlesRewritten));
|
||||
Assert.False(Directory.Exists(root));
|
||||
Assert.Equal(ServerIdentity.IdKey(Id), Bundle(idHome, held).Workspace!.Home!.Server);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AWorkingStateInUseInTheIdHomeIsLeftNamingTheAlias()
|
||||
{
|
||||
var (data, homes, cache) = Make();
|
||||
var home = HomeFixtures.Server(HomeFixtures.Nas);
|
||||
var root = homes.StoreFor(home).Root;
|
||||
var id = HomeFixtures.Project(root, home);
|
||||
// Renamed whole first (nothing held), then held while its working state would be rewritten.
|
||||
var idHome = Path.Combine(homes.Root, "servers", IdFolder);
|
||||
Directory.Move(root, idHome);
|
||||
HomeRekeyResult result;
|
||||
using (HomeFixtures.Hold(Path.Combine(idHome, id.ToString("N"))))
|
||||
result = await Migration(data, homes, cache).RekeyAsync(Id, [HomeFixtures.Nas], context.Cancellation);
|
||||
Assert.Equal((0, 1), (result.BundlesRewritten, result.BundlesInUse));
|
||||
Assert.Equal(HomeFixtures.Nas, Bundle(idHome, id).Workspace!.Home!.Server);
|
||||
Assert.Equal(ServerIdentity.IdKey(Id), Assert.NotNull(ServerHomeRecord.Read(idHome)).Key);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnIdKeyIsNeverAnAliasAndAnEmptyIdIsRefused()
|
||||
{
|
||||
var (data, homes, cache) = Make();
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => Migration(data, homes, cache).RekeyAsync(Guid.Empty, [HomeFixtures.Nas], context.Cancellation));
|
||||
var other = ServerIdentity.IdKey(Guid.CreateVersion7());
|
||||
var otherHome = homes.StoreFor(HomeFixtures.Server(other)).Root;
|
||||
Assert.Equal(new HomeRekeyResult(0, 0, 0, 0, 0, 0, 0), await Migration(data, homes, cache).RekeyAsync(Id, [other], context.Cancellation));
|
||||
Assert.True(Directory.Exists(otherHome));
|
||||
}
|
||||
|
||||
private static bool IsProjectFile(string path) => Path.GetFileName(path) is not (WorkspaceStore.ManifestFile or HomeFolders.ServerFile);
|
||||
}
|
||||
|
||||
/// <summary>A re-key moves the server's links in the index too.</summary>
|
||||
[Category("homes")]
|
||||
public abstract class HomeRekeyLinkTests(TestContext context) : RepositoryTest(context)
|
||||
{
|
||||
private static readonly Guid Id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
|
||||
|
||||
[Test]
|
||||
public async Task TheLinksOfEveryAliasMoveToTheId()
|
||||
{
|
||||
var db = await OpenChronosAsync();
|
||||
var store = new SyncLinkStore(db);
|
||||
foreach (var key in new[] { HomeFixtures.Nas, HomeFixtures.NasByIp, HomeFixtures.Other })
|
||||
{
|
||||
await store.UpsertAsync(new SyncLink
|
||||
{
|
||||
Server = key,
|
||||
RemoteId = Guid.CreateVersion7(),
|
||||
Title = "Harbour",
|
||||
RemoteUpdatedAt = TestData.Now,
|
||||
SyncedAt = TestData.Now,
|
||||
}, Ct);
|
||||
}
|
||||
var data = Context.CreateTempDirectory("data");
|
||||
var migration = new HomeLayoutMigration(new HomeLayoutOptions { DataDirectory = data, Database = db });
|
||||
var result = await migration.RekeyAsync(Id, [HomeFixtures.Nas, HomeFixtures.NasByIp], Ct);
|
||||
Assert.Equal((2, 0), (result.LinksMoved, result.LinksDropped));
|
||||
Assert.Count(2, await store.ListAsync(ServerIdentity.IdKey(Id), Ct));
|
||||
Assert.Count(1, await store.ListAsync(HomeFixtures.Other, Ct));
|
||||
Assert.Empty(await store.ListAsync(HomeFixtures.Nas, Ct));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SqliteHomeRekeyLinkTests(TestContext context) : HomeRekeyLinkTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.SqliteMemory;
|
||||
}
|
||||
|
||||
public sealed class PostgresHomeRekeyLinkTests(TestContext context) : HomeRekeyLinkTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.Postgres;
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Data.Tests.Homes;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Sync;
|
||||
|
||||
/// <summary>Where the proxies of a server's sequence live (owner review 5, #66): its home in the cache, else where an earlier layout left them.</summary>
|
||||
[Category("sync")]
|
||||
public sealed class ProxyCacheTests(TestContext context)
|
||||
{
|
||||
private static readonly Guid Id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
|
||||
|
||||
[Test]
|
||||
public void WithoutAServersRootTheLayoutIs10s()
|
||||
{
|
||||
var root = context.CreateTempDirectory("proxies");
|
||||
var remote = Guid.CreateVersion7();
|
||||
var cache = new ProxyCache(root);
|
||||
Assert.Equal(Path.Combine(root, HomeFolders.AddressHash(HomeFixtures.Nas), remote.ToString("N")), cache.Folder(HomeFixtures.Nas, remote));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ANewSequenceGoesToItsServersHomeAndAnOldOneIsReadWhereItIs()
|
||||
{
|
||||
var cacheRoot = context.CreateTempDirectory("cache");
|
||||
var (legacyRoot, servers) = (Path.Combine(cacheRoot, "proxies"), Path.Combine(cacheRoot, "servers"));
|
||||
var identity = new ServerIdentity([new KnownServerKey(Id, [HomeFixtures.Nas])]);
|
||||
var cache = new ProxyCache(legacyRoot, servers, () => identity);
|
||||
var idKey = ServerIdentity.IdKey(Id);
|
||||
|
||||
var fresh = Guid.CreateVersion7();
|
||||
Assert.Equal(Path.Combine(servers, Id.ToString("N"), "proxies", fresh.ToString("N")), cache.Folder(idKey, fresh));
|
||||
Assert.Equal(cache.Folder(idKey, fresh), cache.Folder(HomeFixtures.Nas, fresh), "an alias names the same home");
|
||||
|
||||
// A sequence cached by 1.0 under the address is used where it is until it is moved.
|
||||
var old = Guid.CreateVersion7();
|
||||
var legacy = HomeFixtures.LegacyProxies(cacheRoot, HomeFixtures.Nas, old);
|
||||
Assert.Equal(legacy, cache.Folder(idKey, old));
|
||||
Assert.True(cache.Exists(idKey, old));
|
||||
|
||||
// In the home of the address (sorted before the server announced its id): used there too.
|
||||
var sorted = Guid.CreateVersion7();
|
||||
var byAddress = Path.Combine(servers, HomeFolders.ServerFolder(HomeFixtures.Nas), "proxies", sorted.ToString("N"));
|
||||
Directory.CreateDirectory(byAddress);
|
||||
Assert.Equal(byAddress, cache.Folder(idKey, sorted));
|
||||
|
||||
// Once in its home, that is where it is.
|
||||
var home = Path.Combine(servers, Id.ToString("N"), "proxies", old.ToString("N"));
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(home)!);
|
||||
Directory.Move(legacy, home);
|
||||
Assert.Equal(home, cache.Folder(HomeFixtures.Nas, old));
|
||||
|
||||
// A server known by its address only has an address home.
|
||||
var other = Guid.CreateVersion7();
|
||||
Assert.Equal(Path.Combine(servers, HomeFolders.ServerFolder(HomeFixtures.Other), "proxies", other.ToString("N")), cache.Folder(HomeFixtures.Other, other));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Sync;
|
||||
|
||||
/// <summary>How the desktop names a server (owner review 5, #66): by its announced id, its address keys kept as aliases.</summary>
|
||||
[Category("sync")]
|
||||
public sealed class ServerIdentityTests
|
||||
{
|
||||
private static readonly Guid Id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
|
||||
|
||||
private static ServerInfo Info(Guid? id) => new("Studio NAS", "1.1.0", 1, [], null, [], new ServerLimits(1, 1), null, null, id);
|
||||
|
||||
[Test]
|
||||
public void AServerThatAnnouncesAnIdIsKeyedByIt()
|
||||
{
|
||||
var key = ServerIdentity.Key(Info(Id), new Uri("https://NAS.local:8443/"));
|
||||
Assert.Equal("id:" + Id.ToString("N"), key);
|
||||
Assert.True(ServerIdentity.IsIdKey(key));
|
||||
Assert.Equal(Id, ServerIdentity.IdOf(key));
|
||||
// Another address of the same server: the same key.
|
||||
Assert.Equal(key, ServerIdentity.Key(Info(Id), new Uri("https://192.168.1.5:8443")));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AnOlderServerKeepsItsAddressKey()
|
||||
{
|
||||
var address = new Uri("https://NAS.local:8443/");
|
||||
Assert.Equal("https://nas.local:8443", ServerIdentity.Key(Info(null), address));
|
||||
Assert.Equal(SyncService.ServerKey(address), ServerIdentity.Key((ServerInfo?)null, address));
|
||||
Assert.Equal(SyncService.ServerKey(address), ServerIdentity.Key(Guid.Empty, address));
|
||||
Assert.False(ServerIdentity.IsIdKey(SyncService.ServerKey(address)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AliasesNameTheServerOfTheirId()
|
||||
{
|
||||
var identity = new ServerIdentity([new KnownServerKey(Id, ["https://nas.local:8443", "https://192.168.1.5:8443"])]);
|
||||
var key = ServerIdentity.IdKey(Id);
|
||||
Assert.Equal(key, identity.Canonical("https://NAS.local:8443"));
|
||||
Assert.Equal(key, identity.Canonical(key.ToUpperInvariant()));
|
||||
Assert.Equal("https://other:1", identity.Canonical("https://other:1"));
|
||||
Assert.True(identity.Same("https://nas.local:8443", "https://192.168.1.5:8443"));
|
||||
Assert.True(identity.Same(key, "https://192.168.1.5:8443"));
|
||||
Assert.False(identity.Same(key, "https://other:1"));
|
||||
Assert.True(identity.Same(null, null));
|
||||
Assert.False(identity.Same(key, null));
|
||||
Assert.Equal(Id.ToString("N"), identity.FolderName("https://192.168.1.5:8443"));
|
||||
Assert.Equal(HomeFolders.ServerFolder("https://other:1"), identity.FolderName("https://other:1"));
|
||||
Assert.SequenceEqual(new[] { key, "https://nas.local:8443", "https://192.168.1.5:8443" }, identity.KeysOf("https://192.168.1.5:8443"));
|
||||
Assert.SequenceEqual(new[] { "https://other:1" }, identity.KeysOf("https://other:1"));
|
||||
Assert.Equal(2, identity.AliasesOf(Id).Count);
|
||||
|
||||
// Without the table every key is its own.
|
||||
Assert.False(ServerIdentity.None.Same(key, "https://nas.local:8443"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AnAddressChangeKeepsTheKeyOnceTheAliasIsKnown()
|
||||
{
|
||||
var identity = new ServerIdentity([new KnownServerKey(Id, ["https://nas.local:8443"])]);
|
||||
var widened = identity.With(Id, "https://nas.local:9443");
|
||||
Assert.True(widened.Same("https://nas.local:8443", "https://nas.local:9443"));
|
||||
Assert.Same(widened, widened.With(Id, "HTTPS://nas.local:9443"));
|
||||
Assert.False(identity.Same("https://nas.local:8443", "https://nas.local:9443"), "the table it came from is unchanged");
|
||||
var other = Guid.CreateVersion7();
|
||||
Assert.Equal(ServerIdentity.IdKey(other), widened.With(other, "https://second:1").Canonical("https://second:1"));
|
||||
// An address two ids claim stays with the first one listed.
|
||||
var clash = new ServerIdentity([new KnownServerKey(Id, ["https://x"]), new KnownServerKey(other, ["https://x"])]);
|
||||
Assert.Equal(ServerIdentity.IdKey(Id), clash.Canonical("https://x"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheArchiveIdOfAnyAliasIsTheServers()
|
||||
{
|
||||
string[] keys = [ServerIdentity.IdKey(Id), "https://nas.local:8443"];
|
||||
Assert.True(ServerProjectHome.IsArchiveIdOf(ServerProjectHome.ArchiveIdOf("https://nas.local:8443"), keys));
|
||||
Assert.True(ServerProjectHome.IsArchiveIdOf(ServerProjectHome.ArchiveIdOf(keys[0]), keys));
|
||||
Assert.False(ServerProjectHome.IsArchiveIdOf(ServerProjectHome.ArchiveIdOf("https://other:1"), keys));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Data.Tests.Infrastructure;
|
||||
using Chronos.Data.Tests.Repositories;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Sync;
|
||||
|
||||
/// <summary>A server's links move from its address key to its id key (owner review 5, #66), the newer row winning a clash.</summary>
|
||||
[Category("sync")]
|
||||
public abstract class SyncLinkRekeyTests(TestContext context) : RepositoryTest(context)
|
||||
{
|
||||
private const string Address = "https://nas.local:8443";
|
||||
private static readonly string IdKey = ServerIdentity.IdKey(Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01"));
|
||||
|
||||
private static SyncLink Link(string server, Guid remoteId, Guid? localId, DateTimeOffset? synced, string title = "Harbour") => new()
|
||||
{
|
||||
Server = server,
|
||||
RemoteId = remoteId,
|
||||
LocalId = localId,
|
||||
Title = title,
|
||||
RemoteUpdatedAt = TestData.Now,
|
||||
SyncedAt = synced,
|
||||
};
|
||||
|
||||
[Test]
|
||||
public async Task TheLinksOfAnAddressMoveToTheIdAndTheNewerRowWinsAClash()
|
||||
{
|
||||
var db = await OpenChronosAsync();
|
||||
var archive = TestData.Archive();
|
||||
await db.Archives.UpsertAsync(archive, Ct);
|
||||
var (a, b, c) = (TestData.Sequence(archive.Id), TestData.Sequence(archive.Id), TestData.Sequence(archive.Id));
|
||||
foreach (var sequence in new[] { a, b, c }) await db.Sequences.UpsertAsync(sequence, Ct);
|
||||
var store = new SyncLinkStore(db);
|
||||
var (plain, sameRemote, sameLocal, stale) = (Guid.CreateVersion7(), Guid.CreateVersion7(), Guid.CreateVersion7(), Guid.CreateVersion7());
|
||||
// Only under the address: it moves.
|
||||
await store.UpsertAsync(Link(Address, plain, a.Id, TestData.Now), Ct);
|
||||
// Under both keys for one server sequence: the address's row is newer, so it replaces the id's.
|
||||
await store.UpsertAsync(Link(Address, sameRemote, null, TestData.Now.AddHours(2), "newer"), Ct);
|
||||
await store.UpsertAsync(Link(IdKey, sameRemote, null, TestData.Now.AddHours(1), "older"), Ct);
|
||||
// Both keys link local copy b to different server sequences: the id's row is newer, so the address's goes.
|
||||
await store.UpsertAsync(Link(Address, sameLocal, b.Id, TestData.Now), Ct);
|
||||
await store.UpsertAsync(Link(IdKey, Guid.CreateVersion7(), b.Id, TestData.Now.AddDays(1)), Ct);
|
||||
// Never compared under the address, compared under the id: the id's stays.
|
||||
await store.UpsertAsync(Link(Address, stale, c.Id, null), Ct);
|
||||
await store.UpsertAsync(Link(IdKey, stale, null, TestData.Now), Ct);
|
||||
|
||||
var (moved, dropped) = await store.RekeyAsync(Address, IdKey, Ct);
|
||||
Assert.Equal((2, 3), (moved, dropped));
|
||||
Assert.Empty(await store.ListAsync(Address, Ct));
|
||||
var links = (await store.ListAsync(IdKey, Ct)).ToDictionary(l => l.RemoteId);
|
||||
Assert.Equal(4, links.Count);
|
||||
Assert.Equal(a.Id, links[plain].LocalId);
|
||||
Assert.Equal("newer", links[sameRemote].Title);
|
||||
Assert.False(links.ContainsKey(sameLocal));
|
||||
Assert.Null(links[stale].LocalId);
|
||||
Assert.Equal(b.Id, Assert.NotNull(await store.FindByLocalAsync(IdKey, b.Id, Ct)).LocalId);
|
||||
|
||||
// Again: nothing left to move; and a key onto itself does nothing.
|
||||
Assert.Equal((0, 0), await store.RekeyAsync(Address, IdKey, Ct));
|
||||
Assert.Equal((0, 0), await store.RekeyAsync(IdKey, IdKey, Ct));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SqliteSyncLinkRekeyTests(TestContext context) : SyncLinkRekeyTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.SqliteMemory;
|
||||
}
|
||||
|
||||
public sealed class PostgresSyncLinkRekeyTests(TestContext context) : SyncLinkRekeyTests(context)
|
||||
{
|
||||
protected override Backend Backend => Backend.Postgres;
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Data.Tests.Homes;
|
||||
using Chronos.Data.Workspaces;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Data.Tests.Workspaces;
|
||||
|
||||
/// <summary>The workspace split into one store per home (owner review 5, #66).</summary>
|
||||
[Category("workspace")]
|
||||
public sealed class WorkspaceHomesTests(TestContext context)
|
||||
{
|
||||
private static readonly Guid Id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
|
||||
|
||||
[Test]
|
||||
public void ANewWorkspaceIsSplitAndEachHomeGetsItsStore()
|
||||
{
|
||||
var root = Path.Combine(context.CreateTempDirectory("ws"), "workspace");
|
||||
var homes = new WorkspaceHomes(root, new ServerIdentity([new KnownServerKey(Id, [HomeFixtures.Nas])]));
|
||||
Assert.True(homes.IsSplit);
|
||||
Assert.True(WorkspaceHomes.IsSplitRoot(root));
|
||||
Assert.Equal((WorkspaceHomes.ParentFormatVersion, WorkspaceHomes.HomesLayout), (homes.Manifest.FormatVersion, homes.Manifest.Layout));
|
||||
Assert.Empty(homes.Homes());
|
||||
// A 1.0 Chronos (store format 1) refuses the parent: it never shows the workspace empty.
|
||||
Assert.Throws<InvalidDataException>(() => new WorkspaceStore(root));
|
||||
|
||||
var local = homes.StoreFor(HomeFixtures.Local());
|
||||
Assert.Equal(Path.Combine(homes.Root, "local"), local.Root);
|
||||
var server = homes.StoreFor(HomeFixtures.Server(HomeFixtures.Nas));
|
||||
Assert.Equal(Path.Combine(homes.Root, "servers", Id.ToString("N")), server.Root);
|
||||
Assert.Same(server, homes.StoreFor(HomeFixtures.Server(ServerIdentity.IdKey(Id))));
|
||||
var record = Assert.NotNull(ServerHomeRecord.Read(server.Root));
|
||||
Assert.Equal((ServerIdentity.IdKey(Id), (Guid?)Id), (record.Key, record.Id));
|
||||
var other = homes.StoreFor(HomeFixtures.Server(HomeFixtures.Other));
|
||||
Assert.Equal(Path.Combine(homes.Root, "servers", HomeFolders.ServerFolder(HomeFixtures.Other)), other.Root);
|
||||
Assert.Equal(HomeFixtures.Other, Assert.NotNull(ServerHomeRecord.Read(other.Root)).Address);
|
||||
Assert.NotEqual(local.Id, server.Id);
|
||||
|
||||
var described = Assert.NotNull(homes.Describe(HomeFixtures.Nas, "Studio NAS", HomeFixtures.Nas, "AA:BB", DateTimeOffset.UtcNow));
|
||||
Assert.Equal(("Studio NAS", HomeFixtures.Nas, "AA:BB"), (described.Name, described.Address, described.TlsFingerprint));
|
||||
Assert.Equal(record.FirstSeen, described.FirstSeen);
|
||||
|
||||
var listed = homes.Homes();
|
||||
Assert.Equal(3, listed.Count);
|
||||
Assert.True(listed[0].IsLocal);
|
||||
Assert.Contains(listed, h => h.ServerKey == ServerIdentity.IdKey(Id) && h.Server?.Name == "Studio NAS");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ProjectsAreFoundInEveryHomeAndTheTrashIsListedPerHome()
|
||||
{
|
||||
var root = Path.Combine(context.CreateTempDirectory("ws"), "workspace");
|
||||
var homes = new WorkspaceHomes(root);
|
||||
var a = HomeFixtures.Project(homes.StoreFor(HomeFixtures.Local()).Root, HomeFixtures.Local());
|
||||
var serverHome = HomeFixtures.Server(HomeFixtures.Nas);
|
||||
var b = HomeFixtures.Project(homes.StoreFor(serverHome).Root, serverHome);
|
||||
Assert.Equal(homes.LocalRoot, Path.GetDirectoryName(Assert.NotNull(homes.Find(a)).Folder));
|
||||
Assert.Equal(homes.ServerRoot(HomeFixtures.Nas), Path.GetDirectoryName(Assert.NotNull(homes.Find(b)).Folder));
|
||||
Assert.Null(homes.Find(Guid.CreateVersion7()));
|
||||
Assert.Equal(2, homes.List().Count);
|
||||
Assert.Equal(2, homes.ListBundles().Count);
|
||||
|
||||
HomeFixtures.TrashEntry(homes.ServerRoot(HomeFixtures.Nas), b, serverHome);
|
||||
var trash = homes.Trash();
|
||||
Assert.Equal(2, trash.Count);
|
||||
Assert.Equal(1, trash.Sum(t => t.Entries.Count));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void A10WorkspaceStaysOneStoreUntilItIsSorted()
|
||||
{
|
||||
var root = HomeFixtures.LegacyWorkspace(context.CreateTempDirectory("ws"));
|
||||
var a = HomeFixtures.Project(root, HomeFixtures.Local());
|
||||
var homes = new WorkspaceHomes(root);
|
||||
Assert.False(homes.IsSplit);
|
||||
Assert.Equal(1, homes.Manifest.FormatVersion);
|
||||
Assert.Equal(homes.Root, homes.StoreFor(HomeFixtures.Server(HomeFixtures.Nas)).Root);
|
||||
Assert.Equal(homes.Root, homes.Local.Root);
|
||||
Assert.True(Assert.NotNull(homes.Find(a)).Exists);
|
||||
Assert.True(homes.Homes().Single().IsLegacy);
|
||||
Assert.False(Directory.Exists(homes.LocalRoot), "nothing is made beside the 1.0 projects");
|
||||
|
||||
// A folder with projects and no manifest is a 1.0 workspace too, never a new split one.
|
||||
var bare = Path.Combine(context.CreateTempDirectory("bare"), "workspace");
|
||||
HomeFixtures.Project(bare, HomeFixtures.Local());
|
||||
Assert.False(new WorkspaceHomes(bare).IsSplit);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AProjectNotSortedYetIsListedWhereItIs()
|
||||
{
|
||||
var root = Path.Combine(context.CreateTempDirectory("ws"), "workspace");
|
||||
_ = new WorkspaceHomes(root);
|
||||
var left = HomeFixtures.Project(root, HomeFixtures.Local());
|
||||
var homes = new WorkspaceHomes(root);
|
||||
Assert.True(homes.IsSplit);
|
||||
Assert.Equal(homes.Root, Path.GetDirectoryName(Assert.NotNull(homes.Find(left)).Folder));
|
||||
Assert.True(homes.Homes()[0].IsLegacy);
|
||||
Assert.Equal(homes.LocalRoot, homes.Local.Root);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AJobQueuedBeforeTheSortingFindsItsProjectInItsHome()
|
||||
{
|
||||
var root = Path.Combine(context.CreateTempDirectory("ws"), "workspace");
|
||||
var homes = new WorkspaceHomes(root);
|
||||
var home = HomeFixtures.Server(HomeFixtures.Nas);
|
||||
var id = HomeFixtures.Project(homes.ServerRoot(HomeFixtures.Nas), home);
|
||||
_ = homes.StoreFor(home);
|
||||
// Queued with the 1.0 folder (the parent): found in the server's home.
|
||||
Assert.Equal(homes.ServerRoot(HomeFixtures.Nas), WorkspaceJobRoots.Resolve(root, id, null, "Errors.Workspace.NotCheckedOut"));
|
||||
// Queued with the home of the address, which was re-keyed to the id since.
|
||||
var rekeyed = Path.Combine(root, "servers", Id.ToString("N"));
|
||||
Directory.Move(homes.ServerRoot(HomeFixtures.Nas), rekeyed);
|
||||
Assert.Equal(rekeyed, WorkspaceJobRoots.Resolve(Path.Combine(root, "servers", HomeFolders.ServerFolder(HomeFixtures.Nas)), id, null, "Errors.Workspace.NotCheckedOut"));
|
||||
// With the parent in use now (Settings › Workspace) and an older folder named.
|
||||
Assert.Equal(rekeyed, WorkspaceJobRoots.Resolve(Path.Combine(context.CreateTempDirectory("gone"), "workspace"), id, () => root, "Errors.Workspace.NotCheckedOut"));
|
||||
// While the parent is being moved nothing runs.
|
||||
File.WriteAllText(Path.Combine(root, WorkspaceMover.JournalFile), "{}");
|
||||
var moving = Assert.Throws<InvalidOperationException>(() => WorkspaceJobRoots.Resolve(rekeyed, id, null, "Errors.Workspace.NotCheckedOut"));
|
||||
Assert.Equal(Loc.L("Errors.Workspace.Moving"), moving.Message);
|
||||
File.Delete(Path.Combine(root, WorkspaceMover.JournalFile));
|
||||
Assert.Throws<InvalidOperationException>(() => WorkspaceJobRoots.Resolve(root, Guid.CreateVersion7(), null, "Errors.Workspace.NotCheckedOut"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SameServerGoesThroughTheAliases()
|
||||
{
|
||||
var identity = new ServerIdentity([new KnownServerKey(Id, [HomeFixtures.Nas])]);
|
||||
var options = new WorkspaceJobOptions(new Chronos.Data.Processing.ProcessingOptions(), () => false);
|
||||
Assert.True(options.IsSameServer("https://NAS.local:8443", HomeFixtures.Nas));
|
||||
Assert.False(options.IsSameServer(ServerIdentity.IdKey(Id), HomeFixtures.Nas));
|
||||
var aliased = options with { SameServer = identity.Same };
|
||||
Assert.True(aliased.IsSameServer(ServerIdentity.IdKey(Id), HomeFixtures.Nas));
|
||||
Assert.False(aliased.IsSameServer(ServerIdentity.IdKey(Id), HomeFixtures.Other));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task MovingASplitWorkspaceMovesEveryHome()
|
||||
{
|
||||
foreach (var sameVolume in new[] { true, false })
|
||||
{
|
||||
var parent = context.CreateTempDirectory("move");
|
||||
var from = Path.Combine(parent, "workspace");
|
||||
var homes = new WorkspaceHomes(from);
|
||||
var serverHome = HomeFixtures.Server(HomeFixtures.Nas);
|
||||
var ids = new[]
|
||||
{
|
||||
HomeFixtures.Project(homes.StoreFor(HomeFixtures.Local()).Root, HomeFixtures.Local()),
|
||||
HomeFixtures.Project(homes.StoreFor(serverHome).Root, serverHome),
|
||||
HomeFixtures.Project(homes.StoreFor(HomeFixtures.Server(HomeFixtures.Other)).Root, HomeFixtures.Server(HomeFixtures.Other)),
|
||||
};
|
||||
var before = HomeFixtures.Manifest(from);
|
||||
var to = Path.Combine(parent, "moved");
|
||||
var mover = new WorkspaceMover(from, to) { SameVolume = sameVolume };
|
||||
var survey = mover.Survey();
|
||||
Assert.Equal(3, survey.Projects.Count);
|
||||
Assert.SequenceEqual(new[] { "local", "servers", WorkspaceStore.ManifestFile }, survey.Entries);
|
||||
var lines = new List<string>();
|
||||
await mover.MoveAsync(survey.Fingerprint, log: lines.Add, cancellationToken: context.Cancellation);
|
||||
Assert.False(Directory.Exists(from), "the old folder went");
|
||||
var moved = new WorkspaceHomes(to);
|
||||
Assert.True(moved.IsSplit);
|
||||
Assert.Equal(3, moved.List().Count);
|
||||
foreach (var id in ids) Assert.NotNull(moved.Find(id));
|
||||
Assert.SequenceEqual(before, HomeFixtures.Manifest(to));
|
||||
Assert.Contains(Loc.L("Archive.Log.WorkspaceMoved", mover.To, 3, survey.Files), lines);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
using System.Text.Json;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Repositories;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Hosting;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Api;
|
||||
|
||||
/// <summary>The server's stable id announced by <c>/server/info</c> (owner review 5, #66).</summary>
|
||||
[Category("server")]
|
||||
public sealed class ServerInfoIdTests(TestContext context)
|
||||
{
|
||||
private static async Task<ServerInfo> InfoAsync(TestServer server)
|
||||
{
|
||||
using var response = await server.Client.GetAsync("/api/v1/server/info");
|
||||
return await response.ReadAsync(ProtocolJson.Default.ServerInfo);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheIdIsMadeOnceAndKeptAcrossRestarts()
|
||||
{
|
||||
var root = context.CreateTempDirectory("kept");
|
||||
void Same(Configuration.ServerOptions o)
|
||||
{
|
||||
o.DataPath = Path.Combine(root, "data");
|
||||
o.ArchivePath = Path.Combine(root, "archive");
|
||||
}
|
||||
Guid first;
|
||||
await using (var server = await TestServer.StartAsync(context, Same))
|
||||
{
|
||||
first = Assert.NotNull((await InfoAsync(server)).ServerId);
|
||||
Assert.NotEqual(Guid.Empty, first);
|
||||
var stored = await server.Database.Settings.GetJsonAsync(SettingScope.App, null, ServerHost.ServerIdKey, context.Cancellation);
|
||||
Assert.Equal("\"" + first.ToString("D") + "\"", stored);
|
||||
}
|
||||
await using (var again = await TestServer.StartAsync(context, Same))
|
||||
Assert.Equal((Guid?)first, (await InfoAsync(again)).ServerId);
|
||||
// Another server (another database) has another id.
|
||||
await using (var other = await TestServer.StartAsync(context))
|
||||
Assert.NotEqual((Guid?)first, (await InfoAsync(other)).ServerId);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheIdSurvivesARestoreOfTheIndex()
|
||||
{
|
||||
var folder = context.CreateTempDirectory("restore");
|
||||
Guid id;
|
||||
string backup;
|
||||
await using (var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(folder, "chronos.db")), context.Cancellation))
|
||||
{
|
||||
id = await ServerHost.ServerIdAsync(db, null, context.Cancellation);
|
||||
backup = await db.BackupAsync(Path.Combine(folder, "backups"), cancellationToken: context.Cancellation);
|
||||
}
|
||||
// A new index (the disk replaced), then the backup put back.
|
||||
await using var restored = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(folder, "new.db")), context.Cancellation);
|
||||
await restored.RestoreAsync(backup, context.Cancellation);
|
||||
Assert.Equal(id, await ServerHost.ServerIdAsync(restored, null, context.Cancellation));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AStoredIdThatIsNotOneIsMadeAgain()
|
||||
{
|
||||
var folder = context.CreateTempDirectory("damaged");
|
||||
await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(folder, "chronos.db")), context.Cancellation);
|
||||
foreach (var damaged in new[] { "\"not a guid\"", "\"" + Guid.Empty.ToString("D") + "\"", "42" })
|
||||
{
|
||||
await db.Settings.SetJsonAsync(SettingScope.App, null, ServerHost.ServerIdKey, damaged, context.Cancellation);
|
||||
var made = await ServerHost.ServerIdAsync(db, null, context.Cancellation);
|
||||
Assert.NotEqual(Guid.Empty, made);
|
||||
Assert.Equal(made, await ServerHost.ServerIdAsync(db, null, context.Cancellation));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
[RequiresEnvironment("CHRONOS_TEST_PG")]
|
||||
public async Task TheIdIsKeptOnPostgres()
|
||||
{
|
||||
var baseConnection = Environment.GetEnvironmentVariable("CHRONOS_TEST_PG")!;
|
||||
var admin = DatabaseFactory.Open(DatabaseOptions.Postgres(baseConnection));
|
||||
var schema = "chronos_s_" + Guid.NewGuid().ToString("N")[..16];
|
||||
await using (var session = await admin.OpenAsync(context.Cancellation))
|
||||
await session.ExecuteScriptAsync($"CREATE SCHEMA {schema}", context.Cancellation);
|
||||
try
|
||||
{
|
||||
var options = DatabaseOptions.Postgres(baseConnection.TrimEnd(';', ' ') + $";Search Path={schema}");
|
||||
Guid id;
|
||||
await using (var db = await ChronosDatabase.OpenAsync(options, context.Cancellation))
|
||||
id = await ServerHost.ServerIdAsync(db, null, context.Cancellation);
|
||||
await using (var db = await ChronosDatabase.OpenAsync(options, context.Cancellation))
|
||||
Assert.Equal(id, await ServerHost.ServerIdAsync(db, null, context.Cancellation));
|
||||
}
|
||||
finally
|
||||
{
|
||||
await using (var session = await admin.OpenAsync(CancellationToken.None))
|
||||
await session.ExecuteScriptAsync($"DROP SCHEMA IF EXISTS {schema} CASCADE", CancellationToken.None);
|
||||
await admin.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AnOlderClientAndAnOlderServerReadEachOther()
|
||||
{
|
||||
var id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
|
||||
var info = new ServerInfo("Studio NAS", "1.1.0", 1, ["sync"], null, ["jpeg"], new ServerLimits(1, 1), null, 3, id);
|
||||
var json = JsonSerializer.Serialize(info, ProtocolJson.Default.ServerInfo);
|
||||
Assert.Contains("\"serverId\":\"" + id.ToString("D") + "\"", json);
|
||||
Assert.Equal(info.ServerId, Assert.NotNull(JsonSerializer.Deserialize(json, ProtocolJson.Default.ServerInfo)).ServerId);
|
||||
|
||||
// A 1.0 server sends no id: it reads as null, and a 1.0 client ignores the member it does not know.
|
||||
const string older = """{"name":"NAS","version":"1.0.0","apiVersion":1,"capabilities":["sync"],"formats":["jpeg"],"limits":{"maxUploadBytes":1,"chunkSizeBytes":1}}""";
|
||||
Assert.Null(Assert.NotNull(JsonSerializer.Deserialize(older, ProtocolJson.Default.ServerInfo)).ServerId);
|
||||
Assert.False(JsonSerializer.Serialize(info with { ServerId = null }, ProtocolJson.Default.ServerInfo).Contains("serverId", StringComparison.Ordinal));
|
||||
using var parsed = JsonDocument.Parse(json);
|
||||
Assert.Equal("Studio NAS", parsed.RootElement.GetProperty("name").GetString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Imaging.Decoders;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Video.Managed;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Data.Scheduling;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Api;
|
||||
using Chronos.Server.Configuration;
|
||||
using Chronos.Server.Hosting;
|
||||
using Chronos.Server.Jobs;
|
||||
using Chronos.Server.Security;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// The server Chronos Desktop hosts to share this PC's library (owner review 5, #67): built over an index, engines, a job
|
||||
/// engine and a scheduler the test owns, as the desktop does, which it never creates, starts, stops or disposes.
|
||||
/// </summary>
|
||||
[Category("server")]
|
||||
[Serial] // Log.Sink is process-wide: the standalone server tests running beside these set their own
|
||||
public sealed class HostedServerTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public async Task ItAnswersWithTheCertificateOfItsDataFolderAndKeepsItsIdAcrossRestarts()
|
||||
{
|
||||
await using var desktop = await DesktopFixture.StartAsync(context);
|
||||
Guid? firstId;
|
||||
string? fingerprint;
|
||||
await using (var shared = await desktop.ShareAsync())
|
||||
{
|
||||
using var http = desktop.Client(shared);
|
||||
using var health = await http.GetAsync("/health");
|
||||
Assert.Equal(HttpStatusCode.OK, health.StatusCode);
|
||||
var info = Assert.NotNull(await http.GetFromJsonAsync("/api/v1/server/info", ProtocolJson.Default.ServerInfo));
|
||||
var pfx = X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(desktop.ShareData, "tls", "server.pfx"), null);
|
||||
Assert.Equal(CertificateStore.Fingerprint(pfx), shared.Fingerprint);
|
||||
Assert.Equal(shared.ServerId, info.ServerId);
|
||||
Assert.True(shared.HttpsPort > 0, "the HTTPS listener's port");
|
||||
firstId = shared.ServerId;
|
||||
fingerprint = shared.Fingerprint;
|
||||
}
|
||||
// A second start on the same folder and index: the same certificate, id and administrator.
|
||||
await using var again = await desktop.ShareAsync();
|
||||
Assert.Equal(fingerprint, again.Fingerprint);
|
||||
Assert.Equal(firstId, again.ServerId);
|
||||
Assert.Count(1, (await desktop.Database.Users.ListAsync()).Where(u => u.Role == UserRole.Admin));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task JobsQueuedByClientsRunOnTheDesktopsEngineWhichOutlivesTheServer()
|
||||
{
|
||||
await using var desktop = await DesktopFixture.StartAsync(context);
|
||||
var sink = Log.Sink;
|
||||
await using (var shared = await desktop.ShareAsync())
|
||||
{
|
||||
Assert.Same(desktop.Engine, shared.Services.GetRequiredService<JobEngineHost>().Engine);
|
||||
Assert.True(shared.Services.GetRequiredService<JobEngineHost>().Hosted, "hosted");
|
||||
using var admin = await desktop.AdminAsync(shared);
|
||||
using var created = await admin.PostAsJsonAsync("/api/v1/jobs", new CreateJobRequest("scan", [], null), ProtocolJson.Default.CreateJobRequest);
|
||||
Assert.Equal(HttpStatusCode.Accepted, created.StatusCode);
|
||||
var job = Assert.NotNull(await created.Content.ReadFromJsonAsync(ProtocolJson.Default.JobDto));
|
||||
var done = await desktop.WaitAsync(job.Id);
|
||||
Assert.Equal(JobState.Done, done.State);
|
||||
Assert.Equal(DesktopFixture.WorkerId, done.NodeId);
|
||||
Assert.Same(sink, Log.Sink);
|
||||
}
|
||||
// Stopped: the index answers, the engine runs jobs, the scheduler still works, the log sink is the desktop's.
|
||||
Assert.Same(sink, Log.Sink);
|
||||
var after = await desktop.Engine.EnqueueAsync(JobKind.Scan, [desktop.Archive.Id], "after");
|
||||
Assert.Equal(JobState.Done, (await desktop.WaitAsync(after.Id)).State);
|
||||
Assert.NotNull(await desktop.Scheduler.ListAsync(context.Cancellation));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheServerAddsOnlyItsOwnSystemSchedulesToTheDesktops()
|
||||
{
|
||||
await using var desktop = await DesktopFixture.StartAsync(context);
|
||||
var before = (await desktop.Scheduler.ListAsync(context.Cancellation)).Items.Select(s => s.SystemKey).OfType<string>().ToHashSet();
|
||||
await using var shared = await desktop.ShareAsync();
|
||||
var after = (await desktop.Scheduler.ListAsync(context.Cancellation)).Items.Select(s => s.SystemKey).OfType<string>().ToHashSet();
|
||||
Assert.SequenceEqual([ServerScheduleHost.AuditCleanup, ServerScheduleHost.UploadCleanup], after.Except(before).Order(StringComparer.Ordinal));
|
||||
Assert.SequenceEqual([DesktopFixture.ScanKey], before);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ItServesTheDesktopsArchiveAloneAndHidesItsPrivateJobs()
|
||||
{
|
||||
await using var desktop = await DesktopFixture.StartAsync(context);
|
||||
var mine = await desktop.SequenceAsync(desktop.Archive);
|
||||
var other = await desktop.Archives.CreateAsync(context.CreateTempDirectory("other"), "Another archive", cancellationToken: context.Cancellation);
|
||||
var theirs = await desktop.SequenceAsync(other);
|
||||
var workspace = await desktop.Engine.EnqueueAsync(JobKind.WorkspaceCopy, [mine.Id], "workspace");
|
||||
await using var shared = await desktop.ShareAsync();
|
||||
using var admin = await desktop.AdminAsync(shared);
|
||||
|
||||
using (var ok = await admin.GetAsync($"/api/v1/sequences/{mine.Id}")) Assert.Equal(HttpStatusCode.OK, ok.StatusCode);
|
||||
foreach (var path in new[] { $"/api/v1/sequences/{theirs.Id}", $"/api/v1/sequences/{theirs.Id}/projects", $"/api/v1/sequences/{theirs.Id}/frames" })
|
||||
{
|
||||
using var hidden = await admin.GetAsync(path);
|
||||
Assert.Equal(HttpStatusCode.NotFound, hidden.StatusCode, path);
|
||||
}
|
||||
using (var job = await admin.PostAsJsonAsync("/api/v1/jobs", new CreateJobRequest("thumbs", [theirs.Id], null), ProtocolJson.Default.CreateJobRequest))
|
||||
Assert.Equal(HttpStatusCode.NotFound, job.StatusCode);
|
||||
|
||||
var listed = Assert.NotNull(await admin.GetFromJsonAsync("/api/v1/jobs", ProtocolJson.Default.PageJobDto));
|
||||
Assert.False(listed.Items.Any(j => j.Id == workspace.Id), "a workspace job is the desktop's own");
|
||||
using (var get = await admin.GetAsync($"/api/v1/jobs/{workspace.Id}")) Assert.Equal(HttpStatusCode.NotFound, get.StatusCode);
|
||||
using (var cancel = await admin.PostAsync($"/api/v1/jobs/{workspace.Id}/cancel", null)) Assert.Equal(HttpStatusCode.NotFound, cancel.StatusCode);
|
||||
Assert.Equal(JobState.Queued, (await desktop.Database.Jobs.GetAsync(workspace.Id))!.State);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheDesktopOwnsItsSettingsAndTheFirstAdministratorsPasswordIsInTheShareFolder()
|
||||
{
|
||||
await using var desktop = await DesktopFixture.StartAsync(context);
|
||||
Environment.SetEnvironmentVariable("CHRONOS_SERVER_NAME", "from a variable");
|
||||
try
|
||||
{
|
||||
var options = ServerOptions.ForHosted(desktop.ShareData, desktop.Settings with { ServerName = "Studio PC" });
|
||||
Assert.Equal("Studio PC", options.ServerName);
|
||||
Assert.True(options.Hosted, "hosted");
|
||||
Assert.Contains(nameof(ServerOptions.HttpsPort), options.Locked);
|
||||
Assert.Equal(ServerOptions.DesktopLock, options.LockedBy[nameof(ServerOptions.Parallelism)]);
|
||||
Assert.False(options.Locked.Contains(nameof(ServerOptions.TokenLifetimeDays)), "the admin panel owns the token lifetime");
|
||||
Assert.Equal(Microsoft.Extensions.Logging.LogLevel.None, options.ConsoleLogLevel);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Environment.SetEnvironmentVariable("CHRONOS_SERVER_NAME", null);
|
||||
}
|
||||
await using var shared = await desktop.ShareAsync();
|
||||
Assert.True(File.Exists(shared.AdminPasswordFile), "the temporary password's file");
|
||||
Assert.Equal(Path.Combine(desktop.ShareData, AdminBootstrap.PasswordFileName), shared.AdminPasswordFile);
|
||||
Assert.NotNull(shared.AdminPassword());
|
||||
using var admin = await desktop.AdminAsync(shared);
|
||||
Assert.Null(shared.AdminPassword());
|
||||
var settings = Assert.NotNull(await admin.GetFromJsonAsync("/api/v1/server/settings", ProtocolJson.Default.ServerSettingsDto));
|
||||
Assert.Equal(ServerOptions.DesktopLock, settings.LockedBy["HttpsPort"]);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ClientsAreKeptForFiveMinutes()
|
||||
{
|
||||
var time = new ManualTime(DateTimeOffset.Parse("2026-11-15T10:00:00Z", System.Globalization.CultureInfo.InvariantCulture));
|
||||
var activity = new ClientActivity(time);
|
||||
var user = new User { Id = Guid.CreateVersion7(), Username = "alberto", PasswordHash = "x", Role = UserRole.Editor, Created = time.GetUtcNow() };
|
||||
activity.Record(new Caller(user, "hash", CredentialSource.Bearer, "Chronos Uploader (Studio)"), "192.168.1.20");
|
||||
activity.Record(new Caller(user, "hash", CredentialSource.Cookie, null), "192.168.1.21");
|
||||
var seen = activity.Recent();
|
||||
Assert.Count(2, seen);
|
||||
Assert.Contains("Chronos Uploader (Studio)", seen.Select(s => s.Client));
|
||||
Assert.Contains(ClientActivity.AdminPanel, seen.Select(s => s.Client));
|
||||
time.Advance(TimeSpan.FromMinutes(6));
|
||||
Assert.Count(0, activity.Recent());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ARenderNeverKeepsTheExportFolderAClientChose()
|
||||
{
|
||||
var parameters = new RenderJobParameters("1080p", """{"preset":"1080p","Folder":"C:\\Users\\someone","nameTemplate":"{title}"}""", "h264", 1920, 1080, false, null);
|
||||
var stripped = JobEndpoints.WithoutExportFolder(parameters);
|
||||
Assert.False(stripped.PresetJson.Contains("Users", StringComparison.Ordinal), stripped.PresetJson);
|
||||
Assert.True(stripped.PresetJson.Contains("nameTemplate", StringComparison.Ordinal), stripped.PresetJson);
|
||||
var plain = parameters with { PresetJson = """{"preset":"1080p"}""" };
|
||||
Assert.Same(plain, JobEndpoints.WithoutExportFolder(plain));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheServiceSwitchesAreGone()
|
||||
{
|
||||
var parsed = ServerCommandLine.Parse(["--service", "--install-service", "--uninstall-service"]);
|
||||
Assert.Equal(ServerCommand.Run, parsed.Command);
|
||||
Assert.SequenceEqual(["--service", "--install-service", "--uninstall-service"], parsed.HostArguments);
|
||||
Assert.False(ServerCommandLine.Usage.Contains("service", StringComparison.OrdinalIgnoreCase), "usage names a service");
|
||||
}
|
||||
|
||||
/// <summary>A clock the test moves.</summary>
|
||||
private sealed class ManualTime(DateTimeOffset start) : TimeProvider
|
||||
{
|
||||
private DateTimeOffset _now = start;
|
||||
|
||||
public override DateTimeOffset GetUtcNow() => _now;
|
||||
|
||||
public void Advance(TimeSpan by) => _now += by;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What Chronos Desktop has when it shares its library: a SQLite index, the archive and processing services (managed
|
||||
/// codecs), a started job engine and a started scheduler with one system schedule of its own.
|
||||
/// </summary>
|
||||
internal sealed class DesktopFixture : IAsyncDisposable
|
||||
{
|
||||
public const string WorkerId = "STUDIO-PC";
|
||||
public const string ScanKey = "archive-scan";
|
||||
|
||||
private readonly TestContext _context;
|
||||
|
||||
private DesktopFixture(TestContext context, string root, ChronosDatabase db, ArchiveService archives, ProcessingService processing, JobEngine engine,
|
||||
Scheduler scheduler, Archive archive)
|
||||
{
|
||||
_context = context;
|
||||
Root = root;
|
||||
Database = db;
|
||||
Archives = archives;
|
||||
Processing = processing;
|
||||
Engine = engine;
|
||||
Scheduler = scheduler;
|
||||
Archive = archive;
|
||||
}
|
||||
|
||||
public string Root { get; }
|
||||
public ChronosDatabase Database { get; }
|
||||
public ArchiveService Archives { get; }
|
||||
public ProcessingService Processing { get; }
|
||||
public JobEngine Engine { get; }
|
||||
public Scheduler Scheduler { get; }
|
||||
public Archive Archive { get; }
|
||||
public string ShareData => Path.Combine(Root, "data", "server");
|
||||
|
||||
public HostedSettings Settings => new(null, 0, 0, null, null, Discovery: false, Archive.RootPath, null, 2, false, new Dictionary<string, string>(), "en",
|
||||
LogLevel.Warning, 14, 50, 1024, LogRotation.Daily, 4);
|
||||
|
||||
public static async Task<DesktopFixture> StartAsync(TestContext context)
|
||||
{
|
||||
var root = context.CreateTempDirectory("desktop");
|
||||
Directory.CreateDirectory(Path.Combine(root, "data"));
|
||||
var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(root, "data", "chronos.db")), context.Cancellation);
|
||||
var archiveOptions = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Parallelism = () => 2 };
|
||||
var archives = new ArchiveService(db, archiveOptions);
|
||||
var processing = new ProcessingService(db, new ProcessingOptions { Archive = archiveOptions, Encoders = [new ManagedEncoderProvider()] });
|
||||
var archive = await archives.CreateAsync(Path.Combine(root, "archive"), "Studio", cancellationToken: context.Cancellation);
|
||||
var handlers = archives.CreateJobHandlers().Concat(processing.CreateJobHandlers()).ToList();
|
||||
var engine = new JobEngine(db, handlers, new JobEngineOptions
|
||||
{
|
||||
WorkerId = WorkerId,
|
||||
Kinds = [.. handlers.Select(h => h.Kind).Distinct()],
|
||||
PollInterval = TimeSpan.FromMilliseconds(100),
|
||||
});
|
||||
await engine.StartAsync(context.Cancellation);
|
||||
var scheduler = new Scheduler(db, engine);
|
||||
await scheduler.StartAsync(new Host(archives, archive), context.Cancellation);
|
||||
return new DesktopFixture(context, root, db, archives, processing, engine, scheduler, archive);
|
||||
}
|
||||
|
||||
public async Task<HostedServer> ShareAsync()
|
||||
{
|
||||
var options = ServerOptions.ForHosted(ShareData, Settings);
|
||||
options.LoginAttemptsPerMinute = 1000;
|
||||
var server = ServerHost.BuildHosted(options, new HostedEngine(Database, Archives, Processing, Engine, Scheduler, Archive));
|
||||
await server.StartAsync(_context.Cancellation);
|
||||
return server;
|
||||
}
|
||||
|
||||
public HttpClient Client(HostedServer server, string? token = null)
|
||||
{
|
||||
var client = new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{server.HttpPort}"), Timeout = TimeSpan.FromSeconds(60) };
|
||||
if (token is not null) client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||
return client;
|
||||
}
|
||||
|
||||
/// <summary>The first administrator, signed in with its temporary password, which it then replaces.</summary>
|
||||
public async Task<HttpClient> AdminAsync(HostedServer server)
|
||||
{
|
||||
var temporary = server.AdminPassword() ?? throw new InvalidOperationException("No temporary password");
|
||||
using var anonymous = Client(server);
|
||||
using var login = await anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("admin", temporary, "tests"), ProtocolJson.Default.LoginRequest);
|
||||
login.EnsureSuccessStatusCode();
|
||||
var token = (await login.Content.ReadFromJsonAsync(ProtocolJson.Default.LoginResponse))!.Token!;
|
||||
var client = Client(server, token);
|
||||
using var changed = await client.PostAsJsonAsync("/api/v1/auth/password", new ChangePasswordRequest(temporary, "a-good-password-1"),
|
||||
ProtocolJson.Default.ChangePasswordRequest);
|
||||
changed.EnsureSuccessStatusCode();
|
||||
return client;
|
||||
}
|
||||
|
||||
public async Task<Sequence> SequenceAsync(Archive archive)
|
||||
{
|
||||
var sequence = new Sequence
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
ArchiveId = archive.Id,
|
||||
Title = "Roof " + archive.Name,
|
||||
Folder = string.Empty,
|
||||
Origin = SequenceOrigin.Server,
|
||||
UpdatedAt = DateTimeOffset.UtcNow,
|
||||
};
|
||||
await Database.Sequences.UpsertAsync(sequence, _context.Cancellation);
|
||||
return sequence;
|
||||
}
|
||||
|
||||
public async Task<Job> WaitAsync(Guid id)
|
||||
{
|
||||
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
|
||||
while (true)
|
||||
{
|
||||
if (await Database.Jobs.GetAsync(id, _context.Cancellation) is { State: JobState.Done or JobState.Failed or JobState.Cancelled } job) return job;
|
||||
Assert.True(DateTime.UtcNow < until, "the job did not finish");
|
||||
await Task.Delay(50, _context.Cancellation);
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await Scheduler.DisposeAsync();
|
||||
await Engine.DisposeAsync();
|
||||
await Database.DisposeAsync();
|
||||
}
|
||||
|
||||
/// <summary>A desktop's schedule host: one archive scan schedule, the archive service's clean-up steps.</summary>
|
||||
private sealed class Host(ArchiveService archives, Archive archive) : IScheduleHost
|
||||
{
|
||||
public TimeZoneInfo TimeZone => TimeZoneInfo.Utc;
|
||||
|
||||
public IReadOnlyList<SystemSchedule> SystemSchedules =>
|
||||
[new(ScanKey, "Archive scan", ScheduleActions.Scan, ScheduleRecurrence.Interval(10, RecurrenceUnit.Minutes), CatchUp: false)];
|
||||
|
||||
public IReadOnlyList<string> CleanupSteps => [.. archives.CleanupSteps.Select(s => s.Name)];
|
||||
|
||||
public bool DeepAnalysisAfterScan => false;
|
||||
|
||||
public ValueTask<Archive?> GetArchiveAsync(CancellationToken cancellationToken) => ValueTask.FromResult<Archive?>(archive);
|
||||
|
||||
public string? Unavailable(string action) => null;
|
||||
}
|
||||
}
|
||||
@@ -1,152 +0,0 @@
|
||||
using System.Diagnostics.Eventing.Reader;
|
||||
using System.Security.AccessControl;
|
||||
using System.Security.Principal;
|
||||
using Chronos.Server.Hosting;
|
||||
using Chronos.Server.Hosting.Windows;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Hosting;
|
||||
|
||||
public sealed class WindowsServiceTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public void CommandSwitchesAreParsedAndTheRestPassedOn()
|
||||
{
|
||||
Assert.Equal(ServerCommand.Run, ServerCommandLine.Parse([]).Command);
|
||||
var service = ServerCommandLine.Parse(["--service", "--urls", "x"]);
|
||||
Assert.Equal(ServerCommand.Service, service.Command);
|
||||
Assert.SequenceEqual(["--urls", "x"], service.HostArguments);
|
||||
Assert.Equal(ServerCommand.InstallService, ServerCommandLine.Parse(["--install-service"]).Command);
|
||||
Assert.Equal(ServerCommand.UninstallService, ServerCommandLine.Parse(["--uninstall-service"]).Command);
|
||||
Assert.Equal(ServerCommand.HealthCheck, ServerCommandLine.Parse(["--healthcheck"]).Command);
|
||||
Assert.Equal(ServerCommand.Help, ServerCommandLine.Parse(["/?"]).Command);
|
||||
Assert.NotNull(ServerCommandLine.Parse(["--install-service", "--uninstall-service"]).Error);
|
||||
Assert.Null(ServerCommandLine.Parse(["--service", "--service"]).Error);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void StatusReportsFollowTheServiceControlManagerRules()
|
||||
{
|
||||
var tracker = new ServiceStatusTracker();
|
||||
var start = tracker.StartPending(60_000);
|
||||
Assert.Equal((ServiceState.StartPending, 0u, 1u, 60_000u), (start.State, start.ControlsAccepted, start.CheckPoint, start.WaitHintMilliseconds));
|
||||
Assert.Equal(2u, tracker.StartPending(60_000).CheckPoint);
|
||||
var running = tracker.Running();
|
||||
Assert.Equal((ServiceState.Running, ServiceStatusTracker.AcceptStop | ServiceStatusTracker.AcceptShutdown, 0u), (running.State, running.ControlsAccepted, running.CheckPoint));
|
||||
Assert.Throws<InvalidOperationException>(() => tracker.Running());
|
||||
Assert.Equal(1u, tracker.StopPending(35_000).CheckPoint);
|
||||
Assert.Equal(2u, tracker.StopPending(35_000).CheckPoint);
|
||||
var stopped = tracker.Stopped(0);
|
||||
Assert.Equal((ServiceState.Stopped, 0u, 0u), (stopped.State, stopped.ControlsAccepted, stopped.CheckPoint));
|
||||
Assert.Throws<InvalidOperationException>(() => tracker.StopPending(1));
|
||||
Assert.Equal(1064u, new ServiceStatusTracker().Stopped(1064).ExitCode);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AServiceFailureLeadsWithTheReasonTheServerGave()
|
||||
{
|
||||
var refused = new InvalidOperationException(@"C:\ProgramData\Chronos Server belongs to PC\ada, not to SYSTEM, Administrators or the account Chronos Server runs as.");
|
||||
var text = ServiceEventLog.Describe("Chronos Server did not start:", refused);
|
||||
Assert.True(text.StartsWith(@"Chronos Server did not start: C:\ProgramData\Chronos Server belongs to PC\ada", StringComparison.Ordinal), text);
|
||||
Assert.Contains("System.InvalidOperationException", text);
|
||||
|
||||
// ReportEvent refuses a longer string: the text is cut, never between the halves of a surrogate pair.
|
||||
var cut = ServiceEventLog.Describe("x", new InvalidOperationException(new string('a', ServiceEventLog.MaxLength)));
|
||||
Assert.Equal(ServiceEventLog.MaxLength, cut.Length);
|
||||
Assert.True(cut.EndsWith("a\u2026", StringComparison.Ordinal), cut[^5..]);
|
||||
var pair = ServiceEventLog.Describe("x", new InvalidOperationException(new string('a', ServiceEventLog.MaxLength - 4) + "\uD83D\uDE00" + new string('b', 99)));
|
||||
Assert.Equal(ServiceEventLog.MaxLength - 1, pair.Length);
|
||||
Assert.True(pair.EndsWith("a\u2026", StringComparison.Ordinal), pair[^5..]);
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void AServiceFailureReachesTheApplicationEventLog()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
// Written as a source of its own, so a test run never looks like a failed service in Event Viewer.
|
||||
const string source = "Chronos.Server.Tests";
|
||||
var marker = source + " " + Guid.NewGuid().ToString("N");
|
||||
Assert.True(ServiceEventLog.Error(source, ServiceEventLog.StartFailed, marker), "the Application log takes the event");
|
||||
var filter = $"*[System[Provider[@Name='{source}'] and EventID={ServiceEventLog.StartFailed}]]";
|
||||
var query = new EventLogQuery("Application", PathType.LogName, filter) { ReverseDirection = true };
|
||||
for (var attempt = 0; attempt < 50; attempt++)
|
||||
{
|
||||
using (var reader = new EventLogReader(query))
|
||||
{
|
||||
for (var read = 0; read < 100 && reader.ReadEvent() is { } record; read++)
|
||||
{
|
||||
using (record)
|
||||
{
|
||||
// The event's one string, which Event Viewer shows whole.
|
||||
if (record.Properties.Count != 1 || record.Properties[0].Value as string != marker) continue;
|
||||
Assert.Equal((byte?)2, record.Level, "an error");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
Thread.Sleep(100);
|
||||
}
|
||||
Assert.Fail($"No {source} event carries '{marker}'.");
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void TheServiceIsRegisteredOnlyFromInsideProgramFiles()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
|
||||
Assert.True(ServiceInstaller.IsUnderProgramFiles(Path.Combine(programFiles, "Chronos", "Chronos.Server.exe")));
|
||||
Assert.False(ServiceInstaller.IsUnderProgramFiles(programFiles));
|
||||
Assert.False(ServiceInstaller.IsUnderProgramFiles(programFiles + " Tools\\Chronos"));
|
||||
Assert.False(ServiceInstaller.IsUnderProgramFiles(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "Chronos")));
|
||||
Assert.False(ServiceInstaller.IsUnderProgramFiles(Path.Combine(programFiles, "..", "Chronos")));
|
||||
// The test build is not under Program Files: registering it is refused, naming the folder.
|
||||
Assert.Contains(Path.TrimEndingDirectorySeparator(AppContext.BaseDirectory), Assert.NotNull(ServiceInstaller.UnsafeLocation()));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void AnyFileOrdinaryUsersCanChangeIsFound()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
using var identity = WindowsIdentity.GetCurrent();
|
||||
if (!new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator)) Assert.Inconclusive("registering a service needs an administrator");
|
||||
var folder = new DirectoryInfo(context.CreateTempDirectory("program"));
|
||||
File.WriteAllBytes(Path.Combine(folder.FullName, "Chronos.Server.exe"), [1]);
|
||||
var satellite = new FileInfo(Path.Combine(folder.CreateSubdirectory("it").FullName, "Chronos.Core.resources.dll"));
|
||||
File.WriteAllBytes(satellite.FullName, [1]);
|
||||
|
||||
// Like Program Files: administrators may change the folder, users only read it.
|
||||
var locked = new DirectorySecurity();
|
||||
locked.SetAccessRuleProtection(isProtected: true, preserveInheritance: false);
|
||||
var everything = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
|
||||
foreach (var account in new[] { new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), identity.User! })
|
||||
locked.AddAccessRule(new FileSystemAccessRule(account, FileSystemRights.FullControl, everything, PropagationFlags.None, AccessControlType.Allow));
|
||||
locked.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.ReadAndExecute, everything,
|
||||
PropagationFlags.None, AccessControlType.Allow));
|
||||
folder.SetAccessControl(locked);
|
||||
Assert.Null(ServiceInstaller.FindChangeable(folder, recursive: true));
|
||||
|
||||
// One satellite assembly users may replace is enough: the service would load it as SYSTEM.
|
||||
var open = satellite.GetAccessControl();
|
||||
open.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.Modify, AccessControlType.Allow));
|
||||
satellite.SetAccessControl(open);
|
||||
Assert.Equal(satellite.FullName, ServiceInstaller.FindChangeable(folder, recursive: true));
|
||||
Assert.Null(ServiceInstaller.FindChangeable(folder, recursive: false));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void TheDispatcherDeclinesAConsoleProcess()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
var built = false;
|
||||
Assert.False(WindowsServiceHost.Run(() =>
|
||||
{
|
||||
built = true;
|
||||
throw new InvalidOperationException("never built outside the SCM");
|
||||
}));
|
||||
Assert.False(built);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user