feat: owner review 2 phase 2: scheduled jobs and log settings (#10)
CI / Build and test (push) Successful in 7m0s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 13m28s
CI / PostgreSQL 16 integration (push) Successful in 5m52s
CI / PostgreSQL 17 integration (push) Successful in 4m50s
CI / Docker image (push) Successful in 1m4s
Release / Server image (push) Successful in 1m35s

- Jobs > Scheduled on the desktop and the admin panel. Every timer that queued work is now a visible system schedule: archive scan, upload clean-up, index backup, job-history and audit clean-ups, desktop housekeeping. New actions: verify, thumbnails, proxies, analysis, maintenance, backup, clean-ups, reports.
- The scheduler: migration 0007, in-house recurrence, compare-and-set claim, catch-up, scan at start.
- Log settings: levels, retention, size parts, total limit, daily or hourly rotation, audit retention, diagnostics share; the server writes Debug/Trace to its files again; logging never fails a job.

Upgrade: CHRONOS_LOG_LEVEL set in an existing container locks both levels; migration 0007 is one-way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #10.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-10-27 11:19:26 +01:00
1 parent 1f089888e8
commit af9eeaab9b
349 files changed
+28341 -1304

No files matched your search

-1
View File
@@ -40,7 +40,6 @@ public sealed class JobEngineHost : IHostedService
{
WorkerId = WorkerId,
Kinds = _kinds,
HistoryRetention = TimeSpan.FromDays(options.JobHistoryDays),
PriorityQueue = () => ServerSettingsStore.PriorityQueue(options),
});
Engine.JobChanged += OnJobChanged;
+168
View File
@@ -0,0 +1,168 @@
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"/>.
/// </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 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.
Scheduler.ScheduleChanged += schedule => events.Publish(new ScheduleChangedEvent(schedule.Id, Deleted: false));
Scheduler.ScheduleDeleted += id => events.Publish(new ScheduleChangedEvent(id, Deleted: true));
}
public Scheduler Scheduler { get; }
public ServerScheduleHost Host { get; }
public async Task StartAsync(CancellationToken cancellationToken)
{
var started = Scheduler.Options.Time.GetUtcNow();
await Scheduler.StartAsync(Host, ApplyLockedAgesAsync, cancellationToken);
var stopping = _stopping.Token;
_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;
await Scheduler.DisposeAsync();
_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)
{
}
}
}
}
@@ -0,0 +1,154 @@
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), Audit: new TimeOnly(4, 30));
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),
new(UploadCleanup, "Upload clean-up", ScheduleActions.Cleanup, ScheduleRecurrence.Interval(UploadSweepHours, RecurrenceUnit.Hours),
new ScheduleParametersDto(OlderThanDays: UploadMaintenance.FinishedRetentionDays, Steps: [UploadCleanupStep.StepName])),
};
// 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])));
var audit = _options.AuditRetentionDays;
list.Add(new(AuditCleanup, "Audit log clean-up", ScheduleActions.Cleanup, ScheduleRecurrence.DailyAt(nightly.Audit),
new ScheduleParametersDto(OlderThanDays: audit, Steps: [Chronos.Data.Housekeeping.CleanupSteps.Audit]), Enabled: audit > 0));
return list;
}
}
/// <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;
}
}