From 80af18170afd22b6cc880ab858787087bedeab40 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Tue, 29 Sep 2026 12:00:00 +0300 Subject: [PATCH] Adds a technical data cleanup scheduled job that fails interrupted media library scans at startup --- .../MediaLibrary/ILibraryScanRepository.cs | 8 +++ .../Libraries/LibraryScanRepository.cs | 16 +++++ .../Core/Seed/DataSeedService.cs | 4 +- .../Enums/Scheduling/ScheduledTaskType.cs | 7 +- .../InfrastructureLayerServices.cs | 13 ++++ .../Execution/ScheduledJobSchedulerJob.cs | 71 +++++++++++++++++++ .../Execution/ScheduledTaskExecutorFactory.cs | 1 + .../TechnicalDataCleanupTaskExecutor.cs | 46 ++++++++++++ .../Enums/Scheduling/ScheduledTaskType.cs | 7 +- .../Views/Admin/Scheduler.ar-SA.resx | 3 + .../Views/Admin/Scheduler.de-DE.resx | 3 + .../Views/Admin/Scheduler.en-US.resx | 3 + .../Views/Admin/Scheduler.es-ES.resx | 3 + .../Views/Admin/Scheduler.fr-FR.resx | 3 + .../Views/Admin/Scheduler.it-IT.resx | 3 + .../Views/Admin/Scheduler.ja-JP.resx | 3 + .../Core/Resources/Views/Admin/Scheduler.resx | 3 + .../Views/Admin/Scheduler.ro-RO.resx | 3 + .../Views/Admin/Scheduler.uk-UA.resx | 3 + .../Views/Admin/Scheduler.zh-CN.resx | 3 + .../Core/Views/Admin/Scheduler.cshtml | 11 +-- .../Libraries/LibraryScanRepositoryTests.cs | 38 ++++++++++ .../Core/Seed/DataSeedServiceTests.cs | 7 +- .../ScheduledJobSchedulerJobTests.cs | 57 +++++++++++++++ .../ScheduledTaskExecutorFactoryTests.cs | 15 ++++ .../TechnicalDataCleanupTaskExecutorTests.cs | 71 +++++++++++++++++++ 26 files changed, 395 insertions(+), 10 deletions(-) create mode 100644 src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/TechnicalDataCleanupTaskExecutor.cs create mode 100644 tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/TechnicalDataCleanupTaskExecutorTests.cs diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanRepository.cs index 4cc72122..179da525 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanRepository.cs @@ -33,4 +33,12 @@ public interface ILibraryScanRepository : IRepository, /// Cancellation token that can be used to stop the execution. /// An containing either a collection of , or an error. Task>> GetRunningScansAsync(CancellationToken cancellationToken); + + /// + /// Marks the media library scans that were interrupted by an application restart, meaning the ones that are still + /// or , as failed. + /// + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> FailInterruptedScansAsync(CancellationToken cancellationToken); } diff --git a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanRepository.cs index 4c8a1c2a..d7719b69 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanRepository.cs @@ -114,4 +114,20 @@ internal sealed class LibraryScanRepository : ILibraryScanRepository EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundLibraryScan, data); return Result.Updated; } + + /// + /// Marks the media library scans that were interrupted by an application restart, meaning the ones that are still + /// or , as failed. + /// + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> FailInterruptedScansAsync(CancellationToken cancellationToken) + { + // The scans that were pending or running when the application stopped cannot survive the restart, because their jobs, + // progress and cancellation tokens live only in memory, so they are marked as failed and can be triggered again. + await _luminaDbContext.LibraryScans + .Where(libraryScan => libraryScan.Status == LibraryScanJobStatus.Pending || libraryScan.Status == LibraryScanJobStatus.Running) + .ExecuteUpdateAsync(setters => setters.SetProperty(libraryScan => libraryScan.Status, LibraryScanJobStatus.Failed), cancellationToken).ConfigureAwait(false); + return Result.Updated; + } } diff --git a/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs b/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs index c49fa627..5e0f4b86 100644 --- a/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs +++ b/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs @@ -198,7 +198,9 @@ public class DataSeedService : IDataSeedService // Repair the installed themes whose files are missing, at every application startup. CreateDefaultScheduledJob("Repair themes at startup", ScheduledTaskType.RepairThemes, ScheduleType.OnceAtStartup, intervalMinutes: null, hour: null, minute: null, adminUserId), // Clean the execution history of the scheduled jobs, keeping only the executions of the past month, at every application startup. - CreateDefaultScheduledJob("Clean scheduled job execution history at startup", ScheduledTaskType.CleanScheduledJobExecutionHistory, ScheduleType.OnceAtStartup, intervalMinutes: null, hour: null, minute: null, adminUserId) + CreateDefaultScheduledJob("Clean scheduled job execution history at startup", ScheduledTaskType.CleanScheduledJobExecutionHistory, ScheduleType.OnceAtStartup, intervalMinutes: null, hour: null, minute: null, adminUserId), + // Clean the technical data that is no longer valid, at every application startup. + CreateDefaultScheduledJob("Technical data cleanup at startup", ScheduledTaskType.TechnicalDataCleanup, ScheduleType.OnceAtStartup, intervalMinutes: null, hour: null, minute: null, adminUserId) ]; foreach (ScheduledJobEntity defaultScheduledJob in defaultScheduledJobs) { diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Scheduling/ScheduledTaskType.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Scheduling/ScheduledTaskType.cs index cc91f3cc..9b99d50c 100644 --- a/src/Lumina.Domain.SharedKernel/Common/Enums/Scheduling/ScheduledTaskType.cs +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Scheduling/ScheduledTaskType.cs @@ -23,5 +23,10 @@ public enum ScheduledTaskType /// /// The scheduled job cleans the execution history of the scheduled jobs, keeping only the recent executions. /// - CleanScheduledJobExecutionHistory + CleanScheduledJobExecutionHistory, + + /// + /// The scheduled job cleans the technical data that is no longer valid. + /// + TechnicalDataCleanup } diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index 7e857371..ba3d74ee 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -17,6 +17,7 @@ using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Art using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; using Lumina.Application.Core.Scheduling.Notifications; using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue; @@ -29,6 +30,7 @@ using Lumina.Infrastructure.Core.Authorization.Policies.Common.Factory; using Lumina.Infrastructure.Core.Authorization.Policies.LibraryOwnership; using Lumina.Infrastructure.Core.Authorization.Policies.Over18; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Cancellation; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress; @@ -104,6 +106,8 @@ public static class InfrastructureLayerServices services.AddHostedService(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -111,6 +115,14 @@ public static class InfrastructureLayerServices services.AddTransient(); services.AddTransient(); + // The media library type specific behavior of the generic scan jobs is provided by the materializers and the enrichers, selected by the media library type. + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddSingleton(); @@ -153,6 +165,7 @@ public static class InfrastructureLayerServices services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); return services; } diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs index 968685da..1b6cb328 100644 --- a/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs @@ -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 } } + /// + /// 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. + /// + /// Cancellation token that can be used to stop the execution. + /// + /// 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. + /// + private async Task EnsureTechnicalDataCleanupScheduledJobAsync(CancellationToken cancellationToken) + { + try + { + await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = scope.ServiceProvider.GetRequiredService(); + Result> getScheduledJobsResult = await unitOfWork.ScheduledJobRepository + .GetAllAsync(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 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 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 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."); + } + } + /// /// Resumes the execution cycles of the scheduled jobs whose cycle was active when the application shut down. /// diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledTaskExecutorFactory.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledTaskExecutorFactory.cs index ce493bfb..d7933a5a 100644 --- a/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledTaskExecutorFactory.cs +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledTaskExecutorFactory.cs @@ -36,6 +36,7 @@ public class ScheduledTaskExecutorFactory : IScheduledTaskExecutorFactory ScheduledTaskType.CleanTemporaryFiles => _serviceProvider.GetRequiredService(), ScheduledTaskType.RepairThemes => _serviceProvider.GetRequiredService(), ScheduledTaskType.CleanScheduledJobExecutionHistory => _serviceProvider.GetRequiredService(), + ScheduledTaskType.TechnicalDataCleanup => _serviceProvider.GetRequiredService(), _ => throw new ArgumentException($"Unsupported task type: {taskType}", nameof(taskType)) }; } diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/TechnicalDataCleanupTaskExecutor.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/TechnicalDataCleanupTaskExecutor.cs new file mode 100644 index 00000000..8a56b8c6 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/TechnicalDataCleanupTaskExecutor.cs @@ -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; + +/// +/// Task executor that cleans the technical data that is no longer valid. +/// +public class TechnicalDataCleanupTaskExecutor : IScheduledTaskExecutor +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for logging. + /// Injected unit of work for interacting with the data access layer repositories. + public TechnicalDataCleanupTaskExecutor(ILogger logger, IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + _logger = logger; + } + + /// + /// Executes the cleanup of the technical data that is no longer valid. + /// + /// 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) + { + Result 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; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Enums/Scheduling/ScheduledTaskType.cs b/src/Lumina.Presentation.Web/Common/Enums/Scheduling/ScheduledTaskType.cs index 5f033276..d7dd6298 100644 --- a/src/Lumina.Presentation.Web/Common/Enums/Scheduling/ScheduledTaskType.cs +++ b/src/Lumina.Presentation.Web/Common/Enums/Scheduling/ScheduledTaskType.cs @@ -23,5 +23,10 @@ public enum ScheduledTaskType /// /// The scheduled job cleans the execution history of the scheduled jobs, keeping only the recent executions. /// - CleanScheduledJobExecutionHistory + CleanScheduledJobExecutionHistory, + + /// + /// The scheduled job cleans the technical data that is no longer valid. + /// + TechnicalDataCleanup } diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ar-SA.resx index 8cd2978e..25470ea5 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ar-SA.resx @@ -165,6 +165,9 @@ تنظيف سجل الوظائف + + تنظيف البيانات التقنية + عند بدء التشغيل diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.de-DE.resx index 6caf3884..0b2904e1 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.de-DE.resx @@ -165,6 +165,9 @@ Jobverlauf bereinigen + + Technische Datenbereinigung + Beim Start diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.en-US.resx index 24fa61bb..7bd2a9ee 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.en-US.resx @@ -165,6 +165,9 @@ Clean job history + + Technical data cleanup + At startup diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.es-ES.resx index 0a45962c..04a5cc5a 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.es-ES.resx @@ -165,6 +165,9 @@ Limpiar historial de trabajos + + Limpieza de datos técnicos + Al inicio diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.fr-FR.resx index bc2a145d..507517ef 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.fr-FR.resx @@ -165,6 +165,9 @@ Nettoyer l'historique des tâches + + Nettoyage des données techniques + Au démarrage diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.it-IT.resx index bc5520f8..dcbbffcb 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.it-IT.resx @@ -165,6 +165,9 @@ Pulisci la cronologia dei processi + + Pulizia dei dati tecnici + All'avvio diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ja-JP.resx index efe836d0..5c1c50c4 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ja-JP.resx @@ -165,6 +165,9 @@ ジョブ履歴を削除 + + 技術データのクリーンアップ + 起動時 diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.resx index 24fa61bb..7bd2a9ee 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.resx @@ -165,6 +165,9 @@ Clean job history + + Technical data cleanup + At startup diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ro-RO.resx index abd5a9b4..3e2226ee 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.ro-RO.resx @@ -165,6 +165,9 @@ Curăță istoricul proceselor + + Curățare date tehnice + La pornire diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.uk-UA.resx index 1feacdb6..9f59af4b 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.uk-UA.resx @@ -165,6 +165,9 @@ Очистити історію завдань + + Очищення технічних даних + Під час запуску diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.zh-CN.resx index 8aed079b..ff07b5c6 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.zh-CN.resx @@ -165,6 +165,9 @@ 清理作业历史 + + 技术数据清理 + 启动时 diff --git a/src/Lumina.Presentation.Web/Core/Views/Admin/Scheduler.cshtml b/src/Lumina.Presentation.Web/Core/Views/Admin/Scheduler.cshtml index f857b8a3..659b7633 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Admin/Scheduler.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Admin/Scheduler.cshtml @@ -46,7 +46,8 @@ It keeps the DOM contract the client script binds to, without any images or colo
@_localizer["TaskType.ScanMediaLibraries"]
@_localizer["TaskType.CleanTemporaryFiles"]
@_localizer["TaskType.RepairThemes"]
-
@_localizer["TaskType.CleanScheduledJobExecutionHistory"]
+
@_localizer["TaskType.CleanScheduledJobExecutionHistory"]
+
@_localizer["TaskType.TechnicalDataCleanup"]
@@ -180,7 +181,8 @@ It keeps the DOM contract the client script binds to, without any images or colo ScanMediaLibraries: '@_localizer["TaskType.ScanMediaLibraries"]', CleanTemporaryFiles: '@_localizer["TaskType.CleanTemporaryFiles"]', RepairThemes: '@_localizer["TaskType.RepairThemes"]', - CleanScheduledJobExecutionHistory: '@_localizer["TaskType.CleanScheduledJobExecutionHistory"]' + CleanScheduledJobExecutionHistory: '@_localizer["TaskType.CleanScheduledJobExecutionHistory"]', + TechnicalDataCleanup: '@_localizer["TaskType.TechnicalDataCleanup"]' }, statusNames: { Added: '@_localizer["Status.Added"]', @@ -195,7 +197,8 @@ It keeps the DOM contract the client script binds to, without any images or colo ScanMediaLibraries: '#5aa7c7', CleanTemporaryFiles: '#c7a15a', RepairThemes: '#8bc34a', - CleanScheduledJobExecutionHistory: '#ba68c8' + CleanScheduledJobExecutionHistory: '#ba68c8', + TechnicalDataCleanup: '#90a4ae' }; // The element references are captured once, so that the cleanup can unbind their listeners even after the AJAX navigator has swapped the content out of the document. @@ -295,7 +298,7 @@ It keeps the DOM contract the client script binds to, without any images or colo } // Graph state. - const taskTypeOrder = ['ScanMediaLibraries', 'CleanTemporaryFiles', 'RepairThemes', 'CleanScheduledJobExecutionHistory']; + const taskTypeOrder = ['ScanMediaLibraries', 'CleanTemporaryFiles', 'RepairThemes', 'CleanScheduledJobExecutionHistory', 'TechnicalDataCleanup']; const graphState = { dataPoints: [], pixelsPerSecond: 0, diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryScanRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryScanRepositoryTests.cs index 8769e260..949f166d 100644 --- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryScanRepositoryTests.cs +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryScanRepositoryTests.cs @@ -73,4 +73,42 @@ public class LibraryScanRepositoryTests Assert.Null(reloadedScan.UpdatedOnUtc); Assert.Null(reloadedScan.UpdatedBy); } + + [Fact] + public async Task FailInterruptedScansAsync_WhenScansArePendingOrRunning_ShouldMarkThemAsFailedAndLeaveTheOthersUnchanged() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-libraryscanrepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + LibraryScanRepository sut = new(context); + + UserEntity storedUser = _userEntityFixture.Create(username: "scan-user", password: "Password123"); + context.Users.Add(storedUser); + LibraryEntity storedLibrary = _libraryEntityFixture.Create(userId: storedUser.Id); + context.Libraries.Add(storedLibrary); + await context.SaveChangesAsync(); + + LibraryScanEntity pendingScan = _libraryScanEntityFixture.Create(libraryId: storedLibrary.Id, userId: storedUser.Id, status: LibraryScanJobStatus.Pending, libraryEntity: storedLibrary); + LibraryScanEntity runningScan = _libraryScanEntityFixture.Create(libraryId: storedLibrary.Id, userId: storedUser.Id, status: LibraryScanJobStatus.Running, libraryEntity: storedLibrary); + LibraryScanEntity completedScan = _libraryScanEntityFixture.Create(libraryId: storedLibrary.Id, userId: storedUser.Id, status: LibraryScanJobStatus.Completed, libraryEntity: storedLibrary); + LibraryScanEntity canceledScan = _libraryScanEntityFixture.Create(libraryId: storedLibrary.Id, userId: storedUser.Id, status: LibraryScanJobStatus.Canceled, libraryEntity: storedLibrary); + LibraryScanEntity failedScan = _libraryScanEntityFixture.Create(libraryId: storedLibrary.Id, userId: storedUser.Id, status: LibraryScanJobStatus.Failed, libraryEntity: storedLibrary); + context.LibraryScans.AddRange(pendingScan, runningScan, completedScan, canceledScan, failedScan); + await context.SaveChangesAsync(); + + // Act + Result result = await sut.FailInterruptedScansAsync(CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + context.ChangeTracker.Clear(); + Assert.Equal(LibraryScanJobStatus.Failed, (await context.LibraryScans.AsNoTracking().FirstAsync(scan => scan.Id == pendingScan.Id)).Status); + Assert.Equal(LibraryScanJobStatus.Failed, (await context.LibraryScans.AsNoTracking().FirstAsync(scan => scan.Id == runningScan.Id)).Status); + Assert.Equal(LibraryScanJobStatus.Completed, (await context.LibraryScans.AsNoTracking().FirstAsync(scan => scan.Id == completedScan.Id)).Status); + Assert.Equal(LibraryScanJobStatus.Canceled, (await context.LibraryScans.AsNoTracking().FirstAsync(scan => scan.Id == canceledScan.Id)).Status); + Assert.Equal(LibraryScanJobStatus.Failed, (await context.LibraryScans.AsNoTracking().FirstAsync(scan => scan.Id == failedScan.Id)).Status); + } } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs index 67b3fa86..93e95a95 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs @@ -569,7 +569,7 @@ public class DataSeedServiceTests } [Fact] - public async Task SetDefaultScheduledJobsAsync_WhenCalled_ShouldInsertTheFiveDefaultJobsAndReturnCreated() + public async Task SetDefaultScheduledJobsAsync_WhenCalled_ShouldInsertTheSixDefaultJobsAndReturnCreated() { // Arrange Guid adminUserId = Guid.NewGuid(); @@ -586,7 +586,7 @@ public class DataSeedServiceTests // Assert Assert.False(result.IsFailure); Assert.Equal(Result.Created, result.Value); - Assert.Equal(5, capturedScheduledJobs.Count); + Assert.Equal(6, capturedScheduledJobs.Count); Assert.All(capturedScheduledJobs, scheduledJob => Assert.Equal(ScheduledJobStatus.Active, scheduledJob.Status)); Assert.All(capturedScheduledJobs, scheduledJob => Assert.Equal(adminUserId, scheduledJob.OwnerUserId)); Assert.All(capturedScheduledJobs, scheduledJob => Assert.Equal(adminUserId, scheduledJob.CreatedBy)); @@ -596,8 +596,9 @@ public class DataSeedServiceTests Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.CleanTemporaryFiles && scheduledJob.ScheduleType == ScheduleType.WithIntervalInMinutes && scheduledJob.IntervalMinutes == 720); Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.RepairThemes && scheduledJob.ScheduleType == ScheduleType.OnceAtStartup); Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.CleanScheduledJobExecutionHistory && scheduledJob.ScheduleType == ScheduleType.OnceAtStartup); + Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.TechnicalDataCleanup && scheduledJob.ScheduleType == ScheduleType.OnceAtStartup); - await mockScheduledJobRepository.Received(5).InsertAsync(Arg.Any(), Arg.Any()); + await mockScheduledJobRepository.Received(6).InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); await mockScheduledJobRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobSchedulerJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobSchedulerJobTests.cs index 5855411a..82bb86fc 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobSchedulerJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobSchedulerJobTests.cs @@ -390,6 +390,8 @@ public class ScheduledJobSchedulerJobTests { // Arrange _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()).Returns(Array.Empty()); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); IThemeService mockThemeService = Substitute.For(); mockThemeService.GetBundledThemeArchivePaths().Returns([]); IThemeRepository mockThemeRepository = Substitute.For(); @@ -407,6 +409,61 @@ public class ScheduledJobSchedulerJobTests await _mockScheduledJobRepository.Received(2).GetActiveOrRunningAsync(Arg.Any()); } + [Fact] + public async Task EnsureTechnicalDataCleanupScheduledJobAsync_WhenTheJobAlreadyExists_ShouldNotInsertIt() + { + // Arrange + ScheduledJobEntity existingJob = _scheduledJobEntityFixture.Create(taskType: ScheduledTaskType.TechnicalDataCleanup, status: ScheduledJobStatus.Active, scheduleType: ScheduleType.OnceAtStartup); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [existingJob], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); + + // Act + await InvokeAsync("EnsureTechnicalDataCleanupScheduledJobAsync", CancellationToken.None); + + // Assert + await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnsureTechnicalDataCleanupScheduledJobAsync_WhenThereAreNoScheduledJobs_ShouldNotInsertIt() + { + // Arrange + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); + + // Act + await InvokeAsync("EnsureTechnicalDataCleanupScheduledJobAsync", CancellationToken.None); + + // Assert + // A fresh installation seeds the default jobs, including the technical data cleanup one, during the application setup. + await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnsureTechnicalDataCleanupScheduledJobAsync_WhenTheJobIsMissing_ShouldInsertItOwnedByTheOtherJobsOwner() + { + // Arrange + Guid ownerUserId = Guid.NewGuid(); + ScheduledJobEntity existingJob = _scheduledJobEntityFixture.Create(taskType: ScheduledTaskType.RepairThemes, status: ScheduledJobStatus.Active, scheduleType: ScheduleType.OnceAtStartup, ownerUserId: ownerUserId); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [existingJob], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); + _mockScheduledJobRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(Result.Created); + + // Act + await InvokeAsync("EnsureTechnicalDataCleanupScheduledJobAsync", CancellationToken.None); + + // Assert + await _mockScheduledJobRepository.Received(1).InsertAsync( + Arg.Is(scheduledJob => + scheduledJob.TaskType == ScheduledTaskType.TechnicalDataCleanup && + scheduledJob.ScheduleType == ScheduleType.OnceAtStartup && + scheduledJob.Status == ScheduledJobStatus.Active && + scheduledJob.OwnerUserId == ownerUserId && + scheduledJob.CreatedBy == ownerUserId), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + [Fact] public async Task RunCycleWorkerAsync_WhenTheScheduleCannotBeLoaded_ShouldEndTheCycle() { diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledTaskExecutorFactoryTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledTaskExecutorFactoryTests.cs index 075bace8..a7dcef91 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledTaskExecutorFactoryTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledTaskExecutorFactoryTests.cs @@ -24,6 +24,7 @@ public class ScheduledTaskExecutorFactoryTests private readonly TemporaryFilesCleanupTaskExecutor _mockTemporaryFilesCleanupTaskExecutor; private readonly RepairThemesTaskExecutor _mockRepairThemesTaskExecutor; private readonly CleanScheduledJobExecutionHistoryTaskExecutor _mockCleanScheduledJobExecutionHistoryTaskExecutor; + private readonly TechnicalDataCleanupTaskExecutor _mockTechnicalDataCleanupTaskExecutor; private readonly ScheduledTaskExecutorFactory _sut; /// @@ -46,11 +47,15 @@ public class ScheduledTaskExecutorFactoryTests Substitute.For(), Substitute.For>(), Substitute.For()); + _mockTechnicalDataCleanupTaskExecutor = Substitute.For( + Substitute.For>(), + Substitute.For()); _mockServiceProvider.GetService(typeof(MediaLibraryScanTaskExecutor)).Returns(_mockMediaLibraryScanTaskExecutor); _mockServiceProvider.GetService(typeof(TemporaryFilesCleanupTaskExecutor)).Returns(_mockTemporaryFilesCleanupTaskExecutor); _mockServiceProvider.GetService(typeof(RepairThemesTaskExecutor)).Returns(_mockRepairThemesTaskExecutor); _mockServiceProvider.GetService(typeof(CleanScheduledJobExecutionHistoryTaskExecutor)).Returns(_mockCleanScheduledJobExecutionHistoryTaskExecutor); + _mockServiceProvider.GetService(typeof(TechnicalDataCleanupTaskExecutor)).Returns(_mockTechnicalDataCleanupTaskExecutor); _sut = new ScheduledTaskExecutorFactory(_mockServiceProvider); } @@ -95,6 +100,16 @@ public class ScheduledTaskExecutorFactoryTests Assert.Same(_mockCleanScheduledJobExecutionHistoryTaskExecutor, result); } + [Fact] + public void CreateExecutor_WhenTaskTypeIsTechnicalDataCleanup_ShouldReturnTechnicalDataCleanupTaskExecutor() + { + // Act + IScheduledTaskExecutor result = _sut.CreateExecutor(ScheduledTaskType.TechnicalDataCleanup); + + // Assert + Assert.Same(_mockTechnicalDataCleanupTaskExecutor, result); + } + [Fact] public void CreateExecutor_WhenTaskTypeIsUnsupported_ShouldThrowArgumentException() { diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/TechnicalDataCleanupTaskExecutorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/TechnicalDataCleanupTaskExecutorTests.cs new file mode 100644 index 00000000..5cc7882d --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/TechnicalDataCleanupTaskExecutorTests.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors; +using Microsoft.Extensions.Logging; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Scheduling.Execution.TaskExecutors; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TechnicalDataCleanupTaskExecutorTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryScanRepository _mockLibraryScanRepository; + private readonly TechnicalDataCleanupTaskExecutor _sut; + private readonly ScheduledJobFixture _scheduledJobFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public TechnicalDataCleanupTaskExecutorTests() + { + _mockUnitOfWork = Substitute.For(); + _mockLibraryScanRepository = Substitute.For(); + _mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository); + ILogger logger = Substitute.For>(); + _sut = new TechnicalDataCleanupTaskExecutor(logger, _mockUnitOfWork); + } + + [Fact] + public async Task ExecutePayloadAsync_WhenCalled_ShouldFailTheInterruptedScans() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.TechnicalDataCleanup); + _mockLibraryScanRepository.FailInterruptedScansAsync(Arg.Any()).Returns(Result.Updated); + + // Act + Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockLibraryScanRepository.Received(1).FailInterruptedScansAsync(Arg.Any()); + } + + [Fact] + public async Task ExecutePayloadAsync_WhenFailingTheInterruptedScansFails_ShouldReturnTheError() + { + // Arrange + ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.TechnicalDataCleanup); + Error expectedError = Error.Failure("Database.Error", "Failed to fail the interrupted scans"); + _mockLibraryScanRepository.FailInterruptedScansAsync(Arg.Any()).Returns(expectedError); + + // Act + Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(expectedError, result.FirstError); + } +}