Adds the scheduled job executor and SignalR hub

This commit is contained in:
BinaryAlley committed 2026-09-03 12:49:21 -07:00
1 parent bb16cd0bb6
commit 58d7375d61
14 files changed
+834 -5

No files matched your search

@@ -0,0 +1,39 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using System.Threading;
#endregion
namespace Lumina.Infrastructure.Core.Scheduling.Execution;
/// <summary>
/// Interface for the registry that holds the live runtime state of the scheduled jobs.
/// </summary>
public interface IScheduledJobRuntimeRegistry
{
/// <summary>
/// Starts the execution cycle of the scheduled job identified by <paramref name="scheduledJobId"/>.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose cycle is started.</param>
/// <param name="cycleCancellationTokenSource">The cancellation token source used to stop the execution cycle.</param>
/// <returns><see langword="true"/> when the cycle was started, <see langword="false"/> when a cycle was already running.</returns>
bool TryStartCycle(ScheduledJobId scheduledJobId, CancellationTokenSource cycleCancellationTokenSource);
/// <summary>
/// Stops the execution cycle of the scheduled job identified by <paramref name="scheduledJobId"/>.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose cycle is stopped.</param>
void StopCycle(ScheduledJobId scheduledJobId);
/// <summary>
/// Attempts to reserve the execution slot of the scheduled job identified by <paramref name="scheduledJobId"/>.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose execution slot is reserved.</param>
/// <returns><see langword="true"/> when the slot was reserved, <see langword="false"/> when another execution is already running.</returns>
bool TryAcquireRunSlot(ScheduledJobId scheduledJobId);
/// <summary>
/// Releases the execution slot of the scheduled job identified by <paramref name="scheduledJobId"/>.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose execution slot is released.</param>
void ReleaseRunSlot(ScheduledJobId scheduledJobId);
}
@@ -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;
/// <summary>
/// Interface for the executor of the task of a scheduled job.
/// </summary>
public interface IScheduledTaskExecutor
{
/// <summary>
/// Executes the payload of the task of the scheduled job, asynchronously.
/// </summary>
/// <param name="scheduledJob">The scheduled job whose task is executed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Success>> ExecutePayloadAsync(ScheduledJob scheduledJob, CancellationToken cancellationToken);
}
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
#endregion
namespace Lumina.Infrastructure.Core.Scheduling.Execution;
/// <summary>
/// Interface for the factory that creates the executor of the task of a scheduled job, based on the type of its task.
/// </summary>
public interface IScheduledTaskExecutorFactory
{
/// <summary>
/// Creates the executor of the task of a scheduled job, based on the type of its task.
/// </summary>
/// <param name="taskType">The type of the task whose executor is created.</param>
/// <returns>The created task executor.</returns>
IScheduledTaskExecutor CreateExecutor(ScheduledTaskType taskType);
}
@@ -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;
/// <summary>
/// Registry that holds the live runtime state of the scheduled jobs.
/// </summary>
public sealed class ScheduledJobRuntimeRegistry : IScheduledJobRuntimeRegistry
{
/// <summary>
/// Class that holds the live runtime state of the execution cycle of a scheduled job.
/// </summary>
private sealed class ScheduledJobRuntimeState
{
public CancellationTokenSource? CycleCancellationTokenSource;
public readonly SemaphoreSlim RunSlot = new(1, 1);
}
private readonly ConcurrentDictionary<ScheduledJobId, ScheduledJobRuntimeState> _runtimeStates = [];
/// <summary>
/// Starts the execution cycle of the scheduled job identified by <paramref name="scheduledJobId"/>.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose cycle is started.</param>
/// <param name="cycleCancellationTokenSource">The cancellation token source used to stop the execution cycle.</param>
/// <returns><see langword="true"/> when the cycle was started, <see langword="false"/> when a cycle was already running.</returns>
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;
}
/// <summary>
/// Stops the execution cycle of the scheduled job identified by <paramref name="scheduledJobId"/>.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose cycle is stopped.</param>
public void StopCycle(ScheduledJobId scheduledJobId)
{
if (!_runtimeStates.TryGetValue(scheduledJobId, out ScheduledJobRuntimeState? state))
return;
CancellationTokenSource? cycleCancellationTokenSource = state.CycleCancellationTokenSource;
state.CycleCancellationTokenSource = null;
cycleCancellationTokenSource?.Cancel();
}
/// <summary>
/// Attempts to reserve the execution slot of the scheduled job identified by <paramref name="scheduledJobId"/>.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose execution slot is reserved.</param>
/// <returns><see langword="true"/> when the slot was reserved, <see langword="false"/> when another execution is already running.</returns>
public bool TryAcquireRunSlot(ScheduledJobId scheduledJobId)
{
ScheduledJobRuntimeState state = _runtimeStates.GetOrAdd(scheduledJobId, static _ => new ScheduledJobRuntimeState());
return state.RunSlot.Wait(0);
}
/// <summary>
/// Releases the execution slot of the scheduled job identified by <paramref name="scheduledJobId"/>.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose execution slot is released.</param>
public void ReleaseRunSlot(ScheduledJobId scheduledJobId)
{
if (_runtimeStates.TryGetValue(scheduledJobId, out ScheduledJobRuntimeState? state))
state.RunSlot.Release();
}
}
@@ -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;
/// <summary>
/// Background service that schedules and executes the tasks of the scheduled jobs.
/// </summary>
public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobScheduler
{
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly IScheduledJobRuntimeRegistry _runtimeRegistry;
private readonly ILogger<ScheduledJobSchedulerJob> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobSchedulerJob"/> class.
/// </summary>
/// <param name="runtimeRegistry">Injected registry that holds the live runtime state of the scheduled jobs.</param>
/// <param name="logger">Injected service for logging.</param>
/// <param name="serviceScopeFactory">Injected factory used for creating scopes in which services are requested.</param>
public ScheduledJobSchedulerJob(IScheduledJobRuntimeRegistry runtimeRegistry, ILogger<ScheduledJobSchedulerJob> logger, IServiceScopeFactory serviceScopeFactory)
{
_serviceScopeFactory = serviceScopeFactory;
_runtimeRegistry = runtimeRegistry;
_logger = logger;
}
/// <summary>
/// Starts the execution cycle of the scheduled job identified by <paramref name="scheduledJobId"/>.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose execution cycle is started.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public Task StartCycleAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken)
{
RunCycleWorkerAsync(scheduledJobId, runImmediately: true, cancellationToken).FireAndForgetSafeAsync();
return Task.CompletedTask;
}
/// <summary>
/// Stops the execution cycle of the scheduled job identified by <paramref name="scheduledJobId"/>.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose execution cycle is stopped.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public Task StopCycleAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken)
{
_runtimeRegistry.StopCycle(scheduledJobId);
return Task.CompletedTask;
}
/// <summary>
/// Fires the task of the scheduled job identified by <paramref name="scheduledJobId"/> once, without affecting its execution cycle.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose task is fired.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public Task RunOnceAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken)
{
RunOnceWorkerAsync(scheduledJobId, cancellationToken).FireAndForgetSafeAsync();
return Task.CompletedTask;
}
/// <summary>
/// Method called when the background service starts; resumes the execution cycles of the scheduled jobs whose cycle was active.
/// </summary>
/// <param name="stoppingToken">Cancellation token that can be used to stop the execution.</param>
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await ResumeActiveCyclesAsync(stoppingToken).ConfigureAwait(false);
try
{
await Task.Delay(Timeout.InfiniteTimeSpan, stoppingToken).ConfigureAwait(false);
}
catch (OperationCanceledException) { }
}
/// <summary>
/// Resumes the execution cycles of the scheduled jobs whose cycle was active when the application shut down.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private async Task ResumeActiveCyclesAsync(CancellationToken cancellationToken)
{
await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = scope.ServiceProvider.GetRequiredService<IUnitOfWork>();
Result<IEnumerable<ScheduledJobEntity>> 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();
}
/// <summary>
/// Runs the execution cycle worker of the scheduled job identified by <paramref name="scheduledJobId"/>.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose cycle is run.</param>
/// <param name="runImmediately">Whether the task of the scheduled job is run immediately when the cycle starts.</param>
/// <param name="stoppingToken">Cancellation token that can be used to stop the execution.</param>
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();
}
}
/// <summary>
/// Runs the task of the scheduled job identified by <paramref name="scheduledJobId"/> once.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose task is run.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
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);
}
}
/// <summary>
/// Runs the task of the scheduled job identified by <paramref name="scheduledJobId"/>, guarding it against overlapping executions.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose task is run.</param>
/// <param name="isCycleRun">Whether the execution was triggered by the execution cycle of the scheduled job, or it is a one time execution.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
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);
}
}
/// <summary>
/// Executes a single run of the task of the scheduled job identified by <paramref name="scheduledJobId"/>.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose task is run.</param>
/// <param name="isCycleRun">Whether the execution was triggered by the execution cycle of the scheduled job, or it is a one time execution.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
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<IUnitOfWork>();
IDomainEventPublisher domainEventPublisher = services.GetRequiredService<IDomainEventPublisher>();
// Load the scheduled job, and mark its task as started.
Result<ScheduledJobEntity?> getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken).ConfigureAwait(false);
if (getScheduledJobResult.IsFailure || getScheduledJobResult.Value is null)
return;
Result<ScheduledJob> scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity();
if (scheduledJobDomainResult.IsFailure)
return;
Result<Success> 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<IScheduledTaskExecutorFactory>();
IScheduledTaskExecutor taskExecutor = taskExecutorFactory.CreateExecutor(scheduledJobDomainResult.Value.TaskType);
Result<Success> 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<Success> completeExecutionResult = scheduledJobDomainResult.Value.MarkExecutionCompleted(isCycleRun);
if (completeExecutionResult.IsFailure)
return;
foreach (IDomainEvent domainEvent in scheduledJobDomainResult.Value.GetDomainEvents())
await domainEventPublisher.PublishAsync(domainEvent, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the schedule of the scheduled job identified by <paramref name="scheduledJobId"/>, or <see langword="null"/> when it cannot be loaded.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose schedule is retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The schedule of the scheduled job, or <see langword="null"/>.</returns>
private async Task<Schedule?> GetScheduleAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken)
{
await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = scope.ServiceProvider.GetRequiredService<IUnitOfWork>();
Result<ScheduledJobEntity?> getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken).ConfigureAwait(false);
if (getScheduledJobResult.IsFailure || getScheduledJobResult.Value is null)
return null;
Result<ScheduledJob> scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity();
return scheduledJobDomainResult.IsFailure ? null : scheduledJobDomainResult.Value.Schedule;
}
/// <summary>
/// Calculates the delay until the next execution of the scheduled job, based on its <paramref name="schedule"/>.
/// </summary>
/// <param name="schedule">The schedule used to calculate the delay.</param>
/// <returns>The calculated delay until the next execution of the scheduled job.</returns>
private async Task<TimeSpan> CalculateDelayAsync(Schedule schedule)
{
await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope();
IDateTimeProvider dateTimeProvider = scope.ServiceProvider.GetRequiredService<IDateTimeProvider>();
// 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);
}
}
@@ -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;
/// <summary>
/// Factory that creates the executor of the task of a scheduled job, based on the type of its task.
/// </summary>
public class ScheduledTaskExecutorFactory : IScheduledTaskExecutorFactory
{
private readonly IServiceProvider _serviceProvider;
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledTaskExecutorFactory"/> class.
/// </summary>
/// <param name="serviceProvider">The service provider.</param>
public ScheduledTaskExecutorFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
/// <summary>
/// Creates the executor of the task of a scheduled job, based on the type of its task.
/// </summary>
/// <param name="taskType">The type of the task whose executor is created.</param>
/// <returns>The created task executor.</returns>
public IScheduledTaskExecutor CreateExecutor(ScheduledTaskType taskType)
{
return taskType switch
{
ScheduledTaskType.ScanMediaLibraries => _serviceProvider.GetRequiredService<MediaLibraryScanTaskExecutor>(),
ScheduledTaskType.CleanTemporaryFiles => _serviceProvider.GetRequiredService<TemporaryFilesCleanupTaskExecutor>(),
_ => throw new ArgumentException($"Unsupported task type: {taskType}", nameof(taskType))
};
}
}
@@ -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;
/// <summary>
/// Task executor that scans all the enabled media libraries, on behalf of the owner of the scheduled job.
/// </summary>
public class MediaLibraryScanTaskExecutor : IScheduledTaskExecutor
{
private readonly IUnitOfWork _unitOfWork;
private readonly IDomainEventPublisher _domainEventPublisher;
private readonly ILogger<MediaLibraryScanTaskExecutor> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="MediaLibraryScanTaskExecutor"/> class.
/// </summary>
/// <param name="domainEventPublisher">The domain event publisher used to publish events.</param>
/// <param name="logger">Injected service for logging.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public MediaLibraryScanTaskExecutor(IDomainEventPublisher domainEventPublisher, ILogger<MediaLibraryScanTaskExecutor> logger, IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_domainEventPublisher = domainEventPublisher;
_logger = logger;
}
/// <summary>
/// Scans all the enabled media libraries, on behalf of the owner of the scheduled job.
/// </summary>
/// <param name="scheduledJob">The scheduled job whose task is executed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Success>> ExecutePayloadAsync(ScheduledJob scheduledJob, CancellationToken cancellationToken)
{
Guid ownerUserId = scheduledJob.OwnerUserId.Value;
// Get all the enabled and unlocked media libraries.
Result<IEnumerable<LibraryEntity>> getLibrariesResult = await _unitOfWork.LibraryRepository.GetAllEnabledAndUnlockedAsync(cancellationToken).ConfigureAwait(false);
if (getLibrariesResult.IsFailure)
return getLibrariesResult.Errors;
IEnumerable<Result<Library>> domainLibrariesResult = getLibrariesResult.Value.ToDomainEntities();
List<IDomainEvent> domainEvents = [];
// Start a scan for each media library that is not already being scanned.
foreach (Result<Library> domainLibraryResult in domainLibrariesResult)
{
if (domainLibraryResult.IsFailure)
return domainLibraryResult.Errors;
// Get the past month's scans for this library.
Result<IEnumerable<LibraryScanEntity>> 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<Result<LibraryScan>> pastLibraryScansDomainResult = pastLibraryScansResult.Value.ToDomainEntities();
foreach (Result<LibraryScan> pastLibraryScanDomainResult in pastLibraryScansDomainResult)
if (pastLibraryScanDomainResult.IsFailure)
return pastLibraryScanDomainResult.Errors;
// Create and queue the media library scan.
Result<LibraryScan> 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<Created> 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;
}
}
@@ -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;
/// <summary>
/// Task executor that empties the temporary directory into which the reading plugins extract the contents of the books.
/// </summary>
public class TemporaryFilesCleanupTaskExecutor : IScheduledTaskExecutor
{
private readonly ILogger<TemporaryFilesCleanupTaskExecutor> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="TemporaryFilesCleanupTaskExecutor"/> class.
/// </summary>
/// <param name="logger">Injected service for logging.</param>
public TemporaryFilesCleanupTaskExecutor(ILogger<TemporaryFilesCleanupTaskExecutor> logger)
{
_logger = logger;
}
/// <summary>
/// Empties the temporary directory into which the reading plugins extract the contents of the books.
/// </summary>
/// <param name="scheduledJob">The scheduled job whose task is executed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Success>> 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)));
}
}
}
@@ -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;
/// <summary>
/// Interface for the SignalR client of the scheduled jobs hub.
/// </summary>
public interface IScheduledJobsClient
{
/// <summary>
/// Receives the current list of scheduled jobs.
/// </summary>
/// <param name="scheduledJobs">The current list of scheduled jobs.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
Task ReceiveScheduledJobsAsync(IReadOnlyList<ScheduledJobResponse> scheduledJobs);
/// <summary>
/// Receives an execution of the task of a scheduled job that started.
/// </summary>
/// <param name="execution">The execution that started.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
Task ScheduledJobExecutionStartedAsync(ScheduledJobExecutionResponse execution);
/// <summary>
/// Receives an execution of the task of a scheduled job that completed.
/// </summary>
/// <param name="execution">The execution that completed.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
Task ScheduledJobExecutionCompletedAsync(ScheduledJobExecutionResponse execution);
}
@@ -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;
/// <summary>
/// Class used to notify SignalR clients about the scheduled jobs and their executions.
/// </summary>
public sealed class ScheduledJobNotifier : IScheduledJobNotifier
{
private readonly IHubContext<ScheduledJobsHub, IScheduledJobsClient> _hubContext;
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobNotifier"/> class.
/// </summary>
/// <param name="hubContext">SignalR hub context abstraction.</param>
public ScheduledJobNotifier(IHubContext<ScheduledJobsHub, IScheduledJobsClient> hubContext)
{
_hubContext = hubContext;
}
/// <summary>
/// Notifies the SignalR clients about the current list of scheduled jobs.
/// </summary>
/// <param name="scheduledJobs">The current list of scheduled jobs.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async Task SendScheduledJobsAsync(IReadOnlyList<ScheduledJobResponse> scheduledJobs, CancellationToken cancellationToken)
{
await _hubContext.Clients.All.ReceiveScheduledJobsAsync(scheduledJobs).ConfigureAwait(false);
}
/// <summary>
/// Notifies the SignalR clients about an execution of the task of a scheduled job that started.
/// </summary>
/// <param name="execution">The execution of the task of the scheduled job that started.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async Task SendScheduledJobExecutionStartedAsync(ScheduledJobExecutionResponse execution, CancellationToken cancellationToken)
{
await _hubContext.Clients.All.ScheduledJobExecutionStartedAsync(execution).ConfigureAwait(false);
}
/// <summary>
/// Notifies the SignalR clients about an execution of the task of a scheduled job that completed.
/// </summary>
/// <param name="execution">The execution of the task of the scheduled job that completed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async Task SendScheduledJobExecutionCompletedAsync(ScheduledJobExecutionResponse execution, CancellationToken cancellationToken)
{
await _hubContext.Clients.All.ScheduledJobExecutionCompletedAsync(execution).ConfigureAwait(false);
}
}
@@ -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;
/// <summary>
/// SignalR hub for broadcasting the state of the scheduled jobs to the connected administrator clients.
/// </summary>
[Authorize]
public class ScheduledJobsHub : Hub<IScheduledJobsClient>
{
private readonly IServiceScopeFactory _serviceScopeFactory;
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobsHub"/> class.
/// </summary>
/// <param name="serviceScopeFactory">Injected factory used for creating scopes in which services are requested.</param>
public ScheduledJobsHub(IServiceScopeFactory serviceScopeFactory)
{
_serviceScopeFactory = serviceScopeFactory;
}
/// <summary>
/// Verifies that the connecting client belongs to an administrator account, and rejects the connection otherwise.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
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);
}
/// <summary>
/// Determines whether the user identified by <paramref name="userId"/> is an administrator.
/// </summary>
/// <param name="userId">The unique identifier of the user to check.</param>
/// <returns><see langword="true"/> when the user is an administrator, <see langword="false"/> otherwise.</returns>
private async Task<bool> IsAdministratorAsync(Guid userId)
{
await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope();
ApplicationAuthorizationService authorizationService = scope.ServiceProvider.GetRequiredService<ApplicationAuthorizationService>();
return await authorizationService.IsInRoleAsync(userId, "Admin", CancellationToken.None).ConfigureAwait(false);
}
}