feat(data): scheduler engine, schedules table and housekeeping jobs

Owner review 2, R10: every timer that queues work becomes a visible schedule,
so the server and the desktop need one shared engine to run them.

- Migration 0007: schedules table (system rows keyed by system_key) and
  jobs.schedule_id; Job.ScheduleId, JobDto.ScheduleId, JobRepository
  HasPendingAsync / ListPendingTargetsAsync / ListByScheduleAsync.
- ScheduleRepository: seeding that keeps user edits, reset, compare-and-set
  claim of a run (one winner across processes), outcomes.
- Scheduling: in-house recurrence (every/daily/weekly/monthly, DST gap moves
  forward, ambiguous time runs once), ScheduleActions resolving scan, verify,
  thumbnails, proxies, analysis, maintenance, backup, cleanup, duplicates and
  orphans into archive jobs, IScheduleHost, and the Scheduler loop (catch-up,
  clock going back, run now, CRUD as API v1 DTOs).
- New job kinds Backup (16) and Cleanup (17) with handlers, shared clean-up
  steps (job history, audit log, trash report that never deletes) and host
  steps through ArchiveServiceOptions; read-only Duplicates and Orphans report
  handlers, so the server can run those kinds too.
- JobEngine no longer purges history at start: the housekeeping schedule's
  job-history step does; JobEngine.CanRun and an EnqueueAsync with scheduleId.
- Protocol DTOs for schedules; job kind names in en and it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit eb0edd2483a493db7c6945d5b494461cabb2a4ad)
This commit is contained in:
Alby96 committed 2026-10-27 02:08:11 +01:00
1 parent 0e84392f4f
commit e5508e7e69
51 files changed
+3219 -30

No files matched your search

