using System.Diagnostics; using Khaemhat.Application.Instance; using Khaemhat.Application.Notifications; using Khaemhat.Core.Instance; using Khaemhat.Core.Logging; using Khaemhat.Core.Scheduling; using Khaemhat.Data; using Khaemhat.Data.Querying; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace Khaemhat.Application.Jobs; /// What a job run receives. /// The task (code, company, parameters). /// The attempt number, from 1. /// The trace identifier of the run, also in the log. public sealed record JobContext(ScheduledTask Task, int Attempt, string TraceId); /// /// A kind of job the scheduler can run (SPEC §9.4). Modules register theirs (e-mail import, SDI polling, reminders, /// backups); is what sys_scheduled_tasks.job_type names. /// public interface IScheduledJob { /// The job type. string Type { get; } /// Runs the job. The token is cancelled at the task timeout or at shutdown. /// The run. /// Cancellation. /// A message for the run history, or . Task RunAsync(JobContext context, CancellationToken cancellationToken); } /// A task created at start when missing. /// The task code. /// The name shown. /// The job type. /// When it runs. /// Its timeout. /// Whether it calls services outside the instance (the tests run it with a stub). public sealed record SystemTaskDefinition(string Code, string Name, string JobType, string Cron, int TimeoutSeconds = 600, bool UsesNetwork = false); /// /// The scheduler (SPEC §9.4; mockup 083): reads sys_scheduled_tasks, runs the due ones with a lock in /// sys_job_locks (so two instances never run the same task together), applies timeout and retries, writes /// sys_job_runs and the section Attività programmate of the log, and notifies the instance accounts when a /// task fails for good. /// public sealed class JobScheduler { /// The system tasks (M2, attachments trash from M3, ECB rates from M4). public static readonly IReadOnlyList SystemTasks = [ new("system.sessions-cleanup", "Pulizia sessioni scadute", SessionCleanupJob.JobType, "15 * * * *", 300), new("system.license-check", "Verifica licenza", LicenseCheckJob.JobType, "0 * * * *", 120), new("system.log-retention", "Conservazione del log", LogRetentionJob.JobType, "30 3 * * *", 1800), new("system.attachments-trash", "Svuotamento cestino allegati", Files.AttachmentTrashPurgeJob.JobType, "45 3 * * *", 1800), new("system.ecb-rates", "Cambi di riferimento BCE", Tables.EcbRatesJob.JobType, "30 16 * * 1-5", 300, UsesNetwork: true), ]; private readonly IUnitOfWorkFactory _factory; private readonly Dictionary _jobs; private readonly NotificationDispatcher _notifications; private readonly TimeProvider _clock; private readonly ILogger _logger; private readonly string _owner = Environment.MachineName + ":" + Environment.ProcessId; /// Creates the scheduler. /// Opens the system database. /// The job types. /// Notifies failures. /// The clock. /// The log. public JobScheduler(IUnitOfWorkFactory factory, IEnumerable jobs, NotificationDispatcher notifications, TimeProvider clock, ILogger logger) { ArgumentNullException.ThrowIfNull(factory); ArgumentNullException.ThrowIfNull(jobs); ArgumentNullException.ThrowIfNull(notifications); ArgumentNullException.ThrowIfNull(clock); ArgumentNullException.ThrowIfNull(logger); _factory = factory; _jobs = jobs.ToDictionary(j => j.Type, StringComparer.Ordinal); _notifications = notifications; _clock = clock; _logger = logger; } /// Creates the system tasks that are missing and computes the next run of every task without one. /// Cancellation. /// A task. public async Task EnsureSystemTasksAsync(CancellationToken cancellationToken = default) { var now = _clock.GetUtcNow().UtcDateTime; await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false); var tasks = unitOfWork.Repository(); await unitOfWork.InTransactionAsync( async ct => { await unitOfWork.AcquireLockAsync("scheduler-setup", ct).ConfigureAwait(false); foreach (var definition in SystemTasks) { var code = definition.Code; if (await tasks.CountAsync(Query.For().Where(t => t.Code == code), ct).ConfigureAwait(false) == 0) { var task = new ScheduledTask { Code = code, Name = definition.Name, JobType = definition.JobType, Cron = definition.Cron, TimeoutSeconds = definition.TimeoutSeconds, IsSystem = true, }; task.NextRunAt = Next(task, now); await tasks.InsertAsync(task, ct).ConfigureAwait(false); } } }, cancellationToken).ConfigureAwait(false); } /// Runs every enabled task that is due, one after the other. /// Cancellation (shutdown). /// How many tasks ran. public async Task RunDueAsync(CancellationToken cancellationToken = default) { var now = _clock.GetUtcNow().UtcDateTime; IReadOnlyList due; await using (var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false)) { due = (await unitOfWork.Repository().ListAsync( Query.For().Where(t => t.IsEnabled && t.NextRunAt != null && t.NextRunAt <= now).OrderBy(t => t.NextRunAt), cancellationToken) .ConfigureAwait(false)).Items; } var count = 0; foreach (var task in due) { cancellationToken.ThrowIfCancellationRequested(); if (await RunAsync(task.Code, cancellationToken).ConfigureAwait(false) is not JobOutcome.Skipped) { count++; } } return count; } /// Runs a task now (also "Esegui ora" from the administration page). /// The task code. /// Cancellation. /// The outcome; when another run holds the lock. public async Task RunAsync(string code, CancellationToken cancellationToken = default) { ScheduledTask? task; await using (var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false)) { task = await unitOfWork.Repository().FindAsync(Query.For().Where(t => t.Code == code), cancellationToken).ConfigureAwait(false); } if (task is null) { throw new KeyNotFoundException($"No scheduled task has code {code}."); } var timeout = TimeSpan.FromSeconds(Math.Max(1, task.TimeoutSeconds)); if (!await TryLockAsync(task.Code, timeout, cancellationToken).ConfigureAwait(false)) { return JobOutcome.Skipped; } try { return await RunLockedAsync(task, timeout, cancellationToken).ConfigureAwait(false); } finally { await UnlockAsync(task.Code).ConfigureAwait(false); } } private async Task RunLockedAsync(ScheduledTask task, TimeSpan timeout, CancellationToken cancellationToken) { using var section = _logger.BeginScope(LogSections.Scope(LogSection.ScheduledJobs)); var outcome = JobOutcome.Failed; string? message = null; for (var attempt = 1; attempt <= task.MaxRetries + 1; attempt++) { var traceId = ActivityTraceId.CreateRandom().ToString(); using var scope = _logger.BeginScope(new Dictionary { [LogSections.TraceIdKey] = traceId, [LogSections.CompanyKey] = task.CompanyCode }); var run = new JobRun { TaskCode = task.Code, StartedAt = _clock.GetUtcNow().UtcDateTime, Outcome = JobOutcome.Running, Attempt = attempt, TraceId = traceId }; run.Id = await SaveRunAsync(run, insert: true, cancellationToken).ConfigureAwait(false); (outcome, message) = await ExecuteAsync(task, new JobContext(task, attempt, traceId), timeout, cancellationToken).ConfigureAwait(false); run.Outcome = outcome; run.Message = message is { Length: > 2000 } ? message[..2000] : message; run.FinishedAt = _clock.GetUtcNow().UtcDateTime; await SaveRunAsync(run, insert: false, CancellationToken.None).ConfigureAwait(false); if (outcome == JobOutcome.Succeeded || cancellationToken.IsCancellationRequested) { break; } } await FinishAsync(task, outcome, cancellationToken).ConfigureAwait(false); if (outcome is JobOutcome.Failed or JobOutcome.TimedOut) { await _notifications.NotifyInstanceAsync( new NotificationMessage("jobs", NotificationSeverity.Error, $"Attività «{task.Name}» non riuscita", message, "/amministrazione/attivita"), cancellationToken: CancellationToken.None).ConfigureAwait(false); } return outcome; } private async Task<(JobOutcome Outcome, string? Message)> ExecuteAsync(ScheduledTask task, JobContext context, TimeSpan timeout, CancellationToken cancellationToken) { if (!_jobs.TryGetValue(task.JobType, out var job)) { _logger.LogError("Task {Task}: job type {JobType} is not known.", task.Code, task.JobType); return (JobOutcome.Failed, "Tipo di attività sconosciuto: " + task.JobType); } using var timeoutSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); timeoutSource.CancelAfter(timeout); var started = Stopwatch.GetTimestamp(); try { var message = await job.RunAsync(context, timeoutSource.Token).ConfigureAwait(false); _logger.LogInformation("Task {Task} completed in {Milliseconds} ms. {Message}", task.Code, (long)Stopwatch.GetElapsedTime(started).TotalMilliseconds, message); return (JobOutcome.Succeeded, message); } catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) { _logger.LogError("Task {Task} stopped after the timeout of {Seconds} s (attempt {Attempt}).", task.Code, (int)timeout.TotalSeconds, context.Attempt); return (JobOutcome.TimedOut, $"Interrotta dopo {(int)timeout.TotalSeconds} secondi."); } catch (Exception ex) when (ex is not OperationCanceledException) { _logger.LogError(ex, "Task {Task} failed (attempt {Attempt}).", task.Code, context.Attempt); return (JobOutcome.Failed, ex.Message); } } private async Task FinishAsync(ScheduledTask task, JobOutcome outcome, CancellationToken cancellationToken) { var now = _clock.GetUtcNow().UtcDateTime; await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, CancellationToken.None).ConfigureAwait(false); var tasks = unitOfWork.Repository(); var current = await tasks.GetAsync(task.Id, CancellationToken.None).ConfigureAwait(false); if (current is null) { return; } current.LastRunAt = now; current.LastOutcome = outcome; current.NextRunAt = Next(current, now); await tasks.UpdateAsync(current, cancellationToken.IsCancellationRequested ? CancellationToken.None : cancellationToken).ConfigureAwait(false); } private async Task SaveRunAsync(JobRun run, bool insert, CancellationToken cancellationToken) { await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false); var runs = unitOfWork.Repository(); if (insert) { return await runs.InsertAsync(run, cancellationToken).ConfigureAwait(false); } await runs.UpdateAsync(run, cancellationToken).ConfigureAwait(false); return run.Id; } // A lock row per task; an expired lock (a process that died) is taken over. private async Task TryLockAsync(string code, TimeSpan timeout, CancellationToken cancellationToken) { var now = _clock.GetUtcNow().UtcDateTime; await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false); var locks = unitOfWork.Repository(); var acquired = false; await unitOfWork.InTransactionAsync( async ct => { await unitOfWork.AcquireLockAsync("job-locks", ct).ConfigureAwait(false); var existing = await locks.GetAsync(code, ct).ConfigureAwait(false); if (existing is not null && existing.ExpiresAt > now) { return; } if (existing is not null) { await locks.DeleteAsync(code, ct).ConfigureAwait(false); } await locks.InsertAsync(new JobLock { Id = code, Owner = _owner, AcquiredAt = now, ExpiresAt = now + timeout + TimeSpan.FromMinutes(1) }, ct).ConfigureAwait(false); acquired = true; }, cancellationToken).ConfigureAwait(false); return acquired; } private async Task UnlockAsync(string code) { await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, CancellationToken.None).ConfigureAwait(false); var owner = _owner; await unitOfWork.ExecuteAsync( SqlFragment.Of($"DELETE FROM {SqlFragment.Identifier("sys_job_locks")} WHERE id = {code} AND owner = {owner}"), CancellationToken.None).ConfigureAwait(false); } private DateTime? Next(ScheduledTask task, DateTime now) { if (!CronExpression.TryParse(task.Cron, out var cron, out _)) { _logger.LogError("Task {Task}: the cron expression '{Cron}' is not valid; the task will not run.", task.Code, task.Cron); return null; } var zone = TimeZoneInfo.TryFindSystemTimeZoneById(task.TimeZone, out var found) ? found : TimeZoneInfo.Utc; return cron.NextAfter(now, zone); } } /// Runs the scheduler every 30 seconds once the instance is ready. /// The scheduler. /// The start state. /// The log. public sealed class JobSchedulerService(JobScheduler scheduler, BootstrapState state, ILogger logger) : BackgroundService { /// How often due tasks are looked for. public static readonly TimeSpan Interval = TimeSpan.FromSeconds(30); /// protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!state.IsReady) { if (state.Phase == BootstrapPhase.Failed) { return; } await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken).ConfigureAwait(false); } await scheduler.EnsureSystemTasksAsync(stoppingToken).ConfigureAwait(false); using var timer = new PeriodicTimer(Interval); do { try { await scheduler.RunDueAsync(stoppingToken).ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException) { using var section = logger.BeginScope(LogSections.Scope(LogSection.ScheduledJobs)); logger.LogError(ex, "The scheduler could not read the tasks."); } } while (await timer.WaitForNextTickAsync(stoppingToken).ConfigureAwait(false)); } }