feat: Chronos Desktop shares its library on the LAN (owner review 5 P4)

Chronos Server for Windows is replaced by Settings > Server > Share this
library: Chronos Desktop hosts the server engine in its own process over its
own index, archive and processing services, job engine and scheduler, so a
second PC, the Uploader and render nodes use this PC's library without a
Windows service or a second index.

- Chronos.Server is a library; Chronos.Server.Host is the console exe that
  Docker and development runs start. The App references the library and the
  ASP.NET Core shared framework (no package).
- ServerHost.BuildHosted/HostedServer: reuses the desktop's engines and
  never creates, starts or disposes them; no static log sink, no console
  lifetime; server.json plus desktop-owned values locked "Set in Chronos
  Desktop"; only upload-cleanup and audit-cleanup schedules are added.
- Both modes: by-id endpoints scoped to the served archive, a client's
  render export folder dropped; hosted mode exposes server job kinds only.
- Desktop: LibraryShare (start after the schedules, stop first, port in
  use named), Settings > Server sharing rows, Server > This library panel
  (state, addresses with Copy, ports, fingerprint, temporary admin
  password, clients, admin panel), own library refused by ConnectFlow and
  dropped from LAN discovery, the uploads sweep step, thumbnails after scans
  while sharing, capture scenes server-share and server-share-failed.
- Removed: the Windows service hosting of Chronos.Server, its switches and
  its tests.

Refs #67

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-15 14:55:50 +01:00
1 parent 9ad8c6f7a9
commit 8d41992d84
69 files changed
+2633 -859

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);
}
}
}