diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Scheduling/ScheduledJobExecutionEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Scheduling/ScheduledJobExecutionEntity.cs index e05774c9..5bf05e66 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/Scheduling/ScheduledJobExecutionEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/Scheduling/ScheduledJobExecutionEntity.cs @@ -43,6 +43,16 @@ public class ScheduledJobExecutionEntity : IStorageEntity, IAuditableEntity /// public DateTime? CompletedOnUtc { get; init; } + /// + /// Gets a value indicating whether the execution cycle of the scheduled job was active when the execution started. + /// + /// + /// A job whose execution cycle is active stays in its active state while a manually fired one time execution runs, so an + /// interrupted execution of such a job must return it to its active state at the next startup; the flag keeps that fact + /// separate from , which records how the execution was triggered for the audit trail. + /// + public required bool WasCycleActive { get; init; } + /// /// Gets or sets the time and date when the entity was added. /// diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/IScheduledJobExecutionRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/IScheduledJobExecutionRepository.cs index d6817638..a01a7f7e 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/IScheduledJobExecutionRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/IScheduledJobExecutionRepository.cs @@ -43,4 +43,12 @@ public interface IScheduledJobExecutionRepository : IRepositoryCancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. Task> DeleteByScheduledJobIdAsync(Guid scheduledJobId, CancellationToken cancellationToken); + + /// + /// Removes all the executions of the tasks of scheduled jobs that started before , from the storage medium. + /// + /// The exclusive lower bound of the retained interval, in UTC; executions that started before it are removed. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> DeleteOlderThanAsync(DateTime cutoffUtc, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/IScheduledJobRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/IScheduledJobRepository.cs index 438dceb2..84138240 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/IScheduledJobRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Scheduling/IScheduledJobRepository.cs @@ -22,6 +22,14 @@ public interface IScheduledJobRepository : IRepository, IUpdateRepositoryAction, IDeleteByIdRepositoryAction { + /// + /// Gets a scheduled job identified by from the storage medium, without tracking it. + /// + /// The id of the scheduled job to get. + /// Cancellation token that can be used to stop the execution. + /// An containing either a identified by , or an error. + Task> GetByIdWithoutTrackingAsync(Guid id, CancellationToken cancellationToken); + /// /// Gets the scheduled jobs that have an active or running execution cycle, from the storage medium. /// diff --git a/src/Lumina.Application/Common/DataAccess/Seed/IDataSeedService.cs b/src/Lumina.Application/Common/DataAccess/Seed/IDataSeedService.cs index da3303cb..4314abbe 100644 --- a/src/Lumina.Application/Common/DataAccess/Seed/IDataSeedService.cs +++ b/src/Lumina.Application/Common/DataAccess/Seed/IDataSeedService.cs @@ -43,4 +43,12 @@ public interface IDataSeedService /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. Task> SetAdminRoleToAdministratorAccount(Guid userId, CancellationToken cancellationToken); + + /// + /// Sets up the default scheduled jobs, owned by the administrator account. + /// + /// The unique identifier of the administrator account that owns the default scheduled jobs. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> SetDefaultScheduledJobsAsync(Guid adminUserId, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobEntityMapping.cs index 78be15a5..23734cb6 100644 --- a/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobEntityMapping.cs @@ -94,6 +94,14 @@ public static class ScheduledJobEntityMapping return Result.From(intervalScheduleResult.Value); } + if (repositoryEntity.ScheduleType == ScheduleType.OnceAtStartup) + { + Result onceAtStartupScheduleResult = OnceAtStartupSchedule.Create(); + if (onceAtStartupScheduleResult.IsFailure) + return onceAtStartupScheduleResult.Errors; + return Result.From(onceAtStartupScheduleResult.Value); + } + Result dailyScheduleResult = DailySchedule.Create(repositoryEntity.Hour ?? 0, repositoryEntity.Minute ?? 0); if (dailyScheduleResult.IsFailure) return dailyScheduleResult.Errors; diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs index fdc1df53..47a8a836 100644 --- a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs @@ -1,16 +1,21 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.Seed; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DomainEvents; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Security; using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Contracts.Responses.Authentication; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; using System; using System.Collections.Generic; using System.Linq; @@ -32,6 +37,7 @@ public class SetupApplicationCommandHandler : ICommandHandler _validator; /// @@ -44,6 +50,7 @@ public class SetupApplicationCommandHandler : ICommandHandlerInjected service for generating QR codes. /// Injected service for time related concerns. /// Injected service for the initial persistence medium data seed. + /// Injected service for the queue of domain events. /// Injected validator for application validation rules. public SetupApplicationCommandHandler( IUnitOfWork unitOfWork, @@ -53,6 +60,7 @@ public class SetupApplicationCommandHandler : ICommandHandler validator) { _unitOfWork = unitOfWork; @@ -62,6 +70,7 @@ public class SetupApplicationCommandHandler : ICommandHandler 0) return validationResult; - // check if any users already exists (admin account is only set once!) + // Check if any users already exists (admin account is only set once!). Result> selectUsersResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); if (selectUsersResult.IsFailure) return selectUsersResult.Errors; @@ -100,23 +109,23 @@ public class SetupApplicationCommandHandler : ICommandHandler insertUserResult = await _unitOfWork.UserRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false); if (insertUserResult.IsFailure) return insertUserResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - // set the default permissions, roles, roles permissions + // Set the default permissions, roles, roles permissions. Result setPermissionsResult = await _dataSeedService.SetDefaultAuthorizationPermissionsAsync(id, cancellationToken).ConfigureAwait(false); if (setPermissionsResult.IsFailure) return setPermissionsResult.Errors; @@ -133,8 +142,23 @@ public class SetupApplicationCommandHandler : ICommandHandler setDefaultScheduledJobsResult = await _dataSeedService.SetDefaultScheduledJobsAsync(id, cancellationToken).ConfigureAwait(false); + if (setDefaultScheduledJobsResult.IsFailure) + return setDefaultScheduledJobsResult.Errors; + + // The default jobs were seeded with an active execution cycle, so a cycle started event is queued for each of them; the + // queued events are published only after the setup transaction commits, because a cycle worker started inside the request + // would try to read the scheduled jobs while the still open setup transaction locks the storage medium. + Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + if (getScheduledJobsResult.IsFailure) + return getScheduledJobsResult.Errors; + foreach (ScheduledJobEntity scheduledJob in getScheduledJobsResult.Value) + if (scheduledJob.Status == ScheduledJobStatus.Active) + _domainEventsQueue.Enqueue(new ScheduledJobCycleStartedDomainEvent(Guid.NewGuid(), ScheduledJobId.Create(scheduledJob.Id), DateTime.UtcNow)); + + // TODO: insert the default admin profile preferences when they are implemented. + // If 2FA was enabled during registration, the TOTP secret needs to be delivered to the client unhashed, so it can be displayed return new RegistrationResponse(user.Id, user.Username, totpSecret); } } diff --git a/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandler.cs b/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandler.cs index aa5167b7..02151efa 100644 --- a/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandler.cs +++ b/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandler.cs @@ -97,6 +97,13 @@ public class AddScheduledJobCommandHandler : ICommandHandler(dailyScheduleResult.Value); } + else if (command.ScheduleType == ScheduleType.OnceAtStartup) + { + Result onceAtStartupScheduleResult = OnceAtStartupSchedule.Create(); + if (onceAtStartupScheduleResult.IsFailure) + return onceAtStartupScheduleResult.Errors; + scheduleResult = Result.From(onceAtStartupScheduleResult.Value); + } else return DomainErrors.Scheduling.InvalidScheduleType; diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandler.cs index ebfaa878..6d2df8ee 100644 --- a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandler.cs @@ -123,6 +123,7 @@ public class ScheduledJobExecutionCompletedDomainEventHandler : IDomainEventHand ScheduledJobId = execution.ScheduledJobId, TaskType = execution.TaskType, IsCycleRun = execution.IsCycleRun, + WasCycleActive = execution.WasCycleActive, StartedOnUtc = execution.StartedOnUtc, CompletedOnUtc = completedOnUtc, CreatedOnUtc = execution.CreatedOnUtc, diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandler.cs index 525bfdcf..2e81591f 100644 --- a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandler.cs @@ -52,6 +52,9 @@ public class ScheduledJobExecutionStartedDomainEventHandler : IDomainEventHandle if (getScheduledJobResult.Value is null) throw new EventualConsistencyException(Errors.Scheduling.ScheduledJobNotFound); ScheduledJobEntity scheduledJob = getScheduledJobResult.Value; + // The execution cycle is active when the scheduled job was in its active state before this execution started; the + // status is read before the scheduled job is updated to its running state below. + bool wasCycleActive = scheduledJob.Status == ScheduledJobStatus.Active; // Update the scheduled job with its running status and the start time of the execution. ScheduledJobEntity updatedScheduledJob = CreateUpdatedScheduledJob(scheduledJob, ScheduledJobStatus.Running, domainEvent.StartedOnUtc, scheduledJob.LastCompletedOnUtc); @@ -66,6 +69,7 @@ public class ScheduledJobExecutionStartedDomainEventHandler : IDomainEventHandle ScheduledJobId = scheduledJob.Id, TaskType = scheduledJob.TaskType, IsCycleRun = domainEvent.IsCycleRun, + WasCycleActive = wasCycleActive, StartedOnUtc = domainEvent.StartedOnUtc, CompletedOnUtc = null, CreatedOnUtc = scheduledJob.CreatedOnUtc, diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandler.cs index 7da598e4..cc735453 100644 --- a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandler.cs @@ -56,6 +56,7 @@ public class ScheduledJobExecutionStoppedDomainEventHandler : IDomainEventHandle ScheduledJobId = execution.ScheduledJobId, TaskType = execution.TaskType, IsCycleRun = execution.IsCycleRun, + WasCycleActive = execution.WasCycleActive, StartedOnUtc = execution.StartedOnUtc, CompletedOnUtc = domainEvent.OccurredOnUtc, CreatedOnUtc = execution.CreatedOnUtc, diff --git a/src/Lumina.DataAccess/Common/Configuration/ScheduledJobExecutionConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/ScheduledJobExecutionConfiguration.cs index 6eee41e5..64053b4a 100644 --- a/src/Lumina.DataAccess/Common/Configuration/ScheduledJobExecutionConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/ScheduledJobExecutionConfiguration.cs @@ -44,22 +44,26 @@ public class ScheduledJobExecutionConfiguration : IEntityTypeConfiguration execution.CompletedOnUtc) .HasColumnOrder(5); - // Audit. - builder.Property(execution => execution.CreatedOnUtc) + builder.Property(execution => execution.WasCycleActive) .IsRequired() .HasColumnOrder(6); - builder.Property(execution => execution.CreatedBy) + // Audit. + builder.Property(execution => execution.CreatedOnUtc) .IsRequired() .HasColumnOrder(7); + builder.Property(execution => execution.CreatedBy) + .IsRequired() + .HasColumnOrder(8); + builder.Property(execution => execution.UpdatedOnUtc) .HasDefaultValue(null) - .HasColumnOrder(8); + .HasColumnOrder(9); builder.Property(execution => execution.UpdatedBy) .HasDefaultValue(null) - .HasColumnOrder(9); + .HasColumnOrder(10); // Enables fast queries of the execution history of scheduled jobs by their time range, and the cleanup of the executions of a removed scheduled job. builder.HasIndex(execution => new { execution.StartedOnUtc, execution.ScheduledJobId }); diff --git a/src/Lumina.DataAccess/Common/Migrations/20260904204717_AddsWasCycleActiveToScheduledJobExecutions.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20260904204717_AddsWasCycleActiveToScheduledJobExecutions.Designer.cs new file mode 100644 index 00000000..b457484e --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260904204717_AddsWasCycleActiveToScheduledJobExecutions.Designer.cs @@ -0,0 +1,1792 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20260904204717_AddsWasCycleActiveToScheduledJobExecutions")] + partial class AddsWasCycleActiveToScheduledJobExecutions + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.BookContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("RoleCategory") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("BookId", "MediaContributorId"); + + b.ToTable("BookContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.MediaContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Biography") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("DateOfBirth") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("DateOfDeath") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1) + .UseCollation("NOCASE"); + + b.Property("LegalName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.HasKey("Id"); + + b.HasIndex("DisplayName") + .IsUnique(); + + b.ToTable("MediaContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastWriteTimeUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("DirectoryScanFingerprints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CanDownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("ShouldSaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("LibraryId", "Status", "CreatedOnUtc") + .IsDescending(true, false, true); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("LibraryScanSnapshots", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("LibraryScanId", "NeedsRehash"); + + b.ToTable("LibraryScanStagingResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("BookId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("BookArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("MetadataStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("REAL") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "MetadataStatus"); + + b.HasIndex("LibraryId", "Path"); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryArtworkProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryBookReaderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId") + .IsUnique(); + + b.ToTable("LibraryBookReaderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryMetadataProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.PluginEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Description") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LoadError") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("LoadStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("SettingsJson") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.ToTable("Plugins", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Hour") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("IntervalMinutes") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("LastCompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LastStartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Minute") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("OwnerUserId") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ScheduleType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.ToTable("ScheduledJobs", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.ScheduledJobExecutionEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CompletedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("IsCycleRun") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ScheduledJobId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("StartedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TaskType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("WasCycleActive") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("ScheduledJobId"); + + b.HasIndex("StartedOnUtc", "ScheduledJobId"); + + b.ToTable("ScheduledJobExecutions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Scheduling.SchedulerDisplayPreferencesEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayTimeSpan") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("DisplayTimeUnit") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("JobTypeFilter") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("SchedulerDisplayPreferences", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Themes.ThemeEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Description") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("InstallSource") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("InstalledAtUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("IsCurrent") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(9); + + b.Property("Name") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PreviewPath") + .HasMaxLength(240) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ThemeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Version") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.HasIndex("IsCurrent") + .IsUnique() + .HasFilter("IsCurrent = 1"); + + b.HasIndex("ThemeId") + .IsUnique(); + + b.ToTable("Themes", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsPaginationEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("IsThemeCachingEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ItemsPerPage") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ShouldAggregateMetadataWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ShouldIgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("ShouldPreserveBookStyles") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("ShouldRenderPdfAsImages") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserSettings", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.BookContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("BookContributors") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LibraryScan"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null) + .WithMany() + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("BookArtwork") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithOne() + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Navigation("LibraryScanResults"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Navigation("BookArtwork"); + + b.Navigation("BookContributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("LibraryScans"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20260904204717_AddsWasCycleActiveToScheduledJobExecutions.cs b/src/Lumina.DataAccess/Common/Migrations/20260904204717_AddsWasCycleActiveToScheduledJobExecutions.cs new file mode 100644 index 00000000..d44ce67a --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260904204717_AddsWasCycleActiveToScheduledJobExecutions.cs @@ -0,0 +1,115 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class AddsWasCycleActiveToScheduledJobExecutions : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "UpdatedOnUtc", + table: "ScheduledJobExecutions", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateTime), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 9) + .OldAnnotation("Relational:ColumnOrder", 8); + + migrationBuilder.AlterColumn( + name: "UpdatedBy", + table: "ScheduledJobExecutions", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 10) + .OldAnnotation("Relational:ColumnOrder", 9); + + migrationBuilder.AlterColumn( + name: "CreatedOnUtc", + table: "ScheduledJobExecutions", + type: "TEXT", + nullable: false, + oldClrType: typeof(DateTime), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 7) + .OldAnnotation("Relational:ColumnOrder", 6); + + migrationBuilder.AlterColumn( + name: "CreatedBy", + table: "ScheduledJobExecutions", + type: "TEXT", + nullable: false, + oldClrType: typeof(Guid), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 8) + .OldAnnotation("Relational:ColumnOrder", 7); + + migrationBuilder.AddColumn( + name: "WasCycleActive", + table: "ScheduledJobExecutions", + type: "INTEGER", + nullable: false, + defaultValue: false) + .Annotation("Relational:ColumnOrder", 6); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "WasCycleActive", + table: "ScheduledJobExecutions"); + + migrationBuilder.AlterColumn( + name: "UpdatedOnUtc", + table: "ScheduledJobExecutions", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateTime), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 8) + .OldAnnotation("Relational:ColumnOrder", 9); + + migrationBuilder.AlterColumn( + name: "UpdatedBy", + table: "ScheduledJobExecutions", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 9) + .OldAnnotation("Relational:ColumnOrder", 10); + + migrationBuilder.AlterColumn( + name: "CreatedOnUtc", + table: "ScheduledJobExecutions", + type: "TEXT", + nullable: false, + oldClrType: typeof(DateTime), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 6) + .OldAnnotation("Relational:ColumnOrder", 7); + + migrationBuilder.AlterColumn( + name: "CreatedBy", + table: "ScheduledJobExecutions", + type: "TEXT", + nullable: false, + oldClrType: typeof(Guid), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 7) + .OldAnnotation("Relational:ColumnOrder", 8); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs index 9f148e5f..79d0b407 100644 --- a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs +++ b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs @@ -1167,11 +1167,11 @@ namespace Lumina.DataAccess.Common.Migrations b.Property("CreatedBy") .HasColumnType("TEXT") - .HasColumnOrder(7); + .HasColumnOrder(8); b.Property("CreatedOnUtc") .HasColumnType("TEXT") - .HasColumnOrder(6); + .HasColumnOrder(7); b.Property("IsCycleRun") .HasColumnType("INTEGER") @@ -1192,11 +1192,15 @@ namespace Lumina.DataAccess.Common.Migrations b.Property("UpdatedBy") .HasColumnType("TEXT") - .HasColumnOrder(9); + .HasColumnOrder(10); b.Property("UpdatedOnUtc") .HasColumnType("TEXT") - .HasColumnOrder(8); + .HasColumnOrder(9); + + b.Property("WasCycleActive") + .HasColumnType("INTEGER") + .HasColumnOrder(6); b.HasKey("Id"); diff --git a/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobExecutionRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobExecutionRepository.cs index b5be3bac..32f4fa45 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobExecutionRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobExecutionRepository.cs @@ -38,8 +38,9 @@ internal sealed class ScheduledJobExecutionRepository : IScheduledJobExecutionRe /// An containing either a identified by , or an error. public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) { - return await _luminaDbContext.ScheduledJobExecutions - .FirstOrDefaultAsync(execution => execution.Id == id, cancellationToken).ConfigureAwait(false); + // FindAsync returns an entity that was already loaded in the current unit of work from the change tracker, and only + // reads it from the storage medium when it is not tracked, so an entity loaded earlier is not read again. + return await _luminaDbContext.ScheduledJobExecutions.FindAsync([id], cancellationToken).ConfigureAwait(false); } /// @@ -67,8 +68,8 @@ internal sealed class ScheduledJobExecutionRepository : IScheduledJobExecutionRe /// An representing either a successful operation, or an error. public async Task> UpdateAsync(ScheduledJobExecutionEntity data, CancellationToken cancellationToken) { - ScheduledJobExecutionEntity? foundExecution = await _luminaDbContext.ScheduledJobExecutions - .FirstOrDefaultAsync(execution => execution.Id == data.Id, cancellationToken).ConfigureAwait(false); + ScheduledJobExecutionEntity? foundExecution = _luminaDbContext.ScheduledJobExecutions.Local.FirstOrDefault(execution => execution.Id == data.Id) + ?? await _luminaDbContext.ScheduledJobExecutions.FirstOrDefaultAsync(execution => execution.Id == data.Id, cancellationToken).ConfigureAwait(false); if (foundExecution is null) return Errors.Scheduling.ScheduledJobExecutionNotFound; // Update scalar properties. @@ -119,4 +120,20 @@ internal sealed class ScheduledJobExecutionRepository : IScheduledJobExecutionRe _luminaDbContext.ScheduledJobExecutions.RemoveRange(executions); return Result.Success; } + + /// + /// Removes all the executions of the tasks of scheduled jobs that started before , from the storage medium. + /// + /// The exclusive lower bound of the retained interval, in UTC; executions that started before it are removed. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteOlderThanAsync(DateTime cutoffUtc, CancellationToken cancellationToken) + { + // The executions are deleted with a single query, without loading them into memory first, because the retention cleanup + // routinely removes a large number of executions at once. + await _luminaDbContext.ScheduledJobExecutions + .Where(execution => execution.StartedOnUtc < cutoffUtc) + .ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false); + return Result.Success; + } } diff --git a/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobRepository.cs index 116c90c6..899b05fb 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobRepository.cs @@ -39,7 +39,22 @@ internal sealed class ScheduledJobRepository : IScheduledJobRepository /// An containing either a identified by , or an error. public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) { + // FindAsync returns an entity that was already loaded in the current unit of work from the change tracker, and only + // reads it from the storage medium when it is not tracked, so an entity loaded earlier is not read again. + return await _luminaDbContext.ScheduledJobs.FindAsync([id], cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets a scheduled job identified by from the storage medium, without tracking it. + /// + /// The id of the scheduled job to get. + /// Cancellation token that can be used to stop the execution. + /// An containing either a identified by , or an error. + public async Task> GetByIdWithoutTrackingAsync(Guid id, CancellationToken cancellationToken) + { + // The entity is read without tracking, so a concurrent update made by another unit of work is never hidden by an already tracked copy. return await _luminaDbContext.ScheduledJobs + .AsNoTracking() .FirstOrDefaultAsync(scheduledJob => scheduledJob.Id == id, cancellationToken).ConfigureAwait(false); } @@ -91,8 +106,8 @@ internal sealed class ScheduledJobRepository : IScheduledJobRepository /// An representing either a successful operation, or an error. public async Task> UpdateAsync(ScheduledJobEntity data, CancellationToken cancellationToken) { - ScheduledJobEntity? foundScheduledJob = await _luminaDbContext.ScheduledJobs - .FirstOrDefaultAsync(scheduledJob => scheduledJob.Id == data.Id, cancellationToken).ConfigureAwait(false); + ScheduledJobEntity? foundScheduledJob = _luminaDbContext.ScheduledJobs.Local.FirstOrDefault(scheduledJob => scheduledJob.Id == data.Id) + ?? await _luminaDbContext.ScheduledJobs.FirstOrDefaultAsync(scheduledJob => scheduledJob.Id == data.Id, cancellationToken).ConfigureAwait(false); if (foundScheduledJob is null) return Errors.Scheduling.ScheduledJobNotFound; // Update scalar properties. diff --git a/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs b/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs index 6caf0fea..f37fceba 100644 --- a/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs +++ b/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs @@ -1,14 +1,14 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Application.Common.DataAccess.Repositories.Authorization; -using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.Seed; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; using System; using System.Collections.Generic; using System.Threading; @@ -44,7 +44,7 @@ public class DataSeedService : IDataSeedService /// An representing either a successful operation, or an error. public async Task> SetDefaultAuthorizationPermissionsAsync(Guid adminId, CancellationToken cancellationToken) { - // create the default authorization permissions and add them to the repository. + // Create the default authorization permissions and add them to the repository. PermissionEntity[] defaultPermissions = [ new() { PermissionName = AuthorizationPermission.CanViewUsers, CreatedBy = adminId, CreatedOnUtc = _dateTimeProvider.UtcNow }, @@ -70,7 +70,7 @@ public class DataSeedService : IDataSeedService /// An representing either a successful operation, or an error. public async Task> SetDefaultAuthorizationRolesAsync(Guid userId, CancellationToken cancellationToken) { - // create the default authorization roles and add them to the repository + // Create the default authorization roles and add them to the repository. RoleEntity[] defaultRoles = [ new() { RoleName = "Admin", CreatedBy = userId, CreatedOnUtc = _dateTimeProvider.UtcNow } @@ -93,7 +93,7 @@ public class DataSeedService : IDataSeedService /// An representing either a successful operation, or an error. public async Task> SetAdminRolePermissionsAsync(Guid userId, CancellationToken cancellationToken) { - // get the admin role + // Get the admin role. Result getAdminRoleResult = await _unitOfWork.RoleRepository.GetByNameAsync("Admin", cancellationToken).ConfigureAwait(false); if (getAdminRoleResult.IsFailure) return getAdminRoleResult.Errors; @@ -101,12 +101,12 @@ public class DataSeedService : IDataSeedService if (getAdminRoleResult.Value is null) return Errors.Authorization.AdminAccountNotFound; - // get all permissions + // Get all permissions. Result> getPermissionsResult = await _unitOfWork.PermissionRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); if (getPermissionsResult.IsFailure) return getPermissionsResult.Errors; - // add each permission to the admin role + // Add each permission to the admin role. foreach (PermissionEntity permission in getPermissionsResult.Value) { RolePermissionEntity rolePermissionEntity = new() @@ -134,7 +134,7 @@ public class DataSeedService : IDataSeedService /// An representing either a successful operation, or an error. public async Task> SetAdminRoleToAdministratorAccount(Guid userId, CancellationToken cancellationToken) { - // get the admin role + // Get the admin role. Result getAdminRoleResult = await _unitOfWork.RoleRepository.GetByNameAsync("Admin", cancellationToken).ConfigureAwait(false); if (getAdminRoleResult.IsFailure) return getAdminRoleResult.Errors; @@ -142,7 +142,7 @@ public class DataSeedService : IDataSeedService if (getAdminRoleResult.Value is null) return Errors.Authorization.AdminRoleNotFound; - // get admin user + // Get admin user. Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure) return getUserResult.Errors; @@ -150,7 +150,7 @@ public class DataSeedService : IDataSeedService if (getUserResult.Value is null) return Errors.Authorization.AdminAccountNotFound; - // add the admin role to the admin user + // Add the admin role to the admin user. UserRoleEntity userRole = new() { CreatedBy = userId, @@ -167,4 +167,69 @@ public class DataSeedService : IDataSeedService await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return Result.Created; } + + /// + /// Sets up the default scheduled jobs, owned by the administrator account. + /// + /// The unique identifier of the administrator account that owns the default scheduled jobs. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> SetDefaultScheduledJobsAsync(Guid adminUserId, CancellationToken cancellationToken) + { + // Seed the default jobs. + ScheduledJobEntity[] defaultScheduledJobs = + [ + // Scan all the enabled media libraries, daily at midnight. + CreateDefaultScheduledJob("Daily media library scan", ScheduledTaskType.ScanMediaLibraries, ScheduleType.DailyAtHourAndMinute, intervalMinutes: null, hour: 0, minute: 0, adminUserId), + // Clean the temporary directory into which the reading plugins extract the books, at every application startup. + CreateDefaultScheduledJob("Clean temporary files at startup", ScheduledTaskType.CleanTemporaryFiles, ScheduleType.OnceAtStartup, intervalMinutes: null, hour: null, minute: null, adminUserId), + // Clean the temporary directory into which the reading plugins extract the books, every 12 hours. + CreateDefaultScheduledJob("Clean temporary files every 12 hours", ScheduledTaskType.CleanTemporaryFiles, ScheduleType.WithIntervalInMinutes, intervalMinutes: 720, hour: null, minute: null, adminUserId), + // 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) + ]; + foreach (ScheduledJobEntity defaultScheduledJob in defaultScheduledJobs) + { + Result insertScheduledJobResult = await _unitOfWork.ScheduledJobRepository.InsertAsync(defaultScheduledJob, cancellationToken).ConfigureAwait(false); + if (insertScheduledJobResult.IsFailure) + return insertScheduledJobResult.Errors; + } + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + return Result.Created; + } + + /// + /// Creates a default scheduled job with its execution cycle active, owned by the administrator account identified by . + /// + /// The name of the default scheduled job. + /// The type of the task executed by the default scheduled job. + /// The type of the schedule of the default scheduled job. + /// The interval in minutes of the schedule, when it is an interval schedule. + /// The hour of the schedule, when it is a daily schedule. + /// The minute of the schedule, when it is a daily schedule. + /// The unique identifier of the administrator account that owns the default scheduled job. + /// The created default scheduled job. + private ScheduledJobEntity CreateDefaultScheduledJob(string name, ScheduledTaskType taskType, ScheduleType scheduleType, int? intervalMinutes, int? hour, int? minute, Guid adminUserId) + { + return new ScheduledJobEntity + { + Id = Guid.NewGuid(), + Name = name, + TaskType = taskType, + ScheduleType = scheduleType, + IntervalMinutes = intervalMinutes, + Hour = hour, + Minute = minute, + Status = ScheduledJobStatus.Active, + OwnerUserId = adminUserId, + LastStartedOnUtc = null, + LastCompletedOnUtc = null, + CreatedOnUtc = _dateTimeProvider.UtcNow, + CreatedBy = adminUserId, + UpdatedOnUtc = null, + UpdatedBy = null + }; + } } diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Scheduling/ScheduleType.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Scheduling/ScheduleType.cs index c8b274f8..34454e08 100644 --- a/src/Lumina.Domain.SharedKernel/Common/Enums/Scheduling/ScheduleType.cs +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Scheduling/ScheduleType.cs @@ -13,5 +13,10 @@ public enum ScheduleType /// /// The scheduled job repeats daily at a fixed hour and minute. /// - DailyAtHourAndMinute + DailyAtHourAndMinute, + + /// + /// The scheduled job fires its task once, every time the application starts. + /// + OnceAtStartup } diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Scheduling/ScheduledTaskType.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Scheduling/ScheduledTaskType.cs index d6691e10..cc91f3cc 100644 --- a/src/Lumina.Domain.SharedKernel/Common/Enums/Scheduling/ScheduledTaskType.cs +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Scheduling/ScheduledTaskType.cs @@ -13,5 +13,15 @@ public enum ScheduledTaskType /// /// The scheduled job cleans the temporary directory of the application. /// - CleanTemporaryFiles + CleanTemporaryFiles, + + /// + /// The scheduled job repairs the installed themes whose files are missing. + /// + RepairThemes, + + /// + /// The scheduled job cleans the execution history of the scheduled jobs, keeping only the recent executions. + /// + CleanScheduledJobExecutionHistory } diff --git a/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/DailySchedule.cs b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/DailySchedule.cs index 083ad154..2b63fe38 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/DailySchedule.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/DailySchedule.cs @@ -10,7 +10,7 @@ using System.Collections.Generic; namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; /// -/// Represents a daily schedule for a scheduled job. +/// Value Object for the daily schedule for a scheduled job. /// public class DailySchedule : Schedule { diff --git a/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/IntervalSchedule.cs b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/IntervalSchedule.cs index cd953c3b..f4720474 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/IntervalSchedule.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/IntervalSchedule.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Errors; -using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; using System; @@ -10,7 +9,7 @@ using System.Collections.Generic; namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; /// -/// Represents an interval based schedule for a scheduled job. +/// Value Object for the interval based schedule for a scheduled job. /// public class IntervalSchedule : Schedule { diff --git a/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/OnceAtStartupSchedule.cs b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/OnceAtStartupSchedule.cs new file mode 100644 index 00000000..c17c914d --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/OnceAtStartupSchedule.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; + +/// +/// Value Object for the schedule that fires the task of the scheduled job once, at every application startup. +/// +public class OnceAtStartupSchedule : Schedule +{ + /// + /// Gets the type of the schedule. + /// + public override ScheduleType ScheduleType { get; } = ScheduleType.OnceAtStartup; + + /// + /// Initializes a new instance of the class. + /// + private OnceAtStartupSchedule() + { + } + + /// + /// Creates a new instance of the class. + /// + /// + /// An containing either a successfully created , or an error message. + /// + public static Result Create() + { + return new OnceAtStartupSchedule(); + } + + /// + /// Calculates the delay until the next execution of the scheduled job, relative to . + /// + /// The current UTC date and time. + /// The time zone in which the daily hour and minute of the schedule are expressed. + /// The delay until the next execution of the scheduled job. + /// + /// A once at startup schedule has no further execution after the one fired at the application startup, so the scheduler + /// never calls this method for it; a maximum delay is returned so that the contract stays total. + /// + public override TimeSpan GetDelayUntilNextExecution(DateTime utcNow, TimeZoneInfo timeZone) + { + return TimeSpan.MaxValue; + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield break; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/Schedule.cs b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/Schedule.cs index fc60cc93..e14d3eeb 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/Schedule.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/Schedule.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Models.Core; -using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; using System; #endregion @@ -8,7 +7,7 @@ using System; namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; /// -/// Represents an abstract schedule for a scheduled job. +/// Value Object for the abstract schedule for a scheduled job. /// public abstract class Schedule : ValueObject { diff --git a/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/ScheduledJobId.cs b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/ScheduledJobId.cs index 67dc42bc..c6dcbdce 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/ScheduledJobId.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/ScheduledJobId.cs @@ -8,7 +8,7 @@ using System.Diagnostics; namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; /// -/// Value object for the Id of a scheduled job. +/// Value Object for the Id of a scheduled job. /// [DebuggerDisplay("{Value}")] public sealed class ScheduledJobId : EntityId diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index 11134530..7e857371 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -139,9 +139,9 @@ public static class InfrastructureLayerServices serviceProvider.GetRequiredService>())); services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService()); - // Themes: the theme service stores and serves theme packs, and the detection job seeds the bundled themes at startup. + // Themes: the theme service stores and serves theme packs; the bundled themes are installed and repaired by the + // default "Repair themes at startup" scheduled job that is seeded when the application is set up. services.AddSingleton(); - services.AddHostedService(); // Scheduled jobs: the scheduler executes the tasks of the scheduled jobs on their schedules, and the notifier broadcasts their state to the SignalR clients. services.AddSingleton(); @@ -151,6 +151,8 @@ public static class InfrastructureLayerServices services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); + services.AddScoped(); return services; } diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledJobRuntimeRegistry.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledJobRuntimeRegistry.cs index 73c671c2..de8ade8b 100644 --- a/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledJobRuntimeRegistry.cs +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/IScheduledJobRuntimeRegistry.cs @@ -18,12 +18,26 @@ public interface IScheduledJobRuntimeRegistry /// when the cycle was started, when a cycle was already running. bool TryStartCycle(ScheduledJobId scheduledJobId, CancellationTokenSource cycleCancellationTokenSource); + /// + /// Gets a value indicating whether the execution cycle of the scheduled job identified by is currently running. + /// + /// The object representing the unique identifier of the scheduled job whose cycle is checked. + /// when a cycle is currently running, otherwise. + bool HasActiveCycle(ScheduledJobId scheduledJobId); + /// /// Stops the execution cycle of the scheduled job identified by . /// /// The object representing the unique identifier of the scheduled job whose cycle is stopped. void StopCycle(ScheduledJobId scheduledJobId); + /// + /// Ends the execution cycle of the scheduled job identified by , when it was started with . + /// + /// The object representing the unique identifier of the scheduled job whose cycle is ended. + /// The cancellation token source of the cycle that is ending. + void EndCycle(ScheduledJobId scheduledJobId, CancellationTokenSource cycleCancellationTokenSource); + /// /// Attempts to reserve the execution slot of the scheduled job identified by . /// diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobRuntimeRegistry.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobRuntimeRegistry.cs index 92230d12..5f2b5eeb 100644 --- a/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobRuntimeRegistry.cs +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobRuntimeRegistry.cs @@ -16,10 +16,28 @@ public sealed class ScheduledJobRuntimeRegistry : IScheduledJobRuntimeRegistry /// private sealed class ScheduledJobRuntimeState { + /// + /// Object used to synchronize the access to the runtime state of the scheduled job. + /// + public readonly object SyncRoot = new(); + + /// + /// Gets or sets the cancellation token source of the running execution cycle, or when no cycle is running. + /// public CancellationTokenSource? CycleCancellationTokenSource; + + /// + /// Gets the slot that guards a scheduled job against overlapping executions. + /// public readonly SemaphoreSlim RunSlot = new(1, 1); } + // One runtime state instance exists per scheduled job, and it is shared by every thread that works on that job: the + // cycle worker of the job, the request handlers that stop or remove the job, and the one time (fired) executions. The + // ConcurrentDictionary only makes the lookup of the state instance itself thread safe; the fields of the instance are + // still plain mutable fields, so every read or write of them is guarded by the per-state lock. The lock is only ever + // held for the few instructions that mutate or read the state, never while a cancellation callback runs, and the lock + // is reentrant for the thread that owns it, which keeps the registry free of deadlocks. private readonly ConcurrentDictionary _runtimeStates = []; /// @@ -31,10 +49,31 @@ public sealed class ScheduledJobRuntimeRegistry : IScheduledJobRuntimeRegistry public bool TryStartCycle(ScheduledJobId scheduledJobId, CancellationTokenSource cycleCancellationTokenSource) { ScheduledJobRuntimeState state = _runtimeStates.GetOrAdd(scheduledJobId, static _ => new ScheduledJobRuntimeState()); - if (state.CycleCancellationTokenSource is not null) + lock (state.SyncRoot) + { + // The check and the assignment must be one atomic step: without the lock, two concurrent starts of the same job could both observe that + // no cycle is running and both store their own cancellation token source, so a job would end up with two live cycles at once. + // The lock serializes the starts, so exactly one wins. + if (state.CycleCancellationTokenSource is not null) + return false; + state.CycleCancellationTokenSource = cycleCancellationTokenSource; + return true; + } + } + + /// + /// Gets a value indicating whether the execution cycle of the scheduled job identified by is currently running. + /// + /// The object representing the unique identifier of the scheduled job whose cycle is checked. + /// when a cycle is currently running, otherwise. + public bool HasActiveCycle(ScheduledJobId scheduledJobId) + { + if (!_runtimeStates.TryGetValue(scheduledJobId, out ScheduledJobRuntimeState? state)) return false; - state.CycleCancellationTokenSource = cycleCancellationTokenSource; - return true; + // The read takes the same lock the writers use, so it never observes a partially updated state, and the lock also acts as the memory barrier + // that guarantees the read sees the latest value written by another thread. + lock (state.SyncRoot) + return state.CycleCancellationTokenSource is not null; } /// @@ -45,11 +84,43 @@ public sealed class ScheduledJobRuntimeRegistry : IScheduledJobRuntimeRegistry { if (!_runtimeStates.TryGetValue(scheduledJobId, out ScheduledJobRuntimeState? state)) return; - CancellationTokenSource? cycleCancellationTokenSource = state.CycleCancellationTokenSource; - state.CycleCancellationTokenSource = null; + CancellationTokenSource? cycleCancellationTokenSource; + lock (state.SyncRoot) + { + // The stored token source is read and cleared while the lock is held, so that a start that races with this stop either sees the cycle and loses, + // or sees no cycle and starts a fresh one whose token source is not the one cancelled here. + cycleCancellationTokenSource = state.CycleCancellationTokenSource; + state.CycleCancellationTokenSource = null; + } + // Cancelling a token source synchronously invokes every callback registered on its token, and those callbacks can reach back into this registry + // (for example the cycle worker that unwinds and ends its own cycle). The lock is therefore released before the cancellation runs, + // so no callback ever executes while the lock is held, and the lock is never held longer than the few instructions that mutate the state. cycleCancellationTokenSource?.Cancel(); } + /// + /// Ends the execution cycle of the scheduled job identified by , when it was started with . + /// + /// The object representing the unique identifier of the scheduled job whose cycle is ended. + /// The cancellation token source of the cycle that is ending. + /// + /// The cycle worker calls this method when its cycle finishes, so that a cycle that was replaced by a newer one + /// after being stopped can never cancel the cycle that replaced it. + /// + public void EndCycle(ScheduledJobId scheduledJobId, CancellationTokenSource cycleCancellationTokenSource) + { + if (_runtimeStates.TryGetValue(scheduledJobId, out ScheduledJobRuntimeState? state)) + lock (state.SyncRoot) + // The identity check matters for the stop-then-start race: when a worker is stopped and a newer cycle is started before the old worker reaches + // its cleanup, the stored token source already belongs to the new cycle. The old worker must only clear the field when it still owns it, + // so it can never cancel the cycle that replaced it. + if (ReferenceEquals(state.CycleCancellationTokenSource, cycleCancellationTokenSource)) + state.CycleCancellationTokenSource = null; + // Cancelling the worker's own token source is always safe and idempotent, and runs outside the lock for the same reason as in StopCycle: + // the cancellation callbacks must not execute while the lock is held. + cycleCancellationTokenSource.Cancel(); + } + /// /// Attempts to reserve the execution slot of the scheduled job identified by . /// @@ -58,7 +129,10 @@ public sealed class ScheduledJobRuntimeRegistry : IScheduledJobRuntimeRegistry public bool TryAcquireRunSlot(ScheduledJobId scheduledJobId) { ScheduledJobRuntimeState state = _runtimeStates.GetOrAdd(scheduledJobId, static _ => new ScheduledJobRuntimeState()); - return state.RunSlot.Wait(0); + lock (state.SyncRoot) + // The slot is acquired under the same lock that guards the rest of the state, so the acquire is serialized + // with the cycle start and end transitions of the job; Wait(0) never blocks, so the lock is held only for a single non blocking instruction. + return state.RunSlot.Wait(0); } /// @@ -67,7 +141,12 @@ public sealed class ScheduledJobRuntimeRegistry : IScheduledJobRuntimeRegistry /// The object representing the unique identifier of the scheduled job whose execution slot is released. public void ReleaseRunSlot(ScheduledJobId scheduledJobId) { - if (_runtimeStates.TryGetValue(scheduledJobId, out ScheduledJobRuntimeState? state)) - state.RunSlot.Release(); + if (!_runtimeStates.TryGetValue(scheduledJobId, out ScheduledJobRuntimeState? state)) + return; + lock (state.SyncRoot) + // The semaphore is only released when a slot is actually taken, which is checked under the same lock as the acquire; + // without that check, releasing a slot that was never acquired, or releasing it twice, would throw a SemaphoreFullException. + if (state.RunSlot.CurrentCount is 0) + state.RunSlot.Release(); } } diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs index 8a4fe0c7..604c5213 100644 --- a/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs @@ -108,7 +108,20 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS return; } foreach (ScheduledJobEntity scheduledJob in getScheduledJobsResult.Value) - RunCycleWorkerAsync(ScheduledJobId.Create(scheduledJob.Id), runImmediately: false, cancellationToken).FireAndForgetSafeAsync(); + { + ScheduledJobId scheduledJobId = ScheduledJobId.Create(scheduledJob.Id); + // A scheduled job that was running when the application shut down had its execution interrupted, so its open + // execution history row is closed and its status is reset before its cycle is resumed. + if (scheduledJob.Status == ScheduledJobStatus.Running) + { + ScheduledJobStatus reconciledStatus = await ReconcileInterruptedRunAsync(scheduledJobId, cancellationToken).ConfigureAwait(false); + if (reconciledStatus != ScheduledJobStatus.Active) + continue; + } + // A once at startup scheduled job fires immediately when its cycle is resumed at startup; the other scheduled jobs wait for their next scheduled execution. + bool runImmediately = scheduledJob.ScheduleType == ScheduleType.OnceAtStartup; + RunCycleWorkerAsync(scheduledJobId, runImmediately, cancellationToken).FireAndForgetSafeAsync(); + } } /// @@ -119,47 +132,69 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS /// Cancellation token that can be used to stop the execution. private async Task RunCycleWorkerAsync(ScheduledJobId scheduledJobId, bool runImmediately, CancellationToken stoppingToken) { - CancellationTokenSource cycleCancellationTokenSource = new(); + // Each cycle owns its own cancellation token source: it is the handle the runtime registry stores, so stopping one + // scheduled job cancels exactly this cycle and no other job's cycle, even though the cycle worker itself runs "fire and forget" on another thread. + using CancellationTokenSource cycleCancellationTokenSource = new(); + // A scheduled job has at most one live cycle, and starts are "fire and forget", so when the registry already holds a + // cycle for the job, there is nothing for this worker to do and the existing cycle keeps ticking. if (!_runtimeRegistry.TryStartCycle(scheduledJobId, cycleCancellationTokenSource)) - { - cycleCancellationTokenSource.Dispose(); return; - } try { - CancellationToken cycleToken = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken, cycleCancellationTokenSource.Token).Token; + // The cycle token is cancelled when the application shuts down (through the host stopping token) or when this cycle is stopped + // (through its own token source), so a single token lets every await of the cycle observe both stop paths. + using CancellationTokenSource linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken, cycleCancellationTokenSource.Token); + CancellationToken cycleToken = linkedCancellationTokenSource.Token; + // An immediate run is executed as a cycle run, so it completes the scheduled job back to its active state and is + // recorded as part of the cycle; this is the path taken by an admin start, by the resume at startup and by the seed of the default jobs. if (runImmediately) await RunScheduledJobAsync(scheduledJobId, isCycleRun: true, cycleToken).ConfigureAwait(false); + // The schedule is read from the storage medium for every cycle, so the delay until the next run is always + // computed from the persisted schedule; when the scheduled job can no longer be read, the cycle simply ends. Schedule? schedule = await GetScheduleAsync(scheduledJobId, cycleToken).ConfigureAwait(false); if (schedule is null) return; + // A once at startup schedule fires its task exactly once when its cycle starts, at the application startup; the cycle + // then ends, and the scheduled job stays active, so its cycle is started again at the next application startup. + if (schedule.ScheduleType == ScheduleType.OnceAtStartup) + return; - while (true) + TimeSpan delay = await CalculateDelayAsync(schedule).ConfigureAwait(false); + // The periodic timer owns the cadence of the cycle: an interval schedule ticks every interval, and a daily + // schedule ticks after the delay until the next daily hour and minute. + using PeriodicTimer timer = new(delay); + // Each iteration waits for the next tick, runs the task and loops; a cancelled token or a disposed timer makes WaitForNextTickAsync exit, + // which ends the cycle through the finally block below. + while (await timer.WaitForNextTickAsync(cycleToken).ConfigureAwait(false)) { - 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); - } + if (cycleToken.IsCancellationRequested) + return; + // The run is awaited inside the tick and the periodic timer does not queue missed ticks, so a task that + // outlasts its interval drops the missed ticks instead of piling them up; the run slot acquired inside + // RunScheduledJobAsync is the second guard against overlapping executions. + await RunScheduledJobAsync(scheduledJobId, isCycleRun: true, cycleToken).ConfigureAwait(false); + // A daily schedule needs its delay recalculated after every run from the current time, so the next run + // happens at the next day's hour and minute, also across daylight saving time changes. + if (schedule.ScheduleType == ScheduleType.DailyAtHourAndMinute) + timer.Period = await CalculateDelayAsync(schedule).ConfigureAwait(false); } } - catch (OperationCanceledException) { } + catch (OperationCanceledException) + { + // A cancelled cycle is the normal way the loop ends when the cycle is stopped or the application shuts down, so it is not an error and must not be logged as one. + } catch (Exception exception) { + // Failures of a single run are handled inside RunScheduledJobAsync, so an exception reaching this point is unexpected and ends the cycle. _logger.LogError(exception, "The execution cycle of the scheduled job '{ScheduledJobId}' failed.", scheduledJobId.Value); } finally { - _runtimeRegistry.StopCycle(scheduledJobId); - cycleCancellationTokenSource.Dispose(); + // The registry is always told that the cycle ended, because every exit path passes through here, including the + // early returns above; EndCycle cancels and deregisters the cycle, and the outer using disposes the token source. + _runtimeRegistry.EndCycle(scheduledJobId, cycleCancellationTokenSource); } } @@ -196,6 +231,15 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS { await ExecuteScheduledJobRunAsync(scheduledJobId, isCycleRun, cancellationToken).ConfigureAwait(false); } + catch (OperationCanceledException) + { + // An execution that was cancelled is a normal outcome when the cycle of the scheduled job is stopped or the application shuts down. + } + catch (Exception exception) + { + _logger.LogError(exception, "The execution of the scheduled job '{ScheduledJobId}' failed unexpectedly.", scheduledJobId.Value); + await ReconcileInterruptedRunAsync(scheduledJobId, CancellationToken.None).ConfigureAwait(false); + } finally { _runtimeRegistry.ReleaseRunSlot(scheduledJobId); @@ -226,27 +270,136 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS Result scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity(); if (scheduledJobDomainResult.IsFailure) return; - Result startExecutionResult = scheduledJobDomainResult.Value.MarkExecutionStarted(isCycleRun); + ScheduledJob scheduledJob = scheduledJobDomainResult.Value; + Result startExecutionResult = scheduledJob.MarkExecutionStarted(isCycleRun); if (startExecutionResult.IsFailure) return; - foreach (IDomainEvent domainEvent in scheduledJobDomainResult.Value.GetDomainEvents()) + foreach (IDomainEvent domainEvent in scheduledJob.GetDomainEvents()) await domainEventPublisher.PublishAsync(domainEvent, cancellationToken).ConfigureAwait(false); - // Execute the payload of the task of the scheduled job. - IScheduledTaskExecutorFactory taskExecutorFactory = services.GetRequiredService(); - IScheduledTaskExecutor taskExecutor = taskExecutorFactory.CreateExecutor(scheduledJobDomainResult.Value.TaskType); - Result executePayloadResult = await taskExecutor.ExecutePayloadAsync(scheduledJobDomainResult.Value, cancellationToken).ConfigureAwait(false); - if (executePayloadResult.IsFailure) - _logger.LogWarning("The task of the scheduled job '{ScheduledJobName}' failed: {Error}", scheduledJobDomainResult.Value.Name, executePayloadResult.FirstError.Description); - - // Mark the task as completed. The same domain entity is reused, because it alone still tracks the run id of the - // current execution, which is required to raise the completion domain event; a fresh copy reloaded from the - // storage medium would no longer know which execution to complete. - Result completeExecutionResult = scheduledJobDomainResult.Value.MarkExecutionCompleted(isCycleRun); - if (completeExecutionResult.IsFailure) + // Execute the payload of the task of the scheduled job; a payload failure is a normal outcome that is logged, while a + // thrown exception is logged as well, so that the run is still completed instead of leaving the scheduled job running. + try + { + if (cancellationToken.IsCancellationRequested) + return; + IScheduledTaskExecutorFactory taskExecutorFactory = services.GetRequiredService(); + IScheduledTaskExecutor taskExecutor = taskExecutorFactory.CreateExecutor(scheduledJob.TaskType); + Result executePayloadResult = await taskExecutor.ExecutePayloadAsync(scheduledJob, cancellationToken).ConfigureAwait(false); + if (executePayloadResult.IsFailure) + _logger.LogWarning("The task of the scheduled job '{ScheduledJobName}' failed: {Error}", scheduledJob.Name, executePayloadResult.FirstError.Description); + } + catch (OperationCanceledException) + { return; - foreach (IDomainEvent domainEvent in scheduledJobDomainResult.Value.GetDomainEvents()) - await domainEventPublisher.PublishAsync(domainEvent, cancellationToken).ConfigureAwait(false); + } + catch (Exception exception) + { + _logger.LogError(exception, "The task of the scheduled job '{ScheduledJobName}' threw an exception.", scheduledJob.Name); + } + + if (cancellationToken.IsCancellationRequested) + return; + + await CompleteExecutionAsync(scheduledJob, unitOfWork, domainEventPublisher, isCycleRun, cancellationToken).ConfigureAwait(false); + } + + /// + /// Completes the execution of the task of , when the scheduled job is still running. + /// + /// The scheduled job whose task execution is completed. + /// The unit of work of the current run, whose tracked entities are reused by the completion handlers. + /// The publisher used to publish the completion domain events. + /// Whether the execution was triggered by the execution cycle of the scheduled job, or it is a one time execution. + /// Cancellation token that can be used to stop the execution. + private async Task CompleteExecutionAsync(ScheduledJob scheduledJob, IUnitOfWork unitOfWork, IDomainEventPublisher domainEventPublisher, bool isCycleRun, CancellationToken cancellationToken) + { + try + { + // Reload the scheduled job from the storage medium without tracking, because a stop or a removal that happened while the + // task was executing already reset its state, and completing the execution here would silently undo that change. + Result getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdWithoutTrackingAsync(scheduledJob.Id.Value, cancellationToken).ConfigureAwait(false); + if (getScheduledJobResult.IsFailure || getScheduledJobResult.Value is null) + return; + if (getScheduledJobResult.Value.Status != ScheduledJobStatus.Running) + return; + + // A one time execution returns the scheduled job to its active state when its execution cycle is still running, so the + // running cycle keeps scheduling executions and the job can still be stopped; the same applies to a once at startup job, + // whose active state is what makes it fire again at the next application startup. + bool completesTheCycleRun = isCycleRun || _runtimeRegistry.HasActiveCycle(scheduledJob.Id) || scheduledJob.Schedule.ScheduleType == ScheduleType.OnceAtStartup; + Result completeExecutionResult = scheduledJob.MarkExecutionCompleted(completesTheCycleRun); + if (completeExecutionResult.IsFailure) + return; + foreach (IDomainEvent domainEvent in scheduledJob.GetDomainEvents()) + await domainEventPublisher.PublishAsync(domainEvent, cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) { } + catch (Exception exception) + { + // The completion failed after the execution was persisted as running, so the interrupted run is reconciled directly. + _logger.LogError(exception, "Failed to complete the execution of the scheduled job '{ScheduledJobId}'.", scheduledJob.Id.Value); + await ReconcileInterruptedRunAsync(scheduledJob.Id, CancellationToken.None).ConfigureAwait(false); + } + } + + /// + /// Reconciles the scheduled job identified by when its execution was interrupted: its open + /// execution history row is closed, and the scheduled job is returned to a status from which it can run again. + /// + /// The object representing the unique identifier of the scheduled job whose interrupted execution is reconciled. + /// Cancellation token that can be used to stop the execution. + /// The status the scheduled job was reconciled to, or its current status when no reconciliation was needed. + private async Task ReconcileInterruptedRunAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken) + { + try + { + await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = scope.ServiceProvider.GetRequiredService(); + Result getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken).ConfigureAwait(false); + if (getScheduledJobResult.IsFailure || getScheduledJobResult.Value is null) + return ScheduledJobStatus.Added; + ScheduledJobEntity scheduledJob = getScheduledJobResult.Value; + // A scheduled job that is not running needs no reconciliation. + if (scheduledJob.Status != ScheduledJobStatus.Running) + return scheduledJob.Status; + + // An interrupted execution returns the scheduled job to its active state when its execution cycle was active + // when the execution started, so its cycle is resumed at startup; an interrupted execution of a job whose cycle + // was not active returns it to its added state. The cycle active state is read from the execution history row + // and not from the IsCycleRun flag, so that a manually fired one time execution on an active job keeps its + // manual audit trail while its cycle is still resumed. + Result getOpenExecutionResult = await unitOfWork.ScheduledJobExecutionRepository + .GetOpenByScheduledJobIdAsync(scheduledJob.Id, cancellationToken).ConfigureAwait(false); + if (getOpenExecutionResult.IsFailure) + return ScheduledJobStatus.Added; + ScheduledJobExecutionEntity? openExecution = getOpenExecutionResult.Value; + ScheduledJobStatus reconciledStatus = (openExecution?.WasCycleActive ?? true) ? ScheduledJobStatus.Active : ScheduledJobStatus.Added; + + Result updateScheduledJobResult = await unitOfWork.ScheduledJobRepository.UpdateAsync( + CreateUpdatedScheduledJob(scheduledJob, reconciledStatus, scheduledJob.LastStartedOnUtc, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + if (updateScheduledJobResult.IsFailure) + return ScheduledJobStatus.Added; + if (openExecution is not null) + { + Result updateExecutionResult = await unitOfWork.ScheduledJobExecutionRepository.UpdateAsync( + CreateClosedExecution(openExecution, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + if (updateExecutionResult.IsFailure) + return ScheduledJobStatus.Added; + } + await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + _logger.LogInformation("The interrupted execution of the scheduled job '{ScheduledJobName}' was closed.", scheduledJob.Name); + return reconciledStatus; + } + catch (OperationCanceledException) + { + return ScheduledJobStatus.Added; + } + catch (Exception exception) + { + _logger.LogWarning(exception, "Failed to reconcile the interrupted execution of the scheduled job '{ScheduledJobId}'.", scheduledJobId.Value); + return ScheduledJobStatus.Added; + } } /// @@ -278,4 +431,58 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS // 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); } + + /// + /// Creates a copy of with the provided status and timestamps. + /// + /// The scheduled job to copy. + /// The status of the copy. + /// The last start time of the copy. + /// The last completion time of the copy. + /// The copy of the scheduled job. + private static ScheduledJobEntity CreateUpdatedScheduledJob(ScheduledJobEntity scheduledJob, ScheduledJobStatus status, DateTime? lastStartedOnUtc, DateTime? lastCompletedOnUtc) + { + return new ScheduledJobEntity + { + Id = scheduledJob.Id, + Name = scheduledJob.Name, + TaskType = scheduledJob.TaskType, + ScheduleType = scheduledJob.ScheduleType, + IntervalMinutes = scheduledJob.IntervalMinutes, + Hour = scheduledJob.Hour, + Minute = scheduledJob.Minute, + Status = status, + OwnerUserId = scheduledJob.OwnerUserId, + LastStartedOnUtc = lastStartedOnUtc, + LastCompletedOnUtc = lastCompletedOnUtc, + CreatedOnUtc = scheduledJob.CreatedOnUtc, + CreatedBy = scheduledJob.CreatedBy, + UpdatedOnUtc = scheduledJob.UpdatedOnUtc, + UpdatedBy = scheduledJob.UpdatedBy + }; + } + + /// + /// Creates a copy of with the provided completion time. + /// + /// The execution to copy. + /// The completion time of the copy. + /// The copy of the execution. + private static ScheduledJobExecutionEntity CreateClosedExecution(ScheduledJobExecutionEntity execution, DateTime? completedOnUtc) + { + return new ScheduledJobExecutionEntity + { + Id = execution.Id, + ScheduledJobId = execution.ScheduledJobId, + TaskType = execution.TaskType, + IsCycleRun = execution.IsCycleRun, + WasCycleActive = execution.WasCycleActive, + StartedOnUtc = execution.StartedOnUtc, + CompletedOnUtc = completedOnUtc, + CreatedOnUtc = execution.CreatedOnUtc, + CreatedBy = execution.CreatedBy, + UpdatedOnUtc = execution.UpdatedOnUtc, + UpdatedBy = execution.UpdatedBy + }; + } } diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledTaskExecutorFactory.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledTaskExecutorFactory.cs index fb00215e..ce493bfb 100644 --- a/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledTaskExecutorFactory.cs +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledTaskExecutorFactory.cs @@ -34,6 +34,8 @@ public class ScheduledTaskExecutorFactory : IScheduledTaskExecutorFactory { ScheduledTaskType.ScanMediaLibraries => _serviceProvider.GetRequiredService(), ScheduledTaskType.CleanTemporaryFiles => _serviceProvider.GetRequiredService(), + ScheduledTaskType.RepairThemes => _serviceProvider.GetRequiredService(), + ScheduledTaskType.CleanScheduledJobExecutionHistory => _serviceProvider.GetRequiredService(), _ => throw new ArgumentException($"Unsupported task type: {taskType}", nameof(taskType)) }; } diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/CleanScheduledJobExecutionHistoryTaskExecutor.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/CleanScheduledJobExecutionHistoryTaskExecutor.cs new file mode 100644 index 00000000..b0aac116 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/CleanScheduledJobExecutionHistoryTaskExecutor.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Microsoft.Extensions.Logging; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors; + +/// +/// Task executor that cleans the execution history of the scheduled jobs, keeping only the executions of the past month. +/// +public class CleanScheduledJobExecutionHistoryTaskExecutor : IScheduledTaskExecutor +{ + private readonly IDateTimeProvider _dateTimeProvider; + private readonly IUnitOfWork _unitOfWork; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for time related concerns. + /// Injected service for logging. + /// Injected unit of work for interacting with the data access layer repositories. + public CleanScheduledJobExecutionHistoryTaskExecutor(IDateTimeProvider dateTimeProvider, ILogger logger, IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + _dateTimeProvider = dateTimeProvider; + _logger = logger; + } + + /// + /// Removes the executions of the tasks of the scheduled jobs that are older than a month, keeping only the recent executions for audit. + /// + /// 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) + { + DateTime cutoffUtc = _dateTimeProvider.UtcNow.AddMonths(-1); + Result deleteResult = await _unitOfWork.ScheduledJobExecutionRepository.DeleteOlderThanAsync(cutoffUtc, cancellationToken).ConfigureAwait(false); + if (deleteResult.IsFailure) + return deleteResult.Errors; + + _logger.LogInformation("Cleaned the execution history of the scheduled jobs on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name); + return Result.Success; + } +} diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/RepairThemesTaskExecutor.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/RepairThemesTaskExecutor.cs new file mode 100644 index 00000000..b9bbf77e --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/RepairThemesTaskExecutor.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Themes; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate; +using Lumina.Infrastructure.Core.Themes; +using Microsoft.Extensions.Logging; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors; + +/// +/// Task executor that repairs the installed themes whose files are missing. +/// +public class RepairThemesTaskExecutor : IScheduledTaskExecutor +{ + private readonly IThemeService _themeService; + private readonly IUnitOfWork _unitOfWork; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for the server-side storage and serving of theme packs. + /// Injected service for logging. + /// Injected unit of work for interacting with the data access layer repositories. + public RepairThemesTaskExecutor(IThemeService themeService, ILogger logger, IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + _themeService = themeService; + _logger = logger; + } + + /// + /// Repairs the installed themes whose files are missing, reinstalling the files of the bundled themes from their shipped archives. + /// + /// 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) + { + // Repairs are best effort, so a failure to repair one theme is logged inside the synchronizer and the remaining themes are still repaired. + try + { + await ThemeSynchronizer.SynchronizeAsync(_themeService, _unitOfWork, _logger, cancellationToken).ConfigureAwait(false); + _logger.LogInformation("Repaired the themes on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name); + return Result.Success; + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception exception) + { + _logger.LogWarning(exception, "The themes could not be repaired on behalf of the scheduled job '{ScheduledJobName}'.", scheduledJob.Name); + return Error.Failure(description: nameof(RepairThemesTaskExecutor)); + } + } +} diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Notifications/ScheduledJobNotifier.cs b/src/Lumina.Infrastructure/Core/Scheduling/Notifications/ScheduledJobNotifier.cs index 6ffa1ee5..94885e5b 100644 --- a/src/Lumina.Infrastructure/Core/Scheduling/Notifications/ScheduledJobNotifier.cs +++ b/src/Lumina.Infrastructure/Core/Scheduling/Notifications/ScheduledJobNotifier.cs @@ -32,7 +32,7 @@ public sealed class ScheduledJobNotifier : IScheduledJobNotifier /// Cancellation token that can be used to stop the execution. public async Task SendScheduledJobsAsync(IReadOnlyList scheduledJobs, CancellationToken cancellationToken) { - await _hubContext.Clients.All.ReceiveScheduledJobsAsync(scheduledJobs).ConfigureAwait(false); + await _hubContext.Clients.Group(ScheduledJobsHub.ADMINISTRATORS_GROUP).ReceiveScheduledJobsAsync(scheduledJobs).ConfigureAwait(false); } /// @@ -42,7 +42,7 @@ public sealed class ScheduledJobNotifier : IScheduledJobNotifier /// Cancellation token that can be used to stop the execution. public async Task SendScheduledJobExecutionStartedAsync(ScheduledJobExecutionResponse execution, CancellationToken cancellationToken) { - await _hubContext.Clients.All.ScheduledJobExecutionStartedAsync(execution).ConfigureAwait(false); + await _hubContext.Clients.Group(ScheduledJobsHub.ADMINISTRATORS_GROUP).ScheduledJobExecutionStartedAsync(execution).ConfigureAwait(false); } /// @@ -52,6 +52,6 @@ public sealed class ScheduledJobNotifier : IScheduledJobNotifier /// Cancellation token that can be used to stop the execution. public async Task SendScheduledJobExecutionCompletedAsync(ScheduledJobExecutionResponse execution, CancellationToken cancellationToken) { - await _hubContext.Clients.All.ScheduledJobExecutionCompletedAsync(execution).ConfigureAwait(false); + await _hubContext.Clients.Group(ScheduledJobsHub.ADMINISTRATORS_GROUP).ScheduledJobExecutionCompletedAsync(execution).ConfigureAwait(false); } } diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Notifications/ScheduledJobsHub.cs b/src/Lumina.Infrastructure/Core/Scheduling/Notifications/ScheduledJobsHub.cs index 4e9958ef..5d498ecb 100644 --- a/src/Lumina.Infrastructure/Core/Scheduling/Notifications/ScheduledJobsHub.cs +++ b/src/Lumina.Infrastructure/Core/Scheduling/Notifications/ScheduledJobsHub.cs @@ -17,6 +17,11 @@ namespace Lumina.Infrastructure.Core.Scheduling.Notifications; [Authorize] public class ScheduledJobsHub : Hub { + /// + /// Name of the group that holds the connections of the verified administrator clients. + /// + public const string ADMINISTRATORS_GROUP = "Administrators"; + private readonly IServiceScopeFactory _serviceScopeFactory; /// @@ -40,6 +45,9 @@ public class ScheduledJobsHub : Hub Context.Abort(); return; } + // The connection is added to the administrator group only after the role check succeeded, so the notifications, which are + // broadcast to that group, can never reach a client whose connection was not verified to belong to an administrator. + await Groups.AddToGroupAsync(Context.ConnectionId, ADMINISTRATORS_GROUP).ConfigureAwait(false); await base.OnConnectedAsync().ConfigureAwait(false); } diff --git a/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs b/src/Lumina.Infrastructure/Core/Themes/ThemeSynchronizer.cs similarity index 51% rename from src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs rename to src/Lumina.Infrastructure/Core/Themes/ThemeSynchronizer.cs index 272832ec..7a0e94b4 100644 --- a/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs +++ b/src/Lumina.Infrastructure/Core/Themes/ThemeSynchronizer.cs @@ -5,8 +5,6 @@ using Lumina.Application.Common.Infrastructure.Models.DTO.Themes; using Lumina.Application.Common.Infrastructure.Themes; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Themes; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -19,76 +17,58 @@ using System.Threading.Tasks; namespace Lumina.Infrastructure.Core.Themes; /// -/// Background job that installs the bundled themes into the storage medium and the theme storage at startup. +/// Utility class that keeps the installed themes in sync with the bundled theme archives. /// -internal sealed class ThemeDetectionSyncJob : BackgroundService +internal static class ThemeSynchronizer { - private readonly IServiceScopeFactory _serviceScopeFactory; - private readonly IThemeService _themeService; - private readonly ILogger _logger; - /// - /// Initializes a new instance of the class. + /// Installs the bundled themes into the storage medium and the theme storage, and repairs the installed themes whose files are missing. /// - /// Injected factory for creating scopes in which services are requested. /// Injected service for the server-side storage and serving of theme packs. + /// The unit of work for interacting with the theme repository. /// Injected logger used for logging. - public ThemeDetectionSyncJob(IServiceScopeFactory serviceScopeFactory, IThemeService themeService, ILogger logger) - { - _serviceScopeFactory = serviceScopeFactory; - _themeService = themeService; - _logger = logger; - } - - /// - /// Method called when the background service starts. - /// /// Cancellation token that can be used to stop the execution. - protected override async Task ExecuteAsync(CancellationToken cancellationToken) + internal static async Task SynchronizeAsync(IThemeService themeService, IUnitOfWork unitOfWork, ILogger logger, CancellationToken cancellationToken) { - await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); - IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetRequiredService(); - - Result> getThemesResult = await unitOfWork.ThemeRepository.GetAllAsync(cancellationToken); + Result> getThemesResult = await unitOfWork.ThemeRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); if (getThemesResult.IsFailure) { - _logger.LogWarning("Failed to read the installed themes: {Error}", getThemesResult.FirstError.Description); + logger.LogWarning("Failed to read the installed themes: {Error}", getThemesResult.FirstError.Description); return; } - // themes that were soft deleted by the user must not be reinstalled automatically + // Themes that were soft deleted by the user must not be reinstalled automatically. List themes = [.. getThemesResult.Value]; - foreach (string archivePath in _themeService.GetBundledThemeArchivePaths()) + foreach (string archivePath in themeService.GetBundledThemeArchivePaths()) { - Result manifestResult = await _themeService.ReadManifestFromArchiveAsync(archivePath, cancellationToken); + Result manifestResult = await themeService.ReadManifestFromArchiveAsync(archivePath, cancellationToken).ConfigureAwait(false); if (manifestResult.IsFailure) { - _logger.LogWarning("Skipping bundled theme archive {ArchivePath}: {Error}", archivePath, manifestResult.FirstError.Description); + logger.LogWarning("Skipping bundled theme archive {ArchivePath}: {Error}", archivePath, manifestResult.FirstError.Description); continue; } ThemeEntity? existingTheme = themes.Where(theme => theme.ThemeId == manifestResult.Value.Id).FirstOrDefault(); - // a theme that was soft deleted by the user must not be reinstalled automatically; an installed bundled theme - // whose files are present is already in sync, so only a bundled theme whose files went missing gets its files reinstalled - if (existingTheme is not null && (existingTheme.IsDeleted || existingTheme.InstallSource != ThemeInstallSource.Bundled || _themeService.HasThemePack(existingTheme.ThemeId))) + // A theme that was soft deleted by the user must not be reinstalled automatically; an installed bundled theme + // whose files are present is already in sync, so only a bundled theme whose files went missing gets its files reinstalled. + if (existingTheme is not null && (existingTheme.IsDeleted || existingTheme.InstallSource != ThemeInstallSource.Bundled || themeService.HasThemePack(existingTheme.ThemeId))) continue; - // installing a bundled theme at startup is best effort: a file system failure here must never crash the host, - // because the default BackgroundServiceExceptionBehavior (StopHost) shuts down the whole application and - // disposes its service provider, making every later request fail + // Installing a bundled theme at startup is best effort: a file system failure here must never crash the host, because the default + // BackgroundServiceExceptionBehavior (StopHost) shuts down the whole application and disposes its service provider, making every later request fail. try { await using FileStream archive = File.OpenRead(archivePath); - Result installResult = await _themeService.InstallAsync(archive, cancellationToken); + Result installResult = await themeService.InstallAsync(archive, cancellationToken).ConfigureAwait(false); if (installResult.IsFailure) { - _logger.LogWarning("Failed to install bundled theme '{ThemeId}': {Error}", manifestResult.Value.Id, installResult.FirstError.Description); + logger.LogWarning("Failed to install bundled theme '{ThemeId}': {Error}", manifestResult.Value.Id, installResult.FirstError.Description); continue; } - // a known theme only gets its missing files reinstalled, so no new row is inserted + // A known theme only gets its missing files reinstalled, so no new row is inserted. if (existingTheme is not null) continue; @@ -108,40 +88,41 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService UpdatedBy = default }; - Result insertResult = await unitOfWork.ThemeRepository.InsertAsync(themeEntity, cancellationToken); + Result insertResult = await unitOfWork.ThemeRepository.InsertAsync(themeEntity, cancellationToken).ConfigureAwait(false); if (insertResult.IsFailure) - _logger.LogWarning("Failed to persist the detection of theme '{ThemeId}': {Error}", manifestResult.Value.Id, insertResult.FirstError.Description); + logger.LogWarning("Failed to persist the detection of theme '{ThemeId}': {Error}", manifestResult.Value.Id, insertResult.FirstError.Description); else themes.Add(themeEntity); } catch (IOException exception) { - _logger.LogWarning(exception, "Failed to install bundled theme '{ThemeId}': the theme files could not be written.", manifestResult.Value.Id); + logger.LogWarning(exception, "Failed to install bundled theme '{ThemeId}': the theme files could not be written.", manifestResult.Value.Id); } catch (UnauthorizedAccessException exception) { - _logger.LogWarning(exception, "Failed to install bundled theme '{ThemeId}': access to the theme files was denied.", manifestResult.Value.Id); + logger.LogWarning(exception, "Failed to install bundled theme '{ThemeId}': access to the theme files was denied.", manifestResult.Value.Id); } } - await CleanUpMissingThemePacksAsync(unitOfWork, themes, cancellationToken); - await EnsureCurrentThemeExistsAsync(unitOfWork, themes, cancellationToken); + await CleanUpMissingThemePacksAsync(themeService, unitOfWork, themes, logger, cancellationToken).ConfigureAwait(false); + await EnsureCurrentThemeExistsAsync(themeService, unitOfWork, themes, cancellationToken).ConfigureAwait(false); - await unitOfWork.SaveChangesAsync(cancellationToken); + await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); } /// /// Restores the files of the damaged bundled themes that were not deleted by the user, and removes the damaged themes whose files could not be recovered. /// + /// Injected service for the server-side storage and serving of theme packs. /// The unit of work for interacting with the theme repository. /// The installed themes read from the storage medium. + /// Injected logger used for logging. /// Cancellation token that can be used to stop the execution. - private async Task CleanUpMissingThemePacksAsync(IUnitOfWork unitOfWork, IReadOnlyList themes, CancellationToken cancellationToken) + private static async Task CleanUpMissingThemePacksAsync(IThemeService themeService, IUnitOfWork unitOfWork, IReadOnlyList themes, ILogger logger, CancellationToken cancellationToken) { - // a soft deleted theme was deleted intentionally from the admin interface, so it must never be restored - // automatically; only a theme that was not deleted, but whose files went missing, was corrupted or removed - // externally, and is the only case where the files are restored - IReadOnlyList brokenThemes = [.. themes.Where(theme => !theme.IsDeleted && !_themeService.HasThemePack(theme.ThemeId))]; + // A soft deleted theme was deleted intentionally from the admin interface, so it must never be restored automatically; + // only a theme that was not deleted, but whose files went missing, was corrupted or removed externally, and is the only case where the files are restored. + IReadOnlyList brokenThemes = [.. themes.Where(theme => !theme.IsDeleted && !themeService.HasThemePack(theme.ThemeId))]; if (brokenThemes.Count is 0) return; @@ -151,39 +132,39 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService { if (brokenTheme.InstallSource == ThemeInstallSource.Bundled) { - // the files of a bundled theme that was not deleted by the user are restored from its shipped archive - Result restoreResult = await _themeService.RestoreBundledThemeAsync(brokenTheme.ThemeId, cancellationToken); + // The files of a bundled theme that was not deleted by the user are restored from its shipped archive. + Result restoreResult = await themeService.RestoreBundledThemeAsync(brokenTheme.ThemeId, cancellationToken).ConfigureAwait(false); if (restoreResult.IsSuccess) continue; - _logger.LogWarning("Failed to restore the files of bundled theme '{ThemeId}': {Error}", brokenTheme.ThemeId, restoreResult.FirstError.Description); + logger.LogWarning("Failed to restore the files of bundled theme '{ThemeId}': {Error}", brokenTheme.ThemeId, restoreResult.FirstError.Description); - // at least one bundled theme must always remain available, so the application never ends up without any theme; - // the last remaining bundled theme is kept even when its files cannot be recovered + // At least one bundled theme must always remain available, so the application never ends up without any theme; + // the last remaining bundled theme is kept even when its files cannot be recovered. int availableBundledThemes = themes.Count(availableTheme => !availableTheme.IsDeleted && availableTheme.InstallSource == ThemeInstallSource.Bundled); if (availableBundledThemes <= 1) { - _logger.LogWarning("Bundled theme '{ThemeId}' is the last remaining bundled theme and its files could not be restored, so it is kept.", brokenTheme.ThemeId); + logger.LogWarning("Bundled theme '{ThemeId}' is the last remaining bundled theme and its files could not be restored, so it is kept.", brokenTheme.ThemeId); continue; } - // a bundled theme whose files could not be recovered is soft deleted, so it is not shown anymore, but can be restored later + // A bundled theme whose files could not be recovered is soft deleted, so it is not shown anymore, but can be restored later. brokenTheme.IsDeleted = true; brokenTheme.IsCurrent = null; brokenTheme.UpdatedOnUtc = DateTime.UtcNow; brokenTheme.UpdatedBy = default; - Result updateResult = await unitOfWork.ThemeRepository.UpdateAsync(brokenTheme, cancellationToken); + Result updateResult = await unitOfWork.ThemeRepository.UpdateAsync(brokenTheme, cancellationToken).ConfigureAwait(false); if (updateResult.IsFailure) - _logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, updateResult.FirstError.Description); + logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, updateResult.FirstError.Description); } else { - // a user theme has no shipped archive to restore from, so damage is permanent and the theme is removed entirely - _logger.LogWarning("The stored files of user theme '{ThemeId}' are missing, so the theme is deleted.", brokenTheme.ThemeId); + // A user theme has no shipped archive to restore from, so damage is permanent and the theme is removed entirely. + logger.LogWarning("The stored files of user theme '{ThemeId}' are missing, so the theme is deleted.", brokenTheme.ThemeId); brokenTheme.IsCurrent = null; - Result deleteResult = await unitOfWork.ThemeRepository.DeleteByIdAsync(brokenTheme.Id, cancellationToken); + Result deleteResult = await unitOfWork.ThemeRepository.DeleteByIdAsync(brokenTheme.Id, cancellationToken).ConfigureAwait(false); if (deleteResult.IsFailure) - _logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, deleteResult.FirstError.Description); + logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, deleteResult.FirstError.Description); } } catch (OperationCanceledException) @@ -192,9 +173,8 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService } catch (Exception exception) { - // repairing a broken theme is best effort: an unexpected failure on one theme must not crash the host, - // so it is logged and the remaining broken themes are still processed - _logger.LogWarning(exception, "Failed to repair the broken theme '{ThemeId}'.", brokenTheme.ThemeId); + // Repairing a broken theme is best effort: an unexpected failure on one theme must not crash the host, so it is logged and the remaining broken themes are still processed. + logger.LogWarning(exception, "Failed to repair the broken theme '{ThemeId}'.", brokenTheme.ThemeId); } } } @@ -202,20 +182,21 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService /// /// Activates the configured default theme when no theme is currently active, so the application always has an active theme. /// + /// Injected service for the server-side storage and serving of theme packs. /// The unit of work for interacting with the theme repository. /// The installed themes read from the storage medium. /// Cancellation token that can be used to stop the execution. - private async Task EnsureCurrentThemeExistsAsync(IUnitOfWork unitOfWork, IReadOnlyList themes, CancellationToken cancellationToken) + private static async Task EnsureCurrentThemeExistsAsync(IThemeService themeService, IUnitOfWork unitOfWork, IReadOnlyList themes, CancellationToken cancellationToken) { if (themes.Any(theme => !theme.IsDeleted && theme.IsCurrent == true)) return; - // a theme whose files are present is preferred, so the activated theme can render immediately; a bundled theme - // whose files could not be restored is kept as the fallback, so the application always has an active theme + // A theme whose files are present is preferred, so the activated theme can render immediately; a bundled theme + // whose files could not be restored is kept as the fallback, so the application always has an active theme. ThemeEntity? defaultTheme = themes .Where(theme => !theme.IsDeleted) - .OrderBy(theme => _themeService.HasThemePack(theme.ThemeId) ? 0 : 1) - .ThenBy(theme => string.Equals(theme.ThemeId, _themeService.DefaultThemeId, StringComparison.OrdinalIgnoreCase) ? 0 : 1) + .OrderBy(theme => themeService.HasThemePack(theme.ThemeId) ? 0 : 1) + .ThenBy(theme => string.Equals(theme.ThemeId, themeService.DefaultThemeId, StringComparison.OrdinalIgnoreCase) ? 0 : 1) .ThenBy(theme => theme.ThemeId, StringComparer.OrdinalIgnoreCase) .FirstOrDefault(); if (defaultTheme is null) @@ -224,6 +205,6 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService defaultTheme.IsCurrent = true; defaultTheme.UpdatedOnUtc = DateTime.UtcNow; defaultTheme.UpdatedBy = default; - await unitOfWork.ThemeRepository.UpdateAsync(defaultTheme, cancellationToken); + await unitOfWork.ThemeRepository.UpdateAsync(defaultTheme, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip b/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip index 53e3a86c..692ed829 100644 Binary files a/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip and b/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip differ diff --git a/src/Lumina.Presentation.Api/Core/Themes/Bundled/lumina-default.zip b/src/Lumina.Presentation.Api/Core/Themes/Bundled/lumina-default.zip index da702055..fa23d569 100644 Binary files a/src/Lumina.Presentation.Api/Core/Themes/Bundled/lumina-default.zip and b/src/Lumina.Presentation.Api/Core/Themes/Bundled/lumina-default.zip differ diff --git a/src/Lumina.Presentation.Web/Common/Enums/Scheduling/ScheduleType.cs b/src/Lumina.Presentation.Web/Common/Enums/Scheduling/ScheduleType.cs index b1832d92..409eff26 100644 --- a/src/Lumina.Presentation.Web/Common/Enums/Scheduling/ScheduleType.cs +++ b/src/Lumina.Presentation.Web/Common/Enums/Scheduling/ScheduleType.cs @@ -13,5 +13,10 @@ public enum ScheduleType /// /// The scheduled job repeats daily at a fixed hour and minute. /// - DailyAtHourAndMinute + DailyAtHourAndMinute, + + /// + /// The scheduled job fires its task once, every time the application starts. + /// + OnceAtStartup } diff --git a/src/Lumina.Presentation.Web/Common/Enums/Scheduling/ScheduledTaskType.cs b/src/Lumina.Presentation.Web/Common/Enums/Scheduling/ScheduledTaskType.cs index 23330b75..5f033276 100644 --- a/src/Lumina.Presentation.Web/Common/Enums/Scheduling/ScheduledTaskType.cs +++ b/src/Lumina.Presentation.Web/Common/Enums/Scheduling/ScheduledTaskType.cs @@ -13,5 +13,15 @@ public enum ScheduledTaskType /// /// The scheduled job cleans the temporary directory of the application. /// - CleanTemporaryFiles + CleanTemporaryFiles, + + /// + /// The scheduled job repairs the installed themes whose files are missing. + /// + RepairThemes, + + /// + /// The scheduled job cleans the execution history of the scheduled jobs, keeping only the recent executions. + /// + CleanScheduledJobExecutionHistory } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpoint.cs index c2c74146..628f529d 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/AddScheduledJob/AddScheduledJobEndpoint.cs @@ -6,7 +6,6 @@ using Lumina.Presentation.Web.Common.DTO.Scheduling; using Lumina.Presentation.Web.Common.Requests.Scheduling; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System.Threading; using System.Threading.Tasks; @@ -41,6 +40,7 @@ public class AddScheduledJobEndpoint : BaseEndpoint options.WithTags("Admin")); Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + EnableAntiforgery(); } /// diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpoint.cs index 134aab46..0688c4c9 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/FireScheduledJob/FireScheduledJobEndpoint.cs @@ -40,6 +40,7 @@ public class FireScheduledJobEndpoint : BaseEndpoint options.WithTags("Admin")); Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + EnableAntiforgery(); } /// diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpoint.cs index 6a3791ed..7ad9a8b1 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/RemoveScheduledJob/RemoveScheduledJobEndpoint.cs @@ -40,6 +40,7 @@ public class RemoveScheduledJobEndpoint : BaseEndpoint options.WithTags("Admin")); Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + EnableAntiforgery(); } /// diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpoint.cs index 3f757800..cf09450c 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/SchedulerIndexViewEndpoint.cs @@ -1,10 +1,20 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.Configuration; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Primitives; using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; using Lumina.Presentation.Web.Core.Endpoints.Common; +using Lumina.Presentation.Web.Core.Themes; +using Microsoft.AspNetCore.Antiforgery; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Localization; +using Microsoft.Extensions.Options; +using System; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #endregion @@ -16,6 +26,40 @@ namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler; /// public class SchedulerIndexViewEndpoint : BaseEndpoint { + // the resource base name deliberately excludes the "Core.Resources" segment: the localization factory re-roots it with the configured ResourcesPath + private const string VIEW_RESOURCE_BASE_NAME = "Lumina.Presentation.Web.Views.Admin.Scheduler"; + private const string VIEW_RESOURCE_LOCATION = "Lumina.Presentation.Web"; + // the page key mirrors the path of the Razor view under Core/Views, so that theme templates can override it at the page, section or default scope + private const string VIEW_PAGE_KEY = "admin/scheduler"; + + private readonly IAntiforgery _antiforgery; + private readonly IOptionsSnapshot _serverConfigurationOptions; + private readonly IUrlService _urlService; + private readonly ThemePageRenderer _themePageRenderer; + private readonly IStringLocalizer _localizer; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service used to create the anti forgery tokens of the page. + /// Injected options used to read the address of the API server that hosts the scheduled jobs hub. + /// Injected service for generating URLs from action and controller names, with localization. + /// Injected service for rendering themed pages. + /// Injected factory used to create the localizer of the view resources. + public SchedulerIndexViewEndpoint( + IAntiforgery antiforgery, + IOptionsSnapshot serverConfigurationOptions, + IUrlService urlService, + ThemePageRenderer themePageRenderer, + IStringLocalizerFactory stringLocalizerFactory) + { + _antiforgery = antiforgery; + _serverConfigurationOptions = serverConfigurationOptions; + _urlService = urlService; + _themePageRenderer = themePageRenderer; + _localizer = stringLocalizerFactory.Create(VIEW_RESOURCE_BASE_NAME, VIEW_RESOURCE_LOCATION); + } + /// /// Configures the endpoint. /// @@ -30,12 +74,65 @@ public class SchedulerIndexViewEndpoint : BaseEndpoint } /// - /// Displays the scheduled jobs dashboard. + /// Displays the scheduled jobs dashboard, rendered by the active theme with a fallback to the Razor view. /// /// The request object. /// Cancellation token that can be used to stop the execution. - public override Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) { - return Task.FromResult(View("/Core/Views/Admin/Scheduler.cshtml")); + ServerConfigurationDto serverConfiguration = _serverConfigurationOptions.Value; + Dictionary localizedStrings = ThemePageDataFactory.CreateLocalizedStrings(_localizer); + + ThemePageDto pageModel = new() + { + PageKey = VIEW_PAGE_KEY, + Title = _localizer["ScheduledJobs"].Value, + Description = string.Empty, + PageData = new Dictionary + { + ["scheduledJobsHubUrl"] = $"{serverConfiguration.BaseAddress}:{serverConfiguration.Port}/scheduledJobsHub", + ["jobsListUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Scheduler.GET_SCHEDULED_JOBS) ?? string.Empty, + ["addJobUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Scheduler.ADD_SCHEDULED_JOB) ?? string.Empty, + ["historyUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Scheduler.GET_SCHEDULED_JOB_HISTORY) ?? string.Empty, + ["startJobUrlTemplate"] = _urlService.GetAbsoluteUrl(WebRoutes.Scheduler.START_SCHEDULED_JOB, new { scheduledJobId = default(System.Guid) }) ?? string.Empty, + ["stopJobUrlTemplate"] = _urlService.GetAbsoluteUrl(WebRoutes.Scheduler.STOP_SCHEDULED_JOB, new { scheduledJobId = default(System.Guid) }) ?? string.Empty, + ["fireJobUrlTemplate"] = _urlService.GetAbsoluteUrl(WebRoutes.Scheduler.FIRE_SCHEDULED_JOB, new { scheduledJobId = default(System.Guid) }) ?? string.Empty, + ["removeJobUrlTemplate"] = _urlService.GetAbsoluteUrl(WebRoutes.Scheduler.REMOVE_SCHEDULED_JOB, new { scheduledJobId = default(System.Guid) }) ?? string.Empty, + ["accessTokenUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Authentication.GET_API_ACCESS_TOKEN) ?? string.Empty, + ["getDisplayPreferencesUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Scheduler.GET_DISPLAY_PREFERENCES) ?? string.Empty, + ["updateDisplayPreferencesUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Scheduler.UPDATE_DISPLAY_PREFERENCES) ?? string.Empty, + ["antiforgeryToken"] = _antiforgery.GetAndStoreTokens(HttpContext).RequestToken ?? string.Empty, + ["strings"] = localizedStrings, + ["taskTypeNames"] = CreateSubgroup(localizedStrings, "TaskType", ["ScanMediaLibraries", "CleanTemporaryFiles", "RepairThemes", "CleanScheduledJobExecutionHistory"]), + ["statusNames"] = CreateSubgroup(localizedStrings, "Status", ["Added", "Active", "Running", "Completed"]) + } + }; + + Result sectionResult = await _themePageRenderer.RenderAsync(pageModel, requestedThemeId: null, cancellationToken).ConfigureAwait(false); + if (sectionResult.IsFailure) + return View("/Core/Views/Admin/Scheduler.cshtml"); + + return View( + "/Core/Views/Shared/_ThemedView.cshtml", + new ThemeViewDto(sectionResult.Value.Content, sectionResult.Value.Script), + new Dictionary { ["Title"] = pageModel.Title }); + } + + /// + /// Creates the subgroup of the localized strings whose resource names start with the provided prefix followed by a dot, + /// keyed by the remainder of their names, so that a template can resolve them with non dotted expressions. + /// + /// The localized strings keyed by their resource names. + /// The prefix of the resource names of the subgroup. + /// The names of the subgroup entries, without the prefix. + /// The localized strings of the subgroup keyed by their names. + private static IReadOnlyDictionary CreateSubgroup(IReadOnlyDictionary localizedStrings, string prefix, IReadOnlyList names) + { + Dictionary subgroup = new(StringComparer.OrdinalIgnoreCase); + foreach (string name in names) + if (localizedStrings.TryGetValue($"{prefix}.{name}", out object? value)) + subgroup[name] = value; + + return subgroup; } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpoint.cs index 61b61967..fa6988a2 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StartScheduledJob/StartScheduledJobEndpoint.cs @@ -40,6 +40,7 @@ public class StartScheduledJobEndpoint : BaseEndpoint options.WithTags("Admin")); Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + EnableAntiforgery(); } /// diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpoint.cs index 246de104..55616f57 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/StopScheduledJob/StopScheduledJobEndpoint.cs @@ -40,6 +40,7 @@ public class StopScheduledJobEndpoint : BaseEndpoint options.WithTags("Admin")); Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + EnableAntiforgery(); } /// diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpoint.cs index 3898862a..03075603 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Scheduler/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpoint.cs @@ -40,6 +40,7 @@ public class UpdateSchedulerDisplayPreferencesEndpoint : BaseEndpoint options.WithTags("Admin")); Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + EnableAntiforgery(); } /// 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 a2f576ca..8cd2978e 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 @@ -159,4 +159,13 @@ اسم المهمة مطلوب. + + إصلاح السمات + + + تنظيف سجل الوظائف + + + عند بدء التشغيل + 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 7a4e8cac..6caf3884 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 @@ -159,4 +159,13 @@ Der Aufgabenname ist erforderlich. + + Designs reparieren + + + Jobverlauf bereinigen + + + 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 be9edf12..24fa61bb 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 @@ -159,4 +159,13 @@ The job name is required. + + Repair themes + + + Clean job history + + + 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 afbcaab9..0a45962c 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 @@ -159,4 +159,13 @@ El nombre de la tarea es obligatorio. + + Reparar temas + + + Limpiar historial de trabajos + + + 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 c286b139..bc2a145d 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 @@ -159,4 +159,13 @@ Le nom de la tâche est requis. + + Réparer les thèmes + + + Nettoyer l'historique des tâches + + + 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 45df67e8..bc5520f8 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 @@ -159,4 +159,13 @@ Il nome dell'attività è obbligatorio. + + Ripara i temi + + + Pulisci la cronologia dei processi + + + 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 7978c6e3..efe836d0 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 @@ -159,4 +159,13 @@ ジョブ名が必要です。 + + テーマを修復 + + + ジョブ履歴を削除 + + + 起動時 + 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 be9edf12..24fa61bb 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Scheduler.resx @@ -159,4 +159,13 @@ The job name is required. + + Repair themes + + + Clean job history + + + 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 56341e70..abd5a9b4 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 @@ -159,4 +159,13 @@ Numele sarcinii este obligatoriu. + + Repară temele + + + Curăță istoricul proceselor + + + 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 c698d127..1feacdb6 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 @@ -159,4 +159,13 @@ Назва завдання обов'язкова. + + Відновлення тем + + + Очистити історію завдань + + + Під час запуску + 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 5fa4b521..8aed079b 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 @@ -159,4 +159,13 @@ 需要提供任务名称。 + + 修复主题 + + + 清理作业历史 + + + 启动时 + diff --git a/src/Lumina.Presentation.Web/Core/Views/Admin/Scheduler.cshtml b/src/Lumina.Presentation.Web/Core/Views/Admin/Scheduler.cshtml index 86ec8bea..86110990 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Admin/Scheduler.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Admin/Scheduler.cshtml @@ -1,5 +1,9 @@ @* /admin/scheduled-jobs + +This view is the application fallback of the scheduler page, rendered only when the theme page of the scheduler cannot be loaded. +It is intentionally plain and unstyled: on a healthy site the page comes from the theme's scheduler template, styled by the theme. +It keeps the DOM contract the client script binds to, without any images or colors, so that the active theme cannot leak into the fallback. *@ @using Lumina.Presentation.Web.Common.DTO.Configuration @@ -40,7 +44,9 @@
@_localizer["All"]
@_localizer["TaskType.ScanMediaLibraries"]
-
@_localizer["TaskType.CleanTemporaryFiles"]
+
@_localizer["TaskType.CleanTemporaryFiles"]
+
@_localizer["TaskType.RepairThemes"]
+
@_localizer["TaskType.CleanScheduledJobExecutionHistory"]
@@ -109,7 +115,9 @@
@_localizer["TaskType.ScanMediaLibraries"]
-
@_localizer["TaskType.CleanTemporaryFiles"]
+
@_localizer["TaskType.CleanTemporaryFiles"]
+
@_localizer["TaskType.RepairThemes"]
+
@_localizer["TaskType.CleanScheduledJobExecutionHistory"]
@@ -124,7 +132,8 @@
@_localizer["IntervalSchedule"]
-
@_localizer["DailySchedule"]
+
@_localizer["DailySchedule"]
+
@_localizer["StartupSchedule"]
@@ -159,6 +168,7 @@ noJobs: '@_localizer["NoJobs"]', daily: '@_localizer["DailySchedule"]', interval: '@_localizer["IntervalSchedule"]', + startup: '@_localizer["StartupSchedule"]', jobStarted: '@_localizer["JobStarted"]', jobRemoved: '@_localizer["JobRemoved"]', jobStopped: '@_localizer["JobStopped"]', @@ -168,7 +178,9 @@ jobAlreadyRunning: '@_localizer["JobAlreadyRunning"]', taskTypeNames: { ScanMediaLibraries: '@_localizer["TaskType.ScanMediaLibraries"]', - CleanTemporaryFiles: '@_localizer["TaskType.CleanTemporaryFiles"]' + CleanTemporaryFiles: '@_localizer["TaskType.CleanTemporaryFiles"]', + RepairThemes: '@_localizer["TaskType.RepairThemes"]', + CleanScheduledJobExecutionHistory: '@_localizer["TaskType.CleanScheduledJobExecutionHistory"]' }, statusNames: { Added: '@_localizer["Status.Added"]', @@ -181,7 +193,9 @@ // Colors of the job types. const jobTypeColors = { ScanMediaLibraries: '#5aa7c7', - CleanTemporaryFiles: '#c7a15a' + CleanTemporaryFiles: '#c7a15a', + RepairThemes: '#8bc34a', + CleanScheduledJobExecutionHistory: '#ba68c8' }; const jobsTable = document.getElementById('scheduler-jobs-table'); @@ -281,7 +295,7 @@ } // Graph state. - const taskTypeOrder = ['ScanMediaLibraries', 'CleanTemporaryFiles']; + const taskTypeOrder = ['ScanMediaLibraries', 'CleanTemporaryFiles', 'RepairThemes', 'CleanScheduledJobExecutionHistory']; const graphState = { dataPoints: [], pixelsPerSecond: 0, @@ -341,13 +355,15 @@ row.dataset.scheduledJobId = job.id; const isInterval = job.scheduleType === 'WithIntervalInMinutes'; + const isDaily = job.scheduleType === 'DailyAtHourAndMinute'; + const scheduleLabel = isInterval ? schedulerStrings.interval : isDaily ? schedulerStrings.daily : schedulerStrings.startup; row.innerHTML = ` ${job.id} ${escapeHtml(job.name)} ${schedulerStrings.taskTypeNames[job.taskType] ?? job.taskType} - ${isInterval ? schedulerStrings.interval : schedulerStrings.daily} + ${scheduleLabel} ${isInterval ? job.intervalMinutes + ' ' + '@_localizer["MinutesShort"]' : '-'} - ${isInterval ? '-' : String(job.hour).padStart(2, '0') + ':' + String(job.minute).padStart(2, '0')} + ${isDaily ? String(job.hour).padStart(2, '0') + ':' + String(job.minute).padStart(2, '0') : '-'} ${schedulerStrings.statusNames[job.status] ?? job.status} ${formatDateTime(job.lastStartedOnUtc)} ${formatDateTime(job.lastCompletedOnUtc)} @@ -746,8 +762,10 @@ // Toggle the schedule fields based on the selected schedule type. const toggleScheduleFields = () => { - const isDaily = getComboboxValue(jobScheduleTypeSelect) === 'DailyAtHourAndMinute'; - intervalGroup.classList.toggle('hidden', isDaily); + const scheduleType = getComboboxValue(jobScheduleTypeSelect); + const isInterval = scheduleType === 'WithIntervalInMinutes'; + const isDaily = scheduleType === 'DailyAtHourAndMinute'; + intervalGroup.classList.toggle('hidden', !isInterval); dailyGroup.classList.toggle('hidden', !isDaily); dailyMinuteGroup.classList.toggle('hidden', !isDaily); }; diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Scheduling/ScheduledJobEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Scheduling/ScheduledJobEntityFixture.cs index 59c82fc0..5c0235fd 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Scheduling/ScheduledJobEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Scheduling/ScheduledJobEntityFixture.cs @@ -69,6 +69,27 @@ public class ScheduledJobEntityFixture UpdatedBy = null }; } + if (resolvedScheduleType == ScheduleType.OnceAtStartup) + { + return new ScheduledJobEntity + { + Id = id ?? Guid.NewGuid(), + Name = name ?? f.Commerce.ProductName(), + TaskType = taskType ?? f.PickRandom(), + ScheduleType = resolvedScheduleType, + IntervalMinutes = null, + Hour = null, + Minute = null, + Status = status ?? f.PickRandom(), + OwnerUserId = ownerUserId ?? Guid.NewGuid(), + LastStartedOnUtc = lastStartedOnUtc, + LastCompletedOnUtc = lastCompletedOnUtc, + CreatedOnUtc = DateTime.UtcNow, + CreatedBy = Guid.NewGuid(), + UpdatedOnUtc = null, + UpdatedBy = null + }; + } return new ScheduledJobEntity { Id = id ?? Guid.NewGuid(), diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Scheduling/ScheduledJobExecutionEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Scheduling/ScheduledJobExecutionEntityFixture.cs index ed2b07b2..7583031c 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Scheduling/ScheduledJobExecutionEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Scheduling/ScheduledJobExecutionEntityFixture.cs @@ -23,6 +23,7 @@ public class ScheduledJobExecutionEntityFixture /// Optional. The Id of the scheduled job whose task was executed. /// Optional. The type of the task that was executed. /// Optional. Whether the execution was a cycle run. + /// Optional. Whether the execution cycle of the scheduled job was active when the execution started. /// Optional. The start time of the execution. /// Optional. The completion time of the execution. /// The created . @@ -31,6 +32,7 @@ public class ScheduledJobExecutionEntityFixture Guid? scheduledJobId = null, ScheduledTaskType? taskType = null, bool? isCycleRun = null, + bool? wasCycleActive = null, DateTime? startedOnUtc = null, DateTime? completedOnUtc = null) { @@ -41,6 +43,7 @@ public class ScheduledJobExecutionEntityFixture ScheduledJobId = scheduledJobId ?? Guid.NewGuid(), TaskType = taskType ?? f.PickRandom(), IsCycleRun = isCycleRun ?? f.Random.Bool(), + WasCycleActive = wasCycleActive ?? f.Random.Bool(), StartedOnUtc = startedOnUtc ?? DateTime.UtcNow, CompletedOnUtc = completedOnUtc, CreatedOnUtc = DateTime.UtcNow, diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/OnceAtStartupScheduleFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/OnceAtStartupScheduleFixture.cs new file mode 100644 index 00000000..d6da6351 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/OnceAtStartupScheduleFixture.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; + +/// +/// Fixture class for the value object. +/// +[ExcludeFromCodeCoverage] +public class OnceAtStartupScheduleFixture +{ + /// + /// Creates a valid . + /// + /// The created . + public OnceAtStartupSchedule Create() + { + return OnceAtStartupSchedule.Create().Value; + } + + /// + /// Creates a list of instances. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/ScheduledJobEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/ScheduledJobEntityMappingTests.cs index 1fa6a60b..dcd6f372 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/ScheduledJobEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Scheduling/ScheduledJobEntityMappingTests.cs @@ -146,24 +146,39 @@ public class ScheduledJobEntityMappingTests } [Fact] - public void ToResponse_WhenRepositoryEntityHasDailySchedule_ShouldMapToResponse() + public void ToDomainEntity_WhenRepositoryEntityHasOnceAtStartupSchedule_ShouldMapToOnceAtStartupScheduledJob() + { + // Arrange + ScheduledJobEntity repositoryEntity = _scheduledJobEntityFixture.Create( + scheduleType: ScheduleType.OnceAtStartup, + status: ScheduledJobStatus.Active); + + // Act + Result result = repositoryEntity.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + OnceAtStartupSchedule onceAtStartupSchedule = Assert.IsType(result.Value.Schedule); + Assert.Equal(ScheduleType.OnceAtStartup, onceAtStartupSchedule.ScheduleType); + } + + [Fact] + public void ToResponse_WhenRepositoryEntityHasOnceAtStartupSchedule_ShouldMapToResponse() { // Arrange ScheduledJobEntity repositoryEntity = _scheduledJobEntityFixture.Create( id: Guid.NewGuid(), - scheduleType: ScheduleType.DailyAtHourAndMinute, - hour: 6, - minute: 30, - status: ScheduledJobStatus.Added); + scheduleType: ScheduleType.OnceAtStartup, + status: ScheduledJobStatus.Active); // Act ScheduledJobResponse result = repositoryEntity.ToResponse(); // Assert Assert.NotNull(result); - Assert.Equal(ScheduleType.DailyAtHourAndMinute, result.ScheduleType); + Assert.Equal(ScheduleType.OnceAtStartup, result.ScheduleType); Assert.Null(result.IntervalMinutes); - Assert.Equal(6, result.Hour); - Assert.Equal(30, result.Minute); + Assert.Null(result.Hour); + Assert.Null(result.Minute); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs index ef38a48c..1068a8df 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandlerTests.cs @@ -1,18 +1,24 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.Seed; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DomainEvents; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Security; using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Fixtures.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; using Lumina.Contracts.Responses.Authentication; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; using NSubstitute; using System; using System.Diagnostics.CodeAnalysis; @@ -35,10 +41,13 @@ public class SetupApplicationCommandHandlerTests private readonly ITotpTokenGenerator _mockTotpTokenGenerator; private readonly IQRCodeGenerator _mockQRCodeGenerator; private readonly IUserRepository _mockUserRepository; + private readonly IScheduledJobRepository _mockScheduledJobRepository; private readonly IDateTimeProvider _mockDateTimeProvider; private readonly IDataSeedService _mockDataSeedService; + private readonly IDomainEventsQueue _mockDomainEventsQueue; private readonly SetupApplicationCommandHandler _sut; private readonly UserEntityFixture _userEntityFixture = new(); + private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new(); private readonly SetupApplicationCommandFixture _setupApplicationCommandFixture = new(); /// @@ -52,14 +61,21 @@ public class SetupApplicationCommandHandlerTests _mockTotpTokenGenerator = Substitute.For(); _mockQRCodeGenerator = Substitute.For(); _mockUserRepository = Substitute.For(); + _mockScheduledJobRepository = Substitute.For(); _mockDateTimeProvider = Substitute.For(); _mockDataSeedService = Substitute.For(); + _mockDomainEventsQueue = Substitute.For(); IValidator mockValidator = Substitute.For>(); mockValidator.Validate(Arg.Any()) .Returns([]); _mockUnitOfWork.UserRepository.Returns(_mockUserRepository); + _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); _mockDateTimeProvider.UtcNow.Returns(DateTime.UtcNow); + _mockDataSeedService.SetDefaultScheduledJobsAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockScheduledJobRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From(Enumerable.Empty())); _sut = new SetupApplicationCommandHandler( _mockUnitOfWork, @@ -69,6 +85,7 @@ public class SetupApplicationCommandHandlerTests _mockQRCodeGenerator, _mockDateTimeProvider, _mockDataSeedService, + _mockDomainEventsQueue, mockValidator); } @@ -336,6 +353,40 @@ public class SetupApplicationCommandHandlerTests await _mockDataSeedService.Received(1).SetDefaultAuthorizationRolesAsync(Arg.Any(), Arg.Any()); await _mockDataSeedService.Received(1).SetAdminRolePermissionsAsync(Arg.Any(), Arg.Any()); await _mockDataSeedService.Received(1).SetAdminRoleToAdministratorAccount(Arg.Any(), Arg.Any()); + await _mockDataSeedService.DidNotReceive().SetDefaultScheduledJobsAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSeedingDefaultScheduledJobsFails_ShouldReturnError() + { + // Arrange + SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); + Error error = Error.Failure("Database.Error", "Failed to seed default scheduled jobs"); + + _mockUserRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From(Enumerable.Empty())); + _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetDefaultScheduledJobsAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + + await _mockDataSeedService.Received(1).SetAdminRoleToAdministratorAccount(Arg.Any(), Arg.Any()); + await _mockDataSeedService.Received(1).SetDefaultScheduledJobsAsync(Arg.Any(), Arg.Any()); } [Fact] @@ -369,5 +420,40 @@ public class SetupApplicationCommandHandlerTests await _mockDataSeedService.Received(1).SetDefaultAuthorizationRolesAsync(Arg.Any(), Arg.Any()); await _mockDataSeedService.Received(1).SetAdminRolePermissionsAsync(Arg.Any(), Arg.Any()); await _mockDataSeedService.Received(1).SetAdminRoleToAdministratorAccount(Arg.Any(), Arg.Any()); + await _mockDataSeedService.Received(1).SetDefaultScheduledJobsAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenDefaultScheduledJobsAreSeeded_ShouldQueueACycleStartedEventForEachActiveJob() + { + // Arrange + SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); + ScheduledJobEntity activeScheduledJob1 = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active); + ScheduledJobEntity activeScheduledJob2 = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active); + ScheduledJobEntity addedScheduledJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added); + + _mockUserRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From(Enumerable.Empty())); + _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetDefaultAuthorizationRolesAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetAdminRolePermissionsAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockScheduledJobRepository.GetAllAsync(Arg.Any()) + .Returns(new[] { activeScheduledJob1, activeScheduledJob2, addedScheduledJob }); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockDomainEventsQueue.Received(1).Enqueue(Arg.Is(domainEvent => domainEvent.ScheduledJobId.Value == activeScheduledJob1.Id)); + _mockDomainEventsQueue.Received(1).Enqueue(Arg.Is(domainEvent => domainEvent.ScheduledJobId.Value == activeScheduledJob2.Id)); + _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Is(domainEvent => domainEvent.ScheduledJobId.Value == addedScheduledJob.Id)); } } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs index a9349aa8..c6bd2276 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs @@ -1,20 +1,25 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Authorization; +using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.DataAccess.Core.Seed; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; using NSubstitute; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -35,6 +40,7 @@ public class DataSeedServiceTests private readonly UserEntityFixture _userEntityFixture = new(); private readonly RoleEntityFixture _roleEntityFixture = new(); private readonly PermissionEntityFixture _permissionEntityFixture = new(); + private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -543,4 +549,103 @@ public class DataSeedServiceTests await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } + + [Fact] + public async Task SetDefaultScheduledJobsAsync_WhenNoScheduledJobsExist_ShouldInsertTheFiveDefaultJobsAndReturnCreated() + { + // Arrange + Guid adminUserId = Guid.NewGuid(); + IScheduledJobRepository mockScheduledJobRepository = Substitute.For(); + _mockUnitOfWork.ScheduledJobRepository.Returns(mockScheduledJobRepository); + mockScheduledJobRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From(Enumerable.Empty())); + List capturedScheduledJobs = []; + mockScheduledJobRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created) + .AndDoes(info => capturedScheduledJobs.Add(info.Arg())); + + // Act + Result result = await _sut.SetDefaultScheduledJobsAsync(adminUserId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + Assert.Equal(5, 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)); + Assert.All(capturedScheduledJobs, scheduledJob => Assert.Equal(_fixedUtcNow, scheduledJob.CreatedOnUtc)); + Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.ScanMediaLibraries && scheduledJob.ScheduleType == ScheduleType.DailyAtHourAndMinute && scheduledJob.Hour == 0 && scheduledJob.Minute == 0); + Assert.Contains(capturedScheduledJobs, scheduledJob => scheduledJob.TaskType == ScheduledTaskType.CleanTemporaryFiles && scheduledJob.ScheduleType == ScheduleType.OnceAtStartup); + 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); + + await mockScheduledJobRepository.Received(5).InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task SetDefaultScheduledJobsAsync_WhenScheduledJobsAlreadyExist_ShouldNotInsertAnyJob() + { + // Arrange + Guid adminUserId = Guid.NewGuid(); + IScheduledJobRepository mockScheduledJobRepository = Substitute.For(); + _mockUnitOfWork.ScheduledJobRepository.Returns(mockScheduledJobRepository); + ScheduledJobEntity existingScheduledJob = _scheduledJobEntityFixture.Create(scheduleType: ScheduleType.WithIntervalInMinutes); + mockScheduledJobRepository.GetAllAsync(Arg.Any()) + .Returns(new[] { existingScheduledJob }); + + // Act + Result result = await _sut.SetDefaultScheduledJobsAsync(adminUserId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + await mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task SetDefaultScheduledJobsAsync_WhenGetAllScheduledJobsFails_ShouldReturnError() + { + // Arrange + Guid adminUserId = Guid.NewGuid(); + IScheduledJobRepository mockScheduledJobRepository = Substitute.For(); + _mockUnitOfWork.ScheduledJobRepository.Returns(mockScheduledJobRepository); + Error expectedError = Error.Failure("ScheduledJobs.NotFound", "Failed to retrieve the scheduled jobs"); + mockScheduledJobRepository.GetAllAsync(Arg.Any()) + .Returns(expectedError); + + // Act + Result result = await _sut.SetDefaultScheduledJobsAsync(adminUserId, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(expectedError, result.FirstError); + await mockScheduledJobRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task SetDefaultScheduledJobsAsync_WhenInsertScheduledJobFails_ShouldReturnError() + { + // Arrange + Guid adminUserId = Guid.NewGuid(); + IScheduledJobRepository mockScheduledJobRepository = Substitute.For(); + _mockUnitOfWork.ScheduledJobRepository.Returns(mockScheduledJobRepository); + mockScheduledJobRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From(Enumerable.Empty())); + Error expectedError = Error.Failure("ScheduledJobs.InsertFailed", "Failed to insert the scheduled job"); + mockScheduledJobRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created, expectedError); + + // Act + Result result = await _sut.SetDefaultScheduledJobsAsync(adminUserId, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(expectedError, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/OnceAtStartupScheduleTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/OnceAtStartupScheduleTests.cs new file mode 100644 index 00000000..15d706d8 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/SchedulingBoundedContext/ScheduledJobAggregate/ValueObjects/OnceAtStartupScheduleTests.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class OnceAtStartupScheduleTests +{ + private readonly OnceAtStartupScheduleFixture _onceAtStartupScheduleFixture = new(); + + [Fact] + public void Create_WhenCalled_ShouldCreateOnceAtStartupSchedule() + { + // Act + OnceAtStartupSchedule schedule = _onceAtStartupScheduleFixture.Create(); + + // Assert + Assert.Equal(ScheduleType.OnceAtStartup, schedule.ScheduleType); + } + + [Fact] + public void GetDelayUntilNextExecution_WhenCalled_ShouldReturnTheMaximumDelay() + { + // Arrange + OnceAtStartupSchedule schedule = _onceAtStartupScheduleFixture.Create(); + DateTime utcNow = new(2026, 1, 1, 10, 0, 0, DateTimeKind.Utc); + + // Act + TimeSpan delay = schedule.GetDelayUntilNextExecution(utcNow, TimeZoneInfo.Utc); + + // Assert + Assert.Equal(TimeSpan.MaxValue, delay); + } + + [Fact] + public void Equals_WhenBothAreOnceAtStartupSchedules_ShouldReturnTrue() + { + // Act + bool areEqual = _onceAtStartupScheduleFixture.Create().Equals(_onceAtStartupScheduleFixture.Create()); + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Notifications/ScheduledJobNotifierTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Notifications/ScheduledJobNotifierTests.cs index aeb60371..df53a5d2 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Notifications/ScheduledJobNotifierTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Notifications/ScheduledJobNotifierTests.cs @@ -32,14 +32,14 @@ public class ScheduledJobNotifierTests { _mockClient = Substitute.For(); _mockHubClients = Substitute.For>(); - _mockHubClients.All.Returns(_mockClient); + _mockHubClients.Group(ScheduledJobsHub.ADMINISTRATORS_GROUP).Returns(_mockClient); _mockHubContext = Substitute.For>(); _mockHubContext.Clients.Returns(_mockHubClients); _sut = new ScheduledJobNotifier(_mockHubContext); } [Fact] - public async Task SendScheduledJobsAsync_WhenCalled_ShouldSendTheScheduledJobsToAllClients() + public async Task SendScheduledJobsAsync_WhenCalled_ShouldSendTheScheduledJobsToTheAdministratorGroup() { // Arrange IReadOnlyList scheduledJobs = _scheduledJobResponseFixture.CreateMany(2); @@ -49,10 +49,11 @@ public class ScheduledJobNotifierTests // Assert await _mockClient.Received(1).ReceiveScheduledJobsAsync(scheduledJobs); + _mockHubClients.Received(1).Group(ScheduledJobsHub.ADMINISTRATORS_GROUP); } [Fact] - public async Task SendScheduledJobExecutionStartedAsync_WhenCalled_ShouldSendTheExecutionToAllClients() + public async Task SendScheduledJobExecutionStartedAsync_WhenCalled_ShouldSendTheExecutionToTheAdministratorGroup() { // Arrange ScheduledJobExecutionResponse execution = _scheduledJobExecutionResponseFixture.Create(); @@ -62,10 +63,11 @@ public class ScheduledJobNotifierTests // Assert await _mockClient.Received(1).ScheduledJobExecutionStartedAsync(execution); + _mockHubClients.Received(1).Group(ScheduledJobsHub.ADMINISTRATORS_GROUP); } [Fact] - public async Task SendScheduledJobExecutionCompletedAsync_WhenCalled_ShouldSendTheExecutionToAllClients() + public async Task SendScheduledJobExecutionCompletedAsync_WhenCalled_ShouldSendTheExecutionToTheAdministratorGroup() { // Arrange ScheduledJobExecutionResponse execution = _scheduledJobExecutionResponseFixture.Create(); @@ -75,5 +77,6 @@ public class ScheduledJobNotifierTests // Assert await _mockClient.Received(1).ScheduledJobExecutionCompletedAsync(execution); + _mockHubClients.Received(1).Group(ScheduledJobsHub.ADMINISTRATORS_GROUP); } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Notifications/ScheduledJobsHubTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Notifications/ScheduledJobsHubTests.cs index ba41a80d..f341d5a5 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Notifications/ScheduledJobsHubTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Notifications/ScheduledJobsHubTests.cs @@ -84,13 +84,16 @@ public class ScheduledJobsHubTests } [Fact] - public async Task OnConnectedAsync_WhenUserIsAdministrator_ShouldNotAbortTheConnection() + public async Task OnConnectedAsync_WhenUserIsAdministrator_ShouldAddTheConnectionToTheAdministratorGroup() { // Arrange Guid userId = Guid.NewGuid(); ClaimsPrincipal user = new(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, userId.ToString())])); HubCallerContext context = CreateHubCallerContext(user); + context.ConnectionId.Returns("connection-1"); _sut.Context = context; + IGroupManager mockGroupManager = Substitute.For(); + _sut.Groups = mockGroupManager; _mockAuthorizationService.IsInRoleAsync(userId, "Admin", System.Threading.CancellationToken.None).Returns(true); // Act @@ -98,6 +101,7 @@ public class ScheduledJobsHubTests // Assert context.DidNotReceive().Abort(); + await mockGroupManager.Received(1).AddToGroupAsync("connection-1", ScheduledJobsHub.ADMINISTRATORS_GROUP, System.Threading.CancellationToken.None); } /// diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeDetectionSyncJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeDetectionSyncJobTests.cs deleted file mode 100644 index 9c12665e..00000000 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeDetectionSyncJobTests.cs +++ /dev/null @@ -1,550 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.Themes; -using Lumina.Application.Common.DataAccess.Repositories.Themes; -using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Common.Infrastructure.Models.DTO.Themes; -using Lumina.Application.Common.Infrastructure.Themes; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; -using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Themes; -using Lumina.Domain.Common.Primitives; -using Lumina.Domain.SharedKernel.Common.Enums.Themes; -using Lumina.Infrastructure.Core.Themes; -using Lumina.Infrastructure.Fixtures.Core.Themes; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using NSubstitute; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.IO; -using System.Reflection; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Infrastructure.UnitTests.Core.Themes; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class ThemeDetectionSyncJobTests : IDisposable -{ - private readonly IServiceScopeFactory _mockServiceScopeFactory; - private readonly IServiceScope _mockServiceScope; - private readonly IServiceProvider _mockServiceProvider; - private readonly IUnitOfWork _mockUnitOfWork; - private readonly IThemeRepository _mockThemeRepository; - private readonly IThemeService _mockThemeService; - private readonly ILogger _mockLogger; - private readonly ThemePackFixture _themePackFixture = new(); - private readonly ThemeEntityFixture _themeEntityFixture = new(); - private readonly ThemeManifestDtoFixture _themeManifestDtoFixture = new(); - private readonly string _testRootPath; - - /// - /// Initializes a new instance of the class. - /// - public ThemeDetectionSyncJobTests() - { - _testRootPath = Path.Combine(Path.GetTempPath(), $"lumina-theme-job-{Guid.NewGuid():N}"); - Directory.CreateDirectory(_testRootPath); - _mockServiceScopeFactory = Substitute.For(); - _mockServiceScope = Substitute.For(); - _mockServiceProvider = Substitute.For(); - _mockServiceScopeFactory.CreateAsyncScope().Returns(new AsyncServiceScope(_mockServiceScope)); - _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); - - _mockUnitOfWork = Substitute.For(); - _mockThemeRepository = Substitute.For(); - _mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository); - _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); - - _mockThemeService = Substitute.For(); - _mockThemeService.HasThemePack(Arg.Any()).Returns(true); - _mockLogger = Substitute.For>(); - } - - /// - /// Cleans up the temporary storage used by the tests. - /// - public void Dispose() - { - try - { - if (Directory.Exists(_testRootPath)) - Directory.Delete(_testRootPath, recursive: true); - } - catch (IOException) - { - // best effort cleanup of the per-test temp directory - } - catch (UnauthorizedAccessException) - { - // best effort cleanup of the per-test temp directory - } - } - - [Fact] - public async Task StartAsync_WhenThereAreNoBundledThemesAndNoInstalledThemes_ShouldOnlySaveChanges() - { - // Arrange - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); - _mockThemeService.GetBundledThemeArchivePaths().Returns([]); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenBundledThemeIsNotYetInstalled_ShouldInstallAndPersistTheTheme() - { - // Arrange - string archivePath = CreateBundledArchiveFile("bundled-theme"); - ThemeManifestDto manifest = _themeManifestDtoFixture.Create(id: "bundled-theme"); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); - _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); - _mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any()).Returns(manifest); - _mockThemeService.InstallAsync(Arg.Any(), Arg.Any()).Returns(manifest); - _mockThemeRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(Result.From(Result.Created)); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeService.Received(1).InstallAsync(Arg.Any(), Arg.Any()); - await _mockThemeRepository.Received(1).InsertAsync( - Arg.Is(theme => theme.ThemeId == "bundled-theme" - && theme.Name == manifest.Name - && theme.Description == manifest.Description - && theme.Version == manifest.Version - && theme.InstallSource == ThemeInstallSource.Bundled), - Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenBundledThemeIsAlreadyInstalled_ShouldSkipInstallingIt() - { - // Arrange - ThemeEntity existingTheme = _themeEntityFixture.Create(themeId: "bundled-theme", isCurrent: true, includeIsCurrent: true, installSource: ThemeInstallSource.Bundled, isDeleted: false); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([existingTheme])); - _mockThemeService.GetBundledThemeArchivePaths().Returns(["C:\\bundled\\bundled-theme.zip"]); - _mockThemeService.ReadManifestFromArchiveAsync("C:\\bundled\\bundled-theme.zip", Arg.Any()).Returns(_themeManifestDtoFixture.Create(id: "bundled-theme")); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); - await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenBundledThemeWasSoftDeletedByTheUser_ShouldNotReinstallIt() - { - // Arrange - ThemeEntity deletedTheme = _themeEntityFixture.Create(themeId: "bundled-theme", isDeleted: true, installSource: ThemeInstallSource.Bundled); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([deletedTheme])); - _mockThemeService.GetBundledThemeArchivePaths().Returns(["C:\\bundled\\bundled-theme.zip"]); - _mockThemeService.ReadManifestFromArchiveAsync("C:\\bundled\\bundled-theme.zip", Arg.Any()).Returns(_themeManifestDtoFixture.Create(id: "bundled-theme")); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); - await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenInstalledBundledThemePackIsMissingAndNotDeleted_ShouldReinstallTheFilesWithoutInsertingANewRow() - { - // Arrange - ThemeEntity existingTheme = _themeEntityFixture.Create(themeId: "bundled-theme", isCurrent: true, includeIsCurrent: true, installSource: ThemeInstallSource.Bundled, isDeleted: false); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([existingTheme])); - _mockThemeService.HasThemePack("bundled-theme").Returns(false); - string archivePath = CreateBundledArchiveFile("bundled-theme"); - ThemeManifestDto manifest = _themeManifestDtoFixture.Create(id: "bundled-theme"); - _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); - _mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any()).Returns(manifest); - _mockThemeService.InstallAsync(Arg.Any(), Arg.Any()).Returns(manifest); - _mockThemeService.RestoreBundledThemeAsync("bundled-theme", Arg.Any()).Returns(Result.Success); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeService.Received(1).InstallAsync(Arg.Any(), Arg.Any()); - await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); - await _mockThemeRepository.DidNotReceiveWithAnyArgs().UpdateAsync(default!, Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenBundledArchiveManifestCannotBeRead_ShouldSkipTheArchive() - { - // Arrange - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); - _mockThemeService.GetBundledThemeArchivePaths().Returns(["C:\\bundled\\broken.zip"]); - _mockThemeService.ReadManifestFromArchiveAsync("C:\\bundled\\broken.zip", Arg.Any()).Returns(Error.Failure("Theme.Files", "unreadable")); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); - await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenBundledThemeInstallFails_ShouldNotPersistTheTheme() - { - // Arrange - string archivePath = CreateBundledArchiveFile("bundled-theme"); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); - _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); - _mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any()).Returns(_themeManifestDtoFixture.Create(id: "bundled-theme")); - _mockThemeService.InstallAsync(Arg.Any(), Arg.Any()).Returns(Error.Failure("Theme.Install", "install failed")); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenPersistingDetectedThemeFails_ShouldLogWarningAndContinue() - { - // Arrange - string archivePath = CreateBundledArchiveFile("bundled-theme"); - ThemeManifestDto manifest = _themeManifestDtoFixture.Create(id: "bundled-theme"); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); - _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); - _mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any()).Returns(manifest); - _mockThemeService.InstallAsync(Arg.Any(), Arg.Any()).Returns(manifest); - _mockThemeRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(Error.Failure("Database.Error", "failed to persist")); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenReadingInstalledThemesFails_ShouldReturnWithoutPersistingChanges() - { - // Arrange - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Error.Failure("Database.Error", "failed to read themes")); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - _mockThemeService.DidNotReceive().GetBundledThemeArchivePaths(); - await _mockUnitOfWork.DidNotReceiveWithAnyArgs().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenMissingBundledThemePackCanBeRestored_ShouldRestoreTheFiles() - { - // Arrange - ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "bundled-theme", isCurrent: true, includeIsCurrent: true, installSource: ThemeInstallSource.Bundled, isDeleted: false); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([brokenTheme])); - _mockThemeService.HasThemePack("bundled-theme").Returns(false); - _mockThemeService.GetBundledThemeArchivePaths().Returns([]); - _mockThemeService.RestoreBundledThemeAsync("bundled-theme", Arg.Any()).Returns(Result.Success); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeService.Received(1).RestoreBundledThemeAsync("bundled-theme", Arg.Any()); - await _mockThemeRepository.DidNotReceiveWithAnyArgs().UpdateAsync(default!, Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenRestoringBundledThemeThrows_ShouldNotCrashTheJob() - { - // Arrange - ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "bundled-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([brokenTheme])); - _mockThemeService.HasThemePack("bundled-theme").Returns(false); - _mockThemeService.GetBundledThemeArchivePaths().Returns([]); - _mockThemeService.RestoreBundledThemeAsync("bundled-theme", Arg.Any()) - .Returns(Task.FromException>(new IOException("The theme storage is locked."))); - _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.From(Result.Updated)); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeService.Received(1).RestoreBundledThemeAsync("bundled-theme", Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenLastBundledThemePackCannotBeRestored_ShouldKeepAndActivateTheTheme() - { - // Arrange - ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "bundled-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([brokenTheme])); - _mockThemeService.HasThemePack("bundled-theme").Returns(false); - _mockThemeService.GetBundledThemeArchivePaths().Returns([]); - _mockThemeService.RestoreBundledThemeAsync("bundled-theme", Arg.Any()).Returns(Error.Failure("Theme.Files", "restore failed")); - _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.From(Result.Updated)); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeRepository.Received(1).UpdateAsync( - Arg.Is(theme => theme.ThemeId == "bundled-theme" && theme.IsCurrent == true && !theme.IsDeleted), - Arg.Any()); - await _mockThemeService.Received(1).RestoreBundledThemeAsync("bundled-theme", Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenMissingBundledThemePackCannotBeRestoredAndAnotherBundledThemeRemains_ShouldSoftDeleteTheTheme() - { - // Arrange - ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "broken-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false); - ThemeEntity healthyTheme = _themeEntityFixture.Create(themeId: "healthy-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([brokenTheme, healthyTheme])); - _mockThemeService.HasThemePack("broken-theme").Returns(false); - _mockThemeService.GetBundledThemeArchivePaths().Returns([]); - _mockThemeService.RestoreBundledThemeAsync("broken-theme", Arg.Any()).Returns(Error.Failure("Theme.Files", "restore failed")); - _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.From(Result.Updated)); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeRepository.Received(1).UpdateAsync( - Arg.Is(theme => theme.ThemeId == "broken-theme" && theme.IsDeleted && theme.IsCurrent == null), - Arg.Any()); - await _mockThemeRepository.Received(1).UpdateAsync( - Arg.Is(theme => theme.ThemeId == "healthy-theme" && theme.IsCurrent == true), - Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenMissingUserThemePackExists_ShouldDeleteTheTheme() - { - // Arrange - ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "user-theme", installSource: ThemeInstallSource.Uploaded, isDeleted: false); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([brokenTheme])); - _mockThemeService.HasThemePack("user-theme").Returns(false); - _mockThemeService.GetBundledThemeArchivePaths().Returns([]); - _mockThemeRepository.DeleteByIdAsync(brokenTheme.Id, Arg.Any()).Returns(Result.From(Result.Deleted)); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeRepository.Received(1).DeleteByIdAsync(brokenTheme.Id, Arg.Any()); - await _mockThemeService.DidNotReceive().RestoreBundledThemeAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenDeletingMissingUserThemeFails_ShouldLogWarningAndContinue() - { - // Arrange - ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "user-theme", installSource: ThemeInstallSource.Uploaded, isDeleted: false); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([brokenTheme])); - _mockThemeService.HasThemePack("user-theme").Returns(false); - _mockThemeService.GetBundledThemeArchivePaths().Returns([]); - _mockThemeRepository.DeleteByIdAsync(brokenTheme.Id, Arg.Any()).Returns(Error.Failure("Database.Error", "delete failed")); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeRepository.Received(1).DeleteByIdAsync(brokenTheme.Id, Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenNoThemeIsCurrent_ShouldActivateTheDefaultTheme() - { - // Arrange - ThemeEntity theme = _themeEntityFixture.Create(themeId: "default-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([theme])); - _mockThemeService.DefaultThemeId.Returns("default-theme"); - _mockThemeService.GetBundledThemeArchivePaths().Returns([]); - _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.From(Result.Updated)); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeRepository.Received(1).UpdateAsync( - Arg.Is(candidate => candidate.ThemeId == "default-theme" && candidate.IsCurrent == true), - Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenNoThemeIsCurrent_ShouldPreferTheConfiguredDefaultTheme() - { - // Arrange - ThemeEntity firstTheme = _themeEntityFixture.Create(themeId: "alpha-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false); - ThemeEntity defaultTheme = _themeEntityFixture.Create(themeId: "default-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([firstTheme, defaultTheme])); - _mockThemeService.DefaultThemeId.Returns("default-theme"); - _mockThemeService.GetBundledThemeArchivePaths().Returns([]); - _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.From(Result.Updated)); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeRepository.Received(1).UpdateAsync( - Arg.Is(candidate => candidate.ThemeId == "default-theme" && candidate.IsCurrent == true), - Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenAThemeIsAlreadyCurrent_ShouldNotChangeActivation() - { - // Arrange - ThemeEntity theme = _themeEntityFixture.Create(themeId: "current-theme", isCurrent: true, includeIsCurrent: true, installSource: ThemeInstallSource.Bundled, isDeleted: false); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([theme])); - _mockThemeService.GetBundledThemeArchivePaths().Returns([]); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeRepository.DidNotReceiveWithAnyArgs().UpdateAsync(default!, Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenBundledThemeArchiveFileCannotBeOpened_ShouldLogWarningAndContinue() - { - // Arrange - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); - string missingArchivePath = Path.Combine(_testRootPath, "bundled", "missing.zip"); - _mockThemeService.GetBundledThemeArchivePaths().Returns([missingArchivePath]); - _mockThemeService.ReadManifestFromArchiveAsync(missingArchivePath, Arg.Any()).Returns(_themeManifestDtoFixture.Create(id: "bundled-theme")); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); - await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenBundledThemeArchivePathIsADirectory_ShouldLogWarningAndContinue() - { - // Arrange - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); - string directoryPath = Path.Combine(_testRootPath, "not-an-archive"); - Directory.CreateDirectory(directoryPath); - _mockThemeService.GetBundledThemeArchivePaths().Returns([directoryPath]); - _mockThemeService.ReadManifestFromArchiveAsync(directoryPath, Arg.Any()).Returns(_themeManifestDtoFixture.Create(id: "bundled-theme")); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); - await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenSoftDeletingUnrestorableBundledThemeFails_ShouldLogWarningAndContinue() - { - // Arrange - ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "broken-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false); - ThemeEntity healthyTheme = _themeEntityFixture.Create(themeId: "healthy-theme", isCurrent: true, includeIsCurrent: true, installSource: ThemeInstallSource.Bundled, isDeleted: false); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([brokenTheme, healthyTheme])); - _mockThemeService.HasThemePack("broken-theme").Returns(false); - _mockThemeService.GetBundledThemeArchivePaths().Returns([]); - _mockThemeService.RestoreBundledThemeAsync("broken-theme", Arg.Any()).Returns(Error.Failure("Theme.Files", "restore failed")); - _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Error.Failure("Database.Error", "update failed")); - - // Act - await StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await _mockThemeRepository.Received(1).UpdateAsync( - Arg.Is(theme => theme.ThemeId == "broken-theme" && theme.IsDeleted && theme.IsCurrent == null), - Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task StartAsync_WhenCancellationIsRequestedWhileCleaningUp_ShouldLetTheCancellationPropagate() - { - // Arrange - ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "user-theme", installSource: ThemeInstallSource.Uploaded, isDeleted: false); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([brokenTheme])); - _mockThemeService.HasThemePack("user-theme").Returns(false); - _mockThemeService.GetBundledThemeArchivePaths().Returns([]); - _mockThemeRepository.DeleteByIdAsync(brokenTheme.Id, Arg.Any()) - .Returns(Task.FromException>(new OperationCanceledException())); - - // Act - Task executionTask = StartAndWaitForExecutionAsync(CreateSut()); - - // Assert - await Assert.ThrowsAnyAsync(() => executionTask); - await _mockUnitOfWork.DidNotReceiveWithAnyArgs().SaveChangesAsync(Arg.Any()); - } - - /// - /// Invokes the protected of the job and awaits its completion. - /// - /// The job to execute. - private static async Task StartAndWaitForExecutionAsync(ThemeDetectionSyncJob sut) - { - MethodInfo executeAsyncMethod = typeof(ThemeDetectionSyncJob).GetMethod("ExecuteAsync", BindingFlags.Instance | BindingFlags.NonPublic)!; - Task executingTask = (Task)executeAsyncMethod.Invoke(sut, [CancellationToken.None])!; - await executingTask; - } - - /// - /// Creates the system under test wired to the mocked dependencies. - /// - /// The created job instance. - private ThemeDetectionSyncJob CreateSut() - { - return new ThemeDetectionSyncJob(_mockServiceScopeFactory, _mockThemeService, _mockLogger); - } - - /// - /// Writes a bundled theme archive file into the per-test temporary directory. - /// - /// The theme id of the bundled archive. - /// The path of the written archive. - private string CreateBundledArchiveFile(string themeId) - { - string bundledPath = Path.Combine(_testRootPath, "bundled"); - Directory.CreateDirectory(bundledPath); - string archivePath = Path.Combine(bundledPath, $"{themeId}.zip"); - File.WriteAllBytes(archivePath, _themePackFixture.Create(themeId: themeId)); - return archivePath; - } -}