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

+37 -1
View File
@@ -40,6 +40,8 @@ public sealed class ArchiveService : IJobHandlerProvider
Images = new ArchiveImages(db, _writer, Indexer);
Imports = new ImportService(db, Ingest);
Trash = new SequenceTrash(db, _writer, Indexer);
var shared = Housekeeping.CleanupSteps.Shared(Trash);
CleanupSteps = [.. shared, .. _writer.Options.CleanupSteps.Where(s => !shared.Any(o => o.Name == s.Name))];
}
public ArchiveIndexer Indexer { get; }
@@ -56,7 +58,19 @@ public sealed class ArchiveService : IJobHandlerProvider
/// <summary>Deletes sequences into the archive's trash and restores them.</summary>
public SequenceTrash Trash { get; }
/// <summary>Handlers for scan, rebuild, verify, import, thumbs, proxies and maintenance jobs; register them on the <see cref="JobEngine"/>.</summary>
/// <summary>
/// The steps this host's <see cref="JobKind.Cleanup"/> jobs can run: the shared ones (<see cref="Housekeeping.CleanupSteps.Shared"/>),
/// then the host's (<see cref="ArchiveServiceOptions.CleanupSteps"/>). A schedule host lists their names.
/// </summary>
public IReadOnlyList<Housekeeping.ICleanupStep> CleanupSteps { get; }
/// <summary>Where this engine's <see cref="JobKind.Backup"/> jobs put their copies (<see cref="ArchiveServiceOptions.BackupDirectory"/>; null: next to the index).</summary>
public string? BackupDirectory => _writer.Options.BackupDirectory;
/// <summary>
/// Handlers for scan, rebuild, verify, import, thumbs, proxies and maintenance jobs, the read-only duplicates and orphans
/// reports, index backups and clean-ups (owner review 2, R10); register them on the <see cref="JobEngine"/>.
/// </summary>
public IReadOnlyList<IJobHandler> CreateJobHandlers() =>
[
new ScanJobHandler(_db, Indexer, JobKind.Scan, _writer.Options.ImagesAfterScan),
@@ -66,6 +80,10 @@ public sealed class ArchiveService : IJobHandlerProvider
new ImageJobHandler(_db, Images, JobKind.Thumbs),
new ImageJobHandler(_db, Images, JobKind.Proxies),
new MaintenanceJobHandler(_db, Maintenance),
new DuplicatesJobHandler(_db, Maintenance),
new OrphansJobHandler(_db, Maintenance),
new Housekeeping.BackupJobHandler(_db, _writer.Options.BackupDirectory),
new Housekeeping.CleanupJobHandler(_db, CleanupSteps, TimeProvider.System),
];
/// <summary>Makes <paramref name="root"/> a new, empty archive and indexes it.</summary>
@@ -482,6 +500,24 @@ public static class ArchiveJobs
new(JobKind.Maintenance, [archive.Id], archive.Name, Json(new MaintenanceParameters(dryRun), ArchiveJobJson.Default.MaintenanceParameters),
JobPriority.Normal);
/// <summary><see cref="JobKind.Duplicates"/>: a read-only report of the archive's duplicate photos into the job log.</summary>
public static ArchiveJobRequest Duplicates(Archive archive) => new(JobKind.Duplicates, [archive.Id], archive.Name, null, JobPriority.Normal);
/// <summary><see cref="JobKind.Orphans"/>: a read-only report of where the index and the disk disagree into the job log.</summary>
public static ArchiveJobRequest Orphans(Archive archive) => new(JobKind.Orphans, [archive.Id], archive.Name, null, JobPriority.Normal);
/// <summary><see cref="JobKind.Backup"/>: a copy of the SQLite index into the backups folder, keeping the newest <paramref name="keep"/>.</summary>
public static ArchiveJobRequest Backup(int keep = DatabaseBackups.Keep) =>
new(JobKind.Backup, [], null, Json(new BackupParameters(keep), ArchiveJobJson.Default.BackupParameters), JobPriority.Normal);
/// <summary>
/// <see cref="JobKind.Cleanup"/>: the clean-up <paramref name="steps"/> (by name, in order) with their age limit; the
/// archive, when given, is what archive steps (the trash report) look at.
/// </summary>
public static ArchiveJobRequest Cleanup(Archive? archive, IReadOnlyList<string> steps, int olderThanDays) =>
new(JobKind.Cleanup, archive is null ? [] : [archive.Id], archive?.Name,
Json(new CleanupParameters(steps, olderThanDays), ArchiveJobJson.Default.CleanupParameters), JobPriority.Normal);
public static Task<Job> EnqueueAsync(this JobEngine engine, ArchiveJobRequest request, Guid? createdBy = null, CancellationToken cancellationToken = default) =>
engine.EnqueueAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, request.Priority, createdBy, cancellationToken);
@@ -22,6 +22,15 @@ public sealed record MaintenanceParameters(bool DryRun);
/// <summary><see cref="JobKind.Import"/>: the exact plan the user confirmed.</summary>
public sealed record ImportJobParameters(Guid ArchiveId, ImportPlan Plan, Guid? CardId, bool Verify, Guid? UserId);
/// <summary><see cref="JobKind.Backup"/>: no target; the newest <paramref name="Keep"/> copies are kept.</summary>
public sealed record BackupParameters(int Keep);
/// <summary>
/// <see cref="JobKind.Cleanup"/>: target = the archive (or none); the clean-up steps to run, by name and in order, and
/// the age in days from which what they clean goes (0 keeps everything).
/// </summary>
public sealed record CleanupParameters(IReadOnlyList<string> Steps, int OlderThanDays);
/// <summary>A job ready to enqueue.</summary>
public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList<Guid> Targets, string? Label, string? ParametersJson, JobPriority Priority);
@@ -31,6 +40,8 @@ public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList<Guid> Targets
[JsonSerializable(typeof(ImageJobParameters))]
[JsonSerializable(typeof(MaintenanceParameters))]
[JsonSerializable(typeof(ImportJobParameters))]
[JsonSerializable(typeof(BackupParameters))]
[JsonSerializable(typeof(CleanupParameters))]
[JsonSerializable(typeof(CardProfile))]
internal sealed partial class ArchiveJobJson : JsonSerializerContext
{
@@ -0,0 +1,58 @@
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Jobs;
namespace Chronos.Data.Archiving.Jobs;
/// <summary>
/// <see cref="JobKind.Duplicates"/> as a job (owner review 2, R10): the archive's groups of photos sharing a hash, counted and
/// the largest listed in the job log. Read-only: the Archive screen's Duplicates tab and the maintenance job's duplicate flags
/// stay what acts on them. This makes the kind runnable on the server too (scheduled reports).
/// </summary>
internal sealed class DuplicatesJobHandler(ChronosDatabase db, ArchiveMaintenance maintenance) : IJobHandler
{
/// <summary>Groups listed one per log line, the largest first; the summary counts them all.</summary>
private const int ListedGroups = 20;
public JobKind Kind => JobKind.Duplicates;
public async Task RunAsync(JobContext context)
{
var archive = await JobArchive.LoadAsync(db, context.Job, context.Cancellation).ConfigureAwait(false);
await context.ReportAsync(0, 1).ConfigureAwait(false);
var groups = await maintenance.FindDuplicatesAsync(archive.Id, context.Cancellation).ConfigureAwait(false);
foreach (var group in groups.OrderByDescending(g => g.Frames.Count).ThenBy(g => g.Frames[0].RelativePath, StringComparer.Ordinal).Take(ListedGroups))
context.Log(Loc.L("Archive.Log.DuplicateGroup", group.Frames[0].RelativePath, group.Frames.Count - 1));
context.Log(Loc.L("Archive.Log.DuplicatesDone", groups.Count, groups.Sum(g => g.Frames.Count - 1)));
context.Log(Loc.L("Archive.Log.ReportOnly"));
await context.ReportAsync(1, 1).ConfigureAwait(false);
}
}
/// <summary>
/// <see cref="JobKind.Orphans"/> as a job (owner review 2, R10): where the index and the disk disagree — photos the index
/// does not list, frames whose file is gone, sequences without their folder, folders not indexed yet — counted and listed in
/// the job log. Read-only: the Archive screen's fixes and a scan stay what acts on them. The archive must be reachable.
/// </summary>
internal sealed class OrphansJobHandler(ChronosDatabase db, ArchiveMaintenance maintenance) : IJobHandler
{
/// <summary>Folders listed one per log line; the summary counts them all.</summary>
private const int ListedFolders = 20;
public JobKind Kind => JobKind.Orphans;
public async Task RunAsync(JobContext context)
{
var archive = await JobArchive.LoadAsync(db, context.Job, context.Cancellation).ConfigureAwait(false);
await context.ReportAsync(0, 1).ConfigureAwait(false);
var report = await maintenance.FindOrphansAsync(archive, context.Cancellation).ConfigureAwait(false);
foreach (var missing in report.MissingSequences.Take(ListedFolders))
context.Log(Loc.L("Archive.Log.FolderMissing", missing.Folder));
foreach (var folder in report.UnindexedFolders.Take(ListedFolders))
context.Log(Loc.L("Archive.Log.FolderUnindexed", folder));
context.Log(Loc.L("Archive.Log.Orphans", report.UnindexedFiles, report.MissingFiles));
context.Log(Loc.L("Archive.Log.OrphanFolders", report.MissingSequences.Count, report.UnindexedFolders.Count));
context.Log(Loc.L("Archive.Log.ReportOnly"));
await context.ReportAsync(1, 1).ConfigureAwait(false);
}
}
@@ -38,6 +38,19 @@ public sealed record ArchiveServiceOptions
/// </summary>
public Func<long> MemoryBudget { get; init; } = () => DefaultMemoryBudget;
/// <summary>
/// The host's own clean-up steps (the server's uploads sweep, the desktop's cache trim), run by
/// <see cref="Core.Model.JobKind.Cleanup"/> jobs after the shared ones of <see cref="Housekeeping.CleanupSteps"/> when a
/// schedule names them (owner review 2, R10). A name the shared steps use already is ignored.
/// </summary>
public IReadOnlyList<Housekeeping.ICleanupStep> CleanupSteps { get; init; } = [];
/// <summary>
/// Folder of the copies <see cref="Core.Model.JobKind.Backup"/> jobs make; null: the <c>backups</c> folder next to the
/// SQLite index (<see cref="DatabaseBackups.DefaultDirectory"/>), where the desktop and the server keep them.
/// </summary>
public string? BackupDirectory { get; init; }
/// <summary>Half the logical cores, at least one: the parallelism when the host sets none.</summary>
public static int DefaultParallelism => Math.Max(1, Environment.ProcessorCount / 2);
+4
View File
@@ -22,6 +22,7 @@ public abstract class ChronosRepositories
Tags = new TagRepository(access);
Audit = new AuditRepository(access);
Uploads = new UploadRepository(access);
Schedules = new ScheduleRepository(access);
}
public ArchiveRepository Archives { get; }
@@ -37,6 +38,9 @@ public abstract class ChronosRepositories
public TagRepository Tags { get; }
public AuditRepository Audit { get; }
public UploadRepository Uploads { get; }
/// <summary>Scheduled jobs (owner review 2, R10).</summary>
public ScheduleRepository Schedules { get; }
}
/// <summary>
+68 -36
View File
@@ -13,22 +13,43 @@ public sealed record DatabaseBackup(string Path, DateTimeOffset Created, long By
public sealed record DatabaseSummary(int SchemaVersion, int Archives, int Sequences, long Photos);
/// <summary>
/// Backups of the SQLite index (BRIEF §6.2): a <c>VACUUM INTO</c> copy made once a day while the host runs (at start
/// when the newest copy is a day old, then checked every hour), the three newest kept; and their restore from
/// Settings › Advanced. A restore never swaps the file under a running host: the chosen copy is staged next to the
/// index and replaces it at the next start, before the host opens the index (so it also recovers an index that no
/// longer opens), once the index it replaces has been kept.
/// Backups of the SQLite index (BRIEF §6.2): <c>VACUUM INTO</c> copies in the backups folder, made by the
/// <see cref="Core.Model.JobKind.Backup"/> jobs of the hosts' <c>index-backup</c> system schedule (owner review 2, R10: every
/// day on the desktop, at 03:00 on the server; its recurrence and Copies kept can be edited, three by default), by Back up
/// now, and of the index a restore replaces. Every copy keeps as many as the backup schedules keep
/// (<see cref="KeptAsync"/>). A restore, from Settings › Advanced, never swaps the file under a running host: the chosen
/// copy is staged next to the index and replaces it at the next start, before the host opens the index (so it also
/// recovers an index that no longer opens), once the index it replaces has been kept.
/// </summary>
public static partial class DatabaseBackups
{
/// <summary>Copies kept (BRIEF §6.2: ×3).</summary>
/// <summary>Copies kept by default (BRIEF §6.2: ×3).</summary>
public const int Keep = 3;
/// <summary>Age of the newest copy from which the next one is due.</summary>
public static readonly TimeSpan Interval = TimeSpan.FromDays(1);
/// <summary>The hosts' system schedule that makes the copies.</summary>
public const string ScheduleKey = "index-backup";
/// <summary>How often a running host checks whether a copy is due.</summary>
public static readonly TimeSpan CheckInterval = TimeSpan.FromHours(1);
/// <summary>Name of the folder next to the index that holds its copies (the desktop's and the server's).</summary>
public const string DirectoryName = "backups";
/// <summary>The backups folder of the index at <paramref name="databasePath"/>: <c>backups</c> next to it.</summary>
public static string DefaultDirectory(string databasePath) =>
Path.Combine(Path.GetDirectoryName(Path.GetFullPath(databasePath)) ?? ".", DirectoryName);
/// <summary>
/// Why <paramref name="db"/> cannot be copied by <see cref="ChronosDatabase.BackupAsync"/> (a <see cref="Scheduling.ScheduleUnavailable"/>
/// code: <c>postgres</c>, or <c>no-index-file</c> for an index in memory); null for an SQLite index file.
/// </summary>
public static string? Unavailable(ChronosDatabase db)
{
ArgumentNullException.ThrowIfNull(db);
return db.Database switch
{
SqliteDatabase { Path: not null } => null,
SqliteDatabase => Scheduling.ScheduleUnavailable.NoIndexFile,
_ => Scheduling.ScheduleUnavailable.Postgres,
};
}
/// <summary>
/// The copies of the index at <paramref name="databasePath"/> in <paramref name="directory"/>, newest first. Their
@@ -58,39 +79,48 @@ public static partial class DatabaseBackups
return backups;
}
/// <summary>True when there is no copy yet or the newest one is at least <see cref="Interval"/> old.</summary>
public static bool IsDue(IReadOnlyList<DatabaseBackup> backups, DateTimeOffset now) => backups.Count == 0 || now - backups[0].Created >= Interval;
/// <summary>
/// Makes the daily copy of a SQLite index into <paramref name="directory"/> until <paramref name="cancellationToken"/>
/// is cancelled: now when one is due, then whenever an hourly check finds one due. A failed copy is logged and tried
/// again at the next check. Returns at once for PostgreSQL, which its own server tools back up.
/// 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"/>): 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 async Task RunDailyAsync(ChronosDatabase db, string directory, TimeProvider? time = null, CancellationToken cancellationToken = default)
public static DateTimeOffset? Newest(ChronosDatabase db, string? directory)
{
if (db.Database is not SqliteDatabase { Path: { } path }) return;
var clock = time ?? TimeProvider.System;
using var timer = new PeriodicTimer(CheckInterval, clock);
ArgumentNullException.ThrowIfNull(db);
if (db.Database is not SqliteDatabase { Path: { } path }) return null;
try
{
do
{
try
{
if (IsDue(List(directory, path), clock.GetUtcNow())) await db.BackupAsync(directory, Keep, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
{
Log.Warning("backup", $"The daily index backup into {directory} failed; it is tried again within the hour", ex);
}
}
while (await timer.WaitForNextTickAsync(cancellationToken).ConfigureAwait(false));
return List(directory ?? DefaultDirectory(path), path) is [var newest, ..] ? newest.Created : null;
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return null;
}
}
/// <summary>
/// How many copies the backups folder keeps: the largest Copies kept of the backup schedules, the <see cref="ScheduleKey"/>
/// system schedule's among them, enabled or not (<see cref="Keep"/> with none). Every copy prunes to it, so Back up now, the
/// copy kept before a restore and a schedule that keeps fewer never delete copies another schedule keeps.
/// </summary>
public static async Task<int> KeptAsync(ChronosDatabase db, CancellationToken cancellationToken = default) =>
await ScheduledKeepAsync(db, cancellationToken).ConfigureAwait(false) is > 0 and var kept ? kept : Keep;
/// <summary>The largest Copies kept of the backup schedules (1 to <see cref="Housekeeping.BackupJobHandler.MaxKeep"/>); 0 without any.</summary>
internal static async Task<int> ScheduledKeepAsync(ChronosDatabase db, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(db);
var kept = 0;
foreach (var schedule in await db.Schedules.ListAsync(cancellationToken).ConfigureAwait(false))
{
if (schedule.Action == Scheduling.ScheduleActions.Backup && Scheduling.ScheduleMapping.Parameters(schedule).Keep is { } keep)
kept = int.Max(kept, int.Clamp(keep, 1, Housekeeping.BackupJobHandler.MaxKeep));
}
return kept;
}
/// <summary>Counts what the index holds (the current one, for the restore's comparison).</summary>
public static async Task<DatabaseSummary> SummarizeAsync(ChronosDatabase db, CancellationToken cancellationToken = default)
{
@@ -174,7 +204,7 @@ public static partial class DatabaseBackups
/// Carries out a staged restore before the host opens the index at <paramref name="databasePath"/>, so it also
/// recovers an index that no longer opens. The staged copy is checked first (<see cref="SummarizeBackupAsync"/>:
/// <c>quick_check</c>, open, migration). The index as it is now is kept in <paramref name="backupDirectory"/>: as a
/// fresh <c>VACUUM INTO</c> copy among the daily ones, or, when it cannot be read, copied there whole (with its WAL) as
/// fresh <c>VACUUM INTO</c> copy among the others, or, when it cannot be read, copied there whole (with its WAL) as
/// <c>&lt;name&gt;-replaced-&lt;stamp&gt;.db</c>, outside the rotation, so it never pushes a good copy out. Only then is
/// the staged copy renamed over the index: the rename consumes it, so it is never applied twice. The host's open then
/// migrates it to this build's schema. False when none was staged.
@@ -209,14 +239,16 @@ public static partial class DatabaseBackups
/// <summary>
/// The index about to be replaced, kept in <paramref name="backupDirectory"/>: a <c>VACUUM INTO</c> copy when it opens,
/// else the file itself with its WAL, set aside under a name the pruning of the daily copies never matches.
/// pruning to what its backup schedules keep (<see cref="KeptAsync"/>), else the file itself with its WAL, set aside under
/// a name the pruning of the copies never matches.
/// </summary>
private static async Task<string> KeepAsync(string path, string backupDirectory, CancellationToken cancellationToken)
{
try
{
await using var current = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(path), cancellationToken).ConfigureAwait(false);
return await current.BackupAsync(backupDirectory, Keep, cancellationToken).ConfigureAwait(false);
var keep = await KeptAsync(current, cancellationToken).ConfigureAwait(false);
return await current.BackupAsync(backupDirectory, keep, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is DatabaseException or SchemaTooNewException)
{
@@ -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,80 @@
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"/>, or more when a backup schedule keeps more (one folder, one
/// retention: <see cref="DatabaseBackups.KeptAsync"/>). 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 own = Math.Clamp(ArchiveJobJson.Read(context.Job, ArchiveJobJson.Default.BackupParameters, new BackupParameters(DatabaseBackups.Keep)).Keep, 1, MaxKeep);
var keep = int.Max(own, await DatabaseBackups.ScheduledKeepAsync(db, context.Cancellation).ConfigureAwait(false));
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)}.");
}
}
+18 -9
View File
@@ -25,9 +25,6 @@ public sealed record JobEngineOptions
/// <summary>Fallback poll for jobs enqueued by other processes; also how often the priority queue is reviewed.</summary>
public TimeSpan PollInterval { get; init; } = TimeSpan.FromSeconds(3);
/// <summary>Finished jobs older than this are purged (BRIEF §14.6: 90 days).</summary>
public TimeSpan HistoryRetention { get; init; } = TimeSpan.FromDays(90);
/// <summary>Clock of the throughput windows and the checkpoint interval (tests pass their own).</summary>
public TimeProvider Time { get; init; } = TimeProvider.System;
@@ -38,7 +35,8 @@ public sealed record JobEngineOptions
/// <summary>
/// Persistent job queue runner (BRIEF §14.6, amended by owner review 1): one worker claims queued jobs from the database
/// in claim order, runs the registered handler, checkpoints progress, and survives crashes (running jobs are requeued at
/// start with their checkpoints). Used by the desktop client (local mode) and the server. Jobs an
/// start with their checkpoints). Used by the desktop client (local mode) and the server. The history of finished jobs is
/// purged by the housekeeping schedule's job-history clean-up step, not here (owner review 2, R10). Jobs an
/// <see cref="ISelectiveJobHandler"/> declines stay queued for other claimers. With the priority queue on
/// (<see cref="JobEngineOptions.PriorityQueue"/>) a queued job of a higher level makes the running job of a lower level
/// yield: it goes back to the queue with its checkpoint and resumes by itself afterwards, never interrupted by the
@@ -87,12 +85,11 @@ public sealed class JobEngine : IAsyncDisposable
/// <summary>The priority queue as it is now (<see cref="JobEngineOptions.PriorityQueue"/>).</summary>
public JobPriorityQueue PriorityQueue => Options.PriorityQueue?.Invoke() ?? JobPriorityQueue.Off;
/// <summary>Requeues this worker's interrupted jobs, purges old history and starts the worker and the queue's review.</summary>
/// <summary>Requeues this worker's interrupted jobs and starts the worker and the queue's review.</summary>
public async Task StartAsync(CancellationToken cancellationToken = default)
{
var requeued = await _db.Jobs.RequeueRunningAsync(Options.WorkerId, cancellationToken).ConfigureAwait(false);
if (requeued > 0) Log.Info("jobs", $"Requeued {requeued} interrupted job(s)");
await _db.Jobs.PurgeHistoryAsync(DateTimeOffset.UtcNow - Options.HistoryRetention, cancellationToken).ConfigureAwait(false);
// Only kinds this engine can run: an empty filter would claim (and fail) every job, render-node work included.
_kinds = [.. (Options.Kinds ?? _handlers.Keys).Where(_handlers.ContainsKey).Distinct()];
_selective = _kinds.Select(k => _handlers[k]).OfType<ISelectiveJobHandler>().ToDictionary(h => h.Kind);
@@ -118,7 +115,18 @@ public sealed class JobEngine : IAsyncDisposable
/// <summary>Queues a job and wakes a worker.</summary>
public Task<Job> EnqueueAsync(JobKind kind, IReadOnlyList<Guid> targets, string? targetLabel = null, string? parametersJson = null,
JobPriority priority = JobPriority.Normal, Guid? createdBy = null, CancellationToken cancellationToken = default) =>
EnqueueAsync(Guid.CreateVersion7(), kind, targets, targetLabel, parametersJson, priority, createdBy, cancellationToken);
EnqueueAsync(Guid.CreateVersion7(), kind, targets, targetLabel, parametersJson, priority, createdBy, null, cancellationToken);
/// <summary>Queues a job that the schedule <paramref name="scheduleId"/> fired (<see cref="Job.ScheduleId"/>) and wakes a worker.</summary>
public Task<Job> EnqueueAsync(JobKind kind, IReadOnlyList<Guid> targets, string? targetLabel, string? parametersJson, JobPriority priority,
Guid? createdBy, Guid? scheduleId, CancellationToken cancellationToken = default) =>
EnqueueAsync(Guid.CreateVersion7(), kind, targets, targetLabel, parametersJson, priority, createdBy, scheduleId, cancellationToken);
/// <summary>
/// True when this engine runs jobs of <paramref name="kind"/>: it has a handler for it and <see cref="JobEngineOptions.Kinds"/>
/// does not leave it out. Known before <see cref="StartAsync"/>, so a host that does not start the engine still answers.
/// </summary>
public bool CanRun(JobKind kind) => _handlers.ContainsKey(kind) && (Options.Kinds is null || Options.Kinds.Contains(kind));
/// <summary>Cancels a queued or running job; a running handler observes its token.</summary>
public Task CancelAsync(Guid id, CancellationToken cancellationToken = default) => TransitionAsync(id, JobState.Cancelled, cancellationToken);
@@ -212,7 +220,7 @@ public sealed class JobEngine : IAsyncDisposable
var id = Guid.CreateVersion7();
// Known before the job is queued, so the review its queueing starts already leaves the parent running.
if (_running.TryGetValue(parent, out var run)) run.FollowUps.TryAdd(id, 0);
return await EnqueueAsync(id, kind, targets, label, parametersJson, priority, createdBy, cancellationToken).ConfigureAwait(false);
return await EnqueueAsync(id, kind, targets, label, parametersJson, priority, createdBy, null, cancellationToken).ConfigureAwait(false);
}
internal void StopJob(Guid id)
@@ -242,7 +250,7 @@ public sealed class JobEngine : IAsyncDisposable
}
private async Task<Job> EnqueueAsync(Guid id, JobKind kind, IReadOnlyList<Guid> targets, string? targetLabel, string? parametersJson,
JobPriority priority, Guid? createdBy, CancellationToken cancellationToken)
JobPriority priority, Guid? createdBy, Guid? scheduleId, CancellationToken cancellationToken)
{
var job = new Job
{
@@ -255,6 +263,7 @@ public sealed class JobEngine : IAsyncDisposable
State = JobState.Queued,
CreatedBy = createdBy,
Created = DateTimeOffset.UtcNow,
ScheduleId = scheduleId,
};
await _db.Jobs.EnqueueAsync(job, cancellationToken).ConfigureAwait(false);
JobChanged?.Invoke(job);
+6 -1
View File
@@ -21,7 +21,10 @@ public enum JobKindPriority
/// </summary>
public sealed record JobPriorityQueue
{
/// <summary>The levels a kind has unless the user changed it: renders, imports and downloads first; the long passes that resume anywhere last.</summary>
/// <summary>
/// The levels a kind has unless the user changed it: renders, imports and downloads first; the long passes that resume
/// anywhere, and the housekeeping of the schedules (backups, clean-ups), last.
/// </summary>
public static IReadOnlyDictionary<JobKind, JobKindPriority> DefaultLevels { get; } = new Dictionary<JobKind, JobKindPriority>
{
[JobKind.Render] = JobKindPriority.High,
@@ -29,6 +32,8 @@ public sealed record JobPriorityQueue
[JobKind.Download] = JobKindPriority.High,
[JobKind.Verify] = JobKindPriority.Low,
[JobKind.Proxies] = JobKindPriority.Low,
[JobKind.Backup] = JobKindPriority.Low,
[JobKind.Cleanup] = JobKindPriority.Low,
};
/// <summary>The strict queue: no levels, no interruptions.</summary>
+1
View File
@@ -56,6 +56,7 @@ public static class JobWire
Created = dto.Created,
Started = dto.Started,
Finished = dto.Finished,
ScheduleId = dto.ScheduleId,
};
}
@@ -0,0 +1,27 @@
-- Scheduled jobs (owner review 2, R10): one row per schedule, the timers a host used to run out of sight included as
-- system schedules (system_key set, seeded by the host at start, never here). next_run is claimed by compare-and-set,
-- so one process fires each run. Jobs remember the schedule that queued them. Mirrors sqlite/0007_schedules.sql.
CREATE TABLE schedules (
id uuid NOT NULL PRIMARY KEY,
system_key text COLLATE "C" UNIQUE,
name text NOT NULL,
action text NOT NULL,
target text NOT NULL DEFAULT 'current',
parameters_json jsonb,
recurrence text NOT NULL,
catch_up boolean NOT NULL DEFAULT TRUE,
priority integer NOT NULL DEFAULT 0,
enabled boolean NOT NULL DEFAULT TRUE,
next_run timestamptz,
last_run timestamptz,
last_job_id uuid,
last_outcome text,
created_by uuid,
created timestamptz NOT NULL,
updated timestamptz NOT NULL
);
CREATE INDEX ix_schedules_due ON schedules (enabled, next_run);
ALTER TABLE jobs ADD COLUMN schedule_id uuid;
CREATE INDEX ix_jobs_schedule ON jobs (schedule_id, created);
@@ -0,0 +1,27 @@
-- Scheduled jobs (owner review 2, R10): one row per schedule, the timers a host used to run out of sight included as
-- system schedules (system_key set, seeded by the host at start, never here). next_run is claimed by compare-and-set,
-- so one process fires each run. Jobs remember the schedule that queued them. Mirrors postgres/0007_schedules.sql.
CREATE TABLE schedules (
id TEXT NOT NULL PRIMARY KEY,
system_key TEXT UNIQUE,
name TEXT NOT NULL,
action TEXT NOT NULL,
target TEXT NOT NULL DEFAULT 'current',
parameters_json TEXT,
recurrence TEXT NOT NULL,
catch_up INTEGER NOT NULL DEFAULT 1,
priority INTEGER NOT NULL DEFAULT 0,
enabled INTEGER NOT NULL DEFAULT 1,
next_run TEXT,
last_run TEXT,
last_job_id TEXT,
last_outcome TEXT,
created_by TEXT,
created TEXT NOT NULL,
updated TEXT NOT NULL
);
CREATE INDEX ix_schedules_due ON schedules (enabled, next_run);
ALTER TABLE jobs ADD COLUMN schedule_id TEXT;
CREATE INDEX ix_jobs_schedule ON jobs (schedule_id, created);
@@ -2,7 +2,7 @@ using Chronos.Core.Model;
namespace Chronos.Data.Repositories;
/// <summary>Append-only record of who did what (BRIEF §5 AuditLog, §14.2).</summary>
/// <summary>Append-only record of who did what (BRIEF §5 AuditLog, §14.2); old entries leave only through a retention (<see cref="PurgeAsync"/>).</summary>
public sealed class AuditRepository
{
private const string Columns = "id, at, user_id, username, action, target_kind, target_id, details, remote_address";
@@ -16,6 +16,10 @@ public sealed class AuditRepository
[entry.Id, entry.At, entry.UserId, entry.Username, entry.Action, entry.TargetKind, entry.TargetId, entry.Details, entry.RemoteAddress],
cancellationToken).ConfigureAwait(false);
/// <summary>Deletes the entries written before <paramref name="before"/> (the audit retention's clean-up step); returns how many.</summary>
public Task<int> PurgeAsync(DateTimeOffset before, CancellationToken cancellationToken = default) =>
_db.ExecuteAsync("DELETE FROM audit_log WHERE at < $1", [before], cancellationToken);
/// <summary>Entries newest first, optionally of one user.</summary>
public Task<Page<AuditEntry>> ListAsync(Guid? userId = null, int limit = 100, string? cursor = null, CancellationToken cancellationToken = default) =>
ListAsync(userId, action: null, limit, cursor, cancellationToken);
+75 -3
View File
@@ -15,7 +15,11 @@ public sealed class JobRepository
{
private const string Columns =
"id, kind, target_ids, target_label, parameters_json, state, priority, progress_done, progress_total, items_per_second, " +
"eta_seconds, checkpoint, log_tail, created_by, node_id, attempts, error, created, started, finished";
"eta_seconds, checkpoint, log_tail, created_by, node_id, attempts, error, created, started, finished, schedule_id";
/// <summary>The states of a job that has not ended: queued, running, paused.</summary>
private static readonly string PendingStates =
string.Join(", ", new[] { JobState.Queued, JobState.Running, JobState.Paused }.Select(s => ((int)s).ToString(CultureInfo.InvariantCulture)));
private readonly DbAccess _db;
@@ -23,11 +27,11 @@ public sealed class JobRepository
public async Task EnqueueAsync(Job job, CancellationToken cancellationToken = default) =>
await _db.ExecuteAsync(
$"INSERT INTO jobs ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20)",
$"INSERT INTO jobs ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21)",
[
job.Id, (int)job.Kind, string.Join(',', job.TargetIds), job.TargetLabel, DbParam.Json(job.ParametersJson), (int)job.State,
(int)job.Priority, job.ProgressDone, job.ProgressTotal, job.ItemsPerSecond, job.Eta?.TotalSeconds, job.Checkpoint, job.LogTail,
job.CreatedBy, job.NodeId, job.Attempts, job.Error, job.Created, job.Started, job.Finished,
job.CreatedBy, job.NodeId, job.Attempts, job.Error, job.Created, job.Started, job.Finished, job.ScheduleId,
], cancellationToken).ConfigureAwait(false);
public Task<Job?> GetAsync(Guid id, CancellationToken cancellationToken = default) =>
@@ -173,6 +177,73 @@ public sealed class JobRepository
$"SELECT count(*) FROM jobs WHERE state = {(int)JobState.Queued} AND kind = $1 AND target_ids = $2",
[(int)kind, targetId.ToString()], cancellationToken).ConfigureAwait(false) > 0;
/// <summary>
/// True when a job of one of <paramref name="kinds"/> is queued, running or paused; with <paramref name="targetIds"/>,
/// only such a job that targets at least one of them (an archive, sequences) counts. A schedule does not queue its
/// action again while one waits (owner review 2, R10).
/// </summary>
public async Task<bool> HasPendingAsync(IReadOnlyCollection<JobKind> kinds, IReadOnlyCollection<Guid>? targetIds = null,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(kinds);
if (kinds.Count == 0 || targetIds is { Count: 0 }) return false;
var p = new SqlParameters();
var sql = $"SELECT count(*) FROM jobs WHERE state IN ({PendingStates}) AND kind IN ({KindList(kinds)})";
// Target ids are stored comma-joined as lower-case text, which never holds a LIKE wildcard.
if (targetIds is not null)
sql += $" AND ({string.Join(" OR ", targetIds.Distinct().Select(id => $"target_ids LIKE {p.Add(SqlDialect.ContainsPattern(id.ToString()))} ESCAPE '\\'"))})";
return await _db.ScalarAsync<long>(sql, p.ToArray(), cancellationToken).ConfigureAwait(false) > 0;
}
/// <summary>The targets of the queued, running and paused jobs of <paramref name="kind"/> (the newest 5000 such jobs).</summary>
public Task<HashSet<Guid>> ListPendingTargetsAsync(JobKind kind, CancellationToken cancellationToken = default) =>
_db.RunAsync(async session =>
{
var rows = await session.QueryListAsync(
$"SELECT target_ids FROM jobs WHERE kind = $1 AND state IN ({PendingStates}) ORDER BY created DESC, id DESC LIMIT 5000",
[(int)kind], r => r.GetString(0), cancellationToken).ConfigureAwait(false);
var ids = new HashSet<Guid>();
foreach (var text in rows)
{
if (text.Length == 0) continue;
foreach (var id in text.Split(',')) ids.Add(Guid.Parse(id));
}
return ids;
}, cancellationToken);
/// <summary>The jobs the schedule <paramref name="scheduleId"/> queued, newest first.</summary>
public Task<IReadOnlyList<Job>> ListByScheduleAsync(Guid scheduleId, int limit = 20, CancellationToken cancellationToken = default) =>
_db.ListAsync($"SELECT {Columns} FROM jobs WHERE schedule_id = $1 ORDER BY created DESC, id DESC LIMIT $2",
[scheduleId, Cursor.ClampLimit(limit)], Map, cancellationToken);
/// <summary>
/// The jobs the schedule <paramref name="scheduleId"/> queued, newest first, a page at a time (the runs a schedule's
/// row lists in the admin panel); <paramref name="cursor"/> continues after the previous page.
/// </summary>
public Task<Page<Job>> PageByScheduleAsync(Guid scheduleId, int limit = 20, string? cursor = null, CancellationToken cancellationToken = default)
{
var p = new SqlParameters();
var where = $"schedule_id = {p.Add(scheduleId)}";
if (cursor is not null)
{
var (value, id) = Cursor.Decode("schedule-runs", cursor);
where += " AND " + Cursor.After("created", "id", descending: true, value, id, p.Add);
}
var take = Cursor.ClampLimit(limit);
var sql = $"SELECT {Columns} FROM jobs WHERE {where} ORDER BY created DESC, id DESC LIMIT {p.Add(take + 1)}";
return _db.RunAsync(async session =>
{
var jobs = await session.QueryListAsync(sql, p.ToArray(), Map, cancellationToken).ConfigureAwait(false);
string? next = null;
if (jobs.Count > take)
{
jobs.RemoveAt(take);
next = Cursor.Encode("schedule-runs", jobs[^1].Created, jobs[^1].Id);
}
return new Page<Job>(jobs, next);
}, cancellationToken);
}
/// <summary>
/// Claims one specific queued job for <paramref name="nodeId"/> (render nodes pick by capability); null when another
/// claimer was faster or the job is no longer queued.
@@ -245,5 +316,6 @@ public sealed class JobRepository
Created = r.GetDateTimeOffset(17),
Started = r.GetDateTimeOffsetOrNull(18),
Finished = r.GetDateTimeOffsetOrNull(19),
ScheduleId = r.GetGuidOrNull(20),
};
}
@@ -0,0 +1,171 @@
using Chronos.Core.Model;
using Chronos.Data.Scheduling;
namespace Chronos.Data.Repositories;
/// <summary>
/// Scheduled jobs (owner review 2, R10). A run is claimed by moving <c>next_run</c> with a compare-and-set
/// (<see cref="TryAdvanceAsync"/>), so when several processes share one database (server instances on one PostgreSQL)
/// exactly one fires it. System schedules are seeded without touching rows that exist (<see cref="EnsureSystemAsync"/>), so
/// what the user changed stays, and they are never deleted (<see cref="DeleteAsync"/>).
/// </summary>
public sealed class ScheduleRepository
{
private const string Columns =
"id, system_key, name, action, target, parameters_json, recurrence, catch_up, priority, enabled, next_run, last_run, last_job_id, " +
"last_outcome, created_by, created, updated";
private const string InsertSql =
$"INSERT INTO schedules ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17)";
/// <summary>System schedules first, then the others, oldest first.</summary>
private const string Order = "CASE WHEN system_key IS NULL THEN 1 ELSE 0 END, created, id";
private readonly DbAccess _db;
internal ScheduleRepository(DbAccess db) => _db = db;
/// <summary>Every schedule: the system ones first, then the others, oldest first.</summary>
public Task<IReadOnlyList<Schedule>> ListAsync(CancellationToken cancellationToken = default) =>
_db.ListAsync($"SELECT {Columns} FROM schedules ORDER BY {Order}", [], Map, cancellationToken);
public Task<Schedule?> GetAsync(Guid id, CancellationToken cancellationToken = default) =>
_db.SingleAsync($"SELECT {Columns} FROM schedules WHERE id = $1", [id], Map, cancellationToken);
public Task<Schedule?> GetBySystemKeyAsync(string systemKey, CancellationToken cancellationToken = default) =>
_db.SingleAsync($"SELECT {Columns} FROM schedules WHERE system_key = $1", [systemKey], Map, cancellationToken);
/// <summary>Adds a schedule; a <see cref="Schedule.SystemKey"/> another row has already fails (unique).</summary>
public async Task InsertAsync(Schedule schedule, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(schedule);
await _db.ExecuteAsync(InsertSql, Values(schedule), cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Stores what a user edits — name, action, target, parameters, recurrence, catch-up, priority, enabled — and the update
/// time; with <paramref name="setNextRun"/> the next run too, otherwise it stays as stored (a run the scheduler claims
/// meanwhile is not undone). The key, the creation and the last run stay as stored. False when the schedule is gone.
/// </summary>
public async Task<bool> UpdateAsync(Schedule schedule, bool setNextRun = true, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(schedule);
return await _db.ExecuteAsync(
"UPDATE schedules SET name = $2, action = $3, target = $4, parameters_json = $5, recurrence = $6, catch_up = $7, priority = $8, " +
$"enabled = $9, updated = $10{(setNextRun ? ", next_run = $11" : string.Empty)} WHERE id = $1",
[
schedule.Id, schedule.Name, schedule.Action, schedule.Target, DbParam.Json(schedule.ParametersJson), schedule.Recurrence,
schedule.CatchUp, (int)schedule.Priority, schedule.Enabled, schedule.Updated, .. setNextRun ? new DbParam[] { schedule.NextRun } : [],
], cancellationToken).ConfigureAwait(false) > 0;
}
/// <summary>Deletes a schedule a user created; false when it is unknown or a system schedule (those are disabled, never deleted).</summary>
public async Task<bool> DeleteAsync(Guid id, CancellationToken cancellationToken = default) =>
await _db.ExecuteAsync("DELETE FROM schedules WHERE id = $1 AND system_key IS NULL", [id], cancellationToken).ConfigureAwait(false) > 0;
/// <summary>
/// Inserts each system schedule whose key no row has yet (<c>INSERT … ON CONFLICT (system_key) DO NOTHING</c>), with
/// no next run (the scheduler computes it), or due at <paramref name="now"/> when it is enabled and its work was last
/// done a period or more before (<see cref="SystemSchedule.LastDone"/>); rows that exist keep whatever the user changed.
/// Rows added together are stamped a microsecond apart, so listings keep the host's order. Returns how many were added.
/// </summary>
public Task<int> EnsureSystemAsync(IEnumerable<SystemSchedule> schedules, DateTimeOffset now, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(schedules);
var rows = schedules.Select((s, i) => FromSystem(s, now.AddTicks(i * TimeSpan.TicksPerMicrosecond)) with
{
NextRun = s.Enabled && s.LastDone is { } done && now - done >= s.Recurrence.Period ? now : null,
}).ToList();
return rows.Count == 0 ? Task.FromResult(0) : _db.InTransactionAsync(async session =>
{
var added = 0;
foreach (var row in rows)
added += await session.ExecuteAsync(InsertSql + " ON CONFLICT (system_key) DO NOTHING", Values(row), cancellationToken).ConfigureAwait(false);
return added;
}, cancellationToken);
}
/// <summary>
/// Puts the system schedule <paramref name="systemKey"/> back to <paramref name="defaults"/> (name, action, parameters,
/// recurrence, catch-up, priority, enabled) with no next run, so the scheduler computes it again; its history stays.
/// False when no row has that key.
/// </summary>
public async Task<bool> ResetSystemAsync(string systemKey, SystemSchedule defaults, DateTimeOffset now, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(defaults);
var row = FromSystem(defaults, now);
return await _db.ExecuteAsync(
"UPDATE schedules SET name = $2, action = $3, target = $4, parameters_json = $5, recurrence = $6, catch_up = $7, priority = $8, " +
"enabled = $9, next_run = NULL, updated = $10 WHERE system_key = $1",
[
systemKey, row.Name, row.Action, row.Target, DbParam.Json(row.ParametersJson), row.Recurrence, row.CatchUp, (int)row.Priority, row.Enabled,
now,
], cancellationToken).ConfigureAwait(false) > 0;
}
/// <summary>Enabled schedules whose next run is at or before <paramref name="nowUtc"/>, the longest due first.</summary>
public Task<IReadOnlyList<Schedule>> ListDueAsync(DateTimeOffset nowUtc, CancellationToken cancellationToken = default) =>
_db.ListAsync($"SELECT {Columns} FROM schedules WHERE enabled = TRUE AND next_run IS NOT NULL AND next_run <= $1 ORDER BY next_run, id",
[nowUtc], Map, cancellationToken);
/// <summary>
/// Moves an enabled schedule's next run from <paramref name="expectedNextRun"/> (null: none yet) to
/// <paramref name="nextRun"/>, only if it still is <paramref name="expectedNextRun"/>: true for the one caller that won.
/// Claiming a due run this way is what keeps two processes from both firing it.
/// </summary>
public async Task<bool> TryAdvanceAsync(Guid id, DateTimeOffset? expectedNextRun, DateTimeOffset? nextRun, CancellationToken cancellationToken = default) =>
await (expectedNextRun is { } expected
? _db.ExecuteAsync("UPDATE schedules SET next_run = $2 WHERE id = $1 AND enabled = TRUE AND next_run = $3", [id, nextRun, expected], cancellationToken)
: _db.ExecuteAsync("UPDATE schedules SET next_run = $2 WHERE id = $1 AND enabled = TRUE AND next_run IS NULL", [id, nextRun], cancellationToken))
.ConfigureAwait(false) > 0;
/// <summary>
/// Records a run: when (<paramref name="atUtc"/>), what it did (<see cref="ScheduleOutcome"/>) and the first job it
/// queued; a run that queued nothing keeps the previous job, so the next run still sees whether it is pending.
/// </summary>
public async Task<bool> RecordOutcomeAsync(Guid id, Guid? jobId, string outcome, DateTimeOffset atUtc, CancellationToken cancellationToken = default) =>
await _db.ExecuteAsync("UPDATE schedules SET last_run = $2, last_job_id = COALESCE($3, last_job_id), last_outcome = $4 WHERE id = $1",
[id, atUtc, jobId, outcome], cancellationToken).ConfigureAwait(false) > 0;
private static Schedule FromSystem(SystemSchedule system, DateTimeOffset now) => new()
{
Id = Guid.CreateVersion7(),
SystemKey = system.SystemKey,
Name = system.Name,
Action = system.Action,
ParametersJson = ScheduleMapping.ParametersJson(system.Action, system.Parameters),
Recurrence = system.Recurrence.Format(),
CatchUp = system.CatchUp,
Priority = system.Priority,
Enabled = system.Enabled,
Created = now,
Updated = now,
};
private static DbParam[] Values(Schedule s) =>
[
s.Id, s.SystemKey, s.Name, s.Action, s.Target, DbParam.Json(s.ParametersJson), s.Recurrence, s.CatchUp, (int)s.Priority, s.Enabled, s.NextRun,
s.LastRun, s.LastJobId, s.LastOutcome, s.CreatedBy, s.Created, s.Updated,
];
private static Schedule Map(DbRow r) => new()
{
Id = r.GetGuid(0),
SystemKey = r.GetStringOrNull(1),
Name = r.GetString(2),
Action = r.GetString(3),
Target = r.GetString(4),
ParametersJson = r.GetStringOrNull(5),
Recurrence = r.GetString(6),
CatchUp = r.GetBool(7),
Priority = (JobPriority)r.GetInt32(8),
Enabled = r.GetBool(9),
NextRun = r.GetDateTimeOffsetOrNull(10),
LastRun = r.GetDateTimeOffsetOrNull(11),
LastJobId = r.GetGuidOrNull(12),
LastOutcome = r.GetStringOrNull(13),
CreatedBy = r.GetGuidOrNull(14),
Created = r.GetDateTimeOffset(15),
Updated = r.GetDateTimeOffset(16),
};
}
@@ -389,6 +389,21 @@ public sealed class SequenceRepository
}, cancellationToken);
}
/// <summary>
/// The sequences of <paramref name="archiveId"/> a rolling verification checks next (owner review 2, R10): those never
/// verified first, then the longest unverified, at most <paramref name="limit"/>. With <paramref name="verifiedBefore"/>
/// only those never verified or last verified before it are listed. Sequences without frames are left out.
/// </summary>
public Task<IReadOnlyList<Guid>> ListVerifyCandidatesAsync(Guid archiveId, DateTimeOffset? verifiedBefore, int limit,
CancellationToken cancellationToken = default)
{
var p = new SqlParameters();
var where = $"archive_id = {p.Add(archiveId)} AND frame_count > 0";
if (verifiedBefore is { } before) where += $" AND (verified_at IS NULL OR verified_at < {p.Add(before)})";
return _db.ListAsync($"SELECT id FROM sequences WHERE {where} ORDER BY verified_at ASC NULLS FIRST, id LIMIT {p.Add(Math.Max(1, limit))}",
p.ToArray(), r => r.GetGuid(0), cancellationToken);
}
/// <summary>Folder and title of every sequence of an archive, by folder.</summary>
public Task<IReadOnlyList<SequenceLocation>> ListLocationsAsync(Guid archiveId, CancellationToken cancellationToken = default) =>
_db.ListAsync("SELECT id, folder, title FROM sequences WHERE archive_id = $1 ORDER BY folder, id", [archiveId],
@@ -0,0 +1,62 @@
using Chronos.Core.Model;
using Chronos.Protocol;
namespace Chronos.Data.Scheduling;
/// <summary>
/// What a host (the server, the desktop) tells its <see cref="Scheduler"/> (owner review 2, R10): its time zone, the archive
/// schedules work on, the system schedules standing for its timers, the clean-up steps its jobs run, and the actions it
/// cannot run. Called from the scheduler's loop, off any UI thread; members must be thread-safe.
/// </summary>
public interface IScheduleHost
{
/// <summary>The zone of daily, weekly and monthly times: the PC's on the desktop, the container's (TZ) on the server.</summary>
TimeZoneInfo TimeZone { get; }
/// <summary>
/// The archive schedules targeting <c>current</c> work on (the server's archive, the desktop's current one), with its
/// settings as fresh as the host keeps them; null when there is none yet or it cannot be reached. The scheduler probes
/// whether it is online itself.
/// </summary>
ValueTask<Archive?> GetArchiveAsync(CancellationToken cancellationToken);
/// <summary>
/// The system schedules: every timer that queues work on this host, as a visible schedule. Seeded at start by key and
/// never overwritten (the user's edits stay); <see cref="Scheduler.ResetAsync"/> puts one back to these values.
/// </summary>
IReadOnlyList<SystemSchedule> SystemSchedules { get; }
/// <summary>The names of the clean-up steps this host's <see cref="JobKind.Cleanup"/> jobs run (normally those of <c>ArchiveService.CleanupSteps</c>).</summary>
IReadOnlyList<string> CleanupSteps { get; }
/// <summary>
/// Whether a scan whose schedule leaves its <c>deep</c> parameter unset gives the sequences it finds a deep analysis.
/// Read at every run, so the desktop's scans follow Settings › Analysis › After a scan as it is then; false on the server.
/// </summary>
bool DeepAnalysisAfterScan { get; }
/// <summary>
/// Why this host does not run <paramref name="action"/> (a short code, e.g. <c>not-here</c>), or null when it may. Asked
/// before the scheduler's own checks (<see cref="ScheduleUnavailable"/>), for the action list and at every run.
/// </summary>
string? Unavailable(string action);
}
/// <summary>
/// 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), 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,
string Name,
string Action,
ScheduleRecurrence Recurrence,
ScheduleParametersDto? Parameters = null,
bool Enabled = true,
bool CatchUp = true,
JobPriority Priority = JobPriority.Background,
DateTimeOffset? LastDone = null);
@@ -0,0 +1,295 @@
using Chronos.Core.Archiving;
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Housekeeping;
using Chronos.Data.Processing;
using Chronos.Data.Repositories;
using Chronos.Protocol;
namespace Chronos.Data.Scheduling;
/// <summary>Whether a host runs an action, and why not (<see cref="ScheduleUnavailable"/> or the host's own code).</summary>
public sealed record ScheduleActionInfo(string Name, bool Available, string? Reason);
/// <summary>
/// What a schedule's run comes to: the jobs to queue (<see cref="ScheduleOutcome.Queued"/>), or none and why
/// (<see cref="ScheduleOutcome.SkippedPending"/>, <see cref="ScheduleOutcome.SkippedOffline"/>,
/// <see cref="ScheduleOutcome.SkippedNothing"/>, <see cref="ScheduleOutcome.Unavailable"/>).
/// </summary>
public sealed record ScheduleResolution(IReadOnlyList<ArchiveJobRequest> Requests, string Outcome)
{
public static ScheduleResolution Skip(string outcome) => new([], outcome);
public static ScheduleResolution Queue(IReadOnlyList<ArchiveJobRequest> requests) => new(requests, ScheduleOutcome.Queued);
}
/// <summary>What resolving an action needs: the index, the host, which job kinds the host's engine runs, and the time of the run.</summary>
public sealed record ScheduleActionContext(ChronosDatabase Database, IScheduleHost Host, Func<JobKind, bool> CanRun, DateTimeOffset Now);
/// <summary>
/// The actions a schedule can take (owner review 2, R10), shared by the server and the desktop: their names, parameters
/// (<see cref="ScheduleParametersDto"/>, normalised to the fields each reads), availability, and the archive jobs a run
/// queues for the host's current archive. Rebuild and render are not schedulable. Every action that works on an archive
/// skips a run while the archive is missing or offline (or read-only, for one that writes), and while a job doing the same
/// work on it is pending; a run that finds nothing to do queues nothing.
/// </summary>
public static class ScheduleActions
{
/// <summary>
/// Incremental scan of the archive (<c>force</c>: a full one; <c>deep</c>: deep analysis of what it indexes; unset, as the
/// host says at the run, <see cref="IScheduleHost.DeepAnalysisAfterScan"/>).
/// </summary>
public const string Scan = "scan";
/// <summary>Integrity check of the originals, the least recently verified first (<c>olderThanDays</c>, <c>percent</c>).</summary>
public const string Verify = "verify";
/// <summary>Thumbnails of the sequences without them (<c>force</c>: of every sequence).</summary>
public const string Thumbnails = "thumbnails";
/// <summary>Proxies of the sequences without them, when the archive makes proxies (<c>force</c>: of every sequence).</summary>
public const string Proxies = "proxies";
/// <summary>Light analysis of the sequences without a current one (<c>deep</c>: deep analysis of those without one).</summary>
public const string Analysis = "analysis";
/// <summary>The archive's maintenance job (<c>dryRun</c>: report only).</summary>
public const string Maintenance = "maintenance";
/// <summary>A copy of the SQLite index (<c>keep</c>: copies kept). Not on PostgreSQL.</summary>
public const string Backup = "backup";
/// <summary>Clean-up steps (<c>steps</c>, <c>olderThanDays</c>): job history, audit log, trash report, the host's own.</summary>
public const string Cleanup = "cleanup";
/// <summary>Report of the duplicate photos into the job log.</summary>
public const string Duplicates = "duplicates";
/// <summary>Report of where the index and the disk disagree into the job log.</summary>
public const string Orphans = "orphans";
/// <summary>Most days a schedule's age limits accept (ten years).</summary>
public const int MaxDays = 3650;
/// <summary>Sequences per job a run queues: a larger set becomes several jobs.</summary>
public const int SequencesPerJob = 500;
/// <summary>Every action, in the order clients list them.</summary>
public static IReadOnlyList<string> All { get; } = [Scan, Verify, Thumbnails, Proxies, Analysis, Maintenance, Backup, Cleanup, Duplicates, Orphans];
public static bool IsKnown(string? action) => action is not null && All.Contains(action, StringComparer.Ordinal);
/// <summary>The job kinds <paramref name="action"/> queues (analysis: light, or deep with <c>deep</c>); empty for an unknown one.</summary>
public static IReadOnlyList<JobKind> KindsOf(string action) => action switch
{
Scan => [JobKind.Scan],
Verify => [JobKind.Verify],
Thumbnails => [JobKind.Thumbs],
Proxies => [JobKind.Proxies],
Analysis => [JobKind.LightAnalyse, JobKind.DeepAnalyse],
Maintenance => [JobKind.Maintenance],
Backup => [JobKind.Backup],
Cleanup => [JobKind.Cleanup],
Duplicates => [JobKind.Duplicates],
Orphans => [JobKind.Orphans],
_ => [],
};
/// <summary>The parameters a new schedule of <paramref name="action"/> starts with.</summary>
public static ScheduleParametersDto Defaults(string action) => action switch
{
// No deep: a scan follows the host's choice at run time (IScheduleHost.DeepAnalysisAfterScan) unless its schedule sets one.
Scan => new(Force: false),
Verify => new(OlderThanDays: 30, Percent: 100),
Thumbnails or Proxies => new(Force: false),
Analysis => new(Deep: false),
Maintenance => new(DryRun: false),
Backup => new(Keep: DatabaseBackups.Keep),
Cleanup => new(Steps: [CleanupSteps.JobHistory], OlderThanDays: CleanupSteps.DefaultHistoryDays),
_ => new(),
};
/// <summary>
/// <paramref name="parameters"/> reduced to the fields <paramref name="action"/> reads, each missing one taken from
/// <see cref="Defaults"/>; clean-up steps keep their order without repeats.
/// </summary>
public static ScheduleParametersDto Normalize(string action, ScheduleParametersDto? parameters)
{
var p = parameters ?? new ScheduleParametersDto();
var d = Defaults(action);
return action switch
{
Scan => new(Force: p.Force ?? d.Force, Deep: p.Deep),
Verify => new(OlderThanDays: p.OlderThanDays ?? d.OlderThanDays, Percent: p.Percent ?? d.Percent),
Thumbnails or Proxies => new(Force: p.Force ?? d.Force),
Analysis => new(Deep: p.Deep ?? d.Deep),
Maintenance => new(DryRun: p.DryRun ?? d.DryRun),
Backup => new(Keep: p.Keep ?? d.Keep),
Cleanup => new(Steps: p.Steps is { } steps ? [.. steps.Distinct(StringComparer.Ordinal)] : d.Steps, OlderThanDays: p.OlderThanDays ?? d.OlderThanDays),
_ => new(),
};
}
/// <summary>
/// The first invalid field of a schedule's action and parameters, by its API name (<c>action</c>,
/// <c>parameters.percent</c>, <c>parameters.steps</c>…); null when they are valid. <paramref name="steps"/> are the
/// clean-up steps the host runs.
/// </summary>
public static string? Problem(string action, ScheduleParametersDto? parameters, IReadOnlyCollection<string> steps)
{
ArgumentNullException.ThrowIfNull(steps);
if (!IsKnown(action)) return "action";
var p = Normalize(action, parameters);
if (p.OlderThanDays is < 0 or > MaxDays) return "parameters.olderThanDays";
if (p.Percent is < 1 or > 100) return "parameters.percent";
if (p.Keep is < 1 or > BackupJobHandler.MaxKeep) return "parameters.keep";
if (action == Cleanup && (p.Steps is not { Count: > 0 } named || named.Any(s => !steps.Contains(s)))) return "parameters.steps";
return null;
}
/// <summary>
/// Every action with whether this host runs it: not when the host says so (<see cref="IScheduleHost.Unavailable"/>), its
/// engine has no handler for the kind (<see cref="ScheduleUnavailable.NoHandler"/>), the index cannot be copied (backup:
/// <see cref="ScheduleUnavailable.Postgres"/>, <see cref="ScheduleUnavailable.NoIndexFile"/>), or the current archive makes
/// no proxies (<see cref="ScheduleUnavailable.ProxiesDisabled"/>). A missing or offline archive leaves actions available:
/// their runs are skipped until it is back.
/// </summary>
public static async Task<IReadOnlyList<ScheduleActionInfo>> AvailabilityAsync(ScheduleActionContext context, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(context);
var archive = await context.Host.GetArchiveAsync(cancellationToken).ConfigureAwait(false);
return [.. All.Select(a => Unavailable(context, a, null, archive) is { } reason ? new ScheduleActionInfo(a, false, reason) : new ScheduleActionInfo(a, true, null))];
}
/// <summary>
/// What a run of <paramref name="action"/> with <paramref name="parameters"/> queues now for the host's current archive,
/// or why it queues nothing (see the type's remarks). Read-only: nothing is queued here.
/// </summary>
public static async Task<ScheduleResolution> ResolveAsync(ScheduleActionContext context, string action, ScheduleParametersDto? parameters,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(context);
if (!IsKnown(action)) return ScheduleResolution.Skip(ScheduleOutcome.Unavailable);
var p = Normalize(action, parameters);
var db = context.Database;
var archive = await context.Host.GetArchiveAsync(cancellationToken).ConfigureAwait(false);
if (Unavailable(context, action, p, archive) is not null) return ScheduleResolution.Skip(ScheduleOutcome.Unavailable);
switch (action)
{
case Backup:
return ScheduleResolution.Queue([ArchiveJobs.Backup(p.Keep!.Value)]);
case Cleanup:
return ScheduleResolution.Queue([ArchiveJobs.Cleanup(archive, p.Steps!, p.OlderThanDays!.Value)]);
}
if (archive is null) return ScheduleResolution.Skip(ScheduleOutcome.SkippedOffline);
var availability = ArchiveService.GetAvailability(archive);
var writes = action is not (Verify or Duplicates or Orphans) && !(action == Maintenance && p.DryRun == true);
if (availability == ArchiveAvailability.Offline || (writes && availability != ArchiveAvailability.Online))
return ScheduleResolution.Skip(ScheduleOutcome.SkippedOffline);
switch (action)
{
case Scan:
return await PendingAsync(db, [JobKind.Scan, JobKind.Rebuild], archive, cancellationToken).ConfigureAwait(false)
?? ScheduleResolution.Queue([ArchiveJobs.Scan(archive, full: p.Force == true, deepAnalysis: p.Deep ?? context.Host.DeepAnalysisAfterScan)]);
case Verify:
return await PendingAsync(db, [JobKind.Verify], archive, cancellationToken).ConfigureAwait(false)
?? await VerifyAsync(context, archive, p, cancellationToken).ConfigureAwait(false);
case Thumbnails:
case Proxies:
{
var kind = action == Thumbnails ? JobKind.Thumbs : JobKind.Proxies;
var built = action == Thumbnails ? SequenceStatus.ThumbsBuilt : SequenceStatus.ProxiesBuilt;
var ids = await SequencesAsync(db, archive.Id, p.Force == true ? SequenceStatus.None : built, cancellationToken).ConfigureAwait(false);
return await ChunkedAsync(db, kind, ids, chunk => action == Thumbnails
? ArchiveJobs.Thumbnails(chunk, archive.Name, p.Force == true)
: ArchiveJobs.Proxies(chunk, archive.Name, p.Force == true), cancellationToken).ConfigureAwait(false);
}
case Analysis:
{
var deep = p.Deep == true;
var ids = deep
? await SequencesAsync(db, archive.Id, SequenceStatus.AnalyzedDeep, cancellationToken).ConfigureAwait(false)
: await AnalysisFollowUp.UnanalysedAsync(db, archive.Id, cancellationToken).ConfigureAwait(false);
return await ChunkedAsync(db, deep ? JobKind.DeepAnalyse : JobKind.LightAnalyse, ids, chunk => deep
? ProcessingJobs.DeepAnalysis(chunk, archive.Name)
: ProcessingJobs.LightAnalysis(chunk, archive.Name), cancellationToken).ConfigureAwait(false);
}
case Maintenance:
return await PendingAsync(db, [JobKind.Maintenance], archive, cancellationToken).ConfigureAwait(false)
?? ScheduleResolution.Queue([ArchiveJobs.Maintenance(archive, p.DryRun == true)]);
case Duplicates:
return await PendingAsync(db, [JobKind.Duplicates], archive, cancellationToken).ConfigureAwait(false)
?? ScheduleResolution.Queue([ArchiveJobs.Duplicates(archive)]);
default:
return await PendingAsync(db, [JobKind.Orphans], archive, cancellationToken).ConfigureAwait(false)
?? ScheduleResolution.Queue([ArchiveJobs.Orphans(archive)]);
}
}
/// <summary>Why <paramref name="action"/> cannot run here; null when it can. With <paramref name="parameters"/>, the kind it would queue must run.</summary>
private static string? Unavailable(ScheduleActionContext context, string action, ScheduleParametersDto? parameters, Archive? archive)
{
if (context.Host.Unavailable(action) is { } reason) return reason;
var kinds = KindsOf(action);
var kind = action == Analysis && parameters?.Deep == true ? JobKind.DeepAnalyse : kinds[0];
if (!context.CanRun(kind)) return ScheduleUnavailable.NoHandler;
if (action == Backup && DatabaseBackups.Unavailable(context.Database) is { } backup) return backup;
if (action == Proxies && archive is { ProxyLongEdge: ProxyPolicy.Disabled }) return ScheduleUnavailable.ProxiesDisabled;
return null;
}
/// <summary><see cref="ScheduleOutcome.SkippedPending"/> while a job of <paramref name="kinds"/> on the archive is queued, running or paused.</summary>
private static async Task<ScheduleResolution?> PendingAsync(ChronosDatabase db, IReadOnlyCollection<JobKind> kinds, Archive archive,
CancellationToken cancellationToken) =>
await db.Jobs.HasPendingAsync(kinds, [archive.Id], cancellationToken).ConfigureAwait(false) ? ScheduleResolution.Skip(ScheduleOutcome.SkippedPending) : null;
/// <summary>
/// The least recently verified sequences: those not verified for <c>olderThanDays</c> (0: any), at most
/// <c>percent</c> of the archive's sequences (rounded up). All of them at 100 % and 0 days, as one archive-wide job.
/// </summary>
private static async Task<ScheduleResolution> VerifyAsync(ScheduleActionContext context, Archive archive, ScheduleParametersDto p, CancellationToken cancellationToken)
{
var db = context.Database;
var total = await db.Sequences.CountAsync(new SequenceQuery { ArchiveId = archive.Id }, cancellationToken).ConfigureAwait(false);
if (total == 0) return ScheduleResolution.Skip(ScheduleOutcome.SkippedNothing);
var days = p.OlderThanDays ?? 0;
var percent = p.Percent ?? 100;
if (days == 0 && percent >= 100) return ScheduleResolution.Queue([ArchiveJobs.Verify(archive)]);
var limit = (int)Math.Ceiling(total * percent / 100.0);
var ids = await db.Sequences.ListVerifyCandidatesAsync(archive.Id, days > 0 ? context.Now - TimeSpan.FromDays(days) : null, limit, cancellationToken)
.ConfigureAwait(false);
return ids.Count == 0 ? ScheduleResolution.Skip(ScheduleOutcome.SkippedNothing) : ScheduleResolution.Queue([ArchiveJobs.Verify(archive, ids)]);
}
/// <summary>The sequences of an archive with frames and without <paramref name="without"/> (none: every one), oldest capture first.</summary>
private static async Task<List<Guid>> SequencesAsync(ChronosDatabase db, Guid archiveId, SequenceStatus without, CancellationToken cancellationToken)
{
var ids = new List<Guid>();
var query = new SequenceQuery { ArchiveId = archiveId, WithoutStatus = without, Sort = SequenceSort.Oldest, Limit = 1000 };
do
{
var page = await db.Sequences.ListAsync(query, cancellationToken).ConfigureAwait(false);
ids.AddRange(page.Items.Where(s => s.FrameCount > 0).Select(s => s.Id));
query = query with { Cursor = page.NextCursor };
}
while (query.Cursor is not null);
return ids;
}
/// <summary>
/// The jobs for <paramref name="ids"/> less those a pending job of <paramref name="kind"/> already covers, at most
/// <see cref="SequencesPerJob"/> per job; <see cref="ScheduleOutcome.SkippedNothing"/> when none is left.
/// </summary>
private static async Task<ScheduleResolution> ChunkedAsync(ChronosDatabase db, JobKind kind, IReadOnlyList<Guid> ids,
Func<IReadOnlyList<Guid>, ArchiveJobRequest> request, CancellationToken cancellationToken)
{
if (ids.Count == 0) return ScheduleResolution.Skip(ScheduleOutcome.SkippedNothing);
var pending = await db.Jobs.ListPendingTargetsAsync(kind, cancellationToken).ConfigureAwait(false);
var left = ids.Where(id => !pending.Contains(id)).Distinct().ToList();
if (left.Count == 0) return ScheduleResolution.Skip(pending.Count > 0 ? ScheduleOutcome.SkippedPending : ScheduleOutcome.SkippedNothing);
return ScheduleResolution.Queue([.. left.Chunk(SequencesPerJob).Select(chunk => request(chunk))]);
}
}
@@ -0,0 +1,89 @@
using System.Globalization;
using System.Text.Json;
using Chronos.Core.Model;
using Chronos.Data.Jobs;
using Chronos.Protocol;
namespace Chronos.Data.Scheduling;
/// <summary>
/// Schedules between the model and API v1 (<see cref="ScheduleDto"/>, <see cref="RecurrenceDto"/>), and the stored form of
/// their parameters (<see cref="ScheduleParametersDto"/> as camelCase JSON, normalised to the fields the action reads).
/// </summary>
public static class ScheduleMapping
{
/// <summary>Wire names of <see cref="RecurrenceKind"/>: <c>every</c>, <c>daily</c>, <c>weekly</c>, <c>monthly</c>.</summary>
public static string Kind(RecurrenceKind kind) => kind.ToString().ToLowerInvariant();
/// <summary>Wire names of <see cref="RecurrenceUnit"/>: <c>minutes</c>, <c>hours</c>, <c>days</c>.</summary>
public static string Unit(RecurrenceUnit unit) => unit.ToString().ToLowerInvariant();
public static ScheduleDto ToDto(Schedule schedule)
{
ArgumentNullException.ThrowIfNull(schedule);
var recurrence = ScheduleRecurrence.TryParse(schedule.Recurrence, out var parsed) ? ToDto(parsed) : new RecurrenceDto(schedule.Recurrence);
return new ScheduleDto(schedule.Id, schedule.SystemKey, schedule.Name, schedule.Action, schedule.Target, Parameters(schedule), recurrence,
schedule.CatchUp, JobWire.Priority(schedule.Priority), schedule.Enabled, schedule.NextRun, schedule.LastRun, schedule.LastJobId,
schedule.LastOutcome, schedule.CreatedBy, schedule.Created, schedule.Updated);
}
public static RecurrenceDto ToDto(ScheduleRecurrence recurrence)
{
ArgumentNullException.ThrowIfNull(recurrence);
var time = recurrence.Time.ToString("HH:mm", CultureInfo.InvariantCulture);
return recurrence.Kind switch
{
RecurrenceKind.Every => new RecurrenceDto(Kind(recurrence.Kind), Every: recurrence.Every, Unit: Unit(recurrence.Unit)),
RecurrenceKind.Daily => new RecurrenceDto(Kind(recurrence.Kind), Time: time),
RecurrenceKind.Weekly => new RecurrenceDto(Kind(recurrence.Kind), Time: time, Days: [.. recurrence.Days.Select(ScheduleRecurrence.DayName)]),
_ => new RecurrenceDto(Kind(recurrence.Kind), Time: time, DayOfMonth: recurrence.DayOfMonth),
};
}
/// <summary>The recurrence <paramref name="dto"/> describes; null when it is missing or invalid (out of range, unknown names).</summary>
public static ScheduleRecurrence? FromDto(RecurrenceDto? dto)
{
if (dto is null) return null;
var text = dto.Kind?.ToLowerInvariant() switch
{
"every" when dto.Every is { } every && Enum.TryParse<RecurrenceUnit>(dto.Unit, ignoreCase: true, out var unit) && Enum.IsDefined(unit)
=> string.Create(CultureInfo.InvariantCulture, $"every:{every}{Unit(unit)[0]}"),
"daily" => "daily:" + dto.Time,
"weekly" when dto.Days is { Count: > 0 } days => $"weekly:{string.Join(',', days)}@{dto.Time}",
"monthly" when dto.DayOfMonth is { } day => string.Create(CultureInfo.InvariantCulture, $"monthly:{day}@{dto.Time}"),
_ => null,
};
return ScheduleRecurrence.TryParse(text, out var recurrence) ? recurrence : null;
}
public static ScheduleActionDto ToDto(ScheduleActionInfo info)
{
ArgumentNullException.ThrowIfNull(info);
return new ScheduleActionDto(info.Name, info.Available, info.Reason);
}
/// <summary>The schedule's parameters, normalised for its action (stored JSON that cannot be read counts as none).</summary>
public static ScheduleParametersDto Parameters(Schedule schedule)
{
ArgumentNullException.ThrowIfNull(schedule);
ScheduleParametersDto? stored = null;
if (schedule.ParametersJson is { Length: > 0 } json)
{
try
{
stored = JsonSerializer.Deserialize(json, ProtocolJson.Default.ScheduleParametersDto);
}
catch (JsonException)
{
}
}
return ScheduleActions.Normalize(schedule.Action, stored);
}
/// <summary>The stored form of <paramref name="parameters"/> for <paramref name="action"/>; null for an action without parameters.</summary>
public static string? ParametersJson(string action, ScheduleParametersDto? parameters)
{
var normalized = ScheduleActions.Normalize(action, parameters);
return normalized == new ScheduleParametersDto() ? null : JsonSerializer.Serialize(normalized, ProtocolJson.Default.ScheduleParametersDto);
}
}
@@ -0,0 +1,67 @@
namespace Chronos.Data.Scheduling;
/// <summary>
/// What a schedule's run did (<see cref="Core.Model.Schedule.LastOutcome"/>), as stored and sent over the API. Clients
/// show them in their own words; <see cref="Failed(string)"/> carries the reason as text.
/// </summary>
public static class ScheduleOutcome
{
/// <summary>The action's jobs were queued (the schedule keeps the first one's id).</summary>
public const string Queued = "queued";
/// <summary>Not queued: the schedule's previous job, or a job doing the same work, is still queued, running or paused.</summary>
public const string SkippedPending = "skipped-pending";
/// <summary>Not queued: the archive the action works on is missing, offline, or read-only for an action that writes.</summary>
public const string SkippedOffline = "skipped-offline";
/// <summary>Not queued: nothing to do (every sequence verified recently, every thumbnail built…).</summary>
public const string SkippedNothing = "skipped-nothing";
/// <summary>Not queued: this host cannot run the action (<see cref="ScheduleUnavailable"/> says why).</summary>
public const string Unavailable = "unavailable";
/// <summary>Prefix of <see cref="Failed(string)"/>.</summary>
public const string FailedPrefix = "failed:";
/// <summary>Longest reason kept after <see cref="FailedPrefix"/>.</summary>
public const int MaxReasonLength = 200;
/// <summary><c>failed:&lt;reason&gt;</c>: resolving or queueing the action threw; the reason is the error's message, shortened.</summary>
public static string Failed(string reason)
{
var text = string.IsNullOrWhiteSpace(reason) ? "error" : reason.ReplaceLineEndings(" ").Trim();
return FailedPrefix + (text.Length > MaxReasonLength ? text[..MaxReasonLength] : text);
}
/// <summary>True for a <c>failed:</c> outcome, with its reason.</summary>
public static bool IsFailed(string? outcome, out string reason)
{
var failed = outcome?.StartsWith(FailedPrefix, StringComparison.Ordinal) == true;
reason = failed ? outcome![FailedPrefix.Length..] : string.Empty;
return failed;
}
/// <summary>The outcomes without a reason, for clients that name each one.</summary>
public static IReadOnlyList<string> Plain { get; } = [Queued, SkippedPending, SkippedOffline, SkippedNothing, Unavailable];
}
/// <summary>
/// Why an action cannot run on a host (<see cref="ScheduleActionInfo.Reason"/>, <c>ScheduleActionDto.reason</c>). A host's
/// own hook (<see cref="IScheduleHost.Unavailable"/>) may answer with codes of its own; clients show unknown codes as
/// "not available here".
/// </summary>
public static class ScheduleUnavailable
{
/// <summary>This host's job engine has no handler for the action's job kind.</summary>
public const string NoHandler = "no-handler";
/// <summary>Index backups: the index is on PostgreSQL, which its own tools back up.</summary>
public const string Postgres = "postgres";
/// <summary>Index backups: the SQLite index has no file (in memory).</summary>
public const string NoIndexFile = "no-index-file";
/// <summary>Proxies: the archive's proxy policy makes none.</summary>
public const string ProxiesDisabled = "proxies-disabled";
}
@@ -0,0 +1,322 @@
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
namespace Chronos.Data.Scheduling;
/// <summary>The shape of a <see cref="ScheduleRecurrence"/>.</summary>
public enum RecurrenceKind
{
/// <summary>A fixed interval: every n minutes, hours or days.</summary>
Every,
/// <summary>Every day at a wall-clock time.</summary>
Daily,
/// <summary>On some days of the week at a wall-clock time.</summary>
Weekly,
/// <summary>On one day of the month (1–28) at a wall-clock time.</summary>
Monthly,
}
/// <summary>Unit of an <see cref="RecurrenceKind.Every"/> interval.</summary>
public enum RecurrenceUnit
{
Minutes,
Hours,
Days,
}
/// <summary>
/// When a schedule fires (owner review 2, R10), in an in-house text form instead of cron: <c>every:&lt;n&gt;m|h|d</c>
/// (at least 5 minutes), <c>daily:HH:MM</c>, <c>weekly:mon,tue,…@HH:MM</c> and <c>monthly:&lt;1–28&gt;@HH:MM</c>.
/// Intervals are fixed durations anchored to the previous due time, so they never drift and the occurrences missed meanwhile
/// collapse into one; days of an interval are 24 hours, whatever the clocks do. Daily, weekly and monthly times are wall-clock
/// times of the host's zone: a time a spring-forward gap skips moves forward by the gap (02:30 becomes 03:30), and a time the
/// clocks go back over happens once, at its first occurrence. Instances compare by value.
/// </summary>
public sealed record ScheduleRecurrence
{
/// <summary>The shortest interval: a schedule never fires more than every 5 minutes.</summary>
public const int MinMinutes = 5;
public const int MaxMinutes = 24 * 60;
public const int MaxHours = 7 * 24;
public const int MaxDays = 366;
/// <summary>The last day a monthly schedule can name: every month has it.</summary>
public const int MaxDayOfMonth = 28;
/// <summary>Wire names of the days, Monday first, as the text form and the API write them.</summary>
public static IReadOnlyList<string> DayNames { get; } = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
private static readonly DayOfWeek[] WeekOrder =
[DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday, DayOfWeek.Saturday, DayOfWeek.Sunday];
/// <summary>Bit <c>1 &lt;&lt; (int)DayOfWeek</c> per weekly day; a field, so equality compares the days.</summary>
private readonly int _days;
private ScheduleRecurrence(RecurrenceKind kind, int every, RecurrenceUnit unit, TimeOnly time, int days, int dayOfMonth)
{
Kind = kind;
Every = every;
Unit = unit;
Time = time;
_days = days;
DayOfMonth = dayOfMonth;
}
public RecurrenceKind Kind { get; }
/// <summary>The interval's count of <see cref="Unit"/>; 0 for the other kinds.</summary>
public int Every { get; }
/// <summary>The interval's unit (<see cref="RecurrenceKind.Every"/> only).</summary>
public RecurrenceUnit Unit { get; }
/// <summary>Wall-clock time of a daily, weekly or monthly schedule, to the minute; midnight for an interval.</summary>
public TimeOnly Time { get; }
/// <summary>The days of a weekly schedule, Monday first; empty for the other kinds.</summary>
public IReadOnlyList<DayOfWeek> Days => [.. WeekOrder.Where(d => (_days & Bit(d)) != 0)];
/// <summary>Day of the month of a monthly schedule (1–28); 0 for the other kinds.</summary>
public int DayOfMonth { get; }
/// <summary>
/// The longest time between two occurrences: the interval, a day, a week, or 31 days for a monthly schedule. A next run
/// further away than two of them means the clock went back, and the next run is computed again.
/// </summary>
public TimeSpan Period => Kind switch
{
RecurrenceKind.Every => Unit switch
{
RecurrenceUnit.Minutes => TimeSpan.FromMinutes(Every),
RecurrenceUnit.Hours => TimeSpan.FromHours(Every),
_ => TimeSpan.FromDays(Every),
},
RecurrenceKind.Daily => TimeSpan.FromDays(1),
RecurrenceKind.Weekly => TimeSpan.FromDays(7),
_ => TimeSpan.FromDays(31),
};
/// <summary>Every <paramref name="every"/> <paramref name="unit"/> (at least <see cref="MinMinutes"/> minutes).</summary>
/// <exception cref="ArgumentOutOfRangeException">The interval is shorter than 5 minutes or longer than its unit allows.</exception>
public static ScheduleRecurrence Interval(int every, RecurrenceUnit unit)
{
var (min, max) = unit switch
{
RecurrenceUnit.Minutes => (MinMinutes, MaxMinutes),
RecurrenceUnit.Hours => (1, MaxHours),
RecurrenceUnit.Days => (1, MaxDays),
_ => throw new ArgumentOutOfRangeException(nameof(unit), unit, "Unknown unit."),
};
ArgumentOutOfRangeException.ThrowIfLessThan(every, min);
ArgumentOutOfRangeException.ThrowIfGreaterThan(every, max);
return new ScheduleRecurrence(RecurrenceKind.Every, every, unit, default, 0, 0);
}
/// <summary>Every day at <paramref name="time"/> (seconds are dropped).</summary>
public static ScheduleRecurrence DailyAt(TimeOnly time) => new(RecurrenceKind.Daily, 0, default, Minute(time), 0, 0);
/// <summary>On <paramref name="days"/> at <paramref name="time"/>.</summary>
/// <exception cref="ArgumentException">No day given.</exception>
public static ScheduleRecurrence WeeklyAt(IEnumerable<DayOfWeek> days, TimeOnly time)
{
ArgumentNullException.ThrowIfNull(days);
var mask = 0;
foreach (var day in days)
{
if (!Enum.IsDefined(day)) throw new ArgumentOutOfRangeException(nameof(days), day, "Unknown day.");
mask |= Bit(day);
}
if (mask == 0) throw new ArgumentException("A weekly schedule needs at least one day.", nameof(days));
return new ScheduleRecurrence(RecurrenceKind.Weekly, 0, default, Minute(time), mask, 0);
}
/// <summary>On day <paramref name="dayOfMonth"/> (1–28) of every month at <paramref name="time"/>.</summary>
public static ScheduleRecurrence MonthlyAt(int dayOfMonth, TimeOnly time)
{
ArgumentOutOfRangeException.ThrowIfLessThan(dayOfMonth, 1);
ArgumentOutOfRangeException.ThrowIfGreaterThan(dayOfMonth, MaxDayOfMonth);
return new ScheduleRecurrence(RecurrenceKind.Monthly, 0, default, Minute(time), 0, dayOfMonth);
}
/// <summary>The recurrence written as <paramref name="text"/> (any case, spaces around parts allowed).</summary>
/// <exception cref="FormatException">The text is not a valid recurrence.</exception>
public static ScheduleRecurrence Parse(string text) =>
TryParse(text, out var recurrence) ? recurrence : throw new FormatException($"'{text}' is not a schedule recurrence.");
/// <summary>Parses the text form; false for anything else, values out of range included.</summary>
public static bool TryParse([NotNullWhen(true)] string? text, [NotNullWhen(true)] out ScheduleRecurrence? recurrence)
{
recurrence = null;
if (string.IsNullOrWhiteSpace(text)) return false;
var colon = text.IndexOf(':', StringComparison.Ordinal);
if (colon <= 0) return false;
var kind = text[..colon].Trim().ToLowerInvariant();
var rest = text[(colon + 1)..].Trim();
try
{
recurrence = kind switch
{
"every" => ParseInterval(rest),
"daily" => TryTime(rest, out var time) ? DailyAt(time) : null,
"weekly" => ParseWeekly(rest),
"monthly" => ParseMonthly(rest),
_ => null,
};
}
catch (ArgumentException)
{
// A value out of range (every:4m, monthly:29@…).
recurrence = null;
}
return recurrence is not null;
}
/// <summary>The canonical text form: <c>every:10m</c>, <c>daily:03:00</c>, <c>weekly:mon,thu@02:30</c>, <c>monthly:1@04:00</c>.</summary>
public string Format()
{
var time = Time.ToString("HH:mm", CultureInfo.InvariantCulture);
return Kind switch
{
RecurrenceKind.Every => string.Create(CultureInfo.InvariantCulture,
$"every:{Every}{Unit switch { RecurrenceUnit.Minutes => 'm', RecurrenceUnit.Hours => 'h', _ => 'd' }}"),
RecurrenceKind.Daily => "daily:" + time,
RecurrenceKind.Weekly => new StringBuilder("weekly:").AppendJoin(',', Days.Select(DayName)).Append('@').Append(time).ToString(),
_ => string.Create(CultureInfo.InvariantCulture, $"monthly:{DayOfMonth}@{time}"),
};
}
public override string ToString() => Format();
/// <summary>The wire name of <paramref name="day"/>: <c>mon</c> … <c>sun</c>.</summary>
public static string DayName(DayOfWeek day) => DayNames[Array.IndexOf(WeekOrder, day)];
/// <summary>The day named <paramref name="name"/> (<see cref="DayNames"/>, any case); false for anything else.</summary>
public static bool TryParseDay(string? name, out DayOfWeek day)
{
var index = IndexOfDay(name);
day = index < 0 ? default : WeekOrder[index];
return index >= 0;
}
/// <summary>
/// The first occurrence strictly after <paramref name="afterUtc"/>, in UTC and to the minute. An interval is laid on the
/// grid of <paramref name="anchorUtc"/> (the previous due time: no drift, missed occurrences collapse into the next one),
/// or starts one interval after <paramref name="afterUtc"/>'s minute without an anchor. Daily, weekly and monthly times
/// are read in <paramref name="zone"/> (see the type's remarks for clock changes); they need no anchor.
/// </summary>
public DateTimeOffset Next(DateTimeOffset afterUtc, TimeZoneInfo zone, DateTimeOffset? anchorUtc = null)
{
ArgumentNullException.ThrowIfNull(zone);
var after = afterUtc.ToUniversalTime();
if (Kind == RecurrenceKind.Every)
{
var period = Period.Ticks;
if (anchorUtc is not { } anchor) return Truncate(after) + Period;
var behind = after.UtcTicks - anchor.UtcTicks;
var steps = behind / period;
if (behind % period != 0 && behind < 0) steps--;
return new DateTimeOffset(anchor.UtcTicks + (steps + 1) * period, TimeSpan.Zero);
}
var local = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(after, zone).DateTime);
// From the day before: a time a gap moves forward can land after a later midnight.
for (var i = -1; i <= 400; i++)
{
var day = local.AddDays(i);
if (!Matches(day)) continue;
var at = ToUtc(day.ToDateTime(Time), zone);
if (at > after) return at;
}
throw new InvalidOperationException($"No occurrence of {Format()} within a year.");
}
/// <summary>
/// The UTC instant of the wall-clock time <paramref name="local"/> in <paramref name="zone"/>: a time inside a
/// spring-forward gap moves forward by the gap, an ambiguous one takes its first occurrence (still on the larger offset).
/// </summary>
public static DateTimeOffset ToUtc(DateTime local, TimeZoneInfo zone)
{
ArgumentNullException.ThrowIfNull(zone);
local = DateTime.SpecifyKind(local, DateTimeKind.Unspecified);
TimeSpan offset;
if (zone.IsInvalidTime(local)) offset = zone.GetUtcOffset(local.AddHours(-12));
else if (zone.IsAmbiguousTime(local)) offset = zone.GetAmbiguousTimeOffsets(local).Max();
else offset = zone.GetUtcOffset(local);
return new DateTimeOffset(local.Ticks - offset.Ticks, TimeSpan.Zero);
}
/// <summary><c>10m</c>, <c>6h</c>, <c>7d</c>; null for anything else.</summary>
private static ScheduleRecurrence? ParseInterval(string text)
{
if (text.Length < 2) return null;
RecurrenceUnit? unit = char.ToLowerInvariant(text[^1]) switch
{
'm' => RecurrenceUnit.Minutes,
'h' => RecurrenceUnit.Hours,
'd' => RecurrenceUnit.Days,
_ => null,
};
return unit is { } u && TryNumber(text[..^1], out var every) ? Interval(every, u) : null;
}
/// <summary><c>mon,thu@02:30</c>; null for anything else.</summary>
private static ScheduleRecurrence? ParseWeekly(string text)
{
var at = text.LastIndexOf('@');
if (at <= 0 || !TryTime(text[(at + 1)..], out var time)) return null;
var days = new List<DayOfWeek>();
foreach (var name in text[..at].Split(','))
{
if (!TryParseDay(name.Trim(), out var day)) return null;
days.Add(day);
}
return WeeklyAt(days, time);
}
/// <summary><c>1@04:00</c>; null for anything else.</summary>
private static ScheduleRecurrence? ParseMonthly(string text)
{
var at = text.LastIndexOf('@');
return at > 0 && TryNumber(text[..at], out var day) && TryTime(text[(at + 1)..], out var time) ? MonthlyAt(day, time) : null;
}
private bool Matches(DateOnly day) => Kind switch
{
RecurrenceKind.Daily => true,
RecurrenceKind.Weekly => (_days & Bit(day.DayOfWeek)) != 0,
_ => day.Day == DayOfMonth,
};
private static int Bit(DayOfWeek day) => 1 << (int)day;
private static TimeOnly Minute(TimeOnly time) => new(time.Hour, time.Minute);
private static DateTimeOffset Truncate(DateTimeOffset utc) => new(utc.UtcTicks - utc.UtcTicks % TimeSpan.TicksPerMinute, TimeSpan.Zero);
private static int IndexOfDay(string? name)
{
for (var i = 0; i < DayNames.Count; i++)
{
if (string.Equals(DayNames[i], name, StringComparison.OrdinalIgnoreCase)) return i;
}
return -1;
}
private static bool TryNumber(string text, out int value) =>
int.TryParse(text.Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out value);
private static bool TryTime(string text, out TimeOnly time)
{
time = default;
var parts = text.Trim().Split(':');
if (parts is not [var h, var m] || h.Length is < 1 or > 2 || m.Length != 2
|| !TryNumber(h, out var hour) || !TryNumber(m, out var minute) || hour > 23 || minute > 59)
return false;
time = new TimeOnly(hour, minute);
return true;
}
}
+450
View File
@@ -0,0 +1,450 @@
using System.Threading.Channels;
using Chronos.Core.Diagnostics;
using Chronos.Core.Model;
using Chronos.Data.Jobs;
using Chronos.Protocol;
namespace Chronos.Data.Scheduling;
/// <summary>How a <see cref="Scheduler"/> keeps time.</summary>
public sealed record SchedulerOptions
{
/// <summary>Clock of the runs (tests pass their own); its timers pace the loop.</summary>
public TimeProvider Time { get; init; } = TimeProvider.System;
/// <summary>How often the loop looks for due schedules (and for schedules other processes changed).</summary>
public TimeSpan Tick { get; init; } = TimeSpan.FromSeconds(30);
/// <summary>
/// How late a run may be and still count as on time. A schedule further behind (the host was off, the PC slept) missed
/// its run: with catch-up it fires once, without it moves to its next occurrence without running.
/// </summary>
public TimeSpan CatchUpGrace { get; init; } = TimeSpan.FromMinutes(5);
}
/// <summary>What a schedule's run did: the outcome (<see cref="ScheduleOutcome"/>) and the first job it queued.</summary>
internal sealed record ScheduleFire(Guid ScheduleId, string Outcome, Guid? JobId);
/// <summary>A schedule created or edited, or the first invalid field by its API name (<c>name</c>, <c>recurrence</c>, <c>parameters.steps</c>…).</summary>
public sealed record ScheduleEditResult(ScheduleDto? Schedule, string? Problem)
{
/// <summary>True when the schedule to edit does not exist.</summary>
public bool NotFound => Schedule is null && Problem is null;
}
/// <summary>What <see cref="Scheduler.DeleteAsync"/> did.</summary>
public enum ScheduleDeleteOutcome
{
Deleted,
NotFound,
/// <summary>A system schedule: disable it instead.</summary>
System,
}
/// <summary>
/// Runs the schedules of one host (owner review 2, R10), in the style of the <see cref="JobEngine"/> it queues jobs on.
/// <see cref="StartAsync"/> seeds the host's system schedules (edits kept), gives enabled schedules without a next run one,
/// moves past the runs that schedules without catch-up missed, fires those with catch-up once, then looks every
/// <see cref="SchedulerOptions.Tick"/> (or at <see cref="Wake"/>). A due run is claimed by moving its next run with a
/// compare-and-set, so several processes on one database fire it once; the claimed run then queues the action's jobs (at the
/// schedule's priority, with its id) unless the schedule's previous job is still pending, and records the outcome. A crash
/// between the claim and the queueing loses that one run (it is logged as claimed first). A next run more than two periods
/// ahead means the clock went back: it is computed again. Edits go through this class so the next run follows them.
/// </summary>
public sealed class Scheduler : IAsyncDisposable
{
/// <summary>Longest schedule name.</summary>
public const int MaxNameLength = 100;
/// <summary>The only target so far: the host's archive.</summary>
public const string CurrentTarget = "current";
private readonly ChronosDatabase _db;
private readonly JobEngine _engine;
private readonly Channel<bool> _wake = Channel.CreateBounded<bool>(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite });
private readonly CancellationTokenSource _shutdown = new();
private readonly Lock _gate = new();
private IScheduleHost? _host;
private Task _loop = Task.CompletedTask;
public Scheduler(ChronosDatabase db, JobEngine engine, SchedulerOptions? options = null)
{
_db = db ?? throw new ArgumentNullException(nameof(db));
_engine = engine ?? throw new ArgumentNullException(nameof(engine));
Options = options ?? new SchedulerOptions();
}
public SchedulerOptions Options { get; }
/// <summary>The host given to <see cref="StartAsync"/>; null before.</summary>
public IScheduleHost? Host => Volatile.Read(ref _host);
/// <summary>A schedule was created, edited, reset or ran (also by the loop). Raised on the caller's or the loop's thread.</summary>
public event Action<ScheduleDto>? ScheduleChanged;
/// <summary>A schedule was deleted.</summary>
public event Action<Guid>? ScheduleDeleted;
/// <summary>
/// Seeds <paramref name="host"/>'s system schedules, settles the runs missed while the host was off (see the type's
/// remarks) and starts the loop. The first pass runs before this returns.
/// </summary>
public Task StartAsync(IScheduleHost host, CancellationToken cancellationToken = default) => StartAsync(host, null, cancellationToken);
/// <summary>
/// <see cref="StartAsync(IScheduleHost, CancellationToken)"/>, calling <paramref name="beforeFirstPass"/> once the system
/// schedules are seeded and edits are possible, before the first pass: what it changes (a value an environment variable
/// fixes) applies to the runs caught up at start too.
/// </summary>
public async Task StartAsync(IScheduleHost host, Func<CancellationToken, Task>? beforeFirstPass, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(host);
if (Host is not null) throw new InvalidOperationException("The scheduler has started already.");
var added = await _db.Schedules.EnsureSystemAsync(host.SystemSchedules, Now(), cancellationToken).ConfigureAwait(false);
if (added > 0) Log.Info("schedules", $"Added {added} system schedule(s)");
if (Interlocked.CompareExchange(ref _host, host, null) is not null) throw new InvalidOperationException("The scheduler has started already.");
if (beforeFirstPass is not null) await beforeFirstPass(cancellationToken).ConfigureAwait(false);
try
{
await RunDueAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
Log.Warning("schedules", "The schedules could not be run at start; the loop tries again", ex);
}
var shutdown = _shutdown.Token;
lock (_gate) _loop = Task.Run(() => LoopAsync(shutdown), CancellationToken.None);
}
/// <summary>Makes the loop look for due schedules now (another process changed them, the archive came back).</summary>
public void Wake() => _wake.Writer.TryWrite(true);
/// <summary>
/// One pass of the loop: corrects next runs (missing, clock gone back, missed without catch-up), then claims and fires
/// every due schedule. Returns how many fired here.
/// </summary>
public async Task<int> RunDueAsync(CancellationToken cancellationToken = default)
{
var host = RequireHost();
var now = Now();
foreach (var schedule in await _db.Schedules.ListAsync(cancellationToken).ConfigureAwait(false))
{
if (schedule.Enabled) await CorrectAsync(host, schedule, now, cancellationToken).ConfigureAwait(false);
}
var fired = 0;
foreach (var schedule in await _db.Schedules.ListDueAsync(now, cancellationToken).ConfigureAwait(false))
{
DateTimeOffset? next = ScheduleRecurrence.TryParse(schedule.Recurrence, out var recurrence)
? recurrence.Next(now, host.TimeZone, schedule.NextRun)
: null;
// The claim: one process wins the run; the others see the moved next run and leave it.
if (!await _db.Schedules.TryAdvanceAsync(schedule.Id, schedule.NextRun, next, cancellationToken).ConfigureAwait(false)) continue;
if (next is null)
{
Log.Warning("schedules", $"Schedule {schedule.Id} has an invalid recurrence '{schedule.Recurrence}'; it stops until edited");
await RecordAsync(schedule.Id, null, ScheduleOutcome.Failed("recurrence"), cancellationToken).ConfigureAwait(false);
continue;
}
Log.Debug("schedules", $"{schedule.Name} ({schedule.Action}) due {schedule.NextRun:O} claimed; next {next:O}");
await FireAsync(host, schedule, schedule.CreatedBy, manual: false, cancellationToken).ConfigureAwait(false);
fired++;
}
return fired;
}
/// <summary>
/// Runs the schedule now, as its next run would (also a disabled one), without moving its next run; null when it does
/// not exist. <paramref name="userId"/> is stamped on the jobs it queues.
/// </summary>
public async Task<ScheduleRunDto?> RunNowAsync(Guid id, Guid? userId, CancellationToken cancellationToken = default)
{
var host = RequireHost();
if (await _db.Schedules.GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } schedule) return null;
var fire = await FireAsync(host, schedule, userId ?? schedule.CreatedBy, manual: true, cancellationToken).ConfigureAwait(false);
var dto = await GetAsync(id, cancellationToken).ConfigureAwait(false) ?? ScheduleMapping.ToDto(schedule);
return new ScheduleRunDto(dto, fire.Outcome, fire.JobId);
}
/// <summary>
/// Runs the system schedule <paramref name="systemKey"/> now (<see cref="RunNowAsync"/>, which skips while its work is
/// pending) when it is enabled and has not run since <paramref name="since"/>; null when it did not run. The hosts' archive
/// scan once at start, as their polling did, and on the desktop when its archive is opened again (owner review 2, R10).
/// </summary>
public async Task<ScheduleRunDto?> RunSystemNowAsync(string systemKey, DateTimeOffset? since = null, CancellationToken cancellationToken = default)
{
_ = RequireHost();
if (await _db.Schedules.GetBySystemKeyAsync(systemKey, cancellationToken).ConfigureAwait(false) is not { Enabled: true } schedule
|| schedule.LastRun >= since) return null;
return await RunNowAsync(schedule.Id, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>The schedules (system ones first), the actions with their availability here, the host's time zone and clean-up steps.</summary>
public async Task<SchedulesDto> ListAsync(CancellationToken cancellationToken = default)
{
var host = RequireHost();
var items = await _db.Schedules.ListAsync(cancellationToken).ConfigureAwait(false);
var actions = await ScheduleActions.AvailabilityAsync(Context(host), cancellationToken).ConfigureAwait(false);
return new SchedulesDto([.. items.Select(ScheduleMapping.ToDto)], [.. actions.Select(ScheduleMapping.ToDto)], host.TimeZone.Id, host.CleanupSteps);
}
public async Task<ScheduleDto?> GetAsync(Guid id, CancellationToken cancellationToken = default) =>
await _db.Schedules.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } schedule ? ScheduleMapping.ToDto(schedule) : null;
/// <summary>Creates a schedule (enabled ones get their next run at once); the result names the first invalid field instead when there is one.</summary>
public async Task<ScheduleEditResult> CreateAsync(CreateScheduleRequest request, Guid? createdBy, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(request);
var host = RequireHost();
if (Problem(host, request.Name, request.Action, request.Target, request.Recurrence, request.Parameters, request.Priority) is { } problem)
return new ScheduleEditResult(null, problem);
var recurrence = ScheduleMapping.FromDto(request.Recurrence)!;
var now = Now();
var schedule = new Schedule
{
Id = Guid.CreateVersion7(),
Name = request.Name.Trim(),
Action = request.Action,
Target = CurrentTarget,
ParametersJson = ScheduleMapping.ParametersJson(request.Action, request.Parameters),
Recurrence = recurrence.Format(),
CatchUp = request.CatchUp,
Priority = Priority(request.Priority, JobPriority.Background),
Enabled = request.Enabled,
NextRun = request.Enabled ? recurrence.Next(now, host.TimeZone) : null,
CreatedBy = createdBy,
Created = now,
Updated = now,
};
await _db.Schedules.InsertAsync(schedule, cancellationToken).ConfigureAwait(false);
Log.Info("schedules", $"Schedule {schedule.Name} ({schedule.Action}, {schedule.Recurrence}) created");
return new ScheduleEditResult(Changed(schedule), null);
}
/// <summary>
/// Changes the fields <paramref name="request"/> gives. The next run is computed again when the recurrence changes or
/// the schedule is enabled; a disabled schedule has none. A system schedule keeps its name and action (asking to change
/// them is a problem of field <c>name</c> or <c>action</c>).
/// </summary>
public async Task<ScheduleEditResult> UpdateAsync(Guid id, UpdateScheduleRequest request, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(request);
var host = RequireHost();
if (await _db.Schedules.GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } current) return new ScheduleEditResult(null, null);
if (current.IsSystem && request.Name is { } name && name.Trim() != current.Name) return new ScheduleEditResult(null, "name");
if (current.IsSystem && request.Action is { } changed && changed != current.Action) return new ScheduleEditResult(null, "action");
var action = request.Action ?? current.Action;
// Another action starts from its own defaults; the same one keeps the stored values the request leaves out.
var parameters = request.Parameters ?? (action == current.Action ? ScheduleMapping.Parameters(current) : null);
var recurrenceDto = request.Recurrence ?? (ScheduleRecurrence.TryParse(current.Recurrence, out var stored) ? ScheduleMapping.ToDto(stored) : null);
if (Problem(host, request.Name ?? current.Name, action, null, recurrenceDto, parameters, request.Priority) is { } problem)
return new ScheduleEditResult(null, problem);
var recurrence = ScheduleMapping.FromDto(recurrenceDto)!;
var now = Now();
var enabled = request.Enabled ?? current.Enabled;
var reschedule = !enabled || !current.Enabled || current.NextRun is null || recurrence.Format() != current.Recurrence;
var schedule = current with
{
Name = (request.Name ?? current.Name).Trim(),
Action = action,
ParametersJson = ScheduleMapping.ParametersJson(action, parameters),
Recurrence = recurrence.Format(),
CatchUp = request.CatchUp ?? current.CatchUp,
Priority = Priority(request.Priority, current.Priority),
Enabled = enabled,
NextRun = !enabled ? null : reschedule ? recurrence.Next(now, host.TimeZone) : current.NextRun,
Updated = now,
};
if (!await _db.Schedules.UpdateAsync(schedule, reschedule, cancellationToken).ConfigureAwait(false)) return new ScheduleEditResult(null, null);
Log.Info("schedules", $"Schedule {schedule.Name} ({schedule.Action}, {schedule.Recurrence}, {(enabled ? "enabled" : "disabled")}) changed");
var saved = await _db.Schedules.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? schedule;
return new ScheduleEditResult(Changed(saved), null);
}
/// <summary>Deletes a schedule a user created; a system schedule is refused (<see cref="ScheduleDeleteOutcome.System"/>).</summary>
public async Task<ScheduleDeleteOutcome> DeleteAsync(Guid id, CancellationToken cancellationToken = default)
{
if (await _db.Schedules.GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } schedule) return ScheduleDeleteOutcome.NotFound;
if (schedule.IsSystem) return ScheduleDeleteOutcome.System;
if (!await _db.Schedules.DeleteAsync(id, cancellationToken).ConfigureAwait(false)) return ScheduleDeleteOutcome.NotFound;
Log.Info("schedules", $"Schedule {schedule.Name} ({schedule.Action}) deleted");
ScheduleDeleted?.Invoke(id);
return ScheduleDeleteOutcome.Deleted;
}
/// <summary>
/// Puts a system schedule back to the host's defaults (<see cref="IScheduleHost.SystemSchedules"/>) with a new next
/// run. A schedule a user created, or one the host no longer defines, is a problem of field <c>systemKey</c>.
/// </summary>
public async Task<ScheduleEditResult> ResetAsync(Guid id, CancellationToken cancellationToken = default)
{
var host = RequireHost();
if (await _db.Schedules.GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } current) return new ScheduleEditResult(null, null);
if (current.SystemKey is not { } key || host.SystemSchedules.FirstOrDefault(s => s.SystemKey == key) is not { } defaults)
return new ScheduleEditResult(null, "systemKey");
var now = Now();
await _db.Schedules.ResetSystemAsync(key, defaults, now, cancellationToken).ConfigureAwait(false);
if (defaults.Enabled) await _db.Schedules.TryAdvanceAsync(id, null, defaults.Recurrence.Next(now, host.TimeZone), cancellationToken).ConfigureAwait(false);
Log.Info("schedules", $"System schedule {key} reset");
var saved = await _db.Schedules.GetAsync(id, cancellationToken).ConfigureAwait(false);
return saved is null ? new ScheduleEditResult(null, null) : new ScheduleEditResult(Changed(saved), null);
}
public async ValueTask DisposeAsync()
{
Task loop;
lock (_gate) loop = _loop;
await _shutdown.CancelAsync().ConfigureAwait(false);
try
{
await loop.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
_shutdown.Dispose();
}
/// <summary>
/// Fills in a missing next run, computes it again after the clock went back, and moves a schedule without catch-up past
/// a run it missed. Compare-and-set like a claim, so concurrent passes agree.
/// </summary>
private async Task CorrectAsync(IScheduleHost host, Schedule schedule, DateTimeOffset now, CancellationToken cancellationToken)
{
if (!ScheduleRecurrence.TryParse(schedule.Recurrence, out var recurrence)) return;
DateTimeOffset next;
string why;
if (schedule.NextRun is not { } due)
{
next = recurrence.Next(now, host.TimeZone);
why = "first run";
}
else if (due - now > recurrence.Period * 2)
{
next = recurrence.Next(now, host.TimeZone);
why = "the clock went back";
}
else if (!schedule.CatchUp && now - due > Options.CatchUpGrace)
{
next = recurrence.Next(now, host.TimeZone, due);
why = $"missed the run of {due:O} (no catch-up)";
}
else
{
return;
}
if (!await _db.Schedules.TryAdvanceAsync(schedule.Id, schedule.NextRun, next, cancellationToken).ConfigureAwait(false)) return;
Log.Info("schedules", $"{schedule.Name} ({schedule.Action}): next run {next:O} ({why})");
Changed(schedule with { NextRun = next });
}
/// <summary>Queues the schedule's action unless its previous job is pending, records the outcome and logs one line.</summary>
private async Task<ScheduleFire> FireAsync(IScheduleHost host, Schedule schedule, Guid? createdBy, bool manual, CancellationToken cancellationToken)
{
string outcome;
Guid? jobId = null;
try
{
if (schedule.LastJobId is { } last
&& await _db.Jobs.GetAsync(last, cancellationToken).ConfigureAwait(false) is { State: JobState.Queued or JobState.Running or JobState.Paused })
{
outcome = ScheduleOutcome.SkippedPending;
}
else
{
var resolution = await ScheduleActions.ResolveAsync(Context(host), schedule.Action, ScheduleMapping.Parameters(schedule), cancellationToken)
.ConfigureAwait(false);
outcome = resolution.Outcome;
foreach (var request in resolution.Requests)
{
var job = await _engine.EnqueueAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, schedule.Priority, createdBy,
schedule.Id, cancellationToken).ConfigureAwait(false);
jobId ??= job.Id;
}
}
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
throw;
}
catch (Exception ex)
{
Log.Warning("schedules", $"{schedule.Name} ({schedule.Action}) could not run", ex);
outcome = ScheduleOutcome.Failed(ex.Message);
}
await RecordAsync(schedule.Id, jobId, outcome, CancellationToken.None).ConfigureAwait(false);
Log.Info("schedules", $"{schedule.Name} ({schedule.Action}{(manual ? ", run now" : string.Empty)}): {outcome}{(jobId is { } id ? $", job {id}" : string.Empty)}");
return new ScheduleFire(schedule.Id, outcome, jobId);
}
private async Task RecordAsync(Guid id, Guid? jobId, string outcome, CancellationToken cancellationToken)
{
await _db.Schedules.RecordOutcomeAsync(id, jobId, outcome, Now(), cancellationToken).ConfigureAwait(false);
if (await _db.Schedules.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } saved) Changed(saved);
}
private async Task LoopAsync(CancellationToken shutdown)
{
while (!shutdown.IsCancellationRequested)
{
await WaitAsync(shutdown).ConfigureAwait(false);
if (shutdown.IsCancellationRequested) return;
try
{
await RunDueAsync(shutdown).ConfigureAwait(false);
}
catch (OperationCanceledException) when (shutdown.IsCancellationRequested)
{
return;
}
catch (Exception ex)
{
// Nothing a pass throws ends the loop (a database briefly away, a host hook that failed).
Log.Warning("schedules", "The schedules could not be run; the next tick tries again", ex);
}
}
}
/// <summary>Waits for <see cref="Wake"/>, the tick or shutdown, whichever comes first.</summary>
private async Task WaitAsync(CancellationToken shutdown)
{
using var tick = new CancellationTokenSource(Options.Tick, Options.Time);
using var either = CancellationTokenSource.CreateLinkedTokenSource(shutdown, tick.Token);
try
{
await _wake.Reader.ReadAsync(either.Token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// Tick elapsed or shutdown.
}
}
private ScheduleDto Changed(Schedule schedule)
{
var dto = ScheduleMapping.ToDto(schedule);
ScheduleChanged?.Invoke(dto);
return dto;
}
private ScheduleActionContext Context(IScheduleHost host) => new(_db, host, _engine.CanRun, Now());
private DateTimeOffset Now() => Options.Time.GetUtcNow();
private IScheduleHost RequireHost() => Host ?? throw new InvalidOperationException("Start the scheduler with its host first.");
private static JobPriority Priority(string? wire, JobPriority fallback) => wire is not null && JobWire.TryParsePriority(wire, out var priority) ? priority : fallback;
/// <summary>The first invalid field of a schedule as given, by its API name; null when it is valid.</summary>
private static string? Problem(IScheduleHost host, string? name, string? action, string? target, RecurrenceDto? recurrence,
ScheduleParametersDto? parameters, string? priority)
{
if (string.IsNullOrWhiteSpace(name) || name.Trim().Length > MaxNameLength) return "name";
if (action is null) return "action";
if (ScheduleActions.Problem(action, parameters, host.CleanupSteps) is { } invalid) return invalid;
if (target is not null && target != CurrentTarget) return "target";
if (ScheduleMapping.FromDto(recurrence) is null) return "recurrence";
if (priority is not null && !JobWire.TryParsePriority(priority, out _)) return "priority";
return null;
}
}