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>
340 lines
20 KiB
C#
340 lines
20 KiB
C#
using Microsoft.AspNetCore.HttpOverrides;
|
|
using Microsoft.Extensions.DependencyInjection.Extensions;
|
|
using Microsoft.AspNetCore.Server.Kestrel.Core;
|
|
using Chronos.Core.Diagnostics;
|
|
using Chronos.Data;
|
|
using Chronos.Data.Archiving;
|
|
using Chronos.Data.Housekeeping;
|
|
using Chronos.Protocol;
|
|
using Chronos.Server.Api;
|
|
using Chronos.Server.Configuration;
|
|
using Chronos.Server.Events;
|
|
using Chronos.Server.Jobs;
|
|
using Chronos.Server.Security;
|
|
using Chronos.Server.Storage;
|
|
|
|
namespace Chronos.Server.Hosting;
|
|
|
|
/// <summary>
|
|
/// Builds the Chronos Server web application from <see cref="ServerOptions"/> (used by Chronos.Server.Host's Program and
|
|
/// tests). The archive module plugs in through the <c>configureServices</c> callback of <see cref="Build"/>,
|
|
/// which runs before the server's own registrations: it must register <see cref="IArchiveIngest"/> and
|
|
/// <see cref="IFrameAssetLocator"/> (the server refuses to start without them), may add
|
|
/// <see cref="Chronos.Data.Jobs.IJobHandler"/>s, and may resolve <see cref="ChronosDatabase"/>, <see cref="ServerArchive"/>
|
|
/// and <see cref="ServerOptions"/> from DI in its factories. <see cref="BuildHosted"/> builds the same server over the index,
|
|
/// engines and scheduler of Chronos Desktop, which shares its library with it (owner review 5, #67).
|
|
/// </summary>
|
|
public static class ServerHost
|
|
{
|
|
/// <summary>Request bodies other than upload chunks stay small (BRIEF §14.2 limits).</summary>
|
|
public const long JsonBodyLimit = 1024 * 1024;
|
|
|
|
public static WebApplication Build(ServerOptions options, string[] args, Action<IServiceCollection>? configureServices = null)
|
|
{
|
|
// Before anything is written there: the folder holds the database, the TLS key and the first admin password.
|
|
DataFolderAccess.Restrict(options.DataPath);
|
|
Directory.CreateDirectory(options.LogPath);
|
|
Directory.CreateDirectory(options.UploadsPath);
|
|
var archiveOpenToOthers = DataFolderAccess.PrepareArchive(options.ArchivePath);
|
|
|
|
var builder = WebApplication.CreateSlimBuilder(new WebApplicationOptions { Args = args, ContentRootPath = AppContext.BaseDirectory });
|
|
// The console and the files each follow their own level, which the admin panel changes while the server runs.
|
|
var logging = new ServerLogging(options);
|
|
logging.AddTo(builder.Logging);
|
|
builder.Services.AddSingleton(logging);
|
|
|
|
// The archive module registers first, so a missing piece stops the server before it touches the database.
|
|
configureServices?.Invoke(builder.Services);
|
|
RequireArchiveModule(builder.Services);
|
|
|
|
using var bootLoggerFactory = LoggerFactory.Create(l => l.AddSimpleConsole(c => c.SingleLine = true).SetMinimumLevel(options.ConsoleLogLevel));
|
|
var bootLogger = bootLoggerFactory.CreateLogger("Chronos.Server");
|
|
var certificate = CertificateStore.Load(options, bootLogger);
|
|
var database = ServerDatabase.OpenAsync(options, bootLogger, CancellationToken.None).GetAwaiter().GetResult();
|
|
try
|
|
{
|
|
var archive = ServerArchive.OpenAsync(database, options, CancellationToken.None).GetAwaiter().GetResult();
|
|
AdminBootstrap.RunAsync(database, options, TimeProvider.System, bootLogger, CancellationToken.None).GetAwaiter().GetResult();
|
|
var state = new ServerState
|
|
{
|
|
TlsFingerprint = certificate is null ? null : CertificateStore.Fingerprint(certificate),
|
|
Database = ServerDatabase.DescribeAsync(database, CancellationToken.None).GetAwaiter().GetResult(),
|
|
ServerId = ServerIdAsync(database, bootLogger, CancellationToken.None).GetAwaiter().GetResult(),
|
|
};
|
|
|
|
ConfigureKestrel(builder, options, certificate);
|
|
ConfigureServices(builder.Services, options, state, database, archive);
|
|
|
|
var app = builder.Build();
|
|
Log.SetSink(new LoggerSink(app.Services.GetRequiredService<ILoggerFactory>()));
|
|
ConfigurePipeline(app, options);
|
|
app.Logger.LogInformation("Chronos Server {Version} · archive {Archive} · data {Data} · {Database} · TLS {Tls}{Fingerprint}",
|
|
SystemEndpoints.Version, options.ArchivePath, options.DataPath, state.Database, options.TlsMode,
|
|
state.TlsFingerprint is null ? string.Empty : " · SHA-256 " + state.TlsFingerprint);
|
|
if (archiveOpenToOthers)
|
|
{
|
|
app.Logger.LogWarning("Accounts other than SYSTEM, Administrators and the one Chronos Server runs as can change the archive {Archive}: "
|
|
+ "they could put a link in place of a folder and redirect the files the server moves. Let only those accounts change it (others may read it).",
|
|
options.ArchivePath);
|
|
}
|
|
if (archive.Structure is { IsComplete: false } structure)
|
|
{
|
|
app.Logger.LogWarning("The archive's folders are incomplete: {Problem} Uploads, deletions and conversions that need the missing folder fail "
|
|
+ "until it can be created; the dashboard shows the problem until then. {Detail}", structure.Message, structure.Detail ?? string.Empty);
|
|
}
|
|
// A space path that cannot be measured is warned about at start, not first when someone opens the dashboard.
|
|
if (!string.IsNullOrWhiteSpace(options.SpacePath)) app.Services.GetRequiredService<VolumeSpace>().Report(archive.Root);
|
|
if (options.FormerWorkersVariable)
|
|
{
|
|
app.Logger.LogWarning("CHRONOS_WORKERS is the former name of CHRONOS_PARALLELISM: jobs now run one at a time, and the value is how many "
|
|
+ "photos the running job processes at once. Rename the variable.");
|
|
}
|
|
if (options.IgnoredSavedPorts)
|
|
{
|
|
app.Logger.LogWarning("server.json sets HttpPort or HttpsPort, which a container ignores: it listens on {Http} and {Https}, the ports the "
|
|
+ "template maps. Saving the settings in the admin panel removes the saved values. Set the Public HTTP and HTTPS ports to the host "
|
|
+ "ports clients use; with network type Host, add the variable CHRONOS_HTTP_PORT or CHRONOS_HTTPS_PORT to listen on other ports.",
|
|
options.HttpPort, options.HttpsPort);
|
|
}
|
|
app.Lifetime.ApplicationStopping.Register(() => app.Logger.LogInformation("Chronos Server stopping"));
|
|
app.Lifetime.ApplicationStopped.Register(() => database.DisposeAsync().AsTask().GetAwaiter().GetResult());
|
|
return app;
|
|
}
|
|
catch
|
|
{
|
|
database.DisposeAsync().AsTask().GetAwaiter().GetResult();
|
|
throw;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The server Chronos Desktop runs in its own process to share this PC's library (owner review 5, #67): the same API, admin
|
|
/// panel, accounts, TLS, discovery, uploads, sync, events and render nodes as a server of its own, over the desktop's
|
|
/// index, archive service, processing service, job engine and scheduler (<paramref name="engine"/>), which it never
|
|
/// creates, starts, stops or disposes. Its own state is in <see cref="ServerOptions.DataPath"/> (made private first);
|
|
/// the first administrator is made there as on a new server. It sets no process-wide log sink or level and hooks no
|
|
/// console signal: the desktop's stay. Runs synchronously: call it off the UI thread.
|
|
/// </summary>
|
|
public static HostedServer BuildHosted(ServerOptions options, HostedEngine engine)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(options);
|
|
ArgumentNullException.ThrowIfNull(engine);
|
|
if (!options.Hosted) throw new ArgumentException("The options are not those of a hosted server (ServerOptions.ForHosted).", nameof(options));
|
|
DataFolderAccess.Restrict(options.DataPath);
|
|
Directory.CreateDirectory(options.LogPath);
|
|
Directory.CreateDirectory(options.UploadsPath);
|
|
|
|
// The desktop's command line and environment are not the server's.
|
|
var builder = WebApplication.CreateSlimBuilder(new WebApplicationOptions { Args = [], ContentRootPath = AppContext.BaseDirectory });
|
|
var logging = new ServerLogging(options, setsEngineLevel: false);
|
|
logging.AddTo(builder.Logging);
|
|
builder.Services.AddSingleton(logging);
|
|
|
|
var bootLogger = new FileLoggerProvider(logging).CreateLogger("Chronos.Server");
|
|
var certificate = CertificateStore.Load(options, bootLogger);
|
|
AdminBootstrap.RunAsync(engine.Database, options, TimeProvider.System, bootLogger, CancellationToken.None).GetAwaiter().GetResult();
|
|
var state = new ServerState
|
|
{
|
|
TlsFingerprint = certificate is null ? null : CertificateStore.Fingerprint(certificate),
|
|
Database = ServerDatabase.DescribeAsync(engine.Database, CancellationToken.None).GetAwaiter().GetResult(),
|
|
ServerId = ServerIdAsync(engine.Database, bootLogger, CancellationToken.None).GetAwaiter().GetResult(),
|
|
};
|
|
var archive = ServerArchive.ForArchive(engine.Archive);
|
|
|
|
ConfigureKestrel(builder, options, certificate);
|
|
ConfigureServices(builder.Services, options, state, engine.Database, archive, engine);
|
|
|
|
var app = builder.Build();
|
|
ConfigurePipeline(app, options);
|
|
app.Logger.LogInformation("Chronos Server {Version} in Chronos Desktop · archive {Archive} · data {Data} · TLS {Tls}{Fingerprint}",
|
|
SystemEndpoints.Version, archive.Root, options.DataPath, options.TlsMode,
|
|
state.TlsFingerprint is null ? string.Empty : " · SHA-256 " + state.TlsFingerprint);
|
|
if (archive.Structure is { IsComplete: false } structure)
|
|
app.Logger.LogWarning("The archive's folders are incomplete: {Problem} {Detail}", structure.Message, structure.Detail ?? string.Empty);
|
|
return new HostedServer(app, options, state, logging);
|
|
}
|
|
|
|
/// <summary>Kestrel on every interface: the HTTP port, and the HTTPS port with HTTP/2 when there is a certificate.</summary>
|
|
private static void ConfigureKestrel(WebApplicationBuilder builder, ServerOptions options, System.Security.Cryptography.X509Certificates.X509Certificate2? certificate) =>
|
|
builder.WebHost.ConfigureKestrel(k =>
|
|
{
|
|
k.AddServerHeader = false;
|
|
k.Limits.MaxRequestBodySize = JsonBodyLimit;
|
|
k.Limits.RequestHeadersTimeout = TimeSpan.FromSeconds(30);
|
|
k.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2);
|
|
k.ListenAnyIP(options.HttpPort);
|
|
if (certificate is not null) k.ListenAnyIP(options.HttpsPort, l =>
|
|
{
|
|
l.Protocols = HttpProtocols.Http1AndHttp2;
|
|
l.UseHttps(certificate);
|
|
});
|
|
});
|
|
|
|
/// <summary>The app setting that holds the server's stable id (<see cref="ServerInfo.ServerId"/>).</summary>
|
|
public const string ServerIdKey = "server.id";
|
|
|
|
/// <summary>
|
|
/// The server's stable id (owner review 5, #66): read from its database's app settings (<see cref="ServerIdKey"/>), or made
|
|
/// once (a version 7 UUID) and stored there at the first start. It lives in the database, so a restore keeps it and the
|
|
/// server keeps its id whatever address, port or name it is reached by. A value that does not read as an id is kept aside
|
|
/// in the log and replaced.
|
|
/// </summary>
|
|
public static async Task<Guid> ServerIdAsync(ChronosDatabase database, ILogger? logger, CancellationToken cancellationToken)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(database);
|
|
var json = await database.Settings.GetJsonAsync(Data.Repositories.SettingScope.App, null, ServerIdKey, cancellationToken).ConfigureAwait(false);
|
|
if (json is not null)
|
|
{
|
|
try
|
|
{
|
|
using var stored = System.Text.Json.JsonDocument.Parse(json);
|
|
if (stored.RootElement.ValueKind == System.Text.Json.JsonValueKind.String && Guid.TryParse(stored.RootElement.GetString(), out var known)
|
|
&& known != Guid.Empty)
|
|
return known;
|
|
}
|
|
catch (System.Text.Json.JsonException)
|
|
{
|
|
// Replaced below; the old value is logged.
|
|
}
|
|
logger?.LogWarning("The server id stored in the database ({Value}) is not an id; a new one is made", json);
|
|
}
|
|
var id = Guid.CreateVersion7();
|
|
await database.Settings.SetJsonAsync(Data.Repositories.SettingScope.App, null, ServerIdKey, "\"" + id.ToString("D") + "\"", cancellationToken)
|
|
.ConfigureAwait(false);
|
|
logger?.LogInformation("Server id {Id} made", id);
|
|
return id;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The single composition root of the server's services; with <paramref name="hosted"/>, those of the library Chronos
|
|
/// Desktop shares, whose engines, engine and scheduler are the desktop's (owner review 5, #67).
|
|
/// </summary>
|
|
public static void ConfigureServices(IServiceCollection services, ServerOptions options, ServerState state, ChronosDatabase database, ServerArchive archive,
|
|
HostedEngine? hosted = null)
|
|
{
|
|
services.AddSingleton(options);
|
|
services.AddSingleton(state);
|
|
services.AddSingleton(database);
|
|
services.AddSingleton(archive);
|
|
services.TryAddSingleton(TimeProvider.System);
|
|
// Tests register their own first, to simulate a full volume.
|
|
services.TryAddSingleton<VolumeSpace>();
|
|
services.ConfigureHttpJsonOptions(j => j.SerializerOptions.TypeInfoResolverChain.Insert(0, ProtocolJson.Default));
|
|
services.Configure<RouteHandlerOptions>(o => o.ThrowOnBadRequest = true);
|
|
// The desktop's exit waits for everything it runs: the server it hosts stops within a few seconds.
|
|
services.Configure<HostOptions>(o => o.ShutdownTimeout = TimeSpan.FromSeconds(hosted is null ? 30 : 5));
|
|
if (hosted is not null) RegisterHosted(services, hosted);
|
|
if (options.TlsMode == TlsMode.Proxy)
|
|
{
|
|
// Only the configured proxies may say who the client is: a client that reaches the HTTP port directly would
|
|
// otherwise pick its own address for the sign-in rate limit and the audit log, and claim HTTPS.
|
|
var trusted = options.TrustedProxyNetworks();
|
|
services.Configure<ForwardedHeadersOptions>(f =>
|
|
{
|
|
f.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost;
|
|
f.KnownIPNetworks.Clear();
|
|
f.KnownProxies.Clear();
|
|
foreach (var network in trusted) f.KnownIPNetworks.Add(network);
|
|
});
|
|
}
|
|
|
|
services.AddSingleton<EventHub>();
|
|
services.AddSingleton<TokenService>();
|
|
services.AddSingleton<LoginGuard>();
|
|
services.AddSingleton<AuditLog>();
|
|
services.AddSingleton<ServerSettingsStore>();
|
|
services.AddSingleton<UploadStore>();
|
|
services.AddSingleton<UploadService>();
|
|
services.AddSingleton<RenderStore>();
|
|
services.AddSingleton<RenderUploads>();
|
|
services.AddSingleton<SequenceJobs>();
|
|
services.AddSingleton<PlanCache>();
|
|
services.AddSingleton<RenderNodeService>();
|
|
services.AddSingleton<ClientActivity>();
|
|
if (hosted is null) services.AddSingleton<JobEngineHost>();
|
|
else services.AddSingleton(sp => new JobEngineHost(hosted.Engine, sp.GetRequiredService<EventHub>()));
|
|
services.AddHostedService(sp => sp.GetRequiredService<JobEngineHost>());
|
|
// After the engine's host: the scheduler queues on its engine, starts after it and stops before it (owner review 2, R10).
|
|
services.AddSingleton<ServerScheduleHost>();
|
|
if (hosted is null) services.AddSingleton<SchedulerHost>();
|
|
else services.AddSingleton(sp => new SchedulerHost(database, hosted.Scheduler, sp.GetRequiredService<ServerScheduleHost>(), options,
|
|
sp.GetRequiredService<EventHub>(), sp.GetRequiredService<TimeProvider>(), sp.GetRequiredService<ILogger<SchedulerHost>>()));
|
|
services.AddHostedService(sp => sp.GetRequiredService<SchedulerHost>());
|
|
services.AddSingleton<RenderNodeMonitor>();
|
|
services.AddHostedService(sp => sp.GetRequiredService<RenderNodeMonitor>());
|
|
// Recovers interrupted commits at start; its sweep is the clean-up step of the upload-cleanup schedule.
|
|
services.AddSingleton<UploadMaintenance>();
|
|
services.AddHostedService(sp => sp.GetRequiredService<UploadMaintenance>());
|
|
// The desktop's archive service holds a step of its own that runs this one while it shares its library.
|
|
services.AddSingleton<UploadCleanupStep>();
|
|
services.AddSingleton<ICleanupStep>(sp => sp.GetRequiredService<UploadCleanupStep>());
|
|
// Main takes settings written outside the projects soon after they are (owner review 2, R8).
|
|
services.AddSingleton<ProjectCatchUp>();
|
|
services.AddHostedService(sp => sp.GetRequiredService<ProjectCatchUp>());
|
|
services.AddSingleton<DiscoveryBeaconService>();
|
|
services.AddHostedService(sp => sp.GetRequiredService<DiscoveryBeaconService>());
|
|
}
|
|
|
|
/// <summary>
|
|
/// The desktop's engines as the archive and processing modules would register them, and a lifetime that hooks no console
|
|
/// signal of the desktop's process (owner review 5, #67).
|
|
/// </summary>
|
|
private static void RegisterHosted(IServiceCollection services, HostedEngine hosted)
|
|
{
|
|
services.AddSingleton(hosted);
|
|
services.AddSingleton(hosted.Archives);
|
|
services.AddSingleton<IArchiveIngest>(hosted.Archives.Ingest);
|
|
services.AddSingleton<Chronos.Data.Videos.IVideoLibrary>(hosted.Archives.Videos);
|
|
services.AddSingleton<IFrameAssetLocator, ArchiveAssetLocator>();
|
|
services.AddSingleton(hosted.Processing);
|
|
services.AddSingleton<RenderNodeAvailability>();
|
|
services.AddSingleton<IHostLifetime, DesktopHostLifetime>();
|
|
}
|
|
|
|
private static void ConfigurePipeline(WebApplication app, ServerOptions options)
|
|
{
|
|
if (options.TlsMode == TlsMode.Proxy) app.UseForwardedHeaders();
|
|
app.UseMiddleware<ResponseMiddleware>();
|
|
app.UseWebSockets(new WebSocketOptions { KeepAliveInterval = TimeSpan.FromSeconds(30) });
|
|
app.UseRouting();
|
|
app.UseMiddleware<AuthenticationMiddleware>();
|
|
|
|
AdminPanel.Map(app, options);
|
|
var api = app.MapGroup("/api/v1");
|
|
// A sequence, frame, render or video of another archive of the index answers as an unknown id (owner review 5, #67).
|
|
api.AddEndpointFilter(ServedItems.FilterAsync);
|
|
SystemEndpoints.Map(app, api);
|
|
AuthEndpoints.Map(api);
|
|
UserEndpoints.Map(api);
|
|
SequenceEndpoints.Map(api);
|
|
ProjectEndpoints.Map(api);
|
|
LibraryEndpoints.Map(api);
|
|
FileEndpoints.Map(api);
|
|
VideoEndpoints.Map(api);
|
|
UploadEndpoints.Map(api);
|
|
JobEndpoints.Map(api);
|
|
ScheduleEndpoints.Map(api);
|
|
NodeEndpoints.Map(api);
|
|
ArchiveEndpoints.Map(api);
|
|
TrashEndpoints.Map(api);
|
|
AdminEndpoints.Map(api);
|
|
DiagnosticsEndpoints.Map(api);
|
|
EventEndpoints.Map(api);
|
|
app.MapFallback("/api/{**path}", (HttpContext context) => ApiErrors.NotFound(context)).AllowAnonymousCaller();
|
|
}
|
|
|
|
/// <summary>Fails fast when the archive module's services are missing (the server would accept uploads it cannot commit).</summary>
|
|
private static void RequireArchiveModule(IServiceCollection services)
|
|
{
|
|
var missing = new List<string>();
|
|
if (!services.Any(d => d.ServiceType == typeof(IArchiveIngest))) missing.Add($"{typeof(IArchiveIngest).FullName} (commits verified uploads into the archive layout)");
|
|
if (!services.Any(d => d.ServiceType == typeof(IFrameAssetLocator))) missing.Add($"{typeof(IFrameAssetLocator).FullName} (finds proxies and thumbnails)");
|
|
if (missing.Count > 0)
|
|
{
|
|
throw new InvalidOperationException(
|
|
"Chronos Server cannot start: no implementation is registered for " + string.Join(" and ", missing) +
|
|
". Register them in the services callback of ServerHost.Build.");
|
|
}
|
|
}
|
|
}
|