Adds the company tables of SPEC 11.1 behind one generic service so that every table gets the same rules, history, cache and CSV import/export, plus the company profile, fiscal years with monthly lock and the base-data seeder. - 26 coded tables, exchange rates, company profile, fiscal years and periods: entities, maps and migrations 010-014 - TableService + TableCatalog: unique codes, per-table rules (VAT codes are checked by the fiscal pack), delete or disable when in use, single default, CSV export/import all-or-nothing, cache with cross-instance invalidation - CompanyProfileService (Italian identifiers through the pack), FiscalYearService with the date check used by every dated record - EcbRatesClient and the ECB rates system task; CsvReader - ISeeder/SeedRunner with the data version in company settings; base tables from the pack (IBaseTablesTemplate) and an embedded ISO country list Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
365 lines
17 KiB
C#
365 lines
17 KiB
C#
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;
|
|
|
|
/// <summary>What a job run receives.</summary>
|
|
/// <param name="Task">The task (code, company, parameters).</param>
|
|
/// <param name="Attempt">The attempt number, from 1.</param>
|
|
/// <param name="TraceId">The trace identifier of the run, also in the log.</param>
|
|
public sealed record JobContext(ScheduledTask Task, int Attempt, string TraceId);
|
|
|
|
/// <summary>
|
|
/// A kind of job the scheduler can run (SPEC §9.4). Modules register theirs (e-mail import, SDI polling, reminders,
|
|
/// backups); <see cref="Type"/> is what <c>sys_scheduled_tasks.job_type</c> names.
|
|
/// </summary>
|
|
public interface IScheduledJob
|
|
{
|
|
/// <summary>The job type.</summary>
|
|
string Type { get; }
|
|
|
|
/// <summary>Runs the job. The token is cancelled at the task timeout or at shutdown.</summary>
|
|
/// <param name="context">The run.</param>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns>A message for the run history, or <see langword="null"/>.</returns>
|
|
Task<string?> RunAsync(JobContext context, CancellationToken cancellationToken);
|
|
}
|
|
|
|
/// <summary>A task created at start when missing.</summary>
|
|
/// <param name="Code">The task code.</param>
|
|
/// <param name="Name">The name shown.</param>
|
|
/// <param name="JobType">The job type.</param>
|
|
/// <param name="Cron">When it runs.</param>
|
|
/// <param name="TimeoutSeconds">Its timeout.</param>
|
|
/// <param name="UsesNetwork">Whether it calls services outside the instance (the tests run it with a stub).</param>
|
|
public sealed record SystemTaskDefinition(string Code, string Name, string JobType, string Cron, int TimeoutSeconds = 600, bool UsesNetwork = false);
|
|
|
|
/// <summary>
|
|
/// The scheduler (SPEC §9.4; mockup 083): reads <c>sys_scheduled_tasks</c>, runs the due ones with a lock in
|
|
/// <c>sys_job_locks</c> (so two instances never run the same task together), applies timeout and retries, writes
|
|
/// <c>sys_job_runs</c> and the section <i>Attività programmate</i> of the log, and notifies the instance accounts when a
|
|
/// task fails for good.
|
|
/// </summary>
|
|
public sealed class JobScheduler
|
|
{
|
|
/// <summary>The system tasks (M2, attachments trash from M3, ECB rates from M4).</summary>
|
|
public static readonly IReadOnlyList<SystemTaskDefinition> 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<string, IScheduledJob> _jobs;
|
|
private readonly NotificationDispatcher _notifications;
|
|
private readonly TimeProvider _clock;
|
|
private readonly ILogger<JobScheduler> _logger;
|
|
private readonly string _owner = Environment.MachineName + ":" + Environment.ProcessId;
|
|
|
|
/// <summary>Creates the scheduler.</summary>
|
|
/// <param name="factory">Opens the system database.</param>
|
|
/// <param name="jobs">The job types.</param>
|
|
/// <param name="notifications">Notifies failures.</param>
|
|
/// <param name="clock">The clock.</param>
|
|
/// <param name="logger">The log.</param>
|
|
public JobScheduler(IUnitOfWorkFactory factory, IEnumerable<IScheduledJob> jobs, NotificationDispatcher notifications, TimeProvider clock, ILogger<JobScheduler> 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;
|
|
}
|
|
|
|
/// <summary>Creates the system tasks that are missing and computes the next run of every task without one.</summary>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns>A task.</returns>
|
|
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<ScheduledTask, long>();
|
|
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<ScheduledTask>().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);
|
|
}
|
|
|
|
/// <summary>Runs every enabled task that is due, one after the other.</summary>
|
|
/// <param name="cancellationToken">Cancellation (shutdown).</param>
|
|
/// <returns>How many tasks ran.</returns>
|
|
public async Task<int> RunDueAsync(CancellationToken cancellationToken = default)
|
|
{
|
|
var now = _clock.GetUtcNow().UtcDateTime;
|
|
IReadOnlyList<ScheduledTask> due;
|
|
await using (var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false))
|
|
{
|
|
due = (await unitOfWork.Repository<ScheduledTask, long>().ListAsync(
|
|
Query.For<ScheduledTask>().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;
|
|
}
|
|
|
|
/// <summary>Runs a task now (also "Esegui ora" from the administration page).</summary>
|
|
/// <param name="code">The task code.</param>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns>The outcome; <see cref="JobOutcome.Skipped"/> when another run holds the lock.</returns>
|
|
public async Task<JobOutcome> RunAsync(string code, CancellationToken cancellationToken = default)
|
|
{
|
|
ScheduledTask? task;
|
|
await using (var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false))
|
|
{
|
|
task = await unitOfWork.Repository<ScheduledTask, long>().FindAsync(Query.For<ScheduledTask>().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<JobOutcome> 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<string, object?> { [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<ScheduledTask, long>();
|
|
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<long> SaveRunAsync(JobRun run, bool insert, CancellationToken cancellationToken)
|
|
{
|
|
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.System, cancellationToken).ConfigureAwait(false);
|
|
var runs = unitOfWork.Repository<JobRun, long>();
|
|
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<bool> 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<JobLock, string>();
|
|
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);
|
|
}
|
|
}
|
|
|
|
/// <summary>Runs the scheduler every 30 seconds once the instance is ready.</summary>
|
|
/// <param name="scheduler">The scheduler.</param>
|
|
/// <param name="state">The start state.</param>
|
|
/// <param name="logger">The log.</param>
|
|
public sealed class JobSchedulerService(JobScheduler scheduler, BootstrapState state, ILogger<JobSchedulerService> logger) : BackgroundService
|
|
{
|
|
/// <summary>How often due tasks are looked for.</summary>
|
|
public static readonly TimeSpan Interval = TimeSpan.FromSeconds(30);
|
|
|
|
/// <inheritdoc />
|
|
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));
|
|
}
|
|
}
|