Files
Chronos/tests/Chronos.App.Tests/Server/LibraryShareTests.cs
T
Alby96 20d64af4a4
CI / Build and test (push) Successful in 11m36s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 12s
Release / Build, test and publish (push) Successful in 14m56s
CI / PostgreSQL 16 integration (push) Successful in 10m11s
CI / PostgreSQL 17 integration (push) Successful in 10m15s
CI / Docker image (push) Successful in 45s
Release / Server image (push) Successful in 4m55s
feat: single setup, mass-pass progress, per-server homes, Desktop shares its library (owner review 5, v1.1.0) (#68)
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
2026-11-15 18:11:43 +01:00

193 lines
8.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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);
}
}
}