using System.Collections.Concurrent; using System.Threading.Channels; using Titano.Core.Diagnostics; using Titano.Core.Model; namespace Titano.Data.Jobs; public sealed record JobEngineOptions { /// Concurrent workers (BRIEF §14.6: default cores / 2). public int Workers { get; init; } = Math.Max(1, Environment.ProcessorCount / 2); /// 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); /// Fallback poll for jobs enqueued by other processes. public TimeSpan PollInterval { get; init; } = TimeSpan.FromSeconds(3); /// Finished jobs older than this are purged (BRIEF §14.6: 90 days). public TimeSpan HistoryRetention { get; init; } = TimeSpan.FromDays(90); } /// /// Persistent job queue runner (BRIEF §14.6): N workers claim queued jobs from the database by priority, run the /// registered handler, checkpoint progress, and survive crashes (running jobs are requeued at start with their /// checkpoints). Used by the desktop client (local mode) and the server. /// public sealed class JobEngine : IAsyncDisposable { private readonly TitanoDatabase _db; private readonly Dictionary _handlers; private readonly ConcurrentDictionary _running = new(); private readonly Channel _wake = Channel.CreateBounded(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite }); private readonly CancellationTokenSource _shutdown = new(); private readonly List _workers = []; public JobEngine(TitanoDatabase 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 (high frequency; throttle in the UI). public event Action? Progress; public IReadOnlyCollection RunningJobIds => [.. _running.Keys]; /// Requeues this worker's interrupted jobs, purges old history and starts the workers. 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); for (var i = 0; i < Options.Workers; i++) { var id = Options.Workers == 1 ? Options.WorkerId : $"{Options.WorkerId}#{i}"; _workers.Add(Task.Run(() => WorkerLoopAsync(id, _shutdown.Token), CancellationToken.None)); } } /// Queues a job and wakes a worker. public async Task EnqueueAsync(JobKind kind, IReadOnlyList targets, string? targetLabel = null, string? parametersJson = null, JobPriority priority = JobPriority.Normal, Guid? createdBy = null, CancellationToken cancellationToken = default) { var job = new Job { Id = Guid.CreateVersion7(), 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; } /// Cancels a queued or running job; a running handler observes its token. public Task CancelAsync(Guid id, CancellationToken cancellationToken = default) => TransitionAsync(id, JobState.Cancelled, cancellationToken); /// Pauses a job: a running one stops at its next check and keeps its checkpoint. 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 workers that new work may be available (also call on PostgreSQL NOTIFY). public void Wake() => _wake.Writer.TryWrite(true); public async ValueTask DisposeAsync() { await _shutdown.CancelAsync().ConfigureAwait(false); try { await Task.WhenAll(_workers).ConfigureAwait(false); } catch (OperationCanceledException) { } _shutdown.Dispose(); } internal void PublishProgress(JobContext context) { 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)); } internal async Task PersistAsync(JobContext context) { var (rate, eta) = context.Rate(); try { 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; } } internal void StopJob(Guid id) { if (_running.TryGetValue(id, out var cts)) cts.Cancel(); } 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); } private async Task WorkerLoopAsync(string workerId, CancellationToken shutdown) { var kinds = Options.Kinds ?? [.. _handlers.Keys]; while (!shutdown.IsCancellationRequested) { Job? job; try { job = await _db.Jobs.ClaimNextAsync(workerId, kinds, shutdown).ConfigureAwait(false); } catch (OperationCanceledException) { return; } catch (DatabaseException ex) { Log.Warning("jobs", "Claiming a job failed", ex); job = null; } if (job is null) { using var timeout = CancellationTokenSource.CreateLinkedTokenSource(shutdown); timeout.CancelAfter(Options.PollInterval); try { await _wake.Reader.ReadAsync(timeout.Token).ConfigureAwait(false); } catch (OperationCanceledException) { // Poll interval elapsed or shutdown. } continue; } await RunAsync(job, shutdown).ConfigureAwait(false); } } private async Task RunAsync(Job job, CancellationToken shutdown) { using var cts = CancellationTokenSource.CreateLinkedTokenSource(shutdown); _running[job.Id] = cts; JobChanged?.Invoke(job); 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) { await PersistAsync(context).ConfigureAwait(false); if (shutdown.IsCancellationRequested) { // Engine stopping: leave the job running so the next start requeues it from its checkpoint. _running.TryRemove(job.Id, out _); return; } // Cancel or pause already wrote the state; keep it. _running.TryRemove(job.Id, out _); 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); } }