@@ -0,0 +1,116 @@
using Chronos.Core.Archiving;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
namespace Chronos.Data.Housekeeping;
/// <summary>
/// One step of a <see cref="JobKind.Cleanup"/> job (owner review 2, R10). The shared steps are in <see cref="CleanupSteps"/>;
/// a host adds its own (the server's uploads sweep, the desktop's cache trim) through
/// <see cref="ArchiveServiceOptions.CleanupSteps"/>. A step must be safe to run again at any time, honour
/// <see cref="CleanupContext.Cancellation"/>, and never delete user data (BRIEF §0.2 rule 8): only what the product made
/// and no longer needs (history, temporary files), never originals or the trash.
/// </summary>
public interface ICleanupStep
{
/// <summary>Wire name, kebab-case (<c>job-history</c>): what a schedule's <c>steps</c> list.</summary>
string Name { get; }
/// <summary>Runs the step and returns the line the job log shows for it (localized).</summary>
Task<string> RunAsync(CleanupContext context, CleanupParameters parameters);
}
/// <summary>What a clean-up step works with: the index, the job's archive (if any), the running job and the time it started.</summary>
public sealed class CleanupContext(ChronosDatabase database, Archive? archive, JobContext job, DateTimeOffset now)
{
public ChronosDatabase Database { get; } = database;
/// <summary>The archive the job targets; null when it targets none (no archive open).</summary>
public Archive? Archive { get; } = archive;
/// <summary>The running clean-up job: its log and cancellation.</summary>
public JobContext Job { get; } = job;
/// <summary>When the job started its steps (UTC); ages count from it.</summary>
public DateTimeOffset Now { get; } = now;
public CancellationToken Cancellation => Job.Cancellation;
/// <summary>The instant before which things are <paramref name="olderThanDays"/> old; null for 0, which keeps everything.</summary>
public DateTimeOffset? Before(int olderThanDays) => olderThanDays > 0 ? Now - TimeSpan.FromDays(olderThanDays) : null;
}
/// <summary>
/// The clean-up steps every host has (owner review 2, R10): <see cref="JobHistory"/> (finished jobs, which the job engine
/// purged at start before), <see cref="Audit"/> (the audit log; 0 days keeps it) and <see cref="TrashReport"/> (lists the
/// archive's trash entries older than the limit with their sizes; it never deletes: emptying the trash stays a user action).
/// </summary>
public static class CleanupSteps
{
public const string JobHistory = "job-history";
public const string Audit = "audit";
public const string TrashReport = "trash-report";
/// <summary>Days of job history the housekeeping schedule keeps unless the host says otherwise (BRIEF §14.6: 90).</summary>
public const int DefaultHistoryDays = 90;
/// <summary>Age in days from which the trash report lists an entry unless the schedule says otherwise.</summary>
public const int DefaultTrashDays = 30;
/// <summary>Trash entries listed one per log line; the report counts them all.</summary>
internal const int ListedTrashEntries = 20;
/// <summary>The shared steps, in the order a host lists them: job history, audit log, trash report.</summary>
public static IReadOnlyList<ICleanupStep> Shared(SequenceTrash trash) => [new JobHistoryStep(), new AuditStep(), new TrashReportStep(trash)];
/// <summary>"12.4 MB" in the language of the log.</summary>
internal static string Megabytes(long bytes) => Loc.L("Common.Size.MB", (bytes / 1e6).ToString("0.#", Loc.Culture));
private sealed class JobHistoryStep : ICleanupStep
{
public string Name => JobHistory;
public async Task<string> RunAsync(CleanupContext context, CleanupParameters parameters)
{
if (context.Before(parameters.OlderThanDays) is not { } before) return Loc.L("Archive.Log.HistoryKept");
var removed = await context.Database.Jobs.PurgeHistoryAsync(before, context.Cancellation).ConfigureAwait(false);
return Loc.L("Archive.Log.HistoryPurged", removed);
}
}
private sealed class AuditStep : ICleanupStep
{
public string Name => Audit;
public async Task<string> RunAsync(CleanupContext context, CleanupParameters parameters)
{
if (context.Before(parameters.OlderThanDays) is not { } before) return Loc.L("Archive.Log.AuditKept");
var removed = await context.Database.Audit.PurgeAsync(before, context.Cancellation).ConfigureAwait(false);
return Loc.L("Archive.Log.AuditPurged", removed);
}
}
/// <summary>Reads the trash and reports; nothing is moved or deleted (BRIEF §0.2 rule 8).</summary>
private sealed class TrashReportStep(SequenceTrash trash) : ICleanupStep
{
public string Name => TrashReport;
public async Task<string> RunAsync(CleanupContext context, CleanupParameters parameters)
{
if (context.Archive is not { } archive || ArchiveVolume.Probe(new ArchivePaths(archive.RootPath)) == ArchiveAvailability.Offline)
return Loc.L("Archive.Log.TrashOffline");
var before = context.Before(parameters.OlderThanDays);
var old = (await trash.ListAsync(archive, context.Cancellation).ConfigureAwait(false))
.Where(e => before is null || e.DeletedAt < before).OrderBy(e => e.DeletedAt).ToList();
foreach (var entry in old.Take(ListedTrashEntries))
{
context.Job.Log(Loc.L("Archive.Log.TrashEntry", entry.DeletedAt.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture),
entry.Title, Megabytes(entry.Bytes)));
}
return Loc.L("Archive.Log.TrashReport", old.Count, Megabytes(old.Sum(e => e.Bytes)));
}
}
}
@@ -0,0 +1,78 @@
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Data.Sqlite;
namespace Chronos.Data.Housekeeping;
/// <summary>
/// <see cref="JobKind.Backup"/> (owner review 2, R10): a <c>VACUUM INTO</c> copy of the SQLite index into
/// <paramref name="directory"/> (by default the <c>backups</c> folder next to the index, <see cref="DatabaseBackups.DefaultDirectory"/>),
/// keeping the newest <see cref="BackupParameters.Keep"/>. A PostgreSQL index, or one without a file, cannot be copied this
/// way (<see cref="DatabaseBackups.Unavailable"/>): the job fails with that reason, and schedules do not queue it.
/// </summary>
internal sealed class BackupJobHandler(ChronosDatabase db, string? directory) : IJobHandler
{
/// <summary>Most copies a schedule may keep.</summary>
public const int MaxKeep = 100;
public JobKind Kind => JobKind.Backup;
public async Task RunAsync(JobContext context)
{
if (db.Database is not SqliteDatabase { Path: { } path })
throw new NotSupportedException(DatabaseBackups.Unavailable(db) == Scheduling.ScheduleUnavailable.Postgres
? "Backups of a PostgreSQL database are made with the server's own tools."
: "An index without a file cannot be backed up.");
var keep = Math.Clamp(ArchiveJobJson.Read(context.Job, ArchiveJobJson.Default.BackupParameters, new BackupParameters(DatabaseBackups.Keep)).Keep, 1, MaxKeep);
await context.ReportAsync(0, 1).ConfigureAwait(false);
var copy = await db.BackupAsync(directory ?? DatabaseBackups.DefaultDirectory(path), keep, context.Cancellation).ConfigureAwait(false);
context.Log(Loc.L("Archive.Log.BackupDone", copy, CleanupSteps.Megabytes(new FileInfo(copy).Length), keep));
await context.ReportAsync(1, 1).ConfigureAwait(false);
}
}
/// <summary>
/// <see cref="JobKind.Cleanup"/> (owner review 2, R10): runs the named steps of <see cref="CleanupParameters"/> in order,
/// each with the job's age limit, and logs one line per step. A step that fails is logged and the others still run; the job
/// then fails naming it. Steps are quick and safe to repeat, so a resumed job runs them all again (no checkpoint). An
/// unknown name (a step of another host, or of a newer build) is logged and skipped.
/// </summary>
internal sealed class CleanupJobHandler(ChronosDatabase db, IReadOnlyList<ICleanupStep> steps, TimeProvider time) : IJobHandler
{
public JobKind Kind => JobKind.Cleanup;
public async Task RunAsync(JobContext context)
{
var parameters = ArchiveJobJson.Read(context.Job, ArchiveJobJson.Default.CleanupParameters, new CleanupParameters([], 0));
var archive = context.Job.TargetIds.Count > 0 ? await db.Archives.GetAsync(context.Job.TargetIds[0], context.Cancellation).ConfigureAwait(false) : null;
var cleanup = new CleanupContext(db, archive, context, time.GetUtcNow());
var names = parameters.Steps;
var failed = new List<string>();
for (var i = 0; i < names.Count; i++)
{
context.Cancellation.ThrowIfCancellationRequested();
await context.ReportAsync(i, names.Count).ConfigureAwait(false);
var step = steps.FirstOrDefault(s => string.Equals(s.Name, names[i], StringComparison.Ordinal));
if (step is null)
{
context.Log(Loc.L("Archive.Log.StepUnknown", names[i]));
continue;
}
try
{
context.Log(await step.RunAsync(cleanup, parameters).ConfigureAwait(false));
}
catch (Exception ex) when (!(ex is OperationCanceledException && context.Cancellation.IsCancellationRequested))
{
Log.Warning("jobs", $"Clean-up step {step.Name} of job {context.Job.Id} failed", ex);
context.Log(Loc.L("Archive.Log.StepFailed", step.Name, ex.Message));
failed.Add(step.Name);
}
}
await context.ReportAsync(names.Count, names.Count).ConfigureAwait(false);
if (failed.Count > 0) throw new InvalidOperationException($"Clean-up steps failed: {string.Join(", ", failed)}.");
}
}