mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Adds scheduled job contracts and application handlers
This commit is contained in:
1 parent
7fbb4dc0d3
commit
ea7e003bff
51 files changed
+2442
No files matched your search
@@ -0,0 +1,90 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DataAccess.Entities.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// Repository entity for a scheduled job.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("Id: {Id}, Status: {Status}")]
|
||||
public class ScheduledJobEntity : IStorageEntity, IAuditableEntity
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the Id of the scheduled job.
|
||||
/// </summary>
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the name of the scheduled job.
|
||||
/// </summary>
|
||||
public required string Name { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the type of the task executed by the scheduled job.
|
||||
/// </summary>
|
||||
public required ScheduledTaskType TaskType { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the type of the schedule of the scheduled job.
|
||||
/// </summary>
|
||||
public required ScheduleType ScheduleType { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the interval in minutes of the schedule of the scheduled job, when its <see cref="ScheduleType"/> is <see cref="ScheduleType.WithIntervalInMinutes"/>.
|
||||
/// </summary>
|
||||
public int? IntervalMinutes { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the hour of the schedule of the scheduled job, when its <see cref="ScheduleType"/> is <see cref="ScheduleType.DailyAtHourAndMinute"/>.
|
||||
/// </summary>
|
||||
public int? Hour { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the minute of the schedule of the scheduled job, when its <see cref="ScheduleType"/> is <see cref="ScheduleType.DailyAtHourAndMinute"/>.
|
||||
/// </summary>
|
||||
public int? Minute { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the status of the scheduled job.
|
||||
/// </summary>
|
||||
public required ScheduledJobStatus Status { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the user that owns the scheduled job.
|
||||
/// </summary>
|
||||
public required Guid OwnerUserId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the optional date and time when the task of the scheduled job last started its execution.
|
||||
/// </summary>
|
||||
public DateTime? LastStartedOnUtc { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the optional date and time when the task of the scheduled job last completed its execution.
|
||||
/// </summary>
|
||||
public DateTime? LastCompletedOnUtc { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
/// </summary>
|
||||
public DateTime? UpdatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DataAccess.Entities.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// Repository entity for an execution of the task of a scheduled job.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("Id: {Id}, ScheduledJobId: {ScheduledJobId}")]
|
||||
public class ScheduledJobExecutionEntity : IStorageEntity, IAuditableEntity
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the Id of the execution of the task of a scheduled job.
|
||||
/// </summary>
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the scheduled job whose task was executed.
|
||||
/// </summary>
|
||||
public required Guid ScheduledJobId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the type of the task that was executed.
|
||||
/// </summary>
|
||||
public required ScheduledTaskType TaskType { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the execution was triggered by the execution cycle of the scheduled job, or it was a one time execution.
|
||||
/// </summary>
|
||||
public required bool IsCycleRun { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the date and time when the execution started.
|
||||
/// </summary>
|
||||
public required DateTime StartedOnUtc { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the optional date and time when the execution completed.
|
||||
/// </summary>
|
||||
public DateTime? CompletedOnUtc { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
/// </summary>
|
||||
public DateTime? UpdatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DataAccess.Repositories.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the repository for the executions of the tasks of scheduled jobs.
|
||||
/// </summary>
|
||||
public interface IScheduledJobExecutionRepository : IRepository<ScheduledJobExecutionEntity>,
|
||||
IGetByIdRepositoryAction<ScheduledJobExecutionEntity, Guid>,
|
||||
IInsertRepositoryAction<ScheduledJobExecutionEntity>,
|
||||
IUpdateRepositoryAction<ScheduledJobExecutionEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the most recent execution of the task of a scheduled job identified by <paramref name="scheduledJobId"/> that is still running, from the storage medium.
|
||||
/// </summary>
|
||||
/// <param name="scheduledJobId">The Id of the scheduled job whose running execution is retrieved.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the running execution of the scheduled job, or <see langword="null"/>.</returns>
|
||||
Task<Result<ScheduledJobExecutionEntity?>> GetOpenByScheduledJobIdAsync(Guid scheduledJobId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the executions of the tasks of scheduled jobs that started in the interval between <paramref name="fromUtc"/> and <paramref name="toUtc"/>, from the storage medium.
|
||||
/// </summary>
|
||||
/// <param name="fromUtc">The inclusive lower bound of the interval, in UTC.</param>
|
||||
/// <param name="toUtc">The inclusive upper bound of the interval, in UTC.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="ScheduledJobExecutionEntity"/>, or an error.</returns>
|
||||
Task<Result<IEnumerable<ScheduledJobExecutionEntity>>> GetByTimeRangeAsync(DateTime fromUtc, DateTime toUtc, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Removes all the executions of the task of a scheduled job identified by <paramref name="scheduledJobId"/>, from the storage medium.
|
||||
/// </summary>
|
||||
/// <param name="scheduledJobId">The Id of the scheduled job whose executions 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>> DeleteByScheduledJobIdAsync(Guid scheduledJobId, CancellationToken cancellationToken);
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DataAccess.Repositories.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the repository for scheduled jobs.
|
||||
/// </summary>
|
||||
public interface IScheduledJobRepository : IRepository<ScheduledJobEntity>,
|
||||
IGetByIdRepositoryAction<ScheduledJobEntity, Guid>,
|
||||
IGetAllRepositoryAction<ScheduledJobEntity>,
|
||||
IInsertRepositoryAction<ScheduledJobEntity>,
|
||||
IUpdateRepositoryAction<ScheduledJobEntity>,
|
||||
IDeleteByIdRepositoryAction<Guid>
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the scheduled jobs that have an active or running execution cycle, from the storage medium.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="ScheduledJobEntity"/>, or an error.</returns>
|
||||
Task<Result<IEnumerable<ScheduledJobEntity>>> GetActiveOrRunningAsync(CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Themes;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using System.Threading;
|
||||
@@ -87,6 +88,16 @@ public interface IUnitOfWork
|
||||
/// </summary>
|
||||
ILibraryBookReaderConfigurationRepository LibraryBookReaderConfigurationRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the scheduled job repository.
|
||||
/// </summary>
|
||||
IScheduledJobRepository ScheduledJobRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the scheduled job execution repository.
|
||||
/// </summary>
|
||||
IScheduledJobExecutionRepository ScheduledJobExecutionRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the plugin repository.
|
||||
/// </summary>
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Infrastructure.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the service that schedules and executes the tasks of scheduled jobs.
|
||||
/// </summary>
|
||||
public interface IScheduledJobScheduler
|
||||
{
|
||||
/// <summary>
|
||||
/// Starts the execution cycle of the scheduled job identified by <paramref name="scheduledJobId"/>.
|
||||
/// </summary>
|
||||
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose execution cycle is started.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
Task StartCycleAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Stops the execution cycle of the scheduled job identified by <paramref name="scheduledJobId"/>.
|
||||
/// </summary>
|
||||
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose execution cycle is stopped.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
Task StopCycleAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Fires the task of the scheduled job identified by <paramref name="scheduledJobId"/> once, without affecting its execution cycle.
|
||||
/// </summary>
|
||||
/// <param name="scheduledJobId">The object representing the unique identifier of the scheduled job whose task is fired.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
Task RunOnceAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Scheduling.Commands.AddScheduledJob;
|
||||
using Lumina.Contracts.Requests.Scheduling;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="AddScheduledJobRequest"/>.
|
||||
/// </summary>
|
||||
public static class AddScheduledJobRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="AddScheduledJobCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <returns>The converted command.</returns>
|
||||
public static AddScheduledJobCommand ToCommand(this AddScheduledJobRequest request)
|
||||
{
|
||||
return new AddScheduledJobCommand(
|
||||
request.Name,
|
||||
request.TaskType,
|
||||
request.ScheduleType,
|
||||
request.IntervalMinutes,
|
||||
request.Hour,
|
||||
request.Minute
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Scheduling.Commands.FireScheduledJob;
|
||||
using Lumina.Contracts.Requests.Scheduling;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="FireScheduledJobRequest"/>.
|
||||
/// </summary>
|
||||
public static class FireScheduledJobRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="FireScheduledJobCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <returns>The converted command.</returns>
|
||||
public static FireScheduledJobCommand ToCommand(this FireScheduledJobRequest request)
|
||||
{
|
||||
return new FireScheduledJobCommand(
|
||||
request.ScheduledJobId
|
||||
);
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Scheduling.Queries.GetScheduledJobHistory;
|
||||
using Lumina.Contracts.Requests.Scheduling;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="GetScheduledJobHistoryRequest"/>.
|
||||
/// </summary>
|
||||
public static class GetScheduledJobHistoryRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="GetScheduledJobHistoryQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <returns>The converted query.</returns>
|
||||
public static GetScheduledJobHistoryQuery ToQuery(this GetScheduledJobHistoryRequest request)
|
||||
{
|
||||
return new GetScheduledJobHistoryQuery(
|
||||
request.From,
|
||||
request.To
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Scheduling.Commands.RemoveScheduledJob;
|
||||
using Lumina.Contracts.Requests.Scheduling;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="RemoveScheduledJobRequest"/>.
|
||||
/// </summary>
|
||||
public static class RemoveScheduledJobRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="RemoveScheduledJobCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <returns>The converted command.</returns>
|
||||
public static RemoveScheduledJobCommand ToCommand(this RemoveScheduledJobRequest request)
|
||||
{
|
||||
return new RemoveScheduledJobCommand(
|
||||
request.ScheduledJobId
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Contracts.Responses.Scheduling;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
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.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="ScheduledJobEntity"/>.
|
||||
/// </summary>
|
||||
public static class ScheduledJobEntityMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="repositoryEntity"/> to <see cref="ScheduledJob"/>.
|
||||
/// </summary>
|
||||
/// <param name="repositoryEntity">The repository entity to be converted.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a converted <see cref="ScheduledJob"/>, or an error message.
|
||||
/// </returns>
|
||||
public static Result<ScheduledJob> ToDomainEntity(this ScheduledJobEntity repositoryEntity)
|
||||
{
|
||||
Result<Schedule> scheduleResult = CreateSchedule(repositoryEntity);
|
||||
if (scheduleResult.IsFailure)
|
||||
return scheduleResult.Errors;
|
||||
|
||||
return ScheduledJob.Create(
|
||||
ScheduledJobId.Create(repositoryEntity.Id),
|
||||
repositoryEntity.Name,
|
||||
repositoryEntity.TaskType,
|
||||
scheduleResult.Value,
|
||||
UserId.Create(repositoryEntity.OwnerUserId),
|
||||
repositoryEntity.Status,
|
||||
Optional<DateTime>.FromNullable(repositoryEntity.LastStartedOnUtc),
|
||||
Optional<DateTime>.FromNullable(repositoryEntity.LastCompletedOnUtc)
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts <paramref name="repositoryEntities"/> to a collection of <see cref="ScheduledJob"/>.
|
||||
/// </summary>
|
||||
/// <param name="repositoryEntities">The repository entities to be converted.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a collection of converted <see cref="ScheduledJob"/>, or an error message.
|
||||
/// </returns>
|
||||
public static IEnumerable<Result<ScheduledJob>> ToDomainEntities(this IEnumerable<ScheduledJobEntity> repositoryEntities)
|
||||
{
|
||||
return repositoryEntities.Select(repositoryEntity => repositoryEntity.ToDomainEntity());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts <paramref name="repositoryEntity"/> to <see cref="ScheduledJobResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="repositoryEntity">The repository entity to be converted.</param>
|
||||
/// <returns>The converted scheduled job response.</returns>
|
||||
public static ScheduledJobResponse ToResponse(this ScheduledJobEntity repositoryEntity)
|
||||
{
|
||||
return new ScheduledJobResponse(
|
||||
repositoryEntity.Id,
|
||||
repositoryEntity.Name,
|
||||
repositoryEntity.TaskType,
|
||||
repositoryEntity.ScheduleType,
|
||||
repositoryEntity.IntervalMinutes,
|
||||
repositoryEntity.Hour,
|
||||
repositoryEntity.Minute,
|
||||
repositoryEntity.Status,
|
||||
repositoryEntity.LastStartedOnUtc,
|
||||
repositoryEntity.LastCompletedOnUtc
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the schedule of <paramref name="repositoryEntity"/> from its flattened schedule properties.
|
||||
/// </summary>
|
||||
/// <param name="repositoryEntity">The repository entity whose schedule is created.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a created <see cref="Schedule"/>, or an error message.
|
||||
/// </returns>
|
||||
private static Result<Schedule> CreateSchedule(ScheduledJobEntity repositoryEntity)
|
||||
{
|
||||
if (repositoryEntity.ScheduleType == ScheduleType.WithIntervalInMinutes)
|
||||
{
|
||||
Result<IntervalSchedule> intervalScheduleResult = IntervalSchedule.Create(repositoryEntity.IntervalMinutes ?? 0);
|
||||
if (intervalScheduleResult.IsFailure)
|
||||
return intervalScheduleResult.Errors;
|
||||
return Result.From<Schedule>(intervalScheduleResult.Value);
|
||||
}
|
||||
|
||||
Result<DailySchedule> dailyScheduleResult = DailySchedule.Create(repositoryEntity.Hour ?? 0, repositoryEntity.Minute ?? 0);
|
||||
if (dailyScheduleResult.IsFailure)
|
||||
return dailyScheduleResult.Errors;
|
||||
return Result.From<Schedule>(dailyScheduleResult.Value);
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Contracts.Responses.Scheduling;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="ScheduledJobExecutionEntity"/>.
|
||||
/// </summary>
|
||||
public static class ScheduledJobExecutionEntityMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="repositoryEntity"/> to <see cref="ScheduledJobExecutionResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="repositoryEntity">The repository entity to be converted.</param>
|
||||
/// <returns>The converted execution response.</returns>
|
||||
public static ScheduledJobExecutionResponse ToResponse(this ScheduledJobExecutionEntity repositoryEntity)
|
||||
{
|
||||
return new ScheduledJobExecutionResponse(
|
||||
repositoryEntity.Id,
|
||||
repositoryEntity.ScheduledJobId,
|
||||
repositoryEntity.TaskType,
|
||||
repositoryEntity.IsCycleRun,
|
||||
repositoryEntity.StartedOnUtc,
|
||||
repositoryEntity.CompletedOnUtc
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Scheduling;
|
||||
using Lumina.Contracts.Responses.Scheduling;
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="ScheduledJob"/>.
|
||||
/// </summary>
|
||||
public static class ScheduledJobMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="domainEntity"/> to <see cref="ScheduledJobEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="domainEntity">The domain entity to be converted.</param>
|
||||
/// <returns>The converted repository entity.</returns>
|
||||
public static ScheduledJobEntity ToRepositoryEntity(this ScheduledJob domainEntity)
|
||||
{
|
||||
return new ScheduledJobEntity
|
||||
{
|
||||
Id = domainEntity.Id.Value,
|
||||
Name = domainEntity.Name,
|
||||
TaskType = domainEntity.TaskType,
|
||||
ScheduleType = domainEntity.Schedule.ScheduleType,
|
||||
IntervalMinutes = GetIntervalMinutes(domainEntity),
|
||||
Hour = GetHour(domainEntity),
|
||||
Minute = GetMinute(domainEntity),
|
||||
Status = domainEntity.Status,
|
||||
OwnerUserId = domainEntity.OwnerUserId.Value,
|
||||
LastStartedOnUtc = domainEntity.LastStartedOnUtc.HasValue ? domainEntity.LastStartedOnUtc.Value : null,
|
||||
LastCompletedOnUtc = domainEntity.LastCompletedOnUtc.HasValue ? domainEntity.LastCompletedOnUtc.Value : null,
|
||||
CreatedOnUtc = domainEntity.CreatedOnUtc,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedOnUtc = domainEntity.UpdatedOnUtc,
|
||||
UpdatedBy = Guid.Empty
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts <paramref name="domainEntity"/> to <see cref="ScheduledJobResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="domainEntity">The domain entity to be converted.</param>
|
||||
/// <returns>The converted scheduled job response.</returns>
|
||||
public static ScheduledJobResponse ToResponse(this ScheduledJob domainEntity)
|
||||
{
|
||||
return new ScheduledJobResponse(
|
||||
domainEntity.Id.Value,
|
||||
domainEntity.Name,
|
||||
domainEntity.TaskType,
|
||||
domainEntity.Schedule.ScheduleType,
|
||||
GetIntervalMinutes(domainEntity),
|
||||
GetHour(domainEntity),
|
||||
GetMinute(domainEntity),
|
||||
domainEntity.Status,
|
||||
domainEntity.LastStartedOnUtc.HasValue ? domainEntity.LastStartedOnUtc.Value : null,
|
||||
domainEntity.LastCompletedOnUtc.HasValue ? domainEntity.LastCompletedOnUtc.Value : null
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the interval in minutes of the schedule of <paramref name="domainEntity"/>, when it is an interval schedule.
|
||||
/// </summary>
|
||||
/// <param name="domainEntity">The scheduled job whose schedule interval is retrieved.</param>
|
||||
/// <returns>The interval in minutes of the schedule, or <see langword="null"/> when the schedule is not an interval schedule.</returns>
|
||||
private static int? GetIntervalMinutes(ScheduledJob domainEntity)
|
||||
{
|
||||
return domainEntity.Schedule is IntervalSchedule intervalSchedule ? intervalSchedule.IntervalMinutes : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the hour of the schedule of <paramref name="domainEntity"/>, when it is a daily schedule.
|
||||
/// </summary>
|
||||
/// <param name="domainEntity">The scheduled job whose schedule hour is retrieved.</param>
|
||||
/// <returns>The hour of the schedule, or <see langword="null"/> when the schedule is not a daily schedule.</returns>
|
||||
private static int? GetHour(ScheduledJob domainEntity)
|
||||
{
|
||||
return domainEntity.Schedule is DailySchedule dailySchedule ? dailySchedule.Hour : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the minute of the schedule of <paramref name="domainEntity"/>, when it is a daily schedule.
|
||||
/// </summary>
|
||||
/// <param name="domainEntity">The scheduled job whose schedule minute is retrieved.</param>
|
||||
/// <returns>The minute of the schedule, or <see langword="null"/> when the schedule is not a daily schedule.</returns>
|
||||
private static int? GetMinute(ScheduledJob domainEntity)
|
||||
{
|
||||
return domainEntity.Schedule is DailySchedule dailySchedule ? dailySchedule.Minute : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Scheduling.Commands.StartScheduledJob;
|
||||
using Lumina.Contracts.Requests.Scheduling;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="StartScheduledJobRequest"/>.
|
||||
/// </summary>
|
||||
public static class StartScheduledJobRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="StartScheduledJobCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <returns>The converted command.</returns>
|
||||
public static StartScheduledJobCommand ToCommand(this StartScheduledJobRequest request)
|
||||
{
|
||||
return new StartScheduledJobCommand(
|
||||
request.ScheduledJobId
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Scheduling.Commands.StopScheduledJob;
|
||||
using Lumina.Contracts.Requests.Scheduling;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="StopScheduledJobRequest"/>.
|
||||
/// </summary>
|
||||
public static class StopScheduledJobRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="StopScheduledJobCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <returns>The converted command.</returns>
|
||||
public static StopScheduledJobCommand ToCommand(this StopScheduledJobRequest request)
|
||||
{
|
||||
return new StopScheduledJobCommand(
|
||||
request.ScheduledJobId
|
||||
);
|
||||
}
|
||||
}
|
||||
+26
@@ -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;
|
||||
+122
@@ -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();
|
||||
}
|
||||
}
|
||||
+64
@@ -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);
|
||||
}
|
||||
}
|
||||
+16
@@ -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;
|
||||
+102
@@ -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();
|
||||
}
|
||||
}
|
||||
+23
@@ -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);
|
||||
}
|
||||
}
|
||||
+16
@@ -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;
|
||||
+114
@@ -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;
|
||||
}
|
||||
}
|
||||
+23
@@ -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);
|
||||
}
|
||||
}
|
||||
+16
@@ -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;
|
||||
+109
@@ -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();
|
||||
}
|
||||
}
|
||||
+23
@@ -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);
|
||||
}
|
||||
}
|
||||
+16
@@ -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;
|
||||
+116
@@ -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();
|
||||
}
|
||||
}
|
||||
+23
@@ -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);
|
||||
}
|
||||
}
|
||||
+58
@@ -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);
|
||||
}
|
||||
}
|
||||
+51
@@ -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);
|
||||
}
|
||||
}
|
||||
+147
@@ -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);
|
||||
}
|
||||
}
|
||||
+129
@@ -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);
|
||||
}
|
||||
}
|
||||
+79
@@ -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);
|
||||
}
|
||||
}
|
||||
+51
@@ -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);
|
||||
}
|
||||
+18
@@ -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;
|
||||
+76
@@ -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()));
|
||||
}
|
||||
}
|
||||
+12
@@ -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;
|
||||
+72
@@ -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()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request to add a scheduled job.
|
||||
/// </summary>
|
||||
/// <param name="Name">The name of the scheduled job. Required.</param>
|
||||
/// <param name="TaskType">The type of the task executed by the scheduled job. Required.</param>
|
||||
/// <param name="ScheduleType">The type of the schedule of the scheduled job. Required.</param>
|
||||
/// <param name="IntervalMinutes">The interval in minutes of the schedule, required when <paramref name="ScheduleType"/> is <see cref="ScheduleType.WithIntervalInMinutes"/>.</param>
|
||||
/// <param name="Hour">The hour of the schedule, required when <paramref name="ScheduleType"/> is <see cref="ScheduleType.DailyAtHourAndMinute"/>.</param>
|
||||
/// <param name="Minute">The minute of the schedule, required when <paramref name="ScheduleType"/> is <see cref="ScheduleType.DailyAtHourAndMinute"/>.</param>
|
||||
[DebuggerDisplay("Name: {Name}")]
|
||||
public record AddScheduledJobRequest(
|
||||
string Name,
|
||||
ScheduledTaskType TaskType,
|
||||
ScheduleType ScheduleType,
|
||||
int? IntervalMinutes,
|
||||
int? Hour,
|
||||
int? Minute
|
||||
);
|
||||
@@ -0,0 +1,15 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request to fire 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. Required.</param>
|
||||
[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
|
||||
public record FireScheduledJobRequest(
|
||||
Guid ScheduledJobId
|
||||
);
|
||||
@@ -0,0 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request to get the history of the executions of the tasks of scheduled jobs.
|
||||
/// </summary>
|
||||
/// <param name="From">The inclusive lower bound of the interval for which the history is requested. Optional.</param>
|
||||
/// <param name="To">The inclusive upper bound of the interval for which the history is requested. Optional.</param>
|
||||
[DebuggerDisplay("From: {From}, To: {To}")]
|
||||
public record GetScheduledJobHistoryRequest(
|
||||
DateTime? From,
|
||||
DateTime? To
|
||||
);
|
||||
@@ -0,0 +1,15 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request to remove a scheduled job.
|
||||
/// </summary>
|
||||
/// <param name="ScheduledJobId">The unique identifier of the scheduled job to remove. Required.</param>
|
||||
[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
|
||||
public record RemoveScheduledJobRequest(
|
||||
Guid ScheduledJobId
|
||||
);
|
||||
@@ -0,0 +1,15 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request to start the execution cycle of a scheduled job.
|
||||
/// </summary>
|
||||
/// <param name="ScheduledJobId">The unique identifier of the scheduled job whose execution cycle is started. Required.</param>
|
||||
[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
|
||||
public record StartScheduledJobRequest(
|
||||
Guid ScheduledJobId
|
||||
);
|
||||
@@ -0,0 +1,15 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request to stop the execution cycle of a scheduled job.
|
||||
/// </summary>
|
||||
/// <param name="ScheduledJobId">The unique identifier of the scheduled job whose execution cycle is stopped. Required.</param>
|
||||
[DebuggerDisplay("ScheduledJobId: {ScheduledJobId}")]
|
||||
public record StopScheduledJobRequest(
|
||||
Guid ScheduledJobId
|
||||
);
|
||||
@@ -0,0 +1,26 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Responses.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// Represents an execution of the task of a scheduled job.
|
||||
/// </summary>
|
||||
/// <param name="Id">The unique identifier of the execution.</param>
|
||||
/// <param name="ScheduledJobId">The unique identifier of the scheduled job whose task was executed.</param>
|
||||
/// <param name="TaskType">The type of the task that was executed.</param>
|
||||
/// <param name="IsCycleRun"><see langword="true"/> when the execution was triggered by the execution cycle of the scheduled job, <see langword="false"/> when it was a one time execution.</param>
|
||||
/// <param name="StartedOnUtc">The date and time when the execution started.</param>
|
||||
/// <param name="CompletedOnUtc">The optional date and time when the execution completed.</param>
|
||||
[DebuggerDisplay("Id: {Id}, ScheduledJobId: {ScheduledJobId}")]
|
||||
public record ScheduledJobExecutionResponse(
|
||||
Guid Id,
|
||||
Guid ScheduledJobId,
|
||||
ScheduledTaskType TaskType,
|
||||
bool IsCycleRun,
|
||||
DateTime StartedOnUtc,
|
||||
DateTime? CompletedOnUtc
|
||||
);
|
||||
@@ -0,0 +1,34 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Responses.Scheduling;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a scheduled job response.
|
||||
/// </summary>
|
||||
/// <param name="Id">The unique identifier of the scheduled job.</param>
|
||||
/// <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 of the scheduled job, when its <see cref="ScheduleType"/> is <see cref="ScheduleType.WithIntervalInMinutes"/>.</param>
|
||||
/// <param name="Hour">The hour of the schedule of the scheduled job, when its <see cref="ScheduleType"/> is <see cref="ScheduleType.DailyAtHourAndMinute"/>.</param>
|
||||
/// <param name="Minute">The minute of the schedule of the scheduled job, when its <see cref="ScheduleType"/> is <see cref="ScheduleType.DailyAtHourAndMinute"/>.</param>
|
||||
/// <param name="Status">The status of the scheduled job.</param>
|
||||
/// <param name="LastStartedOnUtc">The optional date and time when the task of the scheduled job last started its execution.</param>
|
||||
/// <param name="LastCompletedOnUtc">The optional date and time when the task of the scheduled job last completed its execution.</param>
|
||||
[DebuggerDisplay("Id: {Id}, Name: {Name}, Status: {Status}")]
|
||||
public record ScheduledJobResponse(
|
||||
Guid Id,
|
||||
string Name,
|
||||
ScheduledTaskType TaskType,
|
||||
ScheduleType ScheduleType,
|
||||
int? IntervalMinutes,
|
||||
int? Hour,
|
||||
int? Minute,
|
||||
ScheduledJobStatus Status,
|
||||
DateTime? LastStartedOnUtc,
|
||||
DateTime? LastCompletedOnUtc
|
||||
);
|
||||
Reference in new issue
Block a user