mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 10:01:10 +00:00
Adds a technical data cleanup scheduled job that fails interrupted media library scans at startup
This commit is contained in:
1 parent
d33986096e
commit
80af18170a
26 files changed
+395
-10
No files matched your search
+8
@@ -33,4 +33,12 @@ public interface ILibraryScanRepository : IRepository<LibraryScanEntity>,
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="LibraryScanEntity"/>, or an error.</returns>
|
||||
Task<Result<IEnumerable<LibraryScanEntity>>> GetRunningScansAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Marks the media library scans that were interrupted by an application restart, meaning the ones that are still
|
||||
/// <see cref="LibraryScanJobStatus.Pending"/> or <see cref="LibraryScanJobStatus.Running"/>, as failed.
|
||||
/// </summary>
|
||||
/// <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<Updated>> FailInterruptedScansAsync(CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -114,4 +114,20 @@ internal sealed class LibraryScanRepository : ILibraryScanRepository
|
||||
EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundLibraryScan, data);
|
||||
return Result.Updated;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks the media library scans that were interrupted by an application restart, meaning the ones that are still
|
||||
/// <see cref="LibraryScanJobStatus.Pending"/> or <see cref="LibraryScanJobStatus.Running"/>, as failed.
|
||||
/// </summary>
|
||||
/// <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<Updated>> 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;
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
{
|
||||
|
||||
@@ -23,5 +23,10 @@ public enum ScheduledTaskType
|
||||
/// <summary>
|
||||
/// The scheduled job cleans the execution history of the scheduled jobs, keeping only the recent executions.
|
||||
/// </summary>
|
||||
CleanScheduledJobExecutionHistory
|
||||
CleanScheduledJobExecutionHistory,
|
||||
|
||||
/// <summary>
|
||||
/// The scheduled job cleans the technical data that is no longer valid.
|
||||
/// </summary>
|
||||
TechnicalDataCleanup
|
||||
}
|
||||
@@ -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<MediaLibraryScanJobProcessorJob>();
|
||||
|
||||
services.AddTransient<IBooksFileSystemDiscoveryJob, BooksFileSystemDiscoveryJob>();
|
||||
services.AddTransient<IMusicFileSystemDiscoveryJob, MusicFileSystemDiscoveryJob>();
|
||||
services.AddTransient<IMusicMetadataExtractionJob, MusicMetadataExtractionJob>();
|
||||
services.AddTransient<IMediaLibraryScanDiffJob, MediaLibraryScanDiffJob>();
|
||||
services.AddTransient<IMediaLibraryScanHashJob, MediaLibraryScanHashJob>();
|
||||
services.AddTransient<IMediaLibraryScanResultsSaveJob, MediaLibraryScanResultsSaveJob>();
|
||||
@@ -111,6 +115,14 @@ public static class InfrastructureLayerServices
|
||||
services.AddTransient<IMediaLibraryScanMetadataEnrichmentJob, MediaLibraryScanMetadataEnrichmentJob>();
|
||||
services.AddTransient<IMediaLibraryScanArtworkEnrichmentJob, MediaLibraryScanArtworkEnrichmentJob>();
|
||||
|
||||
// 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<IMediaLibraryScanItemMaterializer, BooksMediaLibraryScanItemMaterializer>();
|
||||
services.AddTransient<IMediaLibraryScanItemMaterializer, MusicMediaLibraryScanItemMaterializer>();
|
||||
services.AddTransient<IMediaLibraryScanMetadataEnricher, BooksMediaLibraryScanMetadataEnricher>();
|
||||
services.AddTransient<IMediaLibraryScanMetadataEnricher, MusicMediaLibraryScanMetadataEnricher>();
|
||||
services.AddTransient<IMediaLibraryScanArtworkEnricher, BooksMediaLibraryScanArtworkEnricher>();
|
||||
services.AddTransient<IMediaLibraryScanArtworkEnricher, MusicMediaLibraryScanArtworkEnricher>();
|
||||
|
||||
|
||||
services.AddSingleton<IMediaLibraryScanProgressNotifier, DebouncedMediaLibraryScanProgressNotifier>();
|
||||
|
||||
@@ -153,6 +165,7 @@ public static class InfrastructureLayerServices
|
||||
services.AddScoped<TemporaryFilesCleanupTaskExecutor>();
|
||||
services.AddScoped<RepairThemesTaskExecutor>();
|
||||
services.AddScoped<CleanScheduledJobExecutionHistoryTaskExecutor>();
|
||||
services.AddScoped<TechnicalDataCleanupTaskExecutor>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
@@ -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))
|
||||
};
|
||||
}
|
||||
|
||||
+46
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -23,5 +23,10 @@ public enum ScheduledTaskType
|
||||
/// <summary>
|
||||
/// The scheduled job cleans the execution history of the scheduled jobs, keeping only the recent executions.
|
||||
/// </summary>
|
||||
CleanScheduledJobExecutionHistory
|
||||
CleanScheduledJobExecutionHistory,
|
||||
|
||||
/// <summary>
|
||||
/// The scheduled job cleans the technical data that is no longer valid.
|
||||
/// </summary>
|
||||
TechnicalDataCleanup
|
||||
}
|
||||
@@ -165,6 +165,9 @@
|
||||
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
|
||||
<value>تنظيف سجل الوظائف</value>
|
||||
</data>
|
||||
<data name="TaskType.TechnicalDataCleanup" xml:space="preserve">
|
||||
<value>تنظيف البيانات التقنية</value>
|
||||
</data>
|
||||
<data name="StartupSchedule" xml:space="preserve">
|
||||
<value>عند بدء التشغيل</value>
|
||||
</data>
|
||||
|
||||
@@ -165,6 +165,9 @@
|
||||
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
|
||||
<value>Jobverlauf bereinigen</value>
|
||||
</data>
|
||||
<data name="TaskType.TechnicalDataCleanup" xml:space="preserve">
|
||||
<value>Technische Datenbereinigung</value>
|
||||
</data>
|
||||
<data name="StartupSchedule" xml:space="preserve">
|
||||
<value>Beim Start</value>
|
||||
</data>
|
||||
|
||||
@@ -165,6 +165,9 @@
|
||||
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
|
||||
<value>Clean job history</value>
|
||||
</data>
|
||||
<data name="TaskType.TechnicalDataCleanup" xml:space="preserve">
|
||||
<value>Technical data cleanup</value>
|
||||
</data>
|
||||
<data name="StartupSchedule" xml:space="preserve">
|
||||
<value>At startup</value>
|
||||
</data>
|
||||
|
||||
@@ -165,6 +165,9 @@
|
||||
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
|
||||
<value>Limpiar historial de trabajos</value>
|
||||
</data>
|
||||
<data name="TaskType.TechnicalDataCleanup" xml:space="preserve">
|
||||
<value>Limpieza de datos técnicos</value>
|
||||
</data>
|
||||
<data name="StartupSchedule" xml:space="preserve">
|
||||
<value>Al inicio</value>
|
||||
</data>
|
||||
|
||||
@@ -165,6 +165,9 @@
|
||||
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
|
||||
<value>Nettoyer l'historique des tâches</value>
|
||||
</data>
|
||||
<data name="TaskType.TechnicalDataCleanup" xml:space="preserve">
|
||||
<value>Nettoyage des données techniques</value>
|
||||
</data>
|
||||
<data name="StartupSchedule" xml:space="preserve">
|
||||
<value>Au démarrage</value>
|
||||
</data>
|
||||
|
||||
@@ -165,6 +165,9 @@
|
||||
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
|
||||
<value>Pulisci la cronologia dei processi</value>
|
||||
</data>
|
||||
<data name="TaskType.TechnicalDataCleanup" xml:space="preserve">
|
||||
<value>Pulizia dei dati tecnici</value>
|
||||
</data>
|
||||
<data name="StartupSchedule" xml:space="preserve">
|
||||
<value>All'avvio</value>
|
||||
</data>
|
||||
|
||||
@@ -165,6 +165,9 @@
|
||||
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
|
||||
<value>ジョブ履歴を削除</value>
|
||||
</data>
|
||||
<data name="TaskType.TechnicalDataCleanup" xml:space="preserve">
|
||||
<value>技術データのクリーンアップ</value>
|
||||
</data>
|
||||
<data name="StartupSchedule" xml:space="preserve">
|
||||
<value>起動時</value>
|
||||
</data>
|
||||
|
||||
@@ -165,6 +165,9 @@
|
||||
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
|
||||
<value>Clean job history</value>
|
||||
</data>
|
||||
<data name="TaskType.TechnicalDataCleanup" xml:space="preserve">
|
||||
<value>Technical data cleanup</value>
|
||||
</data>
|
||||
<data name="StartupSchedule" xml:space="preserve">
|
||||
<value>At startup</value>
|
||||
</data>
|
||||
|
||||
@@ -165,6 +165,9 @@
|
||||
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
|
||||
<value>Curăță istoricul proceselor</value>
|
||||
</data>
|
||||
<data name="TaskType.TechnicalDataCleanup" xml:space="preserve">
|
||||
<value>Curățare date tehnice</value>
|
||||
</data>
|
||||
<data name="StartupSchedule" xml:space="preserve">
|
||||
<value>La pornire</value>
|
||||
</data>
|
||||
|
||||
@@ -165,6 +165,9 @@
|
||||
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
|
||||
<value>Очистити історію завдань</value>
|
||||
</data>
|
||||
<data name="TaskType.TechnicalDataCleanup" xml:space="preserve">
|
||||
<value>Очищення технічних даних</value>
|
||||
</data>
|
||||
<data name="StartupSchedule" xml:space="preserve">
|
||||
<value>Під час запуску</value>
|
||||
</data>
|
||||
|
||||
@@ -165,6 +165,9 @@
|
||||
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
|
||||
<value>清理作业历史</value>
|
||||
</data>
|
||||
<data name="TaskType.TechnicalDataCleanup" xml:space="preserve">
|
||||
<value>技术数据清理</value>
|
||||
</data>
|
||||
<data name="StartupSchedule" xml:space="preserve">
|
||||
<value>启动时</value>
|
||||
</data>
|
||||
|
||||
@@ -46,7 +46,8 @@ It keeps the DOM contract the client script binds to, without any images or colo
|
||||
<div class="enlightenment-option" data-value="ScanMediaLibraries">@_localizer["TaskType.ScanMediaLibraries"]</div>
|
||||
<div class="enlightenment-option" data-value="CleanTemporaryFiles">@_localizer["TaskType.CleanTemporaryFiles"]</div>
|
||||
<div class="enlightenment-option" data-value="RepairThemes">@_localizer["TaskType.RepairThemes"]</div>
|
||||
<div class="enlightenment-option last-option" data-value="CleanScheduledJobExecutionHistory">@_localizer["TaskType.CleanScheduledJobExecutionHistory"]</div>
|
||||
<div class="enlightenment-option" data-value="CleanScheduledJobExecutionHistory">@_localizer["TaskType.CleanScheduledJobExecutionHistory"]</div>
|
||||
<div class="enlightenment-option last-option" data-value="TechnicalDataCleanup">@_localizer["TaskType.TechnicalDataCleanup"]</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -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,
|
||||
|
||||
+38
@@ -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<LuminaDbContext>().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<Updated> 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);
|
||||
}
|
||||
}
|
||||
@@ -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<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
|
||||
await mockScheduledJobRepository.Received(6).InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await mockScheduledJobRepository.DidNotReceive().GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
+57
@@ -390,6 +390,8 @@ public class ScheduledJobSchedulerJobTests
|
||||
{
|
||||
// Arrange
|
||||
_mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any<CancellationToken>()).Returns(Array.Empty<ScheduledJobEntity>());
|
||||
_mockScheduledJobRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(new PaginatedResultDto<ScheduledJobEntity> { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 }));
|
||||
IThemeService mockThemeService = Substitute.For<IThemeService>();
|
||||
mockThemeService.GetBundledThemeArchivePaths().Returns([]);
|
||||
IThemeRepository mockThemeRepository = Substitute.For<IThemeRepository>();
|
||||
@@ -407,6 +409,61 @@ public class ScheduledJobSchedulerJobTests
|
||||
await _mockScheduledJobRepository.Received(2).GetActiveOrRunningAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnsureTechnicalDataCleanupScheduledJobAsync_WhenTheJobAlreadyExists_ShouldNotInsertIt()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJobEntity existingJob = _scheduledJobEntityFixture.Create(taskType: ScheduledTaskType.TechnicalDataCleanup, status: ScheduledJobStatus.Active, scheduleType: ScheduleType.OnceAtStartup);
|
||||
_mockScheduledJobRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(new PaginatedResultDto<ScheduledJobEntity> { Data = [existingJob], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 }));
|
||||
|
||||
// Act
|
||||
await InvokeAsync("EnsureTechnicalDataCleanupScheduledJobAsync", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnsureTechnicalDataCleanupScheduledJobAsync_WhenThereAreNoScheduledJobs_ShouldNotInsertIt()
|
||||
{
|
||||
// Arrange
|
||||
_mockScheduledJobRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(new PaginatedResultDto<ScheduledJobEntity> { 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<ScheduledJobEntity>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(new PaginatedResultDto<ScheduledJobEntity> { Data = [existingJob], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 }));
|
||||
_mockScheduledJobRepository.InsertAsync(Arg.Any<ScheduledJobEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
|
||||
|
||||
// Act
|
||||
await InvokeAsync("EnsureTechnicalDataCleanupScheduledJobAsync", CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockScheduledJobRepository.Received(1).InsertAsync(
|
||||
Arg.Is<ScheduledJobEntity>(scheduledJob =>
|
||||
scheduledJob.TaskType == ScheduledTaskType.TechnicalDataCleanup &&
|
||||
scheduledJob.ScheduleType == ScheduleType.OnceAtStartup &&
|
||||
scheduledJob.Status == ScheduledJobStatus.Active &&
|
||||
scheduledJob.OwnerUserId == ownerUserId &&
|
||||
scheduledJob.CreatedBy == ownerUserId),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunCycleWorkerAsync_WhenTheScheduleCannotBeLoaded_ShouldEndTheCycle()
|
||||
{
|
||||
|
||||
+15
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
@@ -46,11 +47,15 @@ public class ScheduledTaskExecutorFactoryTests
|
||||
Substitute.For<IDateTimeProvider>(),
|
||||
Substitute.For<ILogger<CleanScheduledJobExecutionHistoryTaskExecutor>>(),
|
||||
Substitute.For<IUnitOfWork>());
|
||||
_mockTechnicalDataCleanupTaskExecutor = Substitute.For<TechnicalDataCleanupTaskExecutor>(
|
||||
Substitute.For<ILogger<TechnicalDataCleanupTaskExecutor>>(),
|
||||
Substitute.For<IUnitOfWork>());
|
||||
|
||||
_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()
|
||||
{
|
||||
|
||||
+71
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="TechnicalDataCleanupTaskExecutor"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TechnicalDataCleanupTaskExecutorTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ILibraryScanRepository _mockLibraryScanRepository;
|
||||
private readonly TechnicalDataCleanupTaskExecutor _sut;
|
||||
private readonly ScheduledJobFixture _scheduledJobFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="TechnicalDataCleanupTaskExecutorTests"/> class.
|
||||
/// </summary>
|
||||
public TechnicalDataCleanupTaskExecutorTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockLibraryScanRepository = Substitute.For<ILibraryScanRepository>();
|
||||
_mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository);
|
||||
ILogger<TechnicalDataCleanupTaskExecutor> logger = Substitute.For<ILogger<TechnicalDataCleanupTaskExecutor>>();
|
||||
_sut = new TechnicalDataCleanupTaskExecutor(logger, _mockUnitOfWork);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecutePayloadAsync_WhenCalled_ShouldFailTheInterruptedScans()
|
||||
{
|
||||
// Arrange
|
||||
ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.TechnicalDataCleanup);
|
||||
_mockLibraryScanRepository.FailInterruptedScansAsync(Arg.Any<CancellationToken>()).Returns(Result.Updated);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
await _mockLibraryScanRepository.Received(1).FailInterruptedScansAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<CancellationToken>()).Returns(expectedError);
|
||||
|
||||
// Act
|
||||
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(expectedError, result.FirstError);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user