mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 11:11:10 +00:00
Completes the scheduled jobs module with default jobs, a themed scheduler page and aligned recovery semantics
This commit is contained in:
1 parent
99a6159f7f
commit
4b7cfbbe11
67 files changed
+3324
-745
No files matched your search
+10
@@ -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>
|
||||
|
||||
+8
@@ -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);
|
||||
}
|
||||
+8
@@ -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;
|
||||
|
||||
+33
-9
@@ -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);
|
||||
}
|
||||
}
|
||||
+7
@@ -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;
|
||||
|
||||
|
||||
+1
@@ -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,
|
||||
|
||||
+4
@@ -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,
|
||||
|
||||
+1
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user