fix(server): show the audit clean-up's real age limit and lock it before the first pass

Settings › Logs › Keep audit showed ServerOptions.AuditRetentionDays, a second
copy of the audit clean-up schedule's age limit. Edits made on Jobs › Scheduled
never reached it, so the panel could say "kept forever" while entries were
being deleted every night. Saving 0 there then changed nothing, because the
endpoint only compared against the stale option value.

- GET and PUT /server/settings now report the schedule's limit in force (0
  while the schedule is off). Saving compares against that value. A value sent
  back unchanged leaves the server.json reset default and the env lock alone. A
  new value sets the schedule and becomes the reset default.
- ApplyAgeAsync also turns the schedule on when it already holds the days but
  is off.
- CHRONOS_AUDIT_RETENTION_DAYS is now applied before the scheduler's first
  pass, through a new Scheduler.StartAsync overload with a beforeFirstPass hook.
  Before, a missed 04:30 run was caught up at start with the stale days, which
  could delete entries the variable says to keep. While the variable fixes a
  limit above 0, turning the schedule off is a 409 setting_locked.
- Corrected the comments in SchedulerHost, ServerOptions, ServerSettingsStore,
  LogSettingsDto, the header of settings.js and ARCHITECTURE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 490ed286e9f32745174b13b1963d6ec91955196b)
This commit is contained in:
Alby96 committed 2026-10-27 09:56:46 +01:00
1 parent ac121acf7c
commit 422f33d5f3
12 files changed
+232 -52

No files matched your search

