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

@@ -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,