feat(data): scheduler engine, schedules table and housekeeping jobs
Owner review 2, R10: every timer that queues work becomes a visible schedule, so the server and the desktop need one shared engine to run them. - Migration 0007: schedules table (system rows keyed by system_key) and jobs.schedule_id; Job.ScheduleId, JobDto.ScheduleId, JobRepository HasPendingAsync / ListPendingTargetsAsync / ListByScheduleAsync. - ScheduleRepository: seeding that keeps user edits, reset, compare-and-set claim of a run (one winner across processes), outcomes. - Scheduling: in-house recurrence (every/daily/weekly/monthly, DST gap moves forward, ambiguous time runs once), ScheduleActions resolving scan, verify, thumbnails, proxies, analysis, maintenance, backup, cleanup, duplicates and orphans into archive jobs, IScheduleHost, and the Scheduler loop (catch-up, clock going back, run now, CRUD as API v1 DTOs). - New job kinds Backup (16) and Cleanup (17) with handlers, shared clean-up steps (job history, audit log, trash report that never deletes) and host steps through ArchiveServiceOptions; read-only Duplicates and Orphans report handlers, so the server can run those kinds too. - JobEngine no longer purges history at start: the housekeeping schedule's job-history step does; JobEngine.CanRun and an EnqueueAsync with scheduleId. - Protocol DTOs for schedules; job kind names in en and it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit eb0edd2483a493db7c6945d5b494461cabb2a4ad)
This commit is contained in:
1 parent
0e84392f4f
commit
e5508e7e69
51 files changed
+3219
-30
No files matched your search
@@ -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);
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -56,6 +56,7 @@ public static class JobWire
|
||||
Created = dto.Created,
|
||||
Started = dto.Started,
|
||||
Finished = dto.Finished,
|
||||
ScheduleId = dto.ScheduleId,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user