Owner review 1, phase 2 (docs/requests/2026-10-15-owner-review-1.md, R2). Jobs now run one at a time on the desktop and on the server. Parallelism (Settings > Rendering, TITANO_PARALLELISM) is how many photos the running job processes at once: thumbnail and proxy passes draw that many photos together and still write the pack and checkpoints in frame order, decode tiers are probed that many at a time, the deep analysis measures that many frames and a render decodes that many ahead. Wherever originals are developed whole (TIFF, PNG, RAW without a usable preview), fewer run at once within the memory budget, which the running job now has whole; the server's frame window is sized to the host instead of 1 GiB. A new job waits its turn and pausing the running job starts the next one. An optional priority queue gives each job kind a level (renders, imports and downloads high, verifies and proxies low by default): a queued job of a higher level pauses the running one without asking, and that job goes back to the queue with its checkpoint and resumes by itself afterwards. Jobs of the same level, and a job's own follow-ups, never interrupt it. The Jobs screen and the admin panel show the parallelism and the queue; Settings > Rendering and the admin panel's Settings set them, at once. TITANO_WORKERS and the Workers key of server.json still set the parallelism (1 to 64, with a warning at start for the variable). Titano.Tools gains i18n prune, which removed the renamed keys from the 36 machine-translated languages; the new strings are translated in all 38. Found while testing: uploads and imports failed when a pass read the sidecar while they wrote it (atomic writes now retry the rename while a reader holds the file, and never for a read-only one), and taking a lease just released while another process read it failed on Windows (the create now waits for the reader). Five adversarial review rounds checked the phase before this commit. Also updates BRIEF (12.8, 14.6, 14.8, 14.9, 24), DECISIONS, CHANGELOG, ARCHITECTURE, STATUS, the request file and the compose/Unraid templates. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
513 lines
24 KiB
C#
513 lines
24 KiB
C#
using System.Collections.Concurrent;
|
|
using System.Threading.Channels;
|
|
using Titano.Core.Diagnostics;
|
|
using Titano.Core.Localization;
|
|
using Titano.Core.Model;
|
|
|
|
namespace Titano.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>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;
|
|
|
|
/// <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. 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 TitanoDatabase _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(TitanoDatabase 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 (high frequency; throttle in the UI).</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, purges old history 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);
|
|
_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, cancellationToken);
|
|
|
|
/// <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);
|
|
|
|
/// <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));
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
if (context.FirstProgressFailure()) Log.Warning("jobs", $"Progress of {context.Job.Kind} job {context.Job.Id} not published", ex);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Saves progress, 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, 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, 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, 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,
|
|
};
|
|
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.ListQueuedAsync(_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)
|
|
{
|
|
foreach (var queued in await _db.Jobs.ListQueuedAsync(_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.");
|
|
await handler.RunAsync(context).ConfigureAwait(false);
|
|
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 _);
|
|
// 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 _);
|
|
}
|
|
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;
|
|
|
|
public Job Job { get; } = job;
|
|
|
|
/// <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;
|
|
}
|
|
}
|
|
}
|