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

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

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

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

No files matched your search

+127
View File
@@ -0,0 +1,127 @@
using System.IO;
using Chronos.App.Archiving;
using Chronos.App.Infrastructure;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Housekeeping;
using Chronos.Data.Scheduling;
using Chronos.Protocol;
namespace Chronos.App.Jobs;
/// <summary>
/// The desktop's <see cref="IScheduleHost"/> (owner review 2, R10). Times are the PC's; schedules work on the archive at
/// Settings › Archive's folder (<see cref="CurrentArchive"/>), which first takes the settings another process sharing it
/// wrote into its archive.json, as the rescans before it did, and counts as none while it is offline (an unplugged
/// 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). 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
{
/// <summary>Incremental scan of the archive, every <see cref="AppSettings.ScanIntervalMinutes"/> (10) minutes, no catch-up.</summary>
public const string ArchiveScan = "archive-scan";
/// <summary>
/// Copy of the index into the backups folder, every day, with catch-up (it replaced the daily backup loop). Seeded due
/// at once when the newest copy is a day old, as that loop made one at start.
/// </summary>
public const string IndexBackup = DatabaseBackups.ScheduleKey;
/// <summary>Clean-up of the job history and the cache, daily at 04:00, with catch-up.</summary>
public const string Housekeeping = "housekeeping";
/// <summary>When the housekeeping runs.</summary>
public static readonly TimeOnly HousekeepingTime = new(4, 0);
/// <summary>The PC's zone; tests set another.</summary>
public TimeZoneInfo TimeZone { get; init; } = TimeZoneInfo.Local;
public IReadOnlyList<SystemSchedule> SystemSchedules =>
[
new(ArchiveScan, "Archive scan", ScheduleActions.Scan, ScheduleRecurrence.Interval(ScanMinutes(settings), RecurrenceUnit.Minutes),
new ScheduleParametersDto(Force: false), CatchUp: false),
new(IndexBackup, "Index backup", ScheduleActions.Backup, ScheduleRecurrence.Interval(1, RecurrenceUnit.Days),
new ScheduleParametersDto(Keep: DatabaseBackups.Keep),
LastDone: database() is { } db ? DatabaseBackups.Newest(db, archives()?.BackupDirectory) : null),
new(Housekeeping, "Housekeeping", ScheduleActions.Cleanup, ScheduleRecurrence.DailyAt(HousekeepingTime),
new ScheduleParametersDto(Steps: [Chronos.Data.Housekeeping.CleanupSteps.JobHistory, CacheTrimStep.StepName],
OlderThanDays: Chronos.Data.Housekeeping.CleanupSteps.DefaultHistoryDays)),
];
public IReadOnlyList<string> CleanupSteps => archives()?.CleanupSteps.Select(s => s.Name).ToList() ?? [];
/// <summary>
/// The interval the scan schedule is seeded with (and reset to): the former rescan setting, within what an interval
/// accepts (5 minutes to a day).
/// </summary>
public static int ScanMinutes(AppSettings settings)
{
ArgumentNullException.ThrowIfNull(settings);
return int.Clamp(settings.ScanIntervalMinutes, ScheduleRecurrence.MinMinutes, ScheduleRecurrence.MaxMinutes);
}
public async ValueTask<Archive?> GetArchiveAsync(CancellationToken cancellationToken)
{
if (database() is not { } db || archives() is not { } service) return null;
var archive = CurrentArchive.Pick(await db.Archives.ListAsync(cancellationToken).ConfigureAwait(false), settings.LastArchivePath);
if (archive is null || ArchiveService.GetAvailability(archive) == ArchiveAvailability.Offline) return null;
try
{
await service.RefreshSettingsAsync(archive.Id, cancellationToken).ConfigureAwait(false);
return await db.Archives.GetAsync(archive.Id, cancellationToken).ConfigureAwait(false) ?? archive;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException or NewerFormatException)
{
// The settings as last read: the run still works on the archive, the next one reads them again.
Log.Warning("schedules", $"The settings of {archive.RootPath} could not be read again", ex);
return archive;
}
}
/// <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>
/// The desktop's clean-up step <c>cache-trim</c> (owner review 2, R10): brings the cache folder down to Settings › Storage ›
/// Cache limit, oldest files first, skipping files in use (<see cref="CacheStore.Trim"/>). The proxies of server sequences
/// (complete sets the sync keeps), the render node's folder (it trims its own downloads to the same limit) and the copies an
/// import to the server stages are never trimmed; Settings › Storage › Clear still empties everything.
/// </summary>
public sealed class CacheTrimStep(Func<string> folder, Func<long> limitBytes) : ICleanupStep
{
public const string StepName = "cache-trim";
/// <summary>Folders of the cache the trim leaves whole.</summary>
public static IReadOnlyList<string> Kept { get; } = ["proxies", "render-node", "server-import"];
public string Name => StepName;
public Task<string> RunAsync(CleanupContext context, CleanupParameters parameters)
{
ArgumentNullException.ThrowIfNull(context);
var limit = limitBytes();
return Task.Run(() =>
{
var result = CacheStore.Trim(folder(), limit, Kept, context.Cancellation);
if (result is null) return Loc.L("Jobs.Log.CacheNotOwned");
return result.Deleted == 0
? Loc.L("Jobs.Log.CacheKept", Gigabytes(result.After), Gigabytes(limit))
: Loc.L("Jobs.Log.CacheTrimmed", Gigabytes(result.After), Gigabytes(limit), Gigabytes(result.Freed));
}, context.Cancellation);
}
/// <summary>"12.4 GB" in the binary gigabytes of Settings › Storage › Cache limit.</summary>
private static string Gigabytes(long bytes) => Loc.L("Common.Size.GB", (bytes / (double)(1L << 30)).ToString("0.#", Loc.Culture));
}