From 58d7375d6143627b67a816651c57c4b580a292fe Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Thu, 3 Sep 2026 12:49:21 -0700 Subject: [PATCH] Adds the scheduled job executor and SignalR hub --- .../InfrastructureLayerServices.cs | 18 +- .../Execution/IScheduledJobRuntimeRegistry.cs | 39 +++ .../Execution/IScheduledTaskExecutor.cs | 22 ++ .../IScheduledTaskExecutorFactory.cs | 18 ++ .../Execution/ScheduledJobRuntimeRegistry.cs | 73 +++++ .../Execution/ScheduledJobSchedulerJob.cs | 281 ++++++++++++++++++ .../Execution/ScheduledTaskExecutorFactory.cs | 40 +++ .../MediaLibraryScanTaskExecutor.cs | 110 +++++++ .../TemporaryFilesCleanupTaskExecutor.cs | 66 ++++ .../Notifications/IScheduledJobsClient.cs | 34 +++ .../Notifications/ScheduledJobNotifier.cs | 57 ++++ .../Notifications/ScheduledJobsHub.cs | 57 ++++ .../PresentationApiLayerServices.cs | 14 + src/Lumina.Presentation.Api/Program.cs | 10 +- 14 files changed, 834 insertions(+), 5 deletions(-) create mode 100644 src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledJobRuntimeRegistry.cs create mode 100644 src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledTaskExecutor.cs create mode 100644 src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledTaskExecutorFactory.cs create mode 100644 src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobRuntimeRegistry.cs create mode 100644 src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs create mode 100644 src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledTaskExecutorFactory.cs create mode 100644 src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutor.cs create mode 100644 src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/TemporaryFilesCleanupTaskExecutor.cs create mode 100644 src/Lumina.Infrastructure/Core/Scheduling/Notifications/IScheduledJobsClient.cs create mode 100644 src/Lumina.Infrastructure/Core/Scheduling/Notifications/ScheduledJobNotifier.cs create mode 100644 src/Lumina.Infrastructure/Core/Scheduling/Notifications/ScheduledJobsHub.cs diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index 39fc1f8a..11134530 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -8,12 +8,14 @@ using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; using Lumina.Application.Common.Infrastructure.Plugins; using Lumina.Application.Common.Infrastructure.Reading; using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Application.Common.Infrastructure.Scheduling; using Lumina.Application.Common.Infrastructure.Themes; using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.MediaLibrary.Management.Progress; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +using Lumina.Application.Core.Scheduling.Notifications; using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; @@ -34,6 +36,9 @@ using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue; using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; using Lumina.Infrastructure.Core.Plugins; +using Lumina.Infrastructure.Core.Scheduling.Execution; +using Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors; +using Lumina.Infrastructure.Core.Scheduling.Notifications; using Lumina.Infrastructure.Core.Security; using Lumina.Infrastructure.Core.Themes; using Lumina.Infrastructure.Core.Time; @@ -113,8 +118,8 @@ public static class InfrastructureLayerServices services.AddHttpClient(); services.AddScoped(); - // Book reading: resolves the book reader plugins, extracts the books into a temporary directory, and serves their contents; - // the enablement cache lets the reading service skip the per-request database read of the reader configurations. + // Book reading: resolves the book reader plugins, extracts the books into a temporary directory, and serves their contents. + // The enablement cache lets the reading service skip the per-request database read of the reader configurations. services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); @@ -138,6 +143,15 @@ public static class InfrastructureLayerServices services.AddSingleton(); services.AddHostedService(); + // Scheduled jobs: the scheduler executes the tasks of the scheduled jobs on their schedules, and the notifier broadcasts their state to the SignalR clients. + services.AddSingleton(); + services.AddHostedService(serviceProvider => (ScheduledJobSchedulerJob)serviceProvider.GetRequiredService()); + services.AddSingleton(); + services.AddSingleton(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + return services; } } diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledJobRuntimeRegistry.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledJobRuntimeRegistry.cs new file mode 100644 index 00000000..73c671c2 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledJobRuntimeRegistry.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using System.Threading; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Execution; + +/// +/// Interface for the registry that holds the live runtime state of the scheduled jobs. +/// +public interface IScheduledJobRuntimeRegistry +{ + /// + /// Starts the execution cycle of the scheduled job identified by . + /// + /// The object representing the unique identifier of the scheduled job whose cycle is started. + /// The cancellation token source used to stop the execution cycle. + /// when the cycle was started, when a cycle was already running. + bool TryStartCycle(ScheduledJobId scheduledJobId, CancellationTokenSource cycleCancellationTokenSource); + + /// + /// Stops the execution cycle of the scheduled job identified by . + /// + /// The object representing the unique identifier of the scheduled job whose cycle is stopped. + void StopCycle(ScheduledJobId scheduledJobId); + + /// + /// Attempts to reserve the execution slot of the scheduled job identified by . + /// + /// The object representing the unique identifier of the scheduled job whose execution slot is reserved. + /// when the slot was reserved, when another execution is already running. + bool TryAcquireRunSlot(ScheduledJobId scheduledJobId); + + /// + /// Releases the execution slot of the scheduled job identified by . + /// + /// The object representing the unique identifier of the scheduled job whose execution slot is released. + void ReleaseRunSlot(ScheduledJobId scheduledJobId); +} diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledTaskExecutor.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledTaskExecutor.cs new file mode 100644 index 00000000..98de6300 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledTaskExecutor.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Execution; + +/// +/// Interface for the executor of the task of a scheduled job. +/// +public interface IScheduledTaskExecutor +{ + /// + /// Executes the payload of the task of the scheduled job, asynchronously. + /// + /// The scheduled job whose task is executed. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> ExecutePayloadAsync(ScheduledJob scheduledJob, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledTaskExecutorFactory.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledTaskExecutorFactory.cs new file mode 100644 index 00000000..15358b1f --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledTaskExecutorFactory.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Execution; + +/// +/// Interface for the factory that creates the executor of the task of a scheduled job, based on the type of its task. +/// +public interface IScheduledTaskExecutorFactory +{ + /// + /// Creates the executor of the task of a scheduled job, based on the type of its task. + /// + /// The type of the task whose executor is created. + /// The created task executor. + IScheduledTaskExecutor CreateExecutor(ScheduledTaskType taskType); +} diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobRuntimeRegistry.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobRuntimeRegistry.cs new file mode 100644 index 00000000..92230d12 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobRuntimeRegistry.cs @@ -0,0 +1,73 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using System.Collections.Concurrent; +using System.Threading; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Execution; + +/// +/// Registry that holds the live runtime state of the scheduled jobs. +/// +public sealed class ScheduledJobRuntimeRegistry : IScheduledJobRuntimeRegistry +{ + /// + /// Class that holds the live runtime state of the execution cycle of a scheduled job. + /// + private sealed class ScheduledJobRuntimeState + { + public CancellationTokenSource? CycleCancellationTokenSource; + public readonly SemaphoreSlim RunSlot = new(1, 1); + } + + private readonly ConcurrentDictionary _runtimeStates = []; + + /// + /// Starts the execution cycle of the scheduled job identified by . + /// + /// The object representing the unique identifier of the scheduled job whose cycle is started. + /// The cancellation token source used to stop the execution cycle. + /// when the cycle was started, when a cycle was already running. + public bool TryStartCycle(ScheduledJobId scheduledJobId, CancellationTokenSource cycleCancellationTokenSource) + { + ScheduledJobRuntimeState state = _runtimeStates.GetOrAdd(scheduledJobId, static _ => new ScheduledJobRuntimeState()); + if (state.CycleCancellationTokenSource is not null) + return false; + state.CycleCancellationTokenSource = cycleCancellationTokenSource; + return true; + } + + /// + /// Stops the execution cycle of the scheduled job identified by . + /// + /// The object representing the unique identifier of the scheduled job whose cycle is stopped. + public void StopCycle(ScheduledJobId scheduledJobId) + { + if (!_runtimeStates.TryGetValue(scheduledJobId, out ScheduledJobRuntimeState? state)) + return; + CancellationTokenSource? cycleCancellationTokenSource = state.CycleCancellationTokenSource; + state.CycleCancellationTokenSource = null; + cycleCancellationTokenSource?.Cancel(); + } + + /// + /// Attempts to reserve the execution slot of the scheduled job identified by . + /// + /// The object representing the unique identifier of the scheduled job whose execution slot is reserved. + /// when the slot was reserved, when another execution is already running. + public bool TryAcquireRunSlot(ScheduledJobId scheduledJobId) + { + ScheduledJobRuntimeState state = _runtimeStates.GetOrAdd(scheduledJobId, static _ => new ScheduledJobRuntimeState()); + return state.RunSlot.Wait(0); + } + + /// + /// Releases the execution slot of the scheduled job identified by . + /// + /// The object representing the unique identifier of the scheduled job whose execution slot is released. + public void ReleaseRunSlot(ScheduledJobId scheduledJobId) + { + if (_runtimeStates.TryGetValue(scheduledJobId, out ScheduledJobRuntimeState? state)) + state.RunSlot.Release(); + } +} diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs new file mode 100644 index 00000000..8a4fe0c7 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs @@ -0,0 +1,281 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Scheduling; +using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Application.Common.Mapping.Scheduling; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Execution; + +/// +/// Background service that schedules and executes the tasks of the scheduled jobs. +/// +public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobScheduler +{ + private readonly IServiceScopeFactory _serviceScopeFactory; + private readonly IScheduledJobRuntimeRegistry _runtimeRegistry; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// Injected registry that holds the live runtime state of the scheduled jobs. + /// Injected service for logging. + /// Injected factory used for creating scopes in which services are requested. + public ScheduledJobSchedulerJob(IScheduledJobRuntimeRegistry runtimeRegistry, ILogger logger, IServiceScopeFactory serviceScopeFactory) + { + _serviceScopeFactory = serviceScopeFactory; + _runtimeRegistry = runtimeRegistry; + _logger = logger; + } + + /// + /// Starts the execution cycle of the scheduled job identified by . + /// + /// The object representing the unique identifier of the scheduled job whose execution cycle is started. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + public Task StartCycleAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken) + { + RunCycleWorkerAsync(scheduledJobId, runImmediately: true, cancellationToken).FireAndForgetSafeAsync(); + return Task.CompletedTask; + } + + /// + /// Stops the execution cycle of the scheduled job identified by . + /// + /// The object representing the unique identifier of the scheduled job whose execution cycle is stopped. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + public Task StopCycleAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken) + { + _runtimeRegistry.StopCycle(scheduledJobId); + return Task.CompletedTask; + } + + /// + /// Fires the task of the scheduled job identified by once, without affecting its execution cycle. + /// + /// The object representing the unique identifier of the scheduled job whose task is fired. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + public Task RunOnceAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken) + { + RunOnceWorkerAsync(scheduledJobId, cancellationToken).FireAndForgetSafeAsync(); + return Task.CompletedTask; + } + + /// + /// Method called when the background service starts; resumes the execution cycles of the scheduled jobs whose cycle was active. + /// + /// Cancellation token that can be used to stop the execution. + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + await ResumeActiveCyclesAsync(stoppingToken).ConfigureAwait(false); + try + { + await Task.Delay(Timeout.InfiniteTimeSpan, stoppingToken).ConfigureAwait(false); + } + catch (OperationCanceledException) { } + } + + /// + /// Resumes the execution cycles of the scheduled jobs whose cycle was active when the application shut down. + /// + /// Cancellation token that can be used to stop the execution. + private async Task ResumeActiveCyclesAsync(CancellationToken cancellationToken) + { + await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = scope.ServiceProvider.GetRequiredService(); + Result> getScheduledJobsResult = await unitOfWork.ScheduledJobRepository.GetActiveOrRunningAsync(cancellationToken).ConfigureAwait(false); + if (getScheduledJobsResult.IsFailure) + { + _logger.LogWarning("Failed to read the scheduled jobs to resume: {Error}", getScheduledJobsResult.FirstError.Description); + return; + } + foreach (ScheduledJobEntity scheduledJob in getScheduledJobsResult.Value) + RunCycleWorkerAsync(ScheduledJobId.Create(scheduledJob.Id), runImmediately: false, cancellationToken).FireAndForgetSafeAsync(); + } + + /// + /// Runs the execution cycle worker of the scheduled job identified by . + /// + /// The object representing the unique identifier of the scheduled job whose cycle is run. + /// Whether the task of the scheduled job is run immediately when the cycle starts. + /// Cancellation token that can be used to stop the execution. + private async Task RunCycleWorkerAsync(ScheduledJobId scheduledJobId, bool runImmediately, CancellationToken stoppingToken) + { + CancellationTokenSource cycleCancellationTokenSource = new(); + if (!_runtimeRegistry.TryStartCycle(scheduledJobId, cycleCancellationTokenSource)) + { + cycleCancellationTokenSource.Dispose(); + return; + } + + try + { + CancellationToken cycleToken = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken, cycleCancellationTokenSource.Token).Token; + if (runImmediately) + await RunScheduledJobAsync(scheduledJobId, isCycleRun: true, cycleToken).ConfigureAwait(false); + + Schedule? schedule = await GetScheduleAsync(scheduledJobId, cycleToken).ConfigureAwait(false); + if (schedule is null) + return; + + while (true) + { + TimeSpan delay = await CalculateDelayAsync(schedule).ConfigureAwait(false); + using PeriodicTimer timer = new(delay); + while (await timer.WaitForNextTickAsync(cycleToken).ConfigureAwait(false)) + { + if (cycleToken.IsCancellationRequested) + return; + await RunScheduledJobAsync(scheduledJobId, isCycleRun: true, cycleToken).ConfigureAwait(false); + // A daily schedule needs its delay recalculated after every run, so the next run happens at the next day's hour and minute. + if (schedule.ScheduleType == ScheduleType.DailyAtHourAndMinute) + timer.Period = await CalculateDelayAsync(schedule).ConfigureAwait(false); + } + } + } + catch (OperationCanceledException) { } + catch (Exception exception) + { + _logger.LogError(exception, "The execution cycle of the scheduled job '{ScheduledJobId}' failed.", scheduledJobId.Value); + } + finally + { + _runtimeRegistry.StopCycle(scheduledJobId); + cycleCancellationTokenSource.Dispose(); + } + } + + /// + /// Runs the task of the scheduled job identified by once. + /// + /// The object representing the unique identifier of the scheduled job whose task is run. + /// Cancellation token that can be used to stop the execution. + private async Task RunOnceWorkerAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken) + { + try + { + await RunScheduledJobAsync(scheduledJobId, isCycleRun: false, cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) { } + catch (Exception exception) + { + _logger.LogError(exception, "The one time execution of the scheduled job '{ScheduledJobId}' failed.", scheduledJobId.Value); + } + } + + /// + /// Runs the task of the scheduled job identified by , guarding it against overlapping executions. + /// + /// The object representing the unique identifier of the scheduled job whose task is run. + /// Whether the execution was triggered by the execution cycle of the scheduled job, or it is a one time execution. + /// Cancellation token that can be used to stop the execution. + private async Task RunScheduledJobAsync(ScheduledJobId scheduledJobId, bool isCycleRun, CancellationToken cancellationToken) + { + // Skip the execution when another execution of the same scheduled job is already running. + if (!_runtimeRegistry.TryAcquireRunSlot(scheduledJobId)) + return; + try + { + await ExecuteScheduledJobRunAsync(scheduledJobId, isCycleRun, cancellationToken).ConfigureAwait(false); + } + finally + { + _runtimeRegistry.ReleaseRunSlot(scheduledJobId); + } + } + + /// + /// Executes a single run of the task of the scheduled job identified by . + /// + /// The object representing the unique identifier of the scheduled job whose task is run. + /// Whether the execution was triggered by the execution cycle of the scheduled job, or it is a one time execution. + /// Cancellation token that can be used to stop the execution. + private async Task ExecuteScheduledJobRunAsync(ScheduledJobId scheduledJobId, bool isCycleRun, CancellationToken cancellationToken) + { + // A run that was requested to stop before it started must not start at all. + if (cancellationToken.IsCancellationRequested) + return; + + await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope(); + IServiceProvider services = scope.ServiceProvider; + IUnitOfWork unitOfWork = services.GetRequiredService(); + IDomainEventPublisher domainEventPublisher = services.GetRequiredService(); + + // Load the scheduled job, and mark its task as started. + Result getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken).ConfigureAwait(false); + if (getScheduledJobResult.IsFailure || getScheduledJobResult.Value is null) + return; + Result scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity(); + if (scheduledJobDomainResult.IsFailure) + return; + Result startExecutionResult = scheduledJobDomainResult.Value.MarkExecutionStarted(isCycleRun); + if (startExecutionResult.IsFailure) + return; + foreach (IDomainEvent domainEvent in scheduledJobDomainResult.Value.GetDomainEvents()) + await domainEventPublisher.PublishAsync(domainEvent, cancellationToken).ConfigureAwait(false); + + // Execute the payload of the task of the scheduled job. + IScheduledTaskExecutorFactory taskExecutorFactory = services.GetRequiredService(); + IScheduledTaskExecutor taskExecutor = taskExecutorFactory.CreateExecutor(scheduledJobDomainResult.Value.TaskType); + Result executePayloadResult = await taskExecutor.ExecutePayloadAsync(scheduledJobDomainResult.Value, cancellationToken).ConfigureAwait(false); + if (executePayloadResult.IsFailure) + _logger.LogWarning("The task of the scheduled job '{ScheduledJobName}' failed: {Error}", scheduledJobDomainResult.Value.Name, executePayloadResult.FirstError.Description); + + // Mark the task as completed. The same domain entity is reused, because it alone still tracks the run id of the + // current execution, which is required to raise the completion domain event; a fresh copy reloaded from the + // storage medium would no longer know which execution to complete. + Result completeExecutionResult = scheduledJobDomainResult.Value.MarkExecutionCompleted(isCycleRun); + if (completeExecutionResult.IsFailure) + return; + foreach (IDomainEvent domainEvent in scheduledJobDomainResult.Value.GetDomainEvents()) + await domainEventPublisher.PublishAsync(domainEvent, cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets the schedule of the scheduled job identified by , or when it cannot be loaded. + /// + /// The object representing the unique identifier of the scheduled job whose schedule is retrieved. + /// Cancellation token that can be used to stop the execution. + /// The schedule of the scheduled job, or . + private async Task GetScheduleAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken) + { + await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = scope.ServiceProvider.GetRequiredService(); + Result getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken).ConfigureAwait(false); + if (getScheduledJobResult.IsFailure || getScheduledJobResult.Value is null) + return null; + Result scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity(); + return scheduledJobDomainResult.IsFailure ? null : scheduledJobDomainResult.Value.Schedule; + } + + /// + /// Calculates the delay until the next execution of the scheduled job, based on its . + /// + /// The schedule used to calculate the delay. + /// The calculated delay until the next execution of the scheduled job. + private async Task CalculateDelayAsync(Schedule schedule) + { + await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope(); + IDateTimeProvider dateTimeProvider = scope.ServiceProvider.GetRequiredService(); + // The daily hour and minute of a schedule are expressed in the local time of the server, so that a daily schedule follows the clock the server runs on. + return schedule.GetDelayUntilNextExecution(dateTimeProvider.UtcNow, TimeZoneInfo.Local); + } +} diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledTaskExecutorFactory.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledTaskExecutorFactory.cs new file mode 100644 index 00000000..fb00215e --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledTaskExecutorFactory.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors; +using Microsoft.Extensions.DependencyInjection; +using System; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Execution; + +/// +/// Factory that creates the executor of the task of a scheduled job, based on the type of its task. +/// +public class ScheduledTaskExecutorFactory : IScheduledTaskExecutorFactory +{ + private readonly IServiceProvider _serviceProvider; + + /// + /// Initializes a new instance of the class. + /// + /// The service provider. + public ScheduledTaskExecutorFactory(IServiceProvider serviceProvider) + { + _serviceProvider = serviceProvider; + } + + /// + /// Creates the executor of the task of a scheduled job, based on the type of its task. + /// + /// The type of the task whose executor is created. + /// The created task executor. + public IScheduledTaskExecutor CreateExecutor(ScheduledTaskType taskType) + { + return taskType switch + { + ScheduledTaskType.ScanMediaLibraries => _serviceProvider.GetRequiredService(), + ScheduledTaskType.CleanTemporaryFiles => _serviceProvider.GetRequiredService(), + _ => throw new ArgumentException($"Unsupported task type: {taskType}", nameof(taskType)) + }; + } +} diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutor.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutor.cs new file mode 100644 index 00000000..ed8bfaaf --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutor.cs @@ -0,0 +1,110 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors; + +/// +/// Task executor that scans all the enabled media libraries, on behalf of the owner of the scheduled job. +/// +public class MediaLibraryScanTaskExecutor : IScheduledTaskExecutor +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IDomainEventPublisher _domainEventPublisher; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// The domain event publisher used to publish events. + /// Injected service for logging. + /// Injected unit of work for interacting with the data access layer repositories. + public MediaLibraryScanTaskExecutor(IDomainEventPublisher domainEventPublisher, ILogger logger, IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + _domainEventPublisher = domainEventPublisher; + _logger = logger; + } + + /// + /// Scans all the enabled media libraries, on behalf of the owner of the scheduled job. + /// + /// The scheduled job whose task is executed. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> ExecutePayloadAsync(ScheduledJob scheduledJob, CancellationToken cancellationToken) + { + Guid ownerUserId = scheduledJob.OwnerUserId.Value; + + // Get all the enabled and unlocked media libraries. + Result> getLibrariesResult = await _unitOfWork.LibraryRepository.GetAllEnabledAndUnlockedAsync(cancellationToken).ConfigureAwait(false); + if (getLibrariesResult.IsFailure) + return getLibrariesResult.Errors; + + IEnumerable> domainLibrariesResult = getLibrariesResult.Value.ToDomainEntities(); + List domainEvents = []; + + // Start a scan for each media library that is not already being scanned. + foreach (Result domainLibraryResult in domainLibrariesResult) + { + if (domainLibraryResult.IsFailure) + return domainLibraryResult.Errors; + + // Get the past month's scans for this library. + Result> pastLibraryScansResult = await _unitOfWork.LibraryScanRepository + .GetPastMonthScansByLibraryIdAsync(domainLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false); + if (pastLibraryScansResult.IsFailure) + return pastLibraryScansResult.Errors; + + // Convert the repository scans history to domain objects. + IEnumerable> pastLibraryScansDomainResult = pastLibraryScansResult.Value.ToDomainEntities(); + foreach (Result pastLibraryScanDomainResult in pastLibraryScansDomainResult) + if (pastLibraryScanDomainResult.IsFailure) + return pastLibraryScanDomainResult.Errors; + + // Create and queue the media library scan. + Result libraryScanResult = LibraryScan.Create( + LibraryId.Create(domainLibraryResult.Value.Id.Value), + UserId.Create(ownerUserId), + [.. pastLibraryScansDomainResult.Select(pastLibraryScanDomainResult => pastLibraryScanDomainResult.Value)] + ); + if (libraryScanResult.IsFailure) + return libraryScanResult.Errors; + // A media library that is already being scanned is simply skipped, so the other libraries are still scanned. + if (libraryScanResult.Value.QueueScan().IsFailure) + continue; + + Result insertLibraryScanResult = await _unitOfWork.LibraryScanRepository.InsertAsync( + libraryScanResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (insertLibraryScanResult.IsFailure) + return insertLibraryScanResult.Errors; + + domainEvents.AddRange(libraryScanResult.Value.GetDomainEvents()); + } + + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + // Publish the domain events of the queued media library scans. + foreach (IDomainEvent domainEvent in domainEvents) + await _domainEventPublisher.PublishAsync(domainEvent, cancellationToken).ConfigureAwait(false); + + _logger.LogInformation("Scanned all enabled media libraries on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name); + return Result.Success; + } +} diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/TemporaryFilesCleanupTaskExecutor.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/TemporaryFilesCleanupTaskExecutor.cs new file mode 100644 index 00000000..8caabe91 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/TemporaryFilesCleanupTaskExecutor.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; +using Microsoft.Extensions.Logging; +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors; + +/// +/// Task executor that empties the temporary directory into which the reading plugins extract the contents of the books. +/// +public class TemporaryFilesCleanupTaskExecutor : IScheduledTaskExecutor +{ + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for logging. + public TemporaryFilesCleanupTaskExecutor(ILogger logger) + { + _logger = logger; + } + + /// + /// Empties the temporary directory into which the reading plugins extract the contents of the books. + /// + /// The scheduled job whose task is executed. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> ExecutePayloadAsync(ScheduledJob scheduledJob, CancellationToken cancellationToken) + { + string temporaryDirectoryRoot = Path.GetFullPath(ReadingCachePaths.GetRootDirectory()); + string applicationBaseDirectory = Path.GetFullPath(AppContext.BaseDirectory); + StringComparison comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + + // Fail closed when the temporary directory could not be resolved inside the application base directory, so that a misconfiguration can never delete arbitrary directories. + if (string.IsNullOrWhiteSpace(temporaryDirectoryRoot) || + string.Equals(temporaryDirectoryRoot, Path.GetPathRoot(temporaryDirectoryRoot), comparison) || + !temporaryDirectoryRoot.StartsWith(applicationBaseDirectory, comparison) || + string.Equals(temporaryDirectoryRoot, applicationBaseDirectory, comparison)) + { + _logger.LogWarning("The temporary directory to clean could not be resolved safely, so the scheduled job '{ScheduledJobName}' was skipped.", scheduledJob.Name); + return Result.Success; + } + + try + { + if (Directory.Exists(temporaryDirectoryRoot)) + Directory.Delete(temporaryDirectoryRoot, recursive: true); + Directory.CreateDirectory(temporaryDirectoryRoot); + _logger.LogInformation("Emptied the temporary directory '{TemporaryDirectory}'.", temporaryDirectoryRoot); + return Result.Success; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + _logger.LogWarning(exception, "The temporary directory '{TemporaryDirectory}' could not be emptied.", temporaryDirectoryRoot); + return await Task.FromResult(Error.Failure(description: nameof(TemporaryFilesCleanupTaskExecutor))); + } + } +} diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Notifications/IScheduledJobsClient.cs b/src/Lumina.Infrastructure/Core/Scheduling/Notifications/IScheduledJobsClient.cs new file mode 100644 index 00000000..74885209 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Notifications/IScheduledJobsClient.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.Scheduling; +using System.Collections.Generic; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Notifications; + +/// +/// Interface for the SignalR client of the scheduled jobs hub. +/// +public interface IScheduledJobsClient +{ + /// + /// Receives the current list of scheduled jobs. + /// + /// The current list of scheduled jobs. + /// A task that represents the asynchronous operation. + Task ReceiveScheduledJobsAsync(IReadOnlyList scheduledJobs); + + /// + /// Receives an execution of the task of a scheduled job that started. + /// + /// The execution that started. + /// A task that represents the asynchronous operation. + Task ScheduledJobExecutionStartedAsync(ScheduledJobExecutionResponse execution); + + /// + /// Receives an execution of the task of a scheduled job that completed. + /// + /// The execution that completed. + /// A task that represents the asynchronous operation. + Task ScheduledJobExecutionCompletedAsync(ScheduledJobExecutionResponse execution); +} diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Notifications/ScheduledJobNotifier.cs b/src/Lumina.Infrastructure/Core/Scheduling/Notifications/ScheduledJobNotifier.cs new file mode 100644 index 00000000..6ffa1ee5 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Notifications/ScheduledJobNotifier.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Scheduling.Notifications; +using Lumina.Contracts.Responses.Scheduling; +using Microsoft.AspNetCore.SignalR; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Notifications; + +/// +/// Class used to notify SignalR clients about the scheduled jobs and their executions. +/// +public sealed class ScheduledJobNotifier : IScheduledJobNotifier +{ + private readonly IHubContext _hubContext; + + /// + /// Initializes a new instance of the class. + /// + /// SignalR hub context abstraction. + public ScheduledJobNotifier(IHubContext hubContext) + { + _hubContext = hubContext; + } + + /// + /// Notifies the SignalR clients about the current list of scheduled jobs. + /// + /// The current list of scheduled jobs. + /// Cancellation token that can be used to stop the execution. + public async Task SendScheduledJobsAsync(IReadOnlyList scheduledJobs, CancellationToken cancellationToken) + { + await _hubContext.Clients.All.ReceiveScheduledJobsAsync(scheduledJobs).ConfigureAwait(false); + } + + /// + /// Notifies the SignalR clients about an execution of the task of a scheduled job that started. + /// + /// The execution of the task of the scheduled job that started. + /// Cancellation token that can be used to stop the execution. + public async Task SendScheduledJobExecutionStartedAsync(ScheduledJobExecutionResponse execution, CancellationToken cancellationToken) + { + await _hubContext.Clients.All.ScheduledJobExecutionStartedAsync(execution).ConfigureAwait(false); + } + + /// + /// Notifies the SignalR clients about an execution of the task of a scheduled job that completed. + /// + /// The execution of the task of the scheduled job that completed. + /// Cancellation token that can be used to stop the execution. + public async Task SendScheduledJobExecutionCompletedAsync(ScheduledJobExecutionResponse execution, CancellationToken cancellationToken) + { + await _hubContext.Clients.All.ScheduledJobExecutionCompletedAsync(execution).ConfigureAwait(false); + } +} diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Notifications/ScheduledJobsHub.cs b/src/Lumina.Infrastructure/Core/Scheduling/Notifications/ScheduledJobsHub.cs new file mode 100644 index 00000000..4e9958ef --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Notifications/ScheduledJobsHub.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.SignalR; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +using ApplicationAuthorizationService = Lumina.Application.Common.Infrastructure.Authorization.IAuthorizationService; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Notifications; + +/// +/// SignalR hub for broadcasting the state of the scheduled jobs to the connected administrator clients. +/// +[Authorize] +public class ScheduledJobsHub : Hub +{ + private readonly IServiceScopeFactory _serviceScopeFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected factory used for creating scopes in which services are requested. + public ScheduledJobsHub(IServiceScopeFactory serviceScopeFactory) + { + _serviceScopeFactory = serviceScopeFactory; + } + + /// + /// Verifies that the connecting client belongs to an administrator account, and rejects the connection otherwise. + /// + /// A task that represents the asynchronous operation. + public override async Task OnConnectedAsync() + { + string? userIdClaim = Context.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value; + if (!Guid.TryParse(userIdClaim, out Guid userId) || !await IsAdministratorAsync(userId).ConfigureAwait(false)) + { + Context.Abort(); + return; + } + await base.OnConnectedAsync().ConfigureAwait(false); + } + + /// + /// Determines whether the user identified by is an administrator. + /// + /// The unique identifier of the user to check. + /// when the user is an administrator, otherwise. + private async Task IsAdministratorAsync(Guid userId) + { + await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope(); + ApplicationAuthorizationService authorizationService = scope.ServiceProvider.GetRequiredService(); + return await authorizationService.IsInRoleAsync(userId, "Admin", CancellationToken.None).ConfigureAwait(false); + } +} diff --git a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs index 27275cf9..b5a4de98 100644 --- a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs +++ b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs @@ -20,6 +20,7 @@ using System.Linq; using System.Text; using System.Text.Json.Serialization; using System.Threading.RateLimiting; +using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.Common.DependencyInjection; @@ -128,6 +129,15 @@ public static class PresentationApiLayerServices jwtBearerOptions.Events = new JwtBearerEvents { + OnMessageReceived = jwtBearerMessageReceivedContext => // The SignalR clients send the token as a query string parameter, because the browser cannot set the Authorization header of a WebSocket connection. + { + string? accessToken = jwtBearerMessageReceivedContext.Request.Query["access_token"]; + PathString requestPath = jwtBearerMessageReceivedContext.HttpContext.Request.Path; + if (!string.IsNullOrEmpty(accessToken) && + (requestPath.StartsWithSegments("/scanProgressHub") || requestPath.StartsWithSegments("/scheduledJobsHub"))) + jwtBearerMessageReceivedContext.Token = accessToken; + return Task.CompletedTask; + }, OnChallenge = jwtBearerChallengeContext => // Event triggered when authentication is not successful for whatever reason. { jwtBearerChallengeContext.HandleResponse(); // Prevent the default 401 response. @@ -223,6 +233,10 @@ public static class PresentationApiLayerServices }); services.AddSignalR() + .AddJsonProtocol(jsonHubProtocolOptions => + // The scheduler page consumes enum values as strings (job status and task type names), so the hub must + // serialize enums the same way the REST API does, which is also configured with JsonStringEnumConverter. + jsonHubProtocolOptions.PayloadSerializerOptions.Converters.Add(new JsonStringEnumConverter())) .AddMessagePackProtocol(messagePackHubProtocolOptions => messagePackHubProtocolOptions.SerializerOptions = MessagePackSerializerOptions.Standard.WithSecurity(MessagePackSecurity.UntrustedData)); diff --git a/src/Lumina.Presentation.Api/Program.cs b/src/Lumina.Presentation.Api/Program.cs index 00422fe1..811b1de9 100644 --- a/src/Lumina.Presentation.Api/Program.cs +++ b/src/Lumina.Presentation.Api/Program.cs @@ -8,6 +8,7 @@ using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Infrastructure.Common.DependencyInjection; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress; +using Lumina.Infrastructure.Core.Scheduling.Notifications; using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; using Lumina.Presentation.Api.Common.DependencyInjection; using Lumina.Presentation.Api.Common.Middlewares; @@ -133,7 +134,7 @@ public class Program // Add API documentation (OpenApi/Scalar). app.MapOpenApi(); - app.UseOpenApi(openApiDocumentMiddlewareSettings => openApiDocumentMiddlewareSettings.Path = "/openapi/{documentName}.json"); // this is needed for API versioning to work correctly with Scalar + app.UseOpenApi(openApiDocumentMiddlewareSettings => openApiDocumentMiddlewareSettings.Path = "/openapi/{documentName}.json"); // This is needed for API versioning to work correctly with Scalar. app.MapScalarApiReference(scalarOptions => { scalarOptions.WithTitle("Lumina API") @@ -145,7 +146,9 @@ public class Program // Add the middleware that fires domain events and ensures eventual transactional consistency, but NOT for long-polling/WebSockets stuff like SignalR, which would keep the db locked, // and NOT for the health probes, which would otherwise begin a database transaction on every probe. - app.UseWhen(ctx => !ctx.Request.Path.StartsWithSegments("/scanProgressHub") && !ctx.Request.Path.StartsWithSegments("/health"), app => app.UseMiddleware()); + app.UseWhen(ctx => !ctx.Request.Path.StartsWithSegments("/scanProgressHub") && + !ctx.Request.Path.StartsWithSegments("/scheduledJobsHub") && + !ctx.Request.Path.StartsWithSegments("/health"), app => app.UseMiddleware()); // Create a directory relative to the application's startup directory, and use it to store static files that are served at the /media route on the API. string mediaRootDirectoryPathSetting = app.Configuration.GetValue("MediaSettings:RootDirectory") ?? string.Empty; @@ -176,13 +179,14 @@ public class Program RequestPath = "/media", OnPrepareResponse = staticFileContext => { - // the served media must not run as active content, so that attacker-influenced files (e.g. SVG covers) cannot execute scripts on the API origin + // The served media must not run as active content, so that attacker-influenced files (e.g. SVG covers) cannot execute scripts on the API origin. staticFileContext.Context.Response.Headers["X-Content-Type-Options"] = "nosniff"; staticFileContext.Context.Response.Headers["Content-Security-Policy"] = "default-src 'none'; script-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:"; } }); app.MapHub("/scanProgressHub"); + app.MapHub("/scheduledJobsHub"); // The liveness probe reports whether the process is running, while the readiness probe also verifies that the database is reachable. app.MapHealthChecks("/health/live", new HealthCheckOptions