@@ -1,10 +1,10 @@
// Settings (BRIEF §14.8): server name, ports, TLS, discovery, jobs, limits, language, retention, logs. Values fixed by
// environment variables are read-only here; ports, TLS and chunk size apply at the next restart. How long job history is
// kept is a parameter of the Job history clean-up schedule (Jobs › Scheduled, owner review 2, R10); the audit retention
// saved here is the Audit log clean-up schedule's age limit. Jobs run one at a time (owner review 1): the parallelism
// (photos at once) and the priority queue apply at once, as do the log levels, retention, size limits and rotation
// (owner review 2, R11). About (version, API, database, uptime) is the last group, read-only (owner review 2); #/about
// opens here on it.
// kept is a parameter of the Job history clean-up schedule (Jobs › Scheduled, owner review 2, R10); Keep audit shows the
// Audit log clean-up schedule's age limit (0 while it is off), and saving a new one sets it. Jobs run one at a time
// (owner review 1): the parallelism (photos at once) and the priority queue apply at once, as do the log levels,
// retention, size limits and rotation (owner review 2, R11). About (version, API, database, uptime) is the last group,
// read-only (owner review 2); #/about opens here on it.
import { t, applyStrings, languages } from "../i18n.js";
import { escapeHtml, attr, toast, errorText, nativeName, fingerprint, formatDuration, markInvalid, clearInvalid, invalidText, escapeReverts, routeParams, PROXY_WARNING } from "../ui.js";
import { kindLabel } from "../jobs.js";
+25 -5
View File
@@ -19,8 +19,8 @@ public static class AdminEndpoints
public static void Map(RouteGroupBuilder api)
{
api.MapGet("/server/dashboard", DashboardAsync).Requires(Permissions.ManageArchive | Permissions.ManageUsers);
api.MapGet("/server/settings", (HttpContext context, ServerSettingsStore store, ServerOptions options) =>
Results.Json(store.Current() with { ProxyWarning = AdminPanel.BypassesProxy(context, options) }, ProtocolJson.Default.ServerSettingsDto))
api.MapGet("/server/settings", async (HttpContext context, ServerSettingsStore store, ServerOptions options, SchedulerHost schedules) =>
Results.Json(await SettingsAsync(context, store, options, schedules), ProtocolJson.Default.ServerSettingsDto))
.Requires(Permissions.ManageArchive);
api.MapPut("/server/settings", SaveSettingsAsync).Requires(Permissions.ManageArchive);
api.MapGet("/audit", AuditAsync).Requires(Permissions.ManageUsers | Permissions.ManageArchive);
@@ -76,7 +76,15 @@ public static class AdminEndpoints
private static async Task<IResult> SaveSettingsAsync(HttpContext context, Caller caller, ServerSettingsDto request, ServerSettingsStore store, ServerOptions options,
AuditLog audit, JobEngineHost jobs, SchedulerHost schedules)
{
var auditDays = options.AuditRetentionDays;
// Keep audit shows the audit clean-up schedule's age limit (SettingsAsync): sent back as shown it is no change, so
// the default stored in server.json (and an environment variable's lock) is left alone.
var shown = await schedules.AuditRetentionAsync(context.RequestAborted) ?? options.AuditRetentionDays;
int? auditDays = null;
if (request.Logs is { } logs)
{
if (logs.AuditRetentionDays != shown) auditDays = logs.AuditRetentionDays;
else request = request with { Logs = logs with { AuditRetentionDays = options.AuditRetentionDays } };
}
switch (store.Save(request))
{
case ("setting_locked", var setting):
@@ -87,9 +95,21 @@ 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);
if (auditDays is { } days) await schedules.ApplyAuditRetentionAsync(days, 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);
return Results.Json(await SettingsAsync(context, store, options, schedules), ProtocolJson.Default.ServerSettingsDto);
}
/// <summary>
/// The settings as the panel shows them. Keep audit is the audit retention in force, the audit clean-up schedule's age
/// limit (0 while it is off), wherever it was last set; <see cref="ServerOptions.AuditRetentionDays"/> is only what the
/// schedule is reset to (owner review 2, R10, R11).
/// </summary>
private static async Task<ServerSettingsDto> SettingsAsync(HttpContext context, ServerSettingsStore store, ServerOptions options, SchedulerHost schedules)
{
var settings = store.Current();
var audit = await schedules.AuditRetentionAsync(context.RequestAborted) ?? settings.Logs.AuditRetentionDays;
return settings with { Logs = settings.Logs with { AuditRetentionDays = audit }, ProxyWarning = AdminPanel.BypassesProxy(context, options) };
}
/// <summary>The audit log, newest first; <c>action</c> may list several actions separated by commas (<c>login,login_failed</c>).</summary>
+7 -5
View File
@@ -13,8 +13,8 @@ namespace Chronos.Server.Api;
/// delete (409 <c>schedule_system</c> for a system schedule), run now (409 <c>schedule_pending</c> while its last job is
/// queued, running or paused), reset a system schedule (409 <c>schedule_no_defaults</c> otherwise) and the jobs a schedule
/// queued, newest first. An invalid field is 400 <c>invalid_schedule</c> with its name as details (<c>name</c>,
/// <c>recurrence</c>, <c>parameters.percent</c>…); an age limit an environment variable fixes is 409 <c>setting_locked</c>.
/// Every change is audited.
/// <c>recurrence</c>, <c>parameters.percent</c>…); changing an age limit an environment variable fixes, or turning its
/// schedule off, is 409 <c>setting_locked</c>. Every change is audited.
/// </summary>
public static class ScheduleEndpoints
{
@@ -49,9 +49,11 @@ public static class ScheduleEndpoints
{
var ct = context.RequestAborted;
if (await host.Scheduler.GetAsync(id, ct) is not { } current) return ApiErrors.NotFound(context, "schedule");
// Parameters are replaced as a whole: a missing age limit would fall back to the action's default.
if (host.Host.LockedAgeOf(current.SystemKey) is { } locked && request.Parameters is { } parameters
&& ScheduleActions.Normalize(current.Action, parameters).OlderThanDays != locked.Days)
// Parameters are replaced as a whole: a missing age limit would fall back to the action's default. Turning off a
// schedule whose limit is fixed would stop the deletions the variable asks for.
if (host.Host.LockedAgeOf(current.SystemKey) is { } locked
&& ((request.Parameters is { } parameters && ScheduleActions.Normalize(current.Action, parameters).OlderThanDays != locked.Days)
|| (locked.Days > 0 && request.Enabled == false)))
return ApiErrors.Conflict(context, "setting_locked", locked.Setting);
var result = await host.Scheduler.UpdateAsync(id, request, ct);
if (result.NotFound) return ApiErrors.NotFound(context, "schedule");
@@ -221,10 +221,11 @@ public sealed class ServerOptions
public const int MaxAuditRetentionDays = ScheduleActions.MaxDays;
/// <summary>
/// Days of audit log the <c>audit-cleanup</c> system schedule keeps (owner review 2, R10, R11); 0, the default, keeps
/// it all. It is that schedule's age limit: saving it in Settings › Logs sets the schedule's parameter, and Reset
/// goes back to it. Set by <c>CHRONOS_AUDIT_RETENTION_DAYS</c>, it is applied to the schedule at every start and cannot
/// be changed in the panel or on the schedule.
/// Days of audit log the <c>audit-cleanup</c> system schedule keeps when it is created or reset (owner review 2, R10,
/// R11); 0, the default, keeps it all, the schedule off. Afterwards the schedule's own age limit applies: Settings › Logs
/// shows it (0 while the schedule is off), and saving a new one there sets the schedule and stores it here too. Set by
/// <c>CHRONOS_AUDIT_RETENTION_DAYS</c>, it is applied to the schedule at every start, before any run, and cannot be
/// changed in the panel or on the schedule.
/// </summary>
public int AuditRetentionDays { get; set; }
@@ -15,9 +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. 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>).
/// schedule is reset to (owner review 2, R10): the schedule's own value applies. The audit retention kept here is what the
/// audit clean-up schedule is reset to; the endpoint shows that schedule's age limit in its place and puts a new one there
/// (<c>SchedulerHost.AuditRetentionAsync</c>, <c>SchedulerHost.ApplyAuditRetentionAsync</c>).
/// </summary>
public sealed class ServerSettingsStore(ServerOptions options, ServerLogging logging)
{
+26 -13
View File
@@ -1,3 +1,4 @@
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Scheduling;
using Chronos.Protocol;
@@ -8,11 +9,14 @@ 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
/// 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). The audit retention saved in Settings › Logs becomes the audit
/// clean-up's age limit (<see cref="ApplyAuditRetentionAsync"/>).
/// (<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). The audit retention in force is
/// the audit clean-up schedule's age limit, 0 while it is off: 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.
/// </summary>
public sealed class SchedulerHost : IHostedService
{
@@ -38,8 +42,7 @@ public sealed class SchedulerHost : IHostedService
public async Task StartAsync(CancellationToken cancellationToken)
{
var started = Scheduler.Options.Time.GetUtcNow();
await Scheduler.StartAsync(Host, cancellationToken);
await ApplyLockedAgesAsync(cancellationToken);
await Scheduler.StartAsync(Host, ApplyLockedAgesAsync, cancellationToken);
var stopping = _stopping.Token;
_startScan = Task.Run(() => ScanAtStartAsync(started, stopping), CancellationToken.None);
}
@@ -54,14 +57,23 @@ public sealed class SchedulerHost : IHostedService
}
/// <summary>
/// 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.
/// The audit retention in force (owner review 2, R10, R11): the audit clean-up schedule's age limit, 0 while the schedule
/// is off (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, off at 0, which keeps everything.
/// </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>
/// <summary>The age limit of a system schedule that deletes by age, 0 while it is off.</summary>
private static int InForce(Schedule row) => row.Enabled ? ScheduleMapping.Parameters(row).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)
@@ -72,13 +84,14 @@ public sealed class SchedulerHost : IHostedService
/// <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.
/// has a limit now and disabling it at 0; nothing when it already holds the value 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);
if (parameters.OlderThanDays == days) return;
if (parameters.OlderThanDays == days && row.Enabled == (days > 0)) 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);