fix: one audit retention, scans at start, live deep analysis and a 6-hour upload sweep

Settle what the R10 scheduler and R11 log packages left open when they were
integrated (owner review 2, phase 2).

- Audit retention has one source of truth, the audit-cleanup schedule's age
  limit. AuditRetentionDays defaults to 0 (the audit log is kept forever, so
  an upgrade deletes nothing; the schedule is seeded off) and accepts 0-3650,
  what a schedule's age limit takes. Saving Settings › Logs › Keep audit sets
  the schedule's limit (on with a limit, off at 0) without a restart;
  CHRONOS_AUDIT_RETENTION_DAYS locks it and Reset goes back to it.
- Both hosts scan right after start again, as their polling did: the server
  after the scheduler starts, the desktop once the archive was reopened and
  again when an unplugged one is back. Scheduler.RunSystemNowAsync runs the
  archive-scan schedule when it is enabled and has not run since the start,
  and skips while its scan is pending.
- Desktop scans follow Settings › Analysis › After a scan at every run: a scan
  schedule without its own deep parameter asks the host
  (IScheduleHost.DeepAnalysisAfterScan), the archive-scan schedule no longer
  freezes the setting, and the editor offers deep only for analyses, so the
  setting's tooltip stays true.
- The server's upload clean-up runs every 6 hours instead of every 30
  minutes, to keep the job history readable; idle uploads still expire after
  UploadRetentionHours.
- The Unraid template and docker-compose leave CHRONOS_LOG_LEVEL empty or
  commented out, and say that setting it locks both log levels, so the admin
  panel can change them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-10-27 02:51:04 +01:00
1 parent bc786c12c4
commit 8d66be709c
21 files changed
+299 -53

No files matched your search

