fix(server): a locked audit retention also fixes the audit step and the switch

The audit retention in force ignored the audit clean-up's steps: with the
audit step unticked nothing was deleted, yet Settings › Logs still showed the
age limit. It is now 0 without that step, and setting a limit (Settings › Logs
or CHRONOS_AUDIT_RETENTION_DAYS at start) ticks the step again, so a saved or
fixed retention always takes effect. While the variable fixes a limit above 0,
an edit that drops the step is 409 setting_locked like turning the schedule off.

The admin panel's Scheduled tab disables what the variable fixes (the row's
switch, the form's Enabled and audit step, the age limit) with the locked
tooltip, and points a setting_locked refusal at the field actually refused.

The Copies kept tooltips now say the backups folder keeps as many copies as
the backup schedule that keeps the most; the LastDone and Newest comments
state the real first-copy rule; Keep audit is documented last-writer-wins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-10-27 10:39:49 +01:00
1 parent 94a5466c9f
commit e6e69782ed
12 files changed
+125 -45

No files matched your search

+1 -1
View File
@@ -381,7 +381,7 @@
<data name="Admin.Schedules.Param.FullScan" xml:space="preserve"><value>Full scan</value></data>
<data name="Admin.Schedules.Param.FullScan.Tip" xml:space="preserve"><value>Read every file again instead of only those added or changed</value></data>
<data name="Admin.Schedules.Param.Keep" xml:space="preserve"><value>Copies kept</value></data>
<data name="Admin.Schedules.Param.Keep.Tip" xml:space="preserve"><value>How many copies of the index are kept; older ones are deleted</value></data>
<data name="Admin.Schedules.Param.Keep.Tip" xml:space="preserve"><value>Copies of the index to keep at least; the backup schedule that keeps the most, on or off, decides how many stay in the backups folder</value></data>
<data name="Admin.Schedules.Param.MakeAgain" xml:space="preserve"><value>Make again</value></data>
<data name="Admin.Schedules.Param.MakeAgain.Tip" xml:space="preserve"><value>Make them again for every sequence, also those that have them</value></data>
<data name="Admin.Schedules.Param.OlderDays" xml:space="preserve"><value>Older than (days)</value></data>
+1 -1
View File
@@ -342,7 +342,7 @@
<data name="Tooltips.Jobs.Editor.Enabled" xml:space="preserve"><value>Off, the schedule never runs by itself</value></data>
<data name="Tooltips.Jobs.Editor.Every" xml:space="preserve"><value>How many minutes (5 to 1,440), hours (1 to 168) or days (1 to 366)</value></data>
<data name="Tooltips.Jobs.Editor.FullScan" xml:space="preserve"><value>Reads every file again, not only those whose date or size changed</value></data>
<data name="Tooltips.Jobs.Editor.Keep" xml:space="preserve"><value>How many copies of the index are kept; older ones are deleted</value></data>
<data name="Tooltips.Jobs.Editor.Keep" xml:space="preserve"><value>Copies of the index to keep at least; the backup schedule that keeps the most, on or off, decides how many stay in the backups folder</value></data>
<data name="Tooltips.Jobs.Editor.KindDaily" xml:space="preserve"><value>Every day at a time</value></data>
<data name="Tooltips.Jobs.Editor.KindEvery" xml:space="preserve"><value>At a fixed interval: every n minutes, hours or days</value></data>
<data name="Tooltips.Jobs.Editor.KindMonthly" xml:space="preserve"><value>On one day of the month at a time</value></data>
+1 -1
View File
@@ -380,7 +380,7 @@
<data name="Admin.Schedules.Param.FullScan" xml:space="preserve"><value>Scansione completa</value></data>
<data name="Admin.Schedules.Param.FullScan.Tip" xml:space="preserve"><value>Rilegge ogni file invece di quelli aggiunti o modificati</value></data>
<data name="Admin.Schedules.Param.Keep" xml:space="preserve"><value>Copie conservate</value></data>
<data name="Admin.Schedules.Param.Keep.Tip" xml:space="preserve"><value>Quante copie dell'indice si conservano; le più vecchie vengono eliminate</value></data>
<data name="Admin.Schedules.Param.Keep.Tip" xml:space="preserve"><value>Numero minimo di copie dell'indice da conservare; quante ne restano nella cartella dei backup lo decide la pianificazione di copia che ne conserva di più, attiva o no</value></data>
<data name="Admin.Schedules.Param.MakeAgain" xml:space="preserve"><value>Ricrea</value></data>
<data name="Admin.Schedules.Param.MakeAgain.Tip" xml:space="preserve"><value>Le ricrea per ogni sequenza, anche per quelle che le hanno</value></data>
<data name="Admin.Schedules.Param.OlderDays" xml:space="preserve"><value>Più vecchi di (giorni)</value></data>
+1 -1
View File
@@ -341,7 +341,7 @@
<data name="Tooltips.Jobs.Editor.Enabled" xml:space="preserve"><value>Disattivata, la pianificazione non viene mai eseguita da sola</value></data>
<data name="Tooltips.Jobs.Editor.Every" xml:space="preserve"><value>Quanti minuti (da 5 a 1.440), ore (da 1 a 168) o giorni (da 1 a 366)</value></data>
<data name="Tooltips.Jobs.Editor.FullScan" xml:space="preserve"><value>Rilegge ogni file, non solo quelli con data o dimensione cambiate</value></data>
<data name="Tooltips.Jobs.Editor.Keep" xml:space="preserve"><value>Quante copie dell'indice vengono mantenute; le più vecchie vengono eliminate</value></data>
<data name="Tooltips.Jobs.Editor.Keep" xml:space="preserve"><value>Numero minimo di copie dell'indice da conservare; quante ne restano nella cartella delle copie lo decide la pianificazione di copia che ne conserva di più, attiva o no</value></data>
<data name="Tooltips.Jobs.Editor.KindDaily" xml:space="preserve"><value>Ogni giorno a un'ora</value></data>
<data name="Tooltips.Jobs.Editor.KindEvery" xml:space="preserve"><value>A intervallo fisso: ogni n minuti, ore o giorni</value></data>
<data name="Tooltips.Jobs.Editor.KindMonthly" xml:space="preserve"><value>In un giorno del mese a un'ora</value></data>
+3 -2
View File
@@ -82,8 +82,9 @@ public static partial class DatabaseBackups
/// <summary>
/// When the newest copy of <paramref name="db"/>'s index file in <paramref name="directory"/> (null: <see cref="DefaultDirectory"/>)
/// was made; null when there is none, the index has no file, or the folder cannot be read. The hosts seed their index
/// backup schedule with it (<see cref="Scheduling.SystemSchedule.LastDone"/>), so the first copy after an upgrade comes
/// as the former daily loop would have made it.
/// backup schedule with it (<see cref="Scheduling.SystemSchedule.LastDone"/>): the first copy after an upgrade is due at
/// once only when this one is at least a whole period of the schedule's recurrence old; otherwise, and with no copy, it
/// comes at the recurrence's first occurrence.
/// </summary>
public static DateTimeOffset? Newest(ChronosDatabase db, string? directory)
{
+3 -3
View File
@@ -46,9 +46,9 @@ public interface IScheduleHost
/// A host's system schedule: <paramref name="SystemKey"/> identifies it across starts (<c>archive-scan</c>,
/// <c>index-backup</c>, <c>housekeeping</c>…); the rest is what it is seeded with and reset to. <paramref name="Name"/> is
/// stored as given; clients show system schedules by their key in the user's language. <paramref name="LastDone"/> is when
/// the host last did this work before the schedule existed (the newest index copy, made by the timer the schedule
/// replaced): seeded a whole period or more later, the row is due at once, so the upgrade's first start does the work
/// as that timer would have; otherwise, and without it, the first run is the recurrence's first occurrence.
/// the host last did this work before the schedule existed (the newest index copy), read only when the row is seeded: an
/// enabled row seeded at least a whole period of its recurrence after it is due at once; otherwise, and without it, its
/// first run is the recurrence's first occurrence.
/// </summary>
public sealed record SystemSchedule(
string SystemKey,
+45 -13
View File
@@ -30,8 +30,11 @@ const PARAM_KEYS = {
"cleanup.steps": "Steps", "cleanup.olderThanDays": "OlderDays",
};
const NUMBERS = { olderThanDays: 'min="0" max="3650"', percent: 'min="1" max="100"', keep: 'min="1" max="100"' };
/** Settings an environment variable fixes for a system schedule's age limit (ServerScheduleHost.LockedAgeOf). */
const LOCKED_AGES = { "audit-cleanup": ["AuditRetentionDays", "CHRONOS_AUDIT_RETENTION_DAYS"] };
/**
* Settings an environment variable fixes for a system schedule's age limit (ServerScheduleHost.LockedAgeOf): the setting,
* its variable and the steps the limit deletes with (ServerScheduleHost.AgedSteps).
*/
const LOCKED_AGES = { "audit-cleanup": { setting: "AuditRetentionDays", variable: "CHRONOS_AUDIT_RETENTION_DAYS", steps: ["audit"] } };
/** A schedule's name: a system schedule's in the panel's language (by its key), a user's as typed. */
export function scheduleName(schedule) {
@@ -195,6 +198,17 @@ export async function renderSchedules(root, { api, setMeta, actions, onEvent },
return schedules.find((s) => s.id === id);
}
/**
* What an environment variable fixes on the system schedule <paramref name="systemKey"/> whose age limit is
* <paramref name="days"/> (LOCKED_AGES), with the attributes of its fixed controls; null when nothing is fixed. While the
* limit deletes (more than 0 days) its switch and the steps it deletes with are fixed too (ScheduleEndpoints.ChangesLocked).
*/
function ageLock(systemKey, days) {
const age = LOCKED_AGES[systemKey];
if (!age || !locked.some((l) => l.toLowerCase() === age.setting.toLowerCase())) return null;
return { ...age, deletes: days > 0, attrs: `disabled title="${attr(t("Admin.Settings.Locked.Tip", age.variable))}"` };
}
/** Closes a schedule's runs and drops them. */
function forget(id) {
expanded.delete(id);
@@ -206,6 +220,7 @@ export async function renderSchedules(root, { api, setMeta, actions, onEvent },
const button = (act, key, extra = "") => `<button class="btn small${extra}" data-act="${act}" data-i18n="Admin.Schedules.${key}" data-i18n-title="Admin.Schedules.${key}.Tip"></button>`;
const buttons = button("run", "Run") + button("edit", "Edit") + (s.systemKey ? button("reset", "Reset") : button("delete", "Delete", " destructive"));
const when = recurrenceText(s.recurrence);
const lock = ageLock(s.systemKey, s.parameters?.olderThanDays ?? 0);
return `
<div class="row${s.enabled ? "" : " dim"}" role="row" data-key="${attr(s.id)}">
<span class="name-cell" role="cell"><button class="link ellipsis" data-toggle="${attr(s.id)}" aria-expanded="${expanded.has(s.id)}" aria-controls="runs-${attr(s.id)}"
@@ -216,7 +231,7 @@ export async function renderSchedules(root, { api, setMeta, actions, onEvent },
<span class="num nowrap" role="cell" title="${attr(t("Admin.Schedules.NextRun.Tip", zone))}">${escapeHtml(s.enabled ? zonedTime(s.nextRun, zone) : t("Admin.Schedules.Off"))}</span>
<span class="col-last ellipsis" role="cell">${lastResult(s)}</span>
<span role="cell"><input type="checkbox" role="switch" data-enable="${attr(s.id)}" ${s.enabled ? "checked" : ""}
aria-label="${attr(t("Admin.Schedules.EnabledFor", name))}" title="${attr(t("Admin.Schedules.Enabled.Tip"))}"></span>
aria-label="${attr(t("Admin.Schedules.EnabledFor", name))}" ${lock?.deletes ? lock.attrs : `title="${attr(t("Admin.Schedules.Enabled.Tip"))}"`}></span>
<span class="row-actions" role="cell">${buttons}</span>
</div>
${expanded.has(s.id) ? `<div class="row log-row" role="row"><div class="wide" role="cell" id="runs-${attr(s.id)}">${runsHtml(s)}</div></div>` : ""}`;
@@ -344,6 +359,7 @@ export async function renderSchedules(root, { api, setMeta, actions, onEvent },
const first = available.find((a) => a.available)?.name ?? "scan";
const draft = { recurrence: { every: 1, unit: "hours", time: "03:00", days: ["mon"], dayOfMonth: 1, ...(schedule?.recurrence ?? { kind: "daily" }) } };
const fixed = `disabled title="${attr(t("Admin.Schedules.Fixed.Tip"))}"`;
const lock = editing ? ageLock(schedule.systemKey, schedule.parameters?.olderThanDays ?? 0) : null;
const actionOptions = (editing && !available.some((a) => a.name === schedule.action) ? [{ name: schedule.action, available: false }] : available).map((a) =>
`<option value="${attr(a.name)}" ${a.name === (schedule?.action ?? first) ? "selected" : ""} ${a.available || a.name === schedule?.action ? "" : "disabled"}
title="${attr(a.available ? actionTip(a.name) : reasonTip(a.reason))}">${escapeHtml(actionLabel(a.name))}</option>`).join("");
@@ -363,7 +379,7 @@ export async function renderSchedules(root, { api, setMeta, actions, onEvent },
<select class="input" name="priority" data-i18n-title="Admin.Schedules.Priority.Tip">${PRIORITIES.map((p) =>
`<option value="${p}" ${p === (schedule?.priority ?? "background") ? "selected" : ""}>${escapeHtml(t(`Admin.Jobs.Priority.${cap(p)}`))}</option>`).join("")}</select></label>
<label class="check"><input type="checkbox" name="catchUp" ${schedule?.catchUp ?? true ? "checked" : ""} data-i18n-title="Admin.Schedules.CatchUp.Tip"><span data-i18n="Admin.Schedules.CatchUp"></span></label>
<label class="check"><input type="checkbox" name="enabled" ${schedule?.enabled ?? true ? "checked" : ""} data-i18n-title="Admin.Schedules.Enabled.Tip"><span data-i18n="Admin.Schedules.Enabled"></span></label>
<label class="check"><input type="checkbox" name="enabled" ${schedule?.enabled ?? true ? "checked" : ""} ${lock?.deletes ? lock.attrs : `data-i18n-title="Admin.Schedules.Enabled.Tip"`}><span data-i18n="Admin.Schedules.Enabled"></span></label>
<div class="buttons">
<button class="btn" type="button" id="close" data-i18n="Admin.Common.Cancel" data-i18n-title="Admin.Common.Cancel.Tip"></button>
<button class="btn primary" type="submit" data-i18n="${editing ? "Admin.Common.Save" : "Admin.Schedules.Create"}" data-i18n-title="${editing ? "Admin.Common.Save.Tip" : "Admin.Schedules.Create.Tip"}"></button>
@@ -398,7 +414,7 @@ export async function renderSchedules(root, { api, setMeta, actions, onEvent },
toast(t("Admin.Common.Saved"));
await load();
} catch (err) {
fieldError(form, err);
fieldError(form, err, schedule);
}
});
(form.querySelector("input:not([disabled]), select:not([disabled])"))?.focus();
@@ -433,26 +449,29 @@ export async function renderSchedules(root, { api, setMeta, actions, onEvent },
/** The parameters <paramref name="action"/> reads, filled from <paramref name="p"/>. */
function drawParameters(form, action, p, systemKey) {
const host = form.querySelector("#parameters");
const lockedAge = LOCKED_AGES[systemKey];
const ageLocked = lockedAge && locked.some((l) => l.toLowerCase() === lockedAge[0].toLowerCase());
const lock = ageLock(systemKey, p.olderThanDays ?? 0);
host.innerHTML = (PARAMETERS[action] ?? []).map((name) => {
const key = `Admin.Schedules.Param.${PARAM_KEYS[`${action}.${name}`]}`;
if (name === "steps") {
const tip = (step) => lock?.deletes && lock.steps.includes(step) ? lock.attrs : `title="${attr(stepTip(step))}"`;
return `<fieldset><legend data-i18n="${key}"></legend>${steps.map((step) => `<label class="check">
<input type="checkbox" name="step-${attr(step)}" value="${attr(step)}" ${(p.steps ?? []).includes(step) ? "checked" : ""} title="${attr(stepTip(step))}"><span>${escapeHtml(stepLabel(step))}</span></label>`).join("")}</fieldset>`;
<input type="checkbox" name="step-${attr(step)}" value="${attr(step)}" ${(p.steps ?? []).includes(step) ? "checked" : ""} ${tip(step)}><span>${escapeHtml(stepLabel(step))}</span></label>`).join("")}</fieldset>`;
}
if (name in NUMBERS) {
const lock = name === "olderThanDays" && ageLocked ? `disabled title="${attr(t("Admin.Settings.Locked.Tip", lockedAge[1]))}"` : `data-i18n-title="${key}.Tip"`;
return `<label><span data-i18n="${key}"></span><input class="input narrow num" type="number" name="${name}" ${NUMBERS[name]} value="${attr(p[name] ?? 0)}" ${lock}></label>`;
const fixed = name === "olderThanDays" && lock ? lock.attrs : `data-i18n-title="${key}.Tip"`;
return `<label><span data-i18n="${key}"></span><input class="input narrow num" type="number" name="${name}" ${NUMBERS[name]} value="${attr(p[name] ?? 0)}" ${fixed}></label>`;
}
return `<label class="check"><input type="checkbox" name="${name}" ${p[name] ? "checked" : ""} data-i18n-title="${key}.Tip"><span data-i18n="${key}"></span></label>`;
}).join("");
applyStrings(host);
}
/** An API failure on the side form: the field it concerns gets the error border, the message and the focus; a toast announces it. */
function fieldError(form, err) {
const field = fieldOf(form, err.code === "setting_locked" ? "parameters.olderThanDays" : err.code === "invalid_schedule" ? err.details : null);
/**
* An API failure on the side form of <paramref name="schedule"/> (null for a new one): the field it concerns gets the error
* border, the message and the focus; a toast announces it.
*/
function fieldError(form, err, schedule) {
const field = err.code === "setting_locked" ? lockedField(form, schedule) : fieldOf(form, err.code === "invalid_schedule" ? err.details : null);
const message = field && err.code === "invalid_schedule" ? invalidText(field) : errorText(err);
if (field) {
markInvalid(field, message);
@@ -517,6 +536,19 @@ function fieldOf(form, apiField) {
return el[name] ?? null;
}
/**
* The form field a <c>setting_locked</c> refusal concerns, in the server's order (ScheduleEndpoints.ChangesLocked): the
* switch turned off while the limit deletes, the age limit changed, a step the limit deletes with unticked; else the age limit.
*/
function lockedField(form, schedule) {
const el = form.elements;
const days = schedule?.parameters?.olderThanDays ?? 0;
if (days > 0 && !el.enabled.checked) return el.enabled;
if (el.olderThanDays && Number(el.olderThanDays.value) !== days) return el.olderThanDays;
const step = days > 0 ? (LOCKED_AGES[schedule?.systemKey]?.steps ?? []).map((s) => el[`step-${s}`]).find((box) => box && !box.checked) : null;
return step ?? el.olderThanDays ?? null;
}
function actionTip(action) {
const key = `Admin.Schedules.Action.${pascal(action)}.Tip`;
return has(key) ? t(key) : action;
+3 -1
View File
@@ -77,7 +77,9 @@ public static class AdminEndpoints
AuditLog audit, JobEngineHost jobs, SchedulerHost schedules)
{
// 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.
// the default stored in server.json (and an environment variable's lock) is left alone. Like every setting of the
// panel it is last-writer-wins: a value that differs from the limit in force now replaces it, also a limit set in
// Jobs › Scheduled after this page was read.
var shown = await schedules.AuditRetentionAsync(context.RequestAborted) ?? options.AuditRetentionDays;
int? auditDays = null;
if (request.Logs is { } logs)
+17 -6
View File
@@ -14,7 +14,7 @@ namespace Chronos.Server.Api;
/// 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>…); changing an age limit an environment variable fixes, or turning its
/// schedule off, is 409 <c>setting_locked</c>. Every change is audited.
/// schedule off or unticking the steps it deletes with, is 409 <c>setting_locked</c>. Every change is audited.
/// </summary>
public static class ScheduleEndpoints
{
@@ -49,11 +49,7 @@ 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. 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)))
if (host.Host.LockedAgeOf(current.SystemKey) is { } locked && ChangesLocked(host.Host, current, request, locked))
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");
@@ -63,6 +59,21 @@ public static class ScheduleEndpoints
return Results.Json(schedule, ProtocolJson.Default.ScheduleDto);
}
/// <summary>
/// Whether <paramref name="request"/> changes what an environment variable fixes for the system schedule
/// <paramref name="current"/>: its age limit (parameters are replaced as a whole, so a missing one would fall back to the
/// action's default) and, while the limit deletes (more than 0 days), its switch and the steps the limit deletes with
/// (<see cref="ServerScheduleHost.AgedSteps"/>): turned off, or without them, it would keep what the variable asks to delete.
/// </summary>
private static bool ChangesLocked(ServerScheduleHost host, ScheduleDto current, UpdateScheduleRequest request, LockedAge locked)
{
if (locked.Days > 0 && request.Enabled == false) return true;
if (request.Parameters is not { } parameters) return false;
var normalized = ScheduleActions.Normalize(current.Action, parameters);
if (normalized.OlderThanDays != locked.Days) return true;
return locked.Days > 0 && host.AgedSteps(current.SystemKey).Except(normalized.Steps ?? []).Any();
}
private static async Task<IResult> DeleteAsync(HttpContext context, Caller caller, Guid id, SchedulerHost host, AuditLog audit)
{
var ct = context.RequestAborted;
+21 -12
View File
@@ -16,10 +16,10 @@ namespace Chronos.Server.Jobs;
/// 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: 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"/>.
/// 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
{
@@ -72,20 +72,23 @@ public sealed class SchedulerHost : IHostedService
/// <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 (nothing is deleted); null before the schedule is seeded.
/// 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, off at 0, which keeps everything.
/// 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 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 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)
@@ -98,15 +101,21 @@ 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 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.
/// 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);
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),
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);
@@ -124,6 +124,13 @@ public sealed class ServerScheduleHost : IScheduleHost
? 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
@@ -295,8 +295,9 @@ public sealed class ScheduleEndpointTests(TestContext context)
/// <summary>
/// Owner review 2, R10 and R11: the audit retention has one source of truth, the audit clean-up schedule's age limit.
/// Settings › Logs shows it wherever it was set (0 while the schedule is off) and sets it (turning the schedule on, or
/// off at 0); Reset goes back to the value last saved there, and at 0 the audit step deletes nothing.
/// Settings › Logs shows it wherever it was set (0 while the schedule is off or without its audit step) and sets it
/// (turning the schedule on with its audit step, or off at 0); Reset goes back to the value last saved there, and at 0
/// the audit step deletes nothing.
/// </summary>
[Test]
public async Task TheAuditRetentionOfTheSettingsIsTheAgeLimitOfTheAuditCleanUp()
@@ -339,6 +340,14 @@ public sealed class ScheduleEndpointTests(TestContext context)
audit = SystemRow(await ListAsync(admin), ServerScheduleHost.AuditCleanup);
Assert.Equal(((int?)30, true), (audit.Parameters.OlderThanDays, audit.Enabled));
// Without its audit step it deletes nothing either: Settings shows 0, and saving 30 there ticks the step again.
await EditAsync(admin, audit.Id, new UpdateScheduleRequest(Parameters: new ScheduleParametersDto(Steps: ["job-history"], OlderThanDays: 30)));
Assert.Equal(0, (await SettingsAsync(admin)).Logs.AuditRetentionDays);
await SaveAuditRetentionAsync(admin, 30);
audit = SystemRow(await ListAsync(admin), ServerScheduleHost.AuditCleanup);
Assert.Equal(((int?)30, true), (audit.Parameters.OlderThanDays, audit.Enabled));
Assert.SequenceEqual(["job-history", "audit"], audit.Parameters.Steps!);
// Back to 0: kept forever, the schedule off.
await SaveAuditRetentionAsync(admin, 0);
audit = SystemRow(await ListAsync(admin), ServerScheduleHost.AuditCleanup);
@@ -536,9 +545,13 @@ public sealed class ScheduleEndpointTests(TestContext context)
{
var seeded = Assert.NotNull(await first.Database.Schedules.GetBySystemKeyAsync(ServerScheduleHost.AuditCleanup, Ct));
Assert.Equal(((int?)0, false), (ScheduleMapping.Parameters(seeded).OlderThanDays, seeded.Enabled));
// Its audit step unticked before the variable is set.
var unticked = await first.Services.GetRequiredService<SchedulerHost>().Scheduler.UpdateAsync(seeded.Id,
new UpdateScheduleRequest(Parameters: new ScheduleParametersDto(Steps: ["job-history"], OlderThanDays: 0)), Ct);
Assert.Null(unticked.Problem);
}
// CHRONOS_AUDIT_RETENTION_DAYS=30 at the next start.
// CHRONOS_AUDIT_RETENTION_DAYS=30 at the next start: the limit, the switch and the audit step it deletes with.
await using var second = await TestServer.StartAsync(context, o =>
{
Paths(o);
@@ -548,13 +561,18 @@ public sealed class ScheduleEndpointTests(TestContext context)
var admin = await second.AdminAsync();
var audit = SystemRow(await ListAsync(admin), ServerScheduleHost.AuditCleanup);
Assert.Equal(((int?)30, true), (audit.Parameters.OlderThanDays, audit.Enabled));
Assert.SequenceEqual(["job-history", "audit"], audit.Parameters.Steps!);
using (var changed = await admin.PutAsJsonAsync($"/api/v1/schedules/{audit.Id}", new UpdateScheduleRequest(Parameters: new ScheduleParametersDto(Steps: ["audit"], OlderThanDays: 60)),
ProtocolJson.Default.UpdateScheduleRequest))
Assert.Equal("AuditRetentionDays", (await changed.ExpectErrorAsync(HttpStatusCode.Conflict, "setting_locked")).Details);
// Turned off, it would keep what the variable says to delete.
// Turned off, or without its audit step, it would keep what the variable says to delete.
using (var off = await admin.PutAsJsonAsync($"/api/v1/schedules/{audit.Id}", new UpdateScheduleRequest(Enabled: false), ProtocolJson.Default.UpdateScheduleRequest))
Assert.Equal("AuditRetentionDays", (await off.ExpectErrorAsync(HttpStatusCode.Conflict, "setting_locked")).Details);
using (var unticked = await admin.PutAsJsonAsync($"/api/v1/schedules/{audit.Id}",
new UpdateScheduleRequest(Parameters: new ScheduleParametersDto(Steps: ["job-history"], OlderThanDays: 30)), ProtocolJson.Default.UpdateScheduleRequest))
Assert.Equal("AuditRetentionDays", (await unticked.ExpectErrorAsync(HttpStatusCode.Conflict, "setting_locked")).Details);
Assert.SequenceEqual(["job-history", "audit"], SystemRow(await ListAsync(admin), ServerScheduleHost.AuditCleanup).Parameters.Steps!);
// Everything else stays editable.
using var timing = await admin.PutAsJsonAsync($"/api/v1/schedules/{audit.Id}", new UpdateScheduleRequest(Recurrence: new RecurrenceDto("daily", Time: "05:00"),
Parameters: new ScheduleParametersDto(Steps: ["audit", "job-history"], OlderThanDays: 30)), ProtocolJson.Default.UpdateScheduleRequest);