Files
Chronos/src/Chronos.Server/Jobs/ServerScheduleHost.cs
T
Alby96andClaude Opus 5.5 8d41992d84 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>
2026-11-15 14:55:50 +01:00

166 lines
9.1 KiB
C#

using Chronos.Core.Archiving;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Scheduling;
using Chronos.Protocol;
using Chronos.Server.Configuration;
using Chronos.Server.Storage;
namespace Chronos.Server.Jobs;
/// <summary>An age limit an environment variable fixes for a system schedule: the setting it comes from, the variable and the days.</summary>
public sealed record LockedAge(string Setting, string Variable, int Days);
/// <summary>
/// What the server tells its <see cref="Scheduler"/> (owner review 2, R10): the container's time zone (TZ), the archive it
/// serves with the settings another writer put into archive.json (read again at every run and, whatever the runs do, every
/// <see cref="ScanMinutes"/> by <see cref="SchedulerHost"/>, as the former polling did), the server's own clean-up steps,
/// and its system schedules, which stand for every timer it ran out of sight before: the archive scan every 10 minutes
/// (no catch-up), the uploads sweep every 6 hours, the nightly copy of an SQLite index, the job history and the audit log
/// retentions. They are seeded from <see cref="ServerOptions"/> once (the user's edits stay) and reset to the options as
/// they are then.
/// </summary>
public sealed class ServerScheduleHost : IScheduleHost
{
public const string ArchiveScan = "archive-scan";
public const string UploadCleanup = "upload-cleanup";
public const string IndexBackup = DatabaseBackups.ScheduleKey;
public const string Housekeeping = "housekeeping";
public const string AuditCleanup = "audit-cleanup";
/// <summary>Minutes between two archive scans (the desktop's rhythm, as the polling had).</summary>
public const int ScanMinutes = 10;
/// <summary>
/// Hours between two sweeps of abandoned uploads: rare enough to keep the job history readable (four clean-up jobs a
/// day); an idle upload still expires after <see cref="ServerOptions.UploadRetentionHours"/>, at most this much later.
/// </summary>
public const int UploadSweepHours = 6;
private readonly ChronosDatabase _db;
private readonly ServerOptions _options;
private readonly ServerArchive _archive;
private readonly ArchiveService? _archives;
private readonly ILogger<ServerScheduleHost> _logger;
public ServerScheduleHost(ChronosDatabase db, ServerOptions options, ServerArchive archive, IServiceProvider services, ILogger<ServerScheduleHost> logger)
{
ArgumentNullException.ThrowIfNull(services);
_db = db;
_options = options;
_archive = archive;
_logger = logger;
// Without the archive module (tests with a fake ingest) nothing refreshes archive.json and no clean-up step exists.
_archives = services.GetService<ArchiveService>();
CleanupSteps = _archives is null ? [] : [.. _archives.CleanupSteps.Select(s => s.Name)];
TimeZone = ResolveTimeZone(Environment.GetEnvironmentVariable("TZ"), logger);
}
public TimeZoneInfo TimeZone { get; }
public IReadOnlyList<string> CleanupSteps { get; }
/// <summary>Built from the options as they are now, so a reset follows a changed <see cref="ServerOptions.AuditRetentionDays"/>.</summary>
public IReadOnlyList<SystemSchedule> SystemSchedules
{
get
{
var nightly = (Backup: new TimeOnly(3, 0), History: new TimeOnly(4, 0));
var share = ShareSchedules(_options.AuditRetentionDays);
var list = new List<SystemSchedule>
{
// A missed scan is not caught up: the next one comes within minutes and SchedulerHost scans once at start.
new(ArchiveScan, "Archive scan", ScheduleActions.Scan, ScheduleRecurrence.Interval(ScanMinutes, RecurrenceUnit.Minutes), CatchUp: false),
share[0],
};
// PostgreSQL is backed up with its own tools (BRIEF §6.2): no schedule that could never run. Seeded due at once
// when the newest copy is a day old, as the daily loop it replaced made one at start.
if (DatabaseBackups.Unavailable(_db) is null)
{
list.Add(new(IndexBackup, "Index backup", ScheduleActions.Backup, ScheduleRecurrence.DailyAt(nightly.Backup),
new ScheduleParametersDto(Keep: DatabaseBackups.Keep), LastDone: DatabaseBackups.Newest(_db, _archives?.BackupDirectory)));
}
list.Add(new(Housekeeping, "Housekeeping", ScheduleActions.Cleanup, ScheduleRecurrence.DailyAt(nightly.History),
new ScheduleParametersDto(OlderThanDays: _options.JobHistoryDays, Steps: [Chronos.Data.Housekeeping.CleanupSteps.JobHistory])));
list.Add(share[1]);
return list;
}
}
/// <summary>
/// The system schedules of a server's own state, which Chronos Desktop adds to its own while it shares its library
/// (owner review 5, #67), the archive scan, the index backup and the housekeeping being the desktop's: the uploads sweep
/// every <see cref="UploadSweepHours"/> hours and the audit log clean-up, nightly at 04:30, off at 0 days.
/// </summary>
public static IReadOnlyList<SystemSchedule> ShareSchedules(int auditRetentionDays) =>
[
new(UploadCleanup, "Upload clean-up", ScheduleActions.Cleanup, ScheduleRecurrence.Interval(UploadSweepHours, RecurrenceUnit.Hours),
new ScheduleParametersDto(OlderThanDays: UploadMaintenance.FinishedRetentionDays, Steps: [UploadCleanupStep.StepName])),
new(AuditCleanup, "Audit log clean-up", ScheduleActions.Cleanup, ScheduleRecurrence.DailyAt(new TimeOnly(4, 30)),
new ScheduleParametersDto(OlderThanDays: auditRetentionDays, Steps: [Chronos.Data.Housekeeping.CleanupSteps.Audit]), Enabled: auditRetentionDays > 0),
];
/// <summary>
/// The served archive, after taking the settings another writer sharing it (a desktop) put into its archive.json, as
/// the former polling did; while it is offline, or the file cannot be read, as the index has it.
/// </summary>
public async ValueTask<Archive?> GetArchiveAsync(CancellationToken cancellationToken)
{
var current = _archive.Current;
if (_archives is null || ArchiveService.GetAvailability(current) == ArchiveAvailability.Offline) return current;
try
{
return await _archive.RefreshAsync(_archives, _db, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger.LogWarning(ex, "The settings in the archive's archive.json could not be read; schedules use those of the index");
return _archive.Current;
}
}
/// <summary>The server runs every action it has a handler for; the scheduler finds the rest out itself.</summary>
public string? Unavailable(string action) => null;
/// <summary>The server has no such setting: a scan schedule's own <c>deep</c> parameter decides, off when unset.</summary>
public bool DeepAnalysisAfterScan => false;
/// <summary>
/// The age limit of the system schedule <paramref name="systemKey"/> that an environment variable fixes
/// (<c>CHRONOS_AUDIT_RETENTION_DAYS</c> for <see cref="AuditCleanup"/>); null when the schedule's own value applies.
/// </summary>
public LockedAge? LockedAgeOf(string? systemKey) =>
systemKey == AuditCleanup && _options.Locked.Contains(nameof(ServerOptions.AuditRetentionDays))
? new LockedAge(nameof(ServerOptions.AuditRetentionDays), ServerOptions.AuditRetentionVariable, _options.AuditRetentionDays)
: null;
/// <summary>
/// The steps the age limit of the system schedule <paramref name="systemKey"/> deletes with: its default steps
/// (<see cref="SystemSchedules"/>), <c>audit</c> for <see cref="AuditCleanup"/>; none for another key.
/// </summary>
public IReadOnlyList<string> AgedSteps(string? systemKey) =>
SystemSchedules.FirstOrDefault(s => s.SystemKey == systemKey)?.Parameters?.Steps ?? [];
/// <summary>
/// The zone of schedule times: the process's local zone (TZ in a container), by its IANA id where the platform maps it
/// (the admin panel formats times with it); UTC, with a warning, when TZ names a zone this system does not know (no
/// tzdata in the image).
/// </summary>
public static TimeZoneInfo ResolveTimeZone(string? tz, ILogger logger)
{
ArgumentNullException.ThrowIfNull(logger);
var name = tz?.Trim().TrimStart(':');
// TZ may also be a path to a zone file, which the runtime reads itself.
if (!string.IsNullOrEmpty(name) && !Path.IsPathRooted(name) && !OperatingSystem.IsWindows() && !TimeZoneInfo.TryFindSystemTimeZoneById(name, out _))
{
logger.LogWarning("TZ is {Zone}, a time zone this system does not know (is tzdata installed?): schedules run in UTC", name);
return TimeZoneInfo.Utc;
}
var local = TimeZoneInfo.Local;
if (!local.HasIanaId && TimeZoneInfo.TryConvertWindowsIdToIanaId(local.Id, out var iana) && TimeZoneInfo.TryFindSystemTimeZoneById(iana, out var zone))
return zone;
return local;
}
}