Setup: a kept 1.0 Uploader no longer fixes the scope and folder, the Remove tooltip promises kept files only with a hashed log, and a single-program setup preselects it. The Uploader always downloads the setup. Sync links move to the server id at every sign-in while folders wait for jobs and open editors; jobs of a pending homes sort still find their projects. A shared library exposes only the shared archive's client-visible jobs and events, render nodes take only client renders, and the share counts as its own while starting. Progress: a new step waits a quarter interval and a trailing timer publishes the last state; the job bar tooltip carries the whole line; Recent maintenance and the Server jobs list pick up jobs that start while they are shown. Refs #64 #65 #66 #67 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
575 lines
28 KiB
C#
575 lines
28 KiB
C#
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
|
|
{
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
public int Workers { get; init; } = 1;
|
|
|
|
/// <summary>Identity stamped on claimed jobs (node id); also used for crash recovery.</summary>
|
|
public string WorkerId { get; init; } = Environment.MachineName;
|
|
|
|
/// <summary>Kinds this engine runs; null = every kind with a registered handler.</summary>
|
|
public IReadOnlyCollection<JobKind>? Kinds { get; init; }
|
|
|
|
public TimeSpan CheckpointInterval { get; init; } = TimeSpan.FromSeconds(5);
|
|
|
|
/// <summary>
|
|
/// The shortest time between two publishes of one job's progress (<see cref="JobEngine.Progress"/>): twice a second. A new
|
|
/// step, a count that completes and the run's first report go out at once (<see cref="JobContext"/>).
|
|
/// </summary>
|
|
public TimeSpan ProgressInterval { get; init; } = TimeSpan.FromMilliseconds(500);
|
|
|
|
/// <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>Clock of the throughput windows, the progress interval and the checkpoint interval (tests pass their own).</summary>
|
|
public TimeProvider Time { get; init; } = TimeProvider.System;
|
|
|
|
/// <summary>The priority queue as the settings have it now, asked at every claim and review; null: off (<see cref="JobPriorityQueue"/>).</summary>
|
|
public Func<JobPriorityQueue>? PriorityQueue { get; init; }
|
|
}
|
|
|
|
/// <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. 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
|
|
/// follow-ups it queued itself.
|
|
/// </summary>
|
|
public sealed class JobEngine : IAsyncDisposable
|
|
{
|
|
/// <summary>Queued jobs of selective kinds examined per claim; jobs declined beyond it wait until those ahead leave the queue.</summary>
|
|
private const int SelectiveWindow = 100;
|
|
|
|
/// <summary>Queued jobs a review looks through for one that is not a follow-up of the running job.</summary>
|
|
private const int ReviewWindow = 50;
|
|
|
|
/// <summary>Claims lost to other workers before a worker waits for the next poll.</summary>
|
|
private const int MaxClaimRaces = 16;
|
|
|
|
private readonly ChronosDatabase _db;
|
|
private readonly Dictionary<JobKind, IJobHandler> _handlers;
|
|
private IReadOnlyCollection<JobKind> _kinds = [];
|
|
private Dictionary<JobKind, ISelectiveJobHandler> _selective = [];
|
|
private IReadOnlyCollection<JobKind> _others = [];
|
|
private readonly ConcurrentDictionary<Guid, RunningJob> _running = new();
|
|
private readonly Channel<bool> _wake = Channel.CreateBounded<bool>(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite });
|
|
private readonly Channel<bool> _review = Channel.CreateBounded<bool>(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite });
|
|
private readonly CancellationTokenSource _shutdown = new();
|
|
private readonly List<Task> _loops = [];
|
|
private readonly Lock _gate = new();
|
|
|
|
public JobEngine(ChronosDatabase db, IEnumerable<IJobHandler> handlers, JobEngineOptions? options = null)
|
|
{
|
|
_db = db;
|
|
Options = options ?? new JobEngineOptions();
|
|
_handlers = handlers.ToDictionary(h => h.Kind);
|
|
}
|
|
|
|
public JobEngineOptions Options { get; }
|
|
|
|
/// <summary>A job changed state (queued, running, done, failed, cancelled, paused).</summary>
|
|
public event Action<Job>? JobChanged;
|
|
|
|
/// <summary>Progress of a running job, at most once per <see cref="JobEngineOptions.ProgressInterval"/> per job but for new steps and completed counts.</summary>
|
|
public event Action<JobProgressInfo>? Progress;
|
|
|
|
public IReadOnlyCollection<Guid> RunningJobIds => [.. _running.Keys];
|
|
|
|
/// <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 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)");
|
|
// 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);
|
|
_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));
|
|
}
|
|
}
|
|
|
|
/// <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, 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>
|
|
/// Queues a job under the id <paramref name="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.
|
|
/// </summary>
|
|
public Task<Job> EnqueueAsync(Guid id, JobKind kind, IReadOnlyList<Guid> targets, string? targetLabel, string? parametersJson, JobPriority priority,
|
|
Guid? createdBy, CancellationToken cancellationToken = default) =>
|
|
EnqueueAsync(id, kind, targets, targetLabel, parametersJson, priority, createdBy, null, 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. A paused or failed one, which no handler runs,
|
|
/// leaves what it wrote to its handler to clear (<see cref="ICancelledJobHandler"/>), 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.
|
|
/// </summary>
|
|
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);
|
|
}
|
|
}
|
|
|
|
/// <summary>Pauses a job: a running one stops at its next check and keeps its checkpoint, and the next queued job starts.</summary>
|
|
public Task PauseAsync(Guid id, CancellationToken cancellationToken = default) => TransitionAsync(id, JobState.Paused, cancellationToken);
|
|
|
|
/// <summary>Resumes a paused job or retries a failed/cancelled one from its last checkpoint.</summary>
|
|
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();
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
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();
|
|
}
|
|
|
|
/// <summary>Broadcasts live progress. A subscriber that throws never fails the job it watches (logged once per job).</summary>
|
|
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);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
internal async Task<bool> 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;
|
|
}
|
|
}
|
|
|
|
/// <summary>True when this engine claims jobs of <paramref name="kind"/> (it has a handler and the kind is not filtered out).</summary>
|
|
internal bool Runs(JobKind kind) => _kinds.Contains(kind);
|
|
|
|
/// <summary>
|
|
/// Queues follow-up work of the running job <paramref name="parent"/> (<see cref="JobContext.EnqueueFollowUpAsync"/>):
|
|
/// it works on what the parent produces, so it never interrupts it, whatever its level. Null when this engine has no
|
|
/// handler for <paramref name="kind"/>.
|
|
/// </summary>
|
|
internal async Task<Job?> EnqueueFollowUpAsync(Guid parent, JobKind kind, IReadOnlyList<Guid> 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();
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
internal async Task<bool> 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<Job> EnqueueAsync(Guid id, JobKind kind, IReadOnlyList<Guid> 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);
|
|
}
|
|
|
|
/// <summary>Claims and runs jobs until shutdown. Nothing a job or a handler throws ends the worker.</summary>
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Reviews the priority queue (<see cref="ReviewAsync"/>) whenever the queue may have changed (<see cref="Wake"/>) and
|
|
/// at every poll, which also covers jobs queued by other processes. Nothing a review throws ends it.
|
|
/// </summary>
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>Waits for a signal on <paramref name="channel"/>, the poll interval or shutdown, whichever comes first.</summary>
|
|
private async Task WaitAsync(Channel<bool> 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.
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The next job in claim order (<see cref="JobPriorityQueue.ClaimsBefore"/>). Without selective handlers the database
|
|
/// picks it atomically. With them, the first job a selective handler accepts among the first
|
|
/// <see cref="SelectiveWindow"/> 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.
|
|
/// </summary>
|
|
private async Task<Job?> 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;
|
|
}
|
|
|
|
/// <summary>The job a free worker would claim now (<see cref="ClaimAsync"/>) leaving out the follow-ups of <paramref name="running"/>, without claiming it.</summary>
|
|
private async Task<Job?> 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;
|
|
}
|
|
|
|
/// <summary>The first queued job of the selective kinds whose handler takes it now, leaving out the follow-ups of <paramref name="running"/>.</summary>
|
|
private async Task<Job?> 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;
|
|
}
|
|
|
|
/// <summary>A job its handler cannot judge is taken, so it fails here with its reason instead of blocking the queue.</summary>
|
|
private async ValueTask<bool> 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);
|
|
}
|
|
|
|
/// <summary>A job a worker runs: how it is stopped, whether it was stopped to yield, and the follow-ups it queued.</summary>
|
|
private sealed class RunningJob(Job job, CancellationTokenSource cancellation)
|
|
{
|
|
private Job? _yieldsTo;
|
|
private readonly TaskCompletionSource _ended = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
|
|
public Job Job { get; } = job;
|
|
|
|
/// <summary>Completes once the handler has returned and the job left the engine's running jobs.</summary>
|
|
public Task Ended => _ended.Task;
|
|
|
|
public void End() => _ended.TrySetResult();
|
|
|
|
/// <summary>Jobs this one queued as follow-ups (<see cref="EnqueueFollowUpAsync"/>): they never make it yield.</summary>
|
|
public ConcurrentDictionary<Guid, byte> FollowUps { get; } = new();
|
|
|
|
public bool Yielding => YieldsTo is not null;
|
|
|
|
/// <summary>The job of a higher level this one yields to; set, atomically, before it is stopped.</summary>
|
|
public Job? YieldsTo => Volatile.Read(ref _yieldsTo);
|
|
|
|
/// <summary>Signals the job's token; a job that ended meanwhile (its source disposed) needs nothing.</summary>
|
|
public void Stop()
|
|
{
|
|
try
|
|
{
|
|
cancellation.Cancel();
|
|
}
|
|
catch (ObjectDisposedException)
|
|
{
|
|
}
|
|
}
|
|
|
|
/// <summary>Stops the job to yield to <paramref name="to"/>; false when it is yielding already.</summary>
|
|
public bool Yield(Job to)
|
|
{
|
|
if (Interlocked.CompareExchange(ref _yieldsTo, to, null) is not null) return false;
|
|
Stop();
|
|
return true;
|
|
}
|
|
}
|
|
}
|