From e6e69782ed7fcc7129b66adad734b82df685b278 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 27 Oct 2026 10:39:49 +0100 Subject: [PATCH] fix(server): a locked audit retention also fixes the audit step and the switch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- i18n/en/Admin.resx | 2 +- i18n/en/Tooltips.resx | 2 +- i18n/it/Admin.it.resx | 2 +- i18n/it/Tooltips.it.resx | 2 +- src/Chronos.Data/DatabaseBackups.cs | 5 +- src/Chronos.Data/Scheduling/IScheduleHost.cs | 6 +- src/Chronos.Server/Admin/web/schedules.js | 58 ++++++++++++++----- src/Chronos.Server/Api/AdminEndpoints.cs | 4 +- src/Chronos.Server/Api/ScheduleEndpoints.cs | 23 ++++++-- src/Chronos.Server/Jobs/SchedulerHost.cs | 33 +++++++---- src/Chronos.Server/Jobs/ServerScheduleHost.cs | 7 +++ .../Jobs/ScheduleEndpointTests.cs | 26 +++++++-- 12 files changed, 125 insertions(+), 45 deletions(-) diff --git a/i18n/en/Admin.resx b/i18n/en/Admin.resx index 538ca6fd..7b4e9654 100644 --- a/i18n/en/Admin.resx +++ b/i18n/en/Admin.resx @@ -381,7 +381,7 @@ Full scan Read every file again instead of only those added or changed Copies kept - How many copies of the index are kept; older ones are deleted + 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 Make again Make them again for every sequence, also those that have them Older than (days) diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx index 8af475c2..a3c400c7 100644 --- a/i18n/en/Tooltips.resx +++ b/i18n/en/Tooltips.resx @@ -342,7 +342,7 @@ Off, the schedule never runs by itself How many minutes (5 to 1,440), hours (1 to 168) or days (1 to 366) Reads every file again, not only those whose date or size changed - How many copies of the index are kept; older ones are deleted + 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 Every day at a time At a fixed interval: every n minutes, hours or days On one day of the month at a time diff --git a/i18n/it/Admin.it.resx b/i18n/it/Admin.it.resx index 0bc945da..e24adc01 100644 --- a/i18n/it/Admin.it.resx +++ b/i18n/it/Admin.it.resx @@ -380,7 +380,7 @@ Scansione completa Rilegge ogni file invece di quelli aggiunti o modificati Copie conservate - Quante copie dell'indice si conservano; le più vecchie vengono eliminate + 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 Ricrea Le ricrea per ogni sequenza, anche per quelle che le hanno Più vecchi di (giorni) diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx index 965ea598..862a524d 100644 --- a/i18n/it/Tooltips.it.resx +++ b/i18n/it/Tooltips.it.resx @@ -341,7 +341,7 @@ Disattivata, la pianificazione non viene mai eseguita da sola Quanti minuti (da 5 a 1.440), ore (da 1 a 168) o giorni (da 1 a 366) Rilegge ogni file, non solo quelli con data o dimensione cambiate - Quante copie dell'indice vengono mantenute; le più vecchie vengono eliminate + 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 Ogni giorno a un'ora A intervallo fisso: ogni n minuti, ore o giorni In un giorno del mese a un'ora diff --git a/src/Chronos.Data/DatabaseBackups.cs b/src/Chronos.Data/DatabaseBackups.cs index c9a8f9c1..c71a8b55 100644 --- a/src/Chronos.Data/DatabaseBackups.cs +++ b/src/Chronos.Data/DatabaseBackups.cs @@ -82,8 +82,9 @@ public static partial class DatabaseBackups /// /// When the newest copy of 's index file in (null: ) /// 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 (), so the first copy after an upgrade comes - /// as the former daily loop would have made it. + /// backup schedule with it (): 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. /// public static DateTimeOffset? Newest(ChronosDatabase db, string? directory) { diff --git a/src/Chronos.Data/Scheduling/IScheduleHost.cs b/src/Chronos.Data/Scheduling/IScheduleHost.cs index 86668aeb..b1078fe2 100644 --- a/src/Chronos.Data/Scheduling/IScheduleHost.cs +++ b/src/Chronos.Data/Scheduling/IScheduleHost.cs @@ -46,9 +46,9 @@ public interface IScheduleHost /// A host's system schedule: identifies it across starts (archive-scan, /// index-backup, housekeeping…); the rest is what it is seeded with and reset to. is /// stored as given; clients show system schedules by their key in the user's language. 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. /// public sealed record SystemSchedule( string SystemKey, diff --git a/src/Chronos.Server/Admin/web/schedules.js b/src/Chronos.Server/Admin/web/schedules.js index 228149d9..93e60d66 100644 --- a/src/Chronos.Server/Admin/web/schedules.js +++ b/src/Chronos.Server/Admin/web/schedules.js @@ -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 whose age limit is + * (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 = "") => ``; 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 `
${expanded.has(s.id) ? `
${runsHtml(s)}
` : ""}`; @@ -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) => ``).join(""); @@ -363,7 +379,7 @@ export async function renderSchedules(root, { api, setMeta, actions, onEvent }, - +
@@ -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 reads, filled from . */ 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 `
${steps.map((step) => ``).join("")}
`; + ${escapeHtml(stepLabel(step))}`).join("")}`; } 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 ``; + const fixed = name === "olderThanDays" && lock ? lock.attrs : `data-i18n-title="${key}.Tip"`; + return ``; } return ``; }).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 (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 setting_locked 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; diff --git a/src/Chronos.Server/Api/AdminEndpoints.cs b/src/Chronos.Server/Api/AdminEndpoints.cs index 5ba164bb..f59ca983 100644 --- a/src/Chronos.Server/Api/AdminEndpoints.cs +++ b/src/Chronos.Server/Api/AdminEndpoints.cs @@ -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) diff --git a/src/Chronos.Server/Api/ScheduleEndpoints.cs b/src/Chronos.Server/Api/ScheduleEndpoints.cs index d7991416..0ad6c4b8 100644 --- a/src/Chronos.Server/Api/ScheduleEndpoints.cs +++ b/src/Chronos.Server/Api/ScheduleEndpoints.cs @@ -14,7 +14,7 @@ namespace Chronos.Server.Api; /// queued, running or paused), reset a system schedule (409 schedule_no_defaults otherwise) and the jobs a schedule /// queued, newest first. An invalid field is 400 invalid_schedule with its name as details (name, /// recurrence, parameters.percent…); changing an age limit an environment variable fixes, or turning its -/// schedule off, is 409 setting_locked. Every change is audited. +/// schedule off or unticking the steps it deletes with, is 409 setting_locked. Every change is audited. /// 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); } + /// + /// Whether changes what an environment variable fixes for the system schedule + /// : 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 + /// (): turned off, or without them, it would keep what the variable asks to delete. + /// + 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 DeleteAsync(HttpContext context, Caller caller, Guid id, SchedulerHost host, AuditLog audit) { var ct = context.RequestAborted; diff --git a/src/Chronos.Server/Jobs/SchedulerHost.cs b/src/Chronos.Server/Jobs/SchedulerHost.cs index 8d670895..8d8ae5e8 100644 --- a/src/Chronos.Server/Jobs/SchedulerHost.cs +++ b/src/Chronos.Server/Jobs/SchedulerHost.cs @@ -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 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 -/// () and sets it (); -/// 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 . +/// 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 () and sets it (); +/// 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 . /// public sealed class SchedulerHost : IHostedService { @@ -72,20 +72,23 @@ public sealed class SchedulerHost : IHostedService /// /// 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. /// public async Task AuditRetentionAsync(CancellationToken cancellationToken = default) => await _db.Schedules.GetBySystemKeyAsync(ServerScheduleHost.AuditCleanup, cancellationToken) is { } row ? InForce(row) : null; /// /// 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. /// public Task ApplyAuditRetentionAsync(int days, CancellationToken cancellationToken = default) => ApplyAgeAsync(ServerScheduleHost.AuditCleanup, days, "Settings › Logs", cancellationToken); - /// The age limit of a system schedule that deletes by age, 0 while it is off. - private static int InForce(Schedule row) => row.Enabled ? ScheduleMapping.Parameters(row).OlderThanDays ?? 0 : 0; + /// The audit clean-up schedule's age limit, 0 while it is off or without the audit step, which alone deletes by it. + 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; /// The age limits environment variables fix, put into their system schedules at every start, before the first pass. private async Task ApplyLockedAgesAsync(CancellationToken cancellationToken) @@ -98,15 +101,21 @@ public sealed class SchedulerHost : IHostedService /// /// Sets the age limit of the system schedule to , 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 + /// () 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. /// 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); diff --git a/src/Chronos.Server/Jobs/ServerScheduleHost.cs b/src/Chronos.Server/Jobs/ServerScheduleHost.cs index 7782ded1..0cffda9a 100644 --- a/src/Chronos.Server/Jobs/ServerScheduleHost.cs +++ b/src/Chronos.Server/Jobs/ServerScheduleHost.cs @@ -124,6 +124,13 @@ public sealed class ServerScheduleHost : IScheduleHost ? new LockedAge(nameof(ServerOptions.AuditRetentionDays), ServerOptions.AuditRetentionVariable, _options.AuditRetentionDays) : null; + /// + /// The steps the age limit of the system schedule deletes with: its default steps + /// (), audit for ; none for another key. + /// + public IReadOnlyList AgedSteps(string? systemKey) => + SystemSchedules.FirstOrDefault(s => s.SystemKey == systemKey)?.Parameters?.Steps ?? []; + /// /// 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 diff --git a/tests/Chronos.Server.Tests/Jobs/ScheduleEndpointTests.cs b/tests/Chronos.Server.Tests/Jobs/ScheduleEndpointTests.cs index fa2b880f..ee17c7aa 100644 --- a/tests/Chronos.Server.Tests/Jobs/ScheduleEndpointTests.cs +++ b/tests/Chronos.Server.Tests/Jobs/ScheduleEndpointTests.cs @@ -295,8 +295,9 @@ public sealed class ScheduleEndpointTests(TestContext context) /// /// 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. /// [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().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);