Adds a technical data cleanup scheduled job that fails interrupted media library scans at startup

This commit is contained in:
BinaryAlley committed 2026-09-29 12:00:00 +03:00
1 parent d33986096e
commit 80af18170a
26 files changed
+395 -10

No files matched your search

@@ -1,6 +1,8 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Infrastructure.Scheduling;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Application.Common.Infrastructure.Time;
@@ -103,6 +105,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await SynchronizeBundledThemesIfNeededAsync(stoppingToken).ConfigureAwait(false);
await EnsureTechnicalDataCleanupScheduledJobAsync(stoppingToken).ConfigureAwait(false);
await ResumeActiveCyclesAsync(stoppingToken).ConfigureAwait(false);
try
{
@@ -148,6 +151,74 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
}
}
/// <summary>
/// Ensures that the default "Technical data cleanup at startup" scheduled job exists, so that installations created before
/// the job was added to the default jobs also clean up the invalid technical data at every application startup.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <remarks>
/// The job is only created on installations that already have scheduled jobs. On a fresh installation, before the application
/// setup has run, no scheduled jobs exist yet, and the setup flow seeds this job together with the other default jobs.
/// </remarks>
private async Task EnsureTechnicalDataCleanupScheduledJobAsync(CancellationToken cancellationToken)
{
try
{
await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = scope.ServiceProvider.GetRequiredService<IUnitOfWork>();
Result<PaginatedResultDto<ScheduledJobEntity>> getScheduledJobsResult = await unitOfWork.ScheduledJobRepository
.GetAllAsync<BaseFilterDto>(cancellationToken: cancellationToken).ConfigureAwait(false);
if (getScheduledJobsResult.IsFailure)
{
_logger.LogWarning("Failed to read the scheduled jobs to ensure the technical data cleanup job: {Error}", getScheduledJobsResult.FirstError.Description);
return;
}
IReadOnlyList<ScheduledJobEntity> scheduledJobs = getScheduledJobsResult.Value.Data;
// A fresh installation has no scheduled jobs yet, and the setup flow seeds the default jobs, including this one; when the
// job already exists, regardless of its status, it is not created again, so a job that was stopped or removed by the user stays that way.
if (scheduledJobs.Count == 0 || scheduledJobs.Any(scheduledJob => scheduledJob.TaskType == ScheduledTaskType.TechnicalDataCleanup))
return;
// The job is owned by the same user as the other scheduled jobs, which is the administrator account.
Guid ownerUserId = scheduledJobs[0].OwnerUserId;
ScheduledJobEntity technicalDataCleanupJob = new()
{
Id = Guid.NewGuid(),
Name = "Technical data cleanup at startup",
TaskType = ScheduledTaskType.TechnicalDataCleanup,
ScheduleType = ScheduleType.OnceAtStartup,
Status = ScheduledJobStatus.Active,
OwnerUserId = ownerUserId,
LastStartedOnUtc = null,
LastCompletedOnUtc = null,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = ownerUserId,
UpdatedOnUtc = null,
UpdatedBy = null
};
Result<Created> insertScheduledJobResult = await unitOfWork.ScheduledJobRepository.InsertAsync(technicalDataCleanupJob, cancellationToken).ConfigureAwait(false);
if (insertScheduledJobResult.IsFailure)
{
_logger.LogWarning("Failed to insert the technical data cleanup scheduled job: {Error}", insertScheduledJobResult.FirstError.Description);
return;
}
Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
{
_logger.LogWarning("Failed to save the technical data cleanup scheduled job: {Error}", saveChangesResult.FirstError.Description);
return;
}
_logger.LogInformation("Created the default 'Technical data cleanup at startup' scheduled job.");
}
catch (OperationCanceledException) { }
catch (Exception exception)
{
// Ensuring the technical data cleanup job at startup is best effort, so a failure here must never stop the scheduler.
_logger.LogWarning(exception, "Failed to ensure the technical data cleanup scheduled job.");
}
}
/// <summary>
/// Resumes the execution cycles of the scheduled jobs whose cycle was active when the application shut down.
/// </summary>
@@ -36,6 +36,7 @@ public class ScheduledTaskExecutorFactory : IScheduledTaskExecutorFactory
ScheduledTaskType.CleanTemporaryFiles => _serviceProvider.GetRequiredService<TemporaryFilesCleanupTaskExecutor>(),
ScheduledTaskType.RepairThemes => _serviceProvider.GetRequiredService<RepairThemesTaskExecutor>(),
ScheduledTaskType.CleanScheduledJobExecutionHistory => _serviceProvider.GetRequiredService<CleanScheduledJobExecutionHistoryTaskExecutor>(),
ScheduledTaskType.TechnicalDataCleanup => _serviceProvider.GetRequiredService<TechnicalDataCleanupTaskExecutor>(),
_ => throw new ArgumentException($"Unsupported task type: {taskType}", nameof(taskType))
};
}
@@ -0,0 +1,46 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Microsoft.Extensions.Logging;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors;
/// <summary>
/// Task executor that cleans the technical data that is no longer valid.
/// </summary>
public class TechnicalDataCleanupTaskExecutor : IScheduledTaskExecutor
{
private readonly IUnitOfWork _unitOfWork;
private readonly ILogger<TechnicalDataCleanupTaskExecutor> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="TechnicalDataCleanupTaskExecutor"/> class.
/// </summary>
/// <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 TechnicalDataCleanupTaskExecutor(ILogger<TechnicalDataCleanupTaskExecutor> logger, IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_logger = logger;
}
/// <summary>
/// Executes the cleanup of the technical data that is no longer valid.
/// </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)
{
Result<Updated> failInterruptedScansResult = await _unitOfWork.LibraryScanRepository.FailInterruptedScansAsync(cancellationToken).ConfigureAwait(false);
if (failInterruptedScansResult.IsFailure)
return failInterruptedScansResult.Errors;
_logger.LogInformation("Cleaned the technical data on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name);
return Result.Success;
}
}