Completes the scheduled jobs module with default jobs, a themed scheduler page and aligned recovery semantics

This commit is contained in:
BinaryAlley committed 2026-09-04 13:56:04 -07:00
1 parent 99a6159f7f
commit 4b7cfbbe11
67 files changed
+3324 -745

No files matched your search

@@ -43,6 +43,16 @@ public class ScheduledJobExecutionEntity : IStorageEntity, IAuditableEntity
/// </summary>
public DateTime? CompletedOnUtc { get; init; }
/// <summary>
/// Gets a value indicating whether the execution cycle of the scheduled job was active when the execution started.
/// </summary>
/// <remarks>
/// 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 <see cref="IsCycleRun"/>, which records how the execution was triggered for the audit trail.
/// </remarks>
public required bool WasCycleActive { get; init; }
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
@@ -43,4 +43,12 @@ public interface IScheduledJobExecutionRepository : IRepository<ScheduledJobExec
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Success>> DeleteByScheduledJobIdAsync(Guid scheduledJobId, CancellationToken cancellationToken);
/// <summary>
/// Removes all the executions of the tasks of scheduled jobs that started before <paramref name="cutoffUtc"/>, from the storage medium.
/// </summary>
/// <param name="cutoffUtc">The exclusive lower bound of the retained interval, in UTC; executions that started before it are removed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Success>> DeleteOlderThanAsync(DateTime cutoffUtc, CancellationToken cancellationToken);
}
@@ -22,6 +22,14 @@ public interface IScheduledJobRepository : IRepository<ScheduledJobEntity>,
IUpdateRepositoryAction<ScheduledJobEntity>,
IDeleteByIdRepositoryAction<Guid>
{
/// <summary>
/// Gets a scheduled job identified by <paramref name="id"/> from the storage medium, without tracking it.
/// </summary>
/// <param name="id">The id of the scheduled job to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="ScheduledJobEntity"/> identified by <paramref name="id"/>, or an error.</returns>
Task<Result<ScheduledJobEntity?>> GetByIdWithoutTrackingAsync(Guid id, CancellationToken cancellationToken);
/// <summary>
/// Gets the scheduled jobs that have an active or running execution cycle, from the storage medium.
/// </summary>
@@ -43,4 +43,12 @@ public interface IDataSeedService
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Created>> SetAdminRoleToAdministratorAccount(Guid userId, CancellationToken cancellationToken);
/// <summary>
/// Sets up the default scheduled jobs, owned by the administrator account.
/// </summary>
/// <param name="adminUserId">The unique identifier of the administrator account that owns the default scheduled jobs.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Created>> SetDefaultScheduledJobsAsync(Guid adminUserId, CancellationToken cancellationToken);
}
@@ -94,6 +94,14 @@ public static class ScheduledJobEntityMapping
return Result.From<Schedule>(intervalScheduleResult.Value);
}
if (repositoryEntity.ScheduleType == ScheduleType.OnceAtStartup)
{
Result<OnceAtStartupSchedule> onceAtStartupScheduleResult = OnceAtStartupSchedule.Create();
if (onceAtStartupScheduleResult.IsFailure)
return onceAtStartupScheduleResult.Errors;
return Result.From<Schedule>(onceAtStartupScheduleResult.Value);
}
Result<DailySchedule> dailyScheduleResult = DailySchedule.Create(repositoryEntity.Hour ?? 0, repositoryEntity.Minute ?? 0);
if (dailyScheduleResult.IsFailure)
return dailyScheduleResult.Errors;
@@ -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<SetupApplicationCo
private readonly IQRCodeGenerator _qRCodeGenerator;
private readonly IDateTimeProvider _dateTimeProvider;
private readonly IDataSeedService _dataSeedService;
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IValidator<SetupApplicationCommand> _validator;
/// <summary>
@@ -44,6 +50,7 @@ public class SetupApplicationCommandHandler : ICommandHandler<SetupApplicationCo
/// <param name="qRCodeGenerator">Injected service for generating QR codes.</param>
/// <param name="dateTimeProvider">Injected service for time related concerns.</param>
/// <param name="dataSeedService">Injected service for the initial persistence medium data seed.</param>
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public SetupApplicationCommandHandler(
IUnitOfWork unitOfWork,
@@ -53,6 +60,7 @@ public class SetupApplicationCommandHandler : ICommandHandler<SetupApplicationCo
IQRCodeGenerator qRCodeGenerator,
IDateTimeProvider dateTimeProvider,
IDataSeedService dataSeedService,
IDomainEventsQueue domainEventsQueue,
IValidator<SetupApplicationCommand> validator)
{
_unitOfWork = unitOfWork;
@@ -62,6 +70,7 @@ public class SetupApplicationCommandHandler : ICommandHandler<SetupApplicationCo
_qRCodeGenerator = qRCodeGenerator;
_dateTimeProvider = dateTimeProvider;
_dataSeedService = dataSeedService;
_domainEventsQueue = domainEventsQueue;
_validator = validator;
}
@@ -79,7 +88,7 @@ public class SetupApplicationCommandHandler : ICommandHandler<SetupApplicationCo
if (validationResult.Count > 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<IEnumerable<UserEntity>> selectUsersResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (selectUsersResult.IsFailure)
return selectUsersResult.Errors;
@@ -100,23 +109,23 @@ public class SetupApplicationCommandHandler : ICommandHandler<SetupApplicationCo
CreatedBy = id,
LibraryScans = [],
};
// if the user enabled two factor auth, include a QR with the totp secret
// If the user enabled two factor auth, include a QR with the totp secret.
if (command.Use2fa)
{
// generate a TOTP secret
// Generate a TOTP secret.
byte[] secret = _totpTokenGenerator.GenerateSecret();
// convert the secret into a QR code for the user to scan
// Convert the secret into a QR code for the user to scan.
totpSecret = _qRCodeGenerator.GenerateQrCodeDataUri(command.Username!, secret);
// store the TOTP secret in the repository, encrypted
// Store the TOTP secret in the repository, encrypted.
user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(secret));
}
// insert the user
// Insert the user.
Result<Created> 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<Created> setPermissionsResult = await _dataSeedService.SetDefaultAuthorizationPermissionsAsync(id, cancellationToken).ConfigureAwait(false);
if (setPermissionsResult.IsFailure)
return setPermissionsResult.Errors;
@@ -133,8 +142,23 @@ public class SetupApplicationCommandHandler : ICommandHandler<SetupApplicationCo
if (setRoleToAdminResult.IsFailure)
return setRoleToAdminResult.Errors;
// TODO: insert the default admin profile preferences when they are implemented
// if 2FA was enabled, the TOTP secret needs to be delivered to the client unhashed, so it can be displayed
// Seed the default scheduled jobs, owned by the administrator account.
Result<Created> 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<IEnumerable<ScheduledJobEntity>> 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);
}
}
@@ -97,6 +97,13 @@ public class AddScheduledJobCommandHandler : ICommandHandler<AddScheduledJobComm
return dailyScheduleResult.Errors;
scheduleResult = Result.From<Schedule>(dailyScheduleResult.Value);
}
else if (command.ScheduleType == ScheduleType.OnceAtStartup)
{
Result<OnceAtStartupSchedule> onceAtStartupScheduleResult = OnceAtStartupSchedule.Create();
if (onceAtStartupScheduleResult.IsFailure)
return onceAtStartupScheduleResult.Errors;
scheduleResult = Result.From<Schedule>(onceAtStartupScheduleResult.Value);
}
else
return DomainErrors.Scheduling.InvalidScheduleType;
@@ -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,
@@ -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,
@@ -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,
@@ -44,22 +44,26 @@ public class ScheduledJobExecutionConfiguration : IEntityTypeConfiguration<Sched
builder.Property(execution => 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 });
@@ -0,0 +1,115 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Lumina.DataAccess.Common.Migrations
{
/// <inheritdoc />
public partial class AddsWasCycleActiveToScheduledJobExecutions : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<DateTime>(
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<Guid>(
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<DateTime>(
name: "CreatedOnUtc",
table: "ScheduledJobExecutions",
type: "TEXT",
nullable: false,
oldClrType: typeof(DateTime),
oldType: "TEXT")
.Annotation("Relational:ColumnOrder", 7)
.OldAnnotation("Relational:ColumnOrder", 6);
migrationBuilder.AlterColumn<Guid>(
name: "CreatedBy",
table: "ScheduledJobExecutions",
type: "TEXT",
nullable: false,
oldClrType: typeof(Guid),
oldType: "TEXT")
.Annotation("Relational:ColumnOrder", 8)
.OldAnnotation("Relational:ColumnOrder", 7);
migrationBuilder.AddColumn<bool>(
name: "WasCycleActive",
table: "ScheduledJobExecutions",
type: "INTEGER",
nullable: false,
defaultValue: false)
.Annotation("Relational:ColumnOrder", 6);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "WasCycleActive",
table: "ScheduledJobExecutions");
migrationBuilder.AlterColumn<DateTime>(
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<Guid>(
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<DateTime>(
name: "CreatedOnUtc",
table: "ScheduledJobExecutions",
type: "TEXT",
nullable: false,
oldClrType: typeof(DateTime),
oldType: "TEXT")
.Annotation("Relational:ColumnOrder", 6)
.OldAnnotation("Relational:ColumnOrder", 7);
migrationBuilder.AlterColumn<Guid>(
name: "CreatedBy",
table: "ScheduledJobExecutions",
type: "TEXT",
nullable: false,
oldClrType: typeof(Guid),
oldType: "TEXT")
.Annotation("Relational:ColumnOrder", 7)
.OldAnnotation("Relational:ColumnOrder", 8);
}
}
}
@@ -1167,11 +1167,11 @@ namespace Lumina.DataAccess.Common.Migrations
b.Property<Guid>("CreatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(7);
.HasColumnOrder(8);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(6);
.HasColumnOrder(7);
b.Property<bool>("IsCycleRun")
.HasColumnType("INTEGER")
@@ -1192,11 +1192,15 @@ namespace Lumina.DataAccess.Common.Migrations
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(9);
.HasColumnOrder(10);
b.Property<DateTime?>("UpdatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(8);
.HasColumnOrder(9);
b.Property<bool>("WasCycleActive")
.HasColumnType("INTEGER")
.HasColumnOrder(6);
b.HasKey("Id");
@@ -38,8 +38,9 @@ internal sealed class ScheduledJobExecutionRepository : IScheduledJobExecutionRe
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="ScheduledJobExecutionEntity"/> identified by <paramref name="id"/>, or an error.</returns>
public async Task<Result<ScheduledJobExecutionEntity?>> 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);
}
/// <summary>
@@ -67,8 +68,8 @@ internal sealed class ScheduledJobExecutionRepository : IScheduledJobExecutionRe
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Updated>> 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;
}
/// <summary>
/// Removes all the executions of the tasks of scheduled jobs that started before <paramref name="cutoffUtc"/>, from the storage medium.
/// </summary>
/// <param name="cutoffUtc">The exclusive lower bound of the retained interval, in UTC; executions that started before it are removed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Success>> 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;
}
}
@@ -39,7 +39,22 @@ internal sealed class ScheduledJobRepository : IScheduledJobRepository
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="ScheduledJobEntity"/> identified by <paramref name="id"/>, or an error.</returns>
public async Task<Result<ScheduledJobEntity?>> 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);
}
/// <summary>
/// Gets a scheduled job identified by <paramref name="id"/> from the storage medium, without tracking it.
/// </summary>
/// <param name="id">The id of the scheduled job to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="ScheduledJobEntity"/> identified by <paramref name="id"/>, or an error.</returns>
public async Task<Result<ScheduledJobEntity?>> 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
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Updated>> 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.
@@ -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
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> 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
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> 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
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> SetAdminRolePermissionsAsync(Guid userId, CancellationToken cancellationToken)
{
// get the admin role
// Get the admin role.
Result<RoleEntity?> 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<IEnumerable<PermissionEntity>> 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
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> SetAdminRoleToAdministratorAccount(Guid userId, CancellationToken cancellationToken)
{
// get the admin role
// Get the admin role.
Result<RoleEntity?> 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<UserEntity?> 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;
}
/// <summary>
/// Sets up the default scheduled jobs, owned by the administrator account.
/// </summary>
/// <param name="adminUserId">The unique identifier of the administrator account that owns the default scheduled jobs.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> 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<Created> insertScheduledJobResult = await _unitOfWork.ScheduledJobRepository.InsertAsync(defaultScheduledJob, cancellationToken).ConfigureAwait(false);
if (insertScheduledJobResult.IsFailure)
return insertScheduledJobResult.Errors;
}
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
return Result.Created;
}
/// <summary>
/// Creates a default scheduled job with its execution cycle active, owned by the administrator account identified by <paramref name="adminUserId"/>.
/// </summary>
/// <param name="name">The name of the default scheduled job.</param>
/// <param name="taskType">The type of the task executed by the default scheduled job.</param>
/// <param name="scheduleType">The type of the schedule of the default scheduled job.</param>
/// <param name="intervalMinutes">The interval in minutes of the schedule, when it is an interval schedule.</param>
/// <param name="hour">The hour of the schedule, when it is a daily schedule.</param>
/// <param name="minute">The minute of the schedule, when it is a daily schedule.</param>
/// <param name="adminUserId">The unique identifier of the administrator account that owns the default scheduled job.</param>
/// <returns>The created default scheduled job.</returns>
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
};
}
}
@@ -13,5 +13,10 @@ public enum ScheduleType
/// <summary>
/// The scheduled job repeats daily at a fixed hour and minute.
/// </summary>
DailyAtHourAndMinute
DailyAtHourAndMinute,
/// <summary>
/// The scheduled job fires its task once, every time the application starts.
/// </summary>
OnceAtStartup
}
@@ -13,5 +13,15 @@ public enum ScheduledTaskType
/// <summary>
/// The scheduled job cleans the temporary directory of the application.
/// </summary>
CleanTemporaryFiles
CleanTemporaryFiles,
/// <summary>
/// The scheduled job repairs the installed themes whose files are missing.
/// </summary>
RepairThemes,
/// <summary>
/// The scheduled job cleans the execution history of the scheduled jobs, keeping only the recent executions.
/// </summary>
CleanScheduledJobExecutionHistory
}
@@ -10,7 +10,7 @@ using System.Collections.Generic;
namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
/// <summary>
/// Represents a daily schedule for a scheduled job.
/// Value Object for the daily schedule for a scheduled job.
/// </summary>
public class DailySchedule : Schedule
{
@@ -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;
/// <summary>
/// Represents an interval based schedule for a scheduled job.
/// Value Object for the interval based schedule for a scheduled job.
/// </summary>
public class IntervalSchedule : Schedule
{
@@ -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;
/// <summary>
/// Value Object for the schedule that fires the task of the scheduled job once, at every application startup.
/// </summary>
public class OnceAtStartupSchedule : Schedule
{
/// <summary>
/// Gets the type of the schedule.
/// </summary>
public override ScheduleType ScheduleType { get; } = ScheduleType.OnceAtStartup;
/// <summary>
/// Initializes a new instance of the <see cref="OnceAtStartupSchedule"/> class.
/// </summary>
private OnceAtStartupSchedule()
{
}
/// <summary>
/// Creates a new instance of the <see cref="OnceAtStartupSchedule"/> class.
/// </summary>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="OnceAtStartupSchedule"/>, or an error message.
/// </returns>
public static Result<OnceAtStartupSchedule> Create()
{
return new OnceAtStartupSchedule();
}
/// <summary>
/// Calculates the delay until the next execution of the scheduled job, relative to <paramref name="utcNow"/>.
/// </summary>
/// <param name="utcNow">The current UTC date and time.</param>
/// <param name="timeZone">The time zone in which the daily hour and minute of the schedule are expressed.</param>
/// <returns>The delay until the next execution of the scheduled job.</returns>
/// <remarks>
/// 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.
/// </remarks>
public override TimeSpan GetDelayUntilNextExecution(DateTime utcNow, TimeZoneInfo timeZone)
{
return TimeSpan.MaxValue;
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object> GetEqualityComponents()
{
yield break;
}
}
@@ -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;
/// <summary>
/// Represents an abstract schedule for a scheduled job.
/// Value Object for the abstract schedule for a scheduled job.
/// </summary>
public abstract class Schedule : ValueObject
{
@@ -8,7 +8,7 @@ using System.Diagnostics;
namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
/// <summary>
/// Value object for the Id of a scheduled job.
/// Value Object for the Id of a scheduled job.
/// </summary>
[DebuggerDisplay("{Value}")]
public sealed class ScheduledJobId : EntityId<Guid>
@@ -139,9 +139,9 @@ public static class InfrastructureLayerServices
serviceProvider.GetRequiredService<ILogger<PluginDetectionSyncJob>>()));
services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService<PluginDetectionSyncJob>());
// 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<IThemeService, ThemeService>();
services.AddHostedService<ThemeDetectionSyncJob>();
// 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<IScheduledJobScheduler, ScheduledJobSchedulerJob>();
@@ -151,6 +151,8 @@ public static class InfrastructureLayerServices
services.AddScoped<IScheduledTaskExecutorFactory, ScheduledTaskExecutorFactory>();
services.AddScoped<MediaLibraryScanTaskExecutor>();
services.AddScoped<TemporaryFilesCleanupTaskExecutor>();
services.AddScoped<RepairThemesTaskExecutor>();
services.AddScoped<CleanScheduledJobExecutionHistoryTaskExecutor>();
return services;
}
@@ -18,12 +18,26 @@ public interface IScheduledJobRuntimeRegistry
/// <returns><see langword="true"/> when the cycle was started, <see langword="false"/> when a cycle was already running.</returns>
bool TryStartCycle(ScheduledJobId scheduledJobId, CancellationTokenSource cycleCancellationTokenSource);
/// <summary>
/// Gets a value indicating whether the execution cycle of the scheduled job identified by <paramref name="scheduledJobId"/> is currently running.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose cycle is checked.</param>
/// <returns><see langword="true"/> when a cycle is currently running, <see langword="false"/> otherwise.</returns>
bool HasActiveCycle(ScheduledJobId scheduledJobId);
/// <summary>
/// Stops the execution cycle of the scheduled job identified by <paramref name="scheduledJobId"/>.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose cycle is stopped.</param>
void StopCycle(ScheduledJobId scheduledJobId);
/// <summary>
/// Ends the execution cycle of the scheduled job identified by <paramref name="scheduledJobId"/>, when it was started with <paramref name="cycleCancellationTokenSource"/>.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose cycle is ended.</param>
/// <param name="cycleCancellationTokenSource">The cancellation token source of the cycle that is ending.</param>
void EndCycle(ScheduledJobId scheduledJobId, CancellationTokenSource cycleCancellationTokenSource);
/// <summary>
/// Attempts to reserve the execution slot of the scheduled job identified by <paramref name="scheduledJobId"/>.
/// </summary>
@@ -16,10 +16,28 @@ public sealed class ScheduledJobRuntimeRegistry : IScheduledJobRuntimeRegistry
/// </summary>
private sealed class ScheduledJobRuntimeState
{
/// <summary>
/// Object used to synchronize the access to the runtime state of the scheduled job.
/// </summary>
public readonly object SyncRoot = new();
/// <summary>
/// Gets or sets the cancellation token source of the running execution cycle, or <see langword="null"/> when no cycle is running.
/// </summary>
public CancellationTokenSource? CycleCancellationTokenSource;
/// <summary>
/// Gets the slot that guards a scheduled job against overlapping executions.
/// </summary>
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<ScheduledJobId, ScheduledJobRuntimeState> _runtimeStates = [];
/// <summary>
@@ -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;
}
}
/// <summary>
/// Gets a value indicating whether the execution cycle of the scheduled job identified by <paramref name="scheduledJobId"/> is currently running.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose cycle is checked.</param>
/// <returns><see langword="true"/> when a cycle is currently running, <see langword="false"/> otherwise.</returns>
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;
}
/// <summary>
@@ -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();
}
/// <summary>
/// Ends the execution cycle of the scheduled job identified by <paramref name="scheduledJobId"/>, when it was started with <paramref name="cycleCancellationTokenSource"/>.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose cycle is ended.</param>
/// <param name="cycleCancellationTokenSource">The cancellation token source of the cycle that is ending.</param>
/// <remarks>
/// 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.
/// </remarks>
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();
}
/// <summary>
/// Attempts to reserve the execution slot of the scheduled job identified by <paramref name="scheduledJobId"/>.
/// </summary>
@@ -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);
}
/// <summary>
@@ -67,7 +141,12 @@ public sealed class ScheduledJobRuntimeRegistry : IScheduledJobRuntimeRegistry
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose execution slot is released.</param>
public void ReleaseRunSlot(ScheduledJobId scheduledJobId)
{
if (_runtimeStates.TryGetValue(scheduledJobId, out ScheduledJobRuntimeState? state))
state.RunSlot.Release();
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();
}
}
@@ -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();
}
}
/// <summary>
@@ -119,47 +132,69 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS
/// <param name="stoppingToken">Cancellation token that can be used to stop the execution.</param>
private async Task RunCycleWorkerAsync(ScheduledJobId scheduledJobId, bool runImmediately, CancellationToken stoppingToken)
{
CancellationTokenSource cycleCancellationTokenSource = new();
// 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<ScheduledJob> scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity();
if (scheduledJobDomainResult.IsFailure)
return;
Result<Success> startExecutionResult = scheduledJobDomainResult.Value.MarkExecutionStarted(isCycleRun);
ScheduledJob scheduledJob = scheduledJobDomainResult.Value;
Result<Success> 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<IScheduledTaskExecutorFactory>();
IScheduledTaskExecutor taskExecutor = taskExecutorFactory.CreateExecutor(scheduledJobDomainResult.Value.TaskType);
Result<Success> executePayloadResult = await taskExecutor.ExecutePayloadAsync(scheduledJobDomainResult.Value, cancellationToken).ConfigureAwait(false);
if (executePayloadResult.IsFailure)
_logger.LogWarning("The task of the scheduled job '{ScheduledJobName}' failed: {Error}", scheduledJobDomainResult.Value.Name, executePayloadResult.FirstError.Description);
// Mark the task as completed. The same domain entity is reused, because it alone still tracks the run id of the
// current execution, which is required to raise the completion domain event; a fresh copy reloaded from the
// storage medium would no longer know which execution to complete.
Result<Success> completeExecutionResult = scheduledJobDomainResult.Value.MarkExecutionCompleted(isCycleRun);
if (completeExecutionResult.IsFailure)
// 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<IScheduledTaskExecutorFactory>();
IScheduledTaskExecutor taskExecutor = taskExecutorFactory.CreateExecutor(scheduledJob.TaskType);
Result<Success> 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);
}
/// <summary>
/// Completes the execution of the task of <paramref name="scheduledJob"/>, when the scheduled job is still running.
/// </summary>
/// <param name="scheduledJob">The scheduled job whose task execution is completed.</param>
/// <param name="unitOfWork">The unit of work of the current run, whose tracked entities are reused by the completion handlers.</param>
/// <param name="domainEventPublisher">The publisher used to publish the completion domain events.</param>
/// <param name="isCycleRun">Whether the execution was triggered by the execution cycle of the scheduled job, or it is a one time execution.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private async Task 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<ScheduledJobEntity?> 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<Success> 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);
}
}
/// <summary>
/// Reconciles the scheduled job identified by <paramref name="scheduledJobId"/> 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.
/// </summary>
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose interrupted execution is reconciled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The status the scheduled job was reconciled to, or its current status when no reconciliation was needed.</returns>
private async Task<ScheduledJobStatus> ReconcileInterruptedRunAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken)
{
try
{
await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = scope.ServiceProvider.GetRequiredService<IUnitOfWork>();
Result<ScheduledJobEntity?> getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken).ConfigureAwait(false);
if (getScheduledJobResult.IsFailure || getScheduledJobResult.Value is null)
return 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<ScheduledJobExecutionEntity?> 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<Updated> 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<Updated> 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;
}
}
/// <summary>
@@ -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);
}
/// <summary>
/// Creates a copy of <paramref name="scheduledJob"/> with the provided status and timestamps.
/// </summary>
/// <param name="scheduledJob">The scheduled job to copy.</param>
/// <param name="status">The status of the copy.</param>
/// <param name="lastStartedOnUtc">The last start time of the copy.</param>
/// <param name="lastCompletedOnUtc">The last completion time of the copy.</param>
/// <returns>The copy of the scheduled job.</returns>
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
};
}
/// <summary>
/// Creates a copy of <paramref name="execution"/> with the provided completion time.
/// </summary>
/// <param name="execution">The execution to copy.</param>
/// <param name="completedOnUtc">The completion time of the copy.</param>
/// <returns>The copy of the execution.</returns>
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
};
}
}
@@ -34,6 +34,8 @@ public class ScheduledTaskExecutorFactory : IScheduledTaskExecutorFactory
{
ScheduledTaskType.ScanMediaLibraries => _serviceProvider.GetRequiredService<MediaLibraryScanTaskExecutor>(),
ScheduledTaskType.CleanTemporaryFiles => _serviceProvider.GetRequiredService<TemporaryFilesCleanupTaskExecutor>(),
ScheduledTaskType.RepairThemes => _serviceProvider.GetRequiredService<RepairThemesTaskExecutor>(),
ScheduledTaskType.CleanScheduledJobExecutionHistory => _serviceProvider.GetRequiredService<CleanScheduledJobExecutionHistoryTaskExecutor>(),
_ => throw new ArgumentException($"Unsupported task type: {taskType}", nameof(taskType))
};
}
@@ -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;
/// <summary>
/// Task executor that cleans the execution history of the scheduled jobs, keeping only the executions of the past month.
/// </summary>
public class CleanScheduledJobExecutionHistoryTaskExecutor : IScheduledTaskExecutor
{
private readonly IDateTimeProvider _dateTimeProvider;
private readonly IUnitOfWork _unitOfWork;
private readonly ILogger<CleanScheduledJobExecutionHistoryTaskExecutor> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="CleanScheduledJobExecutionHistoryTaskExecutor"/> class.
/// </summary>
/// <param name="dateTimeProvider">Injected service for time related concerns.</param>
/// <param name="logger">Injected service for logging.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public CleanScheduledJobExecutionHistoryTaskExecutor(IDateTimeProvider dateTimeProvider, ILogger<CleanScheduledJobExecutionHistoryTaskExecutor> logger, IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_dateTimeProvider = dateTimeProvider;
_logger = logger;
}
/// <summary>
/// Removes the executions of the tasks of the scheduled jobs that are older than a month, keeping only the recent executions for audit.
/// </summary>
/// <param name="scheduledJob">The scheduled job whose task is executed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Success>> ExecutePayloadAsync(ScheduledJob scheduledJob, CancellationToken cancellationToken)
{
DateTime cutoffUtc = _dateTimeProvider.UtcNow.AddMonths(-1);
Result<Success> 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;
}
}
@@ -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;
/// <summary>
/// Task executor that repairs the installed themes whose files are missing.
/// </summary>
public class RepairThemesTaskExecutor : IScheduledTaskExecutor
{
private readonly IThemeService _themeService;
private readonly IUnitOfWork _unitOfWork;
private readonly ILogger<RepairThemesTaskExecutor> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="RepairThemesTaskExecutor"/> class.
/// </summary>
/// <param name="themeService">Injected service for the server-side storage and serving of theme packs.</param>
/// <param name="logger">Injected service for logging.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public RepairThemesTaskExecutor(IThemeService themeService, ILogger<RepairThemesTaskExecutor> logger, IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_themeService = themeService;
_logger = logger;
}
/// <summary>
/// Repairs the installed themes whose files are missing, reinstalling the files of the bundled themes from their shipped archives.
/// </summary>
/// <param name="scheduledJob">The scheduled job whose task is executed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Success>> ExecutePayloadAsync(ScheduledJob scheduledJob, CancellationToken cancellationToken)
{
// 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));
}
}
}
@@ -32,7 +32,7 @@ public sealed class ScheduledJobNotifier : IScheduledJobNotifier
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async Task SendScheduledJobsAsync(IReadOnlyList<ScheduledJobResponse> scheduledJobs, CancellationToken cancellationToken)
{
await _hubContext.Clients.All.ReceiveScheduledJobsAsync(scheduledJobs).ConfigureAwait(false);
await _hubContext.Clients.Group(ScheduledJobsHub.ADMINISTRATORS_GROUP).ReceiveScheduledJobsAsync(scheduledJobs).ConfigureAwait(false);
}
/// <summary>
@@ -42,7 +42,7 @@ public sealed class ScheduledJobNotifier : IScheduledJobNotifier
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async Task SendScheduledJobExecutionStartedAsync(ScheduledJobExecutionResponse execution, CancellationToken cancellationToken)
{
await _hubContext.Clients.All.ScheduledJobExecutionStartedAsync(execution).ConfigureAwait(false);
await _hubContext.Clients.Group(ScheduledJobsHub.ADMINISTRATORS_GROUP).ScheduledJobExecutionStartedAsync(execution).ConfigureAwait(false);
}
/// <summary>
@@ -52,6 +52,6 @@ public sealed class ScheduledJobNotifier : IScheduledJobNotifier
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async Task SendScheduledJobExecutionCompletedAsync(ScheduledJobExecutionResponse execution, CancellationToken cancellationToken)
{
await _hubContext.Clients.All.ScheduledJobExecutionCompletedAsync(execution).ConfigureAwait(false);
await _hubContext.Clients.Group(ScheduledJobsHub.ADMINISTRATORS_GROUP).ScheduledJobExecutionCompletedAsync(execution).ConfigureAwait(false);
}
}
@@ -17,6 +17,11 @@ namespace Lumina.Infrastructure.Core.Scheduling.Notifications;
[Authorize]
public class ScheduledJobsHub : Hub<IScheduledJobsClient>
{
/// <summary>
/// Name of the group that holds the connections of the verified administrator clients.
/// </summary>
public const string ADMINISTRATORS_GROUP = "Administrators";
private readonly IServiceScopeFactory _serviceScopeFactory;
/// <summary>
@@ -40,6 +45,9 @@ public class ScheduledJobsHub : Hub<IScheduledJobsClient>
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);
}
@@ -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;
/// <summary>
/// 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.
/// </summary>
internal sealed class ThemeDetectionSyncJob : BackgroundService
internal static class ThemeSynchronizer
{
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly IThemeService _themeService;
private readonly ILogger<ThemeDetectionSyncJob> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="ThemeDetectionSyncJob"/> class.
/// Installs the bundled themes into the storage medium and the theme storage, and repairs the installed themes whose files are missing.
/// </summary>
/// <param name="serviceScopeFactory">Injected factory for creating scopes in which services are requested.</param>
/// <param name="themeService">Injected service for the server-side storage and serving of theme packs.</param>
/// <param name="unitOfWork">The unit of work for interacting with the theme repository.</param>
/// <param name="logger">Injected logger used for logging.</param>
public ThemeDetectionSyncJob(IServiceScopeFactory serviceScopeFactory, IThemeService themeService, ILogger<ThemeDetectionSyncJob> logger)
{
_serviceScopeFactory = serviceScopeFactory;
_themeService = themeService;
_logger = logger;
}
/// <summary>
/// Method called when the background service starts.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
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<IUnitOfWork>();
Result<IEnumerable<ThemeEntity>> getThemesResult = await unitOfWork.ThemeRepository.GetAllAsync(cancellationToken);
Result<IEnumerable<ThemeEntity>> 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<ThemeEntity> themes = [.. getThemesResult.Value];
foreach (string archivePath in _themeService.GetBundledThemeArchivePaths())
foreach (string archivePath in themeService.GetBundledThemeArchivePaths())
{
Result<ThemeManifestDto> manifestResult = await _themeService.ReadManifestFromArchiveAsync(archivePath, cancellationToken);
Result<ThemeManifestDto> 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<ThemeManifestDto> installResult = await _themeService.InstallAsync(archive, cancellationToken);
Result<ThemeManifestDto> 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<Created> insertResult = await unitOfWork.ThemeRepository.InsertAsync(themeEntity, cancellationToken);
Result<Created> 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);
}
/// <summary>
/// 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.
/// </summary>
/// <param name="themeService">Injected service for the server-side storage and serving of theme packs.</param>
/// <param name="unitOfWork">The unit of work for interacting with the theme repository.</param>
/// <param name="themes">The installed themes read from the storage medium.</param>
/// <param name="logger">Injected logger used for logging.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private async Task CleanUpMissingThemePacksAsync(IUnitOfWork unitOfWork, IReadOnlyList<ThemeEntity> themes, CancellationToken cancellationToken)
private static async Task CleanUpMissingThemePacksAsync(IThemeService themeService, IUnitOfWork unitOfWork, IReadOnlyList<ThemeEntity> 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<ThemeEntity> 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<ThemeEntity> 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<Success> 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<Success> 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<Updated> updateResult = await unitOfWork.ThemeRepository.UpdateAsync(brokenTheme, cancellationToken);
Result<Updated> 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<Deleted> deleteResult = await unitOfWork.ThemeRepository.DeleteByIdAsync(brokenTheme.Id, cancellationToken);
Result<Deleted> 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
/// <summary>
/// Activates the configured default theme when no theme is currently active, so the application always has an active theme.
/// </summary>
/// <param name="themeService">Injected service for the server-side storage and serving of theme packs.</param>
/// <param name="unitOfWork">The unit of work for interacting with the theme repository.</param>
/// <param name="themes">The installed themes read from the storage medium.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private async Task EnsureCurrentThemeExistsAsync(IUnitOfWork unitOfWork, IReadOnlyList<ThemeEntity> themes, CancellationToken cancellationToken)
private static async Task EnsureCurrentThemeExistsAsync(IThemeService themeService, IUnitOfWork unitOfWork, IReadOnlyList<ThemeEntity> 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);
}
}
@@ -13,5 +13,10 @@ public enum ScheduleType
/// <summary>
/// The scheduled job repeats daily at a fixed hour and minute.
/// </summary>
DailyAtHourAndMinute
DailyAtHourAndMinute,
/// <summary>
/// The scheduled job fires its task once, every time the application starts.
/// </summary>
OnceAtStartup
}
@@ -13,5 +13,15 @@ public enum ScheduledTaskType
/// <summary>
/// The scheduled job cleans the temporary directory of the application.
/// </summary>
CleanTemporaryFiles
CleanTemporaryFiles,
/// <summary>
/// The scheduled job repairs the installed themes whose files are missing.
/// </summary>
RepairThemes,
/// <summary>
/// The scheduled job cleans the execution history of the scheduled jobs, keeping only the recent executions.
/// </summary>
CleanScheduledJobExecutionHistory
}
@@ -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<AddScheduledJobRequest, IRes
DontAutoTag();
Options(options => options.WithTags("Admin"));
Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE);
EnableAntiforgery();
}
/// <summary>
@@ -40,6 +40,7 @@ public class FireScheduledJobEndpoint : BaseEndpoint<FireScheduledJobRequest, IR
DontAutoTag();
Options(options => options.WithTags("Admin"));
Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE);
EnableAntiforgery();
}
/// <summary>
@@ -40,6 +40,7 @@ public class RemoveScheduledJobEndpoint : BaseEndpoint<RemoveScheduledJobRequest
DontAutoTag();
Options(options => options.WithTags("Admin"));
Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE);
EnableAntiforgery();
}
/// <summary>
@@ -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;
/// </summary>
public class SchedulerIndexViewEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
// 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<ServerConfigurationDto> _serverConfigurationOptions;
private readonly IUrlService _urlService;
private readonly ThemePageRenderer _themePageRenderer;
private readonly IStringLocalizer _localizer;
/// <summary>
/// Initializes a new instance of the <see cref="SchedulerIndexViewEndpoint"/> class.
/// </summary>
/// <param name="antiforgery">Injected service used to create the anti forgery tokens of the page.</param>
/// <param name="serverConfigurationOptions">Injected options used to read the address of the API server that hosts the scheduled jobs hub.</param>
/// <param name="urlService">Injected service for generating URLs from action and controller names, with localization.</param>
/// <param name="themePageRenderer">Injected service for rendering themed pages.</param>
/// <param name="stringLocalizerFactory">Injected factory used to create the localizer of the view resources.</param>
public SchedulerIndexViewEndpoint(
IAntiforgery antiforgery,
IOptionsSnapshot<ServerConfigurationDto> 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);
}
/// <summary>
/// Configures the endpoint.
/// </summary>
@@ -30,12 +74,65 @@ public class SchedulerIndexViewEndpoint : BaseEndpoint<EmptyRequest, IResult>
}
/// <summary>
/// Displays the scheduled jobs dashboard.
/// Displays the scheduled jobs dashboard, rendered by the active theme with a fallback to the Razor view.
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
{
return Task.FromResult(View("/Core/Views/Admin/Scheduler.cshtml"));
ServerConfigurationDto serverConfiguration = _serverConfigurationOptions.Value;
Dictionary<string, object?> localizedStrings = ThemePageDataFactory.CreateLocalizedStrings(_localizer);
ThemePageDto pageModel = new()
{
PageKey = VIEW_PAGE_KEY,
Title = _localizer["ScheduledJobs"].Value,
Description = string.Empty,
PageData = new Dictionary<string, object?>
{
["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<ThemePageRenderResultDto> 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<string, object?> { ["Title"] = pageModel.Title });
}
/// <summary>
/// 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.
/// </summary>
/// <param name="localizedStrings">The localized strings keyed by their resource names.</param>
/// <param name="prefix">The prefix of the resource names of the subgroup.</param>
/// <param name="names">The names of the subgroup entries, without the prefix.</param>
/// <returns>The localized strings of the subgroup keyed by their names.</returns>
private static IReadOnlyDictionary<string, object?> CreateSubgroup(IReadOnlyDictionary<string, object?> localizedStrings, string prefix, IReadOnlyList<string> names)
{
Dictionary<string, object?> subgroup = new(StringComparer.OrdinalIgnoreCase);
foreach (string name in names)
if (localizedStrings.TryGetValue($"{prefix}.{name}", out object? value))
subgroup[name] = value;
return subgroup;
}
}
@@ -40,6 +40,7 @@ public class StartScheduledJobEndpoint : BaseEndpoint<StartScheduledJobRequest,
DontAutoTag();
Options(options => options.WithTags("Admin"));
Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE);
EnableAntiforgery();
}
/// <summary>
@@ -40,6 +40,7 @@ public class StopScheduledJobEndpoint : BaseEndpoint<StopScheduledJobRequest, IR
DontAutoTag();
Options(options => options.WithTags("Admin"));
Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE);
EnableAntiforgery();
}
/// <summary>
@@ -40,6 +40,7 @@ public class UpdateSchedulerDisplayPreferencesEndpoint : BaseEndpoint<UpdateSche
DontAutoTag();
Options(options => options.WithTags("Admin"));
Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE);
EnableAntiforgery();
}
/// <summary>
@@ -159,4 +159,13 @@
<data name="JobNameRequired" xml:space="preserve">
<value>اسم المهمة مطلوب.</value>
</data>
<data name="TaskType.RepairThemes" xml:space="preserve">
<value>إصلاح السمات</value>
</data>
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
<value>تنظيف سجل الوظائف</value>
</data>
<data name="StartupSchedule" xml:space="preserve">
<value>عند بدء التشغيل</value>
</data>
</root>
@@ -159,4 +159,13 @@
<data name="JobNameRequired" xml:space="preserve">
<value>Der Aufgabenname ist erforderlich.</value>
</data>
<data name="TaskType.RepairThemes" xml:space="preserve">
<value>Designs reparieren</value>
</data>
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
<value>Jobverlauf bereinigen</value>
</data>
<data name="StartupSchedule" xml:space="preserve">
<value>Beim Start</value>
</data>
</root>
@@ -159,4 +159,13 @@
<data name="JobNameRequired" xml:space="preserve">
<value>The job name is required.</value>
</data>
<data name="TaskType.RepairThemes" xml:space="preserve">
<value>Repair themes</value>
</data>
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
<value>Clean job history</value>
</data>
<data name="StartupSchedule" xml:space="preserve">
<value>At startup</value>
</data>
</root>
@@ -159,4 +159,13 @@
<data name="JobNameRequired" xml:space="preserve">
<value>El nombre de la tarea es obligatorio.</value>
</data>
<data name="TaskType.RepairThemes" xml:space="preserve">
<value>Reparar temas</value>
</data>
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
<value>Limpiar historial de trabajos</value>
</data>
<data name="StartupSchedule" xml:space="preserve">
<value>Al inicio</value>
</data>
</root>
@@ -159,4 +159,13 @@
<data name="JobNameRequired" xml:space="preserve">
<value>Le nom de la tâche est requis.</value>
</data>
<data name="TaskType.RepairThemes" xml:space="preserve">
<value>Réparer les thèmes</value>
</data>
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
<value>Nettoyer l'historique des tâches</value>
</data>
<data name="StartupSchedule" xml:space="preserve">
<value>Au démarrage</value>
</data>
</root>
@@ -159,4 +159,13 @@
<data name="JobNameRequired" xml:space="preserve">
<value>Il nome dell'attività è obbligatorio.</value>
</data>
<data name="TaskType.RepairThemes" xml:space="preserve">
<value>Ripara i temi</value>
</data>
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
<value>Pulisci la cronologia dei processi</value>
</data>
<data name="StartupSchedule" xml:space="preserve">
<value>All'avvio</value>
</data>
</root>
@@ -159,4 +159,13 @@
<data name="JobNameRequired" xml:space="preserve">
<value>ジョブ名が必要です。</value>
</data>
<data name="TaskType.RepairThemes" xml:space="preserve">
<value>テーマを修復</value>
</data>
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
<value>ジョブ履歴を削除</value>
</data>
<data name="StartupSchedule" xml:space="preserve">
<value>起動時</value>
</data>
</root>
@@ -159,4 +159,13 @@
<data name="JobNameRequired" xml:space="preserve">
<value>The job name is required.</value>
</data>
<data name="TaskType.RepairThemes" xml:space="preserve">
<value>Repair themes</value>
</data>
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
<value>Clean job history</value>
</data>
<data name="StartupSchedule" xml:space="preserve">
<value>At startup</value>
</data>
</root>
@@ -159,4 +159,13 @@
<data name="JobNameRequired" xml:space="preserve">
<value>Numele sarcinii este obligatoriu.</value>
</data>
<data name="TaskType.RepairThemes" xml:space="preserve">
<value>Repară temele</value>
</data>
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
<value>Curăță istoricul proceselor</value>
</data>
<data name="StartupSchedule" xml:space="preserve">
<value>La pornire</value>
</data>
</root>
@@ -159,4 +159,13 @@
<data name="JobNameRequired" xml:space="preserve">
<value>Назва завдання обов'язкова.</value>
</data>
<data name="TaskType.RepairThemes" xml:space="preserve">
<value>Відновлення тем</value>
</data>
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
<value>Очистити історію завдань</value>
</data>
<data name="StartupSchedule" xml:space="preserve">
<value>Під час запуску</value>
</data>
</root>
@@ -159,4 +159,13 @@
<data name="JobNameRequired" xml:space="preserve">
<value>需要提供任务名称。</value>
</data>
<data name="TaskType.RepairThemes" xml:space="preserve">
<value>修复主题</value>
</data>
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
<value>清理作业历史</value>
</data>
<data name="StartupSchedule" xml:space="preserve">
<value>启动时</value>
</data>
</root>
@@ -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 @@
<div class="shine-effect" style="top: -4px;"></div>
<div class="enlightenment-option first-option" data-value="All">@_localizer["All"]</div>
<div class="enlightenment-option" data-value="ScanMediaLibraries">@_localizer["TaskType.ScanMediaLibraries"]</div>
<div class="enlightenment-option last-option" data-value="CleanTemporaryFiles">@_localizer["TaskType.CleanTemporaryFiles"]</div>
<div class="enlightenment-option" data-value="CleanTemporaryFiles">@_localizer["TaskType.CleanTemporaryFiles"]</div>
<div class="enlightenment-option" data-value="RepairThemes">@_localizer["TaskType.RepairThemes"]</div>
<div class="enlightenment-option last-option" data-value="CleanScheduledJobExecutionHistory">@_localizer["TaskType.CleanScheduledJobExecutionHistory"]</div>
</div>
</div>
</div>
@@ -109,7 +115,9 @@
<div class="enlightenment-dropdown">
<div class="shine-effect" style="top: -4px;"></div>
<div class="enlightenment-option first-option" data-value="ScanMediaLibraries">@_localizer["TaskType.ScanMediaLibraries"]</div>
<div class="enlightenment-option last-option" data-value="CleanTemporaryFiles">@_localizer["TaskType.CleanTemporaryFiles"]</div>
<div class="enlightenment-option" data-value="CleanTemporaryFiles">@_localizer["TaskType.CleanTemporaryFiles"]</div>
<div class="enlightenment-option" data-value="RepairThemes">@_localizer["TaskType.RepairThemes"]</div>
<div class="enlightenment-option last-option" data-value="CleanScheduledJobExecutionHistory">@_localizer["TaskType.CleanScheduledJobExecutionHistory"]</div>
</div>
</div>
</div>
@@ -124,7 +132,8 @@
<div class="enlightenment-dropdown">
<div class="shine-effect" style="top: -4px;"></div>
<div class="enlightenment-option first-option" data-value="WithIntervalInMinutes">@_localizer["IntervalSchedule"]</div>
<div class="enlightenment-option last-option" data-value="DailyAtHourAndMinute">@_localizer["DailySchedule"]</div>
<div class="enlightenment-option" data-value="DailyAtHourAndMinute">@_localizer["DailySchedule"]</div>
<div class="enlightenment-option last-option" data-value="OnceAtStartup">@_localizer["StartupSchedule"]</div>
</div>
</div>
</div>
@@ -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 = `
<td data-label="${escapeHtml(columnLabels[0])}">${job.id}</td>
<td data-label="${escapeHtml(columnLabels[1])}">${escapeHtml(job.name)}</td>
<td data-label="${escapeHtml(columnLabels[2])}">${schedulerStrings.taskTypeNames[job.taskType] ?? job.taskType}</td>
<td data-label="${escapeHtml(columnLabels[3])}">${isInterval ? schedulerStrings.interval : schedulerStrings.daily}</td>
<td data-label="${escapeHtml(columnLabels[3])}">${scheduleLabel}</td>
<td data-label="${escapeHtml(columnLabels[4])}">${isInterval ? job.intervalMinutes + ' ' + '@_localizer["MinutesShort"]' : '-'}</td>
<td data-label="${escapeHtml(columnLabels[5])}">${isInterval ? '-' : String(job.hour).padStart(2, '0') + ':' + String(job.minute).padStart(2, '0')}</td>
<td data-label="${escapeHtml(columnLabels[5])}">${isDaily ? String(job.hour).padStart(2, '0') + ':' + String(job.minute).padStart(2, '0') : '-'}</td>
<td data-label="${escapeHtml(columnLabels[6])}">${schedulerStrings.statusNames[job.status] ?? job.status}</td>
<td data-label="${escapeHtml(columnLabels[7])}">${formatDateTime(job.lastStartedOnUtc)}</td>
<td data-label="${escapeHtml(columnLabels[8])}">${formatDateTime(job.lastCompletedOnUtc)}</td>
@@ -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);
};