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

@@ -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
};
}
}