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>
219 lines
11 KiB
C#
219 lines
11 KiB
C#
using Chronos.Core.Model;
|
||
using Chronos.Data;
|
||
using Chronos.Data.Scheduling;
|
||
using Chronos.Protocol;
|
||
using Chronos.Server.Configuration;
|
||
using Chronos.Server.Events;
|
||
|
||
namespace Chronos.Server.Jobs;
|
||
|
||
/// <summary>
|
||
/// Hosts the server's <see cref="Scheduler"/> (owner review 2, R10) on the <see cref="JobEngineHost"/>'s engine with the
|
||
/// <see cref="ServerScheduleHost"/>: registered after the engine's host, so it starts after it and stops before it. At start
|
||
/// (<see cref="Scheduler.StartAsync(IScheduleHost, Func{CancellationToken, Task}, CancellationToken)"/>) it seeds the system
|
||
/// schedules, puts the age limits that environment variables fix into them (<see cref="ServerScheduleHost.LockedAgeOf"/>)
|
||
/// before the first pass, so a run caught up at start already uses them, and settles missed runs; then it runs the archive
|
||
/// scan once in the background, as the former polling did, so the photos of an adopted folder are indexed without waiting
|
||
/// for its first interval (only while that schedule is enabled). Every <see cref="ServerScheduleHost.ScanMinutes"/> it
|
||
/// takes the settings another writer put into archive.json, as the polling did, whatever the scan schedule does. The audit
|
||
/// retention in force is the audit clean-up schedule's age limit, 0 while it is off or without its audit step:
|
||
/// Settings › Logs shows it (<see cref="AuditRetentionAsync"/>) and sets it (<see cref="ApplyAuditRetentionAsync"/>);
|
||
/// <see cref="ServerOptions.AuditRetentionDays"/> is only what the schedule is seeded and reset with, or what an environment
|
||
/// variable fixes. Every schedule change and run goes out as a <see cref="ScheduleChangedEvent"/>. On the library Chronos
|
||
/// Desktop shares (owner review 5, #67) the scheduler is the desktop's, already running: this host follows it while the
|
||
/// server runs, adds the server's own system schedules to it (<see cref="ServerScheduleHost.ShareSchedules"/>) and never
|
||
/// starts, seeds the desktop's schedules for or disposes it.
|
||
/// </summary>
|
||
public sealed class SchedulerHost : IHostedService
|
||
{
|
||
private readonly ChronosDatabase _db;
|
||
private readonly TimeProvider _time;
|
||
private readonly ILogger<SchedulerHost> _logger;
|
||
private readonly CancellationTokenSource _stopping = new();
|
||
private Task _startScan = Task.CompletedTask;
|
||
private Task _refresh = Task.CompletedTask;
|
||
private readonly bool _ownsScheduler = true;
|
||
private readonly Action<ScheduleDto> _changed;
|
||
private readonly Action<Guid> _deleted;
|
||
private readonly int _auditRetentionDays;
|
||
private int _stopped;
|
||
|
||
public SchedulerHost(ChronosDatabase db, JobEngineHost jobs, ServerScheduleHost host, EventHub events, TimeProvider time, ILogger<SchedulerHost> logger)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(jobs);
|
||
ArgumentNullException.ThrowIfNull(events);
|
||
_db = db;
|
||
_time = time;
|
||
_logger = logger;
|
||
Host = host;
|
||
Scheduler = new Scheduler(db, jobs.Engine, new SchedulerOptions { Time = time });
|
||
// The Scheduled tab of the admin panel follows them, the runs that queue no job included.
|
||
_changed = schedule => events.Publish(new ScheduleChangedEvent(schedule.Id, Deleted: false));
|
||
_deleted = id => events.Publish(new ScheduleChangedEvent(id, Deleted: true));
|
||
Scheduler.ScheduleChanged += _changed;
|
||
Scheduler.ScheduleDeleted += _deleted;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Follows <paramref name="scheduler"/>, the running scheduler of Chronos Desktop (owner review 5, #67), from
|
||
/// <see cref="StartAsync"/> to <see cref="StopAsync"/>.
|
||
/// </summary>
|
||
public SchedulerHost(ChronosDatabase db, Scheduler scheduler, ServerScheduleHost host, ServerOptions options, EventHub events, TimeProvider time,
|
||
ILogger<SchedulerHost> logger)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(scheduler);
|
||
ArgumentNullException.ThrowIfNull(options);
|
||
ArgumentNullException.ThrowIfNull(events);
|
||
_db = db;
|
||
_time = time;
|
||
_logger = logger;
|
||
_ownsScheduler = false;
|
||
_auditRetentionDays = options.AuditRetentionDays;
|
||
Host = host;
|
||
Scheduler = scheduler;
|
||
_changed = schedule => events.Publish(new ScheduleChangedEvent(schedule.Id, Deleted: false));
|
||
_deleted = id => events.Publish(new ScheduleChangedEvent(id, Deleted: true));
|
||
}
|
||
|
||
public Scheduler Scheduler { get; }
|
||
|
||
public ServerScheduleHost Host { get; }
|
||
|
||
public async Task StartAsync(CancellationToken cancellationToken)
|
||
{
|
||
var stopping = _stopping.Token;
|
||
if (!_ownsScheduler)
|
||
{
|
||
Scheduler.ScheduleChanged += _changed;
|
||
Scheduler.ScheduleDeleted += _deleted;
|
||
// The desktop seeds its own system schedules; the server's state brings two more (never overwritten once there).
|
||
if (await _db.Schedules.EnsureSystemAsync(ServerScheduleHost.ShareSchedules(_auditRetentionDays), _time.GetUtcNow(), cancellationToken) > 0)
|
||
Scheduler.Wake();
|
||
}
|
||
else
|
||
{
|
||
var started = Scheduler.Options.Time.GetUtcNow();
|
||
await Scheduler.StartAsync(Host, ApplyLockedAgesAsync, cancellationToken);
|
||
_startScan = Task.Run(() => ScanAtStartAsync(started, stopping), CancellationToken.None);
|
||
}
|
||
// Created here, so its first period counts from the start.
|
||
var timer = new PeriodicTimer(TimeSpan.FromMinutes(ServerScheduleHost.ScanMinutes), _time);
|
||
_refresh = Task.Run(() => RefreshArchiveAsync(timer, stopping), CancellationToken.None);
|
||
}
|
||
|
||
public async Task StopAsync(CancellationToken cancellationToken)
|
||
{
|
||
if (Interlocked.Exchange(ref _stopped, 1) == 1) return;
|
||
await _stopping.CancelAsync();
|
||
await _startScan;
|
||
await _refresh;
|
||
if (_ownsScheduler)
|
||
{
|
||
await Scheduler.DisposeAsync();
|
||
}
|
||
else
|
||
{
|
||
// The desktop's scheduler runs on: only this server stops following it.
|
||
Scheduler.ScheduleChanged -= _changed;
|
||
Scheduler.ScheduleDeleted -= _deleted;
|
||
}
|
||
_stopping.Dispose();
|
||
}
|
||
|
||
/// <summary>
|
||
/// The audit retention in force (owner review 2, R10, R11): the audit clean-up schedule's age limit, 0 while the schedule
|
||
/// is off or its steps leave out the audit step (nothing is deleted); null before the schedule is seeded.
|
||
/// </summary>
|
||
public async Task<int?> AuditRetentionAsync(CancellationToken cancellationToken = default) =>
|
||
await _db.Schedules.GetBySystemKeyAsync(ServerScheduleHost.AuditCleanup, cancellationToken) is { } row ? InForce(row) : null;
|
||
|
||
/// <summary>
|
||
/// Puts the audit retention saved in Settings › Logs into the audit clean-up schedule, the one source of truth (owner
|
||
/// review 2, R10, R11): enabled with a limit and the audit step, off at 0, which keeps everything.
|
||
/// </summary>
|
||
public Task ApplyAuditRetentionAsync(int days, CancellationToken cancellationToken = default) =>
|
||
ApplyAgeAsync(ServerScheduleHost.AuditCleanup, days, "Settings › Logs", cancellationToken);
|
||
|
||
/// <summary>The audit clean-up schedule's age limit, 0 while it is off or without the audit step, which alone deletes by it.</summary>
|
||
private static int InForce(Schedule row) =>
|
||
row.Enabled && ScheduleMapping.Parameters(row) is { Steps: { } steps } parameters && steps.Contains(Chronos.Data.Housekeeping.CleanupSteps.Audit)
|
||
? parameters.OlderThanDays ?? 0
|
||
: 0;
|
||
|
||
/// <summary>The age limits environment variables fix, put into their system schedules at every start, before the first pass.</summary>
|
||
private async Task ApplyLockedAgesAsync(CancellationToken cancellationToken)
|
||
{
|
||
foreach (var system in Host.SystemSchedules)
|
||
{
|
||
if (Host.LockedAgeOf(system.SystemKey) is { } locked) await ApplyAgeAsync(system.SystemKey, locked.Days, locked.Variable, cancellationToken);
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Sets the age limit of the system schedule <paramref name="systemKey"/> to <paramref name="days"/>, enabling it when it
|
||
/// has a limit now and disabling it at 0; a limit also ticks again the steps it deletes with
|
||
/// (<see cref="ServerScheduleHost.AgedSteps"/>) when they were unticked. Nothing when it already holds the value, with those
|
||
/// steps, and is on (off at 0). A schedule kept enabled keeps its next run, so a missed run is still caught up, with the
|
||
/// new limit.
|
||
/// </summary>
|
||
private async Task ApplyAgeAsync(string systemKey, int days, string source, CancellationToken cancellationToken)
|
||
{
|
||
if (await _db.Schedules.GetBySystemKeyAsync(systemKey, cancellationToken) is not { } row) return;
|
||
var parameters = ScheduleMapping.Parameters(row);
|
||
var steps = parameters.Steps ?? [];
|
||
var missing = days > 0 ? Host.AgedSteps(systemKey).Except(steps).ToList() : [];
|
||
if (parameters.OlderThanDays == days && row.Enabled == (days > 0) && missing.Count == 0) return;
|
||
var result = await Scheduler.UpdateAsync(row.Id,
|
||
new UpdateScheduleRequest(Parameters: parameters with { OlderThanDays = days, Steps = missing.Count == 0 ? parameters.Steps : [.. steps, .. missing] },
|
||
Enabled: days > 0),
|
||
cancellationToken);
|
||
if (result.Problem is { } problem) _logger.LogWarning("{Source} could not be applied to the {Schedule} schedule ({Problem})", source, row.Name, problem);
|
||
else _logger.LogInformation("{Source} sets the {Schedule} schedule to {Days} day(s)", source, row.Name, days);
|
||
}
|
||
|
||
/// <summary>The archive scan's run at start, unless the first pass already fired it or it is disabled.</summary>
|
||
private async Task ScanAtStartAsync(DateTimeOffset started, CancellationToken cancellationToken)
|
||
{
|
||
try
|
||
{
|
||
await Scheduler.RunSystemNowAsync(ServerScheduleHost.ArchiveScan, started, cancellationToken);
|
||
}
|
||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||
{
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
_logger.LogWarning(ex, "The archive scan at start could not be queued; its schedule queues the next one");
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Takes the settings a desktop sharing the archive put into archive.json at every tick of <paramref name="timer"/>
|
||
/// (<see cref="ServerScheduleHost.GetArchiveAsync"/>), so uploads follow them although the scan schedule's runs, which
|
||
/// read them too, are skipped while a long scan is pending, or are rare or off.
|
||
/// </summary>
|
||
private async Task RefreshArchiveAsync(PeriodicTimer timer, CancellationToken cancellationToken)
|
||
{
|
||
using (timer)
|
||
{
|
||
try
|
||
{
|
||
while (await timer.WaitForNextTickAsync(cancellationToken))
|
||
{
|
||
try
|
||
{
|
||
await Host.GetArchiveAsync(cancellationToken);
|
||
}
|
||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||
{
|
||
_logger.LogWarning(ex, "The archive's archive.json could not be read; the next tick tries again");
|
||
}
|
||
}
|
||
}
|
||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||
{
|
||
}
|
||
}
|
||
}
|
||
}
|