using System.Collections.Concurrent; using System.Threading.Channels; using Chronos.Core.Diagnostics; using Chronos.Core.Localization; using Chronos.Core.Model; namespace Chronos.Data.Jobs; public sealed record JobEngineOptions { /// /// Jobs run at once: one (owner review 1, R2). Jobs run one at a time and the host's parallelism decides how many /// photos the running job processes at once; tests run more workers to exercise concurrent claims. /// public int Workers { get; init; } = 1; /// Identity stamped on claimed jobs (node id); also used for crash recovery. public string WorkerId { get; init; } = Environment.MachineName; /// Kinds this engine runs; null = every kind with a registered handler. public IReadOnlyCollection? Kinds { get; init; } public TimeSpan CheckpointInterval { get; init; } = TimeSpan.FromSeconds(5); /// /// The shortest time between two publishes of one job's progress (): twice a second. A new /// step, a count that completes and the run's first report go out at once (). /// public TimeSpan ProgressInterval { get; init; } = TimeSpan.FromMilliseconds(500); /// Fallback poll for jobs enqueued by other processes; also how often the priority queue is reviewed. public TimeSpan PollInterval { get; init; } = TimeSpan.FromSeconds(3); /// Clock of the throughput windows, the progress interval and the checkpoint interval (tests pass their own). public TimeProvider Time { get; init; } = TimeProvider.System; /// The priority queue as the settings have it now, asked at every claim and review; null: off (). public Func? PriorityQueue { get; init; } } /// /// 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. 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 /// declines stay queued for other claimers. With the priority queue on /// () 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 /// follow-ups it queued itself. /// public sealed class JobEngine : IAsyncDisposable { /// Queued jobs of selective kinds examined per claim; jobs declined beyond it wait until those ahead leave the queue. private const int SelectiveWindow = 100; /// Queued jobs a review looks through for one that is not a follow-up of the running job. private const int ReviewWindow = 50; /// Claims lost to other workers before a worker waits for the next poll. private const int MaxClaimRaces = 16; private readonly ChronosDatabase _db; private readonly Dictionary _handlers; private IReadOnlyCollection _kinds = []; private Dictionary _selective = []; private IReadOnlyCollection _others = []; private readonly ConcurrentDictionary _running = new(); private readonly Channel _wake = Channel.CreateBounded(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite }); private readonly Channel _review = Channel.CreateBounded(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite }); private readonly CancellationTokenSource _shutdown = new(); private readonly List _loops = []; private readonly Lock _gate = new(); public JobEngine(ChronosDatabase db, IEnumerable handlers, JobEngineOptions? options = null) { _db = db; Options = options ?? new JobEngineOptions(); _handlers = handlers.ToDictionary(h => h.Kind); } public JobEngineOptions Options { get; } /// A job changed state (queued, running, done, failed, cancelled, paused). public event Action? JobChanged; /// Progress of a running job, at most once per per job but for new steps and completed counts. public event Action? Progress; public IReadOnlyCollection RunningJobIds => [.. _running.Keys]; /// The priority queue as it is now (). public JobPriorityQueue PriorityQueue => Options.PriorityQueue?.Invoke() ?? JobPriorityQueue.Off; /// Requeues this worker's interrupted jobs and starts the worker and the queue's review. 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)"); // 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().ToDictionary(h => h.Kind); _others = [.. _kinds.Where(k => !_selective.ContainsKey(k))]; if (_kinds.Count == 0) { Log.Info("jobs", "No job handlers; this engine claims nothing"); return; } var shutdown = _shutdown.Token; lock (_gate) { for (var i = 0; i < Options.Workers; i++) { // A single worker keeps the plain id; numbered ones get "#n" (crash recovery requeues both). var id = Options.Workers == 1 ? Options.WorkerId : $"{Options.WorkerId}#{i}"; _loops.Add(Task.Run(() => WorkerLoopAsync(id, shutdown), CancellationToken.None)); } _loops.Add(Task.Run(() => SuperviseAsync(shutdown), CancellationToken.None)); } } /// Queues a job and wakes a worker. public Task EnqueueAsync(JobKind kind, IReadOnlyList 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, null, cancellationToken); /// Queues a job that the schedule fired () and wakes a worker. public Task EnqueueAsync(JobKind kind, IReadOnlyList 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); /// /// Queues a job under the id , chosen before (what it reads beside its journal is written under that /// id first, as a conversion's confirmed photos are), and wakes a worker. /// public Task EnqueueAsync(Guid id, JobKind kind, IReadOnlyList targets, string? targetLabel, string? parametersJson, JobPriority priority, Guid? createdBy, CancellationToken cancellationToken = default) => EnqueueAsync(id, kind, targets, targetLabel, parametersJson, priority, createdBy, null, cancellationToken); /// /// True when this engine runs jobs of : it has a handler for it and /// does not leave it out. Known before , so a host that does not start the engine still answers. /// public bool CanRun(JobKind kind) => _handlers.ContainsKey(kind) && (Options.Kinds is null || Options.Kinds.Contains(kind)); /// /// Cancels a queued or running job; a running handler observes its token. A paused or failed one, which no handler runs, /// leaves what it wrote to its handler to clear (), once a handler of this engine that /// was still stopping it (paused a moment ago: what it cleared itself was for a pause) has let go. /// public async Task CancelAsync(Guid id, CancellationToken cancellationToken = default) { var before = await _db.Jobs.GetAsync(id, cancellationToken).ConfigureAwait(false); await TransitionAsync(id, JobState.Cancelled, cancellationToken).ConfigureAwait(false); // Neither claimable nor running here: no handler cleans up after it itself. if (before is not { State: JobState.Paused or JobState.Failed } || !_handlers.TryGetValue(before.Kind, out var handler) || handler is not ICancelledJobHandler cancelled) return; if (_running.TryGetValue(id, out var stopping)) await stopping.Ended.WaitAsync(cancellationToken).ConfigureAwait(false); try { await cancelled.CancelledAsync(before with { State = JobState.Cancelled }, cancellationToken).ConfigureAwait(false); } catch (Exception ex) when (!(ex is OperationCanceledException && cancellationToken.IsCancellationRequested)) { Log.Warning("jobs", $"{before.Kind} job {id} was cancelled, but what it left could not be cleared", ex); } } /// Pauses a job: a running one stops at its next check and keeps its checkpoint, and the next queued job starts. public Task PauseAsync(Guid id, CancellationToken cancellationToken = default) => TransitionAsync(id, JobState.Paused, cancellationToken); /// Resumes a paused job or retries a failed/cancelled one from its last checkpoint. public async Task ResumeAsync(Guid id, CancellationToken cancellationToken = default) { await _db.Jobs.SetStateAsync(id, JobState.Queued, null, cancellationToken).ConfigureAwait(false); await NotifyAsync(id, cancellationToken).ConfigureAwait(false); Wake(); } /// /// Signals that the queue may have changed (also call on PostgreSQL NOTIFY, and after the priority queue's settings /// changed): an idle worker looks for work, and the priority queue is reviewed at once. /// public void Wake() { _wake.Writer.TryWrite(true); _review.Writer.TryWrite(true); } public async ValueTask DisposeAsync() { Task[] loops; lock (_gate) loops = [.. _loops]; await _shutdown.CancelAsync().ConfigureAwait(false); try { await Task.WhenAll(loops).ConfigureAwait(false); } catch (OperationCanceledException) { } _shutdown.Dispose(); } /// Broadcasts live progress. A subscriber that throws never fails the job it watches (logged once per job). internal void PublishProgress(JobContext context) { try { var (rate, eta) = context.Rate(); Progress?.Invoke(new JobProgressInfo(context.Job.Id, context.Job.Kind, context.Job.TargetLabel, context.Done, context.Total, rate, eta, context.Message, context.Detail)); } catch (Exception ex) { if (context.FirstProgressFailure()) Log.Warning("jobs", $"Progress of {context.Job.Kind} job {context.Job.Id} not published", ex); } } /// /// Saves progress, its detail, checkpoint and log tail; false when the job no longer runs here (cancelled or paused elsewhere). /// Saving is best effort and never throws: a failure is logged and the job goes on, so its final state is always written. /// internal async Task PersistAsync(JobContext context) { try { var (rate, eta) = context.Rate(); return await _db.Jobs.UpdateProgressAsync(context.Job.Id, context.Done, context.Total, rate, eta, context.Checkpoint, context.LogTail, context.Detail, CancellationToken.None).ConfigureAwait(false); } catch (DatabaseException ex) when (ex.IsTransient) { Log.Warning("jobs", "Progress not saved (transient database error)", ex); return true; } catch (Exception ex) { Log.Warning("jobs", $"Progress of {context.Job.Kind} job {context.Job.Id} not saved", ex); return true; } } /// True when this engine claims jobs of (it has a handler and the kind is not filtered out). internal bool Runs(JobKind kind) => _kinds.Contains(kind); /// /// Queues follow-up work of the running job (): /// it works on what the parent produces, so it never interrupts it, whatever its level. Null when this engine has no /// handler for . /// internal async Task EnqueueFollowUpAsync(Guid parent, JobKind kind, IReadOnlyList targets, string? label, string? parametersJson, JobPriority priority, Guid? createdBy, CancellationToken cancellationToken) { if (!Runs(kind)) return null; 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, null, cancellationToken).ConfigureAwait(false); } internal void StopJob(Guid id) { if (_running.TryGetValue(id, out var run)) run.Stop(); } /// /// Makes the running job yield when the priority queue is on and a queued job of a higher level waits that this engine /// would claim (not a follow-up of that running job): the running job of the lowest level stops, goes back to the /// queue with its checkpoint and resumes after the higher ones. A free worker would claim the waiting job anyway, so /// only a full engine interrupts one. True when a job was asked to yield. /// internal async Task ReviewAsync(CancellationToken cancellationToken) { var queue = PriorityQueue; if (!queue.Enabled) return false; var running = _running.Values.Where(r => !r.Yielding).ToList(); if (running.Count == 0 || running.Count < Options.Workers) return false; var lowest = running.MinBy(r => queue.LevelOf(r.Job.Kind))!; if (queue.LevelOf(lowest.Job.Kind) == JobKindPriority.High) return false; var next = await PeekAsync(queue, lowest, cancellationToken).ConfigureAwait(false); if (next is null || !queue.Interrupts(next.Kind, lowest.Job.Kind)) return false; if (!lowest.Yield(next)) return false; Log.Info("jobs", $"{lowest.Job.Kind} job {lowest.Job.Id} yields to {next.Kind} job {next.Id} (priority queue)"); return true; } private async Task EnqueueAsync(Guid id, JobKind kind, IReadOnlyList targets, string? targetLabel, string? parametersJson, JobPriority priority, Guid? createdBy, Guid? scheduleId, CancellationToken cancellationToken) { var job = new Job { Id = id, Kind = kind, TargetIds = targets, TargetLabel = targetLabel, ParametersJson = parametersJson, Priority = priority, State = JobState.Queued, CreatedBy = createdBy, Created = DateTimeOffset.UtcNow, ScheduleId = scheduleId, }; await _db.Jobs.EnqueueAsync(job, cancellationToken).ConfigureAwait(false); JobChanged?.Invoke(job); Wake(); return job; } private async Task TransitionAsync(Guid id, JobState state, CancellationToken cancellationToken) { await _db.Jobs.SetStateAsync(id, state, null, cancellationToken).ConfigureAwait(false); StopJob(id); await NotifyAsync(id, cancellationToken).ConfigureAwait(false); } private async Task NotifyAsync(Guid id, CancellationToken cancellationToken) { if (await _db.Jobs.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } job) JobChanged?.Invoke(job); } /// Claims and runs jobs until shutdown. Nothing a job or a handler throws ends the worker. private async Task WorkerLoopAsync(string workerId, CancellationToken shutdown) { while (!shutdown.IsCancellationRequested) { Job? job; try { job = await ClaimAsync(workerId, shutdown).ConfigureAwait(false); } catch (OperationCanceledException) when (shutdown.IsCancellationRequested) { return; } catch (Exception ex) { Log.Warning("jobs", "Claiming a job failed", ex); job = null; } if (job is null) { await WaitAsync(_wake, shutdown).ConfigureAwait(false); continue; } try { await RunAsync(job, workerId, shutdown).ConfigureAwait(false); } catch (Exception ex) { // The job's final state could not be stored (also while stopping): it stays running and is requeued at the // next start. The worker never faults, so disposing the engine never throws. Log.Error("jobs", $"{job.Kind} job {job.Id} could not be finished", ex); } } } /// /// Reviews the priority queue () whenever the queue may have changed () and /// at every poll, which also covers jobs queued by other processes. Nothing a review throws ends it. /// private async Task SuperviseAsync(CancellationToken shutdown) { while (!shutdown.IsCancellationRequested) { await WaitAsync(_review, shutdown).ConfigureAwait(false); if (shutdown.IsCancellationRequested) return; try { await ReviewAsync(shutdown).ConfigureAwait(false); } catch (OperationCanceledException) when (shutdown.IsCancellationRequested) { return; } catch (Exception ex) { Log.Warning("jobs", "The priority queue could not be reviewed", ex); } } } /// Waits for a signal on , the poll interval or shutdown, whichever comes first. private async Task WaitAsync(Channel channel, CancellationToken shutdown) { using var timeout = CancellationTokenSource.CreateLinkedTokenSource(shutdown); timeout.CancelAfter(Options.PollInterval); try { await channel.Reader.ReadAsync(timeout.Token).ConfigureAwait(false); } catch (OperationCanceledException) { // Poll interval elapsed or shutdown. } } /// /// The next job in claim order (). Without selective handlers the database /// picks it atomically. With them, the first job a selective handler accepts among the first /// of its kinds competes with the head of the other kinds: the other kinds are still /// claimed atomically, the selective job by id. A lost race means another worker took a job, so looking again at once /// makes progress. /// private async Task ClaimAsync(string workerId, CancellationToken cancellationToken) { var queue = PriorityQueue; if (_selective.Count == 0) return await _db.Jobs.ClaimNextAsync(workerId, _kinds, queue, cancellationToken).ConfigureAwait(false); for (var attempt = 0; attempt < MaxClaimRaces; attempt++) { var candidate = await AcceptedAsync(queue, null, cancellationToken).ConfigureAwait(false); if (candidate is null) return _others.Count > 0 ? await _db.Jobs.ClaimNextAsync(workerId, _others, queue, cancellationToken).ConfigureAwait(false) : null; if (_others.Count > 0 && (await _db.Jobs.ListQueuedBriefAsync(_others, 1, queue, cancellationToken).ConfigureAwait(false)).FirstOrDefault() is { } head && queue.ClaimsBefore(head, candidate)) { if (await _db.Jobs.ClaimNextAsync(workerId, _others, queue, cancellationToken).ConfigureAwait(false) is { } next) return next; } else if (await _db.Jobs.TryClaimAsync(candidate.Id, workerId, cancellationToken).ConfigureAwait(false) is { } claimed) { return claimed; } } return null; } /// The job a free worker would claim now () leaving out the follow-ups of , without claiming it. private async Task PeekAsync(JobPriorityQueue queue, RunningJob running, CancellationToken cancellationToken) { var candidate = _selective.Count > 0 ? await AcceptedAsync(queue, running, cancellationToken).ConfigureAwait(false) : null; Job? head = null; if (_others.Count > 0) { // Only who comes first counts here: the job that yields to it reads its kind, and a claim reads a job whole. foreach (var queued in await _db.Jobs.ListQueuedBriefAsync(_others, ReviewWindow, queue, cancellationToken).ConfigureAwait(false)) { if (running.FollowUps.ContainsKey(queued.Id)) continue; head = queued; break; } } return head is null ? candidate : candidate is null || queue.ClaimsBefore(head, candidate) ? head : candidate; } /// The first queued job of the selective kinds whose handler takes it now, leaving out the follow-ups of . private async Task AcceptedAsync(JobPriorityQueue queue, RunningJob? running, CancellationToken cancellationToken) { foreach (var queued in await _db.Jobs.ListQueuedAsync(_selective.Keys, SelectiveWindow, queue, cancellationToken).ConfigureAwait(false)) { if (running?.FollowUps.ContainsKey(queued.Id) == true || !await AcceptsAsync(queued, cancellationToken).ConfigureAwait(false)) continue; return queued; } return null; } /// A job its handler cannot judge is taken, so it fails here with its reason instead of blocking the queue. private async ValueTask AcceptsAsync(Job job, CancellationToken cancellationToken) { try { return await _selective[job.Kind].AcceptsAsync(job, cancellationToken).ConfigureAwait(false); } catch (Exception ex) when (!(ex is OperationCanceledException && cancellationToken.IsCancellationRequested)) { Log.Warning("jobs", $"{job.Kind} job {job.Id} could not be examined; it is claimed so that it fails with its reason", ex); return true; } } private async Task RunAsync(Job job, string workerId, CancellationToken shutdown) { using var cts = CancellationTokenSource.CreateLinkedTokenSource(shutdown); var run = new RunningJob(job, cts); _running[job.Id] = run; JobChanged?.Invoke(job); // A job queued while this one was being claimed may outrank it. _review.Writer.TryWrite(true); var context = new JobContext(this, job, cts.Token); JobState final; string? error = null; try { if (!_handlers.TryGetValue(job.Kind, out var handler)) throw new InvalidOperationException($"No handler for {job.Kind} jobs on this worker."); try { await handler.RunAsync(context).ConfigureAwait(false); } finally { // The handler returned: no trailing progress follows its final state. context.End(); } await PersistAsync(context).ConfigureAwait(false); final = JobState.Done; } catch (OperationCanceledException) when (cts.IsCancellationRequested) { // Read once: the job a yield names is set together with the yield itself. var yieldsTo = shutdown.IsCancellationRequested ? null : run.YieldsTo; var yielded = yieldsTo is not null; if (yieldsTo is not null) context.Log(Loc.L("Jobs.Line.Yielded", Loc.L("Jobs.Kind." + yieldsTo.Kind))); await PersistAsync(context).ConfigureAwait(false); _running.TryRemove(job.Id, out _); run.End(); // Engine stopping: leave the job running so the next start requeues it from its checkpoint. if (shutdown.IsCancellationRequested) return; // Yielded to a higher job: back to the queue with its checkpoint, unless the user paused or cancelled it // meanwhile (their state stays). Otherwise cancel or pause already wrote the state; keep it. if (yielded) await _db.Jobs.RequeueAsync(job.Id, workerId, CancellationToken.None).ConfigureAwait(false); await NotifyAsync(job.Id, CancellationToken.None).ConfigureAwait(false); return; } catch (Exception ex) { Log.Error("jobs", $"{job.Kind} job {job.Id} failed", ex); context.Log(ex.Message); await PersistAsync(context).ConfigureAwait(false); final = JobState.Failed; error = ex.Message; } finally { _running.TryRemove(job.Id, out _); run.End(); } await _db.Jobs.SetStateAsync(job.Id, final, error, CancellationToken.None).ConfigureAwait(false); await NotifyAsync(job.Id, CancellationToken.None).ConfigureAwait(false); } /// A job a worker runs: how it is stopped, whether it was stopped to yield, and the follow-ups it queued. private sealed class RunningJob(Job job, CancellationTokenSource cancellation) { private Job? _yieldsTo; private readonly TaskCompletionSource _ended = new(TaskCreationOptions.RunContinuationsAsynchronously); public Job Job { get; } = job; /// Completes once the handler has returned and the job left the engine's running jobs. public Task Ended => _ended.Task; public void End() => _ended.TrySetResult(); /// Jobs this one queued as follow-ups (): they never make it yield. public ConcurrentDictionary FollowUps { get; } = new(); public bool Yielding => YieldsTo is not null; /// The job of a higher level this one yields to; set, atomically, before it is stopped. public Job? YieldsTo => Volatile.Read(ref _yieldsTo); /// Signals the job's token; a job that ended meanwhile (its source disposed) needs nothing. public void Stop() { try { cancellation.Cancel(); } catch (ObjectDisposedException) { } } /// Stops the job to yield to ; false when it is yielding already. public bool Yield(Job to) { if (Interlocked.CompareExchange(ref _yieldsTo, to, null) is not null) return false; Stop(); return true; } } }