+29 -5
View File
@@ -288,10 +288,11 @@ public sealed class AppServices : IAsyncDisposable
/// <summary>
/// At start, off the UI thread: reopens the archive at Settings › Archive's folder (a moved one relinked, interrupted
/// renames finished), then starts the schedules, whose first pass settles the runs missed while Chronos was closed. An
/// archive whose archive.json is not there (an unplugged drive) is looked for every <see cref="ReopenInterval"/> until
/// it is back, then the schedules look at once for a due run; unless the folder changed meanwhile: whatever changed it
/// opened the new archive. The app's exit waits for this on the UI thread.
/// renames finished), then starts the schedules, whose first pass settles the runs missed while Chronos was closed, and
/// runs the archive scan once, as the rescans did at start (<see cref="ScanNowAsync"/>). An archive whose archive.json is
/// not there (an unplugged drive) is looked for every <see cref="ReopenInterval"/> until it is back, then scanned and the
/// schedules look at once for a due run; unless the folder changed meanwhile: whatever changed it opened the new
/// archive. The app's exit waits for this on the UI thread.
/// </summary>
private async Task RunSchedulesAsync(CancellationToken ct)
{
@@ -299,13 +300,19 @@ public sealed class AppServices : IAsyncDisposable
try
{
if (reopen is not null && await ReopenAsync(reopen, ct).ConfigureAwait(false)) reopen = null;
var started = SchedulerTime.GetUtcNow();
await StartSchedulerAsync(ct).ConfigureAwait(false);
if (reopen is null) return;
if (reopen is null)
{
await ScanNowAsync(started, ct).ConfigureAwait(false);
return;
}
using var timer = new PeriodicTimer(ReopenInterval);
while (await timer.WaitForNextTickAsync(ct).ConfigureAwait(false))
{
if (!string.Equals(reopen, Settings.LastArchivePath, StringComparison.OrdinalIgnoreCase)) return;
if (!await ReopenAsync(reopen, ct).ConfigureAwait(false)) continue;
await ScanNowAsync(null, ct).ConfigureAwait(false);
Scheduler?.Wake();
return;
}
@@ -324,6 +331,23 @@ public sealed class AppServices : IAsyncDisposable
}
}
/// <summary>
/// Runs the archive scan schedule once now when it is enabled (owner review 2, R10: the archive was opened or is back),
/// unless it ran since <paramref name="since"/> (the first pass fired it) or its scan is still pending.
/// </summary>
private async Task ScanNowAsync(DateTimeOffset? since, CancellationToken ct)
{
if (Scheduler is not { } scheduler) return;
try
{
await scheduler.RunSystemNowAsync(DesktopScheduleHost.ArchiveScan, since, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is DatabaseException or IOException or InvalidOperationException)
{
Log.Warning("schedules", "The archive scan could not be run now; its schedule runs the next one", ex);
}
}
/// <summary>
/// Starts <see cref="Scheduler"/> on this PC's engine: it seeds the system schedules and runs its first pass before
/// <see cref="SchedulerReady"/> turns true. Without an engine, or when the schedules cannot be read, there is none.
+6 -2
View File
@@ -21,7 +21,8 @@ namespace Chronos.App.Jobs;
/// drive). The system schedules stand for the timers the desktop used to run out of sight: the archive scan (its interval
/// carried over from the former Settings › Archive › Rescan every, <see cref="AppSettings.ScanIntervalMinutes"/>, once:
/// a row that exists keeps the user's edits), the daily index backup, and the housekeeping clean-up at 04:00 (job history,
/// cache trim). Thread-safe: the scheduler calls it from its loop.
/// cache trim). Scans give what they find a deep analysis as Settings › Analysis › After a scan says at each run
/// (<see cref="DeepAnalysisAfterScan"/>), like the scans started by hand. Thread-safe: the scheduler calls it from its loop.
/// </summary>
public sealed class DesktopScheduleHost(AppSettings settings, Func<ChronosDatabase?> database, Func<ArchiveService?> archives) : IScheduleHost
{
@@ -43,7 +44,7 @@ public sealed class DesktopScheduleHost(AppSettings settings, Func<ChronosDataba
public IReadOnlyList<SystemSchedule> SystemSchedules =>
[
new(ArchiveScan, "Archive scan", ScheduleActions.Scan, ScheduleRecurrence.Interval(ScanMinutes(settings), RecurrenceUnit.Minutes),
new ScheduleParametersDto(Force: false, Deep: settings.DeepAnalysisAfterScan), CatchUp: false),
new ScheduleParametersDto(Force: false), CatchUp: false),
new(IndexBackup, "Index backup", ScheduleActions.Backup, ScheduleRecurrence.Interval(1, RecurrenceUnit.Days),
new ScheduleParametersDto(Keep: DatabaseBackups.Keep)),
new(Housekeeping, "Housekeeping", ScheduleActions.Cleanup, ScheduleRecurrence.DailyAt(HousekeepingTime),
@@ -83,6 +84,9 @@ public sealed class DesktopScheduleHost(AppSettings settings, Func<ChronosDataba
/// <summary>The desktop runs every action its engine has a handler for.</summary>
public string? Unavailable(string action) => null;
/// <summary>Settings › Analysis › After a scan, read at every run: a scheduled scan follows it as a scan started by hand does.</summary>
public bool DeepAnalysisAfterScan => settings.DeepAnalysisAfterScan;
}
/// <summary>
@@ -268,7 +268,8 @@ public sealed class ScheduleEditorViewModel : LocalizedViewModel
// ---------------- Parameters ----------------
public bool ShowsForce => _action.Name is ScheduleActions.Scan or ScheduleActions.Thumbnails or ScheduleActions.Proxies;
public bool ShowsDeep => _action.Name is ScheduleActions.Scan or ScheduleActions.Analysis;
/// <summary>Analysis only: a scan's deep analysis follows Settings › Analysis › After a scan at every run.</summary>
public bool ShowsDeep => _action.Name == ScheduleActions.Analysis;
public bool ShowsOlderThan => _action.Name is ScheduleActions.Verify or ScheduleActions.Cleanup;
public bool ShowsPercent => _action.Name == ScheduleActions.Verify;
public bool ShowsDryRun => _action.Name == ScheduleActions.Maintenance;
@@ -294,7 +295,7 @@ public sealed class ScheduleEditorViewModel : LocalizedViewModel
set => Set(ref _deep, value);
}
public string DeepToolTip => Loc.L(_action.Name == ScheduleActions.Scan ? "Tooltips.Jobs.Editor.DeepAfterScan" : "Tooltips.Jobs.Editor.DeepAnalysis");
public string DeepToolTip => Loc.L("Tooltips.Jobs.Editor.DeepAnalysis");
public bool DryRun
{
@@ -29,6 +29,12 @@ public interface IScheduleHost
/// <summary>The names of the clean-up steps this host's <see cref="JobKind.Cleanup"/> jobs run (normally those of <c>ArchiveService.CleanupSteps</c>).</summary>
IReadOnlyList<string> CleanupSteps { get; }
/// <summary>
/// Whether a scan whose schedule leaves its <c>deep</c> parameter unset gives the sequences it finds a deep analysis.
/// Read at every run, so the desktop's scans follow Settings › Analysis › After a scan as it is then; false on the server.
/// </summary>
bool DeepAnalysisAfterScan { get; }
/// <summary>
/// Why this host does not run <paramref name="action"/> (a short code, e.g. <c>not-here</c>), or null when it may. Asked
/// before the scheduler's own checks (<see cref="ScheduleUnavailable"/>), for the action list and at every run.
@@ -36,7 +36,10 @@ public sealed record ScheduleActionContext(ChronosDatabase Database, IScheduleHo
/// </summary>
public static class ScheduleActions
{
/// <summary>Incremental scan of the archive (<c>force</c>: a full one; <c>deep</c>: deep analysis of what it indexes).</summary>
/// <summary>
/// Incremental scan of the archive (<c>force</c>: a full one; <c>deep</c>: deep analysis of what it indexes; unset, as the
/// host says at the run, <see cref="IScheduleHost.DeepAnalysisAfterScan"/>).
/// </summary>
public const string Scan = "scan";
/// <summary>Integrity check of the originals, the least recently verified first (<c>olderThanDays</c>, <c>percent</c>).</summary>
@@ -96,7 +99,8 @@ public static class ScheduleActions
/// <summary>The parameters a new schedule of <paramref name="action"/> starts with.</summary>
public static ScheduleParametersDto Defaults(string action) => action switch
{
Scan => new(Force: false, Deep: false),
// No deep: a scan follows the host's choice at run time (IScheduleHost.DeepAnalysisAfterScan) unless its schedule sets one.
Scan => new(Force: false),
Verify => new(OlderThanDays: 30, Percent: 100),
Thumbnails or Proxies => new(Force: false),
Analysis => new(Deep: false),
@@ -116,7 +120,7 @@ public static class ScheduleActions
var d = Defaults(action);
return action switch
{
Scan => new(Force: p.Force ?? d.Force, Deep: p.Deep ?? d.Deep),
Scan => new(Force: p.Force ?? d.Force, Deep: p.Deep),
Verify => new(OlderThanDays: p.OlderThanDays ?? d.OlderThanDays, Percent: p.Percent ?? d.Percent),
Thumbnails or Proxies => new(Force: p.Force ?? d.Force),
Analysis => new(Deep: p.Deep ?? d.Deep),
@@ -189,7 +193,7 @@ public static class ScheduleActions
{
case Scan:
return await PendingAsync(db, [JobKind.Scan, JobKind.Rebuild], archive, cancellationToken).ConfigureAwait(false)
?? ScheduleResolution.Queue([ArchiveJobs.Scan(archive, full: p.Force == true, deepAnalysis: p.Deep == true)]);
?? ScheduleResolution.Queue([ArchiveJobs.Scan(archive, full: p.Force == true, deepAnalysis: p.Deep ?? context.Host.DeepAnalysisAfterScan)]);
case Verify:
return await PendingAsync(db, [JobKind.Verify], archive, cancellationToken).ConfigureAwait(false)
?? await VerifyAsync(context, archive, p, cancellationToken).ConfigureAwait(false);
+13
View File
@@ -158,6 +158,19 @@ public sealed class Scheduler : IAsyncDisposable
return new ScheduleRunDto(dto, fire.Outcome, fire.JobId);
}
/// <summary>
/// Runs the system schedule <paramref name="systemKey"/> now (<see cref="RunNowAsync"/>, which skips while its work is
/// pending) when it is enabled and has not run since <paramref name="since"/>; null when it did not run. The hosts' archive
/// scan once at start, as their polling did, and on the desktop when its archive is opened again (owner review 2, R10).
/// </summary>
public async Task<ScheduleRunDto?> RunSystemNowAsync(string systemKey, DateTimeOffset? since = null, CancellationToken cancellationToken = default)
{
_ = RequireHost();
if (await _db.Schedules.GetBySystemKeyAsync(systemKey, cancellationToken).ConfigureAwait(false) is not { Enabled: true } schedule
|| schedule.LastRun >= since) return null;
return await RunNowAsync(schedule.Id, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>The schedules (system ones first), the actions with their availability here, the host's time zone and clean-up steps.</summary>
public async Task<SchedulesDto> ListAsync(CancellationToken cancellationToken = default)
{
+4 -1
View File
@@ -74,8 +74,9 @@ public static class AdminEndpoints
}
private static async Task<IResult> SaveSettingsAsync(HttpContext context, Caller caller, ServerSettingsDto request, ServerSettingsStore store, ServerOptions options,
AuditLog audit, JobEngineHost jobs)
AuditLog audit, JobEngineHost jobs, SchedulerHost schedules)
{
var auditDays = options.AuditRetentionDays;
switch (store.Save(request))
{
case ("setting_locked", var setting):
@@ -85,6 +86,8 @@ public static class AdminEndpoints
}
// A priority queue turned on, or a level raised, may make the running job yield at once.
jobs.Engine.Wake();
// The audit retention is the audit clean-up schedule's age limit: a new one goes there (owner review 2, R10, R11).
if (options.AuditRetentionDays != auditDays) await schedules.ApplyAuditRetentionAsync(options.AuditRetentionDays, context.RequestAborted);
await audit.WriteAsync(caller, context, "server_settings", "server", null, request.ServerName);
return Results.Json(store.Current() with { ProxyWarning = AdminPanel.BypassesProxy(context, options) }, ProtocolJson.Default.ServerSettingsDto);
}
@@ -15,7 +15,9 @@ namespace Chronos.Server.Configuration;
/// edited keys; secrets and environment values are never written) and applies what can change while running, the
/// parallelism and the priority queue included (owner review 1), and the log settings through <see cref="ServerLogging"/>
/// (owner review 2, R11); ports, TLS and chunk size wait for a restart. Job history is what the housekeeping system
/// schedule is reset to (owner review 2, R10): the schedule's own value applies.
/// schedule is reset to (owner review 2, R10): the schedule's own value applies. The audit retention is what the audit
/// clean-up schedule is reset to, and saving a new one also sets that schedule's age limit (the endpoint does it through
/// <c>SchedulerHost.ApplyAuditRetentionAsync</c>).
/// </summary>
public sealed class ServerSettingsStore(ServerOptions options, ServerLogging logging)
{
+27 -13
View File
@@ -1,6 +1,7 @@
using Chronos.Data;
using Chronos.Data.Scheduling;
using Chronos.Protocol;
using Chronos.Server.Configuration;
namespace Chronos.Server.Jobs;
@@ -10,7 +11,8 @@ namespace Chronos.Server.Jobs;
/// it seeds the system schedules and settles missed runs (<see cref="Scheduler.StartAsync"/>), applies the age limits that
/// environment variables fix (<see cref="ServerScheduleHost.LockedAgeOf"/>), and 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).
/// interval (only while that schedule is enabled). The audit retention saved in Settings › Logs becomes the audit
/// clean-up's age limit (<see cref="ApplyAuditRetentionAsync"/>).
/// </summary>
public sealed class SchedulerHost : IHostedService
{
@@ -52,31 +54,43 @@ public sealed class SchedulerHost : IHostedService
}
/// <summary>
/// Puts the age limits environment variables fix into their system schedules (also enabling one that has a limit now,
/// or disabling it at 0, which keeps everything); a schedule already holding the value is left as the user set it.
/// Puts the audit retention just saved in Settings › Logs (<see cref="ServerOptions.AuditRetentionDays"/>) into the
/// audit clean-up schedule, its one source of truth (owner review 2, R10, R11): enabled with a limit, off at 0, which
/// keeps everything. A schedule already holding the value is left as the user set it.
/// </summary>
public Task ApplyAuditRetentionAsync(int days, CancellationToken cancellationToken = default) =>
ApplyAgeAsync(ServerScheduleHost.AuditCleanup, days, "Settings › Logs", cancellationToken);
/// <summary>The age limits environment variables fix, put into their system schedules at every start.</summary>
private async Task ApplyLockedAgesAsync(CancellationToken cancellationToken)
{
foreach (var system in Host.SystemSchedules)
{
if (Host.LockedAgeOf(system.SystemKey) is not { } locked) continue;
if (await _db.Schedules.GetBySystemKeyAsync(system.SystemKey, cancellationToken) is not { } row) continue;
var parameters = ScheduleMapping.Parameters(row);
if (parameters.OlderThanDays == locked.Days) continue;
var result = await Scheduler.UpdateAsync(row.Id, new UpdateScheduleRequest(Parameters: parameters with { OlderThanDays = locked.Days }, Enabled: locked.Days > 0),
cancellationToken);
if (result.Problem is { } problem) _logger.LogWarning("{Variable} could not be applied to the {Schedule} schedule ({Problem})", locked.Variable, row.Name, problem);
else _logger.LogInformation("{Variable} sets the {Schedule} schedule to {Days} day(s)", locked.Variable, row.Name, locked.Days);
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; nothing when it already holds the value.
/// </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);
if (parameters.OlderThanDays == days) return;
var result = await Scheduler.UpdateAsync(row.Id, new UpdateScheduleRequest(Parameters: parameters with { OlderThanDays = days }, 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
{
if (await _db.Schedules.GetBySystemKeyAsync(ServerScheduleHost.ArchiveScan, cancellationToken) is not { Enabled: true } scan || scan.LastRun >= started) return;
await Scheduler.RunNowAsync(scan.Id, null, cancellationToken);
await Scheduler.RunSystemNowAsync(ServerScheduleHost.ArchiveScan, started, cancellationToken);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
+10 -4
View File
@@ -16,7 +16,7 @@ public sealed record LockedAge(string Setting, string Variable, int Days);
/// 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 (refreshed at every run, 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 30 minutes, the nightly copy of an SQLite index,
/// 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>
@@ -31,8 +31,11 @@ public sealed class ServerScheduleHost : IScheduleHost
/// <summary>Minutes between two archive scans (the desktop's rhythm, as the polling had).</summary>
public const int ScanMinutes = 10;
/// <summary>Minutes between two sweeps of abandoned uploads (as the upload maintenance had).</summary>
public const int UploadSweepMinutes = 30;
/// <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;
@@ -67,7 +70,7 @@ public sealed class ServerScheduleHost : IScheduleHost
{
// 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(UploadSweepMinutes, RecurrenceUnit.Minutes),
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.
@@ -107,6 +110,9 @@ public sealed class ServerScheduleHost : IScheduleHost
/// <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.