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

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