Replaces Mediator domain event publishing with a custom implementation and removes the Mediator dependency

This commit is contained in:
BinaryAlley committed 2026-08-13 14:02:16 -07:00
1 parent 8c8c96c6db
commit 810fa5c2e7
61 files changed
+618 -176

No files matched your search

@@ -12,9 +12,9 @@ Key constraints that shaped this decision:
1. **Licensing Change**: MediatR became a commercial product for .NET 8+ projects, requiring a paid license for continued use in production systems.
2. **Narrow Usage Scope**: MediatR is used exclusively for command and query dispatching - only one pipeline behavior (automatic application validation) and no notification publishing or stream requests are in use anywhere in the solution.
2. **Narrow Usage Scope**: MediatR is used for command and query dispatching, with a single pipeline behavior (automatic application validation) and no stream requests. Its notification publishing is used for domain event publishing, which is outside the scope of this ADR and is replaced separately (see ADR-0013).
3. **Zero Abstraction Value at Scale**: With only a validation pipeline behavior registered, MediatR provides no runtime value beyond a dispatch indirection that can be replaced by direct handler injection. It actually hurts performance by runtime dispatching of handlers via reflection.
3. **Zero Abstraction Value at Scale**: With only a validation pipeline behavior registered, the command and query dispatching provides no runtime value beyond a dispatch indirection that can be replaced by direct handler injection. It actually hurts performance by runtime dispatching of handlers via reflection.
4. **Ownership and Transparency**: A custom implementation is fully owned, inspectable, and carries no transitive dependency risk or future licensing exposure.
@@ -0,0 +1,76 @@
# Architecture Decision Record (ADR): 0013 - Replace Mediator Domain Event Publishing with a Custom Implementation
## Status
**Accepted** (2026-08-13)
## Context
Domain event publishing, the mechanism that fires the `IDomainEvent` objects raised by aggregates to their handlers, depends on the Mediator library (`Mediator.Abstractions` and `Mediator.SourceGenerator`).
1. **Event contract**: `IDomainEvent` implements Mediator's `INotification` marker interface.
2. **Handler registration**: Domain event handlers implements Mediator's `INotificationHandler<T>` and are registered by the source-generated `AddMediator` call.
3. **Publishing sites**: Mediator's `IPublisher` is used from `EventualConsistencyMiddleware` (queued events, published after the transaction commits), from `MediaLibraryScanningService` (scan start events), and from the scan jobs and `ScanFailurePublisher` (progress and failure events).
The remaining publish half carries the same third-party dependency and source-generated registration that ADR-0011 removed from the dispatch half.
## Decision
Replace Mediator's notification publishing with a first-party domain event publisher.
### New Abstractions (in `Lumina.Domain.Common.Events`)
- `IDomainEvent` no longer inherits `INotification`.
- `IDomainEventPublisher` exposes `ValueTask PublishAsync(IDomainEvent domainEvent, CancellationToken cancellationToken = default)`.
- `IDomainEventHandler<TDomainEvent>` exposes `ValueTask HandleAsync(TDomainEvent domainEvent, CancellationToken cancellationToken)`. The type parameter is invariant so handlers stay mockable by dynamic proxy libraries.
### Publisher Implementation (`DomainEventPublisher` in Infrastructure)
- Scoped, resolving handlers for the event's runtime type from the DI container.
- Dispatches through a compiled delegate cached per event type in a static `ConcurrentDictionary`, built once via `MakeGenericMethod` over a generic dispatch helper. Handlers run sequentially in registration order, exceptions propagate, and events without handlers are no-ops.
- Registered next to the existing `IDomainEventsQueue`.
### Registration (Application DI)
The existing assembly scan that registers `ICommandHandler<>`, `IQueryHandler<>`, and `IValidator<>` now also registers `IDomainEventHandler<>` as scoped, replacing the source-generated `AddMediator`.
### Consistency Guarantees Preserved
- Commit-before-publish ordering in `EventualConsistencyMiddleware` is unchanged (see ADR-0002).
- Re-entrant publishing (a handler publishing another event) is safe: each publish resolves handlers fresh from the scoped provider.
- Jobs publish from their own scopes, so handlers receive a fresh unit of work and `DbContext`.
## Consequences
### Positive Outcomes
| Aspect | Benefit |
|---|---|
| Dependency reduction | Removes `Mediator.Abstractions` and `Mediator.SourceGenerator` from the entire solution |
| Transparency | Dispatch logic is fully owned and inspectable; no generated code |
| Consistency | Domain event handlers join the same explicit registration scan as the CQRS handlers |
| Single event contract | `IDomainEvent` remains the sole contract until a real cross-bounded-context consumer exists |
### Risks and Mitigations
| Risk | Mitigation Strategy |
|---|---|
| Handler resolution failures surface at runtime | Existing integration test suite exercises the DI container on startup |
| Reflection-based dispatch per event type | Compiled delegate cache makes dispatch cheap after the first publish of each type |
| Dynamic proxy cannot proxy generic interfaces | `IDomainEventHandler<TDomainEvent>` is deliberately invariant so handlers remain mockable in unit tests |
## Alternatives Considered
### 1. Domain versus Integration Event Split
Introduce `IIntegrationEvent` now, with a durable outbox, for inter-bounded-context propagation.
**Rejected**: there are no cross-bounded-context consumers today - every event lives in the `LibraryManagementBoundedContext` and is handled in-process. The outbox machinery (durability, retries, idempotency) is speculative until the first real consumer appears, and forcing every existing event into one of two buckets would produce classification with no basis. The seam is documented on `IDomainEvent` itself so the split stays cheap to introduce later.
### 2. Keeping Mediator for Publishing
Keep the Mediator library for the domain event publishing half.
**Rejected**: for the same reason ADR-0011 rejected it for command and query dispatching - an external dependency, with source-generated registration, for functionality that is fully implementable in-house.
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
@@ -22,17 +23,12 @@ public static class ApplicationLayerServices
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddApplicationLayerServices(this IServiceCollection services)
{
// register the Mediator publisher used for publishing domain events
services.AddMediator(options =>
{
options.ServiceLifetime = ServiceLifetime.Scoped;
});
Type[] handlerContractTypes =
[
typeof(CQRS.ICommandHandler<,>),
typeof(CQRS.IQueryHandler<,>),
typeof(Infrastructure.Validation.IValidator<>),
typeof(IDomainEventHandler<>),
];
IEnumerable<Type> concreteTypes = Assembly.GetExecutingAssembly()
@@ -6,7 +6,7 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
using Mediator;
using Lumina.Domain.Common.Events;
using Microsoft.Extensions.Options;
using System;
using System.Threading;
@@ -16,9 +16,9 @@ using System.Threading.Tasks;
namespace Lumina.Application.Core.MediaLibrary.Management.Events;
/// <summary>
/// Handler for the event raised when a media library is deleted.
/// Handler for the domain event raised when a media library is deleted.
/// </summary>
public class LibraryDeletedDomainEventHandler : INotificationHandler<LibraryDeletedDomainEvent>
public class LibraryDeletedDomainEventHandler : IDomainEventHandler<LibraryDeletedDomainEvent>
{
private readonly IEnvironmentContext _environmentContext;
private readonly IPathService _pathService;
@@ -42,7 +42,7 @@ public class LibraryDeletedDomainEventHandler : INotificationHandler<LibraryDele
/// </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 ValueTask Handle(LibraryDeletedDomainEvent domainEvent, CancellationToken cancellationToken)
public ValueTask HandleAsync(LibraryDeletedDomainEvent domainEvent, CancellationToken cancellationToken)
{
// delete the media library directory in the internal location for media library files
ErrorOr<string> libraryPathResult = GetLibraryPath(domainEvent.Library.Id.Value);
@@ -5,12 +5,12 @@ using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
using Lumina.Domain.SharedKernel.Common.Errors;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
using Mediator;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
@@ -23,9 +23,9 @@ using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
namespace Lumina.Application.Core.MediaLibrary.Management.Events;
/// <summary>
/// Handler for the event raised when a media library is created or updated.
/// Handler for the domain event raised when a media library is created or updated.
/// </summary>
public class LibrarySavedDomainEventHandler : INotificationHandler<LibrarySavedDomainEvent>
public class LibrarySavedDomainEventHandler : IDomainEventHandler<LibrarySavedDomainEvent>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IEnvironmentContext _environmentContext;
@@ -56,7 +56,7 @@ public class LibrarySavedDomainEventHandler : INotificationHandler<LibrarySavedD
/// </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 Handle(LibrarySavedDomainEvent domainEvent, CancellationToken cancellationToken)
public async ValueTask HandleAsync(LibrarySavedDomainEvent domainEvent, CancellationToken cancellationToken)
{
if (domainEvent.Library.CoverImage is not null)
{
@@ -5,6 +5,7 @@ using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Domain.SharedKernel.Common.Errors;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
@@ -13,7 +14,6 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Mediator;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -21,9 +21,9 @@ using System.Threading.Tasks;
namespace Lumina.Application.Core.MediaLibrary.Management.Events;
/// <summary>
/// Handler for the event raised when a media library scan is cancelled.
/// Handler for the domain event raised when a media library scan is cancelled.
/// </summary>
public class LibraryScanCancelledDomainEventHandler : INotificationHandler<LibraryScanCancelledDomainEvent>
public class LibraryScanCancelledDomainEventHandler : IDomainEventHandler<LibraryScanCancelledDomainEvent>
{
private readonly IMediaLibraryScanningService _mediaLibraryScanningService;
private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker;
@@ -56,7 +56,7 @@ public class LibraryScanCancelledDomainEventHandler : INotificationHandler<Libra
/// </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 Handle(LibraryScanCancelledDomainEvent domainEvent, CancellationToken cancellationToken)
public async ValueTask HandleAsync(LibraryScanCancelledDomainEvent domainEvent, CancellationToken cancellationToken)
{
// get the library scan from the repository
ErrorOr<LibraryScanEntity?> getLibraryScansResult = await _libraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false);
@@ -6,12 +6,12 @@ using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Core.MediaLibrary.Management.Progress;
using Lumina.Domain.SharedKernel.Common.Errors;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Mediator;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -19,9 +19,9 @@ using System.Threading.Tasks;
namespace Lumina.Application.Core.MediaLibrary.Management.Events;
/// <summary>
/// Handler for the event raised when a media library scan has failed.
/// Handler for the domain event raised when a media library scan has failed.
/// </summary>
public class LibraryScanFailedDomainEventHandler : INotificationHandler<LibraryScanFailedDomainEvent>
public class LibraryScanFailedDomainEventHandler : IDomainEventHandler<LibraryScanFailedDomainEvent>
{
private readonly IMediaLibraryScanProgressNotifier _debouncedLibraryScanProgressNotifier;
private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker;
@@ -52,7 +52,7 @@ public class LibraryScanFailedDomainEventHandler : INotificationHandler<LibraryS
/// </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 Handle(LibraryScanFailedDomainEvent domainEvent, CancellationToken cancellationToken)
public async ValueTask HandleAsync(LibraryScanFailedDomainEvent domainEvent, CancellationToken cancellationToken)
{
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
ILibraryScanStagingResultsRepository stagingResultsRepository = _unitOfWork.GetRepository<ILibraryScanStagingResultsRepository>();
@@ -6,12 +6,12 @@ using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Core.MediaLibrary.Management.Progress;
using Lumina.Domain.SharedKernel.Common.Errors;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Mediator;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -19,9 +19,9 @@ using System.Threading.Tasks;
namespace Lumina.Application.Core.MediaLibrary.Management.Events;
/// <summary>
/// Handler for the event raised when a media library scan is finished.
/// Handler for the domain event raised when a media library scan is finished.
/// </summary>
public class LibraryScanFinishedDomainEventHandler : INotificationHandler<LibraryScanFinishedDomainEvent>
public class LibraryScanFinishedDomainEventHandler : IDomainEventHandler<LibraryScanFinishedDomainEvent>
{
private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker;
private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker;
@@ -52,7 +52,7 @@ public class LibraryScanFinishedDomainEventHandler : INotificationHandler<Librar
/// </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 Handle(LibraryScanFinishedDomainEvent domainEvent, CancellationToken cancellationToken)
public async ValueTask HandleAsync(LibraryScanFinishedDomainEvent domainEvent, CancellationToken cancellationToken)
{
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
@@ -1,8 +1,8 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.Management.Progress;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Mediator;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -10,9 +10,9 @@ using System.Threading.Tasks;
namespace Lumina.Application.Core.MediaLibrary.Management.Events;
/// <summary>
/// Handler for the event raised when a media library's scan progress changes.
/// Handler for the domain event raised when a media library's scan progress changes.
/// </summary>
public class LibraryScanJobProgressChangedDomainEventHandler : INotificationHandler<LibraryScanJobProgressChangedDomainEvent>
public class LibraryScanJobProgressChangedDomainEventHandler : IDomainEventHandler<LibraryScanJobProgressChangedDomainEvent>
{
private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker;
private readonly IMediaLibraryScanProgressNotifier _debouncedLibraryScanProgressNotifier;
@@ -35,7 +35,7 @@ public class LibraryScanJobProgressChangedDomainEventHandler : INotificationHand
/// </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 Handle(LibraryScanJobProgressChangedDomainEvent domainEvent, CancellationToken cancellationToken)
public async ValueTask HandleAsync(LibraryScanJobProgressChangedDomainEvent domainEvent, CancellationToken cancellationToken)
{
_mediaLibrariesScanProgressTracker.UpdateScanJobProgress(domainEvent.LibraryId, domainEvent.MediaLibraryScanCompositeId, domainEvent.Progress);
// notify SignalR clients that the library scan progress changed
@@ -1,8 +1,8 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.Management.Progress;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Mediator;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -10,9 +10,9 @@ using System.Threading.Tasks;
namespace Lumina.Application.Core.MediaLibrary.Management.Events;
/// <summary>
/// Handler for the event raised when a media library's scan progress changes.
/// Handler for the domain event raised when a media library's scan progress changes.
/// </summary>
public class LibraryScanProgressChangedDomainEventHandler : INotificationHandler<LibraryScanProgressChangedDomainEvent>
public class LibraryScanProgressChangedDomainEventHandler : IDomainEventHandler<LibraryScanProgressChangedDomainEvent>
{
private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker;
private readonly IMediaLibraryScanProgressNotifier _debouncedLibraryScanProgressNotifier;
@@ -35,7 +35,7 @@ public class LibraryScanProgressChangedDomainEventHandler : INotificationHandler
/// </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 Handle(LibraryScanProgressChangedDomainEvent domainEvent, CancellationToken cancellationToken)
public async ValueTask HandleAsync(LibraryScanProgressChangedDomainEvent domainEvent, CancellationToken cancellationToken)
{
_mediaLibrariesScanProgressTracker.UpdateScanProgress(domainEvent.LibraryId, domainEvent.MediaLibraryScanCompositeId);
// notify SignalR clients that the library scan progress changed
@@ -12,7 +12,6 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Mediator;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -20,9 +19,9 @@ using System.Threading.Tasks;
namespace Lumina.Application.Core.MediaLibrary.Management.Events;
/// <summary>
/// Handler for the event raised when a media library scan is queued.
/// Handler for the domain event raised when a media library scan is queued.
/// </summary>
public class LibraryScanQueuedDomainEventHandler : INotificationHandler<LibraryScanQueuedDomainEvent>
public class LibraryScanQueuedDomainEventHandler : IDomainEventHandler<LibraryScanQueuedDomainEvent>
{
private readonly IMediaLibraryScanningService _mediaLibraryScanningService;
private readonly IDomainEventsQueue _domainEventsQueue;
@@ -47,7 +46,7 @@ public class LibraryScanQueuedDomainEventHandler : INotificationHandler<LibraryS
/// </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 Handle(LibraryScanQueuedDomainEvent domainEvent, CancellationToken cancellationToken)
public async ValueTask HandleAsync(LibraryScanQueuedDomainEvent domainEvent, CancellationToken cancellationToken)
{
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
@@ -3,9 +3,9 @@ using ErrorOr;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Mediator;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -13,9 +13,9 @@ using System.Threading.Tasks;
namespace Lumina.Application.Core.MediaLibrary.Management.Events;
/// <summary>
/// Handler for the event raised when a media library scan is started.
/// Handler for the domain event raised when a media library scan is started.
/// </summary>
public class LibraryScanStartedDomainEventHandler : INotificationHandler<LibraryScanStartedDomainEvent>
public class LibraryScanStartedDomainEventHandler : IDomainEventHandler<LibraryScanStartedDomainEvent>
{
private readonly IUnitOfWork _unitOfWork;
@@ -33,7 +33,7 @@ public class LibraryScanStartedDomainEventHandler : INotificationHandler<Library
/// </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 Handle(LibraryScanStartedDomainEvent domainEvent, CancellationToken cancellationToken)
public async ValueTask HandleAsync(LibraryScanStartedDomainEvent domainEvent, CancellationToken cancellationToken)
{
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
@@ -20,11 +20,6 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Mediator.Abstractions" Version="3.0.0-preview.27" />
<PackageReference Include="Mediator.SourceGenerator" Version="3.0.0-preview.27">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="10.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.0" />
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using Mediator;
using System;
#endregion
@@ -8,7 +7,7 @@ namespace Lumina.Domain.Common.Events;
/// <summary>
/// Interface defining a domain event.
/// </summary>
public interface IDomainEvent : INotification
public interface IDomainEvent
{
/// <summary>
/// Gets the Id of the domain event.
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Domain.Common.Events;
/// <summary>
/// Defines a contract for handling a domain event type in the application layer.
/// </summary>
/// <typeparam name="TDomainEvent">The type of domain event to handle.</typeparam>
public interface IDomainEventHandler<TDomainEvent> where TDomainEvent : IDomainEvent
{
/// <summary>
/// Handles the specified <paramref name="domainEvent"/>.
/// </summary>
/// <param name="domainEvent">The domain event to handle.</param>
/// <param name="cancellationToken">Token to monitor for cancellation requests.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
ValueTask HandleAsync(TDomainEvent domainEvent, CancellationToken cancellationToken);
}
@@ -0,0 +1,20 @@
#region ========================================================================= USING =====================================================================================
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Domain.Common.Events;
/// <summary>
/// Publishes domain events to all handlers registered for the event type.
/// </summary>
public interface IDomainEventPublisher
{
/// <summary>
/// Publishes the specified <paramref name="domainEvent"/> to all its registered handlers, in registration order.
/// </summary>
/// <param name="domainEvent">The domain event to publish.</param>
/// <param name="cancellationToken">Token to monitor for cancellation requests.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
ValueTask PublishAsync(IDomainEvent domainEvent, CancellationToken cancellationToken = default);
}
@@ -9,7 +9,6 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Mediator;
using System;
using System.Collections.Generic;
using System.Threading;
@@ -27,7 +26,7 @@ internal class MediaLibraryScanningService : IMediaLibraryScanningService
private readonly IMediaLibraryScannerFactory _mediaLibraryScannerFactory;
private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker;
private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker;
private readonly IPublisher _publisher;
private readonly IDomainEventPublisher _domainEventPublisher;
/// <summary>
/// Initializes a new instance of the <see cref="MediaLibraryScanningService"/> class.
@@ -36,19 +35,19 @@ internal class MediaLibraryScanningService : IMediaLibraryScanningService
/// <param name="mediaLibraryScannerFactory">Injected factory for creating media library scanners.</param>
/// <param name="mediaLibrariesScanCancellationTracker">Injected tracker used for canceling media library scans.</param>
/// <param name="mediaLibrariesScanProgressTracker">Injected tracker used for media library scans progress.</param>
/// <param name="publisher">The domain event publisher used to publish events.</param>
/// <param name="domainEventPublisher">The domain event publisher used to publish events.</param>
public MediaLibraryScanningService(
IMediaLibrariesScanQueue mediaLibrariesScanQueue,
IMediaLibraryScannerFactory mediaLibraryScannerFactory,
IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker,
IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker,
IPublisher publisher)
IDomainEventPublisher domainEventPublisher)
{
_mediaLibrariesScanQueue = mediaLibrariesScanQueue;
_mediaLibraryScannerFactory = mediaLibraryScannerFactory;
_mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker;
_mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker;
_publisher = publisher;
_domainEventPublisher = domainEventPublisher;
}
/// <summary>
@@ -67,7 +66,7 @@ internal class MediaLibraryScanningService : IMediaLibraryScanningService
return startScanResult.Errors;
foreach (IDomainEvent domainEvent in scan.GetDomainEvents())
await _publisher!.Publish(domainEvent, cancellationToken).ConfigureAwait(false);
await _domainEventPublisher.PublishAsync(domainEvent, cancellationToken).ConfigureAwait(false);
// register the scan in the tracker for cancellation tokens
_mediaLibrariesScanCancellationTracker.RegisterScan(MediaLibraryScanCompositeId.Create(scan.Id, scan.UserId));
-1
View File
@@ -18,7 +18,6 @@
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.0" />
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.5" />
<PackageReference Include="System.IO.Abstractions" Version="21.1.3" />
<PackageReference Include="Mediator.Abstractions" Version="3.0.0-preview.27" />
</ItemGroup>
<ItemGroup>
@@ -9,6 +9,7 @@ using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.Management.Progress;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue;
@@ -75,6 +76,7 @@ public static class InfrastructureLayerServices
services.AddSingleton<IDateTimeProvider, DateTimeProvider>();
services.AddScoped<IDomainEventsQueue, DomainEventsQueue>();
services.AddScoped<IDomainEventPublisher, DomainEventPublisher>();
// authorization
services.AddScoped<IOver18Policy, Over18Policy>();
@@ -0,0 +1,65 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Concurrent;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Common.DomainEvents;
/// <summary>
/// Publishes domain events to all handlers registered for the event type, by resolving them from the dependency injection container.
/// </summary>
public class DomainEventPublisher : IDomainEventPublisher
{
private static readonly ConcurrentDictionary<Type, Func<IDomainEvent, IServiceProvider, CancellationToken, Task>> s_dispatchers = new();
private readonly IServiceProvider _serviceProvider;
/// <summary>
/// Initializes a new instance of the <see cref="DomainEventPublisher"/> class.
/// </summary>
/// <param name="serviceProvider">Injected provider used to resolve the domain event handlers.</param>
public DomainEventPublisher(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
/// <summary>
/// Publishes the specified <paramref name="domainEvent"/> to all its registered handlers, in registration order.
/// </summary>
/// <param name="domainEvent">The domain event to publish.</param>
/// <param name="cancellationToken">Token to monitor for cancellation requests.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public ValueTask PublishAsync(IDomainEvent domainEvent, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(domainEvent);
Func<IDomainEvent, IServiceProvider, CancellationToken, Task> dispatcher = s_dispatchers.GetOrAdd(domainEvent.GetType(), static eventType =>
{
MethodInfo dispatchMethod = typeof(DomainEventPublisher).GetMethod(nameof(DispatchAsync), BindingFlags.NonPublic | BindingFlags.Static)!
.MakeGenericMethod(eventType);
return dispatchMethod.CreateDelegate<Func<IDomainEvent, IServiceProvider, CancellationToken, Task>>();
});
return new ValueTask(dispatcher(domainEvent, _serviceProvider, cancellationToken));
}
/// <summary>
/// Dispatches the specified <paramref name="domainEvent"/> to all handlers registered for <typeparamref name="TDomainEvent"/>.
/// </summary>
/// <typeparam name="TDomainEvent">The type of the domain event being dispatched.</typeparam>
/// <param name="domainEvent">The domain event to dispatch.</param>
/// <param name="serviceProvider">The provider used to resolve the domain event handlers.</param>
/// <param name="cancellationToken">Token to monitor for cancellation requests.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
private static async Task DispatchAsync<TDomainEvent>(IDomainEvent domainEvent, IServiceProvider serviceProvider, CancellationToken cancellationToken)
where TDomainEvent : IDomainEvent
{
foreach (IDomainEventHandler<TDomainEvent> handler in serviceProvider.GetServices<IDomainEventHandler<TDomainEvent>>())
await handler.HandleAsync((TDomainEvent)domainEvent, cancellationToken).ConfigureAwait(false);
}
}
@@ -3,10 +3,10 @@ using ErrorOr;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Mediator;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading;
@@ -58,13 +58,13 @@ internal sealed class MediaLibraryScanDiffJob : MediaLibraryScanJob, IMediaLibra
// see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository<ILibraryScanStagingResultsRepository>();
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// set the initial progress of the scan job, it's a 1 step job - comparing the discovered files against the media library scan snapshot
ErrorOr<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false);
ErrorOr<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
@@ -74,12 +74,12 @@ internal sealed class MediaLibraryScanDiffJob : MediaLibraryScanJob, IMediaLibra
throw new InvalidOperationException(markChangesResult.FirstError.Description);
// increment the number of processed elements progress
publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false);
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
// this job finished, increment the number of processed jobs progress
await publisher.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Status = LibraryScanJobStatus.Completed;
// call each linked child with the obtained payload
@@ -103,19 +103,19 @@ internal sealed class MediaLibraryScanDiffJob : MediaLibraryScanJob, IMediaLibra
/// <summary>
/// Publishes a job progress update.
/// </summary>
/// <param name="publisher">The service used to publish the progress update.</param>
/// <param name="domainEventPublisher">The service used to publish the progress update.</param>
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
/// <param name="currentProgress">The current job progress.</param>
/// <param name="totalProgress">The total job progress.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
private async Task<ErrorOr<Success>> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
{
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "ComparingFileHashes");
if (scanJobProgressResult.IsError)
return scanJobProgressResult.Errors;
await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(
await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return Result.Success;
@@ -4,10 +4,10 @@ using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Mediator;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
@@ -62,7 +62,7 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra
// see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository<ILibraryScanStagingResultsRepository>();
IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService<IFileHashService>()!;
@@ -75,7 +75,7 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra
int totalFilesToHash = getFilesToHashCountResult.Value;
// set the initial progress of the scan job
ErrorOr<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, totalFilesToHash, cancellationToken).ConfigureAwait(false);
ErrorOr<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalFilesToHash, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
@@ -104,7 +104,7 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra
if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
{
// increment the number of processed elements progress
publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, Interlocked.Increment(ref processedFilesCount), totalFilesToHash, cancellationToken).ConfigureAwait(false);
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedFilesCount), totalFilesToHash, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
lastUpdateTime = now;
@@ -120,7 +120,7 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra
}
// this job finished, increment the number of processed jobs progress
await publisher.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Status = LibraryScanJobStatus.Completed;
// call each linked child with the obtained payload
@@ -144,19 +144,19 @@ internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibra
/// <summary>
/// Publishes a job progress update.
/// </summary>
/// <param name="publisher">The service used to publish the progress update.</param>
/// <param name="domainEventPublisher">The service used to publish the progress update.</param>
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
/// <param name="currentProgress">The current job progress.</param>
/// <param name="totalProgress">The total job progress.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
private async Task<ErrorOr<Success>> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
{
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "HashingFileContents");
if (scanJobProgressResult.IsError)
return scanJobProgressResult.Errors;
await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(
await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return Result.Success;
@@ -8,13 +8,13 @@ using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Contracts.Core.Metadata;
using Mediator;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
@@ -74,7 +74,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
// see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
ILibraryMetadataProviderConfigurationRepository configurationRepository = unitOfWork.GetRepository<ILibraryMetadataProviderConfigurationRepository>();
IBookRepository bookRepository = unitOfWork.GetRepository<IBookRepository>();
@@ -102,7 +102,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
int totalBooksToEnrich = getBooksToEnrichCountResult.Value;
// set the initial progress of the scan job
ErrorOr<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
ErrorOr<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
@@ -134,7 +134,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
{
// increment the number of processed elements progress
publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, Interlocked.Increment(ref processedBooksCount), totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedBooksCount), totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
lastUpdateTime = now;
@@ -148,7 +148,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
// this job finished, and it's the last in the chain, the scan is completed
Status = LibraryScanJobStatus.Completed;
await publisher.Publish(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
// call each linked child with the obtained payload
foreach (IMediaLibraryScanJob child in Children)
@@ -242,19 +242,19 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
/// <summary>
/// Publishes a job progress update.
/// </summary>
/// <param name="publisher">The service used to publish the progress update.</param>
/// <param name="domainEventPublisher">The service used to publish the progress update.</param>
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
/// <param name="currentProgress">The current job progress.</param>
/// <param name="totalProgress">The total job progress.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
private async Task<ErrorOr<Success>> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
{
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "EnrichingMetadata");
if (scanJobProgressResult.IsError)
return scanJobProgressResult.Errors;
await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(
await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return Result.Success;
@@ -6,10 +6,10 @@ using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Mediator;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
@@ -65,13 +65,13 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
// see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
ILibraryScanSnapshotRepository libraryScanSnapshotRepository = unitOfWork.GetRepository<ILibraryScanSnapshotRepository>();
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// set the initial progress of the scan job, it's a 1 step job - applying the scan results to the storage medium
ErrorOr<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false);
ErrorOr<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
@@ -89,7 +89,7 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
foreach (string deletedPath in getDeletedPathsResult.Value)
{
cancellationToken.ThrowIfCancellationRequested();
await publisher.Publish(new LibraryMediaItemDeletedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, deletedPath, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await domainEventPublisher.PublishAsync(new LibraryMediaItemDeletedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, deletedPath, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
}
// materialize the books of the media library from the scan snapshot, so that they are browsable even without web metadata
@@ -114,14 +114,14 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// increment the number of processed elements progress
publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false);
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
Status = LibraryScanJobStatus.Completed;
// when this job has no linked children, it's the last job in the directed acyclic job graph, and the scan is completed
if (Children.Count == 0)
await publisher.Publish(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
// call each linked child with the obtained payload
foreach (IMediaLibraryScanJob child in Children)
@@ -144,19 +144,19 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
/// <summary>
/// Publishes a job progress update.
/// </summary>
/// <param name="publisher">The service used to publish the progress update.</param>
/// <param name="domainEventPublisher">The service used to publish the progress update.</param>
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
/// <param name="currentProgress">The current job progress.</param>
/// <param name="totalProgress">The total job progress.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
private async Task<ErrorOr<Success>> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
{
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "SavingScanData");
if (scanJobProgressResult.IsError)
return scanJobProgressResult.Errors;
await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return Result.Success;
}
@@ -1,8 +1,8 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Mediator;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading;
@@ -30,8 +30,8 @@ internal static class ScanFailurePublisher
try
{
await using AsyncServiceScope asyncServiceScope = serviceScopeFactory.CreateAsyncScope();
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), libraryId, compositeKey, DateTime.UtcNow, exception.Message), cancellationToken).ConfigureAwait(false);
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
await domainEventPublisher.PublishAsync(new LibraryScanFailedDomainEvent(Guid.NewGuid(), libraryId, compositeKey, DateTime.UtcNow, exception.Message), cancellationToken).ConfigureAwait(false);
}
catch
{
@@ -5,6 +5,7 @@ using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
@@ -12,7 +13,6 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
using Mediator;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
@@ -78,7 +78,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
// see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
ILibraryRepository libraryRepository = unitOfWork.GetRepository<ILibraryRepository>()!;
ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository<ILibraryScanStagingResultsRepository>();
IDirectoryScanFingerprintRepository directoryScanFingerprintRepository = unitOfWork.GetRepository<IDirectoryScanFingerprintRepository>();
@@ -106,7 +106,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
}
// set the initial progress of the scan job
ErrorOr<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
ErrorOr<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
@@ -137,8 +137,8 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
DateTime now = DateTime.UtcNow;
if (now - lastHeartbeat >= heartbeatInterval)
{
publishJobProgressResult = await PublishJobProgress(
publisher, compositeKey, processedContentLocations, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
publishJobProgressResult = await PublishJobProgressAsync(
domainEventPublisher, compositeKey, processedContentLocations, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsError)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
lastHeartbeat = now;
@@ -160,7 +160,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
}
// this job finished, increment the number of processed jobs progress
await publisher.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Status = LibraryScanJobStatus.Completed;
// call each linked child with the obtained payload
@@ -321,19 +321,19 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF
/// <summary>
/// Publishes a job progress update.
/// </summary>
/// <param name="publisher">The service used to publish the progress update.</param>
/// <param name="domainEventPublisher">The service used to publish the progress update.</param>
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
/// <param name="currentProgress">The current job progress.</param>
/// <param name="totalProgress">The total job progress.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
private async Task<ErrorOr<Success>> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
{
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "DiscoveringFiles");
if (scanJobProgressResult.IsError)
return scanJobProgressResult.Errors;
await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(
await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return Result.Success;
@@ -3,7 +3,6 @@ using Lumina.Application.Common.DomainEvents;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Exceptions;
using Mediator;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.Logging;
@@ -35,10 +34,10 @@ public class EventualConsistencyMiddleware
/// Handles incoming HTTP requests and ensures that domain events are published and the database transaction is committed upon successful request completion.
/// </summary>
/// <param name="context">The current HTTP context.</param>
/// <param name="publisher">The domain event publisher used to publish events.</param>
/// <param name="domainEventPublisher">The domain event publisher used to publish events.</param>
/// <param name="dbContext">The database context used to manage the transaction.</param>
/// <param name="domainEventQueue">In memory queue containing the queued domain events.</param>
public async Task InvokeAsync(HttpContext context, IPublisher publisher, LuminaDbContext dbContext, IDomainEventsQueue domainEventQueue)
public async Task InvokeAsync(HttpContext context, IDomainEventPublisher domainEventPublisher, LuminaDbContext dbContext, IDomainEventsQueue domainEventQueue)
{
// begin a new database transaction - this will wrap any database operations performed during this HTTP request in an atomic operation
IDbContextTransaction transaction = await dbContext.Database.BeginTransactionAsync(context.RequestAborted).ConfigureAwait(false);
@@ -59,7 +58,7 @@ public class EventualConsistencyMiddleware
// check if domain events exist in the channel queue and publish them
while (domainEventQueue.TryDequeue(out IDomainEvent? nextEvent))
await publisher.Publish(nextEvent);
await domainEventPublisher.PublishAsync(nextEvent);
}
}
catch (EventualConsistencyException ex)
@@ -24,7 +24,6 @@
<ItemGroup>
<PackageReference Include="FastEndpoints" Version="5.31.0.6-beta" />
<PackageReference Include="FastEndpoints.Swagger" Version="5.31.0.6-beta" />
<PackageReference Include="Mediator.Abstractions" Version="3.0.0-preview.27" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.0" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.21.0" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.0" />
@@ -357,7 +357,6 @@
</EmbeddedResource>
</ItemGroup>
<!--disable warnings generated by Mediator source generator-->
<PropertyGroup>
<NoWarn>$(NoWarn);TS6385</NoWarn>
</PropertyGroup>
@@ -6,6 +6,7 @@ using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
#endregion
namespace Lumina.Application.UnitTests.Common.CQRS;
@@ -17,6 +18,7 @@ namespace Lumina.Application.UnitTests.Common.CQRS;
public class HandlersCallTheirValidatorsTests
{
private static readonly Assembly s_applicationAssembly = typeof(ICommand).Assembly;
private static readonly Dictionary<short, OpCode> s_opCodes = BuildOpCodeLookup();
/// <summary>
/// Ensures every command or query that has a validator has a handler that calls that validator.
@@ -101,6 +103,12 @@ public class HandlersCallTheirValidatorsTests
yield return nestedDescendant;
}
/// <summary>
/// Checks whether the IL of the specified <paramref name="method"/> contains a call to <see cref="IValidator{TRequest}.Validate"/>.
/// </summary>
/// <param name="method">The method whose IL is inspected.</param>
/// <param name="validatorInterface">The closed validator interface whose <c>Validate</c> method is being looked for.</param>
/// <returns><see langword="true"/> if the method calls the validator, <see langword="false"/> otherwise.</returns>
private static bool CallsValidatorMethod(MethodInfo method, Type validatorInterface)
{
MethodBody? body = method.GetMethodBody();
@@ -112,38 +120,110 @@ public class HandlersCallTheirValidatorsTests
return false;
Module module = method.Module;
for (int i = 0; i < il.Length; i++)
int offset = 0;
while (offset < il.Length)
{
// 0x28 is the call opcode and 0x6F is the callvirt opcode, both followed by a 4-byte metadata token
if (il[i] != 0x28 && il[i] != 0x6F)
continue;
// read the opcode, handling the 0xFE prefix used by two-byte opcodes
short opCodeValue = il[offset];
int opCodeSize = 1;
if (opCodeValue == 0xFE && offset + 1 < il.Length)
{
opCodeValue = (short)((0xFE << 8) | il[offset + 1]);
opCodeSize = 2;
}
if (i + 4 >= il.Length)
if (!s_opCodes.TryGetValue(opCodeValue, out OpCode opCode))
return false;
offset += opCodeSize;
if (offset >= il.Length)
break;
int token = il[i + 1] | (il[i + 2] << 8) | (il[i + 3] << 16) | (il[i + 4] << 24);
try
if (opCode == OpCodes.Call || opCode == OpCodes.Callvirt)
{
if (module.ResolveMethod(token) is MethodInfo resolvedMethod &&
resolvedMethod.Name == nameof(IValidator<object>.Validate) &&
resolvedMethod.DeclaringType != null &&
resolvedMethod.DeclaringType.Equals(validatorInterface))
return true;
int token = ReadInt32(il, offset);
try
{
if (module.ResolveMethod(token) is MethodInfo resolvedMethod &&
resolvedMethod.Name == nameof(IValidator<object>.Validate) &&
resolvedMethod.DeclaringType != null &&
resolvedMethod.DeclaringType.Equals(validatorInterface))
return true;
}
catch (ArgumentException)
{
// the token is not a valid method token, skip it
}
catch (BadImageFormatException)
{
// the token references corrupt metadata, skip it
}
catch (InvalidOperationException)
{
// the token cannot be resolved as a method, skip it
}
}
catch (ArgumentException)
if (opCode.OperandType == OperandType.InlineSwitch)
{
// the token is not a valid method token, skip it
int switchCases = ReadInt32(il, offset);
offset += 4 + (switchCases * 4);
}
catch (BadImageFormatException)
{
// the token references corrupt metadata, skip it
}
catch (InvalidOperationException)
{
// the token cannot be resolved as a method, skip it
}
i += 4;
else
offset += GetOperandSize(opCode);
}
return false;
}
/// <summary>
/// Builds a lookup table of all opcodes, keyed by their numeric value.
/// </summary>
/// <returns>The built lookup table.</returns>
private static Dictionary<short, OpCode> BuildOpCodeLookup()
{
Dictionary<short, OpCode> opCodes = [];
foreach (FieldInfo field in typeof(OpCodes).GetFields(BindingFlags.Public | BindingFlags.Static))
if (field.GetValue(null) is OpCode opCode)
opCodes[opCode.Value] = opCode;
return opCodes;
}
/// <summary>
/// Gets the size in bytes of the operand of the specified <paramref name="opCode"/>.
/// </summary>
/// <param name="opCode">The opcode whose operand size is returned.</param>
/// <returns>The size of the operand in bytes.</returns>
private static int GetOperandSize(OpCode opCode)
{
return opCode.OperandType switch
{
OperandType.InlineNone => 0,
OperandType.ShortInlineI => 1,
OperandType.ShortInlineVar => 1,
OperandType.ShortInlineBrTarget => 1,
OperandType.InlineVar => 2,
OperandType.InlineBrTarget => 4,
OperandType.InlineField => 4,
OperandType.InlineMethod => 4,
OperandType.InlineType => 4,
OperandType.InlineString => 4,
OperandType.InlineSig => 4,
OperandType.ShortInlineR => 4,
OperandType.InlineI => 4,
OperandType.InlineR => 8,
OperandType.InlineI8 => 8,
_ => 0,
};
}
/// <summary>
/// Reads a 4-byte little-endian integer from the specified offset in the IL stream.
/// </summary>
/// <param name="il">The IL byte stream.</param>
/// <param name="offset">The offset at which to read the integer.</param>
/// <returns>The read integer.</returns>
private static int ReadInt32(byte[] il, int offset)
{
return il[offset] | (il[offset + 1] << 8) | (il[offset + 2] << 16) | (il[offset + 3] << 24);
}
}
@@ -0,0 +1,194 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Infrastructure.Common.DomainEvents;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.DomainEvents;
/// <summary>
/// Contains unit tests for the <see cref="DomainEventPublisher"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DomainEventPublisherTests
{
public sealed record TestDomainEvent(Guid Id, DateTime OccurredOnUtc) : IDomainEvent;
public sealed record NestedTestDomainEvent(Guid Id, DateTime OccurredOnUtc) : IDomainEvent;
private sealed class RecordingDomainEventHandler : IDomainEventHandler<TestDomainEvent>
{
private readonly List<string> _callLog;
private readonly string _handlerName;
public RecordingDomainEventHandler(List<string> callLog, string handlerName)
{
_callLog = callLog;
_handlerName = handlerName;
}
public ValueTask HandleAsync(TestDomainEvent domainEvent, CancellationToken cancellationToken)
{
_callLog.Add(_handlerName);
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Creates a publisher wired to a fresh service provider, optionally registering additional services.
/// </summary>
/// <param name="configureServices">Optional action used to register additional services into the provider.</param>
/// <returns>A domain event publisher resolved from the created provider.</returns>
private static IDomainEventPublisher CreatePublisher(Action<IServiceCollection>? configureServices = null)
{
IServiceCollection services = new ServiceCollection();
services.AddScoped<IDomainEventPublisher, DomainEventPublisher>();
configureServices?.Invoke(services);
ServiceProvider serviceProvider = services.BuildServiceProvider();
return serviceProvider.GetRequiredService<IDomainEventPublisher>();
}
/// <summary>
/// Creates a valid instance of <see cref="TestDomainEvent"/>.
/// </summary>
/// <returns>The created domain event.</returns>
private static TestDomainEvent CreateTestDomainEvent()
{
return new TestDomainEvent(Guid.NewGuid(), DateTime.UtcNow);
}
/// <summary>
/// Creates a valid instance of <see cref="NestedTestDomainEvent"/>.
/// </summary>
/// <returns>The created domain event.</returns>
private static NestedTestDomainEvent CreateNestedTestDomainEvent()
{
return new NestedTestDomainEvent(Guid.NewGuid(), DateTime.UtcNow);
}
[Fact]
public async Task Publish_WhenHandlersAreRegistered_ShouldInvokeAllHandlersInOrder()
{
// Arrange
TestDomainEvent domainEvent = CreateTestDomainEvent();
List<string> callLog = [];
IDomainEventPublisher publisher = CreatePublisher(services =>
{
services.AddScoped<IDomainEventHandler<TestDomainEvent>>(_ => new RecordingDomainEventHandler(callLog, "first"));
services.AddScoped<IDomainEventHandler<TestDomainEvent>>(_ => new RecordingDomainEventHandler(callLog, "second"));
});
// Act
await publisher.PublishAsync(domainEvent, CancellationToken.None);
// Assert
Assert.Equal(["first", "second"], callLog);
}
[Fact]
public async Task Publish_WhenNoHandlersAreRegisteredForTheEventType_ShouldNotThrow()
{
// Arrange
TestDomainEvent domainEvent = CreateTestDomainEvent();
IDomainEventPublisher publisher = CreatePublisher();
// Act
await publisher.PublishAsync(domainEvent, CancellationToken.None);
// Assert
// reaching this point without an exception means the publish was a no-op, as expected
}
[Fact]
public async Task Publish_WhenOnlyAnotherEventTypeHasHandlers_ShouldNotInvokeThem()
{
// Arrange
TestDomainEvent domainEvent = CreateTestDomainEvent();
IDomainEventHandler<NestedTestDomainEvent> nestedHandler = Substitute.For<IDomainEventHandler<NestedTestDomainEvent>>();
IDomainEventPublisher publisher = CreatePublisher(services => services.AddScoped(_ => nestedHandler));
// Act
await publisher.PublishAsync(domainEvent, CancellationToken.None);
// Assert
await nestedHandler.DidNotReceive().HandleAsync(Arg.Any<NestedTestDomainEvent>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Publish_WhenHandlerThrows_ShouldPropagateTheException()
{
// Arrange
TestDomainEvent domainEvent = CreateTestDomainEvent();
InvalidOperationException expectedException = new("Test exception");
IDomainEventHandler<TestDomainEvent> handler = Substitute.For<IDomainEventHandler<TestDomainEvent>>();
handler.HandleAsync(Arg.Any<TestDomainEvent>(), Arg.Any<CancellationToken>())
.Returns(callInfo => throw expectedException);
IDomainEventPublisher publisher = CreatePublisher(services => services.AddScoped<IDomainEventHandler<TestDomainEvent>>(_ => handler));
// Act
InvalidOperationException result = await Assert.ThrowsAsync<InvalidOperationException>(
() => publisher.PublishAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Same(expectedException, result);
}
[Fact]
public async Task Publish_WhenHandlerPublishesAnotherEvent_ShouldInvokeNestedHandlers()
{
// Arrange
TestDomainEvent domainEvent = CreateTestDomainEvent();
NestedTestDomainEvent nestedDomainEvent = CreateNestedTestDomainEvent();
IDomainEventHandler<TestDomainEvent> handler = Substitute.For<IDomainEventHandler<TestDomainEvent>>();
IDomainEventHandler<NestedTestDomainEvent> nestedHandler = Substitute.For<IDomainEventHandler<NestedTestDomainEvent>>();
IDomainEventPublisher publisher = CreatePublisher(services =>
{
services.AddScoped(_ => handler);
services.AddScoped(_ => nestedHandler);
});
handler.HandleAsync(domainEvent, Arg.Any<CancellationToken>())
.Returns(callInfo => publisher.PublishAsync(nestedDomainEvent, callInfo.Arg<CancellationToken>()));
// Act
await publisher.PublishAsync(domainEvent, CancellationToken.None);
// Assert
await nestedHandler.Received(1).HandleAsync(nestedDomainEvent, Arg.Any<CancellationToken>());
}
[Fact]
public async Task Publish_WhenCancellationRequested_ShouldPassTokenToHandlers()
{
// Arrange
TestDomainEvent domainEvent = CreateTestDomainEvent();
using CancellationTokenSource cancellationTokenSource = new();
CancellationToken cancellationToken = cancellationTokenSource.Token;
IDomainEventHandler<TestDomainEvent> handler = Substitute.For<IDomainEventHandler<TestDomainEvent>>();
IDomainEventPublisher publisher = CreatePublisher(services => services.AddScoped(_ => handler));
// Act
await publisher.PublishAsync(domainEvent, cancellationToken);
// Assert
await handler.Received(1).HandleAsync(domainEvent, Arg.Is(cancellationToken));
}
[Fact]
public async Task Publish_WhenDomainEventIsNull_ShouldThrowArgumentNullException()
{
// Arrange
IDomainEventPublisher publisher = CreatePublisher();
// Act
ArgumentNullException result = await Assert.ThrowsAsync<ArgumentNullException>(() => publisher.PublishAsync(null!, CancellationToken.None).AsTask());
// Assert
Assert.Equal("domainEvent", result.ParamName);
}
}
@@ -60,7 +60,7 @@ public class GetPermissionsEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
@@ -55,7 +55,7 @@ public class AddRoleEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
AddRoleRequest request = new("Admin", [Guid.NewGuid()]);
@@ -50,7 +50,7 @@ public class DeleteRoleEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
DeleteRoleRequest request = new(Guid.NewGuid());
@@ -58,7 +58,7 @@ public class GetRolePermissionsEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
GetRolePermissionsRequest request = new(Guid.NewGuid());
@@ -56,7 +56,7 @@ public class GetRolesEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
@@ -60,7 +60,7 @@ public class UpdateRoleEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
UpdateRoleRequest request = new(Guid.NewGuid(), "UpdatedAdmin", [Guid.NewGuid()]);
@@ -60,7 +60,7 @@ public class GetDirectoriesEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
GetDirectoriesRequest request = _fixture.Create<GetDirectoriesRequest>();
@@ -86,7 +86,7 @@ public class GetDirectoriesEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult()
{
// Arrange
GetDirectoriesRequest request = _fixture.Create<GetDirectoriesRequest>();
@@ -112,7 +112,7 @@ public class GetDirectoriesEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendGetDirectoriesQueryToMediator()
public async Task ExecuteAsync_WhenCalled_ShouldSendGetDirectoriesQueryToHandler()
{
// Arrange
GetDirectoriesRequest request = _fixture.Create<GetDirectoriesRequest>();
@@ -57,7 +57,7 @@ public class GetDrivesEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
@@ -82,7 +82,7 @@ public class GetDrivesEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendGetDrivesQueryToMediator()
public async Task ExecuteAsync_WhenCalled_ShouldSendGetDrivesQueryToHandler()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
@@ -71,7 +71,7 @@ public class GetFileSystemTypeEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendGetFileSystemQueryToMediator()
public async Task ExecuteAsync_WhenCalled_ShouldSendGetFileSystemQueryToHandler()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
@@ -62,7 +62,7 @@ public class GetFilesEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
GetFilesRequest request = _fixture.Create<GetFilesRequest>();
@@ -88,7 +88,7 @@ public class GetFilesEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult()
{
// Arrange
GetFilesRequest request = _fixture.Create<GetFilesRequest>();
@@ -63,7 +63,7 @@ public class GetTreeFilesEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
GetTreeFilesRequest request = _fixture.Create<GetTreeFilesRequest>();
@@ -89,7 +89,7 @@ public class GetTreeFilesEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult()
{
// Arrange
GetTreeFilesRequest request = _fixture.Create<GetTreeFilesRequest>();
@@ -57,7 +57,7 @@ public class CheckPathExistsEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendCheckPathExistsQueryToMediator()
public async Task ExecuteAsync_WhenCalled_ShouldSendCheckPathExistsQueryToHandler()
{
// Arrange
CheckPathExistsRequest request = _checkPathExistsRequestFixture.Create(path: @"C:\Users\TestUser\Documents", includeHiddenElements: true);
@@ -58,7 +58,7 @@ public class CombinePathEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
CombinePathRequest request = _combinePathRequestFixture.Create("InvalidPath", "TestUser");
@@ -84,7 +84,7 @@ public class CombinePathEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult()
{
// Arrange
CombinePathRequest request = _combinePathRequestFixture.Create("InvalidPath", "TestUser");
@@ -110,7 +110,7 @@ public class CombinePathEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendCombinePathCommandToMediator()
public async Task ExecuteAsync_WhenCalled_ShouldSendCombinePathCommandToHandler()
{
// Arrange
CombinePathRequest request = _combinePathRequestFixture.Create("C:\\Users", "TestUser");
@@ -61,7 +61,7 @@ public class GetPathParentEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
GetPathParentRequest request = _getPathParentRequestFixture.Create(@"C:\Users\TestUser");
@@ -87,7 +87,7 @@ public class GetPathParentEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult()
{
// Arrange
GetPathParentRequest request = _getPathParentRequestFixture.Create(@"InvalidPath");
@@ -113,7 +113,7 @@ public class GetPathParentEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendGetPathParentQueryToMediator()
public async Task ExecuteAsync_WhenCalled_ShouldSendGetPathParentQueryToHandler()
{
// Arrange
GetPathParentRequest request = _getPathParentRequestFixture.Create(@"C:\Users\TestUser");
@@ -59,7 +59,7 @@ public class GetPathRootEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
GetPathRootRequest request = _getPathRootRequestFixture.Create(@"C:\Users\TestUser");
@@ -85,7 +85,7 @@ public class GetPathRootEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult()
{
// Arrange
GetPathRootRequest request = _getPathRootRequestFixture.Create(@"InvalidPath");
@@ -111,7 +111,7 @@ public class GetPathRootEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendGetPathRootQueryToMediator()
public async Task ExecuteAsync_WhenCalled_ShouldSendGetPathRootQueryToHandler()
{
// Arrange
GetPathRootRequest request = _getPathRootRequestFixture.Create(@"C:\Users\TestUser");
@@ -54,7 +54,7 @@ public class GetPathSeparatorEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendGetPathSeparatorQueryToMediator()
public async Task ExecuteAsync_WhenCalled_ShouldSendGetPathSeparatorQueryToHandler()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
@@ -60,7 +60,7 @@ public class SplitPathEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
SplitPathRequest request = _splitPathRequestFixture.Create(@"InvalidPath");
@@ -87,7 +87,7 @@ public class SplitPathEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendSplitPathCommandToMediator()
public async Task ExecuteAsync_WhenCalled_ShouldSendSplitPathCommandToHandler()
{
// Arrange
SplitPathRequest request = _splitPathRequestFixture.Create(@"C:\Users\TestUser\Documents");
@@ -58,7 +58,7 @@ public class ValidatePathEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendValidatePathQueryToMediator()
public async Task ExecuteAsync_WhenCalled_ShouldSendValidatePathQueryToHandler()
{
// Arrange
ValidatePathRequest request = _validatePathRequestFixture.Create(@"C:\Users\TestUser\Documents");
@@ -76,7 +76,7 @@ public class ValidatePathEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult()
{
// Arrange
ValidatePathRequest request = _validatePathRequestFixture.Create(@"C:\Users\TestUser\Documents");
@@ -59,7 +59,7 @@ public class GetThumbnailEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
GetThumbnailRequest request = _getThumbnailRequestFixture.Create("/path/to/nonexistent/file.jpg", 80);
@@ -85,7 +85,7 @@ public class GetThumbnailEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsValidationError_ShouldReturnValidationProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult()
{
// Arrange
GetThumbnailRequest request = _getThumbnailRequestFixture.Create("/path/to/nonexistent/file.jpg", 80);
@@ -51,7 +51,7 @@ public class CheckInitializationEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendCheckInitializationQueryToMediator()
public async Task ExecuteAsync_WhenCalled_ShouldSendCheckInitializationQueryToHandler()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
@@ -59,7 +59,7 @@ public class SetupApplicationEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
RegistrationRequest request = _registrationRequestFixture.Create();
@@ -56,7 +56,7 @@ public class ChangePasswordEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
ChangePasswordRequest request = _changePasswordRequestFixture.Create();
@@ -55,7 +55,7 @@ public class GetUsersEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
@@ -57,7 +57,7 @@ public class LoginEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
LoginRequest request = _loginRequestFixture.Create();
@@ -56,7 +56,7 @@ public class RecoverPasswordEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create();
@@ -57,7 +57,7 @@ public class RegisterEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
RegistrationRequest request = _registrationRequestFixture.Create();
@@ -62,7 +62,7 @@ public class GetAuthorizationEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
GetAuthorizationRequest request = GetAuthorizationRequestFixture.Create();
@@ -60,7 +60,7 @@ public class GetUserPermissionsEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
GetUserPermissionsRequest request = new(Guid.NewGuid());
@@ -54,7 +54,7 @@ public class GetUserRoleEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
GetUserRoleRequest request = new(Guid.NewGuid());
@@ -64,7 +64,7 @@ public class UpdateUserRoleAndPermissionsEndpointTests
}
[Fact]
public async Task ExecuteAsync_WhenMediatorReturnsError_ShouldReturnProblemResult()
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
UpdateUserRoleAndPermissionsRequest request = new(