Adds scheduled job contracts and application handlers

This commit is contained in:
BinaryAlley committed 2026-09-03 12:48:53 -07:00
1 parent 7fbb4dc0d3
commit ea7e003bff
51 files changed
+2442

No files matched your search

@@ -0,0 +1,26 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.Scheduling.Commands.AddScheduledJob;
/// <summary>
/// Command for adding a scheduled job.
/// </summary>
/// <param name="Name">The name of the scheduled job.</param>
/// <param name="TaskType">The type of the task executed by the scheduled job.</param>
/// <param name="ScheduleType">The type of the schedule of the scheduled job.</param>
/// <param name="IntervalMinutes">The interval in minutes of the schedule, when the schedule type is <see cref="ScheduleType.WithIntervalInMinutes"/>.</param>
/// <param name="Hour">The hour of the schedule, when the schedule type is <see cref="ScheduleType.DailyAtHourAndMinute"/>.</param>
/// <param name="Minute">The minute of the schedule, when the schedule type is <see cref="ScheduleType.DailyAtHourAndMinute"/>.</param>
[DebuggerDisplay("Name: {Name}")]
public record AddScheduledJobCommand(
string Name,
ScheduledTaskType TaskType,
ScheduleType ScheduleType,
int? IntervalMinutes,
int? Hour,
int? Minute
) : ICommand;
@@ -0,0 +1,122 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Scheduling.Commands.AddScheduledJob;
/// <summary>
/// Handler for the command to add a scheduled job.
/// </summary>
public class AddScheduledJobCommandHandler : ICommandHandler<AddScheduledJobCommand, Result<ScheduledJobResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IValidator<AddScheduledJobCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="AddScheduledJobCommandHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public AddScheduledJobCommandHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IDomainEventsQueue domainEventsQueue,
IUnitOfWork unitOfWork,
IValidator<AddScheduledJobCommand> validator)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
_domainEventsQueue = domainEventsQueue;
_validator = validator;
}
/// <summary>
/// Handles the command to add a scheduled job.
/// </summary>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="ScheduledJobResponse"/>, or an error message.
/// </returns>
public async Task<Result<ScheduledJobResponse>> HandleAsync(AddScheduledJobCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// Only administrators can schedule jobs.
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
// Create the schedule of the scheduled job, based on its type.
Result<Schedule> scheduleResult;
if (command.ScheduleType == ScheduleType.WithIntervalInMinutes)
{
Result<IntervalSchedule> intervalScheduleResult = IntervalSchedule.Create(command.IntervalMinutes ?? 0);
if (intervalScheduleResult.IsFailure)
return intervalScheduleResult.Errors;
scheduleResult = Result.From<Schedule>(intervalScheduleResult.Value);
}
else if (command.ScheduleType == ScheduleType.DailyAtHourAndMinute)
{
Result<DailySchedule> dailyScheduleResult = DailySchedule.Create(command.Hour ?? 0, command.Minute ?? 0);
if (dailyScheduleResult.IsFailure)
return dailyScheduleResult.Errors;
scheduleResult = Result.From<Schedule>(dailyScheduleResult.Value);
}
else
return DomainErrors.Scheduling.InvalidScheduleType;
// Create a domain scheduled job object.
Result<ScheduledJob> createScheduledJobResult = ScheduledJob.Create(command.Name, command.TaskType, scheduleResult.Value, UserId.Create(userId));
if (createScheduledJobResult.IsFailure)
return createScheduledJobResult.Errors;
createScheduledJobResult.Value.Add();
// Convert the domain scheduled job to a repository entity, insert it, and save the changes.
ScheduledJobEntity persistenceScheduledJob = createScheduledJobResult.Value.ToRepositoryEntity();
Result<Created> insertScheduledJobResult = await _unitOfWork.ScheduledJobRepository.InsertAsync(persistenceScheduledJob, cancellationToken).ConfigureAwait(false);
if (insertScheduledJobResult.IsFailure)
return insertScheduledJobResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// Queue any domain events.
foreach (IDomainEvent domainEvent in createScheduledJobResult.Value.GetDomainEvents())
_domainEventsQueue.Enqueue(domainEvent);
return createScheduledJobResult.Value.ToResponse();
}
}
@@ -0,0 +1,64 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
#endregion
namespace Lumina.Application.Core.Scheduling.Commands.AddScheduledJob;
/// <summary>
/// Validates the needed validation rules for <see cref="AddScheduledJobCommand"/>.
/// </summary>
public class AddScheduledJobCommandValidator : AbstractValidator<AddScheduledJobCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="AddScheduledJobCommandValidator"/> class.
/// </summary>
public AddScheduledJobCommandValidator()
{
RuleFor(command => command.Name)
.NotEmpty()
.WithError(Errors.Scheduling.ScheduledJobNameCannotBeEmpty)
.MaximumLength(80)
.WithError(Errors.Scheduling.ScheduledJobNameCannotBeEmpty);
RuleFor(command => command.TaskType)
.IsInEnum()
.WithError(Errors.Scheduling.InvalidScheduleType);
RuleFor(command => command.ScheduleType)
.IsInEnum()
.WithError(Errors.Scheduling.InvalidScheduleType);
RuleFor(command => command.IntervalMinutes)
.Must(intervalMinutes => intervalMinutes is null || intervalMinutes > 0)
.WithError(Errors.Scheduling.IntervalMinutesMustBePositive)
.When(command => command.ScheduleType == ScheduleType.WithIntervalInMinutes);
RuleFor(command => command.IntervalMinutes)
.Must(intervalMinutes => intervalMinutes is not null)
.WithError(Errors.Scheduling.IntervalMinutesMustBePositive)
.When(command => command.ScheduleType == ScheduleType.WithIntervalInMinutes);
RuleFor(command => command.Hour)
.Must(hour => hour is not null)
.WithError(Errors.Scheduling.HourMustBeBetweenZeroAndTwentyThree)
.When(command => command.ScheduleType == ScheduleType.DailyAtHourAndMinute);
RuleFor(command => command.Minute)
.Must(minute => minute is not null)
.WithError(Errors.Scheduling.MinuteMustBeBetweenZeroAndFiftyNine)
.When(command => command.ScheduleType == ScheduleType.DailyAtHourAndMinute);
RuleFor(command => command.Hour)
.InclusiveBetween(0, 23)
.WithError(Errors.Scheduling.HourMustBeBetweenZeroAndTwentyThree)
.When(command => command.ScheduleType == ScheduleType.DailyAtHourAndMinute);
RuleFor(command => command.Minute)
.InclusiveBetween(0, 59)
.WithError(Errors.Scheduling.MinuteMustBeBetweenZeroAndFiftyNine)
.When(command => command.ScheduleType == ScheduleType.DailyAtHourAndMinute);
}
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.Scheduling.Commands.FireScheduledJob;
/// <summary>
/// Command for firing the task of a scheduled job once, without affecting its execution cycle.
/// </summary>
/// <param name="ScheduledJobId">The unique identifier of the scheduled job whose task is fired.</param>
[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
public record FireScheduledJobCommand(
Guid ScheduledJobId
) : ICommand;
@@ -0,0 +1,102 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Scheduling.Commands.FireScheduledJob;
/// <summary>
/// Handler for the command to fire the task of a scheduled job once.
/// </summary>
public class FireScheduledJobCommandHandler : ICommandHandler<FireScheduledJobCommand, Result<ScheduledJobResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IValidator<FireScheduledJobCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="FireScheduledJobCommandHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public FireScheduledJobCommandHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IDomainEventsQueue domainEventsQueue,
IUnitOfWork unitOfWork,
IValidator<FireScheduledJobCommand> validator)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
_domainEventsQueue = domainEventsQueue;
_validator = validator;
}
/// <summary>
/// Handles the command to fire the task of a scheduled job once.
/// </summary>
/// <param name="command">The command to be handled.</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="ScheduledJobResponse"/>, or an error message.
/// </returns>
public async Task<Result<ScheduledJobResponse>> HandleAsync(FireScheduledJobCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// Only administrators can fire scheduled jobs.
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
// Get the scheduled job from the storage medium.
Result<ScheduledJobEntity?> getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false);
if (getScheduledJobResult.IsFailure)
return getScheduledJobResult.Errors;
if (getScheduledJobResult.Value is null)
return DomainErrors.Scheduling.ScheduledJobNotFound;
// Convert the repository entity to a domain entity, and guard the fire against a currently running task.
Result<ScheduledJob> scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity();
if (scheduledJobDomainResult.IsFailure)
return scheduledJobDomainResult.Errors;
Result<Success> fireResult = scheduledJobDomainResult.Value.Fire();
if (fireResult.IsFailure)
return fireResult.Errors;
// Queue the domain event that requests a one time execution of the task of the scheduled job.
foreach (IDomainEvent domainEvent in scheduledJobDomainResult.Value.GetDomainEvents())
_domainEventsQueue.Enqueue(domainEvent);
return scheduledJobDomainResult.Value.ToResponse();
}
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
#endregion
namespace Lumina.Application.Core.Scheduling.Commands.FireScheduledJob;
/// <summary>
/// Validates the needed validation rules for <see cref="FireScheduledJobCommand"/>.
/// </summary>
public class FireScheduledJobCommandValidator : AbstractValidator<FireScheduledJobCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="FireScheduledJobCommandValidator"/> class.
/// </summary>
public FireScheduledJobCommandValidator()
{
RuleFor(command => command.ScheduledJobId)
.NotEmpty()
.WithError(Errors.Scheduling.ScheduledJobNotFound);
}
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob;
/// <summary>
/// Command for removing a scheduled job.
/// </summary>
/// <param name="ScheduledJobId">The unique identifier of the scheduled job to remove.</param>
[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
public record RemoveScheduledJobCommand(
Guid ScheduledJobId
) : ICommand;
@@ -0,0 +1,114 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Scheduling;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Scheduling;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob;
/// <summary>
/// Handler for the command to remove a scheduled job.
/// </summary>
public class RemoveScheduledJobCommandHandler : ICommandHandler<RemoveScheduledJobCommand, Result<Success>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IScheduledJobScheduler _scheduledJobScheduler;
private readonly IValidator<RemoveScheduledJobCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="RemoveScheduledJobCommandHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
/// <param name="scheduledJobScheduler">Injected service that schedules and executes the tasks of scheduled jobs.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public RemoveScheduledJobCommandHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IDomainEventsQueue domainEventsQueue,
IScheduledJobScheduler scheduledJobScheduler,
IUnitOfWork unitOfWork,
IValidator<RemoveScheduledJobCommand> validator)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
_domainEventsQueue = domainEventsQueue;
_scheduledJobScheduler = scheduledJobScheduler;
_validator = validator;
}
/// <summary>
/// Handles the command to remove a scheduled job.
/// </summary>
/// <param name="command">The command to be handled.</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>> HandleAsync(RemoveScheduledJobCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// Only administrators can remove scheduled jobs.
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
// Get the scheduled job from the storage medium.
Result<ScheduledJobEntity?> getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false);
if (getScheduledJobResult.IsFailure)
return getScheduledJobResult.Errors;
if (getScheduledJobResult.Value is null)
return DomainErrors.Scheduling.ScheduledJobNotFound;
// Stop the execution cycle of the scheduled job, if it has one.
Result<ScheduledJob> scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity();
if (scheduledJobDomainResult.IsFailure)
return scheduledJobDomainResult.Errors;
await _scheduledJobScheduler.StopCycleAsync(scheduledJobDomainResult.Value.Id, cancellationToken).ConfigureAwait(false);
// Remove the executions and the scheduled job itself from the storage medium.
Result<Success> deleteExecutionsResult = await _unitOfWork.ScheduledJobExecutionRepository.DeleteByScheduledJobIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false);
if (deleteExecutionsResult.IsFailure)
return deleteExecutionsResult.Errors;
Result<Deleted> deleteScheduledJobResult = await _unitOfWork.ScheduledJobRepository.DeleteByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false);
if (deleteScheduledJobResult.IsFailure)
return deleteScheduledJobResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// Queue any domain events.
scheduledJobDomainResult.Value.Remove();
foreach (IDomainEvent domainEvent in scheduledJobDomainResult.Value.GetDomainEvents())
_domainEventsQueue.Enqueue(domainEvent);
return Result.Success;
}
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
#endregion
namespace Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob;
/// <summary>
/// Validates the needed validation rules for <see cref="RemoveScheduledJobCommand"/>.
/// </summary>
public class RemoveScheduledJobCommandValidator : AbstractValidator<RemoveScheduledJobCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="RemoveScheduledJobCommandValidator"/> class.
/// </summary>
public RemoveScheduledJobCommandValidator()
{
RuleFor(command => command.ScheduledJobId)
.NotEmpty()
.WithError(Errors.Scheduling.ScheduledJobNotFound);
}
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.Scheduling.Commands.StartScheduledJob;
/// <summary>
/// Command for starting the execution cycle of a scheduled job.
/// </summary>
/// <param name="ScheduledJobId">The unique identifier of the scheduled job whose execution cycle is started.</param>
[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
public record StartScheduledJobCommand(
Guid ScheduledJobId
) : ICommand;
@@ -0,0 +1,109 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Scheduling.Commands.StartScheduledJob;
/// <summary>
/// Handler for the command to start the execution cycle of a scheduled job.
/// </summary>
public class StartScheduledJobCommandHandler : ICommandHandler<StartScheduledJobCommand, Result<ScheduledJobResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IValidator<StartScheduledJobCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="StartScheduledJobCommandHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public StartScheduledJobCommandHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IDomainEventsQueue domainEventsQueue,
IUnitOfWork unitOfWork,
IValidator<StartScheduledJobCommand> validator)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
_domainEventsQueue = domainEventsQueue;
_validator = validator;
}
/// <summary>
/// Handles the command to start the execution cycle of a scheduled job.
/// </summary>
/// <param name="command">The command to be handled.</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="ScheduledJobResponse"/>, or an error message.
/// </returns>
public async Task<Result<ScheduledJobResponse>> HandleAsync(StartScheduledJobCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// Only administrators can start scheduled jobs.
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
// Get the scheduled job from the storage medium.
Result<ScheduledJobEntity?> getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false);
if (getScheduledJobResult.IsFailure)
return getScheduledJobResult.Errors;
if (getScheduledJobResult.Value is null)
return DomainErrors.Scheduling.ScheduledJobNotFound;
// Convert the repository entity to a domain entity, and start its execution cycle.
Result<ScheduledJob> scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity();
if (scheduledJobDomainResult.IsFailure)
return scheduledJobDomainResult.Errors;
Result<Success> startCycleResult = scheduledJobDomainResult.Value.StartCycle();
if (startCycleResult.IsFailure)
return startCycleResult.Errors;
// Persist the new status of the scheduled job.
Result<Updated> updateScheduledJobResult = await _unitOfWork.ScheduledJobRepository.UpdateAsync(scheduledJobDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
if (updateScheduledJobResult.IsFailure)
return updateScheduledJobResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// Queue any domain events.
foreach (IDomainEvent domainEvent in scheduledJobDomainResult.Value.GetDomainEvents())
_domainEventsQueue.Enqueue(domainEvent);
return scheduledJobDomainResult.Value.ToResponse();
}
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
#endregion
namespace Lumina.Application.Core.Scheduling.Commands.StartScheduledJob;
/// <summary>
/// Validates the needed validation rules for <see cref="StartScheduledJobCommand"/>.
/// </summary>
public class StartScheduledJobCommandValidator : AbstractValidator<StartScheduledJobCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="StartScheduledJobCommandValidator"/> class.
/// </summary>
public StartScheduledJobCommandValidator()
{
RuleFor(command => command.ScheduledJobId)
.NotEmpty()
.WithError(Errors.Scheduling.ScheduledJobNotFound);
}
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.Scheduling.Commands.StopScheduledJob;
/// <summary>
/// Command for stopping the execution cycle of a scheduled job.
/// </summary>
/// <param name="ScheduledJobId">The unique identifier of the scheduled job whose execution cycle is stopped.</param>
[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
public record StopScheduledJobCommand(
Guid ScheduledJobId
) : ICommand;
@@ -0,0 +1,116 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Scheduling;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Scheduling.Commands.StopScheduledJob;
/// <summary>
/// Handler for the command to stop the execution cycle of a scheduled job.
/// </summary>
public class StopScheduledJobCommandHandler : ICommandHandler<StopScheduledJobCommand, Result<ScheduledJobResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IScheduledJobScheduler _scheduledJobScheduler;
private readonly IValidator<StopScheduledJobCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="StopScheduledJobCommandHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
/// <param name="scheduledJobScheduler">Injected service that schedules and executes the tasks of scheduled jobs.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public StopScheduledJobCommandHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IDomainEventsQueue domainEventsQueue,
IScheduledJobScheduler scheduledJobScheduler,
IUnitOfWork unitOfWork,
IValidator<StopScheduledJobCommand> validator)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
_domainEventsQueue = domainEventsQueue;
_scheduledJobScheduler = scheduledJobScheduler;
_validator = validator;
}
/// <summary>
/// Handles the command to stop the execution cycle of a scheduled job.
/// </summary>
/// <param name="command">The command to be handled.</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="ScheduledJobResponse"/>, or an error message.
/// </returns>
public async Task<Result<ScheduledJobResponse>> HandleAsync(StopScheduledJobCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// Only administrators can stop scheduled jobs.
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
// Get the scheduled job from the storage medium.
Result<ScheduledJobEntity?> getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false);
if (getScheduledJobResult.IsFailure)
return getScheduledJobResult.Errors;
if (getScheduledJobResult.Value is null)
return DomainErrors.Scheduling.ScheduledJobNotFound;
// Convert the repository entity to a domain entity, and stop its execution cycle.
Result<ScheduledJob> scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity();
if (scheduledJobDomainResult.IsFailure)
return scheduledJobDomainResult.Errors;
Result<Success> stopCycleResult = scheduledJobDomainResult.Value.StopCycle();
if (stopCycleResult.IsFailure)
return stopCycleResult.Errors;
// Persist the new status of the scheduled job.
Result<Updated> updateScheduledJobResult = await _unitOfWork.ScheduledJobRepository.UpdateAsync(scheduledJobDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
if (updateScheduledJobResult.IsFailure)
return updateScheduledJobResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// Stop the execution cycle in the scheduler service.
await _scheduledJobScheduler.StopCycleAsync(scheduledJobDomainResult.Value.Id, cancellationToken).ConfigureAwait(false);
// Queue any domain events.
foreach (IDomainEvent domainEvent in scheduledJobDomainResult.Value.GetDomainEvents())
_domainEventsQueue.Enqueue(domainEvent);
return scheduledJobDomainResult.Value.ToResponse();
}
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
#endregion
namespace Lumina.Application.Core.Scheduling.Commands.StopScheduledJob;
/// <summary>
/// Validates the needed validation rules for <see cref="StopScheduledJobCommand"/>.
/// </summary>
public class StopScheduledJobCommandValidator : AbstractValidator<StopScheduledJobCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="StopScheduledJobCommandValidator"/> class.
/// </summary>
public StopScheduledJobCommandValidator()
{
RuleFor(command => command.ScheduledJobId)
.NotEmpty()
.WithError(Errors.Scheduling.ScheduledJobNotFound);
}
}
@@ -0,0 +1,51 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.Scheduling;
using Lumina.Application.Core.Scheduling.Notifications;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.Scheduling.Events;
/// <summary>
/// Handler for the domain event raised when a scheduled job is added.
/// </summary>
public class ScheduledJobAddedDomainEventHandler : IDomainEventHandler<ScheduledJobAddedDomainEvent>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IScheduledJobNotifier _scheduledJobNotifier;
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobAddedDomainEventHandler"/> class.
/// </summary>
/// <param name="scheduledJobNotifier">Injected service for notifying the scheduled job changes to SignalR clients.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public ScheduledJobAddedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_scheduledJobNotifier = scheduledJobNotifier;
}
/// <summary>
/// Handles the event raised when a scheduled job is added.
/// </summary>
/// <param name="domainEvent">The domain event to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async ValueTask HandleAsync(ScheduledJobAddedDomainEvent domainEvent, CancellationToken cancellationToken)
{
Result<IEnumerable<ScheduledJobEntity>> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (getScheduledJobsResult.IsFailure)
throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
IReadOnlyList<ScheduledJobResponse> scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
}
}
@@ -0,0 +1,58 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Scheduling;
using Lumina.Application.Common.Mapping.Scheduling;
using Lumina.Application.Core.Scheduling.Notifications;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.Scheduling.Events;
/// <summary>
/// Handler for the domain event raised when the execution cycle of a scheduled job is started.
/// </summary>
public class ScheduledJobCycleStartedDomainEventHandler : IDomainEventHandler<ScheduledJobCycleStartedDomainEvent>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IScheduledJobNotifier _scheduledJobNotifier;
private readonly IScheduledJobScheduler _scheduledJobScheduler;
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobCycleStartedDomainEventHandler"/> class.
/// </summary>
/// <param name="scheduledJobNotifier">Injected service for notifying the scheduled job changes to SignalR clients.</param>
/// <param name="scheduledJobScheduler">Injected service that schedules and executes the tasks of scheduled jobs.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public ScheduledJobCycleStartedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IScheduledJobScheduler scheduledJobScheduler, IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_scheduledJobNotifier = scheduledJobNotifier;
_scheduledJobScheduler = scheduledJobScheduler;
}
/// <summary>
/// Handles the event raised when the execution cycle of a scheduled job is started.
/// </summary>
/// <param name="domainEvent">The domain event to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async ValueTask HandleAsync(ScheduledJobCycleStartedDomainEvent domainEvent, CancellationToken cancellationToken)
{
// Start the execution cycle in the scheduler service, which runs the task of the scheduled job once immediately and then on its schedule.
await _scheduledJobScheduler.StartCycleAsync(domainEvent.ScheduledJobId, cancellationToken).ConfigureAwait(false);
Result<IEnumerable<ScheduledJobEntity>> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (getScheduledJobsResult.IsFailure)
throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
IReadOnlyList<ScheduledJobResponse> scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
}
}
@@ -0,0 +1,51 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.Scheduling;
using Lumina.Application.Core.Scheduling.Notifications;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.Scheduling.Events;
/// <summary>
/// Handler for the domain event raised when the execution cycle of a scheduled job is stopped.
/// </summary>
public class ScheduledJobCycleStoppedDomainEventHandler : IDomainEventHandler<ScheduledJobCycleStoppedDomainEvent>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IScheduledJobNotifier _scheduledJobNotifier;
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobCycleStoppedDomainEventHandler"/> class.
/// </summary>
/// <param name="scheduledJobNotifier">Injected service for notifying the scheduled job changes to SignalR clients.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public ScheduledJobCycleStoppedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_scheduledJobNotifier = scheduledJobNotifier;
}
/// <summary>
/// Handles the event raised when the execution cycle of a scheduled job is stopped.
/// </summary>
/// <param name="domainEvent">The domain event to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async ValueTask HandleAsync(ScheduledJobCycleStoppedDomainEvent domainEvent, CancellationToken cancellationToken)
{
Result<IEnumerable<ScheduledJobEntity>> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (getScheduledJobsResult.IsFailure)
throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
IReadOnlyList<ScheduledJobResponse> scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
}
}
@@ -0,0 +1,147 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.Scheduling;
using Lumina.Application.Core.Scheduling.Notifications;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.Scheduling.Events;
/// <summary>
/// Handler for the domain event raised when the task of a scheduled job completes its execution.
/// </summary>
public class ScheduledJobExecutionCompletedDomainEventHandler : IDomainEventHandler<ScheduledJobExecutionCompletedDomainEvent>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IScheduledJobNotifier _scheduledJobNotifier;
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobExecutionCompletedDomainEventHandler"/> class.
/// </summary>
/// <param name="scheduledJobNotifier">Injected service for notifying the scheduled job changes to SignalR clients.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public ScheduledJobExecutionCompletedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_scheduledJobNotifier = scheduledJobNotifier;
}
/// <summary>
/// Handles the event raised when the task of a scheduled job completes its execution.
/// </summary>
/// <param name="domainEvent">The domain event to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async ValueTask HandleAsync(ScheduledJobExecutionCompletedDomainEvent domainEvent, CancellationToken cancellationToken)
{
// Get the scheduled job from the repository.
Result<ScheduledJobEntity?> getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken).ConfigureAwait(false);
if (getScheduledJobResult.IsFailure)
throw new EventualConsistencyException(getScheduledJobResult.FirstError, getScheduledJobResult.Errors);
if (getScheduledJobResult.Value is null)
throw new EventualConsistencyException(Errors.Scheduling.ScheduledJobNotFound);
ScheduledJobEntity scheduledJob = getScheduledJobResult.Value;
// A cycle run returns the scheduled job to its active status, a one time execution completes it.
ScheduledJobStatus status = domainEvent.IsCycleRun ? ScheduledJobStatus.Active : ScheduledJobStatus.Completed;
ScheduledJobEntity updatedScheduledJob = CreateUpdatedScheduledJob(scheduledJob, status, scheduledJob.LastStartedOnUtc, domainEvent.CompletedOnUtc);
Result<Updated> updateScheduledJobResult = await _unitOfWork.ScheduledJobRepository.UpdateAsync(updatedScheduledJob, cancellationToken).ConfigureAwait(false);
if (updateScheduledJobResult.IsFailure)
throw new EventualConsistencyException(updateScheduledJobResult.FirstError, updateScheduledJobResult.Errors);
// Mark the execution of the task of the scheduled job as completed.
Result<ScheduledJobExecutionEntity?> getExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, cancellationToken).ConfigureAwait(false);
if (getExecutionResult.IsFailure)
throw new EventualConsistencyException(getExecutionResult.FirstError, getExecutionResult.Errors);
if (getExecutionResult.Value is null)
throw new EventualConsistencyException(Errors.Scheduling.ScheduledJobExecutionNotFound);
ScheduledJobExecutionEntity execution = getExecutionResult.Value;
ScheduledJobExecutionEntity updatedExecution = CreateUpdatedExecution(execution, domainEvent.CompletedOnUtc);
Result<Updated> updateExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.UpdateAsync(updatedExecution, cancellationToken).ConfigureAwait(false);
if (updateExecutionResult.IsFailure)
throw new EventualConsistencyException(updateExecutionResult.FirstError, updateExecutionResult.Errors);
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// Notify the SignalR clients about the current scheduled jobs and the completed execution.
await NotifyCurrentScheduledJobsAsync(cancellationToken).ConfigureAwait(false);
await _scheduledJobNotifier.SendScheduledJobExecutionCompletedAsync(updatedExecution.ToResponse(), cancellationToken).ConfigureAwait(false);
}
/// <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 CreateUpdatedExecution(ScheduledJobExecutionEntity execution, DateTime? completedOnUtc)
{
return new ScheduledJobExecutionEntity
{
Id = execution.Id,
ScheduledJobId = execution.ScheduledJobId,
TaskType = execution.TaskType,
IsCycleRun = execution.IsCycleRun,
StartedOnUtc = execution.StartedOnUtc,
CompletedOnUtc = completedOnUtc,
CreatedOnUtc = execution.CreatedOnUtc,
CreatedBy = execution.CreatedBy,
UpdatedOnUtc = execution.UpdatedOnUtc,
UpdatedBy = execution.UpdatedBy
};
}
/// <summary>
/// Notifies the SignalR clients about the current list of scheduled jobs.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private async Task NotifyCurrentScheduledJobsAsync(CancellationToken cancellationToken)
{
Result<IEnumerable<ScheduledJobEntity>> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (getScheduledJobsResult.IsFailure)
throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
IReadOnlyList<ScheduledJobResponse> scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
}
}
@@ -0,0 +1,129 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.Scheduling;
using Lumina.Application.Core.Scheduling.Notifications;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.Scheduling.Events;
/// <summary>
/// Handler for the domain event raised when the task of a scheduled job starts its execution.
/// </summary>
public class ScheduledJobExecutionStartedDomainEventHandler : IDomainEventHandler<ScheduledJobExecutionStartedDomainEvent>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IScheduledJobNotifier _scheduledJobNotifier;
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobExecutionStartedDomainEventHandler"/> class.
/// </summary>
/// <param name="scheduledJobNotifier">Injected service for notifying the scheduled job changes to SignalR clients.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public ScheduledJobExecutionStartedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_scheduledJobNotifier = scheduledJobNotifier;
}
/// <summary>
/// Handles the event raised when the task of a scheduled job starts its execution.
/// </summary>
/// <param name="domainEvent">The domain event to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async ValueTask HandleAsync(ScheduledJobExecutionStartedDomainEvent domainEvent, CancellationToken cancellationToken)
{
// Get the scheduled job from the repository.
Result<ScheduledJobEntity?> getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken).ConfigureAwait(false);
if (getScheduledJobResult.IsFailure)
throw new EventualConsistencyException(getScheduledJobResult.FirstError, getScheduledJobResult.Errors);
if (getScheduledJobResult.Value is null)
throw new EventualConsistencyException(Errors.Scheduling.ScheduledJobNotFound);
ScheduledJobEntity scheduledJob = getScheduledJobResult.Value;
// 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);
Result<Updated> updateScheduledJobResult = await _unitOfWork.ScheduledJobRepository.UpdateAsync(updatedScheduledJob, cancellationToken).ConfigureAwait(false);
if (updateScheduledJobResult.IsFailure)
throw new EventualConsistencyException(updateScheduledJobResult.FirstError, updateScheduledJobResult.Errors);
// Insert the execution of the task of the scheduled job into the repository.
ScheduledJobExecutionEntity execution = new()
{
Id = domainEvent.RunId,
ScheduledJobId = scheduledJob.Id,
TaskType = scheduledJob.TaskType,
IsCycleRun = domainEvent.IsCycleRun,
StartedOnUtc = domainEvent.StartedOnUtc,
CompletedOnUtc = null,
CreatedOnUtc = scheduledJob.CreatedOnUtc,
CreatedBy = scheduledJob.CreatedBy,
UpdatedOnUtc = null,
UpdatedBy = null
};
Result<Created> insertExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.InsertAsync(execution, cancellationToken).ConfigureAwait(false);
if (insertExecutionResult.IsFailure)
throw new EventualConsistencyException(insertExecutionResult.FirstError, insertExecutionResult.Errors);
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// Notify the SignalR clients about the current scheduled jobs and the started execution.
await NotifyCurrentScheduledJobsAsync(cancellationToken).ConfigureAwait(false);
await _scheduledJobNotifier.SendScheduledJobExecutionStartedAsync(execution.ToResponse(), cancellationToken).ConfigureAwait(false);
}
/// <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>
/// Notifies the SignalR clients about the current list of scheduled jobs.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private async Task NotifyCurrentScheduledJobsAsync(CancellationToken cancellationToken)
{
Result<IEnumerable<ScheduledJobEntity>> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (getScheduledJobsResult.IsFailure)
throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
IReadOnlyList<ScheduledJobResponse> scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
}
}
@@ -0,0 +1,79 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.Scheduling;
using Lumina.Application.Core.Scheduling.Notifications;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.Scheduling.Events;
/// <summary>
/// Handler for the domain event raised when the execution of the task of a scheduled job is stopped while it is running.
/// </summary>
public class ScheduledJobExecutionStoppedDomainEventHandler : IDomainEventHandler<ScheduledJobExecutionStoppedDomainEvent>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IScheduledJobNotifier _scheduledJobNotifier;
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobExecutionStoppedDomainEventHandler"/> class.
/// </summary>
/// <param name="scheduledJobNotifier">Injected service for notifying the scheduled job changes to SignalR clients.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public ScheduledJobExecutionStoppedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_scheduledJobNotifier = scheduledJobNotifier;
}
/// <summary>
/// Handles the event raised when the execution of the task of a scheduled job is stopped while it is running.
/// </summary>
/// <param name="domainEvent">The domain event to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async ValueTask HandleAsync(ScheduledJobExecutionStoppedDomainEvent domainEvent, CancellationToken cancellationToken)
{
// Close the execution history row of the stopped execution, if it exists.
Result<ScheduledJobExecutionEntity?> getOpenExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository
.GetOpenByScheduledJobIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken).ConfigureAwait(false);
if (getOpenExecutionResult.IsFailure)
throw new EventualConsistencyException(getOpenExecutionResult.FirstError, getOpenExecutionResult.Errors);
if (getOpenExecutionResult.Value is not null)
{
ScheduledJobExecutionEntity execution = getOpenExecutionResult.Value;
ScheduledJobExecutionEntity updatedExecution = new()
{
Id = execution.Id,
ScheduledJobId = execution.ScheduledJobId,
TaskType = execution.TaskType,
IsCycleRun = execution.IsCycleRun,
StartedOnUtc = execution.StartedOnUtc,
CompletedOnUtc = domainEvent.OccurredOnUtc,
CreatedOnUtc = execution.CreatedOnUtc,
CreatedBy = execution.CreatedBy,
UpdatedOnUtc = execution.UpdatedOnUtc,
UpdatedBy = execution.UpdatedBy
};
Result<Updated> updateExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.UpdateAsync(updatedExecution, cancellationToken).ConfigureAwait(false);
if (updateExecutionResult.IsFailure)
throw new EventualConsistencyException(updateExecutionResult.FirstError, updateExecutionResult.Errors);
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
}
// Notify the SignalR clients about the current list of scheduled jobs.
Result<IEnumerable<ScheduledJobEntity>> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (getScheduledJobsResult.IsFailure)
throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
IReadOnlyList<ScheduledJobResponse> scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
}
}
@@ -0,0 +1,37 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Scheduling;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.Scheduling.Events;
/// <summary>
/// Handler for the domain event raised when the task of a scheduled job is fired once.
/// </summary>
public class ScheduledJobFiredDomainEventHandler : IDomainEventHandler<ScheduledJobFiredDomainEvent>
{
private readonly IScheduledJobScheduler _scheduledJobScheduler;
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobFiredDomainEventHandler"/> class.
/// </summary>
/// <param name="scheduledJobScheduler">Injected service that schedules and executes the tasks of scheduled jobs.</param>
public ScheduledJobFiredDomainEventHandler(IScheduledJobScheduler scheduledJobScheduler)
{
_scheduledJobScheduler = scheduledJobScheduler;
}
/// <summary>
/// Handles the event raised when the task of a scheduled job is fired once.
/// </summary>
/// <param name="domainEvent">The domain event to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async ValueTask HandleAsync(ScheduledJobFiredDomainEvent domainEvent, CancellationToken cancellationToken)
{
// Start a one time execution of the task of the scheduled job in the scheduler service.
await _scheduledJobScheduler.RunOnceAsync(domainEvent.ScheduledJobId, cancellationToken).ConfigureAwait(false);
}
}
@@ -0,0 +1,51 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.Scheduling;
using Lumina.Application.Core.Scheduling.Notifications;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.Scheduling.Events;
/// <summary>
/// Handler for the domain event raised when a scheduled job is removed.
/// </summary>
public class ScheduledJobRemovedDomainEventHandler : IDomainEventHandler<ScheduledJobRemovedDomainEvent>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IScheduledJobNotifier _scheduledJobNotifier;
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobRemovedDomainEventHandler"/> class.
/// </summary>
/// <param name="scheduledJobNotifier">Injected service for notifying the scheduled job changes to SignalR clients.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public ScheduledJobRemovedDomainEventHandler(IScheduledJobNotifier scheduledJobNotifier, IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_scheduledJobNotifier = scheduledJobNotifier;
}
/// <summary>
/// Handles the event raised when a scheduled job is removed.
/// </summary>
/// <param name="domainEvent">The domain event to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async ValueTask HandleAsync(ScheduledJobRemovedDomainEvent domainEvent, CancellationToken cancellationToken)
{
Result<IEnumerable<ScheduledJobEntity>> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (getScheduledJobsResult.IsFailure)
throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors);
IReadOnlyList<ScheduledJobResponse> scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())];
await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false);
}
}
@@ -0,0 +1,35 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Responses.Scheduling;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.Scheduling.Notifications;
/// <summary>
/// Interface for the class used to notify SignalR clients about the scheduled jobs and their executions.
/// </summary>
public interface IScheduledJobNotifier
{
/// <summary>
/// Notifies the SignalR clients about the current list of scheduled jobs.
/// </summary>
/// <param name="scheduledJobs">The current list of scheduled jobs.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
Task SendScheduledJobsAsync(IReadOnlyList<ScheduledJobResponse> scheduledJobs, CancellationToken cancellationToken);
/// <summary>
/// Notifies the SignalR clients about an execution of the task of a scheduled job that started.
/// </summary>
/// <param name="execution">The execution of the task of the scheduled job that started.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
Task SendScheduledJobExecutionStartedAsync(ScheduledJobExecutionResponse execution, CancellationToken cancellationToken);
/// <summary>
/// Notifies the SignalR clients about an execution of the task of a scheduled job that completed.
/// </summary>
/// <param name="execution">The execution of the task of the scheduled job that completed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
Task SendScheduledJobExecutionCompletedAsync(ScheduledJobExecutionResponse execution, CancellationToken cancellationToken);
}
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.Scheduling.Queries.GetScheduledJobHistory;
/// <summary>
/// Query for getting the history of the executions of the tasks of scheduled jobs.
/// </summary>
/// <param name="From">The optional inclusive lower bound of the interval for which the history is requested.</param>
/// <param name="To">The optional inclusive upper bound of the interval for which the history is requested.</param>
[DebuggerDisplay("From: {From}, To: {To}")]
public record GetScheduledJobHistoryQuery(
DateTime? From,
DateTime? To
) : IQuery;
@@ -0,0 +1,76 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Mapping.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Scheduling.Queries.GetScheduledJobHistory;
/// <summary>
/// Handler for the query to get the history of the executions of the tasks of scheduled jobs.
/// </summary>
public class GetScheduledJobHistoryQueryHandler : IQueryHandler<GetScheduledJobHistoryQuery, Result<IEnumerable<ScheduledJobExecutionResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
/// <summary>
/// Initializes a new instance of the <see cref="GetScheduledJobHistoryQueryHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public GetScheduledJobHistoryQueryHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
}
/// <summary>
/// Handles the query to get the history of the executions of the tasks of scheduled jobs.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the execution history, or an error.
/// </returns>
public async Task<Result<IEnumerable<ScheduledJobExecutionResponse>>> HandleAsync(GetScheduledJobHistoryQuery query, CancellationToken cancellationToken)
{
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// Only administrators can get the history of scheduled jobs.
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
// The lower bound defaults to one day before the upper bound, which defaults to now.
DateTime toUtc = query.To ?? DateTime.UtcNow;
DateTime fromUtc = query.From ?? toUtc.AddDays(-1);
// Get the executions from the storage medium.
Result<IEnumerable<ScheduledJobExecutionEntity>> getExecutionsResult = await _unitOfWork.ScheduledJobExecutionRepository.GetByTimeRangeAsync(fromUtc, toUtc, cancellationToken).ConfigureAwait(false);
if (getExecutionsResult.IsFailure)
return getExecutionsResult.Errors;
return Result.From(getExecutionsResult.Value.Select(execution => execution.ToResponse()));
}
}
@@ -0,0 +1,12 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.Scheduling.Queries.GetScheduledJobs;
/// <summary>
/// Query for getting the list of scheduled jobs.
/// </summary>
[DebuggerDisplay("GetScheduledJobsQuery")]
public record GetScheduledJobsQuery : IQuery;
@@ -0,0 +1,72 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Mapping.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Scheduling.Queries.GetScheduledJobs;
/// <summary>
/// Handler for the query to get the list of scheduled jobs.
/// </summary>
public class GetScheduledJobsQueryHandler : IQueryHandler<GetScheduledJobsQuery, Result<IEnumerable<ScheduledJobResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
/// <summary>
/// Initializes a new instance of the <see cref="GetScheduledJobsQueryHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public GetScheduledJobsQueryHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
}
/// <summary>
/// Handles the query to get the list of scheduled jobs.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the list of scheduled jobs, or an error.
/// </returns>
public async Task<Result<IEnumerable<ScheduledJobResponse>>> HandleAsync(GetScheduledJobsQuery query, CancellationToken cancellationToken)
{
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// Only administrators can get the list of scheduled jobs.
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
// Get the scheduled jobs from the storage medium.
Result<IEnumerable<ScheduledJobEntity>> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (getScheduledJobsResult.IsFailure)
return getScheduledJobsResult.Errors;
return Result.From(getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse()));
